View Javadoc

1   /*
2    * Copyright 2008 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.saml2.metadata.provider;
18  
19  import javax.xml.transform.dom.DOMSource;
20  import javax.xml.validation.Validator;
21  
22  import org.opensaml.common.xml.SAMLSchemaBuilder;
23  import org.opensaml.xml.XMLObject;
24  import org.opensaml.xml.util.DatatypeHelper;
25  import org.slf4j.Logger;
26  import org.slf4j.LoggerFactory;
27  import org.xml.sax.SAXException;
28  
29  /**
30   * A metadata filter that schema validates an incoming metadata file.
31   */
32  public class SchemaValidationFilter implements MetadataFilter {
33  
34      /** Class logger. */
35      private final Logger log = LoggerFactory.getLogger(SchemaValidationFilter.class);
36  
37      /**
38       * Constructor.
39       * 
40       * @param extensionSchemas classpath location of metadata extension schemas, may be null
41       */
42      public SchemaValidationFilter(String[] extensionSchemas) {
43          if (extensionSchemas != null) {
44              for (String extension : extensionSchemas) {
45                  extension = DatatypeHelper.safeTrimOrNullString(extension);
46                  if(extension != null){
47                      SAMLSchemaBuilder.addExtensionSchema(extension);
48                  }
49              }
50          }
51      }
52  
53      /** {@inheritDoc} */
54      public void doFilter(XMLObject metadata) throws FilterException {
55          Validator schemaValidator = null;
56          try {
57              schemaValidator = SAMLSchemaBuilder.getSAML11Schema().newValidator();
58          } catch (SAXException e) {
59              log.error("Unable to build metadata validation schema", e);
60              throw new FilterException("Unable to build metadata validation schema", e);
61          }
62  
63          try {
64              schemaValidator.validate(new DOMSource(metadata.getDOM()));
65          } catch (Exception e) {
66              log.error("Incoming metadata was not schema valid.", e);
67              throw new FilterException("Incoming metadata was not schema valid.", e);
68          }
69      }
70  }