View Javadoc

1   /*
2    * Copyright [2007] [University Corporation for Advanced Internet Development, Inc.]
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.opensaml.ws.message.decoder;
18  
19  import java.io.InputStream;
20  
21  import org.opensaml.ws.message.MessageContext;
22  import org.opensaml.ws.security.SecurityPolicy;
23  import org.opensaml.ws.security.SecurityPolicyResolver;
24  import org.opensaml.xml.Configuration;
25  import org.opensaml.xml.XMLObject;
26  import org.opensaml.xml.io.Unmarshaller;
27  import org.opensaml.xml.io.UnmarshallingException;
28  import org.opensaml.xml.parse.BasicParserPool;
29  import org.opensaml.xml.parse.ParserPool;
30  import org.opensaml.xml.parse.XMLParserException;
31  import org.opensaml.xml.security.SecurityException;
32  import org.opensaml.xml.util.XMLHelper;
33  import org.slf4j.Logger;
34  import org.slf4j.LoggerFactory;
35  import org.w3c.dom.Document;
36  import org.w3c.dom.Element;
37  
38  /**
39   * Base class for message decoders.
40   */
41  public abstract class BaseMessageDecoder implements MessageDecoder {
42      
43      /** Used to log protocol messages. */
44      private Logger protocolMessageLog = LoggerFactory.getLogger("PROTOCOL_MESSAGE");
45  
46      /** Class logger. */
47      private final Logger log = LoggerFactory.getLogger(BaseMessageDecoder.class);
48  
49      /** Parser pool used to deserialize the message. */
50      private ParserPool parserPool;
51  
52      /** Constructor. */
53      public BaseMessageDecoder() {
54          parserPool = new BasicParserPool();
55      }
56  
57      /**
58       * Constructor.
59       * 
60       * @param pool parser pool used to deserialize messages
61       */
62      public BaseMessageDecoder(ParserPool pool) {
63          if (pool == null) {
64              throw new IllegalArgumentException("Parser pool may not be null");
65          }
66  
67          parserPool = pool;
68      }
69  
70      /** {@inheritDoc} */
71      public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException {
72          log.debug("Beginning to decode message from inbound transport of type: {}", messageContext
73                  .getInboundMessageTransport().getClass().getName());
74          
75          doDecode(messageContext);
76          
77          logDecodedMessage(messageContext);
78  
79          processSecurityPolicy(messageContext);
80  
81          log.debug("Successfully decoded message.");
82      }
83  
84      /**
85       * Log the decoded message to the protocol message logger.
86       * 
87       * @param messageContext the message context to process
88       */
89      protected void logDecodedMessage(MessageContext messageContext) {
90          if(protocolMessageLog.isDebugEnabled() && messageContext.getInboundMessage() != null){
91              protocolMessageLog.debug("\n" + XMLHelper.prettyPrintXML(messageContext.getInboundMessage().getDOM()));
92          }
93      }
94  
95      /**
96       * Process any {@link SecurityPolicy}s which can be resolved for the message context.
97       * 
98       * @param messageContext the message context to process
99       * @throws SecurityException thrown if the decoded message does not meet the required security constraints
100      */
101     protected void processSecurityPolicy(MessageContext messageContext) throws SecurityException {
102         SecurityPolicyResolver policyResolver = messageContext.getSecurityPolicyResolver();
103         if (policyResolver != null) {
104             Iterable<SecurityPolicy> securityPolicies = policyResolver.resolve(messageContext);
105             if (securityPolicies != null) {
106                 for (SecurityPolicy policy : securityPolicies) {
107                     if (policy != null) {
108                         log.debug("Evaluating security policy of type '{}' for decoded message", policy.getClass()
109                                 .getName());
110                         policy.evaluate(messageContext);
111                     }
112                 }
113             } else {
114                 log.debug("No security policy resolved for this message context, no security policy evaluation attempted");
115             }
116         } else {
117             log.debug("No security policy resolver attached to this message context, no security policy evaluation attempted");
118         }
119     }
120 
121     /**
122      * Decodes a message, updating the message context. Security policy evaluation is handled outside this method.
123      * 
124      * @param messageContext current message context
125      * 
126      * @throws MessageDecodingException thrown if there is a problem decoding the message
127      */
128     protected abstract void doDecode(MessageContext messageContext) throws MessageDecodingException;
129 
130     /**
131      * Gets the parser pool used to deserialize incomming messages.
132      * 
133      * @return parser pool used to deserialize incomming messages
134      */
135     protected ParserPool getParserPool() {
136         return parserPool;
137     }
138 
139     /**
140      * Sets the parser pool used to deserialize incomming messages.
141      * 
142      * @param pool parser pool used to deserialize incomming messages
143      */
144     protected void setParserPool(ParserPool pool) {
145         if (pool == null) {
146             throw new IllegalArgumentException("Parser pool may not be null");
147         }
148         parserPool = pool;
149     }
150 
151     /**
152      * Helper method that deserializes and unmarshalls the message from the given stream.
153      * 
154      * @param messageStream input stream containing the message
155      * 
156      * @return the inbound message
157      * 
158      * @throws MessageDecodingException thrown if there is a problem deserializing and unmarshalling the message
159      */
160     protected XMLObject unmarshallMessage(InputStream messageStream) throws MessageDecodingException {
161         log.debug("Parsing message stream into DOM document");
162 
163         try {
164             Document messageDoc = parserPool.parse(messageStream);
165             Element messageElem = messageDoc.getDocumentElement();
166 
167             if (log.isTraceEnabled()) {
168                 log.trace("Resultant DOM message was:\n{}", XMLHelper.nodeToString(messageElem));
169             }
170 
171             log.debug("Unmarshalling message DOM");
172             Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(messageElem);
173             if (unmarshaller == null) {
174                 log.error("Unable to unmarshall message, no unmarshaller registered for message element "
175                         + XMLHelper.getNodeQName(messageElem));
176                 throw new MessageDecodingException(
177                         "Unable to unmarshall message, no unmarshaller registered for message element "
178                                 + XMLHelper.getNodeQName(messageElem));
179             }
180 
181             XMLObject message = unmarshaller.unmarshall(messageElem);
182 
183             log.debug("Message succesfully unmarshalled");
184             return message;
185         } catch (XMLParserException e) {
186             log.error("Encountered error parsing message into its DOM representation", e);
187             throw new MessageDecodingException("Encountered error parsing message into its DOM representation", e);
188         } catch (UnmarshallingException e) {
189             log.error("Encountered error unmarshalling message from its DOM representation", e);
190             throw new MessageDecodingException("Encountered error unmarshalling message from its DOM representation", e);
191         }
192     }
193 }