From 7d98f0821539f81d371d9be38a0bd1e4650d8cd0 Mon Sep 17 00:00:00 2001 From: antelder Date: Sat, 21 Mar 2009 09:19:18 +0000 Subject: [maven-release-plugin] copy for branch 2.0-M2 git-svn-id: http://svn.us.apache.org/repos/asf/tuscany@756900 13f79535-47bb-0310-9956-ffa450edef68 --- .../sca/policy/xml/BindingTypeProcessor.java | 67 +++ .../sca/policy/xml/ExtensionTypeProcessor.java | 251 +++++++++++ .../policy/xml/ImplementationTypeProcessor.java | 67 +++ .../tuscany/sca/policy/xml/IntentProcessor.java | 387 ++++++++++++++++ .../tuscany/sca/policy/xml/PolicyConstants.java | 74 ++++ .../tuscany/sca/policy/xml/PolicySetProcessor.java | 490 +++++++++++++++++++++ .../sca/policy/xml/PolicyXPathFunction.java | 127 ++++++ .../policy/xml/PolicyXPathFunctionResolver.java | 72 +++ ...ca.contribution.processor.StAXArtifactProcessor | 22 + ...tuscany.sca.contribution.resolver.ModelResolver | 18 + .../policy-xml-validation-messages.properties | 45 ++ .../xml/PolicyXPathFunctionResolverTestCase.java | 132 ++++++ .../sca/policy/xml/ReadDocumentTestCase.java | 295 +++++++++++++ .../sca/policy/xml/TestPolicyProcessor.java | 82 ++++ .../tuscany/sca/policy/xml/Calculator.composite | 49 +++ .../tuscany/sca/policy/xml/test_definitions.xml | 203 +++++++++ 16 files changed, 2381 insertions(+) create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/BindingTypeProcessor.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/ExtensionTypeProcessor.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/ImplementationTypeProcessor.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/IntentProcessor.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyConstants.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicySetProcessor.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunction.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunctionResolver.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/policy-xml-validation-messages.properties create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunctionResolverTestCase.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/ReadDocumentTestCase.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/TestPolicyProcessor.java create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/resources/org/apache/tuscany/sca/policy/xml/Calculator.composite create mode 100644 sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/resources/org/apache/tuscany/sca/policy/xml/test_definitions.xml (limited to 'sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src') diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/BindingTypeProcessor.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/BindingTypeProcessor.java new file mode 100644 index 0000000000..38c7b57f12 --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/BindingTypeProcessor.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.policy.xml; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.policy.BindingType; +import org.apache.tuscany.sca.policy.ExtensionType; +import org.apache.tuscany.sca.policy.PolicyFactory; + +/** + * Processor for handling XML models of BindingType meta data definitions + * + * @version $Rev$ $Date$ + */ +public class BindingTypeProcessor extends ExtensionTypeProcessor { + + public BindingTypeProcessor(PolicyFactory policyFactory, + StAXArtifactProcessor extensionProcessor, + Monitor monitor) { + super(policyFactory, extensionProcessor, monitor); + } + + public BindingTypeProcessor(FactoryExtensionPoint modelFactories, + StAXArtifactProcessor extensionProcessor, + Monitor monitor) { + super(modelFactories.getFactory(PolicyFactory.class), extensionProcessor, monitor); + } + + public QName getArtifactType() { + return BINDING_TYPE_QNAME; + } + + @Override + protected ExtensionType resolveExtensionType(ExtensionType extnType, ModelResolver resolver) + throws ContributionResolveException { + if (extnType instanceof BindingType) { + BindingType bindingType = (BindingType)extnType; + return resolver.resolveModel(BindingType.class, bindingType); + } else { + return extnType; + } + + } +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/ExtensionTypeProcessor.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/ExtensionTypeProcessor.java new file mode 100644 index 0000000000..f437b5d599 --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/ExtensionTypeProcessor.java @@ -0,0 +1,251 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.policy.xml; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; +import org.apache.tuscany.sca.policy.BindingType; +import org.apache.tuscany.sca.policy.ExtensionType; +import org.apache.tuscany.sca.policy.ImplementationType; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.PolicyFactory; + +/** + * Processor for handling XML models of ExtensionType meta data definitions + * + * @version $Rev$ $Date$ + */ +abstract class ExtensionTypeProcessor extends BaseStAXArtifactProcessor implements + StAXArtifactProcessor, PolicyConstants { + + private PolicyFactory policyFactory; + private Monitor monitor; + + protected abstract ExtensionType resolveExtensionType(ExtensionType extnType, ModelResolver resolver) + throws ContributionResolveException; + + public ExtensionTypeProcessor(PolicyFactory policyFactory, + StAXArtifactProcessor extensionProcessor, + Monitor monitor) { + this.policyFactory = policyFactory; + this.monitor = monitor; + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = + monitor.createProblem(this.getClass().getName(), + "policy-xml-validation-messages", + Severity.ERROR, + model, + message, + (Object[])messageParameters); + monitor.problem(problem); + } + } + + public ExtensionType read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + QName extType = getArtifactType(); + QName type = getQName(reader, "type"); + + if (type != null) { + ExtensionType extensionType = null; + if (BINDING_TYPE_QNAME.equals(extType)) { + extensionType = policyFactory.createBindingType(); + } else if (IMPLEMENTATION_TYPE_QNAME.equals(extType)) { + extensionType = policyFactory.createImplementationType(); + } else { + error("UnrecognizedExtensionType", reader, type); + return null; + //throw new ContributionReadException("Unrecognized ExtensionType - " + type); + } + extensionType.setType(type); + extensionType.setUnresolved(true); + + readAlwaysProvidedIntents(extensionType, reader); + readMayProvideIntents(extensionType, reader); + return extensionType; + + } else { + error("RequiredAttributeMissing", reader, extType); + //throw new ContributionReadException("Required attribute '" + TYPE + + //"' missing from BindingType Definition"); + } + return null; + } + + private void readAlwaysProvidedIntents(ExtensionType extnType, XMLStreamReader reader) { + String value = reader.getAttributeValue(null, ALWAYS_PROVIDES); + if (value != null) { + List alwaysProvided = extnType.getAlwaysProvidedIntents(); + for (StringTokenizer tokens = new StringTokenizer(value); tokens.hasMoreTokens();) { + QName qname = getQNameValue(reader, tokens.nextToken()); + Intent intent = policyFactory.createIntent(); + intent.setName(qname); + alwaysProvided.add(intent); + } + } + } + + private void readMayProvideIntents(ExtensionType extnType, XMLStreamReader reader) { + String value = reader.getAttributeValue(null, MAY_PROVIDE); + if (value != null) { + List mayProvide = extnType.getMayProvidedIntents(); + for (StringTokenizer tokens = new StringTokenizer(value); tokens.hasMoreTokens();) { + QName qname = getQNameValue(reader, tokens.nextToken()); + Intent intent = policyFactory.createIntent(); + intent.setName(qname); + mayProvide.add(intent); + } + } + } + + public void write(ExtensionType extnType, XMLStreamWriter writer) throws ContributionWriteException, + XMLStreamException { + + // Write an + if (extnType instanceof BindingType) { + writer.writeStartElement(SCA11_NS, BINDING_TYPE); + } else if (extnType instanceof ImplementationType) { + writer.writeStartElement(SCA11_NS, IMPLEMENTATION_TYPE); + } + + writeAlwaysProvidesIntentsAttribute(extnType, writer); + writeMayProvideIntentsAttribute(extnType, writer); + + writer.writeEndElement(); + } + + private void writeMayProvideIntentsAttribute(ExtensionType extnType, XMLStreamWriter writer) + throws XMLStreamException { + StringBuffer sb = new StringBuffer(); + for (Intent intent : extnType.getMayProvidedIntents()) { + writer.writeNamespace(intent.getName().getPrefix(), intent.getName().getNamespaceURI()); + sb.append(intent.getName().getPrefix() + COLON + intent.getName().getLocalPart()); + sb.append(WHITE_SPACE); + } + + if (sb.length() > 0) { + writer.writeAttribute(MAY_PROVIDE, sb.toString()); + } + } + + private void writeAlwaysProvidesIntentsAttribute(ExtensionType extnType, XMLStreamWriter writer) + throws XMLStreamException { + StringBuffer sb = new StringBuffer(); + for (Intent intent : extnType.getAlwaysProvidedIntents()) { + writer.writeNamespace(intent.getName().getPrefix(), intent.getName().getNamespaceURI()); + sb.append(intent.getName().getPrefix() + COLON + intent.getName().getLocalPart()); + sb.append(WHITE_SPACE); + } + + if (sb.length() > 0) { + writer.writeAttribute(ALWAYS_PROVIDES, sb.toString()); + + } + } + + public void resolve(ExtensionType extnType, ModelResolver resolver) throws ContributionResolveException { + + if (extnType != null && extnType.isUnresolved()) { + resolveAlwaysProvidedIntents(extnType, resolver); + resolveMayProvideIntents(extnType, resolver); + extnType.setUnresolved(false); + //resolveExtensionType(extnType, resolver); + } + } + + private void resolveAlwaysProvidedIntents(ExtensionType extensionType, ModelResolver resolver) + throws ContributionResolveException { + if (extensionType != null) { + // resolve all provided intents + List alwaysProvided = new ArrayList(); + for (Intent providedIntent : extensionType.getAlwaysProvidedIntents()) { + if (providedIntent.isUnresolved()) { + providedIntent = resolver.resolveModel(Intent.class, providedIntent); + if (!providedIntent.isUnresolved()) { + alwaysProvided.add(providedIntent); + } else { + error("AlwaysProvidedIntentNotFound", resolver, providedIntent, extensionType); + //throw new ContributionResolveException("Always Provided Intent - " + providedIntent + //+ " not found for ExtensionType " + //+ extensionType); + } + } else { + alwaysProvided.add(providedIntent); + } + } + extensionType.getAlwaysProvidedIntents().clear(); + extensionType.getAlwaysProvidedIntents().addAll(alwaysProvided); + } + } + + private void resolveMayProvideIntents(ExtensionType extensionType, ModelResolver resolver) + throws ContributionResolveException { + if (extensionType != null) { + // resolve all provided intents + List mayProvide = new ArrayList(); + for (Intent providedIntent : extensionType.getMayProvidedIntents()) { + if (providedIntent.isUnresolved()) { + providedIntent = resolver.resolveModel(Intent.class, providedIntent); + if (!providedIntent.isUnresolved()) { + mayProvide.add(providedIntent); + } else { + error("MayProvideIntentNotFound", resolver, providedIntent, extensionType); + //throw new ContributionResolveException("May Provide Intent - " + providedIntent + //+ " not found for ExtensionType " + //+ extensionType); + } + } else { + mayProvide.add(providedIntent); + } + } + extensionType.getMayProvidedIntents().clear(); + extensionType.getMayProvidedIntents().addAll(mayProvide); + } + } + + public Class getModelType() { + return ExtensionType.class; + } +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/ImplementationTypeProcessor.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/ImplementationTypeProcessor.java new file mode 100644 index 0000000000..41e2af3809 --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/ImplementationTypeProcessor.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.policy.xml; + +import javax.xml.namespace.QName; + +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.policy.ExtensionType; +import org.apache.tuscany.sca.policy.ImplementationType; +import org.apache.tuscany.sca.policy.PolicyFactory; + +/** + * Processor for handling XML models of ImplementationType meta data definitions + * + * @version $Rev$ $Date$ + */ +public class ImplementationTypeProcessor extends ExtensionTypeProcessor { + + public ImplementationTypeProcessor(PolicyFactory policyFactory, + StAXArtifactProcessor extensionProcessor, + Monitor monitor) { + super(policyFactory, extensionProcessor, monitor); + } + + public ImplementationTypeProcessor(FactoryExtensionPoint modelFactories, + StAXArtifactProcessor extensionProcessor, + Monitor monitor) { + super(modelFactories.getFactory(PolicyFactory.class), extensionProcessor, monitor); + } + + public QName getArtifactType() { + return IMPLEMENTATION_TYPE_QNAME; + } + + @Override + protected ExtensionType resolveExtensionType(ExtensionType extnType, ModelResolver resolver) + throws ContributionResolveException { + if (extnType instanceof ImplementationType) { + ImplementationType implType = (ImplementationType)extnType; + return resolver.resolveModel(ImplementationType.class, implType); + } else { + return extnType; + } + + } +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/IntentProcessor.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/IntentProcessor.java new file mode 100644 index 0000000000..d87921dbbf --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/IntentProcessor.java @@ -0,0 +1,387 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.policy.xml; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.StringTokenizer; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; +import org.apache.tuscany.sca.policy.ExtensionType; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.PolicyFactory; +import org.apache.tuscany.sca.policy.Intent.Type; + +/** + * Processor for handling XML models of PolicyIntent definitions + * + * @version $Rev$ $Date$ + */ +public class IntentProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor, + PolicyConstants { + + private PolicyFactory policyFactory; + private Monitor monitor; + + public IntentProcessor(FactoryExtensionPoint modelFactories, Monitor monitor) { + this.policyFactory = modelFactories.getFactory(PolicyFactory.class); + this.monitor = monitor; + } + + public IntentProcessor(PolicyFactory policyFactory, Monitor monitor) { + this.policyFactory = policyFactory; + this.monitor = monitor; + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = + monitor.createProblem(this.getClass().getName(), + "policy-xml-validation-messages", + Severity.ERROR, + model, + message, + messageParameters); + monitor.problem(problem); + } + } + + private void warn(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = + monitor.createProblem(this.getClass().getName(), + "policy-xml-validation-messages", + Severity.WARNING, + model, + message, + messageParameters); + monitor.problem(problem); + } + } + + public Intent read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + Intent intent = null; + String intentLocalName = reader.getAttributeValue(null, NAME); + if (intentLocalName == null) { + error("IntentNameMissing", reader); + return null; + } + + String intentType = reader.getAttributeValue(null, INTENT_TYPE); + if (intentType == null) { + intentType = Intent.Type.interaction.name(); + } + + intent = policyFactory.createIntent(); + + // [rfeng] the target namespace is not available, set the local part for now + // This will be changed in the definitions processor + intent.setName(new QName(intentLocalName)); + intent.setType(Type.valueOf(intentType)); + + readRequiredIntents(intent, reader); + readExcludedIntents(intent, reader); + + readConstrainedTypes(intent, reader); + + Intent current = intent; + int event = reader.getEventType(); + QName name = null; + while (reader.hasNext()) { + event = reader.getEventType(); + switch (event) { + case START_ELEMENT: { + name = reader.getName(); + if (DESCRIPTION_QNAME.equals(name)) { + current.setDescription(reader.getElementText()); + } else if (INTENT_QUALIFIER_QNAME.equals(name)) { + String qualifierName = reader.getAttributeValue(null, NAME); + String defaultQ = reader.getAttributeValue(null, DEFAULT); + boolean isDefault = defaultQ == null ? false : Boolean.parseBoolean(defaultQ); + String qualifiedIntentName = intentLocalName + QUALIFIER + qualifierName; + Intent qualified = policyFactory.createIntent(); + qualified.setType(intent.getType()); + qualified.setName(new QName(qualifiedIntentName)); + if (isDefault) { + intent.setDefaultQualifiedIntent(qualified); + } + intent.getQualifiedIntents().add(qualified); + qualified.setQualifiableIntent(intent); + current = qualified; + } + break; + } + case END_ELEMENT: { + name = reader.getName(); + if (INTENT_QUALIFIER_QNAME.equals(name)) { + current = intent; + } + break; + } + } + if (event == END_ELEMENT && POLICY_INTENT_QNAME.equals(reader.getName())) { + break; + } + + //Read the next element + if (reader.hasNext()) { + reader.next(); + } + } + // REVIEW: [rfeng] What's going to happen if there is only one qualified intent + if (intent.getQualifiedIntents().size() == 1) { + intent.setDefaultQualifiedIntent(intent.getQualifiedIntents().get(0)); + } + return intent; + } + + public void write(Intent intent, XMLStreamWriter writer) throws ContributionWriteException, XMLStreamException { + // Write an + writer.writeStartElement(PolicyConstants.SCA11_NS, INTENT); + writer.writeNamespace(intent.getName().getPrefix(), intent.getName().getNamespaceURI()); + writer.writeAttribute(PolicyConstants.NAME, intent.getName().getPrefix() + COLON + + intent.getName().getLocalPart()); + if (intent.getRequiredIntents() != null && intent.getRequiredIntents().size() > 0) { + StringBuffer sb = new StringBuffer(); + for (Intent requiredIntents : intent.getRequiredIntents()) { + sb.append(requiredIntents.getName()); + sb.append(" "); + } + writer.writeAttribute(PolicyConstants.REQUIRES, sb.toString()); + } + + if (intent.getExcludedIntents() != null && intent.getExcludedIntents().size() > 0) { + StringBuffer sb = new StringBuffer(); + for (Intent excludedIntents : intent.getExcludedIntents()) { + sb.append(excludedIntents.getName()); + sb.append(" "); + } + writer.writeAttribute(PolicyConstants.EXCLUDES, sb.toString()); + } + + if (intent.getConstrainedTypes() != null && intent.getConstrainedTypes().size() > 0) { + StringBuffer sb = new StringBuffer(); + for (ExtensionType contrainedArtifact : intent.getConstrainedTypes()) { + sb.append(contrainedArtifact.getType().getPrefix()); + sb.append(':').append(contrainedArtifact.getType().getLocalPart()); + sb.append(" "); + } + writer.writeAttribute(CONSTRAINS, sb.toString()); + } + + if (intent.getDescription() != null && intent.getDescription().length() > 0) { + writer.writeStartElement(PolicyConstants.SCA11_NS, DESCRIPTION); + writer.writeCData(intent.getDescription()); + writer.writeEndElement(); + } + + writer.writeEndElement(); + } + + private void resolveContrainedTypes(Intent intent, ModelResolver resolver) throws ContributionResolveException { + Collection resolvedTypes = new HashSet(); + for (ExtensionType extensionType : intent.getConstrainedTypes()) { + if (ExtensionType.BINDING_BASE.equals(extensionType.getType()) || ExtensionType.IMPLEMENTATION_BASE + .equals(extensionType.getType())) { + // HACK: Mark sca:binding and sca:implementation as resolved + extensionType.setUnresolved(false); + resolvedTypes.add(extensionType); + } else { + ExtensionType resolved = resolver.resolveModel(ExtensionType.class, extensionType); + if (!resolved.isUnresolved() || resolved != extensionType) { + resolvedTypes.add(resolved); + } else { + warn("ConstrainedTypeNotFound", intent, extensionType, intent); + } + } + } + intent.getConstrainedTypes().clear(); + intent.getConstrainedTypes().addAll(resolvedTypes); + } + + private void resolveProfileIntent(Intent intent, ModelResolver resolver) throws ContributionResolveException { + // FIXME: Need to check for cyclic references first i.e an A requiring B + // and then B requiring A... + if (intent != null && !intent.getRequiredIntents().isEmpty()) { + // resolve all required intents + List requiredIntents = new ArrayList(); + for (Intent required : intent.getRequiredIntents()) { + if (required.isUnresolved()) { + Intent resolved = resolver.resolveModel(Intent.class, required); + // At this point, when the required intent is not resolved, it does not mean + // its undeclared, chances are that their dependency are not resolved yet. + // Lets try to resolve them first. + if (resolved.isUnresolved()) { + if (((resolved).getRequiredIntents()).contains(intent)) { + error("CyclicReferenceFound", resolver, required, intent); + return; + } + } + + if (!resolved.isUnresolved() || resolved != required) { + requiredIntents.add(resolved); + } else { + error("RequiredIntentNotFound", resolver, required, intent); + return; + //throw new ContributionResolveException("Required Intent - " + requiredIntent + //+ " not found for Intent " + policyIntent); + } + } else { + requiredIntents.add(required); + } + } + intent.getRequiredIntents().clear(); + intent.getRequiredIntents().addAll(requiredIntents); + } + } + + private void resolveQualifiedIntent(Intent qualifed, ModelResolver resolver) throws ContributionResolveException { + if (qualifed != null) { + //resolve the qualifiable intent + Intent parent = qualifed.getQualifiableIntent(); + if (parent == null) { + return; + } + if (parent.isUnresolved()) { + Intent resolved = resolver.resolveModel(Intent.class, parent); + // At this point, when the qualifiable intent is not resolved, it does not mean + // its undeclared, chances are that their dependency are not resolved yet. + // Lets try to resolve them first. + + if (!resolved.isUnresolved() || resolved != qualifed) { + qualifed.setQualifiableIntent(resolved); + } else { + error("QualifiableIntentNotFound", resolver, parent, qualifed); + //throw new ContributionResolveException("Qualifiable Intent - " + qualifiableIntent + //+ " not found for Intent " + policyIntent); + } + } + } + } + + public void resolve(Intent intent, ModelResolver resolver) throws ContributionResolveException { + resolveProfileIntent(intent, resolver); + resolveExcludedIntents(intent, resolver); + resolveQualifiedIntent(intent, resolver); + resolveContrainedTypes(intent, resolver); + intent.setUnresolved(false); + } + + public QName getArtifactType() { + return POLICY_INTENT_QNAME; + } + + private void readConstrainedTypes(Intent policyIntent, XMLStreamReader reader) throws ContributionReadException { + String value = reader.getAttributeValue(null, CONSTRAINS); + if (value != null) { + List constrainedTypes = policyIntent.getConstrainedTypes(); + for (StringTokenizer tokens = new StringTokenizer(value); tokens.hasMoreTokens();) { + QName qname = getQNameValue(reader, tokens.nextToken()); + ExtensionType extensionType = policyFactory.createExtensionType(); + extensionType.setType(qname); + constrainedTypes.add(extensionType); + } + } + } + + private void readRequiredIntents(Intent intent, XMLStreamReader reader) { + String value = reader.getAttributeValue(null, REQUIRES); + if (value != null) { + List requiredIntents = intent.getRequiredIntents(); + for (StringTokenizer tokens = new StringTokenizer(value); tokens.hasMoreTokens();) { + QName qname = getQNameValue(reader, tokens.nextToken()); + Intent required = policyFactory.createIntent(); + required.setName(qname); + required.setUnresolved(true); + requiredIntents.add(required); + } + } + } + + private void readExcludedIntents(Intent intent, XMLStreamReader reader) { + String value = reader.getAttributeValue(null, EXCLUDES); + if (value != null) { + List excludedIntents = intent.getExcludedIntents(); + for (StringTokenizer tokens = new StringTokenizer(value); tokens.hasMoreTokens();) { + QName qname = getQNameValue(reader, tokens.nextToken()); + Intent excluded = policyFactory.createIntent(); + excluded.setName(qname); + excluded.setUnresolved(true); + excludedIntents.add(excluded); + } + } + } + + private void resolveExcludedIntents(Intent policyIntent, ModelResolver resolver) + throws ContributionResolveException { + if (policyIntent != null) { + // resolve all excluded intents + List excludedIntents = new ArrayList(); + for (Intent excludedIntent : policyIntent.getExcludedIntents()) { + if (excludedIntent.isUnresolved()) { + Intent resolvedExcludedIntent = resolver.resolveModel(Intent.class, excludedIntent); + if (!resolvedExcludedIntent.isUnresolved()) { + excludedIntents.add(resolvedExcludedIntent); + } else { + error("ExcludedIntentNotFound", resolver, excludedIntent, policyIntent); + return; + //throw new ContributionResolveException("Excluded Intent " + excludedIntent + //+ " not found for intent " + policyIntent); + } + } else { + excludedIntents.add(excludedIntent); + } + } + policyIntent.getExcludedIntents().clear(); + policyIntent.getExcludedIntents().addAll(excludedIntents); + } + } + + public Class getModelType() { + return Intent.class; + } + +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyConstants.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyConstants.java new file mode 100644 index 0000000000..7d63440e23 --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyConstants.java @@ -0,0 +1,74 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.policy.xml; + +import javax.xml.namespace.QName; + +/** + * constants related to policy framework + * + * @version $Rev$ $Date$ + */ +public interface PolicyConstants { + String WHITE_SPACE = " "; + String COLON = ":"; + String SCA11_NS = "http://docs.oasis-open.org/ns/opencsa/sca/200903"; + String TUSCANY_NS = "http://tuscany.apache.org/xmlns/sca/1.1"; + String INTENT = "intent"; + String POLICY_SET = "policySet"; + String POLICY_SET_REFERENCE = "policySetReference"; + String INTENT_MAP = "intentMap"; + String NAME = "name"; + String TARGET_NAMESPACE = "targetNamespace"; + String SCA_DEFINITIONS = "definitions"; + String CONSTRAINS = "constrains"; + String DESCRIPTION = "description"; + String PROVIDES = "provides"; + String APPLIES_TO = "appliesTo"; + String ATTACH_TO = "attachTo"; + String ALWAYS_APPLIES_TO = "alwaysAppliesTo"; + String QUALIFIER = "."; + String INTENT_QUALIFIER = "qualifier"; + String INTENT_MAP_QUALIFIER = "qualifier"; + String REQUIRES = "requires"; + String EXCLUDES = "excludes"; + String DEFAULT = "default"; + + String ALWAYS_PROVIDES = "alwaysProvides"; + String MAY_PROVIDE = "mayProvide"; + String INTENT_TYPE = "intentType"; + String IMPLEMENTATION_TYPE = "implementationType"; + String BINDING_TYPE = "bindingType"; + QName IMPLEMENTATION_TYPE_QNAME = new QName(SCA11_NS, IMPLEMENTATION_TYPE); + QName BINDING_TYPE_QNAME = new QName(SCA11_NS, BINDING_TYPE); + String BINDING = "binding"; + String IMPLEMENTATION = "implementation"; + + QName POLICY_INTENT_QNAME = new QName(SCA11_NS, INTENT); + QName POLICY_SET_QNAME = new QName(SCA11_NS, POLICY_SET); + QName POLICY_INTENT_MAP_QNAME = new QName(SCA11_NS, INTENT_MAP); + QName SCA_DEFINITIONS_QNAME = new QName(SCA11_NS, SCA_DEFINITIONS); + QName DESCRIPTION_QNAME = new QName(SCA11_NS, DESCRIPTION); + QName POLICY_INTENT_MAP_QUALIFIER_QNAME = new QName(SCA11_NS, INTENT_MAP_QUALIFIER); + QName POLICY_SET_REFERENCE_QNAME = new QName(SCA11_NS, POLICY_SET_REFERENCE); + QName INTENT_QUALIFIER_QNAME = new QName(SCA11_NS, INTENT_QUALIFIER); + + String QUALIFIED_INTENT_CONSTRAINS_ERROR = " - Qualified Intents must not specify 'constrains' attribute"; + +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicySetProcessor.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicySetProcessor.java new file mode 100644 index 0000000000..955788ce8f --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicySetProcessor.java @@ -0,0 +1,490 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.policy.xml; + +import static javax.xml.stream.XMLStreamConstants.END_ELEMENT; +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.apache.tuscany.sca.contribution.processor.BaseStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.FactoryExtensionPoint; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.Problem; +import org.apache.tuscany.sca.monitor.Problem.Severity; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentMap; +import org.apache.tuscany.sca.policy.PolicyExpression; +import org.apache.tuscany.sca.policy.PolicyFactory; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.Qualifier; + +/** + * Processor for handling XML models of PolicySet definitions + * + * @version $Rev$ $Date$ + */ +public class PolicySetProcessor extends BaseStAXArtifactProcessor implements StAXArtifactProcessor, + PolicyConstants { + + private PolicyFactory policyFactory; + private StAXArtifactProcessor extensionProcessor; + private XPathFactory xpathFactory = XPathFactory.newInstance(); + private Monitor monitor; + + public PolicySetProcessor(FactoryExtensionPoint modelFactories, + StAXArtifactProcessor extensionProcessor, + Monitor monitor) { + this.policyFactory = modelFactories.getFactory(PolicyFactory.class); + this.extensionProcessor = extensionProcessor; + this.monitor = monitor; + } + + public PolicySetProcessor(PolicyFactory policyFactory, + StAXArtifactProcessor extensionProcessor, + Monitor monitor) { + this.policyFactory = policyFactory; + this.extensionProcessor = extensionProcessor; + this.monitor = monitor; + } + + /** + * Report a exception. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Exception ex) { + if (monitor != null) { + Problem problem = + monitor.createProblem(this.getClass().getName(), + "policy-xml-validation-messages", + Severity.ERROR, + model, + message, + ex); + monitor.problem(problem); + } + } + + /** + * Report a error. + * + * @param problems + * @param message + * @param model + */ + private void error(String message, Object model, Object... messageParameters) { + if (monitor != null) { + Problem problem = + monitor.createProblem(this.getClass().getName(), + "policy-xml-validation-messages", + Severity.ERROR, + model, + message, + (Object[])messageParameters); + monitor.problem(problem); + } + } + + public PolicySet read(XMLStreamReader reader) throws ContributionReadException, XMLStreamException { + PolicySet policySet = null; + + String policySetName = reader.getAttributeValue(null, NAME); + String appliesTo = reader.getAttributeValue(null, APPLIES_TO); + if (policySetName == null || appliesTo == null) { + if (policySetName == null) + error("PolicySetNameMissing", reader); + if (appliesTo == null) + error("PolicySetAppliesToMissing", reader); + return policySet; + } + + policySet = policyFactory.createPolicySet(); + policySet.setName(new QName(policySetName)); + + //TODO: with 1.0 version of specs the applies to xpath is given related to the immediate + //parent whereas the runtime evaluates the xpath aginst the composite element. What the runtime + //is doing is what the future version of the specs could be tending towards. When that happens + //this 'if' must be deleted + if (appliesTo != null && !appliesTo.startsWith("/")) { + appliesTo = "//" + appliesTo; + } + + policySet.setAppliesTo(appliesTo); + + XPath path = xpathFactory.newXPath(); + path.setNamespaceContext(reader.getNamespaceContext()); + try { + if (appliesTo != null) { + policySet.setAppliesToXPathExpression(path.compile(appliesTo)); + } + } catch (XPathExpressionException e) { + ContributionReadException ce = new ContributionReadException(e); + error("ContributionReadException", policySet, ce); + //throw ce; + } + + readProvidedIntents(policySet, reader); + + int event = reader.getEventType(); + QName name = null; + reader.next(); + while (reader.hasNext()) { + event = reader.getEventType(); + switch (event) { + case START_ELEMENT: { + name = reader.getName(); + if (POLICY_INTENT_MAP_QNAME.equals(name)) { + Intent mappedIntent = policyFactory.createIntent(); + String provides = reader.getAttributeValue(null, PROVIDES); + if (provides != null) { + mappedIntent.setName(getQName(reader, PROVIDES)); + if (policySet.getProvidedIntents().contains(mappedIntent)) { + readIntentMap(reader, policySet, mappedIntent); + } else { + error("IntentNotSpecified", policySet, policySetName); + //throw new ContributionReadException("Intent Map provides for Intent not specified as provided by parent PolicySet - " + policySetName); + } + } else { + error("IntentMapProvidesMissing", reader, policySetName); + } + } else if (POLICY_SET_REFERENCE_QNAME.equals(name)) { + PolicySet referredPolicySet = policyFactory.createPolicySet(); + String referencename = reader.getAttributeValue(null, NAME); + if (referencename != null) { + referredPolicySet.setName(getQName(reader, NAME)); + policySet.getReferencedPolicySets().add(referredPolicySet); + } else { + error("PolicySetReferenceNameMissing", reader, policySetName); + } + } /*else if ( WS_POLICY_QNAME.equals(name) ) { + OMElement policyElement = loadElement(reader); + org.apache.neethi.Policy wsPolicy = PolicyEngine.getPolicy(policyElement); + policySet.getPolicies().add(wsPolicy); + } */else { + Object extension = extensionProcessor.read(reader); + if (extension != null) { + PolicyExpression exp = policyFactory.createPolicyExpression(); + exp.setName(name); + exp.setPolicy(extension); + policySet.getPolicies().add(exp); + } + } + break; + } + } + if (event == END_ELEMENT) { + if (POLICY_SET_QNAME.equals(reader.getName())) { + break; + } + } + + //Read the next element + if (reader.hasNext()) { + reader.next(); + } + } + return policySet; + } + + public void readIntentMap(XMLStreamReader reader, PolicySet policySet, Intent mappedIntent) + throws ContributionReadException { + QName name = reader.getName(); + if (POLICY_INTENT_MAP_QNAME.equals(name)) { + + IntentMap intentMap = policyFactory.createIntentMap(); + QName intentName = getQName(reader, INTENT_MAP); + intentMap.setProvidedIntent(mappedIntent); + + policySet.getIntentMaps().add(intentMap); + + String qualifierName = null; + String qualfiedIntentName = null; + Intent qualifiedIntent = null; + + Qualifier qualifier = null; + + int event = reader.getEventType(); + try { + reader.next(); + while (reader.hasNext()) { + event = reader.getEventType(); + switch (event) { + case START_ELEMENT: { + name = reader.getName(); + if (POLICY_INTENT_MAP_QUALIFIER_QNAME.equals(name)) { + qualifierName = getString(reader, NAME); + if (qualifierName != null) { + qualfiedIntentName = + mappedIntent.getName().getLocalPart() + QUALIFIER + qualifierName; + qualifiedIntent = policyFactory.createIntent(); + qualifiedIntent.setName(new QName(mappedIntent.getName().getNamespaceURI(), + qualfiedIntentName)); + qualifier = policyFactory.createQualifier(); + qualifier.setIntent(qualifiedIntent); + intentMap.getQualifiers().add(qualifier); + + } else { + error("QualifierNameMissing", reader, policySet.getName()); + } + } else if (POLICY_INTENT_MAP_QNAME.equals(name)) { + QName providedIntent = getQName(reader, PROVIDES); + if (qualifierName.equals(providedIntent.getLocalPart())) { + readIntentMap(reader, policySet, qualifiedIntent); + } else { + error("IntentMapDoesNotMatch", + providedIntent, + providedIntent, + qualifierName, + policySet); + //throw new ContributionReadException("Intent provided by IntentMap " + + //providedIntent + " does not match parent qualifier " + qualifierName + + //" in policyset - " + policySet); + } + } else { + Object extension = extensionProcessor.read(reader); + if (extension != null && qualifier != null) { + PolicyExpression exp = policyFactory.createPolicyExpression(); + exp.setName(name); + exp.setPolicy(extension); + qualifier.getPolicies().add(exp); + } + } + break; + } + } + if (event == END_ELEMENT && POLICY_INTENT_MAP_QNAME.equals(reader.getName())) { + break; + } + //Read the next element + if (reader.hasNext()) { + reader.next(); + } + } + } catch (XMLStreamException e) { + ContributionReadException ce = new ContributionReadException(e); + error("ContributionReadException", reader, ce); + throw ce; + } + } + } + + public void write(PolicySet policySet, XMLStreamWriter writer) throws ContributionWriteException, + XMLStreamException { + + // Write an + writer.writeStartElement(SCA11_NS, POLICY_SET); + writer.writeNamespace(policySet.getName().getPrefix(), policySet.getName().getNamespaceURI()); + writer.writeAttribute(NAME, policySet.getName().getPrefix() + COLON + policySet.getName().getLocalPart()); + writer.writeAttribute(APPLIES_TO, policySet.getAppliesTo()); + writer.writeAttribute(ATTACH_TO, policySet.getAttachTo()); + + writeProvidedIntents(policySet, writer); + + writer.writeEndElement(); + } + + private void readProvidedIntents(PolicySet policySet, XMLStreamReader reader) { + String value = reader.getAttributeValue(null, PROVIDES); + if (value != null) { + List providedIntents = policySet.getProvidedIntents(); + for (StringTokenizer tokens = new StringTokenizer(value); tokens.hasMoreTokens();) { + QName qname = getQNameValue(reader, tokens.nextToken()); + Intent intent = policyFactory.createIntent(); + intent.setName(qname); + providedIntents.add(intent); + } + } + } + + private void writeProvidedIntents(PolicySet policySet, XMLStreamWriter writer) throws XMLStreamException { + if (!policySet.getProvidedIntents().isEmpty()) { + StringBuffer sb = new StringBuffer(); + for (Intent providedIntents : policySet.getProvidedIntents()) { + sb.append(getQualifiedName(providedIntents.getName(), writer)); + sb.append(" "); + } + // Remove the last space + sb.deleteCharAt(sb.length() - 1); + writer.writeAttribute(PolicyConstants.PROVIDES, sb.toString()); + } + } + + private String getQualifiedName(QName name, XMLStreamWriter writer) throws XMLStreamException { + String local = name.getLocalPart(); + String prefix = writer.getPrefix(name.getNamespaceURI()); + if (prefix != null && prefix.length() > 0) { + return prefix + ':' + local; + } else { + return local; + } + } + + private void resolvePolicies(PolicySet policySet, ModelResolver resolver) throws ContributionResolveException { + boolean unresolved = false; + if (policySet != null) { + for (Object o : policySet.getPolicies()) { + extensionProcessor.resolve(o, resolver); + /*if ( o instanceof Policy && ((Policy)o).isUnresolved() ) { + unresolved = true; + }*/ + } + policySet.setUnresolved(unresolved); + } + } + + public QName getArtifactType() { + return POLICY_SET_QNAME; + } + + public Class getModelType() { + return PolicySet.class; + } + + private void resolveProvidedIntents(PolicySet policySet, ModelResolver resolver) + throws ContributionResolveException { + if (policySet != null) { + //resolve all provided intents + List providedIntents = new ArrayList(); + for (Intent providedIntent : policySet.getProvidedIntents()) { + if (providedIntent.isUnresolved()) { + Intent resolved = resolver.resolveModel(Intent.class, providedIntent); + if (!resolved.isUnresolved() || resolved != providedIntent) { + providedIntents.add(resolved); + } else { + error("ProvidedIntentNotFound", policySet, providedIntent, policySet); + return; + //throw new ContributionResolveException("Provided Intent - " + providedIntent + //+ " not found for PolicySet " + policySet); + } + } else { + providedIntents.add(providedIntent); + } + } + policySet.getProvidedIntents().clear(); + policySet.getProvidedIntents().addAll(providedIntents); + } + } + + private void resolveIntentsInMappedPolicies(PolicySet policySet, ModelResolver resolver) + throws ContributionResolveException { + for (IntentMap intentMap : policySet.getIntentMaps()) { + Intent intent = intentMap.getProvidedIntent(); + if (intent.isUnresolved()) { + Intent resolved = resolver.resolveModel(Intent.class, intent); + if (!resolved.isUnresolved() || resolved != intent) { + intentMap.setProvidedIntent(resolved); + } else { + error("MappedIntentNotFound", policySet, intent, policySet); + return; + //throw new ContributionResolveException("Mapped Intent - " + mappedIntent + //+ " not found for PolicySet " + policySet); + } + } + for (Qualifier qualifier : intentMap.getQualifiers()) { + intent = qualifier.getIntent(); + if (intent.isUnresolved()) { + Intent resolved = resolver.resolveModel(Intent.class, intent); + if (!resolved.isUnresolved() || resolved != intent) { + qualifier.setIntent(resolved); + } else { + error("MappedIntentNotFound", policySet, intent, policySet); + return; + //throw new ContributionResolveException("Mapped Intent - " + mappedIntent + //+ " not found for PolicySet " + policySet); + } + } + for (PolicyExpression exp : qualifier.getPolicies()) { + // FIXME: How to resolve the policies? + } + } + } + + } + + private void resolveReferredPolicySets(PolicySet policySet, ModelResolver resolver) + throws ContributionResolveException { + + List referredPolicySets = new ArrayList(); + for (PolicySet referredPolicySet : policySet.getReferencedPolicySets()) { + if (referredPolicySet.isUnresolved()) { + PolicySet resolved = resolver.resolveModel(PolicySet.class, referredPolicySet); + if (!resolved.isUnresolved() || resolved != referredPolicySet) { + referredPolicySets.add(resolved); + } else { + error("ReferredPolicySetNotFound", policySet, referredPolicySet, policySet); + return; + //throw new ContributionResolveException("Referred PolicySet - " + referredPolicySet + //+ "not found for PolicySet - " + policySet); + } + } else { + referredPolicySets.add(referredPolicySet); + } + } + policySet.getReferencedPolicySets().clear(); + policySet.getReferencedPolicySets().addAll(referredPolicySets); + } + + private void includeReferredPolicySets(PolicySet policySet, PolicySet referredPolicySet) { + for (PolicySet furtherReferredPolicySet : referredPolicySet.getReferencedPolicySets()) { + includeReferredPolicySets(referredPolicySet, furtherReferredPolicySet); + } + policySet.getPolicies().addAll(referredPolicySet.getPolicies()); + policySet.getIntentMaps().addAll(referredPolicySet.getIntentMaps()); + } + + public void resolve(PolicySet policySet, ModelResolver resolver) throws ContributionResolveException { + resolveProvidedIntents(policySet, resolver); + resolveIntentsInMappedPolicies(policySet, resolver); + resolveReferredPolicySets(policySet, resolver); + + for (PolicySet referredPolicySet : policySet.getReferencedPolicySets()) { + includeReferredPolicySets(policySet, referredPolicySet); + } + + if (policySet.isUnresolved()) { + //resolve the policy attachments + resolvePolicies(policySet, resolver); + + /*if ( !policySet.isUnresolved() ) { + resolver.addModel(policySet); + }*/ + } + + policySet.setUnresolved(false); + } +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunction.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunction.java new file mode 100644 index 0000000000..1b6d64e4f7 --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunction.java @@ -0,0 +1,127 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.policy.xml; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.xpath.XPathFunction; +import javax.xml.xpath.XPathFunctionException; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * The SCA-defined XPath function + */ +public class PolicyXPathFunction implements XPathFunction { + private static Logger logger = Logger.getLogger(PolicyXPathFunction.class.getName()); + + static final QName InterfaceRef = new QName(PolicyConstants.SCA11_NS, "InterfaceRef"); + static final QName OperationRef = new QName(PolicyConstants.SCA11_NS, "OperationRef"); + static final QName MessageRef = new QName(PolicyConstants.SCA11_NS, "MessageRef"); + static final QName IntentRefs = new QName(PolicyConstants.SCA11_NS, "IntentRefs"); + static final QName URIRef = new QName(PolicyConstants.SCA11_NS, "URIRef"); + + static final Set functions = + new HashSet(Arrays.asList(InterfaceRef, OperationRef, MessageRef, IntentRefs, URIRef)); + + private NamespaceContext namespaceContext; + private final QName functionName; + + public PolicyXPathFunction(NamespaceContext namespaceContext, QName functionName) { + super(); + this.namespaceContext = namespaceContext; + this.functionName = functionName; + } + + private Node getContextNode(List args) { + if (args.size() >= 2) { + NodeList nodeList = (NodeList)args.get(1); + if (nodeList.getLength() > 0) { + return nodeList.item(0); + } + } + return null; + } + + public Object evaluate(List args) throws XPathFunctionException { + if (logger.isLoggable(Level.FINE)) { + logger.fine(functionName + "(" + args + ")"); + } + + String arg = (String)args.get(0); + Node node = getContextNode(args); + if (InterfaceRef.equals(functionName)) { + return evaluateInterface(arg, node); + } else if (OperationRef.equals(functionName)) { + String[] params = arg.split("/"); + if (params.length != 2) { + throw new IllegalArgumentException("Invalid argument: " + arg); + } + String interfaceName = params[0]; + String operationName = params[1]; + return evaluateOperation(interfaceName, operationName, node); + } else if (MessageRef.equals(functionName)) { + String[] params = arg.split("/"); + if (params.length != 3) { + throw new IllegalArgumentException("Invalid argument: " + arg); + } + String interfaceName = params[0]; + String operationName = params[1]; + String messageName = params[2]; + return evaluateMessage(interfaceName, operationName, messageName, node); + } else if (URIRef.equals(functionName)) { + return evaluateURI(arg, node); + } else if (IntentRefs.equals(functionName)) { + String[] intents = arg.split("(\\s)+"); + return evaluateIntents(intents, node); + } else { + return Boolean.FALSE; + } + } + + private Boolean evaluateInterface(String interfaceName, Node node) { + return Boolean.FALSE; + } + + private Boolean evaluateOperation(String interfaceName, String operationName, Node node) { + return Boolean.FALSE; + } + + private Boolean evaluateMessage(String interfaceName, String operationName, String messageName, Node node) { + return Boolean.FALSE; + } + + private Boolean evaluateURI(String uri, Node node) { + return Boolean.FALSE; + } + + private Boolean evaluateIntents(String[] intents, Node node) { + return Boolean.FALSE; + } + +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunctionResolver.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunctionResolver.java new file mode 100644 index 0000000000..ca44667903 --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunctionResolver.java @@ -0,0 +1,72 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.policy.xml; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.namespace.QName; +import javax.xml.xpath.XPathFunction; +import javax.xml.xpath.XPathFunctionResolver; + +/** + * A resolver that handles SCA-defined XPath functions + * + * Interface Related Functions + *
    + *
  • InterfaceRef( InterfaceName ) + *
  • OperationRef( InterfaceName/OperationName ) + *
  • MessageRef( InterfaceName/OperationName/MessageName ) + *
+ * + * Intent Related Functions + *
    + *
  • IntentRefs( IntentList ) + *
+ * + * URI Based Function + *
    + *
  • URIRef( URI ) + *
+ */ +public class PolicyXPathFunctionResolver implements XPathFunctionResolver { + private NamespaceContext namespaceContext; + + public PolicyXPathFunctionResolver(NamespaceContext namespaceContext) { + super(); + this.namespaceContext = namespaceContext; + } + + public XPathFunction resolveFunction(QName functionName, int arity) { + if (functionName == null) { + throw new NullPointerException("Function name is null"); + } + if (PolicyXPathFunction.functions.contains(functionName)) { + if (arity >= 1) { + // We are relaxing the arity here so that we can pass in the context node + // by modifying the original xpath so that sca functions take self::node() + // as the 2nd argument + return new PolicyXPathFunction(namespaceContext, functionName); + } else { + throw new IllegalArgumentException("Invalid number of arguments: " + arity); + } + } + return null; + } + +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor new file mode 100644 index 0000000000..a64b22dc2a --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor @@ -0,0 +1,22 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Implementation class for the artifact processor extension +org.apache.tuscany.sca.policy.xml.BindingTypeProcessor;qname=http://docs.oasis-open.org/ns/opencsa/sca/200903#bindingType,model=org.apache.tuscany.sca.policy.BindingType +org.apache.tuscany.sca.policy.xml.ImplementationTypeProcessor;qname=http://docs.oasis-open.org/ns/opencsa/sca/200903#implementationType,model=org.apache.tuscany.sca.policy.ImplementationType +org.apache.tuscany.sca.policy.xml.IntentProcessor;qname=http://docs.oasis-open.org/ns/opencsa/sca/200903#intent,model=org.apache.tuscany.sca.policy.Intent +org.apache.tuscany.sca.policy.xml.PolicySetProcessor;qname=http://docs.oasis-open.org/ns/opencsa/sca/200903#policySet,model=org.apache.tuscany.sca.policy.PolicySet diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver new file mode 100644 index 0000000000..4daf46c790 --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/META-INF/services/org.apache.tuscany.sca.contribution.resolver.ModelResolver @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +org.apache.tuscany.sca.contribution.resolver.DefaultModelResolver;model=org.apache.tuscany.sca.policy.Intent diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/policy-xml-validation-messages.properties b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/policy-xml-validation-messages.properties new file mode 100644 index 0000000000..d092b5959a --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/main/resources/policy-xml-validation-messages.properties @@ -0,0 +1,45 @@ +# +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# +# +ReferredPolicySetNotFound = Referred PolicySet - {0} not found for PolicySet - {1} +MappedIntentNotFound = Mapped Intent - {0} not found for PolicySet {1} +ProvidedIntentNotFound = Provided Intent - {0} not found for PolicySet {1} +UnableToMapPolicies = Unable to map policies for default qualifier in IntentMap for - {0} in policy set - {1} +IntentMapDoesNotMatch = Intent provided by IntentMap {0} does not match parent qualifier {1} in policyset - {2} +IntentNotSpecified = Intent Map provides for Intent not specified as provided by parent PolicySet - {0} +ContrainsAttributeMissing = Constrains attribute missing from Policy Intent Definition {0} +RequiredIntentNotFound = Required Intent - {0} not found for ProfileIntent {1} +QualifiableIntentNotFound = Qualifiable Intent - {0} not found for QualifiedIntent {1} +ErrorInPolicyIntentDefinition = Error in PolicyIntent Definition - {0} {1} +ExcludedIntentNotFound = Excluded Intent {0} not found for intent {1} +UnrecognizedIntentAttachPointType = Unrecognized IntentAttachPointType - {0} +RequiredAttributeMissing = Required attribute {0} missing from extension type definition +AlwaysProvidedIntentNotFound = Always Provided Intent - {0} not found for ExtensionType {1} +MayProvideIntentNotFound = May Provide Intent - {0} not found for ExtensionType {1} +ContributionReadException = ContributionReadException occurred due to: {0} +CyclicReferenceFound = Cyclic reference detected in required attributes of ProfileIntents {0} and {1} +IntentNameMissing = Required attribute "name" missing for Intent Definition +PolicySetReferenceNameMissing = Required attribute "name" missing for PolicySetReference in PolicySet : {0} +PolicySetNameMissing = Required attribute "name" missing for PolicySet Definition +PolicySetAppliesToMissing = Required attribute "appliesTo" missing for PolicySet Definition +IntentMapProvidesMissing = Required attribute "provides" missing for IntentMap in PolicySet : {0} +QualifierNameMissing = Required attribute "name" missing for qualifier definition in PolicySet : {0} +ConstrainedTypeNotFound = Unable to find the extension type {0} constrained by intent: {1} + diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunctionResolverTestCase.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunctionResolverTestCase.java new file mode 100644 index 0000000000..e954f1ebe4 --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/PolicyXPathFunctionResolverTestCase.java @@ -0,0 +1,132 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.policy.xml; + +import java.util.Collections; +import java.util.Iterator; + +import javax.xml.namespace.NamespaceContext; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathFactory; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +/** + * + */ +public class PolicyXPathFunctionResolverTestCase { + private static XPath xpath; + + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + XPathFactory factory = XPathFactory.newInstance(); + xpath = factory.newXPath(); + xpath.setNamespaceContext(new NamespaceContextImpl()); + xpath.setXPathFunctionResolver(new PolicyXPathFunctionResolver(xpath.getNamespaceContext())); + } + + @Test + public void testIntentsRef() throws Exception { + InputSource xml = new InputSource(getClass().getResourceAsStream("Calculator.composite")); + // Test the rewrite of xpath so that the self:node() is passed into the SCA function + XPathExpression exp = xpath.compile("//sca:composite/sca:component[sca:IntentRefs('sca:confidentiality', self::node())]"); + Object result = exp.evaluate(xml, XPathConstants.NODESET); + Assert.assertTrue(result instanceof NodeList); + NodeList nodes = (NodeList)result; + // Assert.assertEquals(1, nodes.getLength()); + } + + @Test + public void testURIRef() throws Exception { + InputSource xml = new InputSource(getClass().getResourceAsStream("Calculator.composite")); + XPathExpression exp = xpath.compile("sca:composite/sca:component[sca:URIRef('AddServiceComponent')]"); + Object result = exp.evaluate(xml, XPathConstants.NODESET); + Assert.assertTrue(result instanceof NodeList); + NodeList nodes = (NodeList)result; + // Assert.assertEquals(1, nodes.getLength()); + } + + @Test + public void testInterfaceRef() throws Exception { + InputSource xml = new InputSource(getClass().getResourceAsStream("Calculator.composite")); + XPathExpression exp = xpath.compile("//sca:composite/sca:component/sca:service[sca:InterfaceRef('AddService')]"); + Object result = exp.evaluate(xml, XPathConstants.NODESET); + Assert.assertTrue(result instanceof NodeList); + NodeList nodes = (NodeList)result; + // Assert.assertEquals(1, nodes.getLength()); + } + + @Test + public void testOperationRef() throws Exception { + InputSource xml = new InputSource(getClass().getResourceAsStream("Calculator.composite")); + XPathExpression exp = xpath.compile("//sca:composite/sca:component/sca:reference[sca:OperationRef('AddService/add')]"); + Object result = exp.evaluate(xml, XPathConstants.NODESET); + Assert.assertTrue(result instanceof NodeList); + NodeList nodes = (NodeList)result; + // Assert.assertEquals(1, nodes.getLength()); + } + + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + private static class NamespaceContextImpl implements NamespaceContext { + + private static final String SCA11_NS = "http://docs.oasis-open.org/ns/opencsa/sca/200903"; + + public String getNamespaceURI(String prefix) { + if ("sca".equals(prefix)) { + return SCA11_NS; + } else { + return null; + } + } + + public String getPrefix(String namespaceURI) { + if (SCA11_NS.equals(namespaceURI)) { + return "sca"; + } + return null; + } + + public Iterator getPrefixes(String namespaceURI) { + if (SCA11_NS.equals(namespaceURI)) { + return Collections.singleton("sca").iterator(); + } + return null; + } + + } + +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/ReadDocumentTestCase.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/ReadDocumentTestCase.java new file mode 100644 index 0000000000..0d0f945e43 --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/ReadDocumentTestCase.java @@ -0,0 +1,295 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.tuscany.sca.policy.xml; + +import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; + +import org.apache.tuscany.sca.contribution.processor.ExtensibleStAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessorExtensionPoint; +import org.apache.tuscany.sca.contribution.resolver.DefaultModelResolver; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.core.DefaultExtensionPointRegistry; +import org.apache.tuscany.sca.core.UtilityExtensionPoint; +import org.apache.tuscany.sca.monitor.DefaultMonitorFactory; +import org.apache.tuscany.sca.monitor.Monitor; +import org.apache.tuscany.sca.monitor.MonitorFactory; +import org.apache.tuscany.sca.policy.BindingType; +import org.apache.tuscany.sca.policy.ExtensionType; +import org.apache.tuscany.sca.policy.ImplementationType; +import org.apache.tuscany.sca.policy.Intent; +import org.apache.tuscany.sca.policy.IntentMap; +import org.apache.tuscany.sca.policy.PolicySet; +import org.apache.tuscany.sca.policy.Qualifier; +import org.apache.tuscany.sca.policy.impl.ImplementationTypeImpl; +import org.junit.Before; +import org.junit.Test; + +/** + * Test reading SCA XML assembly documents. + * + * @version $Rev: 551296 $ $Date: 2007-06-28 01:18:35 +0530 (Thu, 28 Jun 2007) $ + */ +public class ReadDocumentTestCase { + + private ModelResolver resolver; + private StAXArtifactProcessor staxProcessor; + private Monitor monitor; + + private static final QName elementToProcess = + new QName("http://docs.oasis-open.org/ns/opencsa/sca/200903", "implementationType"); + + private Map intentTable = new Hashtable(); + private Map policySetTable = new Hashtable(); + private Map bindingTypesTable = new Hashtable(); + private Map implTypesTable = new Hashtable(); + private static final String scaNamespace = "http://docs.oasis-open.org/ns/opencsa/sca/200903"; + private static final String namespace = "http://test"; + + private static final QName confidentiality = new QName(namespace, "confidentiality"); + private static final QName integrity = new QName(namespace, "integrity"); + private static final QName messageProtection = new QName(namespace, "messageProtection"); + private static final QName confidentiality_transport = new QName(namespace, "confidentiality.transport"); + private static final QName confidentiality_message = new QName(namespace, "confidentiality.message"); + private static final QName secureReliablePolicy = new QName(namespace, "SecureReliablePolicy"); + private static final QName secureMessagingPolicies = new QName(namespace, "SecureMessagingPolicies"); + private static final QName securityPolicy = new QName(namespace, "SecurityPolicy"); + private static final QName basicAuthMsgProtSecurity = new QName(namespace, "BasicAuthMsgProtSecurity"); + private static final QName wsBinding = new QName(scaNamespace, "binding.ws"); + private static final QName javaImpl = new QName(scaNamespace, "implementation.java"); + + @Before + public void setUp() throws Exception { + DefaultExtensionPointRegistry extensionPoints = new DefaultExtensionPointRegistry(); + resolver = new DefaultModelResolver(); + XMLInputFactory inputFactory = XMLInputFactory.newInstance(); + // Create a monitor + UtilityExtensionPoint utilities = extensionPoints.getExtensionPoint(UtilityExtensionPoint.class); + MonitorFactory monitorFactory = new DefaultMonitorFactory(); + if (monitorFactory != null) { + monitor = monitorFactory.createMonitor(); + utilities.addUtility(monitorFactory); + } + StAXArtifactProcessorExtensionPoint staxProcessors = + extensionPoints.getExtensionPoint(StAXArtifactProcessorExtensionPoint.class); + staxProcessor = new ExtensibleStAXArtifactProcessor(staxProcessors, inputFactory, null, monitor); + staxProcessors.addArtifactProcessor(new TestPolicyProcessor()); + + URL url = getClass().getResource("test_definitions.xml"); + InputStream urlStream = url.openStream(); + XMLStreamReader reader = inputFactory.createXMLStreamReader(urlStream); + reader.next(); + + //position on the right element qname to get processed + while (reader.hasNext()) { + reader.next(); + int event = reader.getEventType(); + if (event == START_ELEMENT && reader.getName().equals(elementToProcess)) { + break; + } + } + while (true) { + int event = reader.getEventType(); + switch (event) { + case START_ELEMENT: { + Object artifact = staxProcessor.read(reader); + if (artifact instanceof PolicySet) { + PolicySet policySet = (PolicySet)artifact; + policySet.setName(new QName(namespace, policySet.getName().getLocalPart())); + policySetTable.put(policySet.getName(), policySet); + } else if (artifact instanceof Intent) { + Intent intent = (Intent)artifact; + intent.setName(new QName(namespace, intent.getName().getLocalPart())); + intentTable.put(intent.getName(), intent); + for (Intent i : intent.getQualifiedIntents()) { + i.setName(new QName(namespace, i.getName().getLocalPart())); + intentTable.put(i.getName(), i); + resolver.addModel(i); + } + } else if (artifact instanceof BindingType) { + BindingType bindingType = (BindingType)artifact; + bindingTypesTable.put(bindingType.getType(), bindingType); + } else if (artifact instanceof ImplementationTypeImpl) { + ImplementationType implType = (ImplementationType)artifact; + implTypesTable.put(implType.getType(), implType); + } + + if (artifact != null) { + resolver.addModel(artifact); + } + + break; + } + } + if (reader.hasNext()) { + reader.next(); + } else { + break; + } + } + urlStream.close(); + } + + @Test + public void testReadSCADefinitions() throws Exception { + assertNotNull(intentTable.get(confidentiality)); + assertNotNull(intentTable.get(messageProtection)); + assertNotNull(intentTable.get(confidentiality_transport)); + assertTrue(intentTable.get(confidentiality).getDescription().length() > 0); + + assertNotNull(policySetTable.get(secureReliablePolicy)); + assertTrue(policySetTable.get(secureReliablePolicy).getProvidedIntents().size() == 2); + assertTrue(policySetTable.get(secureReliablePolicy).getPolicies().size() == 2); + + assertNotNull(policySetTable.get(secureMessagingPolicies)); + assertEquals(2, policySetTable.get(secureMessagingPolicies).getIntentMaps().get(0).getQualifiers().get(0).getPolicies().size()); + + assertEquals(bindingTypesTable.size(), 1); + assertNotNull(bindingTypesTable.get(wsBinding)); + assertEquals(implTypesTable.size(), 1); + assertNotNull(implTypesTable.get(javaImpl)); + } + + private int getNumberOfQualifiedPolicies(PolicySet policySet) { + int count = 0; + for(IntentMap intentMap: policySet.getIntentMaps()) { + for(Qualifier q: intentMap.getQualifiers()) { + count += q.getPolicies().size(); + } + } + return count; + } + + @Test + public void testResolution() throws Exception { + assertTrue(!intentTable.get(messageProtection).getRequiredIntents().isEmpty()); + Intent profileIntent = intentTable.get(new QName(namespace, "messageProtection")); + assertNull(profileIntent.getRequiredIntents().get(0).getDescription()); + + QName confidentiality_transport = new QName(namespace, "confidentiality.transport"); + assertTrue(intentTable.get(confidentiality_transport) instanceof Intent); + Intent qualifiedIntent = (Intent)intentTable.get(new QName(namespace, "confidentiality.transport")); + assertNull(qualifiedIntent.getDescription()); + assertNotNull(qualifiedIntent.getQualifiableIntent().getDescription()); + + PolicySet secureReliablePolicySet = policySetTable.get(secureReliablePolicy); + PolicySet secureMessagingPolicySet = policySetTable.get(secureMessagingPolicies); + PolicySet securityPolicySet = policySetTable.get(securityPolicy); + + assertEquals(secureReliablePolicySet.getProvidedIntents().get(1).getName(), integrity); + assertNull(secureReliablePolicySet.getProvidedIntents().get(1).getDescription()); + assertTrue(secureMessagingPolicySet.isUnresolved()); + assertEquals(2, getNumberOfQualifiedPolicies(securityPolicySet)); + + //testing to ensure that inclusion of referred policy sets has not happened + PolicySet basicAuthMsgProtSecurityPolicySet = policySetTable.get(basicAuthMsgProtSecurity); + assertTrue(basicAuthMsgProtSecurityPolicySet.getPolicies().isEmpty()); + assertTrue(basicAuthMsgProtSecurityPolicySet.getIntentMaps().isEmpty()); + + ExtensionType wsBindingType = bindingTypesTable.get(wsBinding); + assertNull(wsBindingType.getAlwaysProvidedIntents().get(0).getDescription()); + assertNull(wsBindingType.getMayProvidedIntents().get(0).getDescription()); + + ExtensionType javaImplType = implTypesTable.get(javaImpl); + assertNull(javaImplType.getAlwaysProvidedIntents().get(0).getDescription()); + assertNull(javaImplType.getMayProvidedIntents().get(0).getDescription()); + + List intents = new ArrayList(intentTable.values()); + + for (Intent intent : intents) { + staxProcessor.resolve(intent, resolver); + } + + for (PolicySet policySet : policySetTable.values()) { + if (policySet.getReferencedPolicySets().isEmpty()) + staxProcessor.resolve(policySet, resolver); + } + + for (PolicySet policySet : policySetTable.values()) { + if (!policySet.getReferencedPolicySets().isEmpty()) + staxProcessor.resolve(policySet, resolver); + } + + for (ExtensionType bindingType : bindingTypesTable.values()) { + staxProcessor.resolve(bindingType, resolver); + } + + for (ExtensionType implType : implTypesTable.values()) { + staxProcessor.resolve(implType, resolver); + } + + //testing if policy intents have been linked have property been linked up + assertNotNull(profileIntent.getRequiredIntents().get(0).getDescription()); + assertNotNull(qualifiedIntent.getQualifiableIntent().getDescription()); + assertEquals(secureReliablePolicySet.getProvidedIntents().get(1).getName(), integrity); + assertNotNull(secureReliablePolicySet.getProvidedIntents().get(1).getDescription()); + + //testing if policysets have been properly linked up with intents + assertFalse(secureMessagingPolicySet.isUnresolved()); + assertTrue(isRealizedBy(secureMessagingPolicySet, intentTable.get(confidentiality))); + assertTrue(isRealizedBy(secureMessagingPolicySet, intentTable.get(confidentiality_transport))); + + //testing if intent maps have been properly mapped to policies + assertFalse(securityPolicySet.isUnresolved()); + assertTrue(isRealizedBy(securityPolicySet, intentTable.get(confidentiality))); + assertTrue(isRealizedBy(securityPolicySet, intentTable.get(confidentiality_message))); + + //testing for inclusion of referred policysets + assertFalse(basicAuthMsgProtSecurityPolicySet.getPolicies().isEmpty()); + assertFalse(basicAuthMsgProtSecurityPolicySet.getIntentMaps().isEmpty()); + assertTrue(isRealizedBy(basicAuthMsgProtSecurityPolicySet, intentTable.get(confidentiality_transport))); + + assertNotNull(wsBindingType.getAlwaysProvidedIntents().get(0).getDescription()); + assertNotNull(wsBindingType.getMayProvidedIntents().get(0).getDescription()); + + assertNotNull(javaImplType.getAlwaysProvidedIntents().get(0).getDescription()); + assertNotNull(javaImplType.getMayProvidedIntents().get(0).getDescription()); + } + + private boolean isRealizedBy(PolicySet policySet, Intent intent) { + if (intent.getName().getLocalPart().indexOf('.') == -1) { + return policySet.getProvidedIntents().contains(intent); + } + for (IntentMap map : policySet.getIntentMaps()) { + for (Qualifier q : map.getQualifiers()) { + if (q.getIntent().equals(intent)) { + return true; + } + } + } + return false; + } +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/TestPolicyProcessor.java b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/TestPolicyProcessor.java new file mode 100644 index 0000000000..6887cd1b42 --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/java/org/apache/tuscany/sca/policy/xml/TestPolicyProcessor.java @@ -0,0 +1,82 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.tuscany.sca.policy.xml; + +import javax.xml.namespace.QName; +import javax.xml.stream.XMLStreamException; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.XMLStreamWriter; + +import org.apache.tuscany.sca.contribution.processor.ContributionReadException; +import org.apache.tuscany.sca.contribution.processor.ContributionResolveException; +import org.apache.tuscany.sca.contribution.processor.ContributionWriteException; +import org.apache.tuscany.sca.contribution.processor.StAXArtifactProcessor; +import org.apache.tuscany.sca.contribution.resolver.ModelResolver; +import org.apache.tuscany.sca.policy.PolicyExpression; + +/** + * + * @version $Rev$ $Date$ + */ +public class TestPolicyProcessor implements StAXArtifactProcessor { + + public QName getArtifactType() { + return new QName("http://schemas.xmlsoap.org/ws/2004/09/policy", "PolicyAttachment"); + } + + public PolicyExpression read(XMLStreamReader arg0) throws ContributionReadException, XMLStreamException { + return new MockPolicyImplOne(); + } + + public void write(PolicyExpression arg0, XMLStreamWriter arg1) throws ContributionWriteException, XMLStreamException { + } + + public Class getModelType() { + // TODO Auto-generated method stub + return PolicyExpression.class; + } + + public void resolve(PolicyExpression arg0, ModelResolver arg1) throws ContributionResolveException { + + } + + public class MockPolicyImplOne implements PolicyExpression { + public T getPolicy() { + return null; + } + + public void setName(QName name) { + } + + public void setPolicy(T policy) { + } + + public QName getName() { + return new QName("http://schemas.xmlsoap.org/ws/2004/09/policy", "PolicyAttachment"); + } + + public boolean isUnresolved() { + return false; + } + + public void setUnresolved(boolean unresolved) { + } + + } +} diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/resources/org/apache/tuscany/sca/policy/xml/Calculator.composite b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/resources/org/apache/tuscany/sca/policy/xml/Calculator.composite new file mode 100644 index 0000000000..3ade69523c --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/resources/org/apache/tuscany/sca/policy/xml/Calculator.composite @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/resources/org/apache/tuscany/sca/policy/xml/test_definitions.xml b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/resources/org/apache/tuscany/sca/policy/xml/test_definitions.xml new file mode 100644 index 0000000000..911833550f --- /dev/null +++ b/sandbox/ant/sca/branches/2.0-M2/modules/policy-xml/src/test/resources/org/apache/tuscany/sca/policy/xml/test_definitions.xml @@ -0,0 +1,203 @@ + + + + + + + + + + + + Test Intent + + + + + + Protect messages from unauthorized reading or modification + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ... + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ... + + + + + ... + + + + + + + + + + + sp:X509v3 + + + + + + + + + + + + + + + + + + Protect messages from unauthorized reading or modification + + + + + + Protect messages from unauthorized reading or modification + + + + + + + Communitcation thro this binding must prevent + unauthorized users from reading the messages. + + + + + + + + Communitcation thro this binding must prevent + unauthorized modification of the messages. + + + + + + Communitcation thro this binding required + Authentication. + + + + + + All messages to and from this implementation must be logged + + + + + + Need to figure out some description for this + + + + \ No newline at end of file -- cgit v1.2.3