KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > entity > util > EntityDataLoader


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

25 package org.ofbiz.entity.util;
26
27 import java.io.File JavaDoc;
28 import java.net.URL JavaDoc;
29 import java.util.Collection JavaDoc;
30 import java.util.Collections JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.LinkedList JavaDoc;
33 import java.util.List JavaDoc;
34 import java.util.StringTokenizer JavaDoc;
35
36 import org.w3c.dom.Element JavaDoc;
37
38 import org.ofbiz.base.component.ComponentConfig;
39 import org.ofbiz.base.config.GenericConfigException;
40 import org.ofbiz.base.config.MainResourceHandler;
41 import org.ofbiz.base.config.ResourceHandler;
42 import org.ofbiz.base.util.Debug;
43 import org.ofbiz.base.util.UtilMisc;
44 import org.ofbiz.entity.GenericDelegator;
45 import org.ofbiz.entity.GenericEntityException;
46 import org.ofbiz.entity.config.DatasourceInfo;
47 import org.ofbiz.entity.config.EntityConfigUtil;
48 import org.ofbiz.entity.config.EntityDataReaderInfo;
49 import org.ofbiz.entity.model.ModelEntity;
50 import org.ofbiz.entity.model.ModelReader;
51 import org.ofbiz.entity.model.ModelUtil;
52 import org.ofbiz.entity.model.ModelViewEntity;
53
54 /**
55  * Some utility routines for loading seed data.
56  *
57  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
58  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
59  * @version $Rev: 6614 $
60  * @since 3.0
61  */

62 public class EntityDataLoader {
63
64     public static final String JavaDoc module = EntityDataLoader.class.getName();
65
66     public static String JavaDoc getPathsString(String JavaDoc helperName) {
67         StringBuffer JavaDoc pathBuffer = new StringBuffer JavaDoc();
68         if (helperName != null && helperName.length() > 0) {
69             DatasourceInfo datasourceInfo = EntityConfigUtil.getDatasourceInfo(helperName);
70             List JavaDoc sqlLoadPathElements = datasourceInfo.sqlLoadPaths;
71             Iterator JavaDoc slpIter = sqlLoadPathElements.iterator();
72             while (slpIter.hasNext()) {
73                 Element JavaDoc sqlLoadPathElement = (Element JavaDoc) slpIter.next();
74                 String JavaDoc prependEnv = sqlLoadPathElement.getAttribute("prepend-env");
75                 pathBuffer.append(pathBuffer.length() == 0 ? "" : ";");
76                 if (prependEnv != null && prependEnv.length() > 0) {
77                     pathBuffer.append(System.getProperty(prependEnv));
78                     pathBuffer.append("/");
79                 }
80                 pathBuffer.append(sqlLoadPathElement.getAttribute("path"));
81             }
82         }
83         return pathBuffer.toString();
84     }
85
86     public static List JavaDoc getUrlList(String JavaDoc helperName) {
87         DatasourceInfo datasourceInfo = EntityConfigUtil.getDatasourceInfo(helperName);
88         return getUrlList(helperName, datasourceInfo.readDatas);
89     }
90
91     public static List JavaDoc getUrlList(String JavaDoc helperName, List JavaDoc readerNames) {
92         String JavaDoc paths = getPathsString(helperName);
93         List JavaDoc urlList = new LinkedList JavaDoc();
94         
95         // first get files from resources
96
if (readerNames != null) {
97             Iterator JavaDoc readDataIter = readerNames.iterator();
98             while (readDataIter.hasNext()) {
99                 Object JavaDoc readerInfo = readDataIter.next();
100                 String JavaDoc readerName = null;
101                 if (readerInfo instanceof String JavaDoc) {
102                     readerName = (String JavaDoc) readerInfo;
103                 } else if (readerInfo instanceof Element JavaDoc) {
104                     readerName = ((Element JavaDoc) readerInfo).getAttribute("reader-name");
105                 } else {
106                     throw new IllegalArgumentException JavaDoc("Reader name list does not contain String(s) or Element(s)");
107                 }
108
109                 // get all of the main resource model stuff, ie specified in the entityengine.xml file
110
EntityDataReaderInfo entityDataReaderInfo = EntityConfigUtil.getEntityDataReaderInfo(readerName);
111                 
112                 if (entityDataReaderInfo != null) {
113                     List JavaDoc resourceElements = entityDataReaderInfo.resourceElements;
114                     Iterator JavaDoc resIter = resourceElements.iterator();
115                     while (resIter.hasNext()) {
116                         Element JavaDoc resourceElement = (Element JavaDoc) resIter.next();
117                         ResourceHandler handler = new MainResourceHandler(EntityConfigUtil.ENTITY_ENGINE_XML_FILENAME, resourceElement);
118                         try {
119                             urlList.add(handler.getURL());
120                         } catch (GenericConfigException e) {
121                             String JavaDoc errorMsg = "Could not get URL for Main ResourceHandler: " + e.toString();
122                             Debug.logWarning(errorMsg, module);
123                         }
124                     }
125         
126                     // get all of the component resource model stuff, ie specified in each ofbiz-component.xml file
127
List JavaDoc componentResourceInfos = ComponentConfig.getAllEntityResourceInfos("data");
128                     Iterator JavaDoc componentResourceInfoIter = componentResourceInfos.iterator();
129                     while (componentResourceInfoIter.hasNext()) {
130                         ComponentConfig.EntityResourceInfo componentResourceInfo = (ComponentConfig.EntityResourceInfo) componentResourceInfoIter.next();
131                         if (readerName.equals(componentResourceInfo.readerName)) {
132                             ResourceHandler handler = componentResourceInfo.createResourceHandler();
133                             try {
134                                 urlList.add(handler.getURL());
135                             } catch (GenericConfigException e) {
136                                 String JavaDoc errorMsg = "Could not get URL for Component ResourceHandler: " + e.toString();
137                                 Debug.logWarning(errorMsg, module);
138                             }
139                         }
140                     }
141                 } else {
142                     String JavaDoc errorMsg = "Could not find entity-date-reader named: " + readerName;
143                     Debug.logWarning(errorMsg, module);
144                 }
145             }
146         } else {
147             String JavaDoc errorMsg = "Could not find datasource named: " + helperName;
148             Debug.logWarning(errorMsg, module);
149         }
150         
151         // get files from the paths string
152
if (paths != null && paths.length() > 0) {
153             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(paths, ";");
154             while (tokenizer.hasMoreTokens()) {
155                 String JavaDoc path = tokenizer.nextToken().toLowerCase();
156                 File JavaDoc loadDir = new File JavaDoc(path);
157                 if (loadDir.exists() && loadDir.isDirectory()) {
158                     File JavaDoc[] files = loadDir.listFiles();
159                     List JavaDoc tempFileList = new LinkedList JavaDoc();
160                     for (int i = 0; i < files.length; i++) {
161                         if (files[i].getName().toLowerCase().endsWith(".xml")) {
162                             tempFileList.add(files[i]);
163                         }
164                     }
165                     Collections.sort(tempFileList);
166                     Iterator JavaDoc tempFileIter = tempFileList.iterator();
167                     while (tempFileIter.hasNext()) {
168                         File JavaDoc dataFile = (File JavaDoc) tempFileIter.next();
169                         if (dataFile.exists()) {
170                             URL JavaDoc url = null;
171                             try {
172                                 url = dataFile.toURL();
173                                 urlList.add(url);
174                             } catch (java.net.MalformedURLException JavaDoc e) {
175                                 String JavaDoc xmlError = "Error loading XML file \"" + dataFile.getAbsolutePath() + "\"; Error was: " + e.getMessage();
176                                 Debug.logError(xmlError, module);
177                             }
178                         } else {
179                             String JavaDoc errorMsg = "Could not find file: \"" + dataFile.getAbsolutePath() + "\"";
180                             Debug.logError(errorMsg, module);
181                         }
182                     }
183                 }
184             }
185         }
186
187         return urlList;
188     }
189
190     public static int loadData(URL JavaDoc dataUrl, String JavaDoc helperName, GenericDelegator delegator, List JavaDoc errorMessages) throws GenericEntityException {
191         return loadData(dataUrl, helperName, delegator, errorMessages, -1);
192     }
193
194     public static int loadData(URL JavaDoc dataUrl, String JavaDoc helperName, GenericDelegator delegator, List JavaDoc errorMessages, int txTimeout) throws GenericEntityException {
195         return loadData(dataUrl, helperName, delegator, errorMessages, txTimeout, false, false, false);
196     }
197
198     public static int loadData(URL JavaDoc dataUrl, String JavaDoc helperName, GenericDelegator delegator, List JavaDoc errorMessages, int txTimeout, boolean dummyFks, boolean maintainTxs, boolean tryInsert) throws GenericEntityException {
199         int rowsChanged = 0;
200         
201         if (dataUrl == null) {
202             String JavaDoc errMsg = "Cannot load data, dataUrl was null";
203             errorMessages.add(errMsg);
204             Debug.logError(errMsg, module);
205             return 0;
206         }
207
208         Debug.logVerbose("[install.loadData] Loading XML Resource: \"" + dataUrl.toExternalForm() + "\"", module);
209
210         try {
211             /* The OLD way
212               List toBeStored = delegator.readXmlDocument(url);
213               delegator.storeAll(toBeStored);
214               rowsChanged += toBeStored.size();
215              */

216
217             EntitySaxReader reader = null;
218             if (txTimeout > 0) {
219                 reader = new EntitySaxReader(delegator, txTimeout);
220             } else {
221                 reader = new EntitySaxReader(delegator);
222             }
223             reader.setCreateDummyFks(dummyFks);
224             reader.setMaintainTxStamps(maintainTxs);
225             rowsChanged += reader.parse(dataUrl);
226         } catch (Exception JavaDoc e) {
227             String JavaDoc xmlError = "[install.loadData]: Error loading XML Resource \"" + dataUrl.toExternalForm() + "\"; Error was: " + e.getMessage();
228             errorMessages.add(xmlError);
229             Debug.logError(e, xmlError, module);
230         }
231
232         return rowsChanged;
233     }
234
235     public static int generateData(GenericDelegator delegator, List JavaDoc errorMessages) throws GenericEntityException {
236         int rowsChanged = 0;
237         ModelReader reader = delegator.getModelReader();
238         Collection JavaDoc entityCol = reader.getEntityNames();
239         Iterator JavaDoc classNamesIterator = entityCol.iterator();
240         while (classNamesIterator != null && classNamesIterator.hasNext()) {
241             ModelEntity entity = reader.getModelEntity((String JavaDoc) classNamesIterator.next());
242             String JavaDoc baseName = entity.getPlainTableName();
243             if (entity instanceof ModelViewEntity) {
244                 baseName = ModelUtil.javaNameToDbName(entity.getEntityName());
245             }
246
247             if (baseName != null) {
248                 try {
249                     List JavaDoc toBeStored = new LinkedList JavaDoc();
250                     toBeStored.add(
251                         delegator.makeValue(
252                             "SecurityPermission",
253                             UtilMisc.toMap(
254                                 "permissionId",
255                                 baseName + "_ADMIN",
256                                 "description",
257                                 "Permission to Administer a " + entity.getEntityName() + " entity.")));
258                     toBeStored.add(delegator.makeValue("SecurityGroupPermission", UtilMisc.toMap("groupId", "FULLADMIN", "permissionId", baseName + "_ADMIN")));
259                     rowsChanged += delegator.storeAll(toBeStored);
260                 } catch (GenericEntityException e) {
261                     errorMessages.add("[install.generateData] ERROR: Failed Security Generation for entity \"" + baseName + "\"");
262                 }
263
264                 /*
265                 toStore.add(delegator.makeValue("SecurityPermission", UtilMisc.toMap("permissionId", baseName + "_VIEW", "description", "Permission to View a " + entity.getEntityName() + " entity.")));
266                 toStore.add(delegator.makeValue("SecurityPermission", UtilMisc.toMap("permissionId", baseName + "_CREATE", "description", "Permission to Create a " + entity.getEntityName() + " entity.")));
267                 toStore.add(delegator.makeValue("SecurityPermission", UtilMisc.toMap("permissionId", baseName + "_UPDATE", "description", "Permission to Update a " + entity.getEntityName() + " entity.")));
268                 toStore.add(delegator.makeValue("SecurityPermission", UtilMisc.toMap("permissionId", baseName + "_DELETE", "description", "Permission to Delete a " + entity.getEntityName() + " entity.")));
269                 
270                 toStore.add(delegator.makeValue("SecurityGroupPermission", UtilMisc.toMap("groupId", "FLEXADMIN", "permissionId", baseName + "_VIEW")));
271                 toStore.add(delegator.makeValue("SecurityGroupPermission", UtilMisc.toMap("groupId", "FLEXADMIN", "permissionId", baseName + "_CREATE")));
272                 toStore.add(delegator.makeValue("SecurityGroupPermission", UtilMisc.toMap("groupId", "FLEXADMIN", "permissionId", baseName + "_UPDATE")));
273                 toStore.add(delegator.makeValue("SecurityGroupPermission", UtilMisc.toMap("groupId", "FLEXADMIN", "permissionId", baseName + "_DELETE")));
274                 */

275             }
276         }
277
278         return rowsChanged;
279     }
280 }
281
Popular Tags