KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > webtools > WebToolsServices


1 /*
2  * Copyright (c) 2001-2005 The Open For Business Project - www.ofbiz.org
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included
12  * in all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
19  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
20  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21  */

22 package org.ofbiz.webtools;
23
24 import java.util.HashMap JavaDoc;
25 import java.util.Iterator JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Collection JavaDoc;
29 import java.util.TreeSet JavaDoc;
30 import java.util.Locale JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.io.File JavaDoc;
33 import java.io.InputStream JavaDoc;
34 import java.io.StringReader JavaDoc;
35 import java.io.StringWriter JavaDoc;
36 import java.io.FileReader JavaDoc;
37 import java.io.PrintWriter JavaDoc;
38 import java.io.BufferedWriter JavaDoc;
39 import java.io.OutputStreamWriter JavaDoc;
40 import java.io.FileOutputStream JavaDoc;
41 import java.io.IOException JavaDoc;
42 import java.io.FileNotFoundException JavaDoc;
43 import java.net.URL JavaDoc;
44 import java.net.MalformedURLException JavaDoc;
45
46 import javolution.util.FastMap;
47
48 import org.ofbiz.base.util.Debug;
49 import org.ofbiz.base.util.GeneralException;
50 import org.ofbiz.base.util.UtilMisc;
51 import org.ofbiz.base.util.UtilProperties;
52 import org.ofbiz.base.util.UtilURL;
53 import org.ofbiz.base.util.UtilValidate;
54 import org.ofbiz.base.util.UtilDateTime;
55 import org.ofbiz.entity.GenericDelegator;
56 import org.ofbiz.entity.GenericEntityException;
57 import org.ofbiz.entity.GenericValue;
58 import org.ofbiz.entity.util.EntityListIterator;
59 import org.ofbiz.entity.util.EntitySaxReader;
60 import org.ofbiz.entity.model.ModelReader;
61 import org.ofbiz.entity.model.ModelEntity;
62 import org.ofbiz.entity.model.ModelViewEntity;
63 import org.ofbiz.service.DispatchContext;
64 import org.ofbiz.service.GenericServiceException;
65 import org.ofbiz.service.LocalDispatcher;
66 import org.ofbiz.service.ServiceUtil;
67
68 import org.xml.sax.InputSource JavaDoc;
69 import org.w3c.dom.*;
70
71 import freemarker.template.*;
72 import freemarker.ext.dom.NodeModel;
73 import freemarker.ext.beans.BeansWrapper;
74
75 /**
76  * WebTools Services
77  *
78  * @author <a HREF="mailto:tiz@sastau.it">Jacopo Cappellato</a>
79  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
80  */

81
82 public class WebToolsServices {
83
84     public static final String JavaDoc module = WebToolsServices.class.getName();
85
86     public static Map JavaDoc entityImport(DispatchContext dctx, Map JavaDoc context) {
87         LocalDispatcher dispatcher = dctx.getDispatcher();
88         GenericDelegator delegator = dctx.getDelegator();
89         GenericValue userLogin = (GenericValue) context.get("userLogin");
90         Locale JavaDoc locale = (Locale JavaDoc) context.get("locale");
91
92         List JavaDoc messages = new ArrayList JavaDoc();
93
94         String JavaDoc filename = (String JavaDoc)context.get("filename");
95         String JavaDoc fmfilename = (String JavaDoc)context.get("fmfilename");
96         String JavaDoc fulltext = (String JavaDoc)context.get("fulltext");
97         boolean isUrl = (String JavaDoc)context.get("isUrl") != null;
98         String JavaDoc mostlyInserts = (String JavaDoc)context.get("mostlyInserts");
99         String JavaDoc maintainTimeStamps = (String JavaDoc)context.get("maintainTimeStamps");
100         String JavaDoc createDummyFks = (String JavaDoc)context.get("createDummyFks");
101
102         Integer JavaDoc txTimeout = (Integer JavaDoc)context.get("txTimeout");
103
104         if (txTimeout == null) {
105             txTimeout = new Integer JavaDoc(7200);
106         }
107         InputSource JavaDoc ins = null;
108         URL JavaDoc url = null;
109
110         // #############################
111
// The filename to parse is prepared
112
// #############################
113
if (filename != null && filename.length() > 0) {
114             try {
115                 url = isUrl?new URL JavaDoc(filename):UtilURL.fromFilename(filename);
116                 InputStream JavaDoc is = url.openStream();
117                 ins = new InputSource JavaDoc(is);
118             } catch(MalformedURLException JavaDoc mue) {
119                 return ServiceUtil.returnError("ERROR: invalid file name (" + filename + "): " + mue.getMessage());
120             } catch(IOException JavaDoc ioe) {
121                 return ServiceUtil.returnError("ERROR reading file name (" + filename + "): " + ioe.getMessage());
122             } catch(Exception JavaDoc exc) {
123                 return ServiceUtil.returnError("ERROR: reading file name (" + filename + "): " + exc.getMessage());
124             }
125         }
126
127         // #############################
128
// The text to parse is prepared
129
// #############################
130
if (fulltext != null && fulltext.length() > 0) {
131             StringReader JavaDoc sr = new StringReader JavaDoc(fulltext);
132             ins = new InputSource JavaDoc(sr);
133         }
134
135         // #############################
136
// FM Template
137
// #############################
138
String JavaDoc s = null;
139         if (UtilValidate.isNotEmpty(fmfilename) && ins != null) {
140             FileReader JavaDoc templateReader = null;
141             try {
142                 templateReader = new FileReader JavaDoc(fmfilename);
143             } catch(FileNotFoundException JavaDoc e) {
144                 return ServiceUtil.returnError("ERROR reading template file (" + fmfilename + "): " + e.getMessage());
145             }
146
147             StringWriter JavaDoc outWriter = new StringWriter JavaDoc();
148
149             Template template = null;
150             try {
151                 Configuration conf = org.ofbiz.base.util.template.FreeMarkerWorker.makeDefaultOfbizConfig();
152                 template = new Template("FMImportFilter", templateReader, conf);
153                 Map JavaDoc fmcontext = new HashMap JavaDoc();
154
155                 NodeModel nodeModel = NodeModel.parse(ins);
156                 fmcontext.put("doc", nodeModel);
157                 BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
158                 TemplateHashModel staticModels = wrapper.getStaticModels();
159                 fmcontext.put("Static", staticModels);
160
161                 template.process(fmcontext, outWriter);
162                 s = outWriter.toString();
163             } catch(Exception JavaDoc ex) {
164                 return ServiceUtil.returnError("ERROR processing template file (" + fmfilename + "): " + ex.getMessage());
165             }
166         }
167
168         // #############################
169
// The parsing takes place
170
// #############################
171
if (s != null || fulltext != null || url != null) {
172             try{
173                 Map JavaDoc inputMap = UtilMisc.toMap("mostlyInserts", mostlyInserts,
174                                               "createDummyFks", createDummyFks,
175                                               "maintainTimeStamps", maintainTimeStamps,
176                                               "txTimeout", txTimeout,
177                                               "userLogin", userLogin);
178                 if (s != null) {
179                     inputMap.put("xmltext", s);
180                 } else {
181                     if (fulltext != null) {
182                         inputMap.put("xmltext", fulltext);
183                     } else {
184                         inputMap.put("url", url);
185                     }
186                 }
187                 Map JavaDoc outputMap = dispatcher.runSync("parseEntityXmlFile", inputMap);
188                 if (ServiceUtil.isError(outputMap)) {
189                     return ServiceUtil.returnError("ERROR: " + ServiceUtil.getErrorMessage(outputMap));
190                 } else {
191                     Long JavaDoc numberRead = (Long JavaDoc)outputMap.get("rowProcessed");
192                     messages.add("Got " + numberRead.longValue() + " entities to write to the datasource.");
193                 }
194             } catch (Exception JavaDoc ex){
195                 return ServiceUtil.returnError("ERROR parsing Entity Xml file: " + ex.getMessage());
196             }
197         } else {
198             messages.add("No filename/URL or complete XML document specified, doing nothing.");
199         }
200
201         // send the notification
202
Map JavaDoc resp = UtilMisc.toMap("messages", messages);
203         return resp;
204     }
205
206     public static Map JavaDoc entityImportDir(DispatchContext dctx, Map JavaDoc context) {
207         LocalDispatcher dispatcher = dctx.getDispatcher();
208         GenericDelegator delegator = dctx.getDelegator();
209         GenericValue userLogin = (GenericValue) context.get("userLogin");
210         Locale JavaDoc locale = (Locale JavaDoc) context.get("locale");
211
212         List JavaDoc messages = new ArrayList JavaDoc();
213
214         String JavaDoc path = (String JavaDoc)context.get("path");
215         String JavaDoc mostlyInserts = (String JavaDoc)context.get("mostlyInserts");
216         String JavaDoc maintainTimeStamps = (String JavaDoc)context.get("maintainTimeStamps");
217         String JavaDoc createDummyFks = (String JavaDoc)context.get("createDummyFks");
218         boolean deleteFiles = (String JavaDoc)context.get("deleteFiles") != null;
219
220         Integer JavaDoc txTimeout = (Integer JavaDoc)context.get("txTimeout");
221         Long JavaDoc filePause = (Long JavaDoc)context.get("filePause");
222
223         if (txTimeout == null) {
224             txTimeout = new Integer JavaDoc(7200);
225         }
226         if (filePause == null) {
227             filePause = new Long JavaDoc(0);
228         }
229
230         if (path != null && path.length() > 0) {
231             long pauseLong = filePause != null ? filePause.longValue() : 0;
232             File JavaDoc baseDir = new File JavaDoc(path);
233
234             if (baseDir.isDirectory() && baseDir.canRead()) {
235                 File JavaDoc[] fileArray = baseDir.listFiles();
236                 ArrayList JavaDoc files = new ArrayList JavaDoc(fileArray.length);
237                 for (int a=0; a<fileArray.length; a++){
238                     if (fileArray[a].getName().toUpperCase().endsWith("XML")) {
239                         files.add(fileArray[a]);
240                     }
241                 }
242                 boolean importedOne = false;
243                 int fileListMarkedSize = files.size();
244                 int passes = 0;
245                 for (int a=0; a<files.size(); a++){
246                     // Infinite loop defense
247
if (a == fileListMarkedSize) {
248                         passes++;
249                         fileListMarkedSize = files.size();
250                         messages.add("Pass " + passes + " complete");
251                         // This means we've done a pass
252
if ( false == importedOne ) {
253                             // We've failed to make any imports
254
messages.add("Dropping out as we failed to make any imports on the last pass");
255                             a = files.size();
256                             continue;
257                         }
258                         importedOne = false;
259                     }
260                     File JavaDoc curFile = (File JavaDoc)files.get(a);
261                     try{
262                         URL JavaDoc url = curFile.toURL();
263                         Map JavaDoc inputMap = UtilMisc.toMap("url", url,
264                                                       "mostlyInserts", mostlyInserts,
265                                                       "createDummyFks", createDummyFks,
266                                                       "maintainTimeStamps", maintainTimeStamps,
267                                                       "txTimeout", txTimeout,
268                                                       "userLogin", userLogin);
269                         Map JavaDoc outputMap = dispatcher.runSync("parseEntityXmlFile", inputMap);
270                         Long JavaDoc numberRead = (Long JavaDoc)outputMap.get("rowProcessed");
271
272                         messages.add("Got " + numberRead.longValue() + " entities from " + curFile);
273
274                         importedOne = true;
275                         if (deleteFiles) {
276                             curFile.delete();
277                         }
278                     } catch (Exception JavaDoc ex){
279                         messages.add("Error trying to read from " + curFile + ": " + ex);
280                         if (ex.toString().indexOf("referential integrity violation") > -1 ||
281                                 ex.toString().indexOf("Integrity constraint violation") > -1){
282                             //It didn't work because object it depends on are still
283
//missing from the DB. Retry later.
284
//
285
//FIXME: Of course this is a potential infinite loop.
286
messages.add("Looks like referential integrity violation, will retry");
287                             files.add(curFile);
288                         }
289                     }
290                     // pause in between files
291
if (pauseLong > 0) {
292                         Debug.log("Pausing for [" + pauseLong + "] seconds - " + UtilDateTime.nowTimestamp());
293                         try {
294                             Thread.sleep((pauseLong * 1000));
295                         } catch(InterruptedException JavaDoc ie) {
296                             Debug.log("Pause finished - " + UtilDateTime.nowTimestamp());
297                         }
298                     }
299                 }
300             } else {
301                 messages.add("path not found or can't be read");
302             }
303         } else {
304             messages.add("No path specified, doing nothing.");
305         }
306         // send the notification
307
Map JavaDoc resp = UtilMisc.toMap("messages", messages);
308         return resp;
309     }
310
311     public static Map JavaDoc parseEntityXmlFile(DispatchContext dctx, Map JavaDoc context) {
312         GenericDelegator delegator = dctx.getDelegator();
313         GenericValue userLogin = (GenericValue) context.get("userLogin");
314
315         URL JavaDoc url = (URL JavaDoc)context.get("url");
316         String JavaDoc xmltext = (String JavaDoc)context.get("xmltext");
317
318         if (url == null && xmltext == null) {
319             return ServiceUtil.returnError("No entity xml file or text specified");
320         }
321         boolean mostlyInserts = (String JavaDoc)context.get("mostlyInserts") != null;
322         boolean maintainTimeStamps = (String JavaDoc)context.get("maintainTimeStamps") != null;
323         boolean createDummyFks = (String JavaDoc)context.get("createDummyFks") != null;
324         Integer JavaDoc txTimeout = (Integer JavaDoc)context.get("txTimeout");
325
326         if (txTimeout == null) {
327             txTimeout = new Integer JavaDoc(7200);
328         }
329
330         Long JavaDoc rowProcessed = new Long JavaDoc(0);
331         try {
332             EntitySaxReader reader = new EntitySaxReader(delegator);
333             reader.setUseTryInsertMethod(mostlyInserts);
334             reader.setMaintainTxStamps(maintainTimeStamps);
335             reader.setTransactionTimeout(txTimeout.intValue());
336             reader.setCreateDummyFks(createDummyFks);
337
338             long numberRead = (url != null? reader.parse(url): reader.parse(xmltext));
339             rowProcessed = new Long JavaDoc(numberRead);
340         } catch (Exception JavaDoc ex){
341             return ServiceUtil.returnError("Error parsing entity xml file: " + ex.toString());
342         }
343         // send the notification
344
Map JavaDoc resp = UtilMisc.toMap("rowProcessed", rowProcessed);
345         return resp;
346     }
347
348     public static Map JavaDoc entityExportAll(DispatchContext dctx, Map JavaDoc context) {
349         LocalDispatcher dispatcher = dctx.getDispatcher();
350         GenericDelegator delegator = dctx.getDelegator();
351         GenericValue userLogin = (GenericValue) context.get("userLogin");
352         Locale JavaDoc locale = (Locale JavaDoc) context.get("locale");
353
354         String JavaDoc outpath = (String JavaDoc)context.get("outpath"); // mandatory
355
Integer JavaDoc txTimeout = (Integer JavaDoc)context.get("txTimeout");
356         if (txTimeout == null) {
357             txTimeout = new Integer JavaDoc(7200);
358         }
359
360         List JavaDoc results = new ArrayList JavaDoc();
361
362         if (outpath != null && outpath.length() > 0) {
363             File JavaDoc outdir = new File JavaDoc(outpath);
364             if (!outdir.exists()) {
365                 outdir.mkdir();
366             }
367             if (outdir.isDirectory() && outdir.canWrite()) {
368                 
369                 Iterator JavaDoc passedEntityNames = null;
370                 try {
371                     ModelReader reader = delegator.getModelReader();
372                     Collection JavaDoc ec = reader.getEntityNames();
373                     TreeSet JavaDoc entityNames = new TreeSet JavaDoc(ec);
374                     passedEntityNames = entityNames.iterator();
375                 } catch(Exception JavaDoc exc) {
376                     return ServiceUtil.returnError("Error retrieving entity names.");
377                 }
378                 int fileNumber = 1;
379
380                 while (passedEntityNames.hasNext()) {
381                     long numberWritten = 0;
382                     String JavaDoc curEntityName = (String JavaDoc)passedEntityNames.next();
383                     EntityListIterator values = null;
384
385                     try {
386                         ModelEntity me = delegator.getModelEntity(curEntityName);
387                         if (me instanceof ModelViewEntity) {
388                             results.add("["+fileNumber +"] [vvv] " + curEntityName + " skipping view entity");
389                             continue;
390                         }
391
392                         // some databases don't support cursors, or other problems may happen, so if there is an error here log it and move on to get as much as possible
393
try {
394                             values = delegator.findListIteratorByCondition(curEntityName, null, null, null, me.getPkFieldNames(), null);
395                         } catch (Exception JavaDoc entityEx) {
396                             results.add("["+fileNumber +"] [xxx] Error when writing " + curEntityName + ": " + entityEx);
397                             continue;
398                         }
399
400                         //Don't bother writing the file if there's nothing
401
//to put into it
402
GenericValue value = (GenericValue) values.next();
403                         if (value != null) {
404                             PrintWriter JavaDoc writer = new PrintWriter JavaDoc(new BufferedWriter JavaDoc(new OutputStreamWriter JavaDoc(new FileOutputStream JavaDoc(new File JavaDoc(outdir, curEntityName +".xml")), "UTF-8")));
405                             writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
406                             writer.println("<entity-engine-xml>");
407
408                             do {
409                                 value.writeXmlText(writer, "");
410                                 numberWritten++;
411                             } while ((value = (GenericValue) values.next()) != null);
412                             writer.println("</entity-engine-xml>");
413                             writer.close();
414                             results.add("["+fileNumber +"] [" + numberWritten + "] " + curEntityName + " wrote " + numberWritten + " records");
415                         } else {
416                             results.add("["+fileNumber +"] [---] " + curEntityName + " has no records, not writing file");
417                         }
418                         values.close();
419                     } catch (Exception JavaDoc ex) {
420                         if (values != null) {
421                             try {
422                                 values.close();
423                             } catch(Exception JavaDoc exc) {
424                                 //Debug.warning();
425
}
426                         }
427                         results.add("["+fileNumber +"] [xxx] Error when writing " + curEntityName + ": " + ex);
428                     }
429                     fileNumber++;
430                 }
431             } else {
432                 results.add("Path not found or no write access.");
433             }
434         } else {
435             results.add("No path specified, doing nothing.");
436         }
437         // send the notification
438
Map JavaDoc resp = UtilMisc.toMap("results", results);
439         return resp;
440     }
441
442 }
443
Popular Tags