KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > test > xml > MBeanServerUnitTestCase


1 /*
2   * JBoss, Home of Professional Open Source
3   * Copyright 2005, JBoss Inc., and individual contributors as indicated
4   * by the @authors tag. See the copyright.txt in the distribution for a
5   * full listing of individual contributors.
6   *
7   * This is free software; you can redistribute it and/or modify it
8   * under the terms of the GNU Lesser General Public License as
9   * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */

22 package org.jboss.test.xml;
23
24 import java.util.List JavaDoc;
25 import java.util.Map JavaDoc;
26 import java.util.Properties JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.net.InetAddress JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.io.ByteArrayOutputStream JavaDoc;
31 import java.io.ByteArrayInputStream JavaDoc;
32 import java.io.IOException JavaDoc;
33
34 import javax.security.auth.login.AppConfigurationEntry JavaDoc;
35 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
36 import javax.xml.parsers.DocumentBuilder JavaDoc;
37 import javax.xml.transform.dom.DOMSource JavaDoc;
38 import javax.xml.transform.TransformerFactory JavaDoc;
39 import javax.xml.transform.Transformer JavaDoc;
40 import javax.xml.transform.stream.StreamResult JavaDoc;
41
42 import org.jboss.test.xml.mbeanserver.Services;
43 import org.jboss.test.xml.mbeanserver.MBeanData;
44 import org.jboss.test.xml.mbeanserver.MBeanAttribute;
45 import org.jboss.test.xml.mbeanserver.PolicyConfig;
46 import org.jboss.test.xml.mbeanserver.AuthenticationInfo;
47 import org.jboss.xb.binding.JBossXBRuntimeException;
48 import org.jboss.xb.binding.Unmarshaller;
49 import org.jboss.xb.binding.UnmarshallerFactory;
50 import org.jboss.xb.binding.sunday.unmarshalling.SchemaBinding;
51 import org.jboss.xb.binding.sunday.unmarshalling.SchemaBindingResolver;
52 import org.jboss.xb.binding.sunday.unmarshalling.XsdBinder;
53 import org.jboss.naming.JNDIBindings;
54 import org.jboss.naming.JNDIBinding;
55 import org.jboss.util.xml.JBossEntityResolver;
56 import org.w3c.dom.Element JavaDoc;
57 import org.w3c.dom.Document JavaDoc;
58 import org.w3c.dom.NodeList JavaDoc;
59 import org.w3c.dom.Node JavaDoc;
60 import org.w3c.dom.ls.LSInput JavaDoc;
61 import org.xml.sax.InputSource JavaDoc;
62 import org.xml.sax.SAXException JavaDoc;
63
64 import junit.framework.TestCase;
65
66 /**
67  * Test unmarshalling xml documents conforming to mbean-service_1_0.xsd into
68  * the org.jboss.test.xml.mbeanserver.Services and related objects.
69  *
70  * @author Scott.Stark@jboss.org
71  * @version $Revision: 57180 $
72  */

73 public class MBeanServerUnitTestCase
74    extends TestCase
75 {
76    public void testMbeanService() throws Exception JavaDoc
77    {
78       InputStream JavaDoc is = getResource("xml/mbeanserver/mbean-service_1_0.xsd");
79       SchemaBinding schemaBinding = XsdBinder.bind(is, null);
80       schemaBinding.setIgnoreUnresolvedFieldOrClass(true);
81       schemaBinding.setSchemaResolver(new SchemaBindingResolver()
82       {
83          public String JavaDoc getBaseURI()
84          {
85             throw new UnsupportedOperationException JavaDoc("getBaseURI is not implemented.");
86          }
87
88          public void setBaseURI(String JavaDoc baseURI)
89          {
90             throw new UnsupportedOperationException JavaDoc("setBaseURI is not implemented.");
91          }
92
93          public SchemaBinding resolve(String JavaDoc nsUri, String JavaDoc baseURI, String JavaDoc schemaLocation)
94          {
95             try
96             {
97                if("urn:jboss:login-config2".equals(nsUri))
98                {
99                   InputStream JavaDoc is = getResource("xml/mbeanserver/login-config2.xsd");
100                   SchemaBinding schemaBinding = XsdBinder.bind(is, null, baseURI);
101                   schemaBinding.setSchemaResolver(this);
102                   return schemaBinding;
103                }
104                else if("urn:jboss:user-roles".equals(nsUri))
105                {
106                   InputStream JavaDoc is = getResource("xml/mbeanserver/user-roles.xsd");
107                   return XsdBinder.bind(is, null, baseURI);
108                }
109                else
110                {
111                   throw new JBossXBRuntimeException("Unrecognized namespace: " + nsUri);
112                }
113             }
114             catch(IOException JavaDoc e)
115             {
116                throw new JBossXBRuntimeException("IO error", e);
117             }
118          }
119
120          public LSInput JavaDoc resolveAsLSInput(String JavaDoc nsUri, String JavaDoc baseUri, String JavaDoc schemaLocation)
121          {
122             throw new UnsupportedOperationException JavaDoc("resolveResource is not implemented.");
123          }
124       });
125
126       Unmarshaller unmarshaller = UnmarshallerFactory.newInstance().newUnmarshaller();
127       InputStream JavaDoc is2 = getResource("xml/mbeanserver/testObjFactory.xml");
128       Services services = (Services)unmarshaller.unmarshal(is2, schemaBinding);
129       List JavaDoc mbeans = services.getMBeans();
130       assertEquals("There is 1 mbean", 1, mbeans.size());
131
132       MBeanData mbean = (MBeanData) mbeans.get(0);
133       assertTrue("ClassName == org.jboss.security.auth.login.DynamicLoginConfig",
134          mbean.getCode().equals("org.jboss.security.auth.login.DynamicLoginConfig"));
135       assertTrue("Name == jboss.security.tests:service=DynamicLoginConfig",
136          mbean.getName().equals("jboss.security.tests:service=DynamicLoginConfig"));
137       Map JavaDoc attributes = mbean.getAttributeMap();
138       assertTrue("There are 2 attributes",
139          attributes.size() == 2);
140       MBeanAttribute attr = (MBeanAttribute) attributes.get("PolicyConfig");
141       Object JavaDoc value = attr.getValue();
142       assertTrue("Value isA PolicyConfig",
143           value instanceof PolicyConfig );
144       PolicyConfig pc = (PolicyConfig) value;
145       assertTrue("There 1 AuthenticationInfo",
146          pc.size() == 1);
147       AuthenticationInfo auth = pc.get("conf1");
148       assertTrue("The AuthenticationInfo name ic config1",
149          auth != null);
150       AppConfigurationEntry JavaDoc[] ace = auth.getAppConfigurationEntry();
151       assertTrue("The AppConfigurationEntry has one entry",
152          ace != null && ace.length == 1);
153       assertTrue("LoginModuleName",
154          ace[0].getLoginModuleName().equals("org.jboss.security.auth.spi.IdentityLoginModule"));
155
156       attr = (MBeanAttribute) attributes.get("UserHome");
157       assertTrue("Name == UserHome",
158          attr.getName().equals("UserHome"));
159       assertTrue("Text != null",
160          attr.getText() != null);
161    }
162
163    /**
164     * A test of unmarshalling an element from a document without any knowledge
165     * of the associated schema.
166     *
167     * @throws Exception
168     */

169    public void testJndiBindings() throws Exception JavaDoc
170    {
171       InputStream JavaDoc is = getResource("xml/mbeanserver/testBinding.xml");
172       // Get the Bindings attribute element
173
DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
174       DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
175       Document JavaDoc doc = builder.parse(is);
176       NodeList JavaDoc attributes = doc.getElementsByTagName("attribute");
177       Element JavaDoc element = (Element JavaDoc) attributes.item(0);
178       NodeList JavaDoc children = element.getChildNodes();
179       Element JavaDoc content = null;
180       for(int n = 0; n < children.getLength(); n ++)
181       {
182          Node JavaDoc node = children.item(n);
183          if( node.getNodeType() == Node.ELEMENT_NODE )
184          {
185             content = (Element JavaDoc) node;
186             break;
187          }
188       }
189
190       // Get a parsable representation of this elements content
191
DOMSource JavaDoc source = new DOMSource JavaDoc(content);
192       TransformerFactory JavaDoc tFactory = TransformerFactory.newInstance();
193       Transformer JavaDoc transformer = tFactory.newTransformer();
194       ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
195       StreamResult JavaDoc result = new StreamResult JavaDoc(baos);
196       transformer.transform(source, result);
197       baos.close();
198
199       ByteArrayInputStream JavaDoc is2 = new ByteArrayInputStream JavaDoc(baos.toByteArray());
200
201       /* Parse the element content using the Unmarshaller starting with an
202       empty schema since we don't know anything about it. This is not quite
203       true as we set the schema baseURI to the resources/xml/naming/ directory
204       so that the jndi-binding-service_1_0.xsd can be found, but this baseURI
205       can be easily specified to the SARDeployer, or the schema can be made
206       available to the entity resolver via some other configuration.
207       */

208       final URL JavaDoc url = Thread.currentThread().getContextClassLoader().getResource("xml/naming/");
209
210       Unmarshaller unmarshaller = UnmarshallerFactory.newInstance().newUnmarshaller();
211       unmarshaller.setEntityResolver(new JBossEntityResolver(){
212          public InputSource JavaDoc resolveEntity(String JavaDoc publicId, String JavaDoc systemId) throws SAXException JavaDoc, IOException JavaDoc
213          {
214             if(systemId.endsWith("custom-object-binding.xsd") ||
215                systemId.endsWith("jndi-binding-service_1_0.xsd"))
216             {
217                String JavaDoc fileName = systemId.substring(systemId.lastIndexOf('/') + 1);
218                URL JavaDoc url = Thread.currentThread().getContextClassLoader().
219                   getResource("xml/naming/" + fileName);
220                return new InputSource JavaDoc(url.toExternalForm());
221             }
222             else
223             {
224                return super.resolveEntity(publicId, systemId);
225             }
226          }
227       });
228
229       JNDIBindings bindings = (JNDIBindings) unmarshaller.unmarshal(is2,
230          new SchemaBindingResolver(){
231             public String JavaDoc getBaseURI()
232             {
233                throw new UnsupportedOperationException JavaDoc("getBaseURI is not implemented.");
234             }
235
236             public void setBaseURI(String JavaDoc baseURI)
237             {
238                throw new UnsupportedOperationException JavaDoc("setBaseURI is not implemented.");
239             }
240
241             public SchemaBinding resolve(String JavaDoc nsUri, String JavaDoc baseURI, String JavaDoc schemaLocation)
242             {
243                return XsdBinder.bind(url.toExternalForm() + schemaLocation, this);
244             }
245
246             public LSInput JavaDoc resolveAsLSInput(String JavaDoc nsUri, String JavaDoc baseUri, String JavaDoc schemaLocation)
247             {
248                throw new UnsupportedOperationException JavaDoc("resolveAsLSInput is not implemented.");
249             }
250          });
251
252       is2.close();
253
254       // Validate the bindings
255
JNDIBinding[] values = bindings.getBindings();
256       assertTrue("There are 5 bindings("+values.length+")", values.length == 5);
257
258       JNDIBinding key1 = values[0];
259       assertTrue("values[0] name is ctx1/key1", key1.getName().equals("ctx1/key1"));
260       assertTrue("values[0] is string of value1", key1.getText().equals("value1"));
261
262       JNDIBinding userHome = values[1];
263       assertTrue("values[1] name is ctx1/user.home", userHome.getName().equals("ctx1/user.home"));
264       String JavaDoc p = System.getProperty("user.home");
265       assertTrue("values[1] is property ${user.home}", userHome.getText().equals(p));
266
267       // Test binding from a text to URL based on the type attribute PropertyEditor
268
JNDIBinding jbossHome = values[2];
269       assertTrue("values[2] name is ctx1/key2", jbossHome.getName().equals("ctx1/key2"));
270       assertTrue("values[2] is http://www.jboss.org",
271          jbossHome.getText().equals("http://www.jboss.org"));
272       assertTrue("values[2] type is java.net.URL",
273          jbossHome.getType().equals("java.net.URL"));
274       Object JavaDoc value2 = jbossHome.getValue();
275       assertTrue("values[2] value is URL(http://www.jboss.org)",
276          value2.equals(new URL JavaDoc("http://www.jboss.org")));
277
278       // Test a binding from an xml fragment from a foreign namespace.
279
JNDIBinding properties = values[3];
280       Object JavaDoc value = properties.getValue();
281       assertTrue("values[3] name is ctx2/key1", properties.getName().equals("ctx2/key1"));
282       assertTrue("values[3] is java.util.Properties", value instanceof Properties JavaDoc);
283       Properties JavaDoc props = (Properties JavaDoc) value;
284       assertTrue("Properties(key1) == value1", props.getProperty("key1").equals("value1"));
285       assertTrue("Properties(key2) == value2", props.getProperty("key2").equals("value2"));
286
287       // Test binding from a text to InetAddress based on the editor attribute PropertyEditor
288
JNDIBinding host = values[4];
289       assertTrue("values[4] name is hosts/localhost", host.getName().equals("hosts/localhost"));
290       assertTrue(host.isTrim());
291       assertTrue("values[4] text is 127.0.0.1",
292          host.getText().equals("127.0.0.1"));
293       assertTrue("values[4] editor is org.jboss.util.propertyeditor.InetAddressEditor",
294          host.getEditor().equals("org.jboss.util.propertyeditor.InetAddressEditor"));
295       Object JavaDoc value4 = host.getValue();
296       InetAddress JavaDoc hostValue = (InetAddress JavaDoc) value4;
297       InetAddress JavaDoc localhost = InetAddress.getByName("127.0.0.1");
298       assertTrue("values[4] value is InetAddress(127.0.0.1)",
299          hostValue.getHostAddress().equals(localhost.getHostAddress()));
300
301    }
302
303    // Private
304

305    private InputStream JavaDoc getResource(String JavaDoc path)
306       throws IOException JavaDoc
307    {
308       URL JavaDoc url = Thread.currentThread().getContextClassLoader().getResource(path);
309       if(url == null)
310       {
311          fail("URL not found: " + path);
312       }
313       return url.openStream();
314    }
315 }
316
Popular Tags