KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mmbase > applications > packaging > projects > creators > dataapptools > Apps1DataWriter


1 /*
2
3 This software is OSI Certified Open Source Software.
4 OSI Certified is a certification mark of the Open Source Initiative.
5
6 The license (Mozilla version 1.0) can be read at the MMBase site.
7 See http://www.MMBase.org/license
8
9 */

10 package org.mmbase.applications.packaging.projects.creators.dataapptools;
11
12 import java.io.*;
13 import java.util.*;
14 import org.mmbase.module.core.*;
15 import org.mmbase.util.logging.*;
16
17 import org.mmbase.module.corebuilders.*;
18 import org.mmbase.applications.packaging.projects.*;
19
20 /**
21  */

22 public class Apps1DataWriter {
23
24     /**
25      * Logging instance
26      */

27     private static Logger log = Logging.getLoggerInstance(Apps1DataWriter.class.getName());
28
29     public static boolean write(HashSet fb,String JavaDoc alias,String JavaDoc builder,String JavaDoc where,int depth,String JavaDoc datafile,String JavaDoc datapath,Target target) {
30
31     int startnode = getStartNode(alias,builder,where);
32
33         // the trick is to get all nodes until depth x and filter them
34
HashSet relnodes = new HashSet();
35         HashSet nodes = new HashSet();
36         getSubNodes(startnode,depth,fb, nodes,relnodes);
37
38         writeDataXML(fb,datafile,target);
39         writeNodes(fb,nodes,relnodes,datapath);
40
41     /*
42
43         // create the dir for the Data & resource files
44         File file = new File(targetpath+"/"+app.getApplicationName());
45         try {
46             file.mkdirs();
47         } catch(Exception e) {
48             log.error("Can't create dir : "+targetpath+"/"+app.getApplicationName());
49         }
50         */

51
52         return true;
53     }
54
55     static void writeNodes(HashSet builders,HashSet nodes,HashSet relnodes, String JavaDoc targetpath) {
56
57         // create a list of writer objects for the nodes
58
Hashtable nodeWriters = new Hashtable();
59         Iterator res = builders.iterator();
60         while (res.hasNext()) {
61             Integer JavaDoc i = (Integer JavaDoc)res.next();
62         String JavaDoc nb = MMBase.getMMBase().getTypeDef().getValue(i.intValue());
63         MMObjectBuilder bul=MMBase.getMMBase().getMMObject(nb);
64         boolean isRelation = false;
65         if (bul instanceof InsRel) isRelation = true;
66             // Create nodewriter for this builder
67
NodeWriter nw = new NodeWriter(targetpath, nb, isRelation);
68             // and store in table
69
nodeWriters.put(nb,nw);
70         }
71
72         MMObjectBuilder bul = MMBase.getMMBase().getMMObject("typedef"); // get Typedef object
73
int nrofnodes=0; // set total nodes to export to zero (is this used?).
74
// Store all the nodes that apply using their corresponding NodeWriter object
75
for (Iterator nods=nodes.iterator(); nods.hasNext(); ) {
76         // retrieve the node to export
77
int nr = ((Integer JavaDoc)nods.next()).intValue();
78             MMObjectNode node = bul.getNode(nr);
79             String JavaDoc name = node.getName();
80             NodeWriter nodeWriter = (NodeWriter)nodeWriters.get(name);
81             // export the node if the writer was found
82
if (nodeWriter!=null) {
83                 nodeWriter.write(node);
84                 nrofnodes++;
85             } else {
86         log.info("error missing nodeWriter : "+name);
87         }
88         }
89
90         for (Iterator nods=relnodes.iterator(); nods.hasNext(); ) {
91         // retrieve the node to export
92
int nr = ((Integer JavaDoc)nods.next()).intValue();
93             MMObjectNode node = bul.getNode(nr);
94             String JavaDoc name = node.getName();
95             NodeWriter nodeWriter = (NodeWriter)nodeWriters.get(name);
96             // export the node if the writer was found
97
if (nodeWriter!=null) {
98                 nodeWriter.write(node);
99                 nrofnodes++;
100             } else {
101         log.info("error missing nodeWriter : "+name);
102         }
103         }
104
105         // close the files.
106
for (Enumeration e = nodeWriters.keys(); e.hasMoreElements();) {
107             String JavaDoc name = (String JavaDoc)e.nextElement();
108             NodeWriter nodeWriter;
109             nodeWriter = (NodeWriter)nodeWriters.get(name);
110             nodeWriter.done();
111         }
112     }
113
114     /**
115     * Determines the number of the node referenced by another node.
116     * @param nodeNumber number of the referencing node
117     * @param relationNode node from the relationtable containing the relation data
118     * @returns An <code>int</code> value for the number of the node referenced
119     */

120     static int getRelatedNode(int nodeNumber, MMObjectNode relationNode) {
121         int snumber = relationNode.getIntValue("snumber"); // referenced node is either source
122
if (snumber == nodeNumber) {
123             return relationNode.getIntValue("dnumber"); // or destination
124
} else {
125             return snumber;
126         }
127     }
128
129     static void getSubNodes(int startnodenr, int maxdepth, HashSet fb, HashSet nodesdoneSet, HashSet relationnodesSet) {
130     MMBase mmb=MMBase.getMMBase();
131         HashSet nodesSet_current = null; // holds all nodes not yet 'done' that are on the current level
132
HashSet nodesSet_next = new HashSet(); // holds all nodes not yet 'done' that are on the next level
133
InsRel bul = mmb.getInsRel(); // builder for collecting relations. should be changed to MMRelations later on!
134
Integer JavaDoc type = new Integer JavaDoc(bul.getNodeType(startnodenr)); // retrieve node type (new method in MMObjectBuiilder)
135
if (!fb.contains(type)) { // exit if the type of this node conflicts.
136
// essentially, no nodes are added. This can only occur if the context of
137
// an application specified an invalid node.
138
return;
139         }
140         nodesSet_next.add(new Integer JavaDoc(startnodenr)); // add the very first node to the set...
141
// For each depth of the tree, traverse the nodes on that depth
142
for (int curdepth=1;curdepth<=maxdepth;curdepth++) {
143             nodesSet_current = nodesSet_next; // use the next level of nodes to tarverse
144
nodesSet_next = new HashSet(); // and create a new holder for the nodes one level deeper
145

146             // since the nodes on this level are 'almost done', and therefor should be skipped
147
// when referenced in the next layer, add the current set to the set of nodes that are 'done'
148
//
149
nodesdoneSet.addAll(nodesSet_current);
150             // iterate through the current level
151
for (Iterator curlist=nodesSet_current.iterator(); curlist.hasNext();) {
152                 // get the next node's number
153
Integer JavaDoc thisnodenr = (Integer JavaDoc)curlist.next();
154                 // Iterate through all the relations of a node
155
// determining relations has to be adapted when using MMRelations!
156
for (Iterator rel=bul.getRelationsVector(thisnodenr.intValue()).iterator(); rel.hasNext();) {
157                     // get the relation node and node number
158
MMObjectNode relnode=(MMObjectNode)rel.next();
159                     Integer JavaDoc relnumber=new Integer JavaDoc(relnode.getIntValue("number"));
160                     // check whether to add the referenced node
161
// and the relation between this node and the referenced one.
162
// if relation is in pool, save trouble and do not traverse further
163
if (!relationnodesSet.contains(relnumber)) {
164                         // determine node referenced
165
int nodenumber=getRelatedNode(thisnodenr.intValue(),relnode);
166                         // check type of referenced node
167
type = new Integer JavaDoc(bul.getNodeType(nodenumber));
168                         if (fb.contains(type)) { // good node? then proceed
169
// add the relation node
170
relationnodesSet.add(relnumber);
171                             // if the node has been 'done', don't add it!
172
Integer JavaDoc nodeNumber=new Integer JavaDoc(nodenumber);
173                             if (!nodesdoneSet.contains(nodeNumber)) {
174                                 // because we use a set, no double nodes will be added (cool, uh?)
175
nodesSet_next.add(nodeNumber);
176                             }
177                         }
178                     }
179                 }
180             }
181         }
182         // add the last retrieved set to the set of nodes that are 'done'
183
nodesdoneSet.addAll(nodesSet_next);
184         return;
185     }
186
187     /*
188     static HashSet getWantedBuilders(Vector filter,TypeDef bul) {
189         HashSet resultset=new HashSet();
190         for(Iterator res=filter.iterator(); res.hasNext(); ) {
191             Hashtable bset=(Hashtable)res.next();
192             String name=(String)bset.get("name");
193             int value=bul.getIntValue(name);
194             if (value!=-1) {
195                 resultset.add(new Integer(value));
196             } else {
197                 log.error("XMLContextDepthWriter -> can't get intvalue for : "+name);
198             }
199         }
200         return resultset;
201     }
202     */

203
204
205     static int getStartNode(String JavaDoc alias,String JavaDoc builder,String JavaDoc where) {
206         // first check for an alias
207
if (alias!=null) {
208             // if so, get the node associated with that alias
209
OAlias bul=(OAlias)MMBase.getMMBase().getMMObject("oalias");
210             int number=bul.getNumber(alias);
211             if (number==-1) log.error("Invalid Start Node Alias please make sure its valid");
212             return number;
213         } else {
214             // otherwise, get a builder and the where clause to run on that builder
215

216             // retrieve the actual builder
217
MMObjectBuilder bul=MMBase.getMMBase().getMMObject(builder);
218             if (bul!=null) {
219                 // find the nodes that match
220
Enumeration results=bul.search(where);
221                 // check if there are any nodes
222
if (results.hasMoreElements()) {
223                     // then return the first node found.
224
MMObjectNode node=(MMObjectNode)results.nextElement();
225                     return node.getIntValue("number");
226                 }
227             } else {
228                 log.error("ContextDepthWriter-> can't find builder ("+builder+")");
229             }
230         }
231         log.error("Invalid Start Node please fix your 'where' settings or use a alias");
232         return -1;
233     }
234
235     /**
236      * Saves a string value to a file.
237      * @param filename Name of the file to save.
238      * @param value string to store in the file
239      * @return True if succesfull, false if an error occurred.
240      */

241     static boolean saveFile(String JavaDoc filename,String JavaDoc value) {
242         File sfile = new File(filename);
243         try {
244             DataOutputStream scan = new DataOutputStream(new FileOutputStream(sfile));
245             scan.writeBytes(value);
246             scan.flush();
247             scan.close();
248         } catch(Exception JavaDoc e) {
249             log.error(e);
250             log.error(Logging.stackTrace(e));
251             return false;
252         }
253         return true;
254     }
255
256     /**
257      * Saves an array of byte to a file.
258      * @param filename Name of the file to save.
259      * @param value array to stiore in the file
260      * @return True if succesfull, false if an error occurred.
261      */

262     static boolean saveFile(String JavaDoc filename,byte[] value) {
263         File sfile = new File(filename);
264         try {
265             DataOutputStream scan = new DataOutputStream(new FileOutputStream(sfile));
266             scan.write(value);
267             scan.flush();
268             scan.close();
269         } catch(Exception JavaDoc e) {
270             log.error(e);
271             log.error(Logging.stackTrace(e));
272             return false;
273         }
274         return true;
275     }
276
277     public static boolean writeDataXML(HashSet fb,String JavaDoc datafile,Target target) {
278         String JavaDoc body="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
279         body+="<!DOCTYPE dataset PUBLIC \"-//MMBase/DTD dataset config 1.0//EN\" \"http://www.mmbase.org/dtd/dataset_1_0.dtd\">\n";
280         body+="<dataset>\n";
281     /* not sure if ill keep these
282         body+="\t<creationinfo>\n";
283         body+="\t\t<creator name=\"example\" maintainer=\"submarine\" version=\"2\" />\n";
284         body+="\t\t<creationtime>Thu Oct 28 13:07:25 CEST 2004</creationtime>\n";
285         body+="\t\t<creatorcomments>This is a fake file made by hand</creatorcomments>\n";
286         body+="\t</creationinfo>\n";
287     */

288         body+="\t<objectsets>\n";
289         Iterator res = fb.iterator();
290         while (res.hasNext()) {
291             Integer JavaDoc i = (Integer JavaDoc)res.next();
292             String JavaDoc nb = MMBase.getMMBase().getTypeDef().getValue(i.intValue());
293             MMObjectBuilder bul=MMBase.getMMBase().getMMObject(nb);
294             if (!(bul instanceof InsRel)) {
295         body+="\t\t<objectset builder=\""+nb+"\" path=\"data/"+nb+".xml\" />\n";
296         }
297     }
298         body+="\t</objectsets>\n";
299         body+="\t<relationsets>\n";
300         res = fb.iterator();
301         while (res.hasNext()) {
302             Integer JavaDoc i = (Integer JavaDoc)res.next();
303             String JavaDoc nb = MMBase.getMMBase().getTypeDef().getValue(i.intValue());
304             MMObjectBuilder bul=MMBase.getMMBase().getMMObject(nb);
305             if (bul instanceof InsRel) {
306         body+="\t\t<relationset builder=\""+nb+"\" path=\"data/"+nb+".xml\" />\n";
307         }
308     }
309         body+="\t</relationsets>\n";
310     String JavaDoc type=(String JavaDoc)target.getItem("type");
311         body+="\t<selection type=\""+type+"\">\n";
312     if (type.equals("depth")) {
313             body+="\t\t<model name=\""+target.getItem("depthname")+"\" maintainer=\""+target.getItem("depthmaintainer")+"\" version=\""+target.getItem("depthversion")+"\" />\n";
314         String JavaDoc alias=(String JavaDoc)target.getItem("depthalias");
315         if (alias!=null && !alias.equals("")) {
316                 body+="\t\t<startnode alias=\""+alias+"\">\n";
317         } else {
318                 body+="\t\t<startnode>\n";
319         }
320         String JavaDoc builder=(String JavaDoc)target.getItem("depthbuilder");
321         if (builder!=null && !builder.equals("")) {
322                 body+="\t\t\t<builder>"+builder+"</builder>\n";
323                 body+="\t\t\t<where>"+target.getItem("depthwhere")+"</where>\n";
324         }
325             body+="\t\t</startnode>\n";
326             body+="\t\t<depth>"+target.getItem("depth")+"</depth>\n";
327     }
328         body+="\t</selection>\n";
329         body+="</dataset>\n";
330         saveFile(datafile,body);
331         return true;
332     }
333
334 }
335
Popular Tags