Search in sources :

Example 11 with ModelService

use of org.apache.ofbiz.service.ModelService in project ofbiz-framework by apache.

the class PaymentGatewayServices method releaseOrderPaymentPreference.

/**
 * Releases authorization for a single OrderPaymentPreference through service calls to the defined processing service for the ProductStore/PaymentMethodType
 * @return SUCCESS|FAILED|ERROR for complete processing of payment.
 */
public static Map<String, Object> releaseOrderPaymentPreference(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
    Locale locale = (Locale) context.get("locale");
    Map<String, Object> result = ServiceUtil.returnSuccess();
    // Get the OrderPaymentPreference
    GenericValue paymentPref = null;
    try {
        paymentPref = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderPaymentPreferenceId", orderPaymentPreferenceId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logWarning(e, "Problem getting OrderPaymentPreference for orderPaymentPreferenceId " + orderPaymentPreferenceId, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
    }
    // Error if no OrderPaymentPreference was found
    if (paymentPref == null) {
        Debug.logWarning("Could not find OrderPaymentPreference with orderPaymentPreferenceId: " + orderPaymentPreferenceId, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + orderPaymentPreferenceId);
    }
    // Get the OrderHeader
    GenericValue orderHeader = null;
    String orderId = paymentPref.getString("orderId");
    try {
        orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logWarning(e, "Problem getting OrderHeader for orderId " + orderId, module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
    }
    // Error if no OrderHeader was found
    if (orderHeader == null) {
        Debug.logWarning("Could not find OrderHeader with orderId: " + orderId + "; not processing payments.", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "OrderOrderNotFound", UtilMisc.toMap("orderId", orderId), locale));
    }
    OrderReadHelper orh = new OrderReadHelper(orderHeader);
    String currency = orh.getCurrency();
    // look up the payment configuration settings
    String serviceName = null;
    String paymentConfig = null;
    String paymentGatewayConfigId = null;
    // get the payment settings i.e. serviceName and config properties file name
    GenericValue paymentSettings = getPaymentSettings(orderHeader, paymentPref, RELEASE_SERVICE_TYPE, false);
    if (paymentSettings != null) {
        String customMethodId = paymentSettings.getString("paymentCustomMethodId");
        if (UtilValidate.isNotEmpty(customMethodId)) {
            serviceName = getPaymentCustomMethod(orh.getOrderHeader().getDelegator(), customMethodId);
        }
        if (UtilValidate.isEmpty(serviceName)) {
            serviceName = paymentSettings.getString("paymentService");
        }
        paymentConfig = paymentSettings.getString("paymentPropertiesPath");
        paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
        if (serviceName == null) {
            Debug.logWarning("No payment release service for - " + paymentPref.getString("paymentMethodTypeId"), module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "AccountingTroubleCallingReleaseOrderPaymentPreferenceService", locale) + " " + paymentPref.getString("paymentMethodTypeId"));
        }
    } else {
        Debug.logWarning("No payment release settings found for - " + paymentPref.getString("paymentMethodTypeId"), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "AccountingTroubleCallingReleaseOrderPaymentPreferenceService", locale) + " " + paymentPref.getString("paymentMethodTypeId"));
    }
    if (UtilValidate.isEmpty(paymentConfig)) {
        paymentConfig = "payment.properties";
    }
    GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(paymentPref);
    Map<String, Object> releaseContext = new HashMap<>();
    releaseContext.put("orderPaymentPreference", paymentPref);
    releaseContext.put("releaseAmount", authTransaction.getBigDecimal("amount"));
    releaseContext.put("currency", currency);
    releaseContext.put("paymentConfig", paymentConfig);
    releaseContext.put("paymentGatewayConfigId", paymentGatewayConfigId);
    releaseContext.put("userLogin", userLogin);
    // run the defined service
    Map<String, Object> releaseResult = null;
    try {
        releaseResult = dispatcher.runSync(serviceName, releaseContext, TX_TIME, true);
    } catch (GenericServiceException e) {
        Debug.logError(e, "Problem releasing payment", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "AccountingTroubleCallingReleaseOrderPaymentPreferenceService", locale));
    }
    // get the release result code
    if (releaseResult != null && ServiceUtil.isSuccess(releaseResult)) {
        Map<String, Object> releaseResRes;
        try {
            ModelService model = dctx.getModelService("processReleaseResult");
            releaseResult.put("orderPaymentPreference", paymentPref);
            releaseResult.put("userLogin", userLogin);
            Map<String, Object> resCtx = model.makeValid(releaseResult, ModelService.IN_PARAM);
            releaseResRes = dispatcher.runSync(model.name, resCtx);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Trouble processing the release results", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceOrder, "AccountingTroubleCallingReleaseOrderPaymentPreferenceService", locale) + " " + e.getMessage());
        }
        if (releaseResRes != null && ServiceUtil.isError(releaseResRes)) {
            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(releaseResRes));
        }
    } else if (ServiceUtil.isError(releaseResult)) {
        saveError(dispatcher, userLogin, paymentPref, releaseResult, RELEASE_SERVICE_TYPE, "PGT_RELEASE");
        result = ServiceUtil.returnError(ServiceUtil.getErrorMessage(releaseResult));
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) ModelService(org.apache.ofbiz.service.ModelService)

Example 12 with ModelService

use of org.apache.ofbiz.service.ModelService in project ofbiz-framework by apache.

the class PaymentGatewayServices method processAuthResult.

private static void processAuthResult(DispatchContext dctx, Map<String, Object> result, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    result.put("userLogin", userLogin);
    result.put("orderPaymentPreference", paymentPreference);
    ModelService model = dctx.getModelService("processAuthResult");
    Map<String, Object> context = model.makeValid(result, ModelService.IN_PARAM);
    // in case we rollback make sure this service gets called
    dispatcher.addRollbackService(model.name, context, true);
    // invoke the service
    Map<String, Object> resResp;
    try {
        resResp = dispatcher.runSync(model.name, context);
    } catch (GenericServiceException e) {
        Debug.logError(e, module);
        throw e;
    }
    if (ServiceUtil.isError(resResp)) {
        throw new GeneralException(ServiceUtil.getErrorMessage(resResp));
    }
}
Also used : LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelService(org.apache.ofbiz.service.ModelService)

Example 13 with ModelService

use of org.apache.ofbiz.service.ModelService in project ofbiz-framework by apache.

the class PaymentGatewayServices method refundPayment.

public static Map<String, Object> refundPayment(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    BigDecimal refundAmount = (BigDecimal) context.get("refundAmount");
    Locale locale = (Locale) context.get("locale");
    GenericValue orderHeader = null;
    try {
        orderHeader = paymentPref.getRelatedOne("OrderHeader", false);
    } catch (GenericEntityException e) {
        Debug.logError(e, "Cannot get OrderHeader from OrderPaymentPreference", module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingProblemGettingOrderPaymentPreferences", locale) + " " + e.toString());
    }
    OrderReadHelper orh = new OrderReadHelper(orderHeader);
    GenericValue paymentSettings = null;
    if (orderHeader != null) {
        paymentSettings = getPaymentSettings(orderHeader, paymentPref, REFUND_SERVICE_TYPE, false);
    }
    String serviceName = null;
    String paymentGatewayConfigId = null;
    if (paymentSettings != null) {
        String customMethodId = paymentSettings.getString("paymentCustomMethodId");
        if (UtilValidate.isNotEmpty(customMethodId)) {
            serviceName = getPaymentCustomMethod(orh.getOrderHeader().getDelegator(), customMethodId);
        }
        if (UtilValidate.isEmpty(serviceName)) {
            serviceName = paymentSettings.getString("paymentService");
        }
        String paymentConfig = paymentSettings.getString("paymentPropertiesPath");
        paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
        if (serviceName != null) {
            Map<String, Object> serviceContext = new HashMap<>();
            serviceContext.put("orderPaymentPreference", paymentPref);
            serviceContext.put("paymentConfig", paymentConfig);
            serviceContext.put("paymentGatewayConfigId", paymentGatewayConfigId);
            serviceContext.put("currency", orh.getCurrency());
            // get the creditCard/address/email
            String payToPartyId = null;
            try {
                payToPartyId = getBillingInformation(orh, paymentPref, new HashMap<String, Object>());
            } catch (GenericEntityException e) {
                Debug.logError(e, "Problems getting billing information", module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingBillingAccountNotFound", UtilMisc.toMap("billingAccountId", ""), locale));
            }
            BigDecimal processAmount = refundAmount.setScale(decimals, rounding);
            serviceContext.put("refundAmount", processAmount);
            serviceContext.put("userLogin", userLogin);
            // call the service
            Map<String, Object> refundResponse = null;
            try {
                refundResponse = dispatcher.runSync(serviceName, serviceContext, TX_TIME, true);
            } catch (GenericServiceException e) {
                Debug.logError(e, "Problem refunding payment through processor", module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentRefundError", locale));
            }
            if (ServiceUtil.isError(refundResponse)) {
                saveError(dispatcher, userLogin, paymentPref, refundResponse, REFUND_SERVICE_TYPE, "PGT_REFUND");
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(refundResponse));
            }
            // get the pay to party ID for the order (will be the payFrom)
            String payFromPartyId = getPayToPartyId(orderHeader);
            // process the refund result
            Map<String, Object> refundResRes;
            try {
                ModelService model = dctx.getModelService("processRefundResult");
                Map<String, Object> refundResCtx = model.makeValid(context, ModelService.IN_PARAM);
                refundResCtx.put("currencyUomId", orh.getCurrency());
                refundResCtx.put("payToPartyId", payToPartyId);
                refundResCtx.put("payFromPartyId", payFromPartyId);
                refundResCtx.put("refundRefNum", refundResponse.get("refundRefNum"));
                refundResCtx.put("refundAltRefNum", refundResponse.get("refundAltRefNum"));
                refundResCtx.put("refundMessage", refundResponse.get("refundMessage"));
                refundResCtx.put("refundResult", refundResponse.get("refundResult"));
                // The refund amount could be different from what we tell the payment gateway due to issues
                // such as having to void the entire original auth amount and re-authorize the new order total.
                BigDecimal actualRefundAmount = (BigDecimal) refundResponse.get("refundAmount");
                if (actualRefundAmount != null && actualRefundAmount.compareTo(processAmount) != 0) {
                    refundResCtx.put("refundAmount", refundResponse.get("refundAmount"));
                }
                refundResRes = dispatcher.runSync(model.name, refundResCtx);
                if (ServiceUtil.isError(refundResRes)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(refundResRes));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentRefundError", locale) + " " + e.getMessage());
            }
            return refundResRes;
        } else {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "AccountingPaymentRefundServiceNotDefined", locale));
        }
    } else {
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "AccountingPaymentSettingNotFound", UtilMisc.toMap("productStoreId", orderHeader.getString("productStoreId"), "transactionType", REFUND_SERVICE_TYPE), locale));
    }
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) BigDecimal(java.math.BigDecimal) OrderReadHelper(org.apache.ofbiz.order.order.OrderReadHelper) ModelService(org.apache.ofbiz.service.ModelService)

Example 14 with ModelService

use of org.apache.ofbiz.service.ModelService in project ofbiz-framework by apache.

the class ContentManagementServices method persistContentAndAssoc.

/**
 * persistContentAndAssoc
 * A combination method that will create or update all or one of the following:
 * a Content entity, a ContentAssoc related to the Content, and
 * the ElectronicText that may be associated with the Content.
 * The keys for determining if each entity is created is the presence
 * of the contentTypeId, contentAssocTypeId and dataResourceTypeId.
 * This service tries to handle DataResource fields with and
 * without "dr" prefixes.
 * Assumes binary data is always in field, "imageData".
 *
 * This service does not accept straight ContentAssoc parameters. They must be prefaced with "ca" + cap first letter
 */
public static Map<String, Object> persistContentAndAssoc(DispatchContext dctx, Map<String, ? extends Object> rcontext) throws GenericServiceException {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
    Locale locale = (Locale) context.get("locale");
    // Knowing why a request fails permission check is one of the more difficult
    // aspects of content management. Setting "displayFailCond" to true will
    // put an html table in result.errorMessage that will show what tests were performed
    Boolean bDisplayFailCond = (Boolean) context.get("displayFailCond");
    String mapKey = (String) context.get("mapKey");
    // If "deactivateExisting" is set, other Contents that are tied to the same
    // contentIdTo will be deactivated (thruDate set to now)
    String deactivateString = (String) context.get("deactivateExisting");
    boolean deactivateExisting = "true".equalsIgnoreCase(deactivateString);
    if (Debug.infoOn())
        Debug.logInfo("in persist... mapKey(0):" + mapKey, module);
    // ContentPurposes can get passed in as a delimited string or a list. Combine.
    List<String> contentPurposeList = UtilGenerics.checkList(context.get("contentPurposeList"));
    if (contentPurposeList == null) {
        contentPurposeList = new LinkedList<String>();
    }
    String contentPurposeString = (String) context.get("contentPurposeString");
    if (UtilValidate.isNotEmpty(contentPurposeString)) {
        List<String> tmpPurposes = StringUtil.split(contentPurposeString, "|");
        contentPurposeList.addAll(tmpPurposes);
    }
    if (contentPurposeList != null) {
        context.put("contentPurposeList", contentPurposeList);
        context.put("contentPurposeString", null);
    }
    if (Debug.infoOn()) {
        Debug.logInfo("in persist... contentPurposeList(0):" + contentPurposeList, module);
        Debug.logInfo("in persist... textData(0):" + context.get("textData"), module);
    }
    GenericValue content = delegator.makeValue("Content");
    content.setPKFields(context);
    content.setNonPKFields(context);
    String contentId = (String) content.get("contentId");
    String contentTypeId = (String) content.get("contentTypeId");
    String origContentId = (String) content.get("contentId");
    String origDataResourceId = (String) content.get("dataResourceId");
    if (Debug.infoOn()) {
        Debug.logInfo("in persist... contentId(0):" + contentId, module);
    }
    GenericValue dataResource = delegator.makeValue("DataResource");
    dataResource.setPKFields(context);
    dataResource.setNonPKFields(context);
    dataResource.setAllFields(context, false, "dr", null);
    String isPublic = (String) context.get("isPublic");
    if (UtilValidate.isEmpty(isPublic)) {
        dataResource.set("isPublic", "N");
    }
    context.putAll(dataResource);
    String dataResourceId = (String) dataResource.get("dataResourceId");
    String dataResourceTypeId = (String) dataResource.get("dataResourceTypeId");
    if (Debug.infoOn()) {
        Debug.logInfo("in persist... dataResourceId(0):" + dataResourceId, module);
    }
    GenericValue contentAssoc = delegator.makeValue("ContentAssoc");
    String contentAssocTypeId = (String) context.get("contentAssocTypeId");
    if (UtilValidate.isNotEmpty(contentAssocTypeId)) {
        context.put("caContentAssocTypeId", contentAssocTypeId);
    }
    contentAssocTypeId = (String) context.get("caContentAssocTypeId");
    contentAssoc.setAllFields(context, false, "ca", null);
    contentAssoc.put("contentId", context.get("caContentId"));
    context.putAll(contentAssoc);
    GenericValue electronicText = delegator.makeValue("ElectronicText");
    electronicText.setPKFields(context);
    electronicText.setNonPKFields(context);
    // save expected primary keys on result now in case there is no operation that uses them
    Map<String, Object> results = ServiceUtil.returnSuccess();
    results.put("contentId", content.get("contentId"));
    results.put("dataResourceId", dataResource.get("dataResourceId"));
    results.put("drDataResourceId", dataResource.get("dataResourceId"));
    results.put("drDataResourceId", dataResource.get("dataResourceId"));
    results.put("caContentIdTo", contentAssoc.get("contentIdTo"));
    results.put("caContentId", contentAssoc.get("contentId"));
    results.put("caFromDate", contentAssoc.get("fromDate"));
    results.put("caContentAssocTypeId", contentAssoc.get("contentAssocTypeId"));
    // get user info for multiple use
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    boolean dataResourceExists = true;
    if (Debug.infoOn()) {
        Debug.logInfo("in persist... dataResourceTypeId(0):" + dataResourceTypeId, module);
    }
    if (UtilValidate.isNotEmpty(dataResourceTypeId)) {
        Map<String, Object> dataResourceResult;
        try {
            dataResourceResult = persistDataResourceAndDataMethod(dctx, context);
        } catch (GenericServiceException e) {
            Debug.logError(e, e.toString(), module);
            return ServiceUtil.returnError(e.toString());
        } catch (GenericEntityException e) {
            Debug.logError(e, e.toString(), module);
            return ServiceUtil.returnError(e.toString());
        } catch (Exception e) {
            Debug.logError(e, e.toString(), module);
            return ServiceUtil.returnError(e.toString());
        }
        String errorMsg = ServiceUtil.getErrorMessage(dataResourceResult);
        if (UtilValidate.isNotEmpty(errorMsg)) {
            return ServiceUtil.returnError(errorMsg);
        }
        dataResourceId = (String) dataResourceResult.get("dataResourceId");
        results.put("dataResourceId", dataResourceId);
        results.put("drDataResourceId", dataResourceId);
        context.put("dataResourceId", dataResourceId);
        content.put("dataResourceId", dataResourceId);
        context.put("drDataResourceId", dataResourceId);
    }
    // Do update and create permission checks on Content if warranted.
    // Force check here
    context.put("skipPermissionCheck", null);
    boolean contentExists = true;
    if (Debug.infoOn()) {
        Debug.logInfo("in persist... contentTypeId:" + contentTypeId + " dataResourceTypeId:" + dataResourceTypeId + " contentId:" + contentId + " dataResourceId:" + dataResourceId, module);
    }
    if (UtilValidate.isNotEmpty(contentTypeId)) {
        if (UtilValidate.isEmpty(contentId)) {
            contentExists = false;
        } else {
            try {
                GenericValue val = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
                if (val == null)
                    contentExists = false;
            } catch (GenericEntityException e) {
                return ServiceUtil.returnError(e.toString());
            }
        }
        context.putAll(content);
        if (contentExists) {
            Map<String, Object> contentContext = new HashMap<String, Object>();
            ModelService contentModel = dispatcher.getDispatchContext().getModelService("updateContent");
            contentContext.putAll(contentModel.makeValid(content, ModelService.IN_PARAM));
            contentContext.put("userLogin", userLogin);
            contentContext.put("displayFailCond", bDisplayFailCond);
            contentContext.put("skipPermissionCheck", context.get("skipPermissionCheck"));
            Debug.logInfo("In persistContentAndAssoc calling updateContent with content: " + contentContext, module);
            Map<String, Object> thisResult = dispatcher.runSync("updateContent", contentContext);
            if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentContentUpdatingError", UtilMisc.toMap("serviceName", "persistContentAndAssoc"), locale), null, null, thisResult);
            }
        } else {
            Map<String, Object> contentContext = new HashMap<String, Object>();
            ModelService contentModel = dispatcher.getDispatchContext().getModelService("createContent");
            contentContext.putAll(contentModel.makeValid(content, ModelService.IN_PARAM));
            contentContext.put("userLogin", userLogin);
            contentContext.put("displayFailCond", bDisplayFailCond);
            contentContext.put("skipPermissionCheck", context.get("skipPermissionCheck"));
            Debug.logInfo("In persistContentAndAssoc calling createContent with content: " + contentContext, module);
            Map<String, Object> thisResult = dispatcher.runSync("createContent", contentContext);
            if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentContentCreatingError", UtilMisc.toMap("serviceName", "persistContentAndAssoc"), locale), null, null, thisResult);
            }
            contentId = (String) thisResult.get("contentId");
        }
        results.put("contentId", contentId);
        context.put("contentId", contentId);
        context.put("caContentIdTo", contentId);
        // Add ContentPurposes if this is a create operation
        if (contentId != null && !contentExists) {
            try {
                Set<String> contentPurposeSet = UtilMisc.makeSetWritable(contentPurposeList);
                for (String contentPurposeTypeId : contentPurposeSet) {
                    GenericValue contentPurpose = delegator.makeValue("ContentPurpose", UtilMisc.toMap("contentId", contentId, "contentPurposeTypeId", contentPurposeTypeId));
                    contentPurpose.create();
                }
            } catch (GenericEntityException e) {
                return ServiceUtil.returnError(e.toString());
            }
        }
    } else if (UtilValidate.isNotEmpty(dataResourceTypeId) && UtilValidate.isNotEmpty(contentId)) {
        // If dataResource was not previously existing, then update the associated content with its id
        if (UtilValidate.isNotEmpty(dataResourceId) && !dataResourceExists) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("userLogin", userLogin);
            map.put("dataResourceId", dataResourceId);
            map.put("contentId", contentId);
            if (Debug.infoOn())
                Debug.logInfo("in persist... context:" + context, module);
            Map<String, Object> r = ContentServices.updateContentMethod(dctx, map);
            boolean isError = ModelService.RESPOND_ERROR.equals(r.get(ModelService.RESPONSE_MESSAGE));
            if (isError)
                return ServiceUtil.returnError((String) r.get(ModelService.ERROR_MESSAGE));
        }
    }
    // Put contentId
    if (UtilValidate.isNotEmpty(contentId)) {
        contentAssoc.put("contentIdTo", contentId);
    }
    // If parentContentIdTo or parentContentIdFrom exists, create association with newly created content
    if (Debug.infoOn()) {
        Debug.logInfo("CREATING contentASSOC contentAssocTypeId:" + contentAssocTypeId, module);
    }
    // create content assoc if the key values are present....
    if (Debug.infoOn())
        Debug.logInfo("contentAssoc: " + contentAssoc.toString(), module);
    if (UtilValidate.isNotEmpty(contentAssocTypeId) && contentAssoc.get("contentId") != null && contentAssoc.get("contentIdTo") != null) {
        if (Debug.infoOn())
            Debug.logInfo("in persistContentAndAssoc, deactivateExisting:" + deactivateExisting, module);
        Map<String, Object> contentAssocContext = new HashMap<String, Object>();
        contentAssocContext.put("userLogin", userLogin);
        contentAssocContext.put("displayFailCond", bDisplayFailCond);
        contentAssocContext.put("skipPermissionCheck", context.get("skipPermissionCheck"));
        Map<String, Object> thisResult = null;
        try {
            GenericValue contentAssocExisting = EntityQuery.use(delegator).from("ContentAssoc").where(contentAssoc.getPrimaryKey()).queryOne();
            if (contentAssocExisting == null) {
                ModelService contentAssocModel = dispatcher.getDispatchContext().getModelService("createContentAssoc");
                Map<String, Object> ctx = contentAssocModel.makeValid(contentAssoc, ModelService.IN_PARAM);
                contentAssocContext.putAll(ctx);
                thisResult = dispatcher.runSync("createContentAssoc", contentAssocContext);
                if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
                results.put("caContentIdTo", thisResult.get("contentIdTo"));
                results.put("caContentId", thisResult.get("contentIdFrom"));
                results.put("caContentAssocTypeId", thisResult.get("contentAssocTypeId"));
                results.put("caFromDate", thisResult.get("fromDate"));
                results.put("caSequenceNum", thisResult.get("sequenceNum"));
            } else {
                if (deactivateExisting) {
                    contentAssocExisting.put("thruDate", UtilDateTime.nowTimestamp());
                } else if (UtilValidate.isNotEmpty(context.get("thruDate"))) {
                    contentAssocExisting.put("thruDate", (Timestamp) context.get("thruDate"));
                }
                ModelService contentAssocModel = dispatcher.getDispatchContext().getModelService("updateContentAssoc");
                Map<String, Object> ctx = contentAssocModel.makeValid(contentAssocExisting, ModelService.IN_PARAM);
                contentAssocContext.putAll(ctx);
                thisResult = dispatcher.runSync("updateContentAssoc", contentAssocContext);
                if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            }
        } catch (GenericEntityException e) {
            throw new GenericServiceException(e.toString());
        } catch (Exception e2) {
            throw new GenericServiceException(e2.toString());
        }
        String errMsg = ServiceUtil.getErrorMessage(thisResult);
        if (UtilValidate.isNotEmpty(errMsg)) {
            return ServiceUtil.returnError(errMsg);
        }
    }
    context.remove("skipPermissionCheck");
    context.put("contentId", origContentId);
    context.put("dataResourceId", origDataResourceId);
    context.remove("dataResource");
    Debug.logInfo("results:" + results, module);
    return results;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) Timestamp(java.sql.Timestamp) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ServiceAuthException(org.apache.ofbiz.service.ServiceAuthException) ModelService(org.apache.ofbiz.service.ModelService) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 15 with ModelService

use of org.apache.ofbiz.service.ModelService in project ofbiz-framework by apache.

the class ContentManagementServices method changeLeafToNode.

public static Map<String, Object> changeLeafToNode(DispatchContext dctx, Map<String, ? extends Object> context) throws GenericServiceException {
    Map<String, Object> result = new HashMap<String, Object>();
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Map<String, Object> thisResult = new HashMap<String, Object>();
    String contentId = (String) context.get("contentId");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String userLoginId = userLogin.getString("userLoginId");
    Locale locale = (Locale) context.get("locale");
    try {
        GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
        if (content == null) {
            Debug.logError("content was null", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentNoContentFound", UtilMisc.toMap("contentId", ""), locale));
        }
        String dataResourceId = content.getString("dataResourceId");
        content.set("dataResourceId", null);
        content.set("lastModifiedDate", UtilDateTime.nowTimestamp());
        content.set("lastModifiedByUserLogin", userLoginId);
        content.store();
        if (UtilValidate.isNotEmpty(dataResourceId)) {
            // add previous DataResource as part of new subcontent
            GenericValue contentClone = (GenericValue) content.clone();
            contentClone.set("dataResourceId", dataResourceId);
            content.set("lastModifiedDate", UtilDateTime.nowTimestamp());
            content.set("lastModifiedByUserLogin", userLoginId);
            content.set("createdDate", UtilDateTime.nowTimestamp());
            content.set("createdByUserLogin", userLoginId);
            contentClone.set("contentId", null);
            ModelService modelService = dctx.getModelService("persistContentAndAssoc");
            Map<String, Object> serviceIn = modelService.makeValid(contentClone, ModelService.IN_PARAM);
            serviceIn.put("userLogin", userLogin);
            serviceIn.put("contentIdTo", contentId);
            serviceIn.put("contentAssocTypeId", "SUB_CONTENT");
            serviceIn.put("sequenceNum", Long.valueOf(50));
            try {
                thisResult = dispatcher.runSync("persistContentAndAssoc", serviceIn);
                if (ServiceUtil.isError(thisResult)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(thisResult));
                }
            } catch (ServiceAuthException e) {
                return ServiceUtil.returnError(e.toString());
            }
            List<String> typeList = UtilMisc.toList("SUB_CONTENT");
            ContentManagementWorker.updateStatsTopDown(delegator, contentId, typeList);
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.toString());
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) ServiceAuthException(org.apache.ofbiz.service.ServiceAuthException) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelService(org.apache.ofbiz.service.ModelService)

Aggregations

ModelService (org.apache.ofbiz.service.ModelService)38 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)33 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)28 HashMap (java.util.HashMap)24 GenericValue (org.apache.ofbiz.entity.GenericValue)22 Locale (java.util.Locale)20 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)19 Delegator (org.apache.ofbiz.entity.Delegator)17 ModelParam (org.apache.ofbiz.service.ModelParam)6 ServiceAuthException (org.apache.ofbiz.service.ServiceAuthException)6 LinkedList (java.util.LinkedList)5 Map (java.util.Map)5 GeneralException (org.apache.ofbiz.base.util.GeneralException)5 DispatchContext (org.apache.ofbiz.service.DispatchContext)5 IOException (java.io.IOException)4 BigDecimal (java.math.BigDecimal)4 Timestamp (java.sql.Timestamp)4 ByteBuffer (java.nio.ByteBuffer)3 TimeZone (java.util.TimeZone)3 HttpSession (javax.servlet.http.HttpSession)3