KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jac > aspects > export > Exporter


1 /*
2   Copyright (C) 2003-2004 Laurent Martelli <laurent@aopsys.com>
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU Lesser General Public License as
6   published by the Free Software Foundation; either version 2 of the
7   License, or (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12   GNU Lesser General Public License for more details.
13
14   You should have received a copy of the GNU Lesser General Public License
15   along with this program; if not, write to the Free Software
16   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */

17
18 package org.objectweb.jac.aspects.export;
19
20 import gnu.regexp.RE;
21 import java.io.File JavaDoc;
22 import java.io.FileOutputStream JavaDoc;
23 import java.io.IOException JavaDoc;
24 import java.io.OutputStream JavaDoc;
25 import java.io.OutputStreamWriter JavaDoc;
26 import java.io.Writer JavaDoc;
27 import java.lang.StringBuffer JavaDoc;
28 import java.util.Arrays JavaDoc;
29 import java.util.Collection JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.HashSet JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Set JavaDoc;
35 import org.apache.log4j.Logger;
36 import org.objectweb.jac.aspects.naming.NamingAC;
37 import org.objectweb.jac.aspects.persistence.ValueConverter;
38 import org.objectweb.jac.core.ACManager;
39 import org.objectweb.jac.core.MethodPointcut;
40 import org.objectweb.jac.core.NameRepository;
41 import org.objectweb.jac.core.Wrappee;
42 import org.objectweb.jac.core.rtti.ClassItem;
43 import org.objectweb.jac.core.rtti.ClassRepository;
44 import org.objectweb.jac.core.rtti.CollectionItem;
45 import org.objectweb.jac.core.rtti.FieldItem;
46 import org.objectweb.jac.util.Strings;
47
48 public class Exporter {
49     static Logger logger = Logger.getLogger("export");
50
51     Collection JavaDoc roots;
52     Collection JavaDoc allow;
53     Collection JavaDoc deny;
54
55     RE[] allowRegexps;
56     RE[] denyRegexps;
57
58     Map JavaDoc toExport = new HashMap JavaDoc(); // Objects not exported yet (OPath -> Object)
59
Set JavaDoc exported = new HashSet JavaDoc(); // Already exported objects
60

61
62     NameRepository nr;
63
64     /**
65      * @see #Exporter(Collection,Collection,Collection)
66      */

67     public Exporter(String JavaDoc[] roots, String JavaDoc[] allow, String JavaDoc[] deny) {
68         this(Arrays.asList(roots),Arrays.asList(allow),Arrays.asList(deny));
69     }
70
71     /**
72      * Creates a new exporter.
73      *
74      * @param roots collection of String naming root objects to start export from.
75      * @param allow collection of String naming classes to export
76      * @param deny collection of String naming classes not to export
77      *
78      * @see #Exporter(String[],String[],String[])
79      */

80     public Exporter(Collection JavaDoc roots, Collection JavaDoc allow, Collection JavaDoc deny) {
81         nr = (NameRepository)NameRepository.get();
82         this.roots = roots;
83         this.allow = allow;
84         Iterator JavaDoc i = allow.iterator();
85         int count = 0;
86         allowRegexps = new RE[allow.size()];
87         while (i.hasNext()) {
88             String JavaDoc s = (String JavaDoc)i.next();
89             try {
90                 allowRegexps[count] = MethodPointcut.buildRegexp(s);
91             } catch (Exception JavaDoc e) {
92                 logger.error("Failed to build regexp for "+s,e);
93             }
94         }
95         this.deny = deny;
96         i = deny.iterator();
97         count = 0;
98         denyRegexps = new RE[deny.size()];
99         while (i.hasNext()) {
100             String JavaDoc s = (String JavaDoc)i.next();
101             try {
102                 denyRegexps[count] = MethodPointcut.buildRegexp(s);
103             } catch (Exception JavaDoc e) {
104                 logger.error("Failed to build regexp for "+s,e);
105             }
106         }
107     }
108
109     /**
110      * Exports all objects to a file
111      */

112     public void export(File JavaDoc file) throws IOException JavaDoc {
113         FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(file);
114         try {
115             export(out);
116         } finally {
117             out.close();
118         }
119     }
120
121     /**
122      * Exports all objects to a stream, using UTF-8 encoding.
123      */

124     public void export(OutputStream JavaDoc outStream) throws IOException JavaDoc {
125         export(outStream,"UTF-8");
126     }
127
128     /**
129      * Exports all objects to a stream
130      */

131     public void export(OutputStream JavaDoc outStream, String JavaDoc encoding) throws IOException JavaDoc {
132         Writer JavaDoc out = new OutputStreamWriter JavaDoc(outStream,encoding);
133         out.write("<?xml version=\"1.0\" encoding=\""+encoding+"\"?>\n");
134         out.write("<export>\n");
135         int count = 0;
136         Iterator JavaDoc i = NameRepository.getObjects(roots).iterator();
137         while (i.hasNext()) {
138             Object JavaDoc o = i.next();
139             String JavaDoc name = nr.getName(o);
140             export(out,o,name,name);
141             count++;
142         }
143         while (!toExport.isEmpty()) {
144             i = new HashMap JavaDoc(toExport).entrySet().iterator();
145             while (i.hasNext()) {
146                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc)i.next();
147                 Object JavaDoc o = entry.getKey();
148                 String JavaDoc opath = (String JavaDoc)entry.getValue();
149                 String JavaDoc name = nr.getName(o);
150                 export(out,o,name,opath);
151                 count++;
152             }
153         }
154         logger.info(count+" objects exported");
155         Map JavaDoc counters =
156             ((NamingAC)ACManager.getACM().getACFromFullName("naming")).getNameCounters();
157         i = counters.entrySet().iterator();
158         while(i.hasNext()) {
159             Map.Entry JavaDoc entry = (Map.Entry JavaDoc)i.next();
160             out.write("<nameCounter>\n");
161             out.write(" <name>"+entry.getKey()+"</name>\n");
162             out.write(" <counter>"+entry.getValue()+"</counter>\n");
163             out.write("</nameCounter>\n");
164         }
165         logger.info("Name counters exported");
166         out.write("</export>\n");
167         out.flush();
168     }
169
170     static public String JavaDoc escapeChar(char c) {
171         return (c == '<') ? "&lt;" :
172             (c == '>') ? "&gt;" :
173             (c == '\'') ? "&apos;" :
174             (c == '\"') ? "&quot;" :
175             (c == '&') ? "&amp;" :
176             (c == ']') ? "&#93;" :
177             null;
178     }
179
180     static public String JavaDoc escapeString(String JavaDoc s) {
181         StringBuffer JavaDoc buf = new StringBuffer JavaDoc(s.length()*2);
182         for (int i=0; i<s.length(); i++) {
183             char c = s.charAt(i);
184             String JavaDoc escaped = escapeChar(c);
185             if (escaped==null)
186                 buf.append(c);
187             else
188                 buf.append(escaped);
189         }
190         return buf.toString();
191     }
192
193     /**
194      * Tells wether instances of a class should be exported or not
195      *
196      * @param cli a class item
197      * @return true if instances of this class should be
198      * exported. Instances of a class are exported if the class is not
199      * listed in the deny list and is listed in the allow list.
200      */

201     protected boolean allowExport(ClassItem cli) {
202         for (int i=0; i<denyRegexps.length;i++) {
203             RE regexp = denyRegexps[i];
204             if (regexp!=null && cli.isSubClassOf(regexp))
205                 return false;
206         }
207
208         for (int i=0; i<allowRegexps.length;i++) {
209             RE regexp = allowRegexps[i];
210             if (regexp!=null && cli.isSubClassOf(regexp))
211                 return true;
212         }
213
214         return false;
215     }
216
217     /**
218      * Exports an object to a stream
219      *
220      * @param out the stream to which to export
221      * @param o the object to export
222      * @param name name of the object to export
223      */

224     public void export(Writer JavaDoc out, Object JavaDoc o, String JavaDoc name ,String JavaDoc opath) throws IOException JavaDoc {
225         ClassItem cl = ClassRepository.get().getClass(o);
226         if (name==null) {
227             logger.error("Skipping unamed object "+o+" "+cl.getName()+" at "+opath);
228             new Exception JavaDoc().printStackTrace();
229             toExport.remove(o);
230             return;
231         }
232         if (exported.contains(o)) {
233             logger.debug("Skipping already exported "+name+" "+cl.getName());
234             toExport.remove(o);
235             return;
236         }
237         if (!allowExport(cl)) {
238             logger.debug("Skipping not allowed "+name+" "+cl.getName());
239             toExport.remove(o);
240             return;
241         }
242         logger.debug("Exporting "+name+" "+cl.getName());
243         exported.add(o);
244         out.write("<object name=\""+name+"\" class=\""+cl.getName()+"\">\n");
245         Iterator JavaDoc i = cl.getAllFields().iterator();
246         while (i.hasNext()) {
247             FieldItem field = (FieldItem)i.next();
248             if (!field.isCalculated() && !field.isTransient() &&
249                 !field.isStatic() && !field.isTransient())
250             {
251                 String JavaDoc newPath = opath+"."+field.getName();
252                 try {
253                     if (field instanceof CollectionItem) {
254                         CollectionItem collection = (CollectionItem)field;
255                         ClassItem componentType = collection.getComponentType();
256                         if (allowExport(componentType)) {
257                             out.write(" <field name=\""+field.getName()+"\">\n");
258                         if (collection.isMap()) {
259                             out.write(" <map>\n");
260                             Iterator JavaDoc j = ((Map JavaDoc)collection.getThroughAccessor(o)).entrySet().iterator();
261                             while (j.hasNext()) {
262                                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc)j.next();
263                                 out.write(" <entry><key>");
264                                 writeValue(out,entry.getKey(),newPath+"[key]");
265                                 out.write("</key><value>");
266                                 writeValue(out,entry.getValue(),newPath+"["+entry.getKey()+"]");
267                                 out.write("</value></entry>\n");
268                             }
269                             out.write(" </map>\n");
270                         } else {
271                             if (collection.isList())
272                                 out.write(" <list>\n");
273                             else if (collection.isSet())
274                                 out.write(" <set>\n");
275                             Iterator JavaDoc j = ((Collection JavaDoc)collection.getThroughAccessor(o)).iterator();
276                             int count = 0;
277                             while (j.hasNext()) {
278                                 Object JavaDoc item = j.next();
279                                 out.write(" ");
280                                 writeValue(out,item,newPath+"["+count+"]");
281                                 out.write("\n");
282                                 count++;
283                             }
284                             if (collection.isList())
285                                 out.write(" </list>\n");
286                             else if (collection.isSet())
287                                 out.write(" </set>\n");
288                         }
289                             out.write(" </field>\n");
290                         }
291                     } else {
292                         if (allowExport(field.getTypeItem())) {
293                             out.write(" <field name=\""+field.getName()+"\">\n");
294                         out.write(" ");
295                             writeValue(out,field.getThroughAccessor(o),newPath);
296                         out.write("\n");
297                             out.write(" </field>\n");
298                         }
299                     }
300                 } catch (Exception JavaDoc e) {
301                     logger.error("Failed to export "+name+"."+field);
302                 }
303             }
304         }
305         out.write("</object>\n");
306     }
307
308     protected void writeValue(Writer JavaDoc out, Object JavaDoc value, String JavaDoc opath) throws IOException JavaDoc {
309         if (value instanceof Wrappee) {
310             if (value!=null) {
311                 if (!exported.contains(value)) {
312                     toExport.put(value,opath);
313                     logger.debug("toExport "+opath+" -> "+value+" "+nr.getName(value));
314                 }
315                 out.write("<reference>"+nr.getName(value)+"</reference>");
316             } else {
317                 out.write("<reference>null</reference>");
318             }
319         } else {
320             if (value!=null) {
321                 out.write("<primitive_value>"+
322                           escapeString(Strings.slashify(ValueConverter.objectToString(null,value)))+
323                           "</primitive_value>");
324             } else {
325                 out.write("<primitive_value>null</primitive_value>");
326             }
327         }
328     }
329 }
330
Popular Tags