KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > geronimo > system > configuration > GBeanOverride


1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.geronimo.system.configuration;
18
19 import java.beans.PropertyEditor JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.PrintWriter JavaDoc;
22 import java.io.StringWriter JavaDoc;
23 import java.io.Serializable JavaDoc;
24 import java.io.StringReader JavaDoc;
25 import java.net.URI JavaDoc;
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collections JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.LinkedHashMap JavaDoc;
31 import java.util.LinkedHashSet JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.Set JavaDoc;
34
35 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
36 import javax.xml.parsers.DocumentBuilder JavaDoc;
37
38 import org.apache.geronimo.common.propertyeditor.PropertyEditors;
39 import org.apache.geronimo.gbean.AbstractName;
40 import org.apache.geronimo.gbean.AbstractNameQuery;
41 import org.apache.geronimo.gbean.GAttributeInfo;
42 import org.apache.geronimo.gbean.GBeanData;
43 import org.apache.geronimo.gbean.GBeanInfo;
44 import org.apache.geronimo.gbean.ReferencePatterns;
45 import org.apache.geronimo.kernel.InvalidGBeanException;
46 import org.apache.geronimo.kernel.util.XmlUtil;
47 import org.apache.geronimo.kernel.repository.Artifact;
48 import org.apache.geronimo.util.EncryptionManager;
49 import org.w3c.dom.Element JavaDoc;
50 import org.w3c.dom.Node JavaDoc;
51 import org.w3c.dom.NodeList JavaDoc;
52 import org.w3c.dom.Document JavaDoc;
53 import org.xml.sax.InputSource JavaDoc;
54
55 /**
56  * @version $Rev: 476049 $ $Date: 2006-11-16 23:35:17 -0500 (Thu, 16 Nov 2006) $
57  */

58 public class GBeanOverride implements Serializable JavaDoc {
59     private final Object JavaDoc name;
60     private boolean load;
61     private final Map JavaDoc attributes = new LinkedHashMap JavaDoc();
62     private final Map JavaDoc references = new LinkedHashMap JavaDoc();
63     private final ArrayList JavaDoc clearAttributes = new ArrayList JavaDoc();
64     private final ArrayList JavaDoc nullAttributes = new ArrayList JavaDoc();
65     private final ArrayList JavaDoc clearReferences = new ArrayList JavaDoc();
66     private final String JavaDoc gbeanInfo;
67
68     public GBeanOverride(String JavaDoc name, boolean load) {
69         this.name = name;
70         this.load = load;
71         gbeanInfo = null;
72     }
73
74     public GBeanOverride(AbstractName name, boolean load) {
75         this.name = name;
76         this.load = load;
77         gbeanInfo = null;
78     }
79
80     public GBeanOverride(GBeanData gbeanData) throws InvalidAttributeException {
81         GBeanInfo gbeanInfo = gbeanData.getGBeanInfo();
82         this.gbeanInfo = gbeanInfo.getSourceClass();
83         if (this.gbeanInfo == null) {
84             throw new IllegalArgumentException JavaDoc("GBeanInfo must have a source class set");
85         }
86         name = gbeanData.getAbstractName();
87         load = true;
88
89         // set attributes
90
for (Iterator JavaDoc iterator = gbeanData.getAttributes().entrySet().iterator(); iterator.hasNext();) {
91             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
92             String JavaDoc attributeName = (String JavaDoc) entry.getKey();
93             GAttributeInfo attributeInfo = gbeanInfo.getAttribute(attributeName);
94             if (attributeInfo == null) {
95                 throw new InvalidAttributeException("No attribute: " + attributeName + " for gbean: " + gbeanData.getAbstractName());
96             }
97             Object JavaDoc attributeValue = entry.getValue();
98             setAttribute(attributeName, attributeValue, attributeInfo.getType());
99         }
100
101         // references can be coppied in blind
102
references.putAll(gbeanData.getReferences());
103     }
104
105     public GBeanOverride(Element JavaDoc gbean) throws InvalidGBeanException {
106         String JavaDoc nameString = gbean.getAttribute("name");
107         if (nameString.indexOf('?') > -1) {
108             name = new AbstractName(URI.create(nameString));
109         } else {
110             name = nameString;
111         }
112
113         String JavaDoc gbeanInfoString = gbean.getAttribute("gbeanInfo");
114         if (gbeanInfoString.length() > 0) {
115             gbeanInfo = gbeanInfoString;
116         } else {
117             gbeanInfo = null;
118         }
119         if (gbeanInfo != null && !(name instanceof AbstractName)) {
120             throw new InvalidGBeanException("A gbean element using the gbeanInfo attribute must be specified using a full AbstractName: name=" + nameString);
121         }
122
123         String JavaDoc loadString = gbean.getAttribute("load");
124         load = !"false".equals(loadString);
125
126         // attributes
127
NodeList JavaDoc attributes = gbean.getElementsByTagName("attribute");
128         for (int a = 0; a < attributes.getLength(); a++) {
129             Element JavaDoc attribute = (Element JavaDoc) attributes.item(a);
130
131             String JavaDoc attributeName = attribute.getAttribute("name");
132
133             // Check to see if there is a value attribute
134
if (attribute.hasAttribute("value")) {
135                 setAttribute(attributeName, (String JavaDoc) EncryptionManager.decrypt(attribute.getAttribute("value")));
136                 continue;
137             }
138
139             // Check to see if there is a null attribute
140
if (attribute.hasAttribute("null")) {
141                 String JavaDoc nullString = attribute.getAttribute("null");
142                 if (nullString.equals("true")) {
143                     setNullAttribute(attributeName);
144                     continue;
145                 }
146             }
147
148             String JavaDoc rawAttribute = getContentsAsText(attribute);
149             // If there are no contents, then it's to be cleared
150
if (rawAttribute.length() == 0) {
151                 setClearAttribute(attributeName);
152                 continue;
153             }
154             String JavaDoc attributeValue = (String JavaDoc) EncryptionManager.decrypt(rawAttribute);
155
156             setAttribute(attributeName, attributeValue);
157         }
158
159         // references
160
NodeList JavaDoc references = gbean.getElementsByTagName("reference");
161         for (int r = 0; r < references.getLength(); r++) {
162             Element JavaDoc reference = (Element JavaDoc) references.item(r);
163
164             String JavaDoc referenceName = reference.getAttribute("name");
165
166             Set JavaDoc objectNamePatterns = new LinkedHashSet JavaDoc();
167             NodeList JavaDoc patterns = reference.getElementsByTagName("pattern");
168
169             // If there is no pattern, then its an empty set, so its a
170
// cleared value
171
if (patterns.getLength() == 0) {
172                 setClearReference(referenceName);
173                 continue;
174             }
175
176             for (int p = 0; p < patterns.getLength(); p++) {
177                 Element JavaDoc pattern = (Element JavaDoc) patterns.item(p);
178                 if (pattern == null)
179                     continue;
180
181                 String JavaDoc groupId = getChildAsText(pattern, "groupId");
182                 String JavaDoc artifactId = getChildAsText(pattern, "artifactId");
183                 String JavaDoc version = getChildAsText(pattern, "version");
184                 String JavaDoc type = getChildAsText(pattern, "type");
185                 String JavaDoc module = getChildAsText(pattern, "module");
186                 String JavaDoc name = getChildAsText(pattern, "name");
187
188                 Artifact referenceArtifact = null;
189                 if (artifactId != null) {
190                     referenceArtifact = new Artifact(groupId, artifactId, version, type);
191                 }
192                 Map JavaDoc nameMap = new HashMap JavaDoc();
193                 if (module != null) {
194                     nameMap.put("module", module);
195                 }
196                 if (name != null) {
197                     nameMap.put("name", name);
198                 }
199                 AbstractNameQuery abstractNameQuery = new AbstractNameQuery(referenceArtifact, nameMap, Collections.EMPTY_SET);
200                 objectNamePatterns.add(abstractNameQuery);
201             }
202
203             setReferencePatterns(referenceName, new ReferencePatterns(objectNamePatterns));
204         }
205     }
206
207     private static String JavaDoc getChildAsText(Element JavaDoc element, String JavaDoc name) throws InvalidGBeanException {
208         NodeList JavaDoc children = element.getElementsByTagName(name);
209         if (children == null || children.getLength() == 0) {
210             return null;
211         }
212         if (children.getLength() > 1) {
213             throw new InvalidGBeanException("invalid name, too many parts named: " + name);
214         }
215         return getContentsAsText((Element JavaDoc) children.item(0));
216     }
217
218     private static String JavaDoc getContentsAsText(Element JavaDoc element) throws InvalidGBeanException {
219         String JavaDoc value = "";
220         NodeList JavaDoc text = element.getChildNodes();
221         for (int t = 0; t < text.getLength(); t++) {
222             Node JavaDoc n = text.item(t);
223             if (n.getNodeType() == Node.TEXT_NODE) {
224                 value += n.getNodeValue();
225             } else {
226                 StringWriter JavaDoc sw = new StringWriter JavaDoc();
227                 PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw);
228                 OutputFormat of = new OutputFormat(Method.XML, null, false);
229                 of.setOmitXMLDeclaration(true);
230                 XMLSerializer serializer = new XMLSerializer(pw, of);
231                 try {
232                     serializer.prepare();
233                     serializer.serializeNode(n);
234                     value += sw.toString();
235                 } catch (IOException JavaDoc ioe) {
236                     throw new InvalidGBeanException("Error serializing GBean element", ioe);
237                 }
238             }
239         }
240         return value.trim();
241     }
242
243     public Object JavaDoc getName() {
244         return name;
245     }
246
247     public String JavaDoc getGBeanInfo() {
248         return gbeanInfo;
249     }
250
251     public boolean isLoad() {
252         return load;
253     }
254
255     public void setLoad(boolean load) {
256         this.load = load;
257     }
258
259     public Map JavaDoc getAttributes() {
260         return attributes;
261     }
262
263     public String JavaDoc getAttribute(String JavaDoc attributeName) {
264         return (String JavaDoc) attributes.get(attributeName);
265     }
266
267     public ArrayList JavaDoc getClearAttributes() {
268         return clearAttributes;
269     }
270
271     public ArrayList JavaDoc getNullAttributes() {
272         return nullAttributes;
273     }
274
275     public boolean getNullAttribute(String JavaDoc attributeName) {
276         return nullAttributes.contains(attributeName);
277     }
278
279     public boolean getClearAttribute(String JavaDoc attributeName) {
280         return clearAttributes.contains(attributeName);
281     }
282
283     public ArrayList JavaDoc getClearReferences() {
284         return clearReferences;
285     }
286
287     public boolean getClearReference(String JavaDoc referenceName) {
288         return clearReferences.contains(referenceName);
289     }
290
291     public void setClearAttribute(String JavaDoc attributeName) {
292         if (!clearAttributes.contains(attributeName))
293             clearAttributes.add(attributeName);
294     }
295
296     public void setNullAttribute(String JavaDoc attributeName) {
297         if (!nullAttributes.contains(attributeName))
298             nullAttributes.add(attributeName);
299     }
300
301     public void setClearReference(String JavaDoc referenceName) {
302         if (!clearReferences.contains(referenceName))
303             clearReferences.add(referenceName);
304     }
305
306     public void setAttribute(String JavaDoc attributeName, Object JavaDoc attributeValue, String JavaDoc attributeType) throws InvalidAttributeException {
307         String JavaDoc stringValue = getAsText(attributeValue, attributeType);
308         attributes.put(attributeName, stringValue);
309     }
310
311     public void setAttribute(String JavaDoc attributeName, String JavaDoc attributeValue) {
312         attributes.put(attributeName, attributeValue);
313     }
314
315     public Map JavaDoc getReferences() {
316         return references;
317     }
318
319     public ReferencePatterns getReferencePatterns(String JavaDoc name) {
320         return (ReferencePatterns) references.get(name);
321     }
322
323     public void setReferencePatterns(String JavaDoc name, ReferencePatterns patterns) {
324         references.put(name, patterns);
325     }
326
327     /**
328      * Creates a new child of the supplied parent with the data for this
329      * GBeanOverride, adds it to the parent, and then returns the new
330      * child element.
331      */

332     public Element JavaDoc writeXml(Document JavaDoc doc, Element JavaDoc parent) {
333         String JavaDoc gbeanName;
334         if (name instanceof String JavaDoc) {
335             gbeanName = (String JavaDoc) name;
336         } else {
337             gbeanName = name.toString();
338         }
339
340         Element JavaDoc gbean = doc.createElement("gbean");
341         parent.appendChild(gbean);
342         gbean.setAttribute("name", gbeanName);
343         if (gbeanInfo != null) {
344             gbean.setAttribute("gbeanInfo", gbeanInfo);
345         }
346         if (!load) {
347             gbean.setAttribute("load", "false");
348         }
349
350         // attributes
351
for (Iterator JavaDoc iterator = attributes.entrySet().iterator(); iterator.hasNext();) {
352             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
353             String JavaDoc name = (String JavaDoc) entry.getKey();
354             String JavaDoc value = (String JavaDoc) entry.getValue();
355             if (value == null) {
356                 setNullAttribute(name);
357             }
358             else {
359                 if (getNullAttribute(name)) {
360                     nullAttributes.remove(name);
361                 }
362                 if (name.toLowerCase().indexOf("password") > -1) {
363                     value = EncryptionManager.encrypt(value);
364                 }
365                 Element JavaDoc attribute = doc.createElement("attribute");
366                 attribute.setAttribute("name", name);
367                 gbean.appendChild(attribute);
368                 if (value.length() == 0) {
369                     attribute.setAttribute("value", "");
370                 }
371                 else {
372                     try {
373                         //
374
// NOTE: Construct a new document to handle mixed content attribute values
375
// then add nodes which are children of the first node. This allows
376
// value to be XML or text.
377
//
378

379                         DocumentBuilderFactory JavaDoc factory = XmlUtil.newDocumentBuilderFactory();
380                         DocumentBuilder JavaDoc builder = factory.newDocumentBuilder();
381
382                         // Wrap value in an element to be sure we can handle xml or text values
383
String JavaDoc xml = "<fragment>" + value + "</fragment>";
384                         InputSource JavaDoc input = new InputSource JavaDoc(new StringReader JavaDoc(xml));
385                         Document JavaDoc fragment = builder.parse(input);
386
387                         Node JavaDoc root = fragment.getFirstChild();
388                         NodeList JavaDoc children = root.getChildNodes();
389                         for (int i=0; i<children.getLength(); i++) {
390                             Node JavaDoc child = children.item(i);
391
392                             // Import the child (and its children) into the new document
393
child = doc.importNode(child, true);
394                             attribute.appendChild(child);
395                         }
396                     }
397                     catch (Exception JavaDoc e) {
398                         throw new RuntimeException JavaDoc("Failed to write attribute value fragment: " + e.getMessage(), e);
399                     }
400                 }
401             }
402         }
403
404         // cleared attributes
405
for (Iterator JavaDoc iterator = clearAttributes.iterator(); iterator.hasNext();) {
406             String JavaDoc name = (String JavaDoc) iterator.next();
407             Element JavaDoc attribute = doc.createElement("attribute");
408             gbean.appendChild(attribute);
409             attribute.setAttribute("name", name);
410         }
411
412         // Null attributes
413
for (Iterator JavaDoc iterator = nullAttributes.iterator(); iterator.hasNext();) {
414             String JavaDoc name = (String JavaDoc) iterator.next();
415             Element JavaDoc attribute = doc.createElement("attribute");
416             gbean.appendChild(attribute);
417             attribute.setAttribute("name", name);
418             attribute.setAttribute("null", "true");
419         }
420
421         // references
422
for (Iterator JavaDoc iterator = references.entrySet().iterator(); iterator.hasNext();) {
423             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
424             String JavaDoc name = (String JavaDoc) entry.getKey();
425             ReferencePatterns patterns = (ReferencePatterns) entry.getValue();
426
427             Element JavaDoc reference = doc.createElement("reference");
428             reference.setAttribute("name", name);
429             gbean.appendChild(reference);
430
431             Set JavaDoc patternSet;
432             if (patterns.isResolved()) {
433                 patternSet = Collections.singleton(new AbstractNameQuery(patterns.getAbstractName()));
434             } else {
435                 patternSet = patterns.getPatterns();
436             }
437
438             for (Iterator JavaDoc patternIterator = patternSet.iterator(); patternIterator.hasNext();) {
439                 AbstractNameQuery pattern = (AbstractNameQuery) patternIterator.next();
440                 Element JavaDoc pat = doc.createElement("pattern");
441                 reference.appendChild(pat);
442                 Artifact artifact = pattern.getArtifact();
443
444                 if (artifact != null) {
445                     if (artifact.getGroupId() != null) {
446                         Element JavaDoc group = doc.createElement("groupId");
447                         group.appendChild(doc.createTextNode(artifact.getGroupId()));
448                         pat.appendChild(group);
449                     }
450                     if (artifact.getArtifactId() != null) {
451                         Element JavaDoc art = doc.createElement("artifactId");
452                         art.appendChild(doc.createTextNode(artifact.getArtifactId()));
453                         pat.appendChild(art);
454                     }
455                     if (artifact.getVersion() != null) {
456                         Element JavaDoc version = doc.createElement("version");
457                         version.appendChild(doc.createTextNode(artifact.getVersion().toString()));
458                         pat.appendChild(version);
459                     }
460                     if (artifact.getType() != null) {
461                         Element JavaDoc type = doc.createElement("type");
462                         type.appendChild(doc.createTextNode(artifact.getType()));
463                         pat.appendChild(type);
464                     }
465                 }
466
467                 Map JavaDoc nameMap = pattern.getName();
468                 if (nameMap.get("module") != null) {
469                     Element JavaDoc module = doc.createElement("module");
470                     module.appendChild(doc.createTextNode(nameMap.get("module").toString()));
471                     pat.appendChild(module);
472                 }
473
474                 if (nameMap.get("name") != null) {
475                     Element JavaDoc patName = doc.createElement("name");
476                     patName.appendChild(doc.createTextNode(nameMap.get("name").toString()));
477                     pat.appendChild(patName);
478                 }
479             }
480         }
481
482         // cleared references
483
for (Iterator JavaDoc iterator = clearReferences.iterator(); iterator.hasNext();) {
484             String JavaDoc name = (String JavaDoc) iterator.next();
485             Element JavaDoc reference = doc.createElement("reference");
486             reference.setAttribute("name", name);
487             gbean.appendChild(reference);
488         }
489
490         return gbean;
491     }
492
493     public static String JavaDoc getAsText(Object JavaDoc value, String JavaDoc type) throws InvalidAttributeException {
494         try {
495             String JavaDoc attributeStringValue = null;
496             if (value != null) {
497                 PropertyEditor JavaDoc editor = PropertyEditors.findEditor(type, GBeanOverride.class.getClassLoader());
498                 if (editor == null) {
499                     throw new InvalidAttributeException("Unable to format attribute of type " + type + "; no editor found");
500                 }
501                 editor.setValue(value);
502                 attributeStringValue = editor.getAsText();
503             }
504             return attributeStringValue;
505         } catch (ClassNotFoundException JavaDoc e) {
506             //todo: use the Configuration's ClassLoader to load the attribute, if this ever becomes an issue
507
throw new InvalidAttributeException("Unable to store attribute type " + type);
508         }
509     }
510 }
511
Popular Tags