/** * Copies a user preference group. Call with fromUserLoginId, userPrefGroupTypeId and optional * userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in user's * userLoginId will be used. * * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input arguments. * @return Map with the result of the service, the output parameters. */ public static Map<String, Object> copyUserPreferenceGroup( DispatchContext ctx, Map<String, ?> context) { Delegator delegator = ctx.getDelegator(); Locale locale = (Locale) context.get("locale"); String userLoginId = PreferenceWorker.getUserLoginId(context, false); String fromUserLoginId = (String) context.get("fromUserLoginId"); String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId"); if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefGroupTypeId) || UtilValidate.isEmpty(fromUserLoginId)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "copyPreference.invalidArgument", locale)); } try { Map<String, String> fieldMap = UtilMisc.toMap( "userLoginId", fromUserLoginId, "userPrefGroupTypeId", userPrefGroupTypeId); List<GenericValue> resultList = delegator.findByAnd("UserPreference", fieldMap); if (resultList != null) { for (GenericValue preference : resultList) { preference.set("userLoginId", userLoginId); } delegator.storeAll(resultList); } } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "copyPreference.writeFailure", new Object[] {e.getMessage()}, locale)); } return ServiceUtil.returnSuccess(); }
public static Map<String, Object> ping(DispatchContext dctx, Map<String, ?> context) { Delegator delegator = dctx.getDelegator(); String message = (String) context.get("message"); Locale locale = (Locale) context.get("locale"); if (message == null) { message = "PONG"; } long count = -1; try { count = delegator.findCountByCondition("SequenceValueItem", null, null, null); } catch (GenericEntityException e) { Debug.logError(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "CommonPingDatasourceCannotConnect", locale)); } if (count > 0) { Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("message", message); return result; } else { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "CommonPingDatasourceInvalidCount", locale)); } }
public static Map<String, Object> doAuthorization( DispatchContext dctx, Map<String, Object> context) { Delegator delegator = dctx.getDelegator(); String orderId = (String) context.get("orderId"); BigDecimal processAmount = (BigDecimal) context.get("processAmount"); GenericValue payPalPaymentMethod = (GenericValue) context.get("payPalPaymentMethod"); OrderReadHelper orh = new OrderReadHelper(delegator, orderId); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE); Locale locale = (Locale) context.get("locale"); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoAuthorization"); encoder.add("TRANSACTIONID", payPalPaymentMethod.getString("transactionId")); encoder.add("AMT", processAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("TRANSACTIONENTITY", "Order"); String currency = (String) context.get("currency"); if (currency == null) { currency = orh.getCurrency(); } encoder.add("CURRENCYCODE", currency); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("authResult", false); result.put("authRefNum", "N/A"); result.put("processAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("authCode", error.getKey()); result.put("authMessage", error.getValue()); } else { result.put( "authMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("authResult", true); result.put("processAmount", new BigDecimal(decoder.get("AMT"))); result.put("authRefNum", decoder.get("TRANSACTIONID")); } // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what // should be checked for this type of transaction return result; }
public static Map<String, Object> doCapture(DispatchContext dctx, Map<String, Object> context) { GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference"); BigDecimal captureAmount = (BigDecimal) context.get("captureAmount"); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, PaymentGatewayServices.AUTH_SERVICE_TYPE); GenericValue authTrans = (GenericValue) context.get("authTrans"); Locale locale = (Locale) context.get("locale"); if (authTrans == null) { authTrans = PaymentGatewayServices.getAuthTransaction(paymentPref); } NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoCapture"); encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum")); encoder.add("AMT", captureAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("CURRENCYCODE", authTrans.getString("currencyUomId")); encoder.add("COMPLETETYPE", "NotComplete"); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("captureResult", false); result.put("captureRefNum", "N/A"); result.put("captureAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("captureCode", error.getKey()); result.put("captureMessage", error.getValue()); } else { result.put( "captureMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("captureResult", true); result.put("captureAmount", new BigDecimal(decoder.get("AMT"))); result.put("captureRefNum", decoder.get("TRANSACTIONID")); } // TODO: Look into possible PAYMENTSTATUS and PENDINGREASON return codes, it is unclear what // should be checked for this type of transaction return result; }
/** * Authorizes and captures an EFT transaction. If the authorization or capture fails due to * problems with the transaction, this service will result in a failure. * * <p>If this service results in an error, it means that the service is not propery configured and * will not work until the issues are resolved. */ public static Map authorizeAndCaptureEft(DispatchContext dctx, Map context) { Delegator delegator = dctx.getDelegator(); String resource = getResource(context); Double amount = (Double) context.get("processAmount"); GenericValue eftAccount = (GenericValue) context.get("eftAccount"); String currencyUomId = (String) context.get("currency"); try { Map request = buildRequestHeader(resource); request.putAll(buildRequest(eftAccount, amount, currencyUomId, "AUTH_CAPTURE")); request.putAll(buildCustomerRequest(delegator, context)); request.putAll(buildOrderRequest(context)); AuthorizeResponse response = processRequest(request, resource); // process the response Map results = ServiceUtil.returnSuccess(); if (response == null) { results.put("authResult", Boolean.FALSE); results.put("authRefNum", AuthorizeResponse.ERROR); results.put("processAmount", new Double(0.0)); } else if (AuthorizeResponse.APPROVED.equals(response.getResponseCode())) { results.put("authResult", Boolean.TRUE); results.put("authFlag", response.getReasonCode()); results.put("authMessage", response.getReasonText()); results.put("authCode", response.getResponseField(AuthorizeResponse.AUTHORIZATION_CODE)); results.put("authRefNum", response.getResponseField(AuthorizeResponse.TRANSACTION_ID)); results.put( "processAmount", new Double(response.getResponseField(AuthorizeResponse.AMOUNT))); } else { results.put("authResult", Boolean.FALSE); results.put("authFlag", response.getReasonCode()); results.put("authMessage", response.getReasonText()); results.put("authCode", response.getResponseField(AuthorizeResponse.AUTHORIZATION_CODE)); results.put("authRefNum", AuthorizeResponse.ERROR); results.put("processAmount", new Double(0.0)); } if (isTestMode(resource)) { Debug.logInfo("eCheck.NET AUTH_CAPTURE results: " + results, module); } return results; } catch (GenericEntityException e) { String message = "Entity engine error when attempting to authorize and capture EFT via eCheck.net: " + e.getMessage(); Debug.logError(e, message, module); return ServiceUtil.returnError(message); } catch (GenericServiceException e) { String message = "Service error when attempting to authorize and capture EFT via eCheck.net. This is a configuration problem that must be fixed before this service can work properly: " + e.getMessage(); Debug.logError(e, message, module); return ServiceUtil.returnError(message); } }
public static Map<String, Object> doRefund(DispatchContext dctx, Map<String, Object> context) { Locale locale = (Locale) context.get("locale"); GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null); if (payPalConfig == null) { return ServiceUtil.returnError( UtilProperties.getMessage( resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale)); } GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); GenericValue captureTrans = PaymentGatewayServices.getCaptureTransaction(orderPaymentPreference); BigDecimal refundAmount = (BigDecimal) context.get("refundAmount"); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "RefundTransaction"); encoder.add("TRANSACTIONID", captureTrans.getString("referenceNum")); encoder.add("REFUNDTYPE", "Partial"); encoder.add("CURRENCYCODE", captureTrans.getString("currencyUomId")); encoder.add("AMT", refundAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString()); encoder.add("NOTE", "Order #" + orderPaymentPreference.getString("orderId")); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("refundResult", false); result.put("refundRefNum", captureTrans.getString("referenceNum")); result.put("refundAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("refundCode", error.getKey()); result.put("refundMessage", error.getValue()); } else { result.put( "refundMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("refundResult", true); result.put("refundAmount", new BigDecimal(decoder.get("GROSSREFUNDAMT"))); result.put("refundRefNum", decoder.get("REFUNDTRANSACTIONID")); } return result; }
/** * Retrieves a group of user preferences from persistent storage. Call with userPrefGroupTypeId * and optional userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in * user's userLoginId will be used. The retrieved preferences group is contained in the * <b>userPrefMap</b> element. * * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input arguments. * @return Map with the result of the service, the output parameters. */ public static Map<String, Object> getUserPreferenceGroup( DispatchContext ctx, Map<String, ?> context) { Locale locale = (Locale) context.get("locale"); if (!PreferenceWorker.isValidGetId(ctx, context)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "getPreference.permissionError", locale)); } Delegator delegator = ctx.getDelegator(); String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId"); if (UtilValidate.isEmpty(userPrefGroupTypeId)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "getPreference.invalidArgument", locale)); } String userLoginId = PreferenceWorker.getUserLoginId(context, true); Map<String, Object> userPrefMap = null; try { Map<String, String> fieldMap = UtilMisc.toMap("userLoginId", "_NA_", "userPrefGroupTypeId", userPrefGroupTypeId); userPrefMap = PreferenceWorker.createUserPrefMap(delegator.findByAnd("UserPreference", fieldMap)); fieldMap.put("userLoginId", userLoginId); userPrefMap.putAll( PreferenceWorker.createUserPrefMap(delegator.findByAnd("UserPreference", fieldMap))); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale)); } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale)); } // for the 'DEFAULT' values find the related values in general properties and if found use // those. Iterator it = userPrefMap.entrySet().iterator(); Map generalProperties = UtilProperties.getProperties("general"); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); if ("DEFAULT".equals(pairs.getValue())) { if (UtilValidate.isNotEmpty(generalProperties.get(pairs.getKey()))) { userPrefMap.put((String) pairs.getKey(), generalProperties.get(pairs.getKey())); } } } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("userPrefMap", userPrefMap); return result; }
public static Map<String, Object> uploadTest(DispatchContext dctx, Map<String, ?> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); byte[] array = (byte[]) context.get("uploadFile"); String fileName = (String) context.get("_uploadFile_fileName"); String contentType = (String) context.get("_uploadFile_contentType"); Map<String, Object> createCtx = FastMap.newInstance(); createCtx.put("binData", array); createCtx.put("dataResourceTypeId", "OFBIZ_FILE"); createCtx.put("dataResourceName", fileName); createCtx.put("dataCategoryId", "PERSONAL"); createCtx.put("statusId", "CTNT_PUBLISHED"); createCtx.put("mimeTypeId", contentType); createCtx.put("userLogin", userLogin); Map<String, Object> createResp = null; try { createResp = dispatcher.runSync("createFile", createCtx); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (ServiceUtil.isError(createResp)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createResp)); } GenericValue dataResource = (GenericValue) createResp.get("dataResource"); if (dataResource != null) { Map<String, Object> contentCtx = FastMap.newInstance(); contentCtx.put("dataResourceId", dataResource.getString("dataResourceId")); contentCtx.put("localeString", ((Locale) context.get("locale")).toString()); contentCtx.put("contentTypeId", "DOCUMENT"); contentCtx.put("mimeTypeId", contentType); contentCtx.put("contentName", fileName); contentCtx.put("statusId", "CTNT_PUBLISHED"); contentCtx.put("userLogin", userLogin); Map<String, Object> contentResp = null; try { contentResp = dispatcher.runSync("createContent", contentCtx); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (ServiceUtil.isError(contentResp)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(contentResp)); } } return ServiceUtil.returnSuccess(); }
public static Map<String, Object> doVoid(DispatchContext dctx, Map<String, Object> context) { GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null); Locale locale = (Locale) context.get("locale"); if (payPalConfig == null) { return ServiceUtil.returnError( UtilProperties.getMessage( resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale)); } GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference"); GenericValue authTrans = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference); NVPEncoder encoder = new NVPEncoder(); encoder.add("METHOD", "DoVoid"); encoder.add("AUTHORIZATIONID", authTrans.getString("referenceNum")); NVPDecoder decoder = null; try { decoder = sendNVPRequest(payPalConfig, encoder); } catch (PayPalException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } if (decoder == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingPayPalUnknownError", locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, String> errors = getErrorMessageMap(decoder); if (UtilValidate.isNotEmpty(errors)) { result.put("releaseResult", false); result.put("releaseRefNum", authTrans.getString("referenceNum")); result.put("releaseAmount", BigDecimal.ZERO); if (errors.size() == 1) { Map.Entry<String, String> error = errors.entrySet().iterator().next(); result.put("releaseCode", error.getKey()); result.put("releaseMessage", error.getValue()); } else { result.put( "releaseMessage", "Multiple errors occurred, please refer to the gateway response messages"); result.put("internalRespMsgs", errors); } } else { result.put("releaseResult", true); // PayPal voids the entire order amount minus any captures, that's a little difficult to // figure out here // so until further testing proves we should do otherwise I'm just going to return requested // void amount result.put("releaseAmount", context.get("releaseAmount")); result.put("releaseRefNum", decoder.get("AUTHORIZATIONID")); } return result; }
/** * Retrieves a single user preference from persistent storage. Call with userPrefTypeId and * optional userPrefLoginId. If userPrefLoginId isn't specified, then the currently logged-in * user's userLoginId will be used. The retrieved preference is contained in the * <b>userPrefMap</b> element. * * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input arguments. * @return Map with the result of the service, the output parameters. */ public static Map<String, Object> getUserPreference(DispatchContext ctx, Map<String, ?> context) { Locale locale = (Locale) context.get("locale"); if (!PreferenceWorker.isValidGetId(ctx, context)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "getPreference.permissionError", locale)); } Delegator delegator = ctx.getDelegator(); String userPrefTypeId = (String) context.get("userPrefTypeId"); if (UtilValidate.isEmpty(userPrefTypeId)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "getPreference.invalidArgument", locale)); } String userLoginId = PreferenceWorker.getUserLoginId(context, true); Map<String, String> fieldMap = UtilMisc.toMap("userLoginId", userLoginId, "userPrefTypeId", userPrefTypeId); String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId"); if (UtilValidate.isNotEmpty(userPrefGroupTypeId)) { fieldMap.put("userPrefGroupTypeId", userPrefGroupTypeId); } Map<String, Object> userPrefMap = null; try { GenericValue preference = EntityUtil.getFirst(delegator.findByAnd("UserPreference", fieldMap)); if (preference != null) { userPrefMap = PreferenceWorker.createUserPrefMap(preference); } } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale)); } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "getPreference.readFailure", new Object[] {e.getMessage()}, locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("userPrefMap", userPrefMap); if (userPrefMap != null) { // Put the value in the result Map too, makes access easier for calling methods. Object userPrefValue = userPrefMap.get(userPrefTypeId); if (userPrefValue != null) { result.put("userPrefValue", userPrefValue); } } return result; }
/** * JavaMail Service that gets body content from a URL * * @param ctx The DispatchContext that this service is operating in * @param rcontext Map containing the input parameters * @return Map with the result of the service, the output parameters */ public static Map<String, Object> sendMailFromUrl( DispatchContext ctx, Map<String, ? extends Object> rcontext) { // pretty simple, get the content and then call the sendMail method below Map<String, Object> sendMailContext = UtilMisc.makeMapWritable(rcontext); String bodyUrl = (String) sendMailContext.remove("bodyUrl"); Map<String, Object> bodyUrlParameters = UtilGenerics.checkMap(sendMailContext.remove("bodyUrlParameters")); Locale locale = (Locale) rcontext.get("locale"); LocalDispatcher dispatcher = ctx.getDispatcher(); URL url = null; try { url = new URL(bodyUrl); } catch (MalformedURLException e) { Debug.logWarning(e, module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendMalformedUrl", UtilMisc.toMap("bodyUrl", bodyUrl, "errorString", e.toString()), locale)); } HttpClient httpClient = new HttpClient(url, bodyUrlParameters); String body = null; try { body = httpClient.post(); } catch (HttpClientException e) { Debug.logWarning(e, module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendGettingError", UtilMisc.toMap("errorString", e.toString()), locale)); } sendMailContext.put("body", body); Map<String, Object> sendMailResult; try { sendMailResult = dispatcher.runSync("sendMail", sendMailContext); } catch (GenericServiceException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } // just return the same result; it contains all necessary information return sendMailResult; }
public static Map<String, Object> streamTest(DispatchContext dctx, Map<String, ?> context) { InputStream in = (InputStream) context.get("inputStream"); OutputStream out = (OutputStream) context.get("outputStream"); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); Writer writer = new OutputStreamWriter(out); String line; try { while ((line = reader.readLine()) != null) { Debug.log("Read line: " + line, module); writer.write(line); } } catch (IOException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } finally { try { writer.close(); } catch (Exception e) { Debug.logError(e, module); } } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("contentType", "text/plain"); return result; }
/** Cause a Referential Integrity Error */ public static Map<String, Object> entityFailTest(DispatchContext dctx, Map<String, ?> context) { Delegator delegator = dctx.getDelegator(); Locale locale = (Locale) context.get("locale"); // attempt to create a DataSource entity w/ an invalid dataSourceTypeId GenericValue newEntity = delegator.makeValue("DataSource"); newEntity.set("dataSourceId", "ENTITY_FAIL_TEST"); newEntity.set("dataSourceTypeId", "ENTITY_FAIL_TEST"); newEntity.set("description", "Entity Fail Test - Delete me if I am here"); try { delegator.create(newEntity); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError( UtilProperties.getMessage(resource, "CommonEntityTestFailure", locale)); } /* try { newEntity.remove(); } catch (GenericEntityException e) { Debug.logError(e, module); } */ return ServiceUtil.returnSuccess(); }
/** * Creates a PartyRelationshipType * * @param ctx The DispatchContext that this service is operating in * @param context Map containing the input parameters * @return Map with the result of the service, the output parameters */ public static Map<String, Object> createPartyRelationshipType( DispatchContext ctx, Map<String, ? extends Object> context) { Map<String, Object> result = FastMap.newInstance(); Delegator delegator = ctx.getDelegator(); Security security = ctx.getSecurity(); GenericValue userLogin = (GenericValue) context.get("userLogin"); ServiceUtil.getPartyIdCheckSecurity( userLogin, security, context, result, "PARTYMGR", "_CREATE"); if (result.size() > 0) return result; GenericValue partyRelationshipType = delegator.makeValue( "PartyRelationshipType", UtilMisc.toMap("partyRelationshipTypeId", context.get("partyRelationshipTypeId"))); partyRelationshipType.set("parentTypeId", context.get("parentTypeId"), true); partyRelationshipType.set("hasTable", context.get("hasTable"), true); partyRelationshipType.set("roleTypeIdValidFrom", context.get("roleTypeIdValidFrom"), true); partyRelationshipType.set("roleTypeIdValidTo", context.get("roleTypeIdValidTo"), false); partyRelationshipType.set("description", context.get("description"), true); partyRelationshipType.set("partyRelationshipName", context.get("partyRelationshipName"), true); try { if (delegator.findOne( partyRelationshipType.getEntityName(), partyRelationshipType.getPrimaryKey(), false) != null) { return ServiceUtil.returnError("Could not create party relationship type: already exists"); } } catch (GenericEntityException e) { Debug.logWarning(e, module); return ServiceUtil.returnError( "Could not create party relationship type (read failure): " + e.getMessage()); } try { partyRelationshipType.create(); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( "Could not create party relationship type (write failure): " + e.getMessage()); } result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); return result; }
public static Map<String, Object> pagerSettingInfo(DispatchContext ctx, Map<?, ?> context) { try { Map<String, Object> retresult = ServiceUtil.returnSuccess(); retresult.put("result", pagerSettingInfo(context)); return retresult; } catch (Exception e1) { return ServiceUtil.returnError(e1.getMessage()); } }
public static Map<?, ?> savePagerChange(DispatchContext ctx, Map<?, ?> context) { try { savePagerChange(context); Map<String, Object> retmap = ServiceUtil.returnSuccess(); return retmap; } catch (Exception ex) { return ServiceUtil.returnError(ex.getMessage()); } }
/** * Stores a user preference group in persistent storage. Call with userPrefMap, * userPrefGroupTypeId and optional userPrefLoginId. If userPrefLoginId isn't specified, then the * currently logged-in user's userLoginId will be used. * * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input arguments. * @return Map with the result of the service, the output parameters. */ public static Map<String, Object> setUserPreferenceGroup( DispatchContext ctx, Map<String, ?> context) { Delegator delegator = ctx.getDelegator(); Locale locale = (Locale) context.get("locale"); String userLoginId = PreferenceWorker.getUserLoginId(context, false); Map<String, Object> userPrefMap = checkMap(context.get("userPrefMap"), String.class, Object.class); String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId"); if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefGroupTypeId) || userPrefMap == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "setPreference.invalidArgument", locale)); } try { for (Iterator i = userPrefMap.entrySet().iterator(); i.hasNext(); ) { Map.Entry mapEntry = (Map.Entry) i.next(); GenericValue rec = delegator.makeValidValue( "UserPreference", PreferenceWorker.toFieldMap( userLoginId, (String) mapEntry.getKey(), userPrefGroupTypeId, (String) mapEntry.getValue())); delegator.createOrStore(rec); } } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale)); } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale)); } return ServiceUtil.returnSuccess(); }
public static Map<String, Object> getPagerDefaultPrefefences( DispatchContext ctx, Map<?, ?> context) { try { Map<String, Object> retresult = ServiceUtil.returnSuccess(); retresult.put("result", getPagerDefaultPrefefences()); return retresult; } catch (Exception ex) { return ServiceUtil.returnError(ex.getMessage()); } }
/** * Stores a single user preference in persistent storage. Call with userPrefTypeId, * userPrefGroupTypeId, userPrefValue and optional userPrefLoginId. If userPrefLoginId isn't * specified, then the currently logged-in user's userLoginId will be used. * * @param ctx The DispatchContext that this service is operating in. * @param context Map containing the input arguments. * @return Map with the result of the service, the output parameters. */ public static Map<String, Object> setUserPreference(DispatchContext ctx, Map<String, ?> context) { Delegator delegator = ctx.getDelegator(); Locale locale = (Locale) context.get("locale"); String userLoginId = PreferenceWorker.getUserLoginId(context, false); String userPrefTypeId = (String) context.get("userPrefTypeId"); Object userPrefValue = (String) context.get("userPrefValue"); if (UtilValidate.isEmpty(userLoginId) || UtilValidate.isEmpty(userPrefTypeId) || userPrefValue == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "setPreference.invalidArgument", locale)); } String userPrefGroupTypeId = (String) context.get("userPrefGroupTypeId"); String userPrefDataType = (String) context.get("userPrefDataType"); try { if (UtilValidate.isNotEmpty(userPrefDataType)) { userPrefValue = ObjectType.simpleTypeConvert(userPrefValue, userPrefDataType, null, null, false); } GenericValue rec = delegator.makeValidValue( "UserPreference", PreferenceWorker.toFieldMap( userLoginId, userPrefTypeId, userPrefGroupTypeId, userPrefValue)); delegator.createOrStore(rec); } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale)); } catch (GeneralException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "setPreference.writeFailure", new Object[] {e.getMessage()}, locale)); } return ServiceUtil.returnSuccess(); }
public static Map<String, Object> finAccountReleaseAuth( DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference"); Locale locale = (Locale) context.get("locale"); String err = UtilProperties.getMessage(resourceError, "AccountingFinAccountCannotBeExpired", locale); try { // expire the related financial authorization transaction GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(paymentPref); if (authTransaction == null) { return ServiceUtil.returnError( err + UtilProperties.getMessage( resourceError, "AccountingFinAccountCannotFindAuthorization", locale)); } Map<String, Object> input = UtilMisc.toMap( "userLogin", userLogin, "finAccountAuthId", authTransaction.get("referenceNum")); Map<String, Object> serviceResults = dispatcher.runSync("expireFinAccountAuth", input); Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("releaseRefNum", authTransaction.getString("referenceNum")); result.put("releaseAmount", authTransaction.getBigDecimal("amount")); result.put("releaseResult", Boolean.TRUE); // if there's an error, don't release if (ServiceUtil.isError(serviceResults)) { return ServiceUtil.returnError(err + ServiceUtil.getErrorMessage(serviceResults)); } return result; } catch (GenericServiceException e) { Debug.logError(e, e.getMessage(), module); return ServiceUtil.returnError(err + e.getMessage()); } }
/** * Returns a complete category trail - can be used for exporting proper category trees. This is * mostly useful when used in combination with bread-crumbs, for building a faceted index tree, or * to export a category tree for migration to another system. Will create the tree from root point * to categoryId. * * <p>This method is not meant to be run on every request. Its best use is to generate the trail * every so often and store somewhere (a lucene/solr tree, entities, cache or so). * * @param productCategoryId id of category the trail should be generated for * @returns List organized trail from root point to categoryId. */ public static Map getCategoryTrail(DispatchContext dctx, Map context) { String productCategoryId = (String) context.get("productCategoryId"); Map<String, Object> results = ServiceUtil.returnSuccess(); GenericDelegator delegator = (GenericDelegator) dctx.getDelegator(); List<String> trailElements = FastList.newInstance(); trailElements.add(productCategoryId); String parentProductCategoryId = productCategoryId; while (UtilValidate.isNotEmpty(parentProductCategoryId)) { // find product category rollup try { List<EntityCondition> rolllupConds = FastList.newInstance(); rolllupConds.add( EntityCondition.makeCondition("productCategoryId", parentProductCategoryId)); rolllupConds.add(EntityUtil.getFilterByDateExpr()); List<GenericValue> productCategoryRollups = delegator.findList( "ProductCategoryRollup", EntityCondition.makeCondition(rolllupConds), null, UtilMisc.toList("sequenceNum"), null, true); if (UtilValidate.isNotEmpty(productCategoryRollups)) { // add only categories that belong to the top category to trail for (GenericValue productCategoryRollup : productCategoryRollups) { String trailCategoryId = productCategoryRollup.getString("parentProductCategoryId"); parentProductCategoryId = trailCategoryId; if (trailElements.contains(trailCategoryId)) { break; } else { trailElements.add(trailCategoryId); } } } else { parentProductCategoryId = null; } } catch (GenericEntityException e) { Map<String, String> messageMap = UtilMisc.toMap("errMessage", ". Cannot generate trail from product category. "); String errMsg = UtilProperties.getMessage( "CommonUiLabels", "CommonDatabaseProblem", messageMap, (Locale) context.get("locale")); Debug.logError(e, errMsg, module); return ServiceUtil.returnError(errMsg); } } Collections.reverse(trailElements); results.put("trail", trailElements); return results; }
public static Map<String, Object> testRollbackListener( DispatchContext dctx, Map<String, ?> context) { Locale locale = (Locale) context.get("locale"); ServiceXaWrapper xar = new ServiceXaWrapper(dctx); xar.setRollbackService("testScv", context); try { xar.enlist(); } catch (XAException e) { Debug.logError(e, module); } return ServiceUtil.returnError( UtilProperties.getMessage(resource, "CommonTestRollingBack", locale)); }
public static Map<String, Object> convertOrderIdListToHeaders( DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); List<GenericValue> orderHeaderList = UtilGenerics.checkList(context.get("orderHeaderList")); List<String> orderIdList = UtilGenerics.checkList(context.get("orderIdList")); // we don't want to process if there is already a header list if (orderHeaderList == null) { // convert the ID list to headers if (orderIdList != null) { List<EntityCondition> conditionList1 = FastList.newInstance(); List<EntityCondition> conditionList2 = FastList.newInstance(); // we are only concerned about approved sales orders conditionList2.add( EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "ORDER_APPROVED")); conditionList2.add( EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "SALES_ORDER")); // build the expression list from the IDs for (String orderId : orderIdList) { conditionList1.add( EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId)); } // create the conditions EntityCondition idCond = EntityCondition.makeCondition(conditionList1, EntityOperator.OR); conditionList2.add(idCond); EntityCondition cond = EntityCondition.makeCondition(conditionList2, EntityOperator.AND); // run the query try { orderHeaderList = delegator.findList( "OrderHeader", cond, null, UtilMisc.toList("+orderDate"), null, false); } catch (GenericEntityException e) { Debug.logError(e, module); return ServiceUtil.returnError(e.getMessage()); } Debug.logInfo("Recieved orderIdList - " + orderIdList, module); Debug.logInfo("Found orderHeaderList - " + orderHeaderList, module); } } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("orderHeaderList", orderHeaderList); return result; }
/** * Create Note Record * * @param ctx The DispatchContext that this service is operating in * @param context Map containing the input parameters * @return Map with the result of the service, the output parameters */ public static Map<String, Object> createNote(DispatchContext ctx, Map<String, ?> context) { Delegator delegator = ctx.getDelegator(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Timestamp noteDate = (Timestamp) context.get("noteDate"); String partyId = (String) context.get("partyId"); String noteName = (String) context.get("noteName"); String note = (String) context.get("note"); String noteId = delegator.getNextSeqId("NoteData"); Locale locale = (Locale) context.get("locale"); if (noteDate == null) { noteDate = UtilDateTime.nowTimestamp(); } // check for a party id if (partyId == null) { if (userLogin != null && userLogin.get("partyId") != null) partyId = userLogin.getString("partyId"); } Map<String, Object> fields = UtilMisc.toMap( "noteId", noteId, "noteName", noteName, "noteInfo", note, "noteParty", partyId, "noteDateTime", noteDate); try { GenericValue newValue = delegator.makeValue("NoteData", fields); delegator.create(newValue); } catch (GenericEntityException e) { return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonNoteCannotBeUpdated", UtilMisc.toMap("errorString", e.getMessage()), locale)); } Map<String, Object> result = ServiceUtil.returnSuccess(); result.put("noteId", noteId); result.put("partyId", partyId); return result; }
public static Map<String, Object> getPagerDefaultPrefefences( // µÃµ½È±Ê¡Öµ DispatchContext ctx, Map<?, ?> context) { try { Map<String, Object> retresult = ServiceUtil.returnSuccess(); retresult.put( "result", (ctx.getDispatcher().runSync("getPagerDefaultPrefefencesValue", new HashMap())) .get("result")); return retresult; } catch (Exception ex) { return ServiceUtil.returnError(ex.getMessage()); } }
private Map<String, Object> serviceInvoker( String localName, ModelService modelService, Map<String, Object> context) throws GenericServiceException { if (UtilValidate.isEmpty(modelService.location)) { throw new GenericServiceException("Cannot run Groovy service with empty location"); } Map<String, Object> params = FastMap.newInstance(); params.putAll(context); context.put(ScriptUtil.PARAMETERS_KEY, params); DispatchContext dctx = dispatcher.getLocalContext(localName); context.put("dctx", dctx); context.put("dispatcher", dctx.getDispatcher()); context.put("delegator", dispatcher.getDelegator()); try { ScriptContext scriptContext = ScriptUtil.createScriptContext(context, protectedKeys); ScriptHelper scriptHelper = (ScriptHelper) scriptContext.getAttribute(ScriptUtil.SCRIPT_HELPER_KEY); if (scriptHelper != null) { context.put(ScriptUtil.SCRIPT_HELPER_KEY, scriptHelper); } Script script = InvokerHelper.createScript( GroovyUtil.getScriptClassFromLocation( this.getLocation(modelService), groovyClassLoader), GroovyUtil.getBinding(context)); Object resultObj = null; if (UtilValidate.isEmpty(modelService.invoke)) { resultObj = script.run(); } else { resultObj = script.invokeMethod(modelService.invoke, EMPTY_ARGS); } if (resultObj == null) { resultObj = scriptContext.getAttribute(ScriptUtil.RESULT_KEY); } if (resultObj != null && resultObj instanceof Map<?, ?>) { return cast(resultObj); } Map<String, Object> result = ServiceUtil.returnSuccess(); result.putAll( modelService.makeValid(scriptContext.getBindings(ScriptContext.ENGINE_SCOPE), "OUT")); return result; } catch (GeneralException ge) { throw new GenericServiceException(ge); } catch (Exception e) { return ServiceUtil.returnError(e.getMessage()); } }
public static Map<?, ?> savePagerChange(DispatchContext ctx, Map<?, ?> context) { try { Map<String, Object> map = new HashMap<String, Object>(); map.put("pagerPort", (String) context.get("pagerPort")); map.put("pagerSpeed", (String) context.get("pagerSpeed")); map.put("pagerAlphaPhone", (String) context.get("pagerAlphaPhone")); map.put("pagerAlphaPIN", (String) context.get("pagerAlphaPIN")); map.put("pagerDirectPhone", (String) context.get("pagerDirectPhone")); map.put("pagerOptionPhone", (String) context.get("pagerOptionPhone")); map.put("pagerCustom", (String) context.get("pagerCustom")); map.put("pagerOption", (String) context.get("pagerOption")); map.put("pagerType", (String) context.get("pagerType")); ctx.getDispatcher().runSync("savePagerChangeValue", UtilMisc.toMap("Value", map)); Map<String, Object> retmap = ServiceUtil.returnSuccess(); return retmap; } catch (Exception ex) { return ServiceUtil.returnError(ex.getMessage()); } }
/** * Basic JavaMail Service * * @param ctx The DispatchContext that this service is operating in * @param context Map containing the input parameters * @return Map with the result of the service, the output parameters */ public static Map<String, Object> sendMail( DispatchContext ctx, Map<String, ? extends Object> context) { String communicationEventId = (String) context.get("communicationEventId"); String orderId = (String) context.get("orderId"); Locale locale = (Locale) context.get("locale"); if (communicationEventId != null) { Debug.logInfo("SendMail Running, for communicationEventId : " + communicationEventId, module); } Map<String, Object> results = ServiceUtil.returnSuccess(); String subject = (String) context.get("subject"); subject = FlexibleStringExpander.expandString(subject, context); String partyId = (String) context.get("partyId"); String body = (String) context.get("body"); List<Map<String, Object>> bodyParts = UtilGenerics.checkList(context.get("bodyParts")); GenericValue userLogin = (GenericValue) context.get("userLogin"); results.put("communicationEventId", communicationEventId); results.put("partyId", partyId); results.put("subject", subject); if (UtilValidate.isNotEmpty(orderId)) { results.put("orderId", orderId); } if (UtilValidate.isNotEmpty(body)) { body = FlexibleStringExpander.expandString(body, context); results.put("body", body); } if (UtilValidate.isNotEmpty(bodyParts)) { results.put("bodyParts", bodyParts); } results.put("userLogin", userLogin); String sendTo = (String) context.get("sendTo"); String sendCc = (String) context.get("sendCc"); String sendBcc = (String) context.get("sendBcc"); // check to see if we should redirect all mail for testing String redirectAddress = UtilProperties.getPropertyValue("general.properties", "mail.notifications.redirectTo"); if (UtilValidate.isNotEmpty(redirectAddress)) { String originalRecipients = " [To: " + sendTo + ", Cc: " + sendCc + ", Bcc: " + sendBcc + "]"; subject += originalRecipients; sendTo = redirectAddress; sendCc = null; sendBcc = null; } String sendFrom = (String) context.get("sendFrom"); String sendType = (String) context.get("sendType"); String port = (String) context.get("port"); String socketFactoryClass = (String) context.get("socketFactoryClass"); String socketFactoryPort = (String) context.get("socketFactoryPort"); String socketFactoryFallback = (String) context.get("socketFactoryFallback"); String sendVia = (String) context.get("sendVia"); String authUser = (String) context.get("authUser"); String authPass = (String) context.get("authPass"); String messageId = (String) context.get("messageId"); String contentType = (String) context.get("contentType"); Boolean sendPartial = (Boolean) context.get("sendPartial"); Boolean isStartTLSEnabled = (Boolean) context.get("startTLSEnabled"); boolean useSmtpAuth = false; // define some default if (sendType == null || sendType.equals("mail.smtp.host")) { sendType = "mail.smtp.host"; if (UtilValidate.isEmpty(sendVia)) { sendVia = UtilProperties.getPropertyValue( "general.properties", "mail.smtp.relay.host", "localhost"); } if (UtilValidate.isEmpty(authUser)) { authUser = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.user"); } if (UtilValidate.isEmpty(authPass)) { authPass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.auth.password"); } if (UtilValidate.isNotEmpty(authUser)) { useSmtpAuth = true; } if (UtilValidate.isEmpty(port)) { port = UtilProperties.getPropertyValue("general.properties", "mail.smtp.port"); } if (UtilValidate.isEmpty(socketFactoryPort)) { socketFactoryPort = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.port"); } if (UtilValidate.isEmpty(socketFactoryClass)) { socketFactoryClass = UtilProperties.getPropertyValue("general.properties", "mail.smtp.socketFactory.class"); } if (UtilValidate.isEmpty(socketFactoryFallback)) { socketFactoryFallback = UtilProperties.getPropertyValue( "general.properties", "mail.smtp.socketFactory.fallback", "false"); } if (sendPartial == null) { sendPartial = UtilProperties.propertyValueEqualsIgnoreCase( "general.properties", "mail.smtp.sendpartial", "true") ? true : false; } if (isStartTLSEnabled == null) { isStartTLSEnabled = UtilProperties.propertyValueEqualsIgnoreCase( "general.properties", "mail.smtp.starttls.enable", "true"); } } else if (sendVia == null) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "CommonEmailSendMissingParameterSendVia", locale)); } if (contentType == null) { contentType = "text/html"; } if (UtilValidate.isNotEmpty(bodyParts)) { contentType = "multipart/mixed"; } results.put("contentType", contentType); Session session; MimeMessage mail; try { Properties props = System.getProperties(); props.put(sendType, sendVia); if (UtilValidate.isNotEmpty(port)) { props.put("mail.smtp.port", port); } if (UtilValidate.isNotEmpty(socketFactoryPort)) { props.put("mail.smtp.socketFactory.port", socketFactoryPort); } if (UtilValidate.isNotEmpty(socketFactoryClass)) { props.put("mail.smtp.socketFactory.class", socketFactoryClass); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); } if (UtilValidate.isNotEmpty(socketFactoryFallback)) { props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback); } if (useSmtpAuth) { props.put("mail.smtp.auth", "true"); } if (sendPartial != null) { props.put("mail.smtp.sendpartial", sendPartial ? "true" : "false"); } if (isStartTLSEnabled) { props.put("mail.smtp.starttls.enable", "true"); } session = Session.getInstance(props); boolean debug = UtilProperties.propertyValueEqualsIgnoreCase("general.properties", "mail.debug.on", "Y"); session.setDebug(debug); mail = new MimeMessage(session); if (messageId != null) { mail.setHeader("In-Reply-To", messageId); mail.setHeader("References", messageId); } mail.setFrom(new InternetAddress(sendFrom)); mail.setSubject(subject, "UTF-8"); mail.setHeader("X-Mailer", "Apache OFBiz, The Apache Open For Business Project"); mail.setSentDate(new Date()); mail.addRecipients(Message.RecipientType.TO, sendTo); if (UtilValidate.isNotEmpty(sendCc)) { mail.addRecipients(Message.RecipientType.CC, sendCc); } if (UtilValidate.isNotEmpty(sendBcc)) { mail.addRecipients(Message.RecipientType.BCC, sendBcc); } if (UtilValidate.isNotEmpty(bodyParts)) { // check for multipart message (with attachments) // BodyParts contain a list of Maps items containing content(String) and type(String) of the // attachement MimeMultipart mp = new MimeMultipart(); Debug.logInfo(bodyParts.size() + " multiparts found", module); for (Map<String, Object> bodyPart : bodyParts) { Object bodyPartContent = bodyPart.get("content"); MimeBodyPart mbp = new MimeBodyPart(); if (bodyPartContent instanceof String) { Debug.logInfo( "part of type: " + bodyPart.get("type") + " and size: " + bodyPart.get("content").toString().length(), module); mbp.setText( (String) bodyPartContent, "UTF-8", ((String) bodyPart.get("type")).substring(5)); } else if (bodyPartContent instanceof byte[]) { ByteArrayDataSource bads = new ByteArrayDataSource((byte[]) bodyPartContent, (String) bodyPart.get("type")); Debug.logInfo( "part of type: " + bodyPart.get("type") + " and size: " + ((byte[]) bodyPartContent).length, module); mbp.setDataHandler(new DataHandler(bads)); } else if (bodyPartContent instanceof DataHandler) { mbp.setDataHandler((DataHandler) bodyPartContent); } else { mbp.setDataHandler(new DataHandler(bodyPartContent, (String) bodyPart.get("type"))); } String fileName = (String) bodyPart.get("filename"); if (fileName != null) { mbp.setFileName(fileName); } mp.addBodyPart(mbp); } mail.setContent(mp); mail.saveChanges(); } else { // create the singelpart message if (contentType.startsWith("text")) { mail.setText(body, "UTF-8", contentType.substring(5)); } else { mail.setContent(body, contentType); } mail.saveChanges(); } } catch (MessagingException e) { Debug.logError( e, "MessagingException when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module); Debug.logError( "Email message that could not be created to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendMessagingException", UtilMisc.toMap( "sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale)); } catch (IOException e) { Debug.logError( e, "IOExcepton when creating message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module); Debug.logError( "Email message that could not be created to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendIOException", UtilMisc.toMap( "sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale)); } // check to see if sending mail is enabled String mailEnabled = UtilProperties.getPropertyValue("general.properties", "mail.notifications.enabled", "N"); if (!"Y".equalsIgnoreCase(mailEnabled)) { // no error; just return as if we already processed Debug.logImportant( "Mail notifications disabled in general.properties; mail with subject [" + subject + "] not sent to addressee [" + sendTo + "]", module); Debug.logVerbose( "What would have been sent, the addressee: " + sendTo + " subject: " + subject + " context: " + context, module); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); return results; } Transport trans = null; try { trans = session.getTransport("smtp"); if (!useSmtpAuth) { trans.connect(); } else { trans.connect(sendVia, authUser, authPass); } trans.sendMessage(mail, mail.getAllRecipients()); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); results.put("messageId", mail.getMessageID()); trans.close(); } catch (SendFailedException e) { // message code prefix may be used by calling services to determine the cause of the failure Debug.logError( e, "[ADDRERR] Address error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module); List<SMTPAddressFailedException> failedAddresses = FastList.newInstance(); Exception nestedException = null; while ((nestedException = e.getNextException()) != null && nestedException instanceof MessagingException) { if (nestedException instanceof SMTPAddressFailedException) { SMTPAddressFailedException safe = (SMTPAddressFailedException) nestedException; Debug.logError( "Failed to send message to [" + safe.getAddress() + "], return code [" + safe.getReturnCode() + "], return message [" + safe.getMessage() + "]", module); failedAddresses.add(safe); break; } } Boolean sendFailureNotification = (Boolean) context.get("sendFailureNotification"); if (sendFailureNotification == null || sendFailureNotification) { sendFailureNotification(ctx, context, mail, failedAddresses); results.put("messageWrapper", new MimeMessageWrapper(session, mail)); try { results.put("messageId", mail.getMessageID()); trans.close(); } catch (MessagingException e1) { Debug.logError(e1, module); } } else { return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendAddressError", UtilMisc.toMap( "sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale)); } } catch (MessagingException e) { // message code prefix may be used by calling services to determine the cause of the failure Debug.logError( e, "[CON] Connection error when sending message to [" + sendTo + "] from [" + sendFrom + "] cc [" + sendCc + "] bcc [" + sendBcc + "] subject [" + subject + "]", module); Debug.logError( "Email message that could not be sent to [" + sendTo + "] had context: " + context, module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendConnectionError", UtilMisc.toMap( "sendTo", sendTo, "sendFrom", sendFrom, "sendCc", sendCc, "sendBcc", sendBcc, "subject", subject), locale)); } return results; }
/** * JavaMail Service that gets body content from a Screen Widget defined in the product store * record and if available as attachment also. * * @param dctx The DispatchContext that this service is operating in * @param rServiceContext Map containing the input parameters * @return Map with the result of the service, the output parameters */ public static Map<String, Object> sendMailFromScreen( DispatchContext dctx, Map<String, ? extends Object> rServiceContext) { Map<String, Object> serviceContext = UtilMisc.makeMapWritable(rServiceContext); LocalDispatcher dispatcher = dctx.getDispatcher(); String webSiteId = (String) serviceContext.remove("webSiteId"); String bodyText = (String) serviceContext.remove("bodyText"); String bodyScreenUri = (String) serviceContext.remove("bodyScreenUri"); String xslfoAttachScreenLocationParam = (String) serviceContext.remove("xslfoAttachScreenLocation"); String attachmentNameParam = (String) serviceContext.remove("attachmentName"); List<String> xslfoAttachScreenLocationListParam = UtilGenerics.checkList(serviceContext.remove("xslfoAttachScreenLocationList")); List<String> attachmentNameListParam = UtilGenerics.checkList(serviceContext.remove("attachmentNameList")); List<String> xslfoAttachScreenLocationList = FastList.newInstance(); List<String> attachmentNameList = FastList.newInstance(); if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationParam)) xslfoAttachScreenLocationList.add(xslfoAttachScreenLocationParam); if (UtilValidate.isNotEmpty(attachmentNameParam)) attachmentNameList.add(attachmentNameParam); if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationListParam)) xslfoAttachScreenLocationList.addAll(xslfoAttachScreenLocationListParam); if (UtilValidate.isNotEmpty(attachmentNameListParam)) attachmentNameList.addAll(attachmentNameListParam); Locale locale = (Locale) serviceContext.get("locale"); Map<String, Object> bodyParameters = UtilGenerics.checkMap(serviceContext.remove("bodyParameters")); if (bodyParameters == null) { bodyParameters = MapStack.create(); } if (!bodyParameters.containsKey("locale")) { bodyParameters.put("locale", locale); } else { locale = (Locale) bodyParameters.get("locale"); } String partyId = (String) serviceContext.get("partyId"); if (partyId == null) { partyId = (String) bodyParameters.get("partyId"); } String orderId = (String) bodyParameters.get("orderId"); String custRequestId = (String) bodyParameters.get("custRequestId"); bodyParameters.put("communicationEventId", serviceContext.get("communicationEventId")); NotificationServices.setBaseUrl(dctx.getDelegator(), webSiteId, bodyParameters); String contentType = (String) serviceContext.remove("contentType"); StringWriter bodyWriter = new StringWriter(); MapStack<String> screenContext = MapStack.create(); screenContext.put("locale", locale); ScreenRenderer screens = new ScreenRenderer(bodyWriter, screenContext, htmlScreenRenderer); screens.populateContextForService(dctx, bodyParameters); screenContext.putAll(bodyParameters); if (bodyScreenUri != null) { try { screens.render(bodyScreenUri); } catch (GeneralException e) { Debug.logError(e, "Error rendering screen for email: " + e.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale)); } catch (IOException e) { Debug.logError(e, "Error rendering screen for email: " + e.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale)); } catch (SAXException e) { Debug.logError(e, "Error rendering screen for email: " + e.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale)); } catch (ParserConfigurationException e) { Debug.logError(e, "Error rendering screen for email: " + e.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendRenderingScreenEmailError", UtilMisc.toMap("errorString", e.toString()), locale)); } } boolean isMultiPart = false; // check if attachment screen location passed in if (UtilValidate.isNotEmpty(xslfoAttachScreenLocationList)) { List<Map<String, ? extends Object>> bodyParts = FastList.newInstance(); if (bodyText != null) { bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale); bodyParts.add(UtilMisc.<String, Object>toMap("content", bodyText, "type", "text/html")); } else { bodyParts.add( UtilMisc.<String, Object>toMap("content", bodyWriter.toString(), "type", "text/html")); } for (int i = 0; i < xslfoAttachScreenLocationList.size(); i++) { String xslfoAttachScreenLocation = xslfoAttachScreenLocationList.get(i); String attachmentName = "Details.pdf"; if (UtilValidate.isNotEmpty(attachmentNameList) && attachmentNameList.size() >= i) { attachmentName = attachmentNameList.get(i); } isMultiPart = true; // start processing fo pdf attachment try { Writer writer = new StringWriter(); MapStack<String> screenContextAtt = MapStack.create(); // substitute the freemarker variables... ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContext, foScreenRenderer); screensAtt.populateContextForService(dctx, bodyParameters); screenContextAtt.putAll(bodyParameters); screensAtt.render(xslfoAttachScreenLocation); /* try { // save generated fo file for debugging String buf = writer.toString(); java.io.FileWriter fw = new java.io.FileWriter(new java.io.File("/tmp/file1.xml")); fw.write(buf.toString()); fw.close(); } catch (IOException e) { Debug.logError(e, "Couldn't save xsl-fo xml debug file: " + e.toString(), module); } */ // create the input stream for the generation StreamSource src = new StreamSource(new StringReader(writer.toString())); // create the output stream for the generation ByteArrayOutputStream baos = new ByteArrayOutputStream(); Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF); ApacheFopWorker.transform(src, null, fop); // and generate the PDF baos.flush(); baos.close(); // store in the list of maps for sendmail.... bodyParts.add( UtilMisc.<String, Object>toMap( "content", baos.toByteArray(), "type", "application/pdf", "filename", attachmentName)); } catch (GeneralException ge) { Debug.logError(ge, "Error rendering PDF attachment for email: " + ge.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendRenderingScreenPdfError", UtilMisc.toMap("errorString", ge.toString()), locale)); } catch (IOException ie) { Debug.logError(ie, "Error rendering PDF attachment for email: " + ie.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendRenderingScreenPdfError", UtilMisc.toMap("errorString", ie.toString()), locale)); } catch (FOPException fe) { Debug.logError(fe, "Error rendering PDF attachment for email: " + fe.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendRenderingScreenPdfError", UtilMisc.toMap("errorString", fe.toString()), locale)); } catch (SAXException se) { Debug.logError(se, "Error rendering PDF attachment for email: " + se.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendRenderingScreenPdfError", UtilMisc.toMap("errorString", se.toString()), locale)); } catch (ParserConfigurationException pe) { Debug.logError(pe, "Error rendering PDF attachment for email: " + pe.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendRenderingScreenPdfError", UtilMisc.toMap("errorString", pe.toString()), locale)); } serviceContext.put("bodyParts", bodyParts); } } else { isMultiPart = false; // store body and type for single part message in the context. if (bodyText != null) { bodyText = FlexibleStringExpander.expandString(bodyText, screenContext, locale); serviceContext.put("body", bodyText); } else { serviceContext.put("body", bodyWriter.toString()); } // Only override the default contentType in case of plaintext, since other contentTypes may be // multipart // and would require specific handling. if (contentType != null && contentType.equalsIgnoreCase("text/plain")) { serviceContext.put("contentType", "text/plain"); } else { serviceContext.put("contentType", "text/html"); } } // also expand the subject at this point, just in case it has the FlexibleStringExpander syntax // in it... String subject = (String) serviceContext.remove("subject"); subject = FlexibleStringExpander.expandString(subject, screenContext, locale); Debug.logInfo("Expanded email subject to: " + subject, module); serviceContext.put("subject", subject); serviceContext.put("partyId", partyId); if (UtilValidate.isNotEmpty(orderId)) { serviceContext.put("orderId", orderId); } if (UtilValidate.isNotEmpty(custRequestId)) { serviceContext.put("custRequestId", custRequestId); } if (Debug.verboseOn()) Debug.logVerbose("sendMailFromScreen sendMail context: " + serviceContext, module); Map<String, Object> result = ServiceUtil.returnSuccess(); Map<String, Object> sendMailResult; try { if (isMultiPart) { sendMailResult = dispatcher.runSync("sendMailMultiPart", serviceContext); } else { sendMailResult = dispatcher.runSync("sendMail", serviceContext); } } catch (Exception e) { Debug.logError(e, "Error send email:" + e.toString(), module); return ServiceUtil.returnError( UtilProperties.getMessage( resource, "CommonEmailSendError", UtilMisc.toMap("errorString", e.toString()), locale)); } if (ServiceUtil.isError(sendMailResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(sendMailResult)); } result.put("messageWrapper", sendMailResult.get("messageWrapper")); result.put("body", bodyWriter.toString()); result.put("subject", subject); result.put("communicationEventId", sendMailResult.get("communicationEventId")); if (UtilValidate.isNotEmpty(orderId)) { result.put("orderId", orderId); } if (UtilValidate.isNotEmpty(custRequestId)) { result.put("custRequestId", custRequestId); } return result; }
/** * Creates and updates a PartyRelationship creating related PartyRoles if needed. A side of the * relationship is checked to maintain history * * @param ctx The DispatchContext that this service is operating in * @param context Map containing the input parameters * @return Map with the result of the service, the output parameters */ public static Map<String, Object> createUpdatePartyRelationshipAndRoles( DispatchContext ctx, Map<String, ? extends Object> context) { Map<String, Object> result = FastMap.newInstance(); Delegator delegator = ctx.getDelegator(); LocalDispatcher dispatcher = ctx.getDispatcher(); try { List<GenericValue> partyRelationShipList = PartyRelationshipHelper.getActivePartyRelationships(delegator, context); if (UtilValidate.isEmpty( partyRelationShipList)) { // If already exists and active nothing to do: keep the current // one String partyId = (String) context.get("partyId"); String partyIdFrom = (String) context.get("partyIdFrom"); String partyIdTo = (String) context.get("partyIdTo"); String roleTypeIdFrom = (String) context.get("roleTypeIdFrom"); String roleTypeIdTo = (String) context.get("roleTypeIdTo"); String partyRelationshipTypeId = (String) context.get("partyRelationshipTypeId"); // Before creating the partyRelationShip, create the partyRoles if they don't exist GenericValue partyToRole = null; partyToRole = delegator.findOne( "PartyRole", UtilMisc.toMap("partyId", partyIdTo, "roleTypeId", roleTypeIdTo), false); if (partyToRole == null) { partyToRole = delegator.makeValue( "PartyRole", UtilMisc.toMap("partyId", partyIdTo, "roleTypeId", roleTypeIdTo)); partyToRole.create(); } GenericValue partyFromRole = null; partyFromRole = delegator.findOne( "PartyRole", UtilMisc.toMap("partyId", partyIdFrom, "roleTypeId", roleTypeIdFrom), false); if (partyFromRole == null) { partyFromRole = delegator.makeValue( "PartyRole", UtilMisc.toMap("partyId", partyIdFrom, "roleTypeId", roleTypeIdFrom)); partyFromRole.create(); } // Check if there is already a partyRelationship of that type with another party from the // side indicated String sideChecked = partyIdFrom.equals(partyId) ? "partyIdFrom" : "partyIdTo"; partyRelationShipList = delegator.findByAnd( "PartyRelationship", UtilMisc.toMap( sideChecked, partyId, "roleTypeIdFrom", roleTypeIdFrom, "roleTypeIdTo", roleTypeIdTo, "partyRelationshipTypeId", partyRelationshipTypeId)); // We consider the last one (in time) as sole active (we try to maintain a unique // relationship and keep changes history) partyRelationShipList = EntityUtil.filterByDate(partyRelationShipList); GenericValue oldPartyRelationShip = EntityUtil.getFirst(partyRelationShipList); if (UtilValidate.isNotEmpty(oldPartyRelationShip)) { oldPartyRelationShip.setFields( UtilMisc.toMap("thruDate", UtilDateTime.nowTimestamp())); // Current becomes inactive oldPartyRelationShip.store(); } try { dispatcher.runSync("createPartyRelationship", context); // Create new one } catch (GenericServiceException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( "Could not create party relationship (write failure): " + e.getMessage()); } } } catch (GenericEntityException e) { Debug.logWarning(e.getMessage(), module); return ServiceUtil.returnError( "Could not create party relationship (write failure): " + e.getMessage()); } result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); return result; }