You are viewing a plain text version of this content. The canonical link for it is here.
Posted to fx-dev@ws.apache.org by di...@apache.org on 2004/08/11 15:37:05 UTC

cvs commit: ws-fx/wss4j/src/org/apache/ws/security/trust2 Lifetime.java RequestSecurityToken.java RequestSecurityTokenResponse.java SecurityTokenMessage.java SecurityTokenOrReference.java TokenTypes.java TrustConstants.java WSAddTokenRequest.java

dims        2004/08/11 06:37:05

  Added:       wss4j/src/org/apache/ws/security/trust2 Lifetime.java
                        RequestSecurityToken.java
                        RequestSecurityTokenResponse.java
                        SecurityTokenMessage.java
                        SecurityTokenOrReference.java TokenTypes.java
                        TrustConstants.java WSAddTokenRequest.java
  Log:
  Porting David Del Vecchio's code in anticipation of merging this with our code. (http://article.gmane.org/gmane.comp.apache.webservices.fx.devel/1129)
  
  Revision  Changes    Path
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/trust2/Lifetime.java
  
  Index: Lifetime.java
  ===================================================================
  /*
   * Copyright  2003-2004 The Apache Software Foundation.
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   *
   */
  
  package org.apache.ws.security.trust2;
  
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.WSSConfig;
  import org.apache.ws.security.message.token.Timestamp;
  import org.apache.ws.security.util.WSSecurityUtil;
  import org.w3c.dom.Attr;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.NamedNodeMap;
  
  import java.text.SimpleDateFormat;
  import java.util.Calendar;
  import java.util.Date;
  import java.util.TimeZone;
  
  /**
   * @author ddelvecc
   *         <p/>
   *         For indicating the <Lifetime> associated with a token request or response.
   *         This usually includes wsu:Created and wsu:Expires elements
   */
  public class Lifetime extends Timestamp {
  
      /**
       * @param element
       * @throws org.apache.ws.security.WSSecurityException
       *
       */
      public Lifetime(WSSConfig wssConfig, Document doc, Element element) throws WSSecurityException {
          super(wssConfig, element);
          this.element = copyElement(doc, element);
      }
  
      /**
       * @param doc      The XML document to be used for element creation
       * @param duration Indicates how many seconds in the future this Lifetime Expires
       */
      public Lifetime(WSSConfig wssConfig, Document doc, int duration) {
          super(wssConfig, doc, duration);
          element = changeElementName(element, TrustConstants.WST_NS, TrustConstants.WST_PREFIX + TrustConstants.LIFETIME);
      }
  
      /**
       * Constructs a <code>Lifetime</code> object according
       * to the defined parameters.
       * <p/>
       *
       * @param doc     The SOAP envelope as <code>Document</code>
       * @param created The creation time for this lifetime
       * @param expires When this lifetime expires
       */
      public Lifetime(WSSConfig wssConfig, Document doc, Date created, Date expires) {
          super(wssConfig, doc, 0);
  
          element = doc.createElementNS(TrustConstants.WST_NS, TrustConstants.WST_PREFIX + TrustConstants.LIFETIME);
          WSSecurityUtil.setNamespace(element, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
  
          SimpleDateFormat zulu = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
          zulu.setTimeZone(TimeZone.getTimeZone("GMT"));
          Calendar rightNow = Calendar.getInstance();
          if (created == null)
              created = rightNow.getTime();
  
          elementCreated = doc.createElementNS(WSConstants.WSU_NS, WSConstants.WSU_PREFIX + ":" + WSConstants.CREATED_LN);
          WSSecurityUtil.setNamespace(elementCreated, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
          elementCreated.appendChild(doc.createTextNode(zulu.format(created)));
          element.appendChild(elementCreated);
  
          if (expires == null)
              expires = created;
  
          elementExpires = doc.createElementNS(WSConstants.WSU_NS, WSConstants.WSU_PREFIX + ":" + WSConstants.EXPIRES_LN);
          WSSecurityUtil.setNamespace(elementExpires, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
          elementExpires.appendChild(doc.createTextNode(zulu.format(expires)));
          element.appendChild(elementExpires);
  
          this.created = Calendar.getInstance();
          this.expires = Calendar.getInstance();
          this.created.setTime(created);
          this.expires.setTime(expires);
      }
  
      public Element getElement(Document doc) {
          return copyElement(doc, element);
      }
  
      protected Element copyElement(Document doc, Element oldElement) {
          // Make a copy of the element subtree suitable for inserting into doc
          return (Element) doc.importNode(oldElement, true);
      }
  
      protected Element changeElementName(Document doc, Element oldElement, String newNamespace, String newQualName) {
          // Create an element with the new name
          Element element2 = doc.createElementNS(newNamespace, newQualName);
      
          // Copy the attributes to the new element
          NamedNodeMap attrs = oldElement.getAttributes();
          for (int i = 0; i < attrs.getLength(); i++) {
              Attr attr2 = (Attr) doc.importNode(attrs.item(i), true);
              element2.getAttributes().setNamedItem(attr2);
          }
      
          // Move all the children
          while (oldElement.hasChildNodes()) {
              element2.appendChild(oldElement.getFirstChild());
          }
  
          return element2;
      }
  
      protected Element changeElementName(Element oldElement, String newNamespace, String newQualName) {
          return changeElementName(oldElement.getOwnerDocument(), oldElement, newNamespace, newQualName);
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/trust2/RequestSecurityToken.java
  
  Index: RequestSecurityToken.java
  ===================================================================
  /*
   * Copyright  2003-2004 The Apache Software Foundation.
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   *
   */
  
  package org.apache.ws.security.trust2;
  
  import org.apache.ws.security.trust2.exception.ElementParsingException;
  import org.apache.ws.security.trust2.exception.NoRequestType;
  import org.apache.ws.security.trust2.exception.TrustException;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.NodeList;
  
  import java.net.URI;
  import java.net.URISyntaxException;
  import java.util.ArrayList;
  import java.util.Iterator;
  import java.util.List;
  
  public class RequestSecurityToken extends SecurityTokenMessage {
  
      protected URI requestType = null;
  
      protected SecurityTokenOrReference base = null;
      protected List supporting = new ArrayList();
  
      public RequestSecurityToken(Document doc, URI requestType) {
          super(doc);
          this.requestType = requestType;
      }
  
      /**
       * Constructs a RequestSecurityToken object from an existing element.
       *
       * @param element
       */
      public RequestSecurityToken(Element element) throws ElementParsingException {
          super(element);
          initialize(element);
      }
  
      public RequestSecurityToken(Element element, Document document) throws ElementParsingException {
          super(element, document);
          initialize(element);
      }
  
      private void initialize(Element element) throws ElementParsingException {
          ArrayList elements = (ArrayList) customElements.clone();
          customElements.clear();
  
          for (int i = 0; i < elements.size(); i++) {
              Element currentNode = (Element) elements.get(i);
  
              if (!TrustConstants.WST_NS.equals(currentNode.getNamespaceURI())) {
                  addCustomElement(currentNode);
                  continue;
              } else if (currentNode.getLocalName().equals(TrustConstants.REQUEST_TYPE)) {
                  String textContent = getTextContent(currentNode);
                  if (textContent != null && !textContent.equals("")) {
                      try {
                          setRequestType(new URI(textContent));
                      } catch (URISyntaxException e) {
                          throw new ElementParsingException("URISyntaxException while creating RequestSecurityToken (RequestType) from XML Element: "
                                  + e.getMessage());
                      }
                  }
              } else if (currentNode.getLocalName().equals(TrustConstants.BASE)) {
                  Element elem = getFirstNonBlankChildAsElement(currentNode);
                  if (elem != null)
                      setBase(new SecurityTokenOrReference(elem, doc));
              } else if (currentNode.getLocalName().equals(TrustConstants.SUPPORTING)) {
                  NodeList supportingNodes = currentNode.getChildNodes();
                  if (supportingNodes != null) {
                      for (int j = 0; j < supportingNodes.getLength(); j++)
                          if (supportingNodes.item(j).getLocalName() != null)
                              addSupporting(new SecurityTokenOrReference((Element) supportingNodes.item(j), doc));
                  }
              } else {
                  addCustomElement(currentNode);
              }
          }
      }
  
      public void setRequestType(URI requestType) {
          this.requestType = requestType;
      }
  
      public URI getRequestType() {
          return requestType;
      }
  
      public void setBase(SecurityTokenOrReference base) {
          this.base = base;
      }
  
      public SecurityTokenOrReference getBase() {
          return base;
      }
  
      public void addSupporting(SecurityTokenOrReference supportingToken) {
          supporting.add(supportingToken);
      }
  
      public List getSupporting() {
          return supporting;
      }
  
      public Element getElement() throws TrustException {
          Element wstElement = getElement(TrustConstants.WST_PREFIX + TrustConstants.REQUEST_TAG);
  
          if (requestType != null) {
              Element requestTypeElement = doc.createElementNS(TrustConstants.WST_NS, TrustConstants.WST_PREFIX + TrustConstants.REQUEST_TYPE);
              setTextContent(requestTypeElement, requestType.toString());
              wstElement.appendChild(requestTypeElement);
          } else {
              throw new NoRequestType("RequestType is a required element that cannot be null.");
          }
  
          if (base != null) {
              wstElement.appendChild(createTokenOrReferenceElement(TrustConstants.WST_PREFIX + TrustConstants.BASE, base));
          }
  
          if (!supporting.isEmpty()) {
              Element supportingElement = doc.createElementNS(TrustConstants.WST_NS, TrustConstants.WST_PREFIX + TrustConstants.SUPPORTING);
  
              for (Iterator itr = supporting.iterator(); itr.hasNext();) {
                  SecurityTokenOrReference next = (SecurityTokenOrReference) itr.next();
                  supportingElement.appendChild(next.getElement());
              }
  
              wstElement.appendChild(supportingElement);
          }
          return wstElement;
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/trust2/RequestSecurityTokenResponse.java
  
  Index: RequestSecurityTokenResponse.java
  ===================================================================
  /*
   * Copyright  2003-2004 The Apache Software Foundation.
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   *
   */
  
  package org.apache.ws.security.trust2;
  
  import org.apache.ws.security.trust2.exception.ElementParsingException;
  import org.apache.ws.security.trust2.exception.NoTokenInResponse;
  import org.apache.ws.security.trust2.exception.TrustException;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  
  import java.util.ArrayList;
  
  /**
   * @author ddelvecc
   *         <p/>
   *         Represents the WS-Trust <RequestSecurityTokenResponse> message which includes the requested token.
   */
  public class RequestSecurityTokenResponse extends SecurityTokenMessage {
  
      protected SecurityTokenOrReference requestedSecurityToken = null;
      protected SecurityTokenOrReference requestedProofToken = null;
  
      public RequestSecurityTokenResponse(Document doc) {
          super(doc);
      }
  
      public RequestSecurityTokenResponse(Document doc, SecurityTokenOrReference requestedSecurityToken) {
          super(doc);
          this.requestedSecurityToken = requestedSecurityToken;
      }
  
      /**
       * Constructs a RequestSecurityToken object from an existing element.
       *
       * @param element
       */
      public RequestSecurityTokenResponse(Element element) throws ElementParsingException {
          super(element);
          initialize();
      }
  
      public RequestSecurityTokenResponse(Element element, Document document) throws ElementParsingException {
          super(element, document);
          initialize();
      }
  
      private void initialize() throws ElementParsingException {
          ArrayList elements = (ArrayList) customElements.clone();
          customElements.clear();
  
          for (int i = 0; i < elements.size(); i++) {
              Element currentNode = (Element) elements.get(i);
  
              if (!TrustConstants.WST_NS.equals(currentNode.getNamespaceURI())) {
                  addCustomElement(currentNode);
                  continue;
              } else if (currentNode.getLocalName().equals(TrustConstants.REQUESTED_TOKEN)) {
                  Element elem = getFirstNonBlankChildAsElement(currentNode);
                  if (elem != null)
                      setRequestedSecurityToken(new SecurityTokenOrReference(elem, doc));
              } else if (currentNode.getLocalName().equals(TrustConstants.REQUESTED_PROOF)) {
                  Element elem = getFirstNonBlankChildAsElement(currentNode);
                  if (elem != null)
                      setRequestedProofToken(new SecurityTokenOrReference(elem, doc));
              } else
                  addCustomElement(currentNode);
          }
      }
  
      public SecurityTokenOrReference getRequestedSecurityToken() {
          return requestedSecurityToken;
      }
  
      public void setRequestedSecurityToken(SecurityTokenOrReference requestedToken) {
          this.requestedSecurityToken = requestedToken;
      }
  
      public SecurityTokenOrReference getRequestedProofToken() {
          return requestedProofToken;
      }
  
      public void setRequestedProofToken(SecurityTokenOrReference requestedProofToken) {
          this.requestedProofToken = requestedProofToken;
      }
  
      public Element getElement() throws TrustException {
          Element wstElement = getElement(TrustConstants.WST_PREFIX + TrustConstants.RESPONSE_TAG);
  
          if ((requestedSecurityToken == null) && (requestedProofToken == null))
              throw new NoTokenInResponse("Either a RequestedSecurityToken or a RequestedProofToken is required. Both cannot be null.");
          else if (requestedSecurityToken != null)
              wstElement.appendChild(createTokenOrReferenceElement(TrustConstants.WST_PREFIX + TrustConstants.REQUESTED_TOKEN,
                      requestedSecurityToken));
          else if (requestedProofToken != null)
              wstElement.appendChild(createTokenOrReferenceElement(TrustConstants.WST_PREFIX + TrustConstants.REQUESTED_PROOF,
                      requestedSecurityToken));
  
          return wstElement;
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/trust2/SecurityTokenMessage.java
  
  Index: SecurityTokenMessage.java
  ===================================================================
  /*
   * Copyright  2003-2004 The Apache Software Foundation.
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   *
   */
  
  package org.apache.ws.security.trust2;
  
  import org.apache.ws.security.trust2.exception.ElementParsingException;
  import org.apache.ws.security.trust2.exception.EmptyTokenOrReference;
  import org.apache.ws.security.trust2.exception.TrustException;
  import org.apache.axis.utils.DOM2Writer;
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.WSSConfig;
  import org.w3c.dom.Attr;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  import org.w3c.dom.NodeList;
  
  import java.net.URI;
  import java.net.URISyntaxException;
  import java.util.ArrayList;
  import java.util.Iterator;
  import java.util.List;
  
  /**
   * @author ddelvecc
   *         <p/>
   *         A base class for WS-Trust messages such as <RequestSecurityToken> and <RequestSecurityTokenResponse>.
   */
  public abstract class SecurityTokenMessage {
  
      protected URI context = null;
      protected URI tokenType = null;
      protected URI keyType;
  
      protected int keySize;
      protected URI signatureAlgorithm;
      protected SecurityTokenOrReference encryption;
      protected SecurityTokenOrReference proofEncryption;
      protected Lifetime lifetime = null;
  
      protected ArrayList customElements = new ArrayList();
  
      protected Element element;
      protected Document doc;
  
      /**
       * Constructs a SecurityTokenMessage object from an existing element.
       *
       * @param element
       */
      public SecurityTokenMessage(Element element) throws ElementParsingException {
          if (element != null) {
              this.doc = element.getOwnerDocument();
              initialize(element);
          }
      }
  
      public SecurityTokenMessage(Element element, Document doc) throws ElementParsingException {
          if (element != null) {
              this.doc = doc;
              initialize(element);
          }
      }
  
      private void initialize(Element element) throws ElementParsingException {
          try {
              Attr context = element.getAttributeNodeNS(TrustConstants.WST_NS, TrustConstants.CONTEXT_ATTR);
  
              if (context != null)
                  setContext(new URI(context.getValue()));
  
              NodeList childNodes = element.getChildNodes();
              if (childNodes != null) {
                  for (int i = 0; i < childNodes.getLength(); i++) {
                      Node currentNode = childNodes.item(i);
                      if (!TrustConstants.WST_NS.equals(currentNode.getNamespaceURI())) {
                          if (currentNode instanceof Element)
                              addCustomElement((Element) currentNode);
                          continue;
                      } else if (currentNode.getLocalName().equals(TrustConstants.TOKEN_TYPE)) {
                          String textContent = getTextContent(currentNode);
                          if (textContent != null && !textContent.equals(""))
                              setTokenType(new URI(textContent));
                      } else if (currentNode.getLocalName().equals(TrustConstants.LIFETIME) ||
                              (TrustConstants.MS_COMPATIBLE_LIFETIMES && currentNode.getLocalName().equals(TrustConstants.LIFETIME_MS))) {
  
                          lifetime = new Lifetime(WSSConfig.getDefaultWSConfig(), doc, (Element) currentNode);
                      } else {
                          if (currentNode instanceof Element)
                              addCustomElement((Element) currentNode);
                      }
                  }
              }
          } catch (URISyntaxException e) {
              throw new ElementParsingException("URISyntaxException while creating SecurityTokenMessage from XML element: " + e.getMessage());
          } catch (WSSecurityException e) {
              throw new ElementParsingException("WSSecurityException while creating SecurityTokenMessage from XML element: " + e.getMessage());
          }
      }
  
      public SecurityTokenMessage(Document doc) {
          this.doc = doc;
      }
  
      public void setDocument(Document doc) {
          this.doc = doc;
      }
  
      public Document getDocument() {
          return doc;
      }
  
      public void setContext(URI context) {
          this.context = context;
      }
  
      public URI getContext() {
          return context;
      }
  
      public void setTokenType(URI tokenType) {
          this.tokenType = tokenType;
      }
  
      public URI getTokenType() {
          return tokenType;
      }
  
      public void addCustomElement(Element element) {
          customElements.add(element);
      }
  
      public Element addCustomElement(String tagName) {
          Element element = doc.createElement(tagName);
          addCustomElement(element);
          return element;
      }
  
      public Element addCustomElementNS(String namespaceUri, String qualifiedName) {
          Element element = doc.createElementNS(namespaceUri, qualifiedName);
          addCustomElement(element);
          return element;
      }
  
      public List getCustomElements() {
          return customElements;
      }
  
      public Element getCustomElement(String namespaceUri, String localName) {
          Element currentElement;
          for (Iterator itr = customElements.iterator(); itr.hasNext();) {
              currentElement = (Element) itr.next();
              String elementNs = currentElement.getNamespaceURI();
              if ((namespaceUri == null && elementNs == null) || (namespaceUri != null && namespaceUri.equals(elementNs))) {
                  String elementLocalName = currentElement.getLocalName();
                  if ((localName == null && elementLocalName == null) || (localName != null && localName.equals(elementLocalName)))
                      return currentElement;
              }
          }
          return null;
      }
  
      public void setLifetime(Lifetime lifetime) {
          this.lifetime = lifetime;
      }
  
      public Lifetime getLifetime() {
          return lifetime;
      }
  
      public abstract Element getElement() throws TrustException;
  
      protected Element getElement(String tagName) throws TrustException {
          element = doc.createElementNS(TrustConstants.WST_NS, tagName);
          if (context != null) {
              element.setAttributeNS(TrustConstants.WST_NS, TrustConstants.WST_PREFIX + TrustConstants.CONTEXT_ATTR, context.toString());
          }
  
          if (tokenType != null) {
              Element tokenTypeElement = doc.createElementNS(TrustConstants.WST_NS, TrustConstants.WST_PREFIX + TrustConstants.TOKEN_TYPE);
              setTextContent(tokenTypeElement, tokenType.toString());
              element.appendChild(tokenTypeElement);
          }
  
          for (Iterator itr = customElements.iterator(); itr.hasNext();) {
              element.appendChild((Element) itr.next());
          }
  
          if (lifetime != null) {
              element.appendChild(lifetime.getElement());
          }
  
          return element;
      }
  
      protected Element createTokenOrReferenceElement(String enclosingTagName, SecurityTokenOrReference token) throws TrustException {
          Element element = doc.createElementNS(TrustConstants.WST_NS, enclosingTagName);
          Element tokenElement = token.getElement();
          if (tokenElement == null)
              throw new EmptyTokenOrReference("SecurityTokenOrReference specified does not contain " +
                      "a security token element or reference element.");
          element.appendChild(tokenElement);
          return element;
      }
  
      /**
       * Adds a text child node to the given element.
       *
       * @param element The element to add text to
       * @param string  The text string to add
       */
      protected void setTextContent(Element element, String string) {
          Node textNode = doc.createTextNode(string);
          element.appendChild(textNode);
      }
  
      protected String getTextContent(Node currentNode) {
          NodeList nodes = currentNode.getChildNodes();
          for (int j = 0; j < nodes.getLength(); j++) {
              if (nodes.item(j).getNodeValue() != null)
                  return nodes.item(j).getNodeValue();
          }
          return null;
      }
  
      protected Element getFirstNonBlankChildAsElement(Node currentNode) {
          NodeList nodes = currentNode.getChildNodes();
          for (int j = 0; j < nodes.getLength(); j++) {
              if (nodes.item(j).getLocalName() != null)
                  return (Element) nodes.item(j);
          }
          return null;
      }
  
      public String toString() {
          try {
              return DOM2Writer.nodeToString(getElement(), true);
          } catch (TrustException e) {
              return "TrustException when trying to convert to String: " + e.getMessage();
          }
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/trust2/SecurityTokenOrReference.java
  
  Index: SecurityTokenOrReference.java
  ===================================================================
  /*
   * Copyright  2003-2004 The Apache Software Foundation.
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   *
   */
  
  
  package org.apache.ws.security.trust2;
  
  import org.apache.ws.security.trust2.exception.ElementParsingException;
  import org.apache.ws.security.trust2.exception.InvalidSecurityTokenReference;
  import org.apache.ws.security.trust2.exception.TrustException;
  import org.apache.ws.security.WSSecurityException;
  import org.apache.ws.security.WSSConfig;
  import org.apache.ws.security.message.token.BinarySecurity;
  import org.apache.ws.security.message.token.SecurityTokenReference;
  import org.apache.ws.security.message.token.UsernameToken;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  
  import javax.xml.namespace.QName;
  
  /**
   * @author ddelvecc
   *         <p/>
   *         A class to hold either a security token of some kind (UsernameToken, BinarySecurityToken, etc.)
   *         or a SecurityTokenReference.
   */
  public class SecurityTokenOrReference {
  
      protected Document doc = null;
  
      protected SecurityTokenReference reference = null;
      protected UsernameToken usernameToken = null;
      protected BinarySecurity binarySecurityToken = null;
  
      protected boolean isReference;
  
      public boolean isReference() {
          return reference != null;
      }
  
      public boolean isToken() {
          return reference == null;
      }
  
      public SecurityTokenOrReference(Element element) throws ElementParsingException {
  
          QName el = new QName(element.getNamespaceURI(), element.getLocalName());
          WSSConfig wssConfig = WSSConfig.getDefaultWSConfig();
          try {
              if (el.equals(SecurityTokenReference.SECURITY_TOKEN_REFERENCE))
                  this.reference = new SecurityTokenReference(wssConfig, element);
              if (el.equals(UsernameToken.TOKEN))
                  this.usernameToken = new UsernameToken(wssConfig, element);
              if (el.equals(BinarySecurity.TOKEN))
                  this.binarySecurityToken = new BinarySecurity(wssConfig, element);
              doc = element.getOwnerDocument();
          } catch (WSSecurityException e) {
              throw new ElementParsingException("WSSecurityException while trying to create a SecurityTokenOrReference object from an XML Element: "
                      + e.getMessage());
          }
      }
  
      public SecurityTokenOrReference(Element element, Document doc) throws ElementParsingException {
          this(element);
          this.doc = doc;
      }
  
      public SecurityTokenOrReference(SecurityTokenReference reference) {
          this.reference = reference;
      }
  
      public SecurityTokenOrReference(UsernameToken securityToken) {
          this.usernameToken = securityToken;
      }
  
      public SecurityTokenOrReference(BinarySecurity securityToken) {
          this.binarySecurityToken = securityToken;
      }
  
      public void setDocument(Document doc) {
          this.doc = doc;
      }
  
      public Element getElement() {
          if (reference != null)
              return reference.getElement();
          else
              return getTokenElement();
      }
  
      private Element getTokenElement() {
          if (usernameToken != null)
              return usernameToken.getElement();
          if (binarySecurityToken != null)
              return binarySecurityToken.getElement();
          return null;
      }
  
      public Object getTokenOrReference() throws TrustException {
          if (reference != null)
              return reference;
          return resolveToken();
      }
  
      public Object resolveToken() throws TrustException {
          if (usernameToken != null)
              return usernameToken;
          if (binarySecurityToken != null)
              return binarySecurityToken;
          if (reference != null) {
              try {
                  Element tokenElement = reference.getTokenElement(doc, null);
                  if (tokenElement != null) {
                      QName el = new QName(tokenElement.getNamespaceURI(), tokenElement.getLocalName());
                      try {
                          WSSConfig wssConfig = WSSConfig.getDefaultWSConfig();
                          if (el.equals(UsernameToken.TOKEN))
                              return new UsernameToken(wssConfig, tokenElement);
                          if (el.equals(BinarySecurity.TOKEN))
                              return new BinarySecurity(wssConfig, tokenElement);
                      } catch (WSSecurityException e) {
                          throw new ElementParsingException("WSSecurityException while trying to create a SecurityToken object from a SecurityTokenReference: "
                                  + e.getMessage());
                      }
                  }
              } catch (WSSecurityException e) {
                  throw new InvalidSecurityTokenReference("WSSecurityException while trying to dereference a <SecurityTokenReference>: " + e.getMessage());
              }
          }
          return null;
      }
  
      public SecurityTokenReference getReference() {
          return reference;
      }
  
      public UsernameToken getUsernameToken() {
          return usernameToken;
      }
  
      public BinarySecurity getBinarySecurity() {
          return binarySecurityToken;
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/trust2/TokenTypes.java
  
  Index: TokenTypes.java
  ===================================================================
  /*
   * Copyright  2003-2004 The Apache Software Foundation.
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   *
   */
  
  package org.apache.ws.security.trust2;
  
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.message.token.X509Security;
  
  import java.net.URI;
  import java.net.URISyntaxException;
  
  /**
   * @author ddelvecc
   *         <p/>
   *         A set of URI constants representing different token types defined by the WS-Security TC. These are typically used
   *         in the WS-Trust <TokenType> element.
   */
  public abstract class TokenTypes {
      public static URI USERNAME;
  
      private static final String x509prefix = WSConstants.X509TOKEN_NS;
  
      public static URI X509;
      public static URI X509PKIPATH;
      public static URI PKCS7;
  
      static {
          try {
              USERNAME = new URI(WSConstants.USERNAMETOKEN_NS + "#" + WSConstants.USERNAME_TOKEN_LN);
              X509 = new URI(WSConstants.X509TOKEN_NS + "#" + X509Security.X509_V3);
              X509PKIPATH = new URI(x509prefix + "#X509PKIPathv1");
              PKCS7 = new URI(x509prefix + "#PKCS7");
          } catch (URISyntaxException e) {
          }
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/trust2/TrustConstants.java
  
  Index: TrustConstants.java
  ===================================================================
  /*
   * Copyright  2003-2004 The Apache Software Foundation.
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   *
   */
  
  package org.apache.ws.security.trust2;
  
  import javax.xml.namespace.QName;
  import java.net.URI;
  import java.net.URISyntaxException;
  
  /**
   * @author ddelvecc
   *         <p/>
   *         WS-Trust constants.
   */
  public abstract class TrustConstants {
  
      private static final String NS_YEAR_PREFIX = "http://schemas.xmlsoap.org/ws/2004/04/";
      public static final String WST_NS = NS_YEAR_PREFIX + "trust";
      public static final String WST_PREFIX = "wst:";
  
      public static final String REQUEST_TAG = "RequestSecurityToken";
      public static final QName REQUEST_NAME = new QName(WST_NS, REQUEST_TAG, WST_PREFIX);
  
      public static final String CONTEXT_ATTR = "Context";
      public static final String TOKEN_TYPE = "TokenType";
      public static final String REQUEST_TYPE = "RequestType";
      public static final String BASE = "Base";
      public static final String SUPPORTING = "Supporting";
      public static final String LIFETIME = "Lifetime";
      public static final String LIFETIME_MS = "LifeTime";
  
      public static final boolean MS_COMPATIBLE_LIFETIMES = true;
  
      public static final String RESPONSE_TAG = "RequestSecurityTokenResponse";
      public static final QName RESPONSE_NAME = new QName(WST_NS, RESPONSE_TAG, WST_PREFIX);
  
      public static final String REQUESTED_TOKEN = "RequestedSecurityToken";
      public static final String REQUESTED_PROOF = "RequestedProofToken";
  
      public static final String WSA_NS = "http://schemas.xmlsoap.org/ws/2004/03/addressing";
      public static final String WSA_PREFIX = "wsa:";
      public static final String ACTION_TAG = "Action";
  
      private static final String SECURITY_TRUST_PREFIX = NS_YEAR_PREFIX + "security/trust/";
  
      public static URI REQUEST_ISSUE;
      public static URI REQUEST_RENEW;
      public static URI REQUEST_VALIDATE;
  
      private static final String ACTION_REQUEST_PREFIX = SECURITY_TRUST_PREFIX + "RST/";
  
      public static URI ACTION_REQUEST_ISSUE;
      public static URI ACTION_REQUEST_RENEW;
      public static URI ACTION_REQUEST_VALIDATE;
  
      private static final String ACTION_RESPONSE_PREFIX = SECURITY_TRUST_PREFIX + "RSTR/";
  
      public static URI ACTION_RESPONSE_ISSUE;
      public static URI ACTION_RESPONSE_RENEW;
      public static URI ACTION_RESPONSE_VALIDATE;
  
      static {
          try {
              REQUEST_ISSUE = new URI(SECURITY_TRUST_PREFIX + "Issue");
              REQUEST_RENEW = new URI(SECURITY_TRUST_PREFIX + "Renew");
              REQUEST_VALIDATE = new URI(SECURITY_TRUST_PREFIX + "Validate");
  
              ACTION_REQUEST_ISSUE = new URI(ACTION_REQUEST_PREFIX + "Issue");
              ACTION_REQUEST_RENEW = new URI(ACTION_REQUEST_PREFIX + "Renew");
              ACTION_REQUEST_VALIDATE = new URI(ACTION_REQUEST_PREFIX + "Validate");
  
              ACTION_RESPONSE_ISSUE = new URI(ACTION_RESPONSE_PREFIX + "Issue");
              ACTION_RESPONSE_RENEW = new URI(ACTION_RESPONSE_PREFIX + "Renew");
              ACTION_RESPONSE_VALIDATE = new URI(ACTION_RESPONSE_PREFIX + "Validate");
          } catch (URISyntaxException e) {
          }
      }
  
      public static URI getActionRequest(URI requestType) {
          if (REQUEST_ISSUE.equals(requestType))
              return ACTION_REQUEST_ISSUE;
          if (REQUEST_ISSUE.equals(requestType))
              return ACTION_REQUEST_RENEW;
          if (REQUEST_ISSUE.equals(requestType))
              return ACTION_REQUEST_VALIDATE;
          return requestType;
      }
  }
  
  
  
  1.1                  ws-fx/wss4j/src/org/apache/ws/security/trust2/WSAddTokenRequest.java
  
  Index: WSAddTokenRequest.java
  ===================================================================
  /*
   * Copyright  2003-2004 The Apache Software Foundation.
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   *
   */
  
  package org.apache.ws.security.trust2;
  
  import org.apache.ws.security.trust2.exception.NoRequestType;
  import org.apache.ws.security.trust2.exception.NoSoapBody;
  import org.apache.ws.security.trust2.exception.TrustException;
  import org.apache.axis.message.SOAPEnvelope;
  import org.apache.ws.security.SOAPConstants;
  import org.apache.ws.security.WSConstants;
  import org.apache.ws.security.WSSConfig;
  import org.apache.ws.security.message.token.UsernameToken;
  import org.apache.ws.security.util.WSSecurityUtil;
  import org.w3c.dom.DOMException;
  import org.w3c.dom.Document;
  import org.w3c.dom.Element;
  import org.w3c.dom.Node;
  
  import java.net.URI;
  
  /**
   * @author ddelvecc
   *         <p/>
   *         A class for adding a WS-Trust RequestSecurityToken element to a SOAP envelope (an XML document).
   */
  public class WSAddTokenRequest {
  
      private URI action = null;
      private RequestSecurityToken tokenRequest;
  
      public WSAddTokenRequest(RequestSecurityToken tokenRequest) {
          this.tokenRequest = tokenRequest;
      }
  
      /**
       * Adds the standard Action element corresponding to the RequestType specified in the RequestSecurityToken message being used.
       * If the request type is non-standard (not Issue, Renew, Validate), the Action URI added will be the same as the RequestType URI.
       *
       * @throws NoRequestType
       */
      public void addAction() throws NoRequestType {
          action = TrustConstants.getActionRequest(tokenRequest.getRequestType());
          if (action == null) {
              throw new NoRequestType("Cannot generate standard action element, no requestType specified.");
          }
      }
  
      /**
       * Adds a custom Action element to the SOAP header. See WS-Addressing specs for more details.
       *
       * @param action The action URI to add.
       */
      public void addAction(URI action) {
          this.action = action;
      }
  
      /**
       * Adds a new <code>RequestSecurityToken</code> to a soap envelope.
       * <p/>
       *
       * @param doc The SOAP enevlope as W3C document
       * @return Document with RequestSecurityToken added
       * @throws DOMException NoRequestType NoSoapBody
       */
      public Document build(Document doc) throws DOMException, TrustException {
          SOAPConstants soapConsts = WSSecurityUtil.getSOAPConstants(doc.getDocumentElement());
  
          if (action != null) {
              Element envelope = doc.getDocumentElement();
              Element soapHeader = (Element) WSSecurityUtil.getDirectChild(doc.getFirstChild(), soapConsts.getHeaderQName().getLocalPart(),
                      soapConsts.getEnvelopeURI());
  
              if (soapHeader == null) {
                  soapHeader = createElementInSameNamespace(envelope, soapConsts.getHeaderQName().getLocalPart());
                  soapHeader = WSSecurityUtil.prependChildElement(doc, envelope, soapHeader, true);
              }
  
              Element actionElement = doc.createElementNS(TrustConstants.WSA_NS, TrustConstants.WST_PREFIX + TrustConstants.ACTION_TAG);
              Node actionContent = doc.createTextNode(action.toString());
              actionElement.appendChild(actionContent);
              soapHeader.appendChild(actionElement);
          }
          Element soapBody = WSSecurityUtil.findBodyElement(doc, soapConsts);
          if (soapBody == null) {
              throw new NoSoapBody("A SOAP Body element is needed to insert the <RequestSecurityToken>.");
          }
  
          setWsuId(soapBody);
          if (tokenRequest != null)
              soapBody.appendChild(tokenRequest.getElement());
          return doc;
      }
  
      /**
       * create a new element in the same namespace
       * <p/>
       *
       * @param parent
       * @param localName
       * @return
       */
      private static Element createElementInSameNamespace(Element parent, String localName) {
          String prefix = parent.getPrefix();
          if (prefix == null) {
              prefix = "";
          }
          String qName = prefix + ":" + localName;
          String nsUri = parent.getNamespaceURI();
          return parent.getOwnerDocument().createElementNS(nsUri, qName);
      }
  
      private String setWsuId(Element bodyElement) {
          String id = bodyElement.getAttributeNS(WSConstants.WSU_NS, "Id");
          if ((id == null) || (id.length() == 0)) {
              id = "id-" + Integer.toString(bodyElement.hashCode());
              String prefix = WSSecurityUtil.setNamespace(bodyElement, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
              bodyElement.setAttributeNS(WSConstants.WSU_NS, prefix + ":Id", id);
          }
          return id;
      }
  
      public static void main(String[] args) throws Exception {
          SOAPEnvelope env = new SOAPEnvelope();
          Document doc = env.getAsDocument();
          WSSConfig wssConfig = WSSConfig.getDefaultWSConfig();
  
          RequestSecurityToken tokenRequest = new RequestSecurityToken(doc, TrustConstants.REQUEST_ISSUE);
  
          tokenRequest.setContext(new URI("http://context.context"));
          tokenRequest.setTokenType(TokenTypes.X509);
  
          UsernameToken userToken = new UsernameToken(wssConfig, doc);
          userToken.setName("bob");
          userToken.setPassword("bobspass");
          tokenRequest.setBase(new SecurityTokenOrReference(userToken));
  
          UsernameToken user2Token = new UsernameToken(wssConfig, doc);
          user2Token.setName("joe");
          user2Token.setPassword("bobspass");
          tokenRequest.addSupporting(new SecurityTokenOrReference(user2Token));
  
          UsernameToken user3Token = new UsernameToken(wssConfig, doc);
          user3Token.setName("mike");
          user3Token.setPassword("bobspass");
          tokenRequest.addSupporting(new SecurityTokenOrReference(user3Token));
  
          WSAddTokenRequest builder = new WSAddTokenRequest(tokenRequest);
          builder.addAction();
          doc = builder.build(doc);
          /*
          WSSignEnvelope builder = new WSSignEnvelope();
          builder.setUserInfo(credName, password);
          builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
          doc = builder.build(env.getAsDocument(), CryptoFactory.getInstance(cryptoPropFile));
  */
  										
          System.out.println("\n============= Request ==============");
          System.out.println(org.apache.axis.utils.XMLUtils.DocumentToString(doc));
      }
  
  }