Simple code cleanups.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / utils / ResolverTest.java
1 /* 
2  * The Shibboleth License, Version 1. 
3  * Copyright (c) 2002 
4  * University Corporation for Advanced Internet Development, Inc. 
5  * All rights reserved
6  * 
7  * 
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions are met:
10  * 
11  * Redistributions of source code must retain the above copyright notice, this 
12  * list of conditions and the following disclaimer.
13  * 
14  * Redistributions in binary form must reproduce the above copyright notice, 
15  * this list of conditions and the following disclaimer in the documentation 
16  * and/or other materials provided with the distribution, if any, must include 
17  * the following acknowledgment: "This product includes software developed by 
18  * the University Corporation for Advanced Internet Development 
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement 
20  * may appear in the software itself, if and wherever such third-party 
21  * acknowledgments normally appear.
22  * 
23  * Neither the name of Shibboleth nor the names of its contributors, nor 
24  * Internet2, nor the University Corporation for Advanced Internet Development, 
25  * Inc., nor UCAID may be used to endorse or promote products derived from this 
26  * software without specific prior written permission. For written permission, 
27  * please contact shibboleth@shibboleth.org
28  * 
29  * Products derived from this software may not be called Shibboleth, Internet2, 
30  * UCAID, or the University Corporation for Advanced Internet Development, nor 
31  * may Shibboleth appear in their name, without prior written permission of the 
32  * University Corporation for Advanced Internet Development.
33  * 
34  * 
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK 
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. 
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY 
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, 
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 package edu.internet2.middleware.shibboleth.utils;
51
52 import jargs.gnu.CmdLineParser;
53
54 import java.io.ByteArrayOutputStream;
55 import java.io.IOException;
56 import java.io.PrintStream;
57 import java.util.Properties;
58
59 import org.apache.log4j.BasicConfigurator;
60 import org.apache.log4j.Level;
61 import org.apache.log4j.Logger;
62 import org.apache.xml.serialize.OutputFormat;
63 import org.apache.xml.serialize.XMLSerializer;
64 import org.opensaml.SAMLException;
65 import org.w3c.dom.Element;
66 import org.w3c.dom.Node;
67
68 import edu.internet2.middleware.shibboleth.aa.AAAttribute;
69 import edu.internet2.middleware.shibboleth.aa.AAAttributeSet;
70 import edu.internet2.middleware.shibboleth.aa.AAAttributeSet.ShibAttributeIterator;
71 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
72 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
73 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
74
75 /**
76  * Utility for testing an Attribute Resolver configuration.
77  * 
78  * @author Walter Hoehn
79  */
80 public class ResolverTest {
81
82         private static boolean debug = false;
83         private static String file = null;
84         private static String requester = null;
85         private static String user = null;
86
87         public static void main(String[] args) {
88
89                 CmdLineParser parser = new CmdLineParser();
90                 CmdLineParser.Option helpOption = parser.addBooleanOption('h', "help");
91                 CmdLineParser.Option debugOption = parser.addBooleanOption('d', "debug");
92                 CmdLineParser.Option fileOption = parser.addStringOption('f', "file");
93                 CmdLineParser.Option userOption = parser.addStringOption('u', "user");
94                 CmdLineParser.Option requesterOption = parser.addStringOption('r', "requester");
95
96                 try {
97                         parser.parse(args);
98                 } catch (CmdLineParser.OptionException e) {
99                         System.err.println(e.getMessage());
100                         try {
101                                 Thread.sleep(100); //silliness to get error to print first
102                         } catch (InterruptedException ie) {
103                                 //doesn't matter
104                         }
105                         printUsage(System.out);
106                         System.exit(1);
107                 }
108
109                 Boolean helpEnabled = (Boolean) parser.getOptionValue(helpOption);
110                 if (helpEnabled != null && helpEnabled.booleanValue()) {
111                         printUsage(System.out);
112                         System.exit(0);
113                 }
114
115                 Boolean debugEnabled = ((Boolean) parser.getOptionValue(debugOption));
116                 if (debugEnabled != null) {
117                         debug = debugEnabled.booleanValue();
118                 }
119
120                 file = (String) parser.getOptionValue(fileOption);
121                 user = (String) parser.getOptionValue(userOption);
122                 requester = (String) parser.getOptionValue(requesterOption);
123
124                 configureLogging(debug);
125                 checkRequired();
126
127                 Properties configuration = new Properties();
128                 configuration.setProperty(
129                         "edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver.ResolverConfig",
130                         file);
131
132                 try {
133                         AttributeResolver resolver = new AttributeResolver(configuration);
134                         String[] attributes = resolver.listRegisteredAttributeDefinitionPlugIns();
135
136                         AAAttributeSet attributeSet = new AAAttributeSet();
137                         for (int i = 0; i < attributes.length; i++) {
138                                 attributeSet.add(new AAAttribute(attributes[i]));
139                         }
140
141                         resolver.resolveAttributes(new AuthNPrincipal(user), requester, attributeSet);
142
143                         System.out.println(
144                                 "Received the following back from the Attribute Resolver:" + System.getProperty("line.separator"));
145
146                         for (ShibAttributeIterator iterator = attributeSet.shibAttributeIterator(); iterator.hasNext();) {
147                                 AAAttribute attribute = iterator.nextShibAttribute();
148                                 Node node = attribute.toDOM();
149                                 ByteArrayOutputStream xml = new ByteArrayOutputStream();
150                                 if (!(node instanceof Element)) {
151                                         throw new IOException("Received bad Element data from SAML library.");
152                                 }
153                                 OutputFormat format = new OutputFormat();
154                                 format.setIndenting(true);
155                                 format.setIndent(4);
156                                 new XMLSerializer(xml, format).serialize((Element) node);
157                                 System.out.println(xml.toString() + System.getProperty("line.separator"));
158                         }
159                 
160                 } catch (AttributeResolverException e) {
161                         System.err.println("Error initializing the Attribute Resolver: " + e.getMessage());
162                 } catch (SAMLException e) {
163                         System.err.println("Error creating SAML attribute: " + e.getMessage());
164                 } catch (IOException e) {
165                         System.err.println("Error serializing output from Resolver: " + e.getMessage());
166                 }
167         }
168
169         /**
170          * Ensures that all required parameters were specified and successfully parsed.
171          *
172          */
173         private static void checkRequired() {
174                 if (file == null || user == null) {
175                         System.err.println("Missing required parameter(s).");
176                         try {
177                                 Thread.sleep(100); //silliness to get error to print first
178                         } catch (InterruptedException e) {
179                                 //doesn't matter
180                         }
181                         printUsage(System.out);
182                         System.exit(1);
183                 }
184         }
185
186         private static void configureLogging(boolean debugEnabled) {
187
188                 BasicConfigurator.configure();
189                 if (debugEnabled) {
190                         Logger.getRootLogger().setLevel(Level.DEBUG);
191                 } else {
192                         Logger.getRootLogger().setLevel(Level.INFO);
193                         Logger.getLogger("edu.internet2.middleware.shibboleth.aa.attrresolv").setLevel(Level.WARN);
194                 }
195                 Logger.getLogger("org.apache.xml.security").setLevel(Level.OFF);
196         }
197
198         private static void printUsage(PrintStream out) {
199
200                 out.println("Usage: resolvertest [options]..." + System.getProperty("line.separator"));
201                 out.println("Tests an AA Attribute Resolver configuration." + System.getProperty("line.separator"));
202
203                 out.println("-d, --debug                   run in debug mode");
204                 out.println("-h, --help                    print usage information");
205                 out.println("-f, --file=FILEURL            the URL of the resolver configuration");
206                 out.println("                                file (resolver.xml)");
207                 out.println("-u, --user=USER               the user for which attributes should");
208                 out.println("                                be resolved");
209                 out.println("-r, --requester=REQUESTER     the name of the requester (SHAR),");
210                 out.println("                                emulates unauthenticated requester if");
211                 out.println("                                not specified" + System.getProperty("line.separator"));
212
213         }
214 }