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.message.encoder.MessageEncodingException;
23  import org.opensaml.ws.security.SecurityPolicy;
24  import org.opensaml.ws.security.SecurityPolicyResolver;
25  import org.opensaml.xml.Configuration;
26  import org.opensaml.xml.XMLObject;
27  import org.opensaml.xml.io.Marshaller;
28  import org.opensaml.xml.io.MarshallingException;
29  import org.opensaml.xml.io.Unmarshaller;
30  import org.opensaml.xml.io.UnmarshallingException;
31  import org.opensaml.xml.parse.BasicParserPool;
32  import org.opensaml.xml.parse.ParserPool;
33  import org.opensaml.xml.parse.XMLParserException;
34  import org.opensaml.xml.security.SecurityException;
35  import org.opensaml.xml.util.XMLHelper;
36  import org.slf4j.Logger;
37  import org.slf4j.LoggerFactory;
38  import org.w3c.dom.Document;
39  import org.w3c.dom.Element;
40  
41  /**
42   * Base class for message decoders.
43   */
44  public abstract class BaseMessageDecoder implements MessageDecoder {
45      
46      /** Used to log protocol messages. */
47      private Logger protocolMessageLog = LoggerFactory.getLogger("PROTOCOL_MESSAGE");
48  
49      /** Class logger. */
50      private final Logger log = LoggerFactory.getLogger(BaseMessageDecoder.class);
51  
52      /** Parser pool used to deserialize the message. */
53      private ParserPool parserPool;
54  
55      /** Constructor. */
56      public BaseMessageDecoder() {
57          parserPool = new BasicParserPool();
58      }
59  
60      /**
61       * Constructor.
62       * 
63       * @param pool parser pool used to deserialize messages
64       */
65      public BaseMessageDecoder(ParserPool pool) {
66          if (pool == null) {
67              throw new IllegalArgumentException("Parser pool may not be null");
68          }
69  
70          parserPool = pool;
71      }
72  
73      /** {@inheritDoc} */
74      public void decode(MessageContext messageContext) throws MessageDecodingException, SecurityException {
75          log.debug("Beginning to decode message from inbound transport of type: {}", messageContext
76                  .getInboundMessageTransport().getClass().getName());
77          
78          doDecode(messageContext);
79          
80          logDecodedMessage(messageContext);
81  
82          processSecurityPolicy(messageContext);
83  
84          log.debug("Successfully decoded message.");
85      }
86  
87      /**
88       * Log the decoded message to the protocol message logger.
89       * 
90       * @param messageContext the message context to process
91       */
92      protected void logDecodedMessage(MessageContext messageContext) {
93          if(protocolMessageLog.isDebugEnabled() && messageContext.getInboundMessage() != null){
94              if (messageContext.getInboundMessage().getDOM() == null) {
95                  XMLObject message = messageContext.getInboundMessage();
96                  Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(message);
97                  if (marshaller != null) {
98                      try {
99                          marshaller.marshall(message);
100                     } catch (MarshallingException e) {
101                         log.error("Unable to marshall message for logging purposes: " + e.getMessage());
102                     }
103                 }
104                 else {
105                     log.error("Unable to marshall message for logging purposes, no marshaller registered for message object: "
106                             + message.getElementQName());
107                 }
108                 if (message.getDOM() == null) {
109                     return;
110                 }
111             }
112             protocolMessageLog.debug("\n" + XMLHelper.prettyPrintXML(messageContext.getInboundMessage().getDOM()));
113         }
114     }
115 
116     /**
117      * Process any {@link SecurityPolicy}s which can be resolved for the message context.
118      * 
119      * @param messageContext the message context to process
120      * @throws SecurityException thrown if the decoded message does not meet the required security constraints
121      */
122     protected void processSecurityPolicy(MessageContext messageContext) throws SecurityException {
123         SecurityPolicyResolver policyResolver = messageContext.getSecurityPolicyResolver();
124         if (policyResolver != null) {
125             Iterable<SecurityPolicy> securityPolicies = policyResolver.resolve(messageContext);
126             if (securityPolicies != null) {
127                 for (SecurityPolicy policy : securityPolicies) {
128                     if (policy != null) {
129                         log.debug("Evaluating security policy of type '{}' for decoded message", policy.getClass()
130                                 .getName());
131                         policy.evaluate(messageContext);
132                     }
133                 }
134             } else {
135                 log.debug("No security policy resolved for this message context, no security policy evaluation attempted");
136             }
137         } else {
138             log.debug("No security policy resolver attached to this message context, no security policy evaluation attempted");
139         }
140     }
141 
142     /**
143      * Decodes a message, updating the message context. Security policy evaluation is handled outside this method.
144      * 
145      * @param messageContext current message context
146      * 
147      * @throws MessageDecodingException thrown if there is a problem decoding the message
148      */
149     protected abstract void doDecode(MessageContext messageContext) throws MessageDecodingException;
150 
151     /**
152      * Gets the parser pool used to deserialize incomming messages.
153      * 
154      * @return parser pool used to deserialize incomming messages
155      */
156     protected ParserPool getParserPool() {
157         return parserPool;
158     }
159 
160     /**
161      * Sets the parser pool used to deserialize incomming messages.
162      * 
163      * @param pool parser pool used to deserialize incomming messages
164      */
165     protected void setParserPool(ParserPool pool) {
166         if (pool == null) {
167             throw new IllegalArgumentException("Parser pool may not be null");
168         }
169         parserPool = pool;
170     }
171 
172     /**
173      * Helper method that deserializes and unmarshalls the message from the given stream.
174      * 
175      * @param messageStream input stream containing the message
176      * 
177      * @return the inbound message
178      * 
179      * @throws MessageDecodingException thrown if there is a problem deserializing and unmarshalling the message
180      */
181     protected XMLObject unmarshallMessage(InputStream messageStream) throws MessageDecodingException {
182         log.debug("Parsing message stream into DOM document");
183 
184         try {
185             Document messageDoc = parserPool.parse(messageStream);
186             Element messageElem = messageDoc.getDocumentElement();
187 
188             if (log.isTraceEnabled()) {
189                 log.trace("Resultant DOM message was:\n{}", XMLHelper.nodeToString(messageElem));
190             }
191 
192             log.debug("Unmarshalling message DOM");
193             Unmarshaller unmarshaller = Configuration.getUnmarshallerFactory().getUnmarshaller(messageElem);
194             if (unmarshaller == null) {
195                 log.error("Unable to unmarshall message, no unmarshaller registered for message element "
196                         + XMLHelper.getNodeQName(messageElem));
197                 throw new MessageDecodingException(
198                         "Unable to unmarshall message, no unmarshaller registered for message element "
199                                 + XMLHelper.getNodeQName(messageElem));
200             }
201 
202             XMLObject message = unmarshaller.unmarshall(messageElem);
203 
204             log.debug("Message succesfully unmarshalled");
205             return message;
206         } catch (XMLParserException e) {
207             log.error("Encountered error parsing message into its DOM representation", e);
208             throw new MessageDecodingException("Encountered error parsing message into its DOM representation", e);
209         } catch (UnmarshallingException e) {
210             log.error("Encountered error unmarshalling message from its DOM representation", e);
211             throw new MessageDecodingException("Encountered error unmarshalling message from its DOM representation", e);
212         }
213     }
214 }