KickJava   Java API By Example, From Geeks To Geeks.

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


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.module.corebuilders.InsRel;
16
17 import org.mmbase.core.CoreField;
18
19 import org.mmbase.util.logging.*;
20 import org.mmbase.util.*;
21
22 /**
23  * @todo This look a remarkable lot like {@link org.mmbase.util.NodeWriter}. One of them has to go!
24  * @version $Id: NodeWriter.java,v 1.6 2006/03/24 13:08:30 nklasens Exp $
25  */

26 public class NodeWriter{
27
28     // logger
29
private static final Logger log = Logging.getLoggerInstance(NodeWriter.class);
30
31     private MMBase mmb;
32     private String JavaDoc directory;
33     private String JavaDoc builderName;
34     private boolean isRelationNode;
35     private File file;
36     private OutputStreamWriter fw;
37     private int nrOfNodes;
38
39     /**
40      * Constructor, opens the initial xml file and writes a header.
41      * The file opened for writing is [directory]/[buildername].xml.
42      *
43      * @param mmb MMBase object for retrieving type information
44      * @param directory the directory to write the files to (including the
45      * trailing slash).
46      * @param buildername name of the builder to export
47      * @param isRelationNode if <code>true</code>, the source to write is a relationsource.
48      * Otherwise, a datasource is written.
49      */

50     NodeWriter(String JavaDoc directory, String JavaDoc builderName, boolean isRelationNode) {
51         // store parameters
52
this.mmb = MMBase.getMMBase();
53         this.directory = directory;
54         this.builderName = builderName;
55         this.isRelationNode = isRelationNode;
56         // define and open the file to write
57
file = new File(directory + builderName + ".xml");
58         try {
59             log.debug("Opening " + file + " for writing.");
60             fw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
61         } catch (Exception JavaDoc e) {
62             //resultsmsgs.addElement("Failed opening file " + file);
63
}
64         // Write the header
65
write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
66         write("<!DOCTYPE objectset PUBLIC \"-//MMBase/DTD objectset config 1.0//EN\" \"http://www.mmbase.org/dtd/objectset_1_0.dtd\">\n");
67         Calendar cal= Calendar.getInstance();
68         long htimestamp=cal.get(Calendar.YEAR)*10000+
69                        (cal.get(Calendar.MONTH)+1)*100+
70                        cal.get(Calendar.DAY_OF_MONTH);
71         long ltimestamp= cal.get(Calendar.AM_PM)*120000+
72                          cal.get(Calendar.HOUR)*10000+
73                          cal.get(Calendar.MINUTE)*100+
74                          cal.get(Calendar.SECOND);
75         long timestamp=(htimestamp*1000000)+ltimestamp;
76
77     if (isRelationNode) {
78             write("<relationset type=\"" + builderName + "\" exportsource=\"mmbase://"+mmb.getHost()+"/"+mmb.getStorageManagerFactory().getCatalog()+"/"+mmb.getBaseName()+"\" timestamp=\""+timestamp+"\">\n");
79     } else {
80             write("<objectset type=\"" + builderName + "\" exportsource=\"mmbase://"+mmb.getHost()+"/"+mmb.getStorageManagerFactory().getCatalog()+"/"+mmb.getBaseName()+"\" timestamp=\""+timestamp+"\">\n");
81     }
82         // initialize the nr of nodes written
83
nrOfNodes = 0;
84     }
85
86     /**
87     * Writes a node (object) to the datasource file.
88     * Relationsources are stored in a slightly different format from data sources.
89     * @param node The object to store.
90     */

91     public void write(MMObjectNode node) {
92         // retrieve basic information of the node
93
int number=node.getIntValue("number");
94         String JavaDoc owner=node.getStringValue("owner");
95         // start writing the node
96
if (isRelationNode) {
97             // For a relationnode, the fields snumber, dnumber and rnumber are stored as
98
// named references (as snumber, rnumber, and rtype).
99
// determine the relation 'type' (use the value of sname in RelDef, or the
100
// current buildername by default)
101
String JavaDoc rtype = builderName;
102             int rnumber=node.getIntValue("rnumber");
103             MMObjectNode reldefnode=mmb.getRelDef().getNode(rnumber);
104             if (reldefnode!=null) {
105                 rtype = reldefnode.getStringValue("sname");
106             }
107             write("\t<relation number=\""+number+"\" owner=\""+owner+"\" snumber=\""+ node.getIntValue("snumber") +"\" dnumber=\""+ node.getIntValue("dnumber") +"\" rtype=\""+ rtype +"\"");
108             // add directionality if used
109
if (InsRel.usesdir) {
110                 int dir=node.getIntValue("dir");
111                 if (dir==1) {
112                     write(" dir=\"unidirectional\"");
113                 } else {
114                     write(" dir=\"bidirectional\"");
115                 }
116             }
117             write(">\n");
118         } else {
119             // For a data node, store the alias if at all possible.
120
String JavaDoc tm=mmb.getOAlias().getAlias(number);
121             if (tm==null) {
122                 write("\t<object number=\""+number+"\" owner=\""+owner+"\">\n");
123             } else {
124                 write("\t<object number=\""+number+"\" owner=\""+owner+"\" alias=\""+tm+"\">\n");
125             }
126         }
127     MMObjectBuilder bul = node.getBuilder();
128     Iterator nd = bul.getFields().iterator();
129         while (nd.hasNext()) {
130             CoreField def=(CoreField)nd.next();
131             if (def.inStorage()) {
132                 String JavaDoc key=def.getName();
133                 if (isRelationNode) {
134                     // note that the routine below assumes
135
// fields in a relation node cannot contain binary blobs
136
//
137
if (!key.equals("number") && !key.equals("owner")
138                             && !key.equals("otype")
139                             && !key.equals("snumber") && !key.equals("dnumber")
140                             && !key.equals("rnumber") && !key.equals("dir") && !def.isTemporary()) {
141                         write("\t\t<field name=\""+key+"\">"+node.getValue(key)+"</field>\n");
142                     }
143                 } else {
144                     //due to current tcp implementation sometimes nodeField are created
145
//those fiels always start with an underscore. If a node starts with
146
//we skip it
147
if (!def.isTemporary()) {
148                             write(writeXMLField(key, node, directory, mmb));
149                     }
150                 }
151             }
152         }
153         // end the node
154
if (isRelationNode) {
155             write("\t</relation>\n\n");
156     } else {
157             write("\t</object>\n\n");
158     }
159         nrOfNodes++;
160     }
161
162     /**
163     * Writes a footer to the xml file, and closes the file.
164     */

165     public void done() {
166         // write the footer
167
if (isRelationNode) {
168             write("</relationset>\n");
169     } else {
170             write("</objectset>\n");
171     }
172         try {
173             log.debug("Closing file " + file);
174             fw.close();
175         } catch (Exception JavaDoc e) {
176             //resultsmsgs.addElement("Failed closing file " + file);
177
}
178     }
179
180     /**
181     * Writes a string datasource file.
182     * @param s The string to store.
183     */

184     private void write(String JavaDoc s) {
185         try {
186             fw.write(s);
187         } catch (Exception JavaDoc e) {
188             //resultsmsgs.addElement("Failed writing to file " + file);
189
}
190     }
191
192     /**
193     * Creates a description string of a field in a node for use in a datasource file.
194     * Binary data (such as images) are stored as seperate binary files, the string then contains
195     * a reference in lieu of the actual value.
196     * A number of 'special purpose' fields (number, owner, otype) are skipped and not written.
197     * Other fields are added 'in line'.
198     * @param key the fieldname to store
199     * @param node The node wose field to store
200     * @param targetpath the path where any binary files may be stored
201     * @param mmb MMBase object for retrieving type info
202     * @return A <code>String</code> descriving in xml-format the field's content (or a reference to that content)
203     */

204     private static String JavaDoc writeXMLField(String JavaDoc key,MMObjectNode node, String JavaDoc targetpath,MMBase mmb) {
205         if (!key.equals("number") && !key.equals("owner") && !key.equals("otype")) {
206             // this is a bad way of doing it imho
207
int type=node.getDBType(key);
208             String JavaDoc stype=mmb.getTypeDef().getValue(node.getIntValue("otype"));
209             if (type == CoreField.TYPE_BYTE) {
210                 String JavaDoc body="\t\t<field name=\""+key+"\" file=\""+stype+"/"+node.getIntValue("number")+"."+key+"\" />\n";
211                 File file = new File(targetpath+stype);
212                 try {
213                     file.mkdirs();
214                 } catch(Exception JavaDoc e) {
215                     log.error("Can't create dir : "+targetpath+stype);
216                 }
217                 byte[] value=node.getByteValue(key);
218                 saveFile(targetpath+stype+"/"+node.getIntValue("number")+"."+key,value);
219                 return body;
220             } else {
221                 String JavaDoc body="\t\t<field name=\""+key+"\">"+Encode.encode("ESCAPE_XML", "" + Casting.toString(node.getValue(key))) +"</field>\n";
222                 return body;
223            }
224         }
225         return "";
226     }
227
228     /**
229     * Stores binary data in a file
230     * @param filename path of the file to store the data
231     * @param value binary data to store (byte array)
232     * @return <code>true</code> if the write was succesful, <code>false</code> if an exception occurred
233     */

234     static boolean saveFile(String JavaDoc filename,byte[] value) {
235         File sfile = new File(filename);
236         try {
237             DataOutputStream scan = new DataOutputStream(new FileOutputStream(sfile));
238             scan.write(value);
239             scan.flush();
240             scan.close();
241         } catch(Exception JavaDoc e) {
242             log.error(e.toString());
243             log.error(Logging.stackTrace(e));
244             return false;
245         }
246         return true;
247     }
248
249 }
250
Popular Tags