KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > common > CommonServices


1 /*
2  * $Id: CommonServices.java 6424 2005-12-23 18:11:54Z 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.common;
26
27 import java.io.FileNotFoundException JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.RandomAccessFile JavaDoc;
30 import java.sql.Timestamp JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.Locale JavaDoc;
34 import java.util.Map JavaDoc;
35 import java.util.Set JavaDoc;
36 import java.util.TreeSet JavaDoc;
37
38 import javax.transaction.xa.XAException JavaDoc;
39 import javax.mail.internet.MimeMessage JavaDoc;
40 import javax.mail.Address JavaDoc;
41
42 import org.ofbiz.base.util.Debug;
43 import org.ofbiz.base.util.UtilDateTime;
44 import org.ofbiz.base.util.UtilMisc;
45 import org.ofbiz.entity.GenericDelegator;
46 import org.ofbiz.entity.GenericEntityException;
47 import org.ofbiz.entity.GenericValue;
48 import org.ofbiz.entity.model.ModelEntity;
49 import org.ofbiz.entity.transaction.TransactionUtil;
50 import org.ofbiz.entity.util.ByteWrapper;
51 import org.ofbiz.service.DispatchContext;
52 import org.ofbiz.service.GenericServiceException;
53 import org.ofbiz.service.LocalDispatcher;
54 import org.ofbiz.service.ModelService;
55 import org.ofbiz.service.ServiceUtil;
56 import org.ofbiz.service.ServiceXaWrapper;
57 import org.ofbiz.service.mail.MimeMessageWrapper;
58
59 /**
60  * Common Services
61  *
62  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
63  * @version $Rev: 6424 $
64  * @since 2.0
65  */

66 public class CommonServices {
67
68     public final static String JavaDoc module = CommonServices.class.getName();
69
70     /**
71      * Generic Test Service
72      *@param dctx The DispatchContext that this service is operating in
73      *@param context Map containing the input parameters
74      *@return Map with the result of the service, the output parameters
75      */

76     public static Map JavaDoc testService(DispatchContext dctx, Map JavaDoc context) {
77         Map JavaDoc response = ServiceUtil.returnSuccess();
78
79         if (context.size() > 0) {
80             Iterator JavaDoc i = context.keySet().iterator();
81
82             while (i.hasNext()) {
83                 Object JavaDoc cKey = i.next();
84                 Object JavaDoc value = context.get(cKey);
85
86                 System.out.println("---- SVC-CONTEXT: " + cKey + " => " + value);
87             }
88         }
89         if (!context.containsKey("message")) {
90             response.put("resp", "no message found");
91         } else {
92             System.out.println("-----SERVICE TEST----- : " + (String JavaDoc) context.get("message"));
93             response.put("resp", "service done");
94         }
95
96         System.out.println("----- SVC: " + dctx.getName() + " -----");
97         return response;
98     }
99
100     public static Map JavaDoc blockingTestService(DispatchContext dctx, Map JavaDoc context) {
101         System.out.println("-----SERVICE BLOCKING----- : 30 seconds");
102         try {
103             Thread.sleep(30000);
104         } catch (InterruptedException JavaDoc e) {
105         }
106         return CommonServices.testService(dctx, context);
107     }
108
109     public static Map JavaDoc testWorkflowCondition(DispatchContext dctx, Map JavaDoc context) {
110         Map JavaDoc result = new HashMap JavaDoc();
111         result.put("evaluationResult", new Boolean JavaDoc(true));
112         return result;
113     }
114
115     public static Map JavaDoc testRollbackListener(DispatchContext dctx, Map JavaDoc context) {
116         ServiceXaWrapper xar = new ServiceXaWrapper(dctx);
117         xar.setRollbackService("testScv", context);
118         try {
119             xar.enlist();
120         } catch (XAException JavaDoc e) {
121             Debug.logError(e, module);
122         }
123         return ServiceUtil.returnError("Rolling back!");
124     }
125
126     public static Map JavaDoc testCommitListener(DispatchContext dctx, Map JavaDoc context) {
127         ServiceXaWrapper xar = new ServiceXaWrapper(dctx);
128         xar.setCommitService("testScv", context);
129         try {
130             xar.enlist();
131         } catch (XAException JavaDoc e) {
132             Debug.logError(e, module);
133         }
134         return ServiceUtil.returnSuccess();
135     }
136
137     /**
138      * Create Note Record
139      *@param ctx The DispatchContext that this service is operating in
140      *@param context Map containing the input parameters
141      *@return Map with the result of the service, the output parameters
142      */

143     public static Map JavaDoc createNote(DispatchContext ctx, Map JavaDoc context) {
144         GenericDelegator delegator = ctx.getDelegator();
145         GenericValue userLogin = (GenericValue) context.get("userLogin");
146         Timestamp JavaDoc noteDate = (Timestamp JavaDoc) context.get("noteDate");
147         String JavaDoc partyId = (String JavaDoc) context.get("partyId");
148         String JavaDoc noteName = (String JavaDoc) context.get("noteName");
149         String JavaDoc note = (String JavaDoc) context.get("note");
150         String JavaDoc noteId = delegator.getNextSeqId("NoteData");
151         if (noteDate == null) {
152             noteDate = UtilDateTime.nowTimestamp();
153         }
154
155
156         // check for a party id
157
if (partyId == null) {
158             if (userLogin != null && userLogin.get("partyId") != null)
159                 partyId = userLogin.getString("partyId");
160         }
161
162         Map JavaDoc fields = UtilMisc.toMap("noteId", noteId, "noteName", noteName, "noteInfo", note,
163                 "noteParty", partyId, "noteDateTime", noteDate);
164
165         try {
166             GenericValue newValue = delegator.makeValue("NoteData", fields);
167
168             delegator.create(newValue);
169         } catch (GenericEntityException e) {
170             return ServiceUtil.returnError("Could update note data (write failure): " + e.getMessage());
171         }
172         Map JavaDoc result = ServiceUtil.returnSuccess();
173
174         result.put("noteId", noteId);
175         return result;
176     }
177
178     /**
179      * Service for setting debugging levels.
180      *@param dctx The DispatchContext that this service is operating in
181      *@param context Map containing the input parameters
182      *@return Map with the result of the service, the output parameters
183      */

184     public static Map JavaDoc setDebugLevels(DispatchContext dctx, Map JavaDoc context) {
185         Boolean JavaDoc verbose = (Boolean JavaDoc) context.get("verbose");
186         Boolean JavaDoc timing = (Boolean JavaDoc) context.get("timing");
187         Boolean JavaDoc info = (Boolean JavaDoc) context.get("info");
188         Boolean JavaDoc important = (Boolean JavaDoc) context.get("important");
189         Boolean JavaDoc warning = (Boolean JavaDoc) context.get("warning");
190         Boolean JavaDoc error = (Boolean JavaDoc) context.get("error");
191         Boolean JavaDoc fatal = (Boolean JavaDoc) context.get("fatal");
192
193         if (verbose != null)
194             Debug.set(Debug.VERBOSE, verbose.booleanValue());
195         else
196             Debug.set(Debug.VERBOSE, false);
197         if (timing != null)
198             Debug.set(Debug.TIMING, timing.booleanValue());
199         else
200             Debug.set(Debug.TIMING, false);
201         if (info != null)
202             Debug.set(Debug.INFO, info.booleanValue());
203         else
204             Debug.set(Debug.INFO, false);
205         if (important != null)
206             Debug.set(Debug.IMPORTANT, important.booleanValue());
207         else
208             Debug.set(Debug.IMPORTANT, false);
209         if (warning != null)
210             Debug.set(Debug.WARNING, warning.booleanValue());
211         else
212             Debug.set(Debug.WARNING, false);
213         if (error != null)
214             Debug.set(Debug.ERROR, error.booleanValue());
215         else
216             Debug.set(Debug.ERROR, false);
217         if (fatal != null)
218             Debug.set(Debug.FATAL, fatal.booleanValue());
219         else
220             Debug.set(Debug.FATAL, false);
221
222         return ServiceUtil.returnSuccess();
223     }
224
225     public static Map JavaDoc forceGc(DispatchContext dctx, Map JavaDoc context) {
226         System.gc();
227         return ServiceUtil.returnSuccess();
228     }
229
230     /**
231      * Echo service; returns exactly what was sent.
232      * This service does not have required parameters and does not validate
233      */

234      public static Map JavaDoc echoService(DispatchContext dctx, Map JavaDoc context) {
235          context.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
236          return context;
237      }
238
239     /**
240      * Return Error Service; Used for testing error handling
241      */

242     public static Map JavaDoc returnErrorService(DispatchContext dctx, Map JavaDoc context) {
243         return ServiceUtil.returnError("Return Error Service : Returning Error");
244     }
245
246     /**
247      * Return TRUE Service; ECA Condition Service
248      */

249     public static Map JavaDoc conditionTrueService(DispatchContext dctx, Map JavaDoc context) {
250         Map JavaDoc result = ServiceUtil.returnSuccess();
251         result.put("conditionReply", Boolean.TRUE);
252         return result;
253     }
254
255     /**
256      * Return FALSE Service; ECA Condition Service
257      */

258     public static Map JavaDoc conditionFalseService(DispatchContext dctx, Map JavaDoc context) {
259         Map JavaDoc result = ServiceUtil.returnSuccess();
260         result.put("conditionReply", Boolean.FALSE);
261         return result;
262     }
263
264     /** Cause a Referential Integrity Error */
265     public static Map JavaDoc entityFailTest(DispatchContext dctx, Map JavaDoc context) {
266         GenericDelegator delegator = dctx.getDelegator();
267
268         // attempt to create a DataSource entity w/ an invalid dataSourceTypeId
269
GenericValue newEntity = delegator.makeValue("DataSource", null);
270         newEntity.set("dataSourceId", "ENTITY_FAIL_TEST");
271         newEntity.set("dataSourceTypeId", "ENTITY_FAIL_TEST");
272         newEntity.set("description", "Entity Fail Test - Delete me if I am here");
273         try {
274             delegator.create(newEntity);
275         } catch (GenericEntityException e) {
276             Debug.logError(e, module);
277             return ServiceUtil.returnError("Unable to create test entity");
278         }
279
280         /*
281         try {
282             newEntity.remove();
283         } catch(GenericEntityException e) {
284             Debug.logError(e, module);
285         }
286         */

287
288         return ServiceUtil.returnSuccess();
289     }
290
291     /** Test entity sorting */
292     public static Map JavaDoc entitySortTest(DispatchContext dctx, Map JavaDoc context) {
293         GenericDelegator delegator = dctx.getDelegator();
294         Set JavaDoc set = new TreeSet JavaDoc();
295
296         set.add(delegator.getModelEntity("Person"));
297         set.add(delegator.getModelEntity("PartyRole"));
298         set.add(delegator.getModelEntity("Party"));
299         set.add(delegator.getModelEntity("ContactMech"));
300         set.add(delegator.getModelEntity("PartyContactMech"));
301         set.add(delegator.getModelEntity("OrderHeader"));
302         set.add(delegator.getModelEntity("OrderItem"));
303         set.add(delegator.getModelEntity("OrderContactMech"));
304         set.add(delegator.getModelEntity("OrderRole"));
305         set.add(delegator.getModelEntity("Product"));
306         set.add(delegator.getModelEntity("RoleType"));
307
308         Iterator JavaDoc i = set.iterator();
309         while (i.hasNext()) {
310             Debug.log(((ModelEntity)i.next()).getEntityName(), module);
311         }
312         return ServiceUtil.returnSuccess();
313     }
314
315     public static Map JavaDoc makeALotOfVisits(DispatchContext dctx, Map JavaDoc context) {
316         GenericDelegator delegator = dctx.getDelegator();
317         int count = ((Integer JavaDoc) context.get("count")).intValue();
318
319         for (int i = 0; i < count; i++ ) {
320             GenericValue v = delegator.makeValue("Visit", null);
321             String JavaDoc seqId = delegator.getNextSeqId("Visit").toString();
322
323             v.set("visitId", seqId);
324             v.set("userCreated", "N");
325             v.set("sessionId", "NA-" + seqId);
326             v.set("serverIpAddress", "127.0.0.1");
327             v.set("serverHostName", "localhost");
328             v.set("webappName", "webtools");
329             v.set("initialLocale", "en_US");
330             v.set("initialRequest", "http://localhost:8080/webtools/control/main");
331             v.set("initialReferrer", "http://localhost:8080/webtools/control/main");
332             v.set("initialUserAgent", "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1");
333             v.set("clientIpAddress", "127.0.0.1");
334             v.set("clientHostName", "localhost");
335             v.set("fromDate", UtilDateTime.nowTimestamp());
336
337             try {
338                 delegator.create(v);
339             } catch (GenericEntityException e) {
340                 Debug.logError(e, module);
341             }
342         }
343
344         return ServiceUtil.returnSuccess();
345     }
346
347     public static Map JavaDoc displayXaDebugInfo(DispatchContext dctx, Map JavaDoc context) {
348         if (TransactionUtil.debugResources) {
349             if (TransactionUtil.debugResMap != null && TransactionUtil.debugResMap.size() > 0) {
350                 TransactionUtil.logRunningTx();
351             } else {
352                 Debug.log("No running transaction to display.", module);
353             }
354         } else {
355             Debug.log("Debug resources is disabled.", module);
356         }
357
358         return ServiceUtil.returnSuccess();
359     }
360
361     public static Map JavaDoc byteWrapperTest(DispatchContext dctx, Map JavaDoc context) {
362         ByteWrapper wrapper1 = (ByteWrapper) context.get("byteWrapper1");
363         ByteWrapper wrapper2 = (ByteWrapper) context.get("byteWrapper2");
364         String JavaDoc fileName1 = (String JavaDoc) context.get("saveAsFileName1");
365         String JavaDoc fileName2 = (String JavaDoc) context.get("saveAsFileName2");
366         String JavaDoc ofbizHome = System.getProperty("ofbiz.home");
367         String JavaDoc outputPath1 = ofbizHome + (fileName1.startsWith("/") ? fileName1 : "/" + fileName1);
368         String JavaDoc outputPath2 = ofbizHome + (fileName2.startsWith("/") ? fileName2 : "/" + fileName2);
369
370         try {
371             RandomAccessFile JavaDoc file1 = new RandomAccessFile JavaDoc(outputPath1, "rw");
372             RandomAccessFile JavaDoc file2 = new RandomAccessFile JavaDoc(outputPath2, "rw");
373             file1.write(wrapper1.getBytes());
374             file2.write(wrapper2.getBytes());
375         } catch (FileNotFoundException JavaDoc e) {
376             Debug.logError(e, module);
377         } catch (IOException JavaDoc e) {
378             Debug.logError(e, module);
379         }
380
381         return ServiceUtil.returnSuccess();
382     }
383
384     public static Map JavaDoc uploadTest(DispatchContext dctx, Map JavaDoc context) {
385         LocalDispatcher dispatcher = dctx.getDispatcher();
386         GenericValue userLogin = (GenericValue) context.get("userLogin");
387
388         ByteWrapper wrapper = (ByteWrapper) context.get("uploadFile");
389         String JavaDoc fileName = (String JavaDoc) context.get("_uploadFile_fileName");
390         String JavaDoc contentType = (String JavaDoc) context.get("_uploadFile_contentType");
391
392         Map JavaDoc createCtx = new HashMap JavaDoc();
393         createCtx.put("binData", wrapper);
394         createCtx.put("dataResourceTypeId", "OFBIZ_FILE");
395         createCtx.put("dataResourceName", fileName);
396         createCtx.put("dataCategoryId", "PERSONAL");
397         createCtx.put("statusId", "CTNT_PUBLISHED");
398         createCtx.put("mimeTypeId", contentType);
399         createCtx.put("userLogin", userLogin);
400
401         Map JavaDoc createResp = null;
402         try {
403             createResp = dispatcher.runSync("createFile", createCtx);
404         } catch (GenericServiceException e) {
405             Debug.logError(e, module);
406             return ServiceUtil.returnError(e.getMessage());
407         }
408         if (ServiceUtil.isError(createResp)) {
409             return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createResp));
410         }
411
412         GenericValue dataResource = (GenericValue) createResp.get("dataResource");
413         if (dataResource != null) {
414             Map JavaDoc contentCtx = new HashMap JavaDoc();
415             contentCtx.put("dataResourceId", dataResource.getString("dataResourceId"));
416             contentCtx.put("localeString", ((Locale JavaDoc) context.get("locale")).toString());
417             contentCtx.put("contentTypeId", "DOCUMENT");
418             contentCtx.put("mimeTypeId", contentType);
419             contentCtx.put("contentName", fileName);
420             contentCtx.put("statusId", "CTNT_PUBLISHED");
421             contentCtx.put("userLogin", userLogin);
422
423             Map JavaDoc contentResp = null;
424             try {
425                 contentResp = dispatcher.runSync("createContent", contentCtx);
426             } catch (GenericServiceException e) {
427                 Debug.logError(e, module);
428                 return ServiceUtil.returnError(e.getMessage());
429             }
430             if (ServiceUtil.isError(contentResp)) {
431                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(contentResp));
432             }
433         }
434
435         return ServiceUtil.returnSuccess();
436     }
437
438     public static Map JavaDoc mcaTest(DispatchContext dctx, Map JavaDoc context) {
439         MimeMessageWrapper wrapper = (MimeMessageWrapper) context.get("messageWrapper");
440         MimeMessage JavaDoc message = wrapper.getMessage();
441         try {
442             if (message.getAllRecipients() != null) {
443                Debug.log("To: " + UtilMisc.toListArray(message.getAllRecipients()), module);
444             }
445             if (message.getFrom() != null) {
446                Debug.log("From: " + UtilMisc.toListArray(message.getFrom()), module);
447             }
448             Debug.log("Subject: " + message.getSubject(), module);
449             if (message.getSentDate() != null) {
450                 Debug.log("Sent: " + message.getSentDate().toString(), module);
451             }
452             if (message.getReceivedDate() != null) {
453                 Debug.log("Received: " + message.getReceivedDate().toString(), module);
454             }
455         } catch (Exception JavaDoc e) {
456             Debug.logError(e, module);
457         }
458         return ServiceUtil.returnSuccess();
459     }
460
461     public static Map JavaDoc ping(DispatchContext dctx, Map JavaDoc context) {
462         GenericDelegator delegator = dctx.getDelegator();
463         String JavaDoc message = (String JavaDoc) context.get("message");
464         if (message == null) {
465             message = "PONG";
466         }
467
468         long count = -1;
469         try {
470             count = delegator.findCountByAnd("SequenceValueItem", null);
471         } catch (GenericEntityException e) {
472             Debug.logError(e.getMessage(), module);
473             return ServiceUtil.returnError("Unable to connect to datasource!");
474         }
475
476         if (count > 0) {
477             Map JavaDoc result = ServiceUtil.returnSuccess();
478             result.put("message", message);
479             return result;
480         } else {
481             return ServiceUtil.returnError("Invalid count returned from database");
482         }
483     }
484 }
485
486
Popular Tags