Turned on schema validation for federation metadata. Better error handling.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / metadata / provider / XMLMetadataLoadWrapper.java
1 /*
2  * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation for Advanced Internet Development, Inc.
3  * All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted
4  * provided that the following conditions are met: Redistributions of source code must retain the above copyright
5  * notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the
6  * above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other
7  * materials provided with the distribution, if any, must include the following acknowledgment: "This product includes
8  * software developed by the University Corporation for Advanced Internet Development <http://www.ucaid.edu>Internet2
9  * Project. Alternately, this acknowledegement may appear in the software itself, if and wherever such third-party
10  * acknowledgments normally appear. Neither the name of Shibboleth nor the names of its contributors, nor Internet2,
11  * nor the University Corporation for Advanced Internet Development, Inc., nor UCAID may be used to endorse or promote
12  * products derived from this software without specific prior written permission. For written permission, please
13  * contact shibboleth@shibboleth.org Products derived from this software may not be called Shibboleth, Internet2,
14  * UCAID, or the University Corporation for Advanced Internet Development, nor may Shibboleth appear in their name,
15  * without prior written permission of the University Corporation for Advanced Internet Development. THIS SOFTWARE IS
16  * PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES,
17  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
18  * NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS
19  * WITH LICENSEE. IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED
20  * INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
23  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24  * POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 package edu.internet2.middleware.shibboleth.metadata.provider;
28
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.util.StringTokenizer;
32
33 import org.apache.log4j.Logger;
34 import org.apache.xerces.parsers.DOMParser;
35 import org.xml.sax.EntityResolver;
36 import org.xml.sax.ErrorHandler;
37 import org.xml.sax.InputSource;
38 import org.xml.sax.SAXException;
39 import org.xml.sax.SAXParseException;
40
41 import edu.internet2.middleware.shibboleth.common.ResourceWatchdog;
42 import edu.internet2.middleware.shibboleth.common.ResourceWatchdogExecutionException;
43 import edu.internet2.middleware.shibboleth.common.ShibResource;
44 import edu.internet2.middleware.shibboleth.common.ShibResource.ResourceNotAvailableException;
45 import edu.internet2.middleware.shibboleth.metadata.Metadata;
46 import edu.internet2.middleware.shibboleth.metadata.MetadataException;
47 import edu.internet2.middleware.shibboleth.metadata.Provider;
48
49 /**
50  * @author Walter Hoehn (wassa@columbia.edu)
51  */
52 public class XMLMetadataLoadWrapper extends ResourceWatchdog implements Metadata {
53
54         private static Logger   log     = Logger.getLogger(XMLMetadataLoadWrapper.class.getName());
55         private Metadata                currentMeta;
56         private DOMParser               parser;
57
58         public XMLMetadataLoadWrapper(String sitesFileLocation) throws MetadataException, ResourceNotAvailableException {
59                 super(new ShibResource(sitesFileLocation));
60
61                 parser = new DOMParser();
62                 try {
63                         parser.setFeature("http://xml.org/sax/features/validation", true);
64                         parser.setFeature("http://apache.org/xml/features/validation/schema", true);
65
66                         parser.setEntityResolver(new EntityResolver() {
67
68                                 public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
69                                         log.debug("Resolving entity for System ID: " + systemId);
70                                         if (systemId != null) {
71                                                 StringTokenizer tokenString = new StringTokenizer(systemId, "/");
72                                                 String xsdFile = "";
73                                                 while (tokenString.hasMoreTokens()) {
74                                                         xsdFile = tokenString.nextToken();
75                                                 }
76                                                 if (xsdFile.endsWith(".xsd")) {
77                                                         InputStream stream;
78                                                         try {
79                                                                 stream = new ShibResource("/schemas/" + xsdFile, this.getClass()).getInputStream();
80                                                         } catch (IOException ioe) {
81                                                                 log.error("Error loading schema: " + xsdFile + ": " + ioe);
82                                                                 return null;
83                                                         }
84                                                         if (stream != null) {
85                                                                 return new InputSource(stream);
86                                                         }
87                                                 }
88                                         }
89                                         return null;
90                                 }
91                         });
92
93                         parser.setErrorHandler(new ErrorHandler() {
94
95                                 public void error(SAXParseException arg0) throws SAXException {
96                                         throw new SAXException("Error parsing xml file: " + arg0);
97                                 }
98
99                                 public void fatalError(SAXParseException arg0) throws SAXException {
100                                         throw new SAXException("Error parsing xml file: " + arg0);
101                                 }
102
103                                 public void warning(SAXParseException arg0) throws SAXException {
104                                         throw new SAXException("Error parsing xml file: " + arg0);
105                                 }
106                         });
107
108                         parser.parse(new InputSource(resource.getInputStream()));
109
110                 } catch (SAXException e) {
111                         log.error("Encountered a problem parsing federation metadata source: " + e);
112                         throw new MetadataException("Unable to parse federation metadata.");
113                 } catch (IOException e) {
114                         log.error("Encountered a problem reading federation metadata source: " + e);
115                         throw new MetadataException("Unable to read federation metadata.");
116                 }
117
118                 currentMeta = new XMLMetadata(parser.getDocument().getDocumentElement());
119
120                 //Start checking for metadata updates
121                 start();
122
123         }
124
125         public Provider lookup(String providerId) {
126                 synchronized (currentMeta) {
127                         return currentMeta.lookup(providerId);
128                 }
129         }
130
131         protected void doOnChange() throws ResourceWatchdogExecutionException {
132                 //Log
133                 try {
134                         log.info("Detected a change in the federation metadata.  Reloading from (" + resource.getURL().toString()
135                                         + ").");
136                 } catch (IOException e) {
137                         log.error("Encountered an error retrieving updated federation metadata, continuing to use stale copy.");
138                         return;
139                 }
140
141                 //Load new, but keep the old in place
142                 try {
143                         parser.parse(new InputSource(resource.getInputStream()));
144                 } catch (SAXException e) {
145                         log.error("Encountered an error parsing updated federation metadata, continuing to use stale copy.");
146                         return;
147                 } catch (IOException e) {
148                         log.error("Encountered an error retrieving updated federation metadata, continuing to use stale copy.");
149                         return;
150                 }
151
152                 //If things went well, replace the live copy
153                 Metadata newMeta = null;
154                 try {
155                         newMeta = new XMLMetadata(parser.getDocument().getDocumentElement());
156                 } catch (MetadataException e1) {
157                         log.error("Encountered an error loading updated federation metadata, continuing to use stale copy.");
158                         return;
159                 }
160
161                 if (newMeta != null) {
162                         synchronized (currentMeta) {
163                                 currentMeta = newMeta;
164                         }
165                 }
166         }
167
168 }