Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * 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.assembly.xml;
 
 import static javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI;
 import static javax.xml.XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
 import static javax.xml.stream.XMLStreamConstants.CDATA;
 import static javax.xml.stream.XMLStreamConstants.CHARACTERS;
 import static javax.xml.stream.XMLStreamConstants.COMMENT;
 import static javax.xml.stream.XMLStreamConstants.END_ELEMENT;
 import static javax.xml.stream.XMLStreamConstants.START_ELEMENT;
 import static org.apache.tuscany.sca.assembly.xml.Constants.ELEMENT;
 import static org.apache.tuscany.sca.assembly.xml.Constants.MANY;
 import static org.apache.tuscany.sca.assembly.xml.Constants.MULTIPLICITY;
 import static org.apache.tuscany.sca.assembly.xml.Constants.MUST_SUPPLY;
 import static org.apache.tuscany.sca.assembly.xml.Constants.NAME;
 import static org.apache.tuscany.sca.assembly.xml.Constants.ONE_N;
 import static org.apache.tuscany.sca.assembly.xml.Constants.ONE_ONE;
 import static org.apache.tuscany.sca.assembly.xml.Constants.PROPERTY;
 import static org.apache.tuscany.sca.assembly.xml.Constants.PROPERTY_QNAME;
 import static org.apache.tuscany.sca.assembly.xml.Constants.SCA11_NS;
 import static org.apache.tuscany.sca.assembly.xml.Constants.TARGET;
 import static org.apache.tuscany.sca.assembly.xml.Constants.TYPE;
 import static org.apache.tuscany.sca.assembly.xml.Constants.VALUE;
 import static org.apache.tuscany.sca.assembly.xml.Constants.VALUE_QNAME;
 import static org.apache.tuscany.sca.assembly.xml.Constants.ZERO_N;
 import static org.apache.tuscany.sca.assembly.xml.Constants.ZERO_ONE;
 
 import java.util.List;
 
 
A base class with utility methods for the other artifact processors in this module.

Version:
$Rev: 979205 $ $Date: 2010-07-26 10:06:29 +0100 (Mon, 26 Jul 2010) $
 
 abstract class BaseAssemblyProcessor extends BaseStAXArtifactProcessor {
    protected AssemblyFactory assemblyFactory;
    protected PolicyFactory policyFactory;
Constructs a new BaseArtifactProcessor.

Parameters:
assemblyFactory
policyFactory
    @SuppressWarnings("unchecked")
    protected BaseAssemblyProcessor(AssemblyFactory assemblyFactory,
                                    PolicyFactory policyFactory,
                                    DocumentBuilderFactory documentBuilderFactory,
                                    StAXArtifactProcessor extensionProcessor) {
        this. = assemblyFactory;
        this. = policyFactory;
        this. = documentBuilderFactory;
        this. = (StAXArtifactProcessor<Object>)extensionProcessor;
        this. = new PolicySubjectProcessor(policyFactory);
    }

    

Parameters:
modelFactories
staxProcessor
monitor
    protected BaseAssemblyProcessor(FactoryExtensionPoint modelFactories,
                                    StAXArtifactProcessor staxProcessor) {
        this. = modelFactories.getFactory(AssemblyFactory.class);
        this. = modelFactories.getFactory(PolicyFactory.class);
        this. = modelFactories.getFactory(DocumentBuilderFactory.class);
        this. = (StAXArtifactProcessor<Object>)staxProcessor;
    }

    
Marshals warnings into the monitor

Parameters:
message
model
messageParameters
    protected void warning(Monitor monitorString messageObject modelObject... messageParameters) {
        if (monitor != null) {
            Problem problem =
                monitor.createProblem(this.getClass().getName(),
                                      .,
                                      .,
                                      model,
                                      message,
                                      (Object[])messageParameters);
            monitor.problem(problem);
        }
    }

    
Marshals errors into the monitor

Parameters:
problems
message
model
    protected void error(Monitor monitorString messageObject modelObject... messageParameters) {
        if (monitor != null) {
            Problem problem =
                monitor.createProblem(this.getClass().getName(),
                                      .,
                                      .,
                                      model,
                                      message,
                                      (Object[])messageParameters);
            monitor.problem(problem);
        }
    }

    
Marshals exceptions into the monitor

Parameters:
problems
message
model
    protected void error(Monitor monitorString messageObject modelException ex) {
        if (monitor != null) {
            Problem problem =
                monitor.createProblem(this.getClass().getName(),
                                      .,
                                      .,
                                      model,
                                      message,
                                      ex);
            monitor.problem(problem);
        }
    }

    
Start an element.

Parameters:
writer
name
attrs
Throws:
javax.xml.stream.XMLStreamException
    protected void writeStart(XMLStreamWriter writerString nameXAttr... attrsthrows XMLStreamException {
        super.writeStart(writernameattrs);
    }

    
Start a document.

Parameters:
writer
Throws:
javax.xml.stream.XMLStreamException
    protected void writeStartDocument(XMLStreamWriter writerString nameXAttr... attrsthrows XMLStreamException {
        super.writeStartDocument(writernameattrs);
    }

    
Read list of reference targets

Parameters:
reference
reader
    protected void readTargets(Reference referenceXMLStreamReader reader) {
        String value = getString(reader);
        ComponentService target = null;
        if (value != null) {
            for (StringTokenizer tokens = new StringTokenizer(value); tokens.hasMoreTokens();) {
                target = .createComponentService();
                target.setUnresolved(true);
                target.setName(tokens.nextToken());
                reference.getTargets().add(target);
            }
        }
    }

    
Write a list of targets into an attribute

Parameters:
reference
Returns:
    protected XAttr writeTargets(Reference reference) {
        List<Stringtargets = new ArrayList<String>();
        for (Service target : reference.getTargets()) {
            targets.add(target.getName());
        }
        return new XAttr(targets);
    }

    
Read a multiplicity attribute.

Parameters:
reference
reader
    protected void readMultiplicity(AbstractReference referenceXMLStreamReader reader) {
        String value = reader.getAttributeValue(null);
        if (.equals(value)) {
            reference.setMultiplicity(.);
        } else if (.equals(value)) {
            reference.setMultiplicity(.);
        } else if (.equals(value)) {
            reference.setMultiplicity(.);
        } else if (.equals(value)) {
            reference.setMultiplicity(.);
        }
    }
    protected XAttr writeMultiplicity(AbstractReference reference) {
        Multiplicity multiplicity = reference.getMultiplicity();
        if (multiplicity != null) {
            String value = null;
            if (..equals(multiplicity)) {
                value = ;
            } else if (..equals(multiplicity)) {
                value = ;
            } else if (..equals(multiplicity)) {
                value = ;
            } else if (..equals(multiplicity)) {
                value = ;
                return null;
            }
            return new XAttr(value);
        }
        return null;
    }


    
Reads an abstract property element.

    protected void readAbstractProperty(AbstractProperty propertyXMLStreamReader readerProcessorContext contextthrows XMLStreamException,
        ContributionReadException {
        property.setName(getString(reader));
        property.setMany(getBoolean(reader));
        property.setMustSupply(getBoolean(reader));
        property.setXSDElement(getQName(reader));
        property.setXSDType(getQName(reader));
        // MJE added 14/05/2009 - check for both @element and @type being present - disallowed by OASIS Assembly spec
        ifproperty.getXSDElement() != null && property.getXSDType() != null ) {
        	ContributionReadException ce = new ContributionReadException("[ASM40010,ASM60040] Error: property has both @type and @element attribute values - " + 
        			                                                     property.getName());
        	error(context.getMonitor(), "ContributionReadException"propertyce);
        } // end if
    }

    
Resolve an implementation.

Parameters:
implementation
resolver
context
Returns:
Throws:
org.apache.tuscany.sca.contribution.processor.ContributionResolveException
    protected Implementation resolveImplementation(Implementation implementationModelResolver resolverProcessorContext context)
        throws ContributionResolveException {
        if (implementation != null) {
            if (implementation.isUnresolved()) {
                implementation = resolver.resolveModel(Implementation.classimplementationcontext);
                // Lazily resolve implementations
                if (implementation.isUnresolved()) {
                    .resolve(implementationresolvercontext);
                    if (!implementation.isUnresolved()) {
                        resolver.addModel(implementationcontext);
                    }
                }
            }
        }
        return implementation;
    }

    
Resolve interface, callback interface and bindings on a list of contracts.

Parameters:
contracts the list of contracts
resolver the resolver to use to resolve models
context TODO
    protected <C extends Contractvoid resolveContracts(List<C> contractsModelResolver resolverProcessorContext context)
        throws ContributionResolveException {
        resolveContracts(nullcontractsresolvercontext);
    }

    
Resolve interface, callback interface and bindings on a list of contracts.

Parameters:
parent element for the contracts
contracts the list of contracts
resolver the resolver to use to resolve models
context TODO
    protected <C extends Contractvoid resolveContracts(Base parentList<C> contractsModelResolver resolverProcessorContext context)
        throws ContributionResolveException {
        String parentName =
            (parent instanceof Composite) ? ((Composite)parent).getName().toString() : (parent instanceof Component)
                ? ((Component)parent).getName() : "UNKNOWN";
        for (Contract contract : contracts) {
            // Resolve the interface contract
            InterfaceContract interfaceContract = contract.getInterfaceContract();
            if (interfaceContract != null) {
                .resolve(interfaceContractresolvercontext);
            }
            // Resolve bindings
            for (int i = 0, n = contract.getBindings().size(); i < ni++) {
                Binding binding = contract.getBindings().get(i);
                .resolve(bindingresolvercontext);
            }
            // Resolve callback bindings
            if (contract.getCallback() != null) {
                for (int i = 0, n = contract.getCallback().getBindings().size(); i < ni++) {
                    Binding binding = contract.getCallback().getBindings().get(i);
                    .resolve(bindingresolvercontext);
                }
            }
        }
    }

    
Resolve interface and callback interface on a list of abstract contracts.

Parameters:
contracts the list of contracts
resolver the resolver to use to resolve models
context TODO
    protected <C extends AbstractContractvoid resolveAbstractContracts(List<C> contractsModelResolver resolverProcessorContext context)
        throws ContributionResolveException {
        for (AbstractContract contract : contracts) {
            // Resolve the interface contract
            InterfaceContract interfaceContract = contract.getInterfaceContract();
            if (interfaceContract != null) {
                .resolve(interfaceContractresolvercontext);
            }
        }
    }

    
    protected Document readPropertyValue(QName elementQName typeboolean isManyXMLStreamReader readerProcessorContext contextthrows XMLStreamException,
        ContributionReadException {
        Document document;
        try {
            if ( == null) {
                 = DocumentBuilderFactory.newInstance();
                .setNamespaceAware(true);
            }
            document = .newDocumentBuilder().newDocument();
        } catch (ParserConfigurationException e) {
            ContributionReadException ce = new ContributionReadException(e);
            error(context.getMonitor(), "ContributionReadException"ce);
            throw ce;
        }
        // Collect the property values as <value> elements under the <property>
        Element root = document.createElementNS("sca:" + );
        String nameAttr = getString(reader);
        if (nameAttr != null) {
            root.setAttributeNS("sca:" + nameAttr);
        }
        declareNamespace(root"sca");
        if (type != null) {
            org.w3c.dom.Attr xsi = document.createAttributeNS("xmlns:xsi");
            xsi.setValue();
            root.setAttributeNodeNS(xsi);
            String prefix = type.getPrefix();
            if (prefix == null || prefix.length() == 0) {
                prefix = "ns";
            }
            declareNamespace(rootprefixtype.getNamespaceURI());
            org.w3c.dom.Attr xsiType = document.createAttributeNS("xsi:type");
            xsiType.setValue(prefix + ":" + type.getLocalPart());
            root.setAttributeNodeNS(xsiType);
        }
        document.appendChild(root);
        // Start to parse the property
        QName name = reader.getName(); // Should be sca:property
        // SCA 1.1 supports the @value for simple types
        String valueAttr = getString(reader);
        if (valueAttr != null) {
            Element valueElement = document.createElementNS();
            root.appendChild(valueElement);
            valueElement.setTextContent(valueAttr);
        }
        boolean gotOneValue = false;
        boolean isTextForProperty = true;
        StringBuffer text = new StringBuffer();
        int event = reader.getEventType();
        while (true) {
            switch (event) {
                case :
                    name = reader.getName();
                    if (.equals(name)) {
                        isTextForProperty = true;
                        break;
                    }
                    isTextForProperty = false;
                    
                    // CONFORMANCE: ASM50033
                    // A property <value/> subelement MUST NOT be used when the @value attribute is used 
                    // to specify the value for that property.
                    if (valueAttr != null) {
                        error(context.getMonitor(), "ASM50033: value attribute exists for the property element"namename);
                    }
                    // Read <value>
                    if (.equals(name)) {
                    	if (gotOneValue && !isMany) {
                    	    // TODO: TUSCANY-3231 this should be error not warning but that breaks OASIS tests
                    	    // [rfeng] We should not issue warning here as the component property many inherit @many from the componentType property
                    	    // warning(context.getMonitor(), "ASM50032: multiple value elements for single-valued property", name, name);
                    	}
                        loadElement(readerroot);
                        gotOneValue = true;
                    } else {
                        // Global elements
                        loadElement(readerroot);
                    }
                    break;
                case .:
                case .:
                    if (isTextForProperty) {
                        text.append(reader.getText());
                    }
                    break;
                case :
                    name = reader.getName();
                    if (.equals(name)) {
                        
                        if (root.getChildNodes().getLength() == 0) {
                            // Add an text as an <value>
                            if (isTextForProperty){
                                if (text.length() > 0) {
                                    Element valueElement = document.createElementNS();
                                    root.appendChild(valueElement);
                                    valueElement.setTextContent(text.toString());
                                }
                            }
                        }
                        return document;
                    }
                    break;
            }
            if (reader.hasNext()) {
                event = reader.next();
            } else {
                break;
            }
        }
        return document;
    }

    
Create a DOM element

Parameters:
document
name
Returns:
    private Element createElement(Document documentQName name) {
        String prefix = name.getPrefix();
        String qname =
            (prefix != null && prefix.length() > 0) ? prefix + ":" + name.getLocalPart() : name.getLocalPart();
        return document.createElementNS(name.getNamespaceURI(), qname);
    }

    
Declare a namespace.

Parameters:
element
prefix
ns
    private void declareNamespace(Element elementString prefixString ns) {
        if (ns == null) {
            ns = "";
        }
        if (prefix == null) {
            prefix = "";
        }
        String qname = null;
        if ("".equals(prefix)) {
            qname = "xmlns";
        } else {
            qname = "xmlns:" + prefix;
        }
        Node node = element;
        boolean declared = false;
        while (node != null && node.getNodeType() == .) {
            NamedNodeMap attrs = node.getAttributes();
            if (attrs == null) {
                break;
            }
            Node attr = attrs.getNamedItem(qname);
            if (attr != null) {
                declared = ns.equals(attr.getNodeValue());
                break;
            }
            node = node.getParentNode();
        }
        if (!declared) {
            org.w3c.dom.Attr attr = element.getOwnerDocument().createAttributeNS(qname);
            attr.setValue(ns);
            element.setAttributeNodeNS(attr);
        }
    }

    
Load a property value specification from an StAX stream into a DOM Document. Only elements, text and attributes are processed; all comments and other whitespace are ignored.

Parameters:
reader the stream to read from
root the DOM node to load
Throws:
javax.xml.stream.XMLStreamException
    private void loadElement(XMLStreamReader readerElement rootthrows XMLStreamException {
        Document document = root.getOwnerDocument();
        Node current = root;
        while (true) {
            switch (reader.getEventType()) {
                case :
                    QName name = reader.getName();
                    Element child = createElement(documentname);
                    // push the new element and make it the current one
                    current.appendChild(child);
                    current = child;
                    int count = reader.getNamespaceCount();
                    for (int i = 0; i < counti++) {
                        String prefix = reader.getNamespacePrefix(i);
                        String ns = reader.getNamespaceURI(i);
                        declareNamespace(childprefixns);
                    }
                    if (!"".equals(name.getNamespaceURI())) {
                        declareNamespace(childname.getPrefix(), name.getNamespaceURI());
                    }
                    // add the attributes for this element
                    count = reader.getAttributeCount();
                    for (int i = 0; i < counti++) {
                        String ns = reader.getAttributeNamespace(i);
                        String prefix = reader.getAttributePrefix(i);
                        String qname = reader.getAttributeLocalName(i);
                        String value = reader.getAttributeValue(i);
                        if (prefix != null && prefix.length() != 0) {
                            qname = prefix + ":" + qname;
                        }
                        child.setAttributeNS(nsqnamevalue);
                        if (ns != null) {
                            declareNamespace(childprefixns);
                        }
                    }
                    break;
                case :
                    current.appendChild(document.createCDATASection(reader.getText()));
                    break;
                case :
                    current.appendChild(document.createTextNode(reader.getText()));
                    break;
                case :
                    current.appendChild(document.createComment(reader.getText()));
                    break;
                case :
                    // pop the element off the stack
                    current = current.getParentNode();
                    // if we are back at the root then we are done
                    if (current == root) {
                        return;
                    }
            }
            if (reader.hasNext()) {
                reader.next();
            } else {
                return;
            }
        }
    }

    

Parameters:
reader
elementName
extensionAttributeProcessor
context TODO
estensibleElement
Throws:
org.apache.tuscany.sca.contribution.processor.ContributionReadException
javax.xml.stream.XMLStreamException
    protected void readExtendedAttributes(XMLStreamReader reader,
                                          QName elementName,
                                          Extensible extensible,
                                          StAXAttributeProcessor extensionAttributeProcessor,
                                          ProcessorContext contextthrows ContributionReadException,
        XMLStreamException {
        super.readExtendedAttributes(readerextensibleextensionAttributeProcessorcontext);
    }
    /*protected void validatePolicySets(PolicySubject policySetAttachPoint) 
                                                            throws ContributionResolveException {
        validatePolicySets(policySetAttachPoint, policySetAttachPoint.getApplicablePolicySets());
    }
     
    
    protected void validatePolicySets(PolicySubject policySetAttachPoint,
                                      List<PolicySet> applicablePolicySets) throws ContributionResolveException {
        //Since the applicablePolicySets in a policySetAttachPoint will already have the 
        //list of policysets that might ever be applicable to this attachPoint, just check
        //if the defined policysets feature in the list of applicable policysets
        ExtensionType attachPointType = policySetAttachPoint.getType();
        for ( PolicySet definedPolicySet : policySetAttachPoint.getPolicySets() ) {
            if ( !definedPolicySet.isUnresolved() ) {
                if ( !applicablePolicySets.contains(definedPolicySet)) {
                    throw new ContributionResolveException("Policy Set '" + definedPolicySet.getName()
                                                           + "' does not apply to binding type  "
                                                           + attachPointType.getName());
                }
            } else {
                throw new ContributionResolveException("Policy Set '" + definedPolicySet.getName()
                                                       + "' is not defined in this domain  ");
                                                
            
            }
        }
    }*/
New to GrepCode? Check out our FAQ X