001: /*******************************************************************************
002: * Licensed to the Apache Software Foundation (ASF) under one
003: * or more contributor license agreements. See the NOTICE file
004: * distributed with this work for additional information
005: * regarding copyright ownership. The ASF licenses this file
006: * to you under the Apache License, Version 2.0 (the
007: * "License"); you may not use this file except in compliance
008: * with the License. You may obtain a copy of the License at
009: *
010: * http://www.apache.org/licenses/LICENSE-2.0
011: *
012: * Unless required by applicable law or agreed to in writing,
013: * software distributed under the License is distributed on an
014: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015: * KIND, either express or implied. See the License for the
016: * specific language governing permissions and limitations
017: * under the License.
018: *******************************************************************************/package org.ofbiz.common;
019:
020: import java.io.*;
021: import java.sql.Timestamp;
022: import java.util.*;
023:
024: import javax.mail.internet.MimeMessage;
025: import javax.transaction.xa.XAException;
026:
027: import org.apache.log4j.Level;
028: import org.apache.log4j.Logger;
029: import org.ofbiz.base.util.Debug;
030: import org.ofbiz.base.util.UtilDateTime;
031: import org.ofbiz.base.util.UtilMisc;
032: import org.ofbiz.entity.GenericDelegator;
033: import org.ofbiz.entity.GenericEntityException;
034: import org.ofbiz.entity.GenericValue;
035: import org.ofbiz.entity.model.ModelEntity;
036: import org.ofbiz.entity.transaction.TransactionUtil;
037: import org.ofbiz.entity.util.ByteWrapper;
038: import org.ofbiz.service.DispatchContext;
039: import org.ofbiz.service.GenericServiceException;
040: import org.ofbiz.service.LocalDispatcher;
041: import org.ofbiz.service.ModelService;
042: import org.ofbiz.service.ServiceUtil;
043: import org.ofbiz.service.ServiceXaWrapper;
044: import org.ofbiz.service.mail.MimeMessageWrapper;
045:
046: /**
047: * Common Services
048: */
049: public class CommonServices {
050:
051: public final static String module = CommonServices.class.getName();
052:
053: /**
054: * Generic Test Service
055: *@param dctx The DispatchContext that this service is operating in
056: *@param context Map containing the input parameters
057: *@return Map with the result of the service, the output parameters
058: */
059: public static Map testService(DispatchContext dctx, Map context) {
060: Map response = ServiceUtil.returnSuccess();
061:
062: if (context.size() > 0) {
063: Iterator i = context.keySet().iterator();
064:
065: while (i.hasNext()) {
066: Object cKey = i.next();
067: Object value = context.get(cKey);
068:
069: System.out.println("---- SVC-CONTEXT: " + cKey + " => "
070: + value);
071: }
072: }
073: if (!context.containsKey("message")) {
074: response.put("resp", "no message found");
075: } else {
076: System.out.println("-----SERVICE TEST----- : "
077: + (String) context.get("message"));
078: response.put("resp", "service done");
079: }
080:
081: System.out.println("----- SVC: " + dctx.getName() + " -----");
082: return response;
083: }
084:
085: public static Map blockingTestService(DispatchContext dctx,
086: Map context) {
087: System.out.println("-----SERVICE BLOCKING----- : 30 seconds");
088: try {
089: Thread.sleep(30000);
090: } catch (InterruptedException e) {
091: }
092: return CommonServices.testService(dctx, context);
093: }
094:
095: public static Map testWorkflowCondition(DispatchContext dctx,
096: Map context) {
097: Map result = new HashMap();
098: result.put("evaluationResult", Boolean.TRUE);
099: return result;
100: }
101:
102: public static Map testRollbackListener(DispatchContext dctx,
103: Map context) {
104: ServiceXaWrapper xar = new ServiceXaWrapper(dctx);
105: xar.setRollbackService("testScv", context);
106: try {
107: xar.enlist();
108: } catch (XAException e) {
109: Debug.logError(e, module);
110: }
111: return ServiceUtil.returnError("Rolling back!");
112: }
113:
114: public static Map testCommitListener(DispatchContext dctx,
115: Map context) {
116: ServiceXaWrapper xar = new ServiceXaWrapper(dctx);
117: xar.setCommitService("testScv", context);
118: try {
119: xar.enlist();
120: } catch (XAException e) {
121: Debug.logError(e, module);
122: }
123: return ServiceUtil.returnSuccess();
124: }
125:
126: /**
127: * Create Note Record
128: *@param ctx The DispatchContext that this service is operating in
129: *@param context Map containing the input parameters
130: *@return Map with the result of the service, the output parameters
131: */
132: public static Map createNote(DispatchContext ctx, Map context) {
133: GenericDelegator delegator = ctx.getDelegator();
134: GenericValue userLogin = (GenericValue) context
135: .get("userLogin");
136: Timestamp noteDate = (Timestamp) context.get("noteDate");
137: String partyId = (String) context.get("partyId");
138: String noteName = (String) context.get("noteName");
139: String note = (String) context.get("note");
140: String noteId = delegator.getNextSeqId("NoteData");
141: if (noteDate == null) {
142: noteDate = UtilDateTime.nowTimestamp();
143: }
144:
145: // check for a party id
146: if (partyId == null) {
147: if (userLogin != null && userLogin.get("partyId") != null)
148: partyId = userLogin.getString("partyId");
149: }
150:
151: Map fields = UtilMisc.toMap("noteId", noteId, "noteName",
152: noteName, "noteInfo", note, "noteParty", partyId,
153: "noteDateTime", noteDate);
154:
155: try {
156: GenericValue newValue = delegator.makeValue("NoteData",
157: fields);
158:
159: delegator.create(newValue);
160: } catch (GenericEntityException e) {
161: return ServiceUtil
162: .returnError("Could update note data (write failure): "
163: + e.getMessage());
164: }
165: Map result = ServiceUtil.returnSuccess();
166:
167: result.put("noteId", noteId);
168: return result;
169: }
170:
171: /**
172: * Service for setting debugging levels.
173: *@param dctx The DispatchContext that this service is operating in
174: *@param context Map containing the input parameters
175: *@return Map with the result of the service, the output parameters
176: */
177: public static Map adjustDebugLevels(DispatchContext dctc,
178: Map context) {
179: Debug.set(Debug.FATAL, "Y".equalsIgnoreCase((String) context
180: .get("fatal")));
181: Debug.set(Debug.ERROR, "Y".equalsIgnoreCase((String) context
182: .get("error")));
183: Debug.set(Debug.WARNING, "Y".equalsIgnoreCase((String) context
184: .get("warning")));
185: Debug.set(Debug.IMPORTANT, "Y"
186: .equalsIgnoreCase((String) context.get("important")));
187: Debug.set(Debug.INFO, "Y".equalsIgnoreCase((String) context
188: .get("info")));
189: Debug.set(Debug.TIMING, "Y".equalsIgnoreCase((String) context
190: .get("timing")));
191: Debug.set(Debug.VERBOSE, "Y".equalsIgnoreCase((String) context
192: .get("verbose")));
193:
194: return ServiceUtil.returnSuccess();
195: }
196:
197: public static Map addOrUpdateLogger(DispatchContext dctc,
198: Map context) {
199: String name = (String) context.get("name");
200: String level = (String) context.get("level");
201: boolean additivity = "Y".equalsIgnoreCase((String) context
202: .get("additivity"));
203:
204: Logger logger = null;
205: if ("root".equals(name)) {
206: logger = Logger.getRootLogger();
207: } else {
208: logger = Logger.getLogger(name);
209: }
210: logger.setLevel(Level.toLevel(level));
211: logger.setAdditivity(additivity);
212:
213: return ServiceUtil.returnSuccess();
214: }
215:
216: public static Map forceGc(DispatchContext dctx, Map context) {
217: System.gc();
218: return ServiceUtil.returnSuccess();
219: }
220:
221: /**
222: * Echo service; returns exactly what was sent.
223: * This service does not have required parameters and does not validate
224: */
225: public static Map echoService(DispatchContext dctx, Map context) {
226: context.put(ModelService.RESPONSE_MESSAGE,
227: ModelService.RESPOND_SUCCESS);
228: return context;
229: }
230:
231: /**
232: * Return Error Service; Used for testing error handling
233: */
234: public static Map returnErrorService(DispatchContext dctx,
235: Map context) {
236: return ServiceUtil
237: .returnError("Return Error Service : Returning Error");
238: }
239:
240: /**
241: * Return TRUE Service; ECA Condition Service
242: */
243: public static Map conditionTrueService(DispatchContext dctx,
244: Map context) {
245: Map result = ServiceUtil.returnSuccess();
246: result.put("conditionReply", Boolean.TRUE);
247: return result;
248: }
249:
250: /**
251: * Return FALSE Service; ECA Condition Service
252: */
253: public static Map conditionFalseService(DispatchContext dctx,
254: Map context) {
255: Map result = ServiceUtil.returnSuccess();
256: result.put("conditionReply", Boolean.FALSE);
257: return result;
258: }
259:
260: /** Cause a Referential Integrity Error */
261: public static Map entityFailTest(DispatchContext dctx, Map context) {
262: GenericDelegator delegator = dctx.getDelegator();
263:
264: // attempt to create a DataSource entity w/ an invalid dataSourceTypeId
265: GenericValue newEntity = delegator
266: .makeValue("DataSource", null);
267: newEntity.set("dataSourceId", "ENTITY_FAIL_TEST");
268: newEntity.set("dataSourceTypeId", "ENTITY_FAIL_TEST");
269: newEntity.set("description",
270: "Entity Fail Test - Delete me if I am here");
271: try {
272: delegator.create(newEntity);
273: } catch (GenericEntityException e) {
274: Debug.logError(e, module);
275: return ServiceUtil
276: .returnError("Unable to create test entity");
277: }
278:
279: /*
280: try {
281: newEntity.remove();
282: } catch(GenericEntityException e) {
283: Debug.logError(e, module);
284: }
285: */
286:
287: return ServiceUtil.returnSuccess();
288: }
289:
290: /** Test entity sorting */
291: public static Map entitySortTest(DispatchContext dctx, Map context) {
292: GenericDelegator delegator = dctx.getDelegator();
293: Set set = new TreeSet();
294:
295: set.add(delegator.getModelEntity("Person"));
296: set.add(delegator.getModelEntity("PartyRole"));
297: set.add(delegator.getModelEntity("Party"));
298: set.add(delegator.getModelEntity("ContactMech"));
299: set.add(delegator.getModelEntity("PartyContactMech"));
300: set.add(delegator.getModelEntity("OrderHeader"));
301: set.add(delegator.getModelEntity("OrderItem"));
302: set.add(delegator.getModelEntity("OrderContactMech"));
303: set.add(delegator.getModelEntity("OrderRole"));
304: set.add(delegator.getModelEntity("Product"));
305: set.add(delegator.getModelEntity("RoleType"));
306:
307: Iterator i = set.iterator();
308: while (i.hasNext()) {
309: Debug.log(((ModelEntity) i.next()).getEntityName(), module);
310: }
311: return ServiceUtil.returnSuccess();
312: }
313:
314: public static Map makeALotOfVisits(DispatchContext dctx, Map context) {
315: GenericDelegator delegator = dctx.getDelegator();
316: int count = ((Integer) context.get("count")).intValue();
317:
318: for (int i = 0; i < count; i++) {
319: GenericValue v = delegator.makeValue("Visit", null);
320: String seqId = delegator.getNextSeqId("Visit");
321:
322: v.set("visitId", seqId);
323: v.set("userCreated", "N");
324: v.set("sessionId", "NA-" + seqId);
325: v.set("serverIpAddress", "127.0.0.1");
326: v.set("serverHostName", "localhost");
327: v.set("webappName", "webtools");
328: v.set("initialLocale", "en_US");
329: v.set("initialRequest",
330: "http://localhost:8080/webtools/control/main");
331: v.set("initialReferrer",
332: "http://localhost:8080/webtools/control/main");
333: v
334: .set(
335: "initialUserAgent",
336: "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/124 (KHTML, like Gecko) Safari/125.1");
337: v.set("clientIpAddress", "127.0.0.1");
338: v.set("clientHostName", "localhost");
339: v.set("fromDate", UtilDateTime.nowTimestamp());
340:
341: try {
342: delegator.create(v);
343: } catch (GenericEntityException e) {
344: Debug.logError(e, module);
345: }
346: }
347:
348: return ServiceUtil.returnSuccess();
349: }
350:
351: public static Map displayXaDebugInfo(DispatchContext dctx,
352: Map context) {
353: if (TransactionUtil.debugResources) {
354: if (TransactionUtil.debugResMap != null
355: && TransactionUtil.debugResMap.size() > 0) {
356: TransactionUtil.logRunningTx();
357: } else {
358: Debug.log("No running transaction to display.", module);
359: }
360: } else {
361: Debug.log("Debug resources is disabled.", module);
362: }
363:
364: return ServiceUtil.returnSuccess();
365: }
366:
367: public static Map byteWrapperTest(DispatchContext dctx, Map context) {
368: ByteWrapper wrapper1 = (ByteWrapper) context
369: .get("byteWrapper1");
370: ByteWrapper wrapper2 = (ByteWrapper) context
371: .get("byteWrapper2");
372: String fileName1 = (String) context.get("saveAsFileName1");
373: String fileName2 = (String) context.get("saveAsFileName2");
374: String ofbizHome = System.getProperty("ofbiz.home");
375: String outputPath1 = ofbizHome
376: + (fileName1.startsWith("/") ? fileName1 : "/"
377: + fileName1);
378: String outputPath2 = ofbizHome
379: + (fileName2.startsWith("/") ? fileName2 : "/"
380: + fileName2);
381:
382: try {
383: RandomAccessFile file1 = new RandomAccessFile(outputPath1,
384: "rw");
385: RandomAccessFile file2 = new RandomAccessFile(outputPath2,
386: "rw");
387: file1.write(wrapper1.getBytes());
388: file2.write(wrapper2.getBytes());
389: } catch (FileNotFoundException e) {
390: Debug.logError(e, module);
391: } catch (IOException e) {
392: Debug.logError(e, module);
393: }
394:
395: return ServiceUtil.returnSuccess();
396: }
397:
398: public static Map uploadTest(DispatchContext dctx, Map context) {
399: LocalDispatcher dispatcher = dctx.getDispatcher();
400: GenericValue userLogin = (GenericValue) context
401: .get("userLogin");
402:
403: ByteWrapper wrapper = (ByteWrapper) context.get("uploadFile");
404: String fileName = (String) context.get("_uploadFile_fileName");
405: String contentType = (String) context
406: .get("_uploadFile_contentType");
407:
408: Map createCtx = new HashMap();
409: createCtx.put("binData", wrapper);
410: createCtx.put("dataResourceTypeId", "OFBIZ_FILE");
411: createCtx.put("dataResourceName", fileName);
412: createCtx.put("dataCategoryId", "PERSONAL");
413: createCtx.put("statusId", "CTNT_PUBLISHED");
414: createCtx.put("mimeTypeId", contentType);
415: createCtx.put("userLogin", userLogin);
416:
417: Map createResp = null;
418: try {
419: createResp = dispatcher.runSync("createFile", createCtx);
420: } catch (GenericServiceException e) {
421: Debug.logError(e, module);
422: return ServiceUtil.returnError(e.getMessage());
423: }
424: if (ServiceUtil.isError(createResp)) {
425: return ServiceUtil.returnError(ServiceUtil
426: .getErrorMessage(createResp));
427: }
428:
429: GenericValue dataResource = (GenericValue) createResp
430: .get("dataResource");
431: if (dataResource != null) {
432: Map contentCtx = new HashMap();
433: contentCtx.put("dataResourceId", dataResource
434: .getString("dataResourceId"));
435: contentCtx.put("localeString", ((Locale) context
436: .get("locale")).toString());
437: contentCtx.put("contentTypeId", "DOCUMENT");
438: contentCtx.put("mimeTypeId", contentType);
439: contentCtx.put("contentName", fileName);
440: contentCtx.put("statusId", "CTNT_PUBLISHED");
441: contentCtx.put("userLogin", userLogin);
442:
443: Map contentResp = null;
444: try {
445: contentResp = dispatcher.runSync("createContent",
446: contentCtx);
447: } catch (GenericServiceException e) {
448: Debug.logError(e, module);
449: return ServiceUtil.returnError(e.getMessage());
450: }
451: if (ServiceUtil.isError(contentResp)) {
452: return ServiceUtil.returnError(ServiceUtil
453: .getErrorMessage(contentResp));
454: }
455: }
456:
457: return ServiceUtil.returnSuccess();
458: }
459:
460: public static Map simpleMapListTest(DispatchContext dctx,
461: Map context) {
462: List listOfStrings = (List) context.get("listOfStrings");
463: Map mapOfStrings = (Map) context.get("mapOfStrings");
464:
465: Iterator i = listOfStrings.iterator();
466: while (i.hasNext()) {
467: String str = (String) i.next();
468: String v = (String) mapOfStrings.get(str);
469: Debug.log("SimpleMapListTest: " + str + " -> " + v, module);
470: }
471:
472: return ServiceUtil.returnSuccess();
473: }
474:
475: public static Map mcaTest(DispatchContext dctx, Map context) {
476: MimeMessageWrapper wrapper = (MimeMessageWrapper) context
477: .get("messageWrapper");
478: MimeMessage message = wrapper.getMessage();
479: try {
480: if (message.getAllRecipients() != null) {
481: Debug.log("To: "
482: + UtilMisc.toListArray(message
483: .getAllRecipients()), module);
484: }
485: if (message.getFrom() != null) {
486: Debug.log("From: "
487: + UtilMisc.toListArray(message.getFrom()),
488: module);
489: }
490: Debug.log("Subject: " + message.getSubject(), module);
491: if (message.getSentDate() != null) {
492: Debug.log("Sent: " + message.getSentDate().toString(),
493: module);
494: }
495: if (message.getReceivedDate() != null) {
496: Debug.log("Received: "
497: + message.getReceivedDate().toString(), module);
498: }
499: } catch (Exception e) {
500: Debug.logError(e, module);
501: }
502: return ServiceUtil.returnSuccess();
503: }
504:
505: public static Map streamTest(DispatchContext dctx, Map context) {
506: InputStream in = (InputStream) context.get("inputStream");
507: OutputStream out = (OutputStream) context.get("outputStream");
508:
509: BufferedReader reader = new BufferedReader(
510: new InputStreamReader(in));
511: Writer writer = new OutputStreamWriter(out);
512: String line;
513:
514: try {
515: while ((line = reader.readLine()) != null) {
516: Debug.log("Read line: " + line, module);
517: writer.write(line);
518: }
519: } catch (IOException e) {
520: Debug.logError(e, module);
521: return ServiceUtil.returnError(e.getMessage());
522: } finally {
523: try {
524: writer.close();
525: } catch (Exception e) {
526: Debug.logError(e, module);
527: }
528: }
529:
530: Map result = ServiceUtil.returnSuccess();
531: result.put("contentType", "text/plain");
532: return result;
533: }
534:
535: public static Map ping(DispatchContext dctx, Map context) {
536: GenericDelegator delegator = dctx.getDelegator();
537: String message = (String) context.get("message");
538: if (message == null) {
539: message = "PONG";
540: }
541:
542: long count = -1;
543: try {
544: count = delegator.findCountByAnd("SequenceValueItem", null);
545: } catch (GenericEntityException e) {
546: Debug.logError(e.getMessage(), module);
547: return ServiceUtil
548: .returnError("Unable to connect to datasource!");
549: }
550:
551: if (count > 0) {
552: Map result = ServiceUtil.returnSuccess();
553: result.put("message", message);
554: return result;
555: } else {
556: return ServiceUtil
557: .returnError("Invalid count returned from database");
558: }
559: }
560: }
|