feat(jdk8): move files to new folder to avoid resources compiled.

This commit is contained in:
2025-09-07 15:25:52 +08:00
parent 3f0047bf6f
commit 8c35cfb1c0
17415 changed files with 217 additions and 213 deletions

View File

@@ -0,0 +1,429 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.ws.policy.PolicyConstants;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.xml.namespace.QName;
/**
* Wrapper class for possible data that each "assertion" and "assertion parameter content" policy source model node may
* have attached.
* <p/>
* This data, when stored in an 'assertion' model node, is intended to be used as input parameter when creating
* {@link com.sun.xml.internal.ws.policy.PolicyAssertion} objects via {@link com.sun.xml.internal.ws.policy.spi.PolicyAssertionCreator}
* implementations.
*
* @author Marek Potociar (marek.potociar@sun.com)
* @author Fabian Ritzmann
*/
public final class AssertionData implements Cloneable, Serializable {
private static final long serialVersionUID = 4416256070795526315L;
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(AssertionData.class);
private final QName name;
private final String value;
private final Map<QName, String> attributes;
private ModelNode.Type type;
private boolean optional;
private boolean ignorable;
/**
* Constructs assertion data wrapper instance for an assertion that does not
* contain any value nor any attributes.
*
* @param name the FQN of the assertion
*
* @throws IllegalArgumentException in case the {@code type} parameter is not
* {@link ModelNode.Type#ASSERTION ASSERTION} or
* {@link ModelNode.Type#ASSERTION_PARAMETER_NODE ASSERTION_PARAMETER_NODE}
*/
public static AssertionData createAssertionData(final QName name) throws IllegalArgumentException {
return new AssertionData(name, null, null, ModelNode.Type.ASSERTION, false, false);
}
/**
* Constructs assertion data wrapper instance for an assertion parameter that
* does not contain any value nor any attributes.
*
* @param name the FQN of the assertion parameter
*
* @throws IllegalArgumentException in case the {@code type} parameter is not
* {@link ModelNode.Type#ASSERTION ASSERTION} or
* {@link ModelNode.Type#ASSERTION_PARAMETER_NODE ASSERTION_PARAMETER_NODE}
*/
public static AssertionData createAssertionParameterData(final QName name) throws IllegalArgumentException {
return new AssertionData(name, null, null, ModelNode.Type.ASSERTION_PARAMETER_NODE, false, false);
}
/**
* Constructs assertion data wrapper instance for an assertion that does
* contain a value or attributes.
*
* @param name the FQN of the assertion
* @param value a {@link String} representation of model node value
* @param attributes map of model node's &lt;attribute name, attribute value&gt; pairs
* @param optional flag indicating whether the assertion is optional or not
* @param ignorable flag indicating whether the assertion is ignorable or not
*
* @throws IllegalArgumentException in case the {@code type} parameter is not
* {@link ModelNode.Type#ASSERTION ASSERTION} or
* {@link ModelNode.Type#ASSERTION_PARAMETER_NODE ASSERTION_PARAMETER_NODE}
*/
public static AssertionData createAssertionData(final QName name, final String value, final Map<QName, String> attributes, boolean optional, boolean ignorable) throws IllegalArgumentException {
return new AssertionData(name, value, attributes, ModelNode.Type.ASSERTION, optional, ignorable);
}
/**
* Constructs assertion data wrapper instance for an assertion parameter that
* contains a value or attributes
*
* @param name the FQN of the assertion parameter
* @param value a {@link String} representation of model node value
* @param attributes map of model node's &lt;attribute name, attribute value&gt; pairs
*
* @throws IllegalArgumentException in case the {@code type} parameter is not
* {@link ModelNode.Type#ASSERTION ASSERTION} or
* {@link ModelNode.Type#ASSERTION_PARAMETER_NODE ASSERTION_PARAMETER_NODE}
*/
public static AssertionData createAssertionParameterData(final QName name, final String value, final Map<QName, String> attributes) throws IllegalArgumentException {
return new AssertionData(name, value, attributes, ModelNode.Type.ASSERTION_PARAMETER_NODE, false, false);
}
/**
* Constructs assertion data wrapper instance for an assertion or assertion parameter that contains a value or
* some attributes. Whether the data wrapper is constructed for assertion or assertion parameter node is distinguished by
* the supplied {@code type} parameter.
*
* @param name the FQN of the assertion or assertion parameter
* @param value a {@link String} representation of model node value
* @param attributes map of model node's &lt;attribute name, attribute value&gt; pairs
* @param type specifies whether the data will belong to the assertion or assertion parameter node. This is
* a workaround solution that allows us to transfer this information about the owner node to
* a policy assertion instance factory without actualy having to touch the {@link PolicyAssertionCreator}
* interface and protected {@link PolicyAssertion} constructors.
*
* @throws IllegalArgumentException in case the {@code type} parameter is not
* {@link ModelNode.Type#ASSERTION ASSERTION} or
* {@link ModelNode.Type#ASSERTION_PARAMETER_NODE ASSERTION_PARAMETER_NODE}
*/
AssertionData(QName name, String value, Map<QName, String> attributes, ModelNode.Type type, boolean optional, boolean ignorable) throws IllegalArgumentException {
this.name = name;
this.value = value;
this.optional = optional;
this.ignorable = ignorable;
this.attributes = new HashMap<QName, String>();
if (attributes != null && !attributes.isEmpty()) {
this.attributes.putAll(attributes);
}
setModelNodeType(type);
}
private void setModelNodeType(final ModelNode.Type type) throws IllegalArgumentException {
if (type == ModelNode.Type.ASSERTION || type == ModelNode.Type.ASSERTION_PARAMETER_NODE) {
this.type = type;
} else {
throw LOGGER.logSevereException(new IllegalArgumentException(
LocalizationMessages.WSP_0074_CANNOT_CREATE_ASSERTION_BAD_TYPE(type, ModelNode.Type.ASSERTION, ModelNode.Type.ASSERTION_PARAMETER_NODE)));
}
}
/**
* Copy constructor.
*
* @param data The instance that is to be copied.
*/
AssertionData(final AssertionData data) {
this.name = data.name;
this.value = data.value;
this.attributes = new HashMap<QName, String>();
if (!data.attributes.isEmpty()) {
this.attributes.putAll(data.attributes);
}
this.type = data.type;
}
@Override
protected AssertionData clone() throws CloneNotSupportedException {
return (AssertionData) super.clone();
}
/**
* Returns true if the given attribute exists, false otherwise.
*
* @param name The name of the attribute. Must not be null.
* @return True if the given attribute exists, false otherwise.
*/
public boolean containsAttribute(final QName name) {
synchronized (attributes) {
return attributes.containsKey(name);
}
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof AssertionData)) {
return false;
}
boolean result = true;
final AssertionData that = (AssertionData) obj;
result = result && this.name.equals(that.name);
result = result && ((this.value == null) ? that.value == null : this.value.equals(that.value));
synchronized (attributes) {
result = result && this.attributes.equals(that.attributes);
}
return result;
}
/**
* Returns the value of the given attribute. Returns null if the attribute
* does not exist.
*
* @param name The name of the attribute. Must not be null.
* @return The value of the given attribute. Returns null if the attribute
* does not exist.
*/
public String getAttributeValue(final QName name) {
synchronized (attributes) {
return attributes.get(name);
}
}
/**
* Returns the disconnected map of attributes attached to the assertion.
* <p/>
* 'Disconnected' means, that the result of this method will not be synchronized with any consequent assertion's attribute modification. It is
* also important to notice that a manipulation with returned set of attributes will not have any effect on the actual assertion's
* attributes.
*
* @return disconnected map of attributes attached to the assertion.
*/
public Map<QName, String> getAttributes() {
synchronized (attributes) {
return new HashMap<QName, String>(attributes);
}
}
/**
* Returns the disconnected set of attributes attached to the assertion. Each attribute is represented as a single
* {@code Map.Entry<attributeName, attributeValue>} element.
* <p/>
* 'Disconnected' means, that the result of this method will not be synchronized with any consequent assertion's attribute modification. It is
* also important to notice that a manipulation with returned set of attributes will not have any effect on the actual assertion's
* attributes.
*
* @return disconnected set of attributes attached to the assertion.
*/
public Set<Map.Entry<QName, String>> getAttributesSet() {
synchronized (attributes) {
return new HashSet<Map.Entry<QName, String>>(attributes.entrySet());
}
}
/**
* Returns the name of the assertion.
*
* @return assertion's name
*/
public QName getName() {
return name;
}
/**
* Returns the value of the assertion.
*
* @return assertion's value
*/
public String getValue() {
return value;
}
/**
* An {@code Object.hashCode()} method override.
*/
@Override
public int hashCode() {
int result = 17;
result = 37 * result + this.name.hashCode();
result = 37 * result + ((this.value == null) ? 0 : this.value.hashCode());
synchronized (attributes) {
result = 37 * result + this.attributes.hashCode();
}
return result;
}
/**
* Method specifies whether the assertion data contain proprietary visibility element set to "private" value.
*
* @return {@code 'true'} if the attribute is present and set properly (i.e. the node containing this assertion data instance should
* not be marshaled into generated WSDL documents). Returns {@code false} otherwise.
*/
public boolean isPrivateAttributeSet() {
return PolicyConstants.VISIBILITY_VALUE_PRIVATE.equals(getAttributeValue(PolicyConstants.VISIBILITY_ATTRIBUTE));
}
/**
* Removes the given attribute from the assertion data.
*
* @param name The name of the attribute. Must not be null
* @return The value of the removed attribute.
*/
public String removeAttribute(final QName name) {
synchronized (attributes) {
return attributes.remove(name);
}
}
/**
* Adds or overwrites an attribute.
*
* @param name The name of the attribute.
* @param value The value of the attribute.
*/
public void setAttribute(final QName name, final String value) {
synchronized (attributes) {
attributes.put(name, value);
}
}
/**
* Sets the optional attribute.
*
* @param value The value of the optional attribute.
*/
public void setOptionalAttribute(final boolean value) {
optional = value;
}
/**
* Tests if the optional attribute is set.
*
* @return True if optional is set and is true. False otherwise.
*/
public boolean isOptionalAttributeSet() {
return optional;
}
/**
* Sets the ignorable attribute.
*
* @param value The value of the ignorable attribute.
*/
public void setIgnorableAttribute(final boolean value) {
ignorable = value;
}
/**
* Tests if the ignorable attribute is set.
*
* @return True if ignorable is set and is true. False otherwise.
*/
public boolean isIgnorableAttributeSet() {
return ignorable;
}
@Override
public String toString() {
return toString(0, new StringBuffer()).toString();
}
/**
* A helper method that appends indented string representation of this instance to the input string buffer.
*
* @param indentLevel indentation level to be used.
* @param buffer buffer to be used for appending string representation of this instance
* @return modified buffer containing new string representation of the instance
*/
public StringBuffer toString(final int indentLevel, final StringBuffer buffer) {
final String indent = PolicyUtils.Text.createIndent(indentLevel);
final String innerIndent = PolicyUtils.Text.createIndent(indentLevel + 1);
final String innerDoubleIndent = PolicyUtils.Text.createIndent(indentLevel + 2);
buffer.append(indent);
if (type == ModelNode.Type.ASSERTION) {
buffer.append("assertion data {");
} else {
buffer.append("assertion parameter data {");
}
buffer.append(PolicyUtils.Text.NEW_LINE);
buffer.append(innerIndent).append("namespace = '").append(name.getNamespaceURI()).append('\'').append(PolicyUtils.Text.NEW_LINE);
buffer.append(innerIndent).append("prefix = '").append(name.getPrefix()).append('\'').append(PolicyUtils.Text.NEW_LINE);
buffer.append(innerIndent).append("local name = '").append(name.getLocalPart()).append('\'').append(PolicyUtils.Text.NEW_LINE);
buffer.append(innerIndent).append("value = '").append(value).append('\'').append(PolicyUtils.Text.NEW_LINE);
buffer.append(innerIndent).append("optional = '").append(optional).append('\'').append(PolicyUtils.Text.NEW_LINE);
buffer.append(innerIndent).append("ignorable = '").append(ignorable).append('\'').append(PolicyUtils.Text.NEW_LINE);
synchronized (attributes) {
if (attributes.isEmpty()) {
buffer.append(innerIndent).append("no attributes");
} else {
buffer.append(innerIndent).append("attributes {").append(PolicyUtils.Text.NEW_LINE);
for(Map.Entry<QName, String> entry : attributes.entrySet()) {
final QName aName = entry.getKey();
buffer.append(innerDoubleIndent).append("name = '").append(aName.getNamespaceURI()).append(':').append(aName.getLocalPart());
buffer.append("', value = '").append(entry.getValue()).append('\'').append(PolicyUtils.Text.NEW_LINE);
}
buffer.append(innerIndent).append('}');
}
}
buffer.append(PolicyUtils.Text.NEW_LINE).append(indent).append('}');
return buffer;
}
public ModelNode.Type getNodeType() {
return type;
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.ws.policy.AssertionSet;
import com.sun.xml.internal.ws.policy.NestedPolicy;
import com.sun.xml.internal.ws.policy.Policy;
import com.sun.xml.internal.ws.policy.PolicyAssertion;
import com.sun.xml.internal.ws.policy.PolicyException;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
/**
* Create a compact WS-Policy infoset. ExactlyOne and All elements are omitted
* where possible.
*
* @author Fabian Ritzmann
*/
class CompactModelGenerator extends PolicyModelGenerator {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(CompactModelGenerator.class);
private final PolicySourceModelCreator sourceModelCreator;
CompactModelGenerator(PolicySourceModelCreator sourceModelCreator) {
this.sourceModelCreator = sourceModelCreator;
}
@Override
public PolicySourceModel translate(final Policy policy) throws PolicyException {
LOGGER.entering(policy);
PolicySourceModel model = null;
if (policy == null) {
LOGGER.fine(LocalizationMessages.WSP_0047_POLICY_IS_NULL_RETURNING());
} else {
model = this.sourceModelCreator.create(policy);
ModelNode rootNode = model.getRootNode();
final int numberOfAssertionSets = policy.getNumberOfAssertionSets();
if (numberOfAssertionSets > 1) {
rootNode = rootNode.createChildExactlyOneNode();
}
ModelNode alternativeNode = rootNode;
for (AssertionSet set : policy) {
if (numberOfAssertionSets > 1) {
alternativeNode = rootNode.createChildAllNode();
}
for (PolicyAssertion assertion : set) {
final AssertionData data = AssertionData.createAssertionData(assertion.getName(), assertion.getValue(), assertion.getAttributes(), assertion.isOptional(), assertion.isIgnorable());
final ModelNode assertionNode = alternativeNode.createChildAssertionNode(data);
if (assertion.hasNestedPolicy()) {
translate(assertionNode, assertion.getNestedPolicy());
}
if (assertion.hasParameters()) {
translate(assertionNode, assertion.getParametersIterator());
}
}
}
}
LOGGER.exiting(model);
return model;
}
@Override
protected ModelNode translate(final ModelNode parentAssertion, final NestedPolicy policy) {
final ModelNode nestedPolicyRoot = parentAssertion.createChildPolicyNode();
final AssertionSet set = policy.getAssertionSet();
translate(nestedPolicyRoot, set);
return nestedPolicyRoot;
}
}

View File

@@ -0,0 +1,70 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.ws.policy.*;
import com.sun.xml.internal.ws.policy.spi.AssertionCreationException;
import com.sun.xml.internal.ws.policy.spi.PolicyAssertionCreator;
import java.util.Collection;
/**
* Default implementation of a policy assertion creator. This implementation is used to create policy assertions in case
* no domain specific policy assertion creator is registered for the namespace of the policy assertion.
*
* This is the only PolicyAssertionCreator implementation that is allowed to break general contract, claiming that
* {@code getSupportedDomainNamespaceUri()} must not return empty String without causing PolicyAssertionCreator registration
* fail.
*
* @author Marek Potociar (marek.potociar at sun.com)
*/
class DefaultPolicyAssertionCreator implements PolicyAssertionCreator {
private static final class DefaultPolicyAssertion extends PolicyAssertion {
DefaultPolicyAssertion(AssertionData data, Collection<PolicyAssertion> assertionParameters, AssertionSet nestedAlternative) {
super (data, assertionParameters, nestedAlternative);
}
}
/**
* Creates a new instance of DefaultPolicyAssertionCreator
*/
DefaultPolicyAssertionCreator() {
// nothing to initialize
}
/**
* See {@link PolicyAssertionCreator#getSupportedDomainNamespaceURIs() method documentation in interface}
*/
public String[] getSupportedDomainNamespaceURIs() {
return null;
}
/**
* See {@link PolicyAssertionCreator#createAssertion(AssertionData, Collection, AssertionSet, PolicyAssertionCreator) method documentation in interface}
*/
public PolicyAssertion createAssertion(final AssertionData data, final Collection<PolicyAssertion> assertionParameters, final AssertionSet nestedAlternative, final PolicyAssertionCreator defaultCreator) throws AssertionCreationException {
return new DefaultPolicyAssertion(data, assertionParameters, nestedAlternative);
}
}

View File

@@ -0,0 +1,596 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import com.sun.xml.internal.ws.policy.sourcemodel.wspolicy.XmlToken;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
/**
* The general representation of a single node within a {@link com.sun.xml.internal.ws.policy.sourcemodel.PolicySourceModel} instance.
* The model node is created via factory methods of the {@link com.sun.xml.internal.ws.policy.sourcemodel.PolicySourceModel} instance.
* It may also hold {@link com.sun.xml.internal.ws.policy.sourcemodel.AssertionData} instance in case its type is {@code ModelNode.Type.ASSERTION}.
*
* @author Marek Potociar
*/
public final class ModelNode implements Iterable<ModelNode>, Cloneable {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(ModelNode.class);
/**
* Policy source model node type enumeration
*/
public static enum Type {
POLICY(XmlToken.Policy),
ALL(XmlToken.All),
EXACTLY_ONE(XmlToken.ExactlyOne),
POLICY_REFERENCE(XmlToken.PolicyReference),
ASSERTION(XmlToken.UNKNOWN),
ASSERTION_PARAMETER_NODE(XmlToken.UNKNOWN);
private XmlToken token;
Type(XmlToken token) {
this.token = token;
}
public XmlToken getXmlToken() {
return token;
}
/**
* Method checks the PSM state machine if the creation of new child of given type is plausible for a node element
* with type set to this type instance.
*
* @param childType The type.
* @return True if the type is supported, false otherwise
*/
private boolean isChildTypeSupported(final Type childType) {
switch (this) {
case POLICY:
case ALL:
case EXACTLY_ONE:
switch (childType) {
case ASSERTION_PARAMETER_NODE:
return false;
default:
return true;
}
case POLICY_REFERENCE:
return false;
case ASSERTION:
switch (childType) {
case POLICY:
case POLICY_REFERENCE:
case ASSERTION_PARAMETER_NODE:
return true;
default:
return false;
}
case ASSERTION_PARAMETER_NODE:
switch (childType) {
case ASSERTION_PARAMETER_NODE:
return true;
default:
return false;
}
default:
throw LOGGER.logSevereException(new IllegalStateException(
LocalizationMessages.WSP_0060_POLICY_ELEMENT_TYPE_UNKNOWN(this)));
}
}
}
// comon model node attributes
private LinkedList<ModelNode> children;
private Collection<ModelNode> unmodifiableViewOnContent;
private final ModelNode.Type type;
private ModelNode parentNode;
private PolicySourceModel parentModel;
// attributes used only in 'POLICY_REFERENCE' model node
private PolicyReferenceData referenceData;
private PolicySourceModel referencedModel;
// attibutes used only in 'ASSERTION' or 'ASSERTION_PARAMETER_NODE' model node
private AssertionData nodeData;
/**
* The factory method creates and initializes the POLICY model node and sets it's parent model reference to point to
* the model supplied as an input parameter. This method is intended to be used ONLY from {@link PolicySourceModel} during
* the initialization of its own internal structures.
*
* @param model policy source model to be used as a parent model of the newly created {@link ModelNode}. Must not be {@code null}
* @return POLICY model node with the parent model reference initialized to the model supplied as an input parameter
* @throws IllegalArgumentException if the {@code model} input parameter is {@code null}
*/
static ModelNode createRootPolicyNode(final PolicySourceModel model) throws IllegalArgumentException {
if (model == null) {
throw LOGGER.logSevereException(new IllegalArgumentException(LocalizationMessages.WSP_0039_POLICY_SRC_MODEL_INPUT_PARAMETER_MUST_NOT_BE_NULL()));
}
return new ModelNode(ModelNode.Type.POLICY, model);
}
private ModelNode(Type type, PolicySourceModel parentModel) {
this.type = type;
this.parentModel = parentModel;
this.children = new LinkedList<ModelNode>();
this.unmodifiableViewOnContent = Collections.unmodifiableCollection(this.children);
}
private ModelNode(Type type, PolicySourceModel parentModel, AssertionData data) {
this(type, parentModel);
this.nodeData = data;
}
private ModelNode(PolicySourceModel parentModel, PolicyReferenceData data) {
this(Type.POLICY_REFERENCE, parentModel);
this.referenceData = data;
}
private void checkCreateChildOperationSupportForType(final Type type) throws UnsupportedOperationException {
if (!this.type.isChildTypeSupported(type)) {
throw LOGGER.logSevereException(new UnsupportedOperationException(LocalizationMessages.WSP_0073_CREATE_CHILD_NODE_OPERATION_NOT_SUPPORTED(type, this.type)));
}
}
/**
* Factory method that creates new policy source model node as specified by a factory method name and input parameters.
* Each node is created with respect to its enclosing policy source model.
*
* @return A new Policy node.
*/
public ModelNode createChildPolicyNode() {
checkCreateChildOperationSupportForType(Type.POLICY);
final ModelNode node = new ModelNode(ModelNode.Type.POLICY, parentModel);
this.addChild(node);
return node;
}
/**
* Factory method that creates new policy source model node as specified by a factory method name and input parameters.
* Each node is created with respect to its enclosing policy source model.
*
* @return A new All node.
*/
public ModelNode createChildAllNode() {
checkCreateChildOperationSupportForType(Type.ALL);
final ModelNode node = new ModelNode(ModelNode.Type.ALL, parentModel);
this.addChild(node);
return node;
}
/**
* Factory method that creates new policy source model node as specified by a factory method name and input parameters.
* Each node is created with respect to its enclosing policy source model.
*
* @return A new ExactlyOne node.
*/
public ModelNode createChildExactlyOneNode() {
checkCreateChildOperationSupportForType(Type.EXACTLY_ONE);
final ModelNode node = new ModelNode(ModelNode.Type.EXACTLY_ONE, parentModel);
this.addChild(node);
return node;
}
/**
* Factory method that creates new policy source model node as specified by a factory method name and input parameters.
* Each node is created with respect to its enclosing policy source model.
*
* @return A new policy assertion node.
*/
public ModelNode createChildAssertionNode() {
checkCreateChildOperationSupportForType(Type.ASSERTION);
final ModelNode node = new ModelNode(ModelNode.Type.ASSERTION, parentModel);
this.addChild(node);
return node;
}
/**
* Factory method that creates new policy source model node as specified by a factory method name and input parameters.
* Each node is created with respect to its enclosing policy source model.
*
* @param nodeData The policy assertion data.
* @return A new policy assertion node.
*/
public ModelNode createChildAssertionNode(final AssertionData nodeData) {
checkCreateChildOperationSupportForType(Type.ASSERTION);
final ModelNode node = new ModelNode(Type.ASSERTION, parentModel, nodeData);
this.addChild(node);
return node;
}
/**
* Factory method that creates new policy source model node as specified by a factory method name and input parameters.
* Each node is created with respect to its enclosing policy source model.
*
* @return A new assertion parameter node.
*/
public ModelNode createChildAssertionParameterNode() {
checkCreateChildOperationSupportForType(Type.ASSERTION_PARAMETER_NODE);
final ModelNode node = new ModelNode(ModelNode.Type.ASSERTION_PARAMETER_NODE, parentModel);
this.addChild(node);
return node;
}
/**
* Factory method that creates new policy source model node as specified by a factory method name and input parameters.
* Each node is created with respect to its enclosing policy source model.
*
* @param nodeData The assertion parameter data.
* @return A new assertion parameter node.
*/
ModelNode createChildAssertionParameterNode(final AssertionData nodeData) {
checkCreateChildOperationSupportForType(Type.ASSERTION_PARAMETER_NODE);
final ModelNode node = new ModelNode(Type.ASSERTION_PARAMETER_NODE, parentModel, nodeData);
this.addChild(node);
return node;
}
/**
* Factory method that creates new policy source model node as specified by a factory method name and input parameters.
* Each node is created with respect to its enclosing policy source model.
*
* @param referenceData The PolicyReference data.
* @return A new PolicyReference node.
*/
ModelNode createChildPolicyReferenceNode(final PolicyReferenceData referenceData) {
checkCreateChildOperationSupportForType(Type.POLICY_REFERENCE);
final ModelNode node = new ModelNode(parentModel, referenceData);
this.parentModel.addNewPolicyReference(node);
this.addChild(node);
return node;
}
Collection<ModelNode> getChildren() {
return unmodifiableViewOnContent;
}
/**
* Sets the parent model reference on the node and its children. The method may be invoked only on the root node
* of the policy source model (or - in general - on a model node that dose not reference a parent node). Otherwise an
* exception is thrown.
*
* @param model new parent policy source model to be set.
* @throws IllegalAccessException in case this node references a parent node (i.e. is not a root node of the model).
*/
void setParentModel(final PolicySourceModel model) throws IllegalAccessException {
if (parentNode != null) {
throw LOGGER.logSevereException(new IllegalAccessException(LocalizationMessages.WSP_0049_PARENT_MODEL_CAN_NOT_BE_CHANGED()));
}
this.updateParentModelReference(model);
}
/**
* The method updates the parentModel reference on current model node instance and all of it's children
*
* @param model new policy source model reference.
*/
private void updateParentModelReference(final PolicySourceModel model) {
this.parentModel = model;
for (ModelNode child : children) {
child.updateParentModelReference(model);
}
}
/**
* Returns the parent policy source model that contains this model node.
*
* @return the parent policy source model
*/
public PolicySourceModel getParentModel() {
return parentModel;
}
/**
* Returns the type of this policy source model node.
*
* @return actual type of this policy source model node
*/
public ModelNode.Type getType() {
return type;
}
/**
* Returns the parent referenced by this policy source model node.
*
* @return current parent of this policy source model node or {@code null} if the node does not have a parent currently.
*/
public ModelNode getParentNode() {
return parentNode;
}
/**
* Returns the data for this policy source model node (if any). The model node data are expected to be not {@code null} only in
* case the type of this node is ASSERTION or ASSERTION_PARAMETER_NODE.
*
* @return the data of this policy source model node or {@code null} if the node does not have any data associated to it
* attached.
*/
public AssertionData getNodeData() {
return nodeData;
}
/**
* Returns the policy reference data for this policy source model node. The policy reference data are expected to be not {@code null} only in
* case the type of this node is POLICY_REFERENCE.
*
* @return the policy reference data for this policy source model node or {@code null} if the node does not have any policy reference data
* attached.
*/
PolicyReferenceData getPolicyReferenceData() {
return referenceData;
}
/**
* The method may be used to set or replace assertion data set for this node. If there are assertion data set already,
* those are replaced by a new reference and eventualy returned from the method.
* <p/>
* This method is supported only in case this model node instance's type is {@code ASSERTION} or {@code ASSERTION_PARAMETER_NODE}.
* If used from other node types, an exception is thrown.
*
* @param newData new assertion data to be set.
* @return old and replaced assertion data if any or {@code null} otherwise.
*
* @throws UnsupportedOperationException in case this method is called on nodes of type other than {@code ASSERTION}
* or {@code ASSERTION_PARAMETER_NODE}
*/
public AssertionData setOrReplaceNodeData(final AssertionData newData) {
if (!isDomainSpecific()) {
throw LOGGER.logSevereException(new UnsupportedOperationException(LocalizationMessages.WSP_0051_OPERATION_NOT_SUPPORTED_FOR_THIS_BUT_ASSERTION_RELATED_NODE_TYPE(type)));
}
final AssertionData oldData = this.nodeData;
this.nodeData = newData;
return oldData;
}
/**
* The method specifies whether the model node instance represents assertion related node, it means whether its type
* is 'ASSERTION' or 'ASSERTION_PARAMETER_NODE'. This is, for example, the way to determine whether the node supports
* setting a {@link AssertionData} object via {@link #setOrReplaceNodeData(AssertionData)} method or not.
*
* @return {@code true} or {@code false} according to whether the node instance represents assertion related node or not.
*/
boolean isDomainSpecific() {
return type == Type.ASSERTION || type == Type.ASSERTION_PARAMETER_NODE;
}
/**
* Appends the specified child node to the end of the children list of this node and sets it's parent to reference
* this node.
*
* @param child node to be appended to the children list of this node.
* @return {@code true} (as per the general contract of the {@code Collection.add} method).
*
* @throws NullPointerException if the specified node is {@code null}.
* @throws IllegalArgumentException if child has a parent node set already to point to some node
*/
private boolean addChild(final ModelNode child) {
children.add(child);
child.parentNode = this;
return true;
}
void setReferencedModel(final PolicySourceModel model) {
if (this.type != Type.POLICY_REFERENCE) {
throw LOGGER.logSevereException(new UnsupportedOperationException(LocalizationMessages.WSP_0050_OPERATION_NOT_SUPPORTED_FOR_THIS_BUT_POLICY_REFERENCE_NODE_TYPE(type)));
}
referencedModel = model;
}
PolicySourceModel getReferencedModel() {
return referencedModel;
}
/**
* Returns the number of child policy source model nodes. If this model node contains
* more than {@code Integer.MAX_VALUE} children, returns {@code Integer.MAX_VALUE}.
*
* @return the number of children of this node.
*/
public int childrenSize() {
return children.size();
}
/**
* Returns true if the node has at least one child node.
*
* @return true if the node has at least one child node, false otherwise.
*/
public boolean hasChildren() {
return !children.isEmpty();
}
/**
* Iterates through all child nodes.
*
* @return An iterator for the child nodes
*/
public Iterator<ModelNode> iterator() {
return children.iterator();
}
/**
* An {@code Object.equals(Object obj)} method override. Method ignores the parent source model. It means that two
* model nodes may be the same even if they belong to different models.
* <p/>
* If parent model comparison is desired, it must be accomplished separately. To perform that, the reference equality
* test is sufficient ({@code nodeA.getParentModel() == nodeB.getParentModel()}), since all model nodes are created
* for specific model instances.
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ModelNode)) {
return false;
}
boolean result = true;
final ModelNode that = (ModelNode) obj;
result = result && this.type.equals(that.type);
// result = result && ((this.parentNode == null) ? that.parentNode == null : this.parentNode.equals(that.parentNode));
result = result && ((this.nodeData == null) ? that.nodeData == null : this.nodeData.equals(that.nodeData));
result = result && ((this.children == null) ? that.children == null : this.children.equals(that.children));
return result;
}
/**
* An {@code Object.hashCode()} method override.
*/
@Override
public int hashCode() {
int result = 17;
result = 37 * result + this.type.hashCode();
result = 37 * result + ((this.parentNode == null) ? 0 : this.parentNode.hashCode());
result = 37 * result + ((this.nodeData == null) ? 0 : this.nodeData.hashCode());
result = 37 * result + this.children.hashCode();
return result;
}
/**
* Returns a string representation of the object. In general, the <code>toString</code> method
* returns a string that "textually represents" this object.
*
* @return a string representation of the object.
*/
@Override
public String toString() {
return toString(0, new StringBuffer()).toString();
}
/**
* A helper method that appends indented string representation of this instance to the input string buffer.
*
* @param indentLevel indentation level to be used.
* @param buffer buffer to be used for appending string representation of this instance
* @return modified buffer containing new string representation of the instance
*/
public StringBuffer toString(final int indentLevel, final StringBuffer buffer) {
final String indent = PolicyUtils.Text.createIndent(indentLevel);
final String innerIndent = PolicyUtils.Text.createIndent(indentLevel + 1);
buffer.append(indent).append(type).append(" {").append(PolicyUtils.Text.NEW_LINE);
if (type == Type.ASSERTION) {
if (nodeData == null) {
buffer.append(innerIndent).append("no assertion data set");
} else {
nodeData.toString(indentLevel + 1, buffer);
}
buffer.append(PolicyUtils.Text.NEW_LINE);
} else if (type == Type.POLICY_REFERENCE) {
if (referenceData == null) {
buffer.append(innerIndent).append("no policy reference data set");
} else {
referenceData.toString(indentLevel + 1, buffer);
}
buffer.append(PolicyUtils.Text.NEW_LINE);
} else if (type == Type.ASSERTION_PARAMETER_NODE) {
if (nodeData == null) {
buffer.append(innerIndent).append("no parameter data set");
}
else {
nodeData.toString(indentLevel + 1, buffer);
}
buffer.append(PolicyUtils.Text.NEW_LINE);
}
if (children.size() > 0) {
for (ModelNode child : children) {
child.toString(indentLevel + 1, buffer).append(PolicyUtils.Text.NEW_LINE);
}
} else {
buffer.append(innerIndent).append("no child nodes").append(PolicyUtils.Text.NEW_LINE);
}
buffer.append(indent).append('}');
return buffer;
}
@Override
protected ModelNode clone() throws CloneNotSupportedException {
final ModelNode clone = (ModelNode) super.clone();
if (this.nodeData != null) {
clone.nodeData = this.nodeData.clone();
}
// no need to clone PolicyReferenceData, since those are immutable
if (this.referencedModel != null) {
clone.referencedModel = this.referencedModel.clone();
}
clone.children = new LinkedList<ModelNode>();
clone.unmodifiableViewOnContent = Collections.unmodifiableCollection(clone.children);
for (ModelNode thisChild : this.children) {
clone.addChild(thisChild.clone());
}
return clone;
}
PolicyReferenceData getReferenceData() {
return referenceData;
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.ws.policy.AssertionSet;
import com.sun.xml.internal.ws.policy.NestedPolicy;
import com.sun.xml.internal.ws.policy.Policy;
import com.sun.xml.internal.ws.policy.PolicyAssertion;
import com.sun.xml.internal.ws.policy.PolicyException;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
/**
* Create a fully normalized WS-Policy infoset.
*
* @author Fabian Ritzmann
*/
class NormalizedModelGenerator extends PolicyModelGenerator {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(NormalizedModelGenerator.class);
private final PolicySourceModelCreator sourceModelCreator;
NormalizedModelGenerator(PolicySourceModelCreator sourceModelCreator) {
this.sourceModelCreator = sourceModelCreator;
}
@Override
public PolicySourceModel translate(final Policy policy) throws PolicyException {
LOGGER.entering(policy);
PolicySourceModel model = null;
if (policy == null) {
LOGGER.fine(LocalizationMessages.WSP_0047_POLICY_IS_NULL_RETURNING());
} else {
model = this.sourceModelCreator.create(policy);
final ModelNode rootNode = model.getRootNode();
final ModelNode exactlyOneNode = rootNode.createChildExactlyOneNode();
for (AssertionSet set : policy) {
final ModelNode alternativeNode = exactlyOneNode.createChildAllNode();
for (PolicyAssertion assertion : set) {
final AssertionData data = AssertionData.createAssertionData(assertion.getName(), assertion.getValue(), assertion.getAttributes(), assertion.isOptional(), assertion.isIgnorable());
final ModelNode assertionNode = alternativeNode.createChildAssertionNode(data);
if (assertion.hasNestedPolicy()) {
translate(assertionNode, assertion.getNestedPolicy());
}
if (assertion.hasParameters()) {
translate(assertionNode, assertion.getParametersIterator());
}
}
}
}
LOGGER.exiting(model);
return model;
}
@Override
protected ModelNode translate(final ModelNode parentAssertion, final NestedPolicy policy) {
final ModelNode nestedPolicyRoot = parentAssertion.createChildPolicyNode();
final ModelNode exactlyOneNode = nestedPolicyRoot.createChildExactlyOneNode();
final AssertionSet set = policy.getAssertionSet();
final ModelNode alternativeNode = exactlyOneNode.createChildAllNode();
translate(alternativeNode, set);
return nestedPolicyRoot;
}
}

View File

@@ -0,0 +1,171 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.ws.policy.AssertionSet;
import com.sun.xml.internal.ws.policy.NestedPolicy;
import com.sun.xml.internal.ws.policy.Policy;
import com.sun.xml.internal.ws.policy.PolicyAssertion;
import com.sun.xml.internal.ws.policy.PolicyException;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
import java.util.Iterator;
/**
* Translate a policy into a PolicySourceModel.
*
* Code that depends on JAX-WS should use com.sun.xml.internal.ws.api.policy.ModelGenerator
* instead of this class.
*
* @author Marek Potociar
* @author Fabian Ritzmann
*/
public abstract class PolicyModelGenerator {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(PolicyModelGenerator.class);
/**
* This protected constructor avoids direct instantiation from outside of the class
*/
protected PolicyModelGenerator() {
// nothing to initialize
}
/**
* Factory method that returns a {@link PolicyModelGenerator} instance.
*
* @return {@link PolicyModelGenerator} instance
*/
public static PolicyModelGenerator getGenerator() {
return getNormalizedGenerator(new PolicySourceModelCreator());
}
/**
* Allows derived classes to create instances of the package private
* CompactModelGenerator.
*
* @param creator An implementation of the PolicySourceModelCreator.
* @return An instance of CompactModelGenerator.
*/
protected static PolicyModelGenerator getCompactGenerator(PolicySourceModelCreator creator) {
return new CompactModelGenerator(creator);
}
/**
* Allows derived classes to create instances of the package private
* NormalizedModelGenerator.
*
* @param creator An implementation of the PolicySourceModelCreator.
* @return An instance of NormalizedModelGenerator.
*/
protected static PolicyModelGenerator getNormalizedGenerator(PolicySourceModelCreator creator) {
return new NormalizedModelGenerator(creator);
}
/**
* This method translates a {@link Policy} into a
* {@link com.sun.xml.internal.ws.policy.sourcemodel policy infoset}. The resulting
* PolicySourceModel is disconnected from the input policy, thus any
* additional changes in the policy will have no effect on the PolicySourceModel.
*
* @param policy The policy to be translated into an infoset. May be null.
* @return translated The policy infoset. May be null if the input policy was
* null.
* @throws PolicyException in case Policy translation fails.
*/
public abstract PolicySourceModel translate(final Policy policy) throws PolicyException;
/**
* Iterates through a nested policy and returns the corresponding policy info model.
*
* @param parentAssertion The parent node.
* @param policy The nested policy.
* @return The nested policy translated to the policy info model.
*/
protected abstract ModelNode translate(final ModelNode parentAssertion, final NestedPolicy policy);
/**
* Add the contents of the assertion set as child node to the given model node.
*
* @param node The content of this assertion set are added as child nodes to this node.
* May not be null.
* @param assertions The assertions that are to be added to the node. May not be null.
*/
protected void translate(final ModelNode node, final AssertionSet assertions) {
for (PolicyAssertion assertion : assertions) {
final AssertionData data = AssertionData.createAssertionData(assertion.getName(), assertion.getValue(), assertion.getAttributes(), assertion.isOptional(), assertion.isIgnorable());
final ModelNode assertionNode = node.createChildAssertionNode(data);
if (assertion.hasNestedPolicy()) {
translate(assertionNode, assertion.getNestedPolicy());
}
if (assertion.hasParameters()) {
translate(assertionNode, assertion.getParametersIterator());
}
}
}
/**
* Iterates through all contained assertions and adds them to the info model.
*
* @param assertionParametersIterator The contained assertions.
* @param assertionNode The node to which the assertions are added as child nodes
*/
protected void translate(final ModelNode assertionNode, final Iterator<PolicyAssertion> assertionParametersIterator) {
while (assertionParametersIterator.hasNext()) {
final PolicyAssertion assertionParameter = assertionParametersIterator.next();
final AssertionData data = AssertionData.createAssertionParameterData(assertionParameter.getName(), assertionParameter.getValue(), assertionParameter.getAttributes());
final ModelNode assertionParameterNode = assertionNode.createChildAssertionParameterNode(data);
if (assertionParameter.hasNestedPolicy()) {
throw LOGGER.logSevereException(new IllegalStateException(LocalizationMessages.WSP_0005_UNEXPECTED_POLICY_ELEMENT_FOUND_IN_ASSERTION_PARAM(assertionParameter)));
}
if (assertionParameter.hasNestedAssertions()) {
translate(assertionParameterNode, assertionParameter.getNestedAssertionsIterator());
}
}
}
/**
* Allows derived classes to pass their own implementation of PolicySourceModelCreator
* into the PolicyModelGenerator instance.
*/
protected static class PolicySourceModelCreator {
/**
* Create an instance of the PolicySourceModel.
*
* @param policy The policy that underlies the created PolicySourceModel.
* @return An instance of the PolicySourceModel.
*/
protected PolicySourceModel create(final Policy policy) {
return PolicySourceModel.createPolicySourceModel(policy.getNamespaceVersion(),
policy.getId(), policy.getName());
}
}
}

View File

@@ -0,0 +1,80 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import java.util.Collection;
import com.sun.xml.internal.ws.policy.PolicyException;
/**
* Abstract class defines interface for policy model marshaller implementations that are specific to underlying
* persistence layer.
*
* @author Marek Potociar
*/
public abstract class PolicyModelMarshaller {
private static final PolicyModelMarshaller defaultXmlMarshaller = new XmlPolicyModelMarshaller(false);
private static final PolicyModelMarshaller invisibleAssertionXmlMarshaller = new XmlPolicyModelMarshaller(true);
/**
* Default constructor to ensure we have a common model marshaller base, but only our API classes implemented in this
* package will be able to extend this abstract class. This is to restrict attempts of extending the class from
* a client code.
*/
PolicyModelMarshaller() {
// nothing to instantiate
}
/**
* Marshalls the policy source model using provided storage reference
*
* @param model policy source model to be marshalled
* @param storage reference to underlying storage that should be used for model marshalling
* @throws PolicyException If marshalling failed
*/
public abstract void marshal(PolicySourceModel model, Object storage) throws PolicyException;
/**
* Marshalls the collection of policy source models using provided storage reference
*
* @param models collection of policy source models to be marshalled
* @param storage reference to underlying storage that should be used for model marshalling
* @throws PolicyException If marshalling failed
*/
public abstract void marshal(Collection<PolicySourceModel> models, Object storage) throws PolicyException;
/**
* Factory methods that returns a marshaller instance based on input parameter.
*
* @param marshallInvisible boolean parameter indicating whether the marshaller
* returned by this method does marshall private assertions or not.
*
* @return policy model marshaller that either marshalls private assertions or not
* based on the input argument.
*/
public static PolicyModelMarshaller getXmlMarshaller(final boolean marshallInvisible) {
return (marshallInvisible) ? invisibleAssertionXmlMarshaller : defaultXmlMarshaller;
}
}

View File

@@ -0,0 +1,459 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import com.sun.xml.internal.ws.policy.AssertionSet;
import com.sun.xml.internal.ws.policy.Policy;
import com.sun.xml.internal.ws.policy.PolicyAssertion;
import com.sun.xml.internal.ws.policy.PolicyException;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import com.sun.xml.internal.ws.policy.spi.AssertionCreationException;
import com.sun.xml.internal.ws.policy.spi.PolicyAssertionCreator;
/**
* This class provides a method for translating a {@link PolicySourceModel} structure to a normalized {@link Policy} expression.
* The resulting Policy is disconnected from its model, thus any additional changes in the model will have no effect on the Policy
* expression.
*
* @author Marek Potociar
* @author Fabian Ritzmann
*/
public class PolicyModelTranslator {
private static final class ContentDecomposition {
final List<Collection<ModelNode>> exactlyOneContents = new LinkedList<Collection<ModelNode>>();
final List<ModelNode> assertions = new LinkedList<ModelNode>();
void reset() {
exactlyOneContents.clear();
assertions.clear();
}
}
private static final class RawAssertion {
ModelNode originalNode; // used to initialize nestedPolicy and nestedAssertions in the constructor of RawAlternative
Collection<RawAlternative> nestedAlternatives = null;
final Collection<ModelNode> parameters;
RawAssertion(ModelNode originalNode, Collection<ModelNode> parameters) {
this.parameters = parameters;
this.originalNode = originalNode;
}
}
private static final class RawAlternative {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(PolicyModelTranslator.RawAlternative.class);
final List<RawPolicy> allNestedPolicies = new LinkedList<RawPolicy>(); // used to track the nested policies which need to be normalized
final Collection<RawAssertion> nestedAssertions;
RawAlternative(Collection<ModelNode> assertionNodes) throws PolicyException {
this.nestedAssertions = new LinkedList<RawAssertion>();
for (ModelNode node : assertionNodes) {
RawAssertion assertion = new RawAssertion(node, new LinkedList<ModelNode>());
nestedAssertions.add(assertion);
for (ModelNode assertionNodeChild : assertion.originalNode.getChildren()) {
switch (assertionNodeChild.getType()) {
case ASSERTION_PARAMETER_NODE:
assertion.parameters.add(assertionNodeChild);
break;
case POLICY:
case POLICY_REFERENCE:
if (assertion.nestedAlternatives == null) {
assertion.nestedAlternatives = new LinkedList<RawAlternative>();
RawPolicy nestedPolicy;
if (assertionNodeChild.getType() == ModelNode.Type.POLICY) {
nestedPolicy = new RawPolicy(assertionNodeChild, assertion.nestedAlternatives);
} else {
nestedPolicy = new RawPolicy(getReferencedModelRootNode(assertionNodeChild), assertion.nestedAlternatives);
}
this.allNestedPolicies.add(nestedPolicy);
} else {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0006_UNEXPECTED_MULTIPLE_POLICY_NODES()));
}
break;
default:
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0008_UNEXPECTED_CHILD_MODEL_TYPE(assertionNodeChild.getType())));
}
}
}
}
}
private static final class RawPolicy {
final Collection<ModelNode> originalContent;
final Collection<RawAlternative> alternatives;
RawPolicy(ModelNode policyNode, Collection<RawAlternative> alternatives) {
originalContent = policyNode.getChildren();
this.alternatives = alternatives;
}
}
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(PolicyModelTranslator.class);
private static final PolicyAssertionCreator defaultCreator = new DefaultPolicyAssertionCreator();
private final Map<String, PolicyAssertionCreator> assertionCreators;
private PolicyModelTranslator() throws PolicyException {
this(null);
}
protected PolicyModelTranslator(final Collection<PolicyAssertionCreator> creators) throws PolicyException {
LOGGER.entering(creators);
final Collection<PolicyAssertionCreator> allCreators = new LinkedList<PolicyAssertionCreator>();
final PolicyAssertionCreator[] discoveredCreators = PolicyUtils.ServiceProvider.load(PolicyAssertionCreator.class);
for (PolicyAssertionCreator creator : discoveredCreators) {
allCreators.add(creator);
}
if (creators != null) {
for (PolicyAssertionCreator creator : creators) {
allCreators.add(creator);
}
}
final Map<String, PolicyAssertionCreator> pacMap = new HashMap<String, PolicyAssertionCreator>();
for (PolicyAssertionCreator creator : allCreators) {
final String[] supportedURIs = creator.getSupportedDomainNamespaceURIs();
final String creatorClassName = creator.getClass().getName();
if (supportedURIs == null || supportedURIs.length == 0) {
LOGGER.warning(LocalizationMessages.WSP_0077_ASSERTION_CREATOR_DOES_NOT_SUPPORT_ANY_URI(creatorClassName));
continue;
}
for (String supportedURI : supportedURIs) {
LOGGER.config(LocalizationMessages.WSP_0078_ASSERTION_CREATOR_DISCOVERED(creatorClassName, supportedURI));
if (supportedURI == null || supportedURI.length() == 0) {
throw LOGGER.logSevereException(new PolicyException(
LocalizationMessages.WSP_0070_ERROR_REGISTERING_ASSERTION_CREATOR(creatorClassName)));
}
final PolicyAssertionCreator oldCreator = pacMap.put(supportedURI, creator);
if (oldCreator != null) {
throw LOGGER.logSevereException(new PolicyException(
LocalizationMessages.WSP_0071_ERROR_MULTIPLE_ASSERTION_CREATORS_FOR_NAMESPACE(
supportedURI, oldCreator.getClass().getName(), creator.getClass().getName())));
}
}
}
this.assertionCreators = Collections.unmodifiableMap(pacMap);
LOGGER.exiting();
}
/**
* Method returns thread-safe policy model translator instance.
*
* This method is only intended to be used by code that has no dependencies on
* JAX-WS. Otherwise use com.sun.xml.internal.ws.policy.api.ModelTranslator.
*
* @return A policy model translator instance.
* @throws PolicyException If instantiating a PolicyAssertionCreator failed.
*/
public static PolicyModelTranslator getTranslator() throws PolicyException {
return new PolicyModelTranslator();
}
/**
* The method translates {@link PolicySourceModel} structure into normalized {@link Policy} expression. The resulting Policy
* is disconnected from its model, thus any additional changes in model will have no effect on the Policy expression.
*
* @param model the model to be translated into normalized policy expression. Must not be {@code null}.
* @return translated policy expression in it's normalized form.
* @throws PolicyException in case of translation failure
*/
public Policy translate(final PolicySourceModel model) throws PolicyException {
LOGGER.entering(model);
if (model == null) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0043_POLICY_MODEL_TRANSLATION_ERROR_INPUT_PARAM_NULL()));
}
PolicySourceModel localPolicyModelCopy;
try {
localPolicyModelCopy = model.clone();
} catch (CloneNotSupportedException e) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0016_UNABLE_TO_CLONE_POLICY_SOURCE_MODEL(), e));
}
final String policyId = localPolicyModelCopy.getPolicyId();
final String policyName = localPolicyModelCopy.getPolicyName();
final Collection<AssertionSet> alternatives = createPolicyAlternatives(localPolicyModelCopy);
LOGGER.finest(LocalizationMessages.WSP_0052_NUMBER_OF_ALTERNATIVE_COMBINATIONS_CREATED(alternatives.size()));
Policy policy = null;
if (alternatives.size() == 0) {
policy = Policy.createNullPolicy(model.getNamespaceVersion(), policyName, policyId);
LOGGER.finest(LocalizationMessages.WSP_0055_NO_ALTERNATIVE_COMBINATIONS_CREATED());
} else if (alternatives.size() == 1 && alternatives.iterator().next().isEmpty()) {
policy = Policy.createEmptyPolicy(model.getNamespaceVersion(), policyName, policyId);
LOGGER.finest(LocalizationMessages.WSP_0026_SINGLE_EMPTY_ALTERNATIVE_COMBINATION_CREATED());
} else {
policy = Policy.createPolicy(model.getNamespaceVersion(), policyName, policyId, alternatives);
LOGGER.finest(LocalizationMessages.WSP_0057_N_ALTERNATIVE_COMBINATIONS_M_POLICY_ALTERNATIVES_CREATED(alternatives.size(), policy.getNumberOfAssertionSets()));
}
LOGGER.exiting(policy);
return policy;
}
/**
* Method creates policy alternatives according to provided model. The model structure is modified in the process.
*
* @return created policy alternatives resulting from policy source model.
*/
private Collection<AssertionSet> createPolicyAlternatives(final PolicySourceModel model) throws PolicyException {
// creating global method variables
final ContentDecomposition decomposition = new ContentDecomposition();
// creating processing queue and starting the processing iterations
final Queue<RawPolicy> policyQueue = new LinkedList<RawPolicy>();
final Queue<Collection<ModelNode>> contentQueue = new LinkedList<Collection<ModelNode>>();
final RawPolicy rootPolicy = new RawPolicy(model.getRootNode(), new LinkedList<RawAlternative>());
RawPolicy processedPolicy = rootPolicy;
do {
Collection<ModelNode> processedContent = processedPolicy.originalContent;
do {
decompose(processedContent, decomposition);
if (decomposition.exactlyOneContents.isEmpty()) {
final RawAlternative alternative = new RawAlternative(decomposition.assertions);
processedPolicy.alternatives.add(alternative);
if (!alternative.allNestedPolicies.isEmpty()) {
policyQueue.addAll(alternative.allNestedPolicies);
}
} else { // we have a non-empty collection of exactly ones
final Collection<Collection<ModelNode>> combinations = PolicyUtils.Collections.combine(decomposition.assertions, decomposition.exactlyOneContents, false);
if (combinations != null && !combinations.isEmpty()) {
// processed alternative was split into some new alternatives, which we need to process
contentQueue.addAll(combinations);
}
}
} while ((processedContent = contentQueue.poll()) != null);
} while ((processedPolicy = policyQueue.poll()) != null);
// normalize nested policies to contain single alternative only
final Collection<AssertionSet> assertionSets = new LinkedList<AssertionSet>();
for (RawAlternative rootAlternative : rootPolicy.alternatives) {
final Collection<AssertionSet> normalizedAlternatives = normalizeRawAlternative(rootAlternative);
assertionSets.addAll(normalizedAlternatives);
}
return assertionSets;
}
/**
* Decomposes the unprocessed alternative content into two different collections:
* <p/>
* Content of 'EXACTLY_ONE' child nodes is expanded and placed in one list and
* 'ASSERTION' nodes are placed into other list. Direct 'ALL' and 'POLICY' child nodes are 'dissolved' in the process.
*
* Method reuses precreated ContentDecomposition object, which is reset before reuse.
*/
private void decompose(final Collection<ModelNode> content, final ContentDecomposition decomposition) throws PolicyException {
decomposition.reset();
final Queue<ModelNode> allContentQueue = new LinkedList<ModelNode>(content);
ModelNode node;
while ((node = allContentQueue.poll()) != null) {
// dissolving direct 'POLICY', 'POLICY_REFERENCE' and 'ALL' child nodes
switch (node.getType()) {
case POLICY :
case ALL :
allContentQueue.addAll(node.getChildren());
break;
case POLICY_REFERENCE :
allContentQueue.addAll(getReferencedModelRootNode(node).getChildren());
break;
case EXACTLY_ONE :
decomposition.exactlyOneContents.add(expandsExactlyOneContent(node.getChildren()));
break;
case ASSERTION :
decomposition.assertions.add(node);
break;
default :
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0007_UNEXPECTED_MODEL_NODE_TYPE_FOUND(node.getType())));
}
}
}
private static ModelNode getReferencedModelRootNode(final ModelNode policyReferenceNode) throws PolicyException {
final PolicySourceModel referencedModel = policyReferenceNode.getReferencedModel();
if (referencedModel == null) {
final PolicyReferenceData refData = policyReferenceNode.getPolicyReferenceData();
if (refData == null) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0041_POLICY_REFERENCE_NODE_FOUND_WITH_NO_POLICY_REFERENCE_IN_IT()));
} else {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0010_UNEXPANDED_POLICY_REFERENCE_NODE_FOUND_REFERENCING(refData.getReferencedModelUri())));
}
} else {
return referencedModel.getRootNode();
}
}
/**
* Expands content of 'EXACTLY_ONE' node. Direct 'EXACTLY_ONE' child nodes are dissolved in the process.
*/
private Collection<ModelNode> expandsExactlyOneContent(final Collection<ModelNode> content) throws PolicyException {
final Collection<ModelNode> result = new LinkedList<ModelNode>();
final Queue<ModelNode> eoContentQueue = new LinkedList<ModelNode>(content);
ModelNode node;
while ((node = eoContentQueue.poll()) != null) {
// dissolving direct 'EXACTLY_ONE' child nodes
switch (node.getType()) {
case POLICY :
case ALL :
case ASSERTION :
result.add(node);
break;
case POLICY_REFERENCE :
result.add(getReferencedModelRootNode(node));
break;
case EXACTLY_ONE :
eoContentQueue.addAll(node.getChildren());
break;
default :
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0001_UNSUPPORTED_MODEL_NODE_TYPE(node.getType())));
}
}
return result;
}
private List<AssertionSet> normalizeRawAlternative(final RawAlternative alternative) throws AssertionCreationException, PolicyException {
final List<PolicyAssertion> normalizedContentBase = new LinkedList<PolicyAssertion>();
final Collection<List<PolicyAssertion>> normalizedContentOptions = new LinkedList<List<PolicyAssertion>>();
if (!alternative.nestedAssertions.isEmpty()) {
final Queue<RawAssertion> nestedAssertionsQueue = new LinkedList<RawAssertion>(alternative.nestedAssertions);
RawAssertion rawAssertion;
while((rawAssertion = nestedAssertionsQueue.poll()) != null) {
final List<PolicyAssertion> normalized = normalizeRawAssertion(rawAssertion);
// if there is only a single result, we can add it direclty to the content base collection
// more elements in the result indicate that we will have to create combinations
if (normalized.size() == 1) {
normalizedContentBase.addAll(normalized);
} else {
normalizedContentOptions.add(normalized);
}
}
}
final List<AssertionSet> options = new LinkedList<AssertionSet>();
if (normalizedContentOptions.isEmpty()) {
// we do not have any options to combine => returning this assertion
options.add(AssertionSet.createAssertionSet(normalizedContentBase));
} else {
// we have some options to combine => creating assertion options based on content combinations
final Collection<Collection<PolicyAssertion>> contentCombinations = PolicyUtils.Collections.combine(normalizedContentBase, normalizedContentOptions, true);
for (Collection<PolicyAssertion> contentOption : contentCombinations) {
options.add(AssertionSet.createAssertionSet(contentOption));
}
}
return options;
}
private List<PolicyAssertion> normalizeRawAssertion(final RawAssertion assertion) throws AssertionCreationException, PolicyException {
List<PolicyAssertion> parameters;
if (assertion.parameters.isEmpty()) {
parameters = null;
} else {
parameters = new ArrayList<PolicyAssertion>(assertion.parameters.size());
for (ModelNode parameterNode : assertion.parameters) {
parameters.add(createPolicyAssertionParameter(parameterNode));
}
}
final List<AssertionSet> nestedAlternatives = new LinkedList<AssertionSet>();
if (assertion.nestedAlternatives != null && !assertion.nestedAlternatives.isEmpty()) {
final Queue<RawAlternative> nestedAlternativeQueue = new LinkedList<RawAlternative>(assertion.nestedAlternatives);
RawAlternative rawAlternative;
while((rawAlternative = nestedAlternativeQueue.poll()) != null) {
nestedAlternatives.addAll(normalizeRawAlternative(rawAlternative));
}
// if there is only a single result, we can add it direclty to the content base collection
// more elements in the result indicate that we will have to create combinations
}
final List<PolicyAssertion> assertionOptions = new LinkedList<PolicyAssertion>();
final boolean nestedAlternativesAvailable = !nestedAlternatives.isEmpty();
if (nestedAlternativesAvailable) {
for (AssertionSet nestedAlternative : nestedAlternatives) {
assertionOptions.add(createPolicyAssertion(assertion.originalNode.getNodeData(), parameters, nestedAlternative));
}
} else {
assertionOptions.add(createPolicyAssertion(assertion.originalNode.getNodeData(), parameters, null));
}
return assertionOptions;
}
private PolicyAssertion createPolicyAssertionParameter(final ModelNode parameterNode) throws AssertionCreationException, PolicyException {
if (parameterNode.getType() != ModelNode.Type.ASSERTION_PARAMETER_NODE) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0065_INCONSISTENCY_IN_POLICY_SOURCE_MODEL(parameterNode.getType())));
}
List<PolicyAssertion> childParameters = null;
if (parameterNode.hasChildren()) {
childParameters = new ArrayList<PolicyAssertion>(parameterNode.childrenSize());
for (ModelNode childParameterNode : parameterNode) {
childParameters.add(createPolicyAssertionParameter(childParameterNode));
}
}
return createPolicyAssertion(parameterNode.getNodeData(), childParameters, null /* parameters do not have any nested alternatives */);
}
private PolicyAssertion createPolicyAssertion(final AssertionData data, final Collection<PolicyAssertion> assertionParameters, final AssertionSet nestedAlternative) throws AssertionCreationException {
final String assertionNamespace = data.getName().getNamespaceURI();
final PolicyAssertionCreator domainSpecificPAC = assertionCreators.get(assertionNamespace);
if (domainSpecificPAC == null) {
return defaultCreator.createAssertion(data, assertionParameters, nestedAlternative, null);
} else {
return domainSpecificPAC.createAssertion(data, assertionParameters, nestedAlternative, defaultCreator);
}
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.ws.policy.PolicyException;
/**
* Abstract class defines interface for policy model unmarshaller implementations that are specific to underlying
* persistence layer.
*
* Code that depends on JAX-WS should use com.sun.xml.internal.ws.api.policy.ModelUnmarshaller
* instead of this class.
*
* @author Marek Potociar
* @author Fabian Ritzmann
*/
public abstract class PolicyModelUnmarshaller {
private static final PolicyModelUnmarshaller xmlUnmarshaller = new XmlPolicyModelUnmarshaller();
/**
* Default constructor to ensure we have a common model unmarshaller base, but only our API classes implemented in this
* package will be able to extend this abstract class. This is to restrict attempts of extending the class from
* a client code.
*/
PolicyModelUnmarshaller() {
// nothing to intitialize
}
/**
* Unmarshalls single policy source model from provided storage reference. Method expects that the storage
* cursor to be alread placed on the start of a policy expression. Inner comments and whitespaces are skipped
* in processing. Any other cursor position results in a PolicyException being thrown.
*
* @param storage reference to underlying storage that should be used for model unmarshalling
* @return unmarshalled policy source model. If no policies are found, returns {@code null}.
* @throws PolicyException in case of the unmarshalling problems
*/
public abstract PolicySourceModel unmarshalModel(Object storage) throws PolicyException;
/**
* Factory method that returns policy model unmarshaller able to unmarshal
* policy expressions from XML source.
*
* Code that depends on JAX-WS should use com.sun.xml.internal.ws.api.policy.ModelUnmarshaller.getUnmarshaller()
* instead of this method.
*
* @return policy model unmarshaller able to unmarshal policy expressions from XML source.
*/
public static PolicyModelUnmarshaller getXmlUnmarshaller() {
return xmlUnmarshaller;
}
}

View File

@@ -0,0 +1,134 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import java.net.URI;
import java.net.URISyntaxException;
/**
*
* @author Marek Potociar
*/
final class PolicyReferenceData {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(PolicyReferenceData.class);
private static final URI DEFAULT_DIGEST_ALGORITHM_URI;
private static final URISyntaxException CLASS_INITIALIZATION_EXCEPTION;
static {
URISyntaxException tempEx = null;
URI tempUri = null;
try {
tempUri = new URI("http://schemas.xmlsoap.org/ws/2004/09/policy/Sha1Exc");
} catch (URISyntaxException e) {
tempEx = e;
} finally {
DEFAULT_DIGEST_ALGORITHM_URI = tempUri;
CLASS_INITIALIZATION_EXCEPTION = tempEx;
}
}
private final URI referencedModelUri;
private final String digest;
private final URI digestAlgorithmUri;
/** Creates a new instance of PolicyReferenceData */
public PolicyReferenceData(URI referencedModelUri) {
this.referencedModelUri = referencedModelUri;
this.digest = null;
this.digestAlgorithmUri = null;
}
public PolicyReferenceData(URI referencedModelUri, String expectedDigest, URI usedDigestAlgorithm) {
if (CLASS_INITIALIZATION_EXCEPTION != null) {
throw LOGGER.logSevereException(new IllegalStateException(LocalizationMessages.WSP_0015_UNABLE_TO_INSTANTIATE_DIGEST_ALG_URI_FIELD(), CLASS_INITIALIZATION_EXCEPTION));
}
if (usedDigestAlgorithm != null && expectedDigest == null) {
throw LOGGER.logSevereException(new IllegalArgumentException(LocalizationMessages.WSP_0072_DIGEST_MUST_NOT_BE_NULL_WHEN_ALG_DEFINED()));
}
this.referencedModelUri = referencedModelUri;
if (expectedDigest == null) {
this.digest = null;
this.digestAlgorithmUri = null;
} else {
this.digest = expectedDigest;
if (usedDigestAlgorithm == null) {
this.digestAlgorithmUri = DEFAULT_DIGEST_ALGORITHM_URI;
} else {
this.digestAlgorithmUri = usedDigestAlgorithm;
}
}
}
public URI getReferencedModelUri() {
return referencedModelUri;
}
public String getDigest() {
return digest;
}
public URI getDigestAlgorithmUri() {
return digestAlgorithmUri;
}
/**
* An {@code Object.toString()} method override.
*/
@Override
public String toString() {
return toString(0, new StringBuffer()).toString();
}
/**
* A helper method that appends indented string representation of this instance to the input string buffer.
*
* @param indentLevel indentation level to be used.
* @param buffer buffer to be used for appending string representation of this instance
* @return modified buffer containing new string representation of the instance
*/
public StringBuffer toString(final int indentLevel, final StringBuffer buffer) {
final String indent = PolicyUtils.Text.createIndent(indentLevel);
final String innerIndent = PolicyUtils.Text.createIndent(indentLevel + 1);
buffer.append(indent).append("reference data {").append(PolicyUtils.Text.NEW_LINE);
buffer.append(innerIndent).append("referenced policy model URI = '").append(referencedModelUri).append('\'').append(PolicyUtils.Text.NEW_LINE);
if (digest == null) {
buffer.append(innerIndent).append("no digest specified").append(PolicyUtils.Text.NEW_LINE);
} else {
buffer.append(innerIndent).append("digest algorith URI = '").append(digestAlgorithmUri).append('\'').append(PolicyUtils.Text.NEW_LINE);
buffer.append(innerIndent).append("digest = '").append(digest).append('\'').append(PolicyUtils.Text.NEW_LINE);
}
buffer.append(indent).append('}');
return buffer;
}
}

View File

@@ -0,0 +1,428 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.ws.policy.sourcemodel.wspolicy.NamespaceVersion;
import com.sun.xml.internal.ws.policy.PolicyConstants;
import com.sun.xml.internal.ws.policy.PolicyException;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import com.sun.xml.internal.ws.policy.spi.PrefixMapper;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import javax.xml.namespace.QName;
/**
* This class is a root of unmarshaled policy source structure. Each instance of the class contains factory method
* to create new {@link com.sun.xml.internal.ws.policy.sourcemodel.ModelNode} instances associated with the actual model instance.
*
* @author Marek Potociar
* @author Fabian Ritzmann
*/
public class PolicySourceModel implements Cloneable {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(PolicySourceModel.class);
private static final Map<String, String> DEFAULT_NAMESPACE_TO_PREFIX = new HashMap<String, String>();
static {
PrefixMapper[] prefixMappers = PolicyUtils.ServiceProvider.load(PrefixMapper.class);
if (prefixMappers != null) {
for (PrefixMapper mapper: prefixMappers) {
DEFAULT_NAMESPACE_TO_PREFIX.putAll(mapper.getPrefixMap());
}
}
for (NamespaceVersion version : NamespaceVersion.values()) {
DEFAULT_NAMESPACE_TO_PREFIX.put(version.toString(), version.getDefaultNamespacePrefix());
}
DEFAULT_NAMESPACE_TO_PREFIX.put(PolicyConstants.WSU_NAMESPACE_URI,
PolicyConstants.WSU_NAMESPACE_PREFIX);
DEFAULT_NAMESPACE_TO_PREFIX.put(PolicyConstants.SUN_POLICY_NAMESPACE_URI,
PolicyConstants.SUN_POLICY_NAMESPACE_PREFIX);
}
// Map namespaces to prefixes
private final Map<String, String> namespaceToPrefix =
new HashMap<String, String>(DEFAULT_NAMESPACE_TO_PREFIX);
private ModelNode rootNode;
private final String policyId;
private final String policyName;
private final NamespaceVersion nsVersion;
private final List<ModelNode> references = new LinkedList<ModelNode>(); // links to policy reference nodes
private boolean expanded = false;
/**
* Factory method that creates new policy source model instance.
*
* This method is only intended to be used by code that has no dependencies on
* JAX-WS. Otherwise use com.sun.xml.internal.ws.policy.api.SourceModel.
*
* @param nsVersion The policy version
* @return Newly created policy source model instance.
*/
public static PolicySourceModel createPolicySourceModel(final NamespaceVersion nsVersion) {
return new PolicySourceModel(nsVersion);
}
/**
* Factory method that creates new policy source model instance and initializes it according to parameters provided.
*
* This method is only intended to be used by code that has no dependencies on
* JAX-WS. Otherwise use com.sun.xml.internal.ws.policy.api.SourceModel.
*
* @param nsVersion The policy version
* @param policyId local policy identifier - relative URI. May be {@code null}.
* @param policyName global policy identifier - absolute policy expression URI. May be {@code null}.
* @return Newly created policy source model instance with its name and id properly set.
*/
public static PolicySourceModel createPolicySourceModel(final NamespaceVersion nsVersion, final String policyId, final String policyName) {
return new PolicySourceModel(nsVersion, policyId, policyName);
}
/**
* Constructor that creates a new policy source model instance without any
* id or name identifier. The namespace-to-prefix map is initialized with mapping
* of policy namespace to the default value set by
* {@link PolicyConstants#POLICY_NAMESPACE_PREFIX POLICY_NAMESPACE_PREFIX constant}.
*
* @param nsVersion The WS-Policy version.
*/
private PolicySourceModel(NamespaceVersion nsVersion) {
this(nsVersion, null, null);
}
/**
* Constructor that creates a new policy source model instance with given
* id or name identifier.
*
* @param nsVersion The WS-Policy version.
* @param policyId Relative policy reference within an XML document. May be {@code null}.
* @param policyName Absolute IRI of policy expression. May be {@code null}.
*/
private PolicySourceModel(NamespaceVersion nsVersion, String policyId, String policyName) {
this(nsVersion, policyId, policyName, null);
}
/**
* Constructor that creates a new policy source model instance with given
* id or name identifier and a set of PrefixMappers.
*
* This constructor is intended to be used by the JAX-WS com.sun.xml.internal.ws.policy.api.SourceModel.
*
* @param nsVersion The WS-Policy version.
* @param policyId Relative policy reference within an XML document. May be {@code null}.
* @param policyName Absolute IRI of policy expression. May be {@code null}.
* @param prefixMappers A collection of PrefixMappers to be used with this instance. May be {@code null}.
*/
protected PolicySourceModel(NamespaceVersion nsVersion, String policyId,
String policyName, Collection<PrefixMapper> prefixMappers) {
this.rootNode = ModelNode.createRootPolicyNode(this);
this.nsVersion = nsVersion;
this.policyId = policyId;
this.policyName = policyName;
if (prefixMappers != null) {
for (PrefixMapper prefixMapper : prefixMappers) {
this.namespaceToPrefix.putAll(prefixMapper.getPrefixMap());
}
}
}
/**
* Returns a root node of this policy source model. It is allways of POLICY type.
*
* @return root policy source model node - allways of POLICY type.
*/
public ModelNode getRootNode() {
return rootNode;
}
/**
* Returns a policy name of this policy source model.
*
* @return policy name.
*/
public String getPolicyName() {
return policyName;
}
/**
* Returns a policy ID of this policy source model.
*
* @return policy ID.
*/
public String getPolicyId() {
return policyId;
}
/**
* Returns an original namespace version of this policy source model.
*
* @return namespace version.
*/
public NamespaceVersion getNamespaceVersion() {
return nsVersion;
}
/**
* Provides information about how namespaces used in this {@link PolicySourceModel}
* instance should be mapped to their default prefixes when marshalled.
*
* @return immutable map that holds information about namespaces used in the
* model and their mapping to prefixes that should be used when marshalling
* this model.
* @throws PolicyException Thrown if one of the prefix mappers threw an exception.
*/
Map<String, String> getNamespaceToPrefixMapping() throws PolicyException {
final Map<String, String> nsToPrefixMap = new HashMap<String, String>();
final Collection<String> namespaces = getUsedNamespaces();
for (String namespace : namespaces) {
final String prefix = getDefaultPrefix(namespace);
if (prefix != null) {
nsToPrefixMap.put(namespace, prefix);
}
}
return nsToPrefixMap;
}
/**
* An {@code Object.equals(Object obj)} method override.
* <p/>
* When child nodes are tested for equality, the parent policy source model is not considered. Thus two different
* policy source models instances may be equal based on their node content.
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof PolicySourceModel)) {
return false;
}
boolean result = true;
final PolicySourceModel that = (PolicySourceModel) obj;
result = result && ((this.policyId == null) ? that.policyId == null : this.policyId.equals(that.policyId));
result = result && ((this.policyName == null) ? that.policyName == null : this.policyName.equals(that.policyName));
result = result && this.rootNode.equals(that.rootNode);
return result;
}
/**
* An {@code Object.hashCode()} method override.
*/
@Override
public int hashCode() {
int result = 17;
result = 37 * result + ((this.policyId == null) ? 0 : this.policyId.hashCode());
result = 37 * result + ((this.policyName == null) ? 0 : this.policyName.hashCode());
result = 37 * result + this.rootNode.hashCode();
return result;
}
/**
* Returns a string representation of the object. In general, the <code>toString</code> method
* returns a string that "textually represents" this object.
*
* @return a string representation of the object.
*/
@Override
public String toString() {
final String innerIndent = PolicyUtils.Text.createIndent(1);
final StringBuffer buffer = new StringBuffer(60);
buffer.append("Policy source model {").append(PolicyUtils.Text.NEW_LINE);
buffer.append(innerIndent).append("policy id = '").append(policyId).append('\'').append(PolicyUtils.Text.NEW_LINE);
buffer.append(innerIndent).append("policy name = '").append(policyName).append('\'').append(PolicyUtils.Text.NEW_LINE);
rootNode.toString(1, buffer).append(PolicyUtils.Text.NEW_LINE).append('}');
return buffer.toString();
}
@Override
protected PolicySourceModel clone() throws CloneNotSupportedException {
final PolicySourceModel clone = (PolicySourceModel) super.clone();
clone.rootNode = this.rootNode.clone();
try {
clone.rootNode.setParentModel(clone);
} catch (IllegalAccessException e) {
throw LOGGER.logSevereException(new CloneNotSupportedException(LocalizationMessages.WSP_0013_UNABLE_TO_SET_PARENT_MODEL_ON_ROOT()), e);
}
return clone;
}
/**
* Returns a boolean value indicating whether this policy source model contains references to another policy source models.
* <p/>
* Every source model that references other policies must be expanded before it can be translated into a Policy objects. See
* {@link #expand(PolicySourceModelContext)} and {@link #isExpanded()} for more details.
*
* @return {@code true} or {code false} depending on whether this policy source model contains references to another policy source models.
*/
public boolean containsPolicyReferences() {
return !references.isEmpty();
}
/**
* Returns a boolean value indicating whether this policy source model contains is already expanded (i.e. contains no unexpanded
* policy references) or not. This means that if model does not originally contain any policy references, it is considered as expanded,
* thus this method returns {@code true} in such case. Also this method does not check whether the references policy source models are expanded
* as well, so after expanding this model a value of {@code true} is returned even if referenced models are not expanded yet. Thus each model
* can be considered to be fully expanded only if all policy source models stored in PolicySourceModelContext instance are expanded, provided the
* PolicySourceModelContext instance contains full set of policy source models.
* <p/>
* Every source model that references other policies must be expanded before it can be translated into a Policy object. See
* {@link #expand(PolicySourceModelContext)} and {@link #containsPolicyReferences()} for more details.
*
* @return {@code true} or {@code false} depending on whether this policy source model contains is expanded or not.
*/
private boolean isExpanded() {
return references.isEmpty() || expanded;
}
/**
* Expands current policy model. This means, that if this model contains any (unexpanded) policy references, then the method expands those
* references by placing the content of the referenced policy source models under the policy reference nodes. This operation merely creates
* a link between this and referenced policy source models. Thus any change in the referenced models will be visible wihtin this model as well.
* <p/>
* Please, notice that the method does not check if the referenced models are already expanded nor does the method try to expand unexpanded
* referenced models. This must be preformed manually within client's code. Consecutive calls of this method will have no effect.
* <p/>
* Every source model that references other policies must be expanded before it can be translated into a Policy object. See
* {@link #isExpanded()} and {@link #containsPolicyReferences()} for more details.
*
* @param context a policy source model context holding the set of unmarshalled policy source models within the same context.
* @throws PolicyException Thrown if a referenced policy could not be resolved
*/
public synchronized void expand(final PolicySourceModelContext context) throws PolicyException {
if (!isExpanded()) {
for (ModelNode reference : references) {
final PolicyReferenceData refData = reference.getPolicyReferenceData();
final String digest = refData.getDigest();
PolicySourceModel referencedModel;
if (digest == null) {
referencedModel = context.retrieveModel(refData.getReferencedModelUri());
} else {
referencedModel = context.retrieveModel(refData.getReferencedModelUri(), refData.getDigestAlgorithmUri(), digest);
}
reference.setReferencedModel(referencedModel);
}
expanded = true;
}
}
/**
* Adds new policy reference to the policy source model. The method is used by
* the ModelNode instances of type POLICY_REFERENCE that need to register themselves
* as policy references in the model.
*
* @param node policy reference model node to be registered as a policy reference
* in this model.
*/
void addNewPolicyReference(final ModelNode node) {
if (node.getType() != ModelNode.Type.POLICY_REFERENCE) {
throw new IllegalArgumentException(LocalizationMessages.WSP_0042_POLICY_REFERENCE_NODE_EXPECTED_INSTEAD_OF(node.getType()));
}
references.add(node);
}
/**
* Iterates through policy vocabulary and extracts set of namespaces used in
* the policy expression.
*
* @return collection of used namespaces within given policy instance
* @throws PolicyException Thrown if internal processing failed.
*/
private Collection<String> getUsedNamespaces() throws PolicyException {
final Set<String> namespaces = new HashSet<String>();
namespaces.add(getNamespaceVersion().toString());
if (this.policyId != null) {
namespaces.add(PolicyConstants.WSU_NAMESPACE_URI);
}
final Queue<ModelNode> nodesToBeProcessed = new LinkedList<ModelNode>();
nodesToBeProcessed.add(rootNode);
ModelNode processedNode;
while ((processedNode = nodesToBeProcessed.poll()) != null) {
for (ModelNode child : processedNode.getChildren()) {
if (child.hasChildren()) {
if (!nodesToBeProcessed.offer(child)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0081_UNABLE_TO_INSERT_CHILD(nodesToBeProcessed, child)));
}
}
if (child.isDomainSpecific()) {
final AssertionData nodeData = child.getNodeData();
namespaces.add(nodeData.getName().getNamespaceURI());
if (nodeData.isPrivateAttributeSet()) {
namespaces.add(PolicyConstants.SUN_POLICY_NAMESPACE_URI);
}
for (Entry<QName, String> attribute : nodeData.getAttributesSet()) {
namespaces.add(attribute.getKey().getNamespaceURI());
}
}
}
}
return namespaces;
}
/**
* Method retrieves default prefix for given namespace. Method returns null if
* no default prefix is defined..
*
* @param namespace to get default prefix for.
* @return default prefix for given namespace. May return {@code null} if the
* default prefix for given namespace is not defined.
*/
private String getDefaultPrefix(final String namespace) {
return namespaceToPrefix.get(namespace);
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
/**
*
* @author Marek Potociar, Jakub Podlesak
*/
public final class PolicySourceModelContext {
Map<URI,PolicySourceModel> policyModels;
/**
* Private constructor prevents instantiation of the instance from outside of the class
*/
private PolicySourceModelContext() {
// nothing to initialize
}
private Map<URI,PolicySourceModel> getModels() {
if (null==policyModels) {
policyModels = new HashMap<URI,PolicySourceModel>();
}
return policyModels;
}
public void addModel(final URI modelUri, final PolicySourceModel model) {
getModels().put(modelUri,model);
}
public static PolicySourceModelContext createContext() {
return new PolicySourceModelContext();
}
public boolean containsModel(final URI modelUri) {
return getModels().containsKey(modelUri);
}
PolicySourceModel retrieveModel(final URI modelUri) {
return getModels().get(modelUri);
}
PolicySourceModel retrieveModel(final URI modelUri, final URI digestAlgorithm, final String digest) {
// TODO: implement
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return "PolicySourceModelContext: policyModels = " + this.policyModels;
}
}

View File

@@ -0,0 +1,193 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.txw2.TXW;
import com.sun.xml.internal.txw2.TypedXmlWriter;
import com.sun.xml.internal.txw2.output.StaxSerializer;
import com.sun.xml.internal.ws.policy.sourcemodel.wspolicy.XmlToken;
import com.sun.xml.internal.ws.policy.sourcemodel.wspolicy.NamespaceVersion;
import com.sun.xml.internal.ws.policy.PolicyConstants;
import com.sun.xml.internal.ws.policy.PolicyException;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamWriter;
public final class XmlPolicyModelMarshaller extends PolicyModelMarshaller {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(XmlPolicyModelMarshaller.class);
private final boolean marshallInvisible;
XmlPolicyModelMarshaller(boolean marshallInvisible) {
this.marshallInvisible = marshallInvisible;
}
public void marshal(final PolicySourceModel model, final Object storage) throws PolicyException {
if (storage instanceof StaxSerializer) {
marshal(model, (StaxSerializer) storage);
} else if (storage instanceof TypedXmlWriter) {
marshal(model, (TypedXmlWriter) storage);
} else if (storage instanceof XMLStreamWriter) {
marshal(model, (XMLStreamWriter) storage);
} else {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0022_STORAGE_TYPE_NOT_SUPPORTED(storage.getClass().getName())));
}
}
public void marshal(final Collection<PolicySourceModel> models, final Object storage) throws PolicyException {
for (PolicySourceModel model : models) {
marshal(model, storage);
}
}
/**
* Marshal a policy onto the given StaxSerializer.
*
* @param model A policy source model.
* @param writer A Stax serializer.
* @throws PolicyException If marshalling failed.
*/
private void marshal(final PolicySourceModel model, final StaxSerializer writer) throws PolicyException {
final TypedXmlWriter policy = TXW.create(model.getNamespaceVersion().asQName(XmlToken.Policy), TypedXmlWriter.class, writer);
marshalDefaultPrefixes(model, policy);
marshalPolicyAttributes(model, policy);
marshal(model.getNamespaceVersion(), model.getRootNode(), policy);
policy.commit();
}
/**
* Marshal a policy onto the given TypedXmlWriter.
*
* @param model A policy source model.
* @param writer A typed XML writer.
* @throws PolicyException If marshalling failed.
*/
private void marshal(final PolicySourceModel model, final TypedXmlWriter writer) throws PolicyException {
final TypedXmlWriter policy = writer._element(model.getNamespaceVersion().asQName(XmlToken.Policy), TypedXmlWriter.class);
marshalDefaultPrefixes(model, policy);
marshalPolicyAttributes(model, policy);
marshal(model.getNamespaceVersion(), model.getRootNode(), policy);
}
/**
* Marshal a policy onto the given XMLStreamWriter.
*
* @param model A policy source model.
* @param writer An XML stream writer.
* @throws PolicyException If marshalling failed.
*/
private void marshal(final PolicySourceModel model, final XMLStreamWriter writer) throws PolicyException {
final StaxSerializer serializer = new StaxSerializer(writer);
final TypedXmlWriter policy = TXW.create(model.getNamespaceVersion().asQName(XmlToken.Policy), TypedXmlWriter.class, serializer);
marshalDefaultPrefixes(model, policy);
marshalPolicyAttributes(model, policy);
marshal(model.getNamespaceVersion(), model.getRootNode(), policy);
policy.commit();
serializer.flush();
}
/**
* Marshal the Policy root element attributes onto the TypedXmlWriter.
*
* @param model The policy source model.
* @param writer The typed XML writer.
*/
private static void marshalPolicyAttributes(final PolicySourceModel model, final TypedXmlWriter writer) {
final String policyId = model.getPolicyId();
if (policyId != null) {
writer._attribute(PolicyConstants.WSU_ID, policyId);
}
final String policyName = model.getPolicyName();
if (policyName != null) {
writer._attribute(model.getNamespaceVersion().asQName(XmlToken.Name), policyName);
}
}
/**
* Marshal given ModelNode and child elements on given TypedXmlWriter.
*
* @param nsVersion The WS-Policy version.
* @param rootNode The ModelNode that is marshalled.
* @param writer The TypedXmlWriter onto which the content of the rootNode is marshalled.
*/
private void marshal(final NamespaceVersion nsVersion, final ModelNode rootNode, final TypedXmlWriter writer) {
for (ModelNode node : rootNode) {
final AssertionData data = node.getNodeData();
if (marshallInvisible || data == null || !data.isPrivateAttributeSet()) {
TypedXmlWriter child = null;
if (data == null) {
child = writer._element(nsVersion.asQName(node.getType().getXmlToken()), TypedXmlWriter.class);
} else {
child = writer._element(data.getName(), TypedXmlWriter.class);
final String value = data.getValue();
if (value != null) {
child._pcdata(value);
}
if (data.isOptionalAttributeSet()) {
child._attribute(nsVersion.asQName(XmlToken.Optional), Boolean.TRUE);
}
if (data.isIgnorableAttributeSet()) {
child._attribute(nsVersion.asQName(XmlToken.Ignorable), Boolean.TRUE);
}
for (Entry<QName, String> entry : data.getAttributesSet()) {
child._attribute(entry.getKey(), entry.getValue());
}
}
marshal(nsVersion, node, child);
}
}
}
/**
* Write default prefixes onto the given TypedXmlWriter
*
* @param model The policy source model. May not be null.
* @param writer The TypedXmlWriter. May not be null.
* @throws PolicyException If the creation of the prefix to namespace URI map failed.
*/
private void marshalDefaultPrefixes(final PolicySourceModel model, final TypedXmlWriter writer) throws PolicyException {
final Map<String, String> nsMap = model.getNamespaceToPrefixMapping();
if (!marshallInvisible && nsMap.containsKey(PolicyConstants.SUN_POLICY_NAMESPACE_URI)) {
nsMap.remove(PolicyConstants.SUN_POLICY_NAMESPACE_URI);
}
for (Map.Entry<String, String> nsMappingEntry : nsMap.entrySet()) {
writer._namespace(nsMappingEntry.getKey(), nsMappingEntry.getValue());
}
}
}

View File

@@ -0,0 +1,374 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;
import com.sun.xml.internal.ws.policy.PolicyConstants;
import com.sun.xml.internal.ws.policy.PolicyException;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
import com.sun.xml.internal.ws.policy.sourcemodel.wspolicy.NamespaceVersion;
import com.sun.xml.internal.ws.policy.sourcemodel.wspolicy.XmlToken;
import java.io.Reader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
/**
* Unmarshal XML policy expressions.
*
* @author Marek Potociar
* @author Fabian Ritzmann
*/
public class XmlPolicyModelUnmarshaller extends PolicyModelUnmarshaller {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(XmlPolicyModelUnmarshaller.class);
/**
* Creates a new instance of XmlPolicyModelUnmarshaller
*/
protected XmlPolicyModelUnmarshaller() {
// nothing to initialize
}
/**
* See {@link PolicyModelUnmarshaller#unmarshalModel(Object) base method documentation}.
*/
public PolicySourceModel unmarshalModel(final Object storage) throws PolicyException {
final XMLEventReader reader = createXMLEventReader(storage);
PolicySourceModel model = null;
loop:
while (reader.hasNext()) {
try {
final XMLEvent event = reader.peek();
switch (event.getEventType()) {
case XMLStreamConstants.START_DOCUMENT:
case XMLStreamConstants.COMMENT:
reader.nextEvent();
break; // skipping the comments and start document events
case XMLStreamConstants.CHARACTERS:
processCharacters(ModelNode.Type.POLICY, event.asCharacters(), null);
// we advance the reader only if there is no exception thrown from
// the processCharacters(...) call. Otherwise we don't modify the stream
reader.nextEvent();
break;
case XMLStreamConstants.START_ELEMENT:
if (NamespaceVersion.resolveAsToken(event.asStartElement().getName()) == XmlToken.Policy) {
StartElement rootElement = reader.nextEvent().asStartElement();
model = initializeNewModel(rootElement);
unmarshalNodeContent(model.getNamespaceVersion(), model.getRootNode(), rootElement.getName(), reader);
break loop;
} else {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
}
default:
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0048_POLICY_ELEMENT_EXPECTED_FIRST()));
}
} catch (XMLStreamException e) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
}
}
return model;
}
/**
* Allow derived classes to pass in a custom instance of PolicySourceModel.
*
* @param nsVersion
* @param id
* @param name
* @return
*/
protected PolicySourceModel createSourceModel(NamespaceVersion nsVersion, String id, String name) {
return PolicySourceModel.createPolicySourceModel(nsVersion, id, name);
}
private PolicySourceModel initializeNewModel(final StartElement element) throws PolicyException, XMLStreamException {
PolicySourceModel model;
final NamespaceVersion nsVersion = NamespaceVersion.resolveVersion(element.getName().getNamespaceURI());
final Attribute policyName = getAttributeByName(element, nsVersion.asQName(XmlToken.Name));
final Attribute xmlId = getAttributeByName(element, PolicyConstants.XML_ID);
Attribute policyId = getAttributeByName(element, PolicyConstants.WSU_ID);
if (policyId == null) {
policyId = xmlId;
} else if (xmlId != null) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0058_MULTIPLE_POLICY_IDS_NOT_ALLOWED()));
}
model = createSourceModel(nsVersion,
(policyId == null) ? null : policyId.getValue(),
(policyName == null) ? null : policyName.getValue());
return model;
}
private ModelNode addNewChildNode(final NamespaceVersion nsVersion, final ModelNode parentNode, final StartElement childElement) throws PolicyException {
ModelNode childNode;
final QName childElementName = childElement.getName();
if (parentNode.getType() == ModelNode.Type.ASSERTION_PARAMETER_NODE) {
childNode = parentNode.createChildAssertionParameterNode();
} else {
XmlToken token = NamespaceVersion.resolveAsToken(childElementName);
switch (token) {
case Policy:
childNode = parentNode.createChildPolicyNode();
break;
case All:
childNode = parentNode.createChildAllNode();
break;
case ExactlyOne:
childNode = parentNode.createChildExactlyOneNode();
break;
case PolicyReference:
final Attribute uri = getAttributeByName(childElement, nsVersion.asQName(XmlToken.Uri));
if (uri == null) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0040_POLICY_REFERENCE_URI_ATTR_NOT_FOUND()));
} else {
try {
final URI reference = new URI(uri.getValue());
final Attribute digest = getAttributeByName(childElement, nsVersion.asQName(XmlToken.Digest));
PolicyReferenceData refData;
if (digest == null) {
refData = new PolicyReferenceData(reference);
} else {
final Attribute digestAlgorithm = getAttributeByName(childElement, nsVersion.asQName(XmlToken.DigestAlgorithm));
URI algorithmRef = null;
if (digestAlgorithm != null) {
algorithmRef = new URI(digestAlgorithm.getValue());
}
refData = new PolicyReferenceData(reference, digest.getValue(), algorithmRef);
}
childNode = parentNode.createChildPolicyReferenceNode(refData);
} catch (URISyntaxException e) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0012_UNABLE_TO_UNMARSHALL_POLICY_MALFORMED_URI(), e));
}
}
break;
default:
if (parentNode.isDomainSpecific()) {
childNode = parentNode.createChildAssertionParameterNode();
} else {
childNode = parentNode.createChildAssertionNode();
}
}
}
return childNode;
}
private void parseAssertionData(NamespaceVersion nsVersion, String value, ModelNode childNode, final StartElement childElement) throws IllegalArgumentException, PolicyException {
// finish assertion node processing: create and set assertion data...
final Map<QName, String> attributeMap = new HashMap<QName, String>();
boolean optional = false;
boolean ignorable = false;
final Iterator iterator = childElement.getAttributes();
while (iterator.hasNext()) {
final Attribute nextAttribute = (Attribute) iterator.next();
final QName name = nextAttribute.getName();
if (attributeMap.containsKey(name)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0059_MULTIPLE_ATTRS_WITH_SAME_NAME_DETECTED_FOR_ASSERTION(nextAttribute.getName(), childElement.getName())));
} else {
if (nsVersion.asQName(XmlToken.Optional).equals(name)) {
optional = parseBooleanValue(nextAttribute.getValue());
} else if (nsVersion.asQName(XmlToken.Ignorable).equals(name)) {
ignorable = parseBooleanValue(nextAttribute.getValue());
} else {
attributeMap.put(name, nextAttribute.getValue());
}
}
}
final AssertionData nodeData = new AssertionData(childElement.getName(), value, attributeMap, childNode.getType(), optional, ignorable);
// check visibility value syntax if present...
if (nodeData.containsAttribute(PolicyConstants.VISIBILITY_ATTRIBUTE)) {
final String visibilityValue = nodeData.getAttributeValue(PolicyConstants.VISIBILITY_ATTRIBUTE);
if (!PolicyConstants.VISIBILITY_VALUE_PRIVATE.equals(visibilityValue)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0004_UNEXPECTED_VISIBILITY_ATTR_VALUE(visibilityValue)));
}
}
childNode.setOrReplaceNodeData(nodeData);
}
private Attribute getAttributeByName(final StartElement element,
final QName attributeName) {
// call standard API method to retrieve the attribute by name
Attribute attribute = element.getAttributeByName(attributeName);
// try to find the attribute without a prefix.
if (attribute == null) {
final String localAttributeName = attributeName.getLocalPart();
final Iterator iterator = element.getAttributes();
while (iterator.hasNext()) {
final Attribute nextAttribute = (Attribute) iterator.next();
final QName aName = nextAttribute.getName();
final boolean attributeFoundByWorkaround = aName.equals(attributeName) || (aName.getLocalPart().equals(localAttributeName) && (aName.getPrefix() == null || "".equals(aName.getPrefix())));
if (attributeFoundByWorkaround) {
attribute = nextAttribute;
break;
}
}
}
return attribute;
}
private String unmarshalNodeContent(final NamespaceVersion nsVersion, final ModelNode node, final QName nodeElementName, final XMLEventReader reader) throws PolicyException {
StringBuilder valueBuffer = null;
loop:
while (reader.hasNext()) {
try {
final XMLEvent xmlParserEvent = reader.nextEvent();
switch (xmlParserEvent.getEventType()) {
case XMLStreamConstants.COMMENT:
break; // skipping the comments
case XMLStreamConstants.CHARACTERS:
valueBuffer = processCharacters(node.getType(), xmlParserEvent.asCharacters(), valueBuffer);
break;
case XMLStreamConstants.END_ELEMENT:
checkEndTagName(nodeElementName, xmlParserEvent.asEndElement());
break loop; // data exctraction for currently processed policy node is done
case XMLStreamConstants.START_ELEMENT:
final StartElement childElement = xmlParserEvent.asStartElement();
ModelNode childNode = addNewChildNode(nsVersion, node, childElement);
String value = unmarshalNodeContent(nsVersion, childNode, childElement.getName(), reader);
if (childNode.isDomainSpecific()) {
parseAssertionData(nsVersion, value, childNode, childElement);
}
break;
default:
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0011_UNABLE_TO_UNMARSHALL_POLICY_XML_ELEM_EXPECTED()));
}
} catch (XMLStreamException e) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0068_FAILED_TO_UNMARSHALL_POLICY_EXPRESSION(), e));
}
}
return (valueBuffer == null) ? null : valueBuffer.toString().trim();
}
/**
* Method checks if the storage type is supported and transforms it to XMLEventReader instance which is then returned.
* Throws PolicyException if the transformation is not succesfull or if the storage type is not supported.
*
* @param storage An XMLEventReader instance.
* @return The storage cast to an XMLEventReader.
* @throws PolicyException If the XMLEventReader cast failed.
*/
private XMLEventReader createXMLEventReader(final Object storage)
throws PolicyException {
if (storage instanceof XMLEventReader) {
return (XMLEventReader) storage;
}
else if (!(storage instanceof Reader)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0022_STORAGE_TYPE_NOT_SUPPORTED(storage.getClass().getName())));
}
try {
return XMLInputFactory.newInstance().createXMLEventReader((Reader) storage);
} catch (XMLStreamException e) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0014_UNABLE_TO_INSTANTIATE_READER_FOR_STORAGE(), e));
}
}
/**
* Method checks whether the actual name of the end tag is equal to the expected name - the name of currently unmarshalled
* XML policy model element. Throws exception, if the two FQNs are not equal as expected.
*
* @param expected The expected element name.
* @param element The actual element.
* @throws PolicyException If the actual element name did not match the expected element.
*/
private void checkEndTagName(final QName expected, final EndElement element) throws PolicyException {
final QName actual = element.getName();
if (!expected.equals(actual)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0003_UNMARSHALLING_FAILED_END_TAG_DOES_NOT_MATCH(expected, actual)));
}
}
private StringBuilder processCharacters(final ModelNode.Type currentNodeType, final Characters characters,
final StringBuilder currentValueBuffer)
throws PolicyException {
if (characters.isWhiteSpace()) {
return currentValueBuffer;
} else {
final StringBuilder buffer = (currentValueBuffer == null) ? new StringBuilder() : currentValueBuffer;
final String data = characters.getData();
if (currentNodeType == ModelNode.Type.ASSERTION || currentNodeType == ModelNode.Type.ASSERTION_PARAMETER_NODE) {
return buffer.append(data);
} else {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0009_UNEXPECTED_CDATA_ON_SOURCE_MODEL_NODE(currentNodeType, data)));
}
}
}
/**
* Return true if the value is "true" or "1". Return false if the value is
* "false" or "0". Throw an exception otherwise. The test is case sensitive.
*
* @param value The String representation of the value. Must not be null.
* @return True if the value is "true" or "1". False if the value is
* "false" or "0".
* @throws PolicyException If the value is not "true", "false", "0" or "1".
*/
private boolean parseBooleanValue(String value) throws PolicyException {
if ("true".equals(value) || "1".equals(value)) {
return true;
}
else if ("false".equals(value) || "0".equals(value)) {
return false;
}
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0095_INVALID_BOOLEAN_VALUE(value)));
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel.attach;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.MessageFormat;
import java.util.ResourceBundle;
import java.util.WeakHashMap;
/**
* Simple utility ensuring that the value is cached only in case it is non-internal implementation
*/
abstract class ContextClassloaderLocal<V> {
private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
private WeakHashMap<ClassLoader, V> CACHE = new WeakHashMap<ClassLoader, V>();
public V get() throws Error {
ClassLoader tccl = getContextClassLoader();
V instance = CACHE.get(tccl);
if (instance == null) {
instance = createNewInstance();
CACHE.put(tccl, instance);
}
return instance;
}
public void set(V instance) {
CACHE.put(getContextClassLoader(), instance);
}
protected abstract V initialValue() throws Exception;
private V createNewInstance() {
try {
return initialValue();
} catch (Exception e) {
throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
}
}
private static String format(String property, Object... args) {
String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
return MessageFormat.format(text, args);
}
private static ClassLoader getContextClassLoader() {
return (ClassLoader)
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ClassLoader cl = null;
try {
cl = Thread.currentThread().getContextClassLoader();
} catch (SecurityException ex) {
}
return cl;
}
});
}
}

View File

@@ -0,0 +1,248 @@
/*
* Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel.attach;
import com.sun.xml.internal.ws.policy.Policy;
import com.sun.xml.internal.ws.policy.PolicyConstants;
import com.sun.xml.internal.ws.policy.PolicyException;
import com.sun.xml.internal.ws.policy.privateutil.LocalizationMessages;
import com.sun.xml.internal.ws.policy.privateutil.PolicyLogger;
import com.sun.xml.internal.ws.policy.sourcemodel.PolicyModelTranslator;
import com.sun.xml.internal.ws.policy.sourcemodel.PolicyModelUnmarshaller;
import com.sun.xml.internal.ws.policy.sourcemodel.PolicySourceModel;
import java.io.Reader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.stream.Location;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
/**
* Unmarshal external policy attachments.
*
* @author Fabian Ritzmann
*/
public class ExternalAttachmentsUnmarshaller {
private static final PolicyLogger LOGGER = PolicyLogger.getLogger(ExternalAttachmentsUnmarshaller.class);
public static final URI BINDING_ID;
public static final URI BINDING_OPERATION_ID;
public static final URI BINDING_OPERATION_INPUT_ID;
public static final URI BINDING_OPERATION_OUTPUT_ID;
public static final URI BINDING_OPERATION_FAULT_ID;
static {
try {
BINDING_ID = new URI("urn:uuid:c9bef600-0d7a-11de-abc1-0002a5d5c51b");
BINDING_OPERATION_ID = new URI("urn:uuid:62e66b60-0d7b-11de-a1a2-0002a5d5c51b");
BINDING_OPERATION_INPUT_ID = new URI("urn:uuid:730d8d20-0d7b-11de-84e9-0002a5d5c51b");
BINDING_OPERATION_OUTPUT_ID = new URI("urn:uuid:85b0f980-0d7b-11de-8e9d-0002a5d5c51b");
BINDING_OPERATION_FAULT_ID = new URI("urn:uuid:917cb060-0d7b-11de-9e80-0002a5d5c51b");
} catch (URISyntaxException e) {
throw LOGGER.logSevereException(new IllegalArgumentException(LocalizationMessages.WSP_0094_INVALID_URN()), e);
}
}
private static final QName POLICY_ATTACHMENT = new QName("http://www.w3.org/ns/ws-policy", "PolicyAttachment");
private static final QName APPLIES_TO = new QName("http://www.w3.org/ns/ws-policy", "AppliesTo");
private static final QName POLICY = new QName("http://www.w3.org/ns/ws-policy", "Policy");
private static final QName URI = new QName("http://www.w3.org/ns/ws-policy", "URI");
private static final QName POLICIES = new QName(PolicyConstants.SUN_MANAGEMENT_NAMESPACE, "Policies");
private static final ContextClassloaderLocal<XMLInputFactory> XML_INPUT_FACTORY = new ContextClassloaderLocal<XMLInputFactory>() {
@Override
protected XMLInputFactory initialValue() throws Exception {
return XMLInputFactory.newInstance();
}
};
private static final PolicyModelUnmarshaller POLICY_UNMARSHALLER = PolicyModelUnmarshaller.getXmlUnmarshaller();
private final Map<URI, Policy> map = new HashMap<URI, Policy>();
private URI currentUri = null;
private Policy currentPolicy = null;
public static Map<URI, Policy> unmarshal(final Reader source) throws PolicyException {
LOGGER.entering(source);
try {
XMLEventReader reader = XML_INPUT_FACTORY.get().createXMLEventReader(source);
ExternalAttachmentsUnmarshaller instance = new ExternalAttachmentsUnmarshaller();
final Map<URI, Policy> map = instance.unmarshal(reader, null);
LOGGER.exiting(map);
return Collections.unmodifiableMap(map);
} catch (XMLStreamException ex) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0086_FAILED_CREATE_READER(source)), ex);
}
}
private Map<URI, Policy> unmarshal(final XMLEventReader reader, final StartElement parentElement) throws PolicyException {
XMLEvent event = null;
while (reader.hasNext()) {
try {
event = reader.peek();
switch (event.getEventType()) {
case XMLStreamConstants.START_DOCUMENT:
case XMLStreamConstants.COMMENT:
reader.nextEvent();
break;
case XMLStreamConstants.CHARACTERS:
processCharacters(event.asCharacters(), parentElement, map);
reader.nextEvent();
break;
case XMLStreamConstants.END_ELEMENT:
processEndTag(event.asEndElement(), parentElement);
reader.nextEvent();
return map;
case XMLStreamConstants.START_ELEMENT:
final StartElement element = event.asStartElement();
processStartTag(element, parentElement, reader, map);
break;
case XMLStreamConstants.END_DOCUMENT:
return map;
default:
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0087_UNKNOWN_EVENT(event)));
}
} catch (XMLStreamException e) {
final Location location = event == null ? null : event.getLocation();
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0088_FAILED_PARSE(location)), e);
}
}
return map;
}
private void processStartTag(final StartElement element, final StartElement parent,
final XMLEventReader reader, final Map<URI, Policy> map)
throws PolicyException {
try {
final QName name = element.getName();
if (parent == null) {
if (!name.equals(POLICIES)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<Policies>", name, element.getLocation())));
}
} else {
final QName parentName = parent.getName();
if (parentName.equals(POLICIES)) {
if (!name.equals(POLICY_ATTACHMENT)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<PolicyAttachment>", name, element.getLocation())));
}
} else if (parentName.equals(POLICY_ATTACHMENT)) {
if (name.equals(POLICY)) {
readPolicy(reader);
return;
} else if (!name.equals(APPLIES_TO)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<AppliesTo> or <Policy>", name, element.getLocation())));
}
} else if (parentName.equals(APPLIES_TO)) {
if (!name.equals(URI)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<URI>", name, element.getLocation())));
}
} else {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0090_UNEXPECTED_ELEMENT(name, element.getLocation())));
}
}
reader.nextEvent();
this.unmarshal(reader, element);
} catch (XMLStreamException e) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0088_FAILED_PARSE(element.getLocation()), e));
}
}
private void readPolicy(final XMLEventReader reader) throws PolicyException {
final PolicySourceModel policyModel = POLICY_UNMARSHALLER.unmarshalModel(reader);
final PolicyModelTranslator translator = PolicyModelTranslator.getTranslator();
final Policy policy = translator.translate(policyModel);
if (this.currentUri != null) {
map.put(this.currentUri, policy);
this.currentUri = null;
this.currentPolicy = null;
}
else {
this.currentPolicy = policy;
}
}
private void processEndTag(EndElement element, StartElement startElement) throws PolicyException {
checkEndTagName(startElement.getName(), element);
}
private void checkEndTagName(final QName expectedName, final EndElement element) throws PolicyException {
final QName actualName = element.getName();
if (!expectedName.equals(actualName)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0091_END_ELEMENT_NO_MATCH(expectedName, element, element.getLocation())));
}
}
private void processCharacters(final Characters chars, final StartElement currentElement, final Map<URI, Policy> map)
throws PolicyException {
if (chars.isWhiteSpace()) {
return;
}
else {
final String data = chars.getData();
if ((currentElement != null) && URI.equals(currentElement.getName())) {
processUri(chars, map);
return;
} else {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0092_CHARACTER_DATA_UNEXPECTED(currentElement, data, chars.getLocation())));
}
}
}
private void processUri(final Characters chars, final Map<URI, Policy> map) throws PolicyException {
final String data = chars.getData().trim();
try {
final URI uri = new URI(data);
if (this.currentPolicy != null) {
map.put(uri, this.currentPolicy);
this.currentUri = null;
this.currentPolicy = null;
} else {
this.currentUri = uri;
}
} catch (URISyntaxException e) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0093_INVALID_URI(data, chars.getLocation())), e);
}
}
}

View File

@@ -0,0 +1,31 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel.attach;
/**
* Implements utility routines to parse external policy attachments as defined
* by WS-PolicyAttachment.
*/

View File

@@ -0,0 +1,30 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* The part of public policy API that defines the classes and interfaces dealing with
* the policy tree structure (policy source model) creation and manipulation.
*/
package com.sun.xml.internal.ws.policy.sourcemodel;

View File

@@ -0,0 +1,169 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel.wspolicy;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.xml.namespace.QName;
/**
*
* @author Marek Potociar (marek.potociar at sun.com)
*/
public enum NamespaceVersion {
v1_2("http://schemas.xmlsoap.org/ws/2004/09/policy", "wsp1_2", new XmlToken[] {
XmlToken.Policy,
XmlToken.ExactlyOne,
XmlToken.All,
XmlToken.PolicyReference,
XmlToken.UsingPolicy,
XmlToken.Name,
XmlToken.Optional,
XmlToken.Ignorable,
XmlToken.PolicyUris,
XmlToken.Uri,
XmlToken.Digest,
XmlToken.DigestAlgorithm
}),
v1_5("http://www.w3.org/ns/ws-policy", "wsp", new XmlToken[] {
XmlToken.Policy,
XmlToken.ExactlyOne,
XmlToken.All,
XmlToken.PolicyReference,
XmlToken.UsingPolicy,
XmlToken.Name,
XmlToken.Optional,
XmlToken.Ignorable,
XmlToken.PolicyUris,
XmlToken.Uri,
XmlToken.Digest,
XmlToken.DigestAlgorithm
});
/**
* Resolves URI represented as a String into an enumeration value. If the URI
* doesn't represent any existing enumeration value, method returns
* {@code null}.
*
* @param uri WS-Policy namespace URI
* @return Enumeration value that represents given URI or {@code null} if
* no enumeration value exists for given URI.
*/
public static NamespaceVersion resolveVersion(String uri) {
for (NamespaceVersion namespaceVersion : NamespaceVersion.values()) {
if (namespaceVersion.toString().equalsIgnoreCase(uri)) {
return namespaceVersion;
}
}
return null;
}
/**
* Resolves fully qualified name defined in the WS-Policy namespace into an
* enumeration value. If the URI in the name doesn't represent any existing
* enumeration value, method returns {@code null}
*
* @param name fully qualified name defined in the WS-Policy namespace
* @return Enumeration value that represents given namespace or {@code null} if
* no enumeration value exists for given namespace.
*/
public static NamespaceVersion resolveVersion(QName name) {
return resolveVersion(name.getNamespaceURI());
}
/**
* Returns latest supported version of the policy namespace
*
* @return latest supported policy namespace version.
*/
public static NamespaceVersion getLatestVersion() {
return v1_5;
}
/**
* Resolves FQN into a policy XML token. The version of the token can be determined
* by invoking {@link #resolveVersion(QName)}.
*
* @param name fully qualified name defined in the WS-Policy namespace
* @return XML token enumeration that represents this fully qualified name.
* If the token or the namespace is not resolved {@link XmlToken#UNKNOWN} value
* is returned.
*/
public static XmlToken resolveAsToken(QName name) {
NamespaceVersion nsVersion = resolveVersion(name);
if (nsVersion != null) {
XmlToken token = XmlToken.resolveToken(name.getLocalPart());
if (nsVersion.tokenToQNameCache.containsKey(token)) {
return token;
}
}
return XmlToken.UNKNOWN;
}
private final String nsUri;
private final String defaultNsPrefix;
private final Map<XmlToken, QName> tokenToQNameCache;
private NamespaceVersion(String uri, String prefix, XmlToken... supportedTokens) {
nsUri = uri;
defaultNsPrefix = prefix;
Map<XmlToken, QName> temp = new HashMap<XmlToken, QName>();
for (XmlToken token : supportedTokens) {
temp.put(token, new QName(nsUri, token.toString()));
}
tokenToQNameCache = Collections.unmodifiableMap(temp);
}
/**
* Method returns default namespace prefix for given namespace version.
*
* @return default namespace prefix for given namespace version
*/
public String getDefaultNamespacePrefix() {
return defaultNsPrefix;
}
/**
* Resolves XML token into a fully qualified name within given namespace version.
*
* @param token XML token enumeration value.
* @return fully qualified name of the {@code token} within given namespace
* version. Method returns {@code null} in case the token is not supported in
* given namespace version or in case {@link XmlToken#UNKNOWN} was used as
* an input parameter.
*/
public QName asQName(XmlToken token) throws IllegalArgumentException {
return tokenToQNameCache.get(token);
}
@Override
public String toString() {
return nsUri;
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.policy.sourcemodel.wspolicy;
/**
*
* @author Marek Potociar (marek.potociar at sun.com)
*/
public enum XmlToken {
Policy("Policy", true),
ExactlyOne("ExactlyOne", true),
All("All", true),
PolicyReference("PolicyReference", true),
UsingPolicy("UsingPolicy", true),
Name("Name", false),
Optional("Optional", false),
Ignorable("Ignorable", false),
PolicyUris("PolicyURIs", false),
Uri("URI", false),
Digest("Digest", false),
DigestAlgorithm("DigestAlgorithm", false),
UNKNOWN("", true);
/**
* Resolves URI represented as a String into an enumeration value. If the URI
* doesn't represent any existing enumeration value, method returns {@code null}
*
* @param uri
* @return Enumeration value that represents given URI or {@code null} if
* no enumeration value exists for given URI.
*/
public static XmlToken resolveToken(String name) {
for (XmlToken token : XmlToken.values()) {
if (token.toString().equals(name)) {
return token;
}
}
return UNKNOWN;
}
private String tokenName;
private boolean element;
private XmlToken(final String name, boolean element) {
this.tokenName = name;
this.element = element;
}
public boolean isElement() {
return element;
}
@Override
public String toString() {
return tokenName;
}
}