Search in sources :

Example 31 with GenericServiceException

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

the class ReplaceImage method replaceImageToExistImage.

public static Map<String, Object> replaceImageToExistImage(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.management.path", delegator), context);
    String productId = (String) context.get("productId");
    String contentIdExist = (String) context.get("contentIdExist");
    String contentIdReplace = (String) context.get("contentIdReplace");
    String dataResourceNameExist = (String) context.get("dataResourceNameExist");
    String dataResourceNameReplace = (String) context.get("dataResourceNameReplace");
    if (UtilValidate.isNotEmpty(dataResourceNameExist)) {
        if (UtilValidate.isNotEmpty(contentIdReplace)) {
            if (contentIdExist.equals(contentIdReplace)) {
                String errMsg = UtilProperties.getMessage(resourceError, "ProductCannotReplaceBecauseBothImagesAreTheSameImage", locale);
                Debug.logError(errMsg, module);
                return ServiceUtil.returnError(errMsg);
            }
        } else {
            String errMsg = UtilProperties.getMessage(resourceError, "ProductPleaseChooseImageToReplace", locale);
            Debug.logError(errMsg, module);
            return ServiceUtil.returnError(errMsg);
        }
    } else {
        String errMsg = UtilProperties.getMessage(resourceError, "ProductPleaseChooseReplacementImage", locale);
        Debug.logError(errMsg, module);
        return ServiceUtil.returnError(errMsg);
    }
    try {
        BufferedImage bufImg = ImageIO.read(new File(imageServerPath + "/" + productId + "/" + dataResourceNameReplace));
        ImageIO.write(bufImg, "jpg", new File(imageServerPath + "/" + productId + "/" + dataResourceNameExist));
        List<GenericValue> contentAssocReplaceList = EntityQuery.use(delegator).from("ContentAssoc").where("contentId", contentIdReplace, "contentAssocTypeId", "IMAGE_THUMBNAIL").queryList();
        if (contentAssocReplaceList.size() > 0) {
            for (int i = 0; i < contentAssocReplaceList.size(); i++) {
                GenericValue contentAssocReplace = contentAssocReplaceList.get(i);
                GenericValue dataResourceAssocReplace = EntityQuery.use(delegator).from("ContentDataResourceView").where("contentId", contentAssocReplace.get("contentIdTo")).queryFirst();
                GenericValue contentAssocExist = EntityQuery.use(delegator).from("ContentAssoc").where("contentId", contentIdExist, "contentAssocTypeId", "IMAGE_THUMBNAIL", "mapKey", contentAssocReplace.get("mapKey")).queryFirst();
                GenericValue dataResourceAssocExist = EntityQuery.use(delegator).from("ContentDataResourceView").where("contentId", contentAssocExist.get("contentIdTo")).queryFirst();
                if (UtilValidate.isNotEmpty(dataResourceAssocExist)) {
                    BufferedImage bufImgAssocReplace = ImageIO.read(new File(imageServerPath + "/" + productId + "/" + dataResourceAssocReplace.get("drDataResourceName")));
                    ImageIO.write(bufImgAssocReplace, "jpg", new File(imageServerPath + "/" + productId + "/" + dataResourceAssocExist.get("drDataResourceName")));
                } else {
                    BufferedImage bufImgAssocReplace = ImageIO.read(new File(imageServerPath + "/" + productId + "/" + dataResourceAssocReplace.get("drDataResourceName")));
                    ImageIO.write(bufImgAssocReplace, "jpg", new File(imageServerPath + "/" + productId + "/" + dataResourceNameExist.substring(0, dataResourceNameExist.length() - 4) + "-" + contentAssocReplace.get("mapKey") + ".jpg"));
                }
            }
        }
        GenericValue productContent = EntityQuery.use(delegator).from("ProductContent").where("productId", productId, "contentId", contentIdReplace, "productContentTypeId", "IMAGE").queryFirst();
        if (productContent != null) {
            Map<String, Object> productContentCtx = new HashMap<>();
            productContentCtx.put("productId", productId);
            productContentCtx.put("contentId", contentIdReplace);
            productContentCtx.put("productContentTypeId", "IMAGE");
            productContentCtx.put("fromDate", productContent.get("fromDate"));
            productContentCtx.put("userLogin", userLogin);
            Map<String, Object> serviceResult = dispatcher.runSync("removeProductContentAndImageFile", productContentCtx);
            if (ServiceUtil.isError(serviceResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
            }
        }
    } catch (IOException | IllegalArgumentException | GenericEntityException | GenericServiceException e) {
        String errMsg = UtilProperties.getMessage(resourceError, "ProductCannotReplaceImage", locale);
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg);
    }
    String successMsg = UtilProperties.getMessage(resource, "ProductReplaceImageSuccessfully", locale);
    return ServiceUtil.returnSuccess(successMsg);
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) File(java.io.File)

Example 32 with GenericServiceException

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

the class ICalWorker method logInUser.

private static void logInUser(HttpServletRequest request, HttpServletResponse response) throws GenericServiceException, GenericEntityException {
    Map<String, Object> serviceMap = WebDavUtil.getCredentialsFromRequest(request);
    if (serviceMap == null) {
        return;
    }
    serviceMap.put("locale", UtilHttp.getLocale(request));
    GenericValue userLogin = null;
    HttpSession session = request.getSession();
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    Map<String, Object> result = dispatcher.runSync("userLogin", serviceMap);
    if (ServiceUtil.isError(result) || ServiceUtil.isFailure(result)) {
        String errorMessage = ServiceUtil.getErrorMessage(result);
        request.setAttribute("_ERROR_MESSAGE_", errorMessage);
        Debug.logError(errorMessage, module);
        throw new GenericServiceException(errorMessage);
    }
    userLogin = (GenericValue) result.get("userLogin");
    request.setAttribute("userLogin", userLogin);
    session.setAttribute("userLogin", userLogin);
    VisitHandler.getVisitor(request, response);
    GenericValue person = userLogin.getRelatedOne("Person", false);
    if (person != null) {
        request.setAttribute("person", person);
    } else {
        GenericValue partyGroup = userLogin.getRelatedOne("PartyGroup", false);
        if (partyGroup != null) {
            request.setAttribute("partyGroup", partyGroup);
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HttpSession(javax.servlet.http.HttpSession) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 33 with GenericServiceException

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

the class WorkEffortServices method processWorkEffortEventReminders.

/**
 * Process work effort event reminders. This service is used by the job scheduler.
 * @param ctx the dispatch context
 * @param context the context
 * @return returns the result of the service execution
 */
public static Map<String, Object> processWorkEffortEventReminders(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    Locale localePar = (Locale) context.get("locale");
    Timestamp now = new Timestamp(System.currentTimeMillis());
    List<GenericValue> eventReminders = null;
    try {
        eventReminders = EntityQuery.use(delegator).from("WorkEffortEventReminder").where(EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("reminderDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("reminderDateTime", EntityOperator.LESS_THAN_EQUAL_TO, now)), EntityOperator.OR)).queryList();
    } catch (GenericEntityException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "WorkEffortEventRemindersRetrivingError", UtilMisc.toMap("errorString", e), localePar));
    }
    for (GenericValue reminder : eventReminders) {
        if (UtilValidate.isEmpty(reminder.get("contactMechId"))) {
            continue;
        }
        int repeatCount = reminder.get("repeatCount") == null ? 0 : reminder.getLong("repeatCount").intValue();
        int currentCount = reminder.get("currentCount") == null ? 0 : reminder.getLong("currentCount").intValue();
        GenericValue workEffort = null;
        try {
            workEffort = reminder.getRelatedOne("WorkEffort", false);
        } catch (GenericEntityException e) {
            Debug.logWarning("Error while getting work effort: " + e, module);
        }
        if (workEffort == null) {
            try {
                reminder.remove();
            } catch (GenericEntityException e) {
                Debug.logWarning("Error while removing work effort event reminder: " + e, module);
            }
            continue;
        }
        Locale locale = reminder.getString("localeId") == null ? Locale.getDefault() : new Locale(reminder.getString("localeId"));
        TimeZone timeZone = reminder.getString("timeZoneId") == null ? TimeZone.getDefault() : TimeZone.getTimeZone(reminder.getString("timeZoneId"));
        Map<String, Object> parameters = UtilMisc.toMap("locale", locale, "timeZone", timeZone, "workEffortId", reminder.get("workEffortId"));
        Map<String, Object> processCtx = UtilMisc.toMap("reminder", reminder, "bodyParameters", parameters, "userLogin", context.get("userLogin"));
        Calendar cal = UtilDateTime.toCalendar(now, timeZone, locale);
        Timestamp reminderStamp = reminder.getTimestamp("reminderDateTime");
        Date eventDateTime = workEffort.getTimestamp("estimatedStartDate");
        String tempExprId = workEffort.getString("tempExprId");
        if (UtilValidate.isNotEmpty(tempExprId)) {
            TemporalExpression temporalExpression = null;
            try {
                temporalExpression = TemporalExpressionWorker.getTemporalExpression(delegator, tempExprId);
            } catch (GenericEntityException e) {
                Debug.logWarning("Error while getting temporal expression, id = " + tempExprId + ": " + e, module);
            }
            if (temporalExpression != null) {
                eventDateTime = temporalExpression.first(cal).getTime();
                Date reminderDateTime = null;
                long reminderOffset = reminder.get("reminderOffset") == null ? 0 : reminder.getLong("reminderOffset").longValue();
                if (reminderStamp == null) {
                    if (reminderOffset != 0) {
                        cal.setTime(eventDateTime);
                        TimeDuration duration = TimeDuration.fromLong(reminderOffset);
                        duration.addToCalendar(cal);
                        reminderDateTime = cal.getTime();
                    } else {
                        reminderDateTime = eventDateTime;
                    }
                } else {
                    reminderDateTime = new Date(reminderStamp.getTime());
                }
                if (reminderDateTime.before(now) && reminderStamp != null) {
                    try {
                        parameters.put("eventDateTime", new Timestamp(eventDateTime.getTime()));
                        Map<String, Object> result = dispatcher.runSync("processWorkEffortEventReminder", processCtx);
                        if (ServiceUtil.isError(result)) {
                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                        }
                        if (repeatCount != 0 && currentCount + 1 >= repeatCount) {
                            reminder.remove();
                        } else {
                            cal.setTime(reminderDateTime);
                            Date newReminderDateTime = null;
                            if (reminderOffset != 0) {
                                TimeDuration duration = TimeDuration.fromLong(-reminderOffset);
                                duration.addToCalendar(cal);
                                cal.setTime(temporalExpression.next(cal).getTime());
                                duration = TimeDuration.fromLong(reminderOffset);
                                duration.addToCalendar(cal);
                                newReminderDateTime = cal.getTime();
                            } else {
                                newReminderDateTime = temporalExpression.next(cal).getTime();
                            }
                            reminder.set("currentCount", Long.valueOf(currentCount + 1));
                            reminder.set("reminderDateTime", new Timestamp(newReminderDateTime.getTime()));
                            reminder.store();
                        }
                    } catch (GenericEntityException e) {
                        Debug.logWarning("Error while processing temporal expression reminder, id = " + tempExprId + ": " + e, module);
                    } catch (GenericServiceException e) {
                        Debug.logError(e, module);
                    }
                } else if (reminderStamp == null) {
                    try {
                        reminder.set("reminderDateTime", new Timestamp(reminderDateTime.getTime()));
                        reminder.store();
                    } catch (GenericEntityException e) {
                        Debug.logWarning("Error while processing temporal expression reminder, id = " + tempExprId + ": " + e, module);
                    }
                }
            }
            continue;
        }
        if (reminderStamp != null) {
            Date reminderDateTime = new Date(reminderStamp.getTime());
            if (reminderDateTime.before(now)) {
                try {
                    parameters.put("eventDateTime", eventDateTime);
                    Map<String, Object> result = dispatcher.runSync("processWorkEffortEventReminder", processCtx);
                    if (ServiceUtil.isError(result)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                    }
                    TimeDuration duration = TimeDuration.fromNumber(reminder.getLong("repeatInterval"));
                    if ((repeatCount != 0 && currentCount + 1 >= repeatCount) || duration.isZero()) {
                        reminder.remove();
                    } else {
                        cal.setTime(now);
                        duration.addToCalendar(cal);
                        reminderDateTime = cal.getTime();
                        reminder.set("currentCount", Long.valueOf(currentCount + 1));
                        reminder.set("reminderDateTime", new Timestamp(reminderDateTime.getTime()));
                        reminder.store();
                    }
                } catch (GenericEntityException e) {
                    Debug.logWarning("Error while processing event reminder: " + e, module);
                } catch (GenericServiceException e) {
                    Debug.logError(e, module);
                }
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) TemporalExpression(org.apache.ofbiz.service.calendar.TemporalExpression) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Calendar(com.ibm.icu.util.Calendar) Timestamp(java.sql.Timestamp) Date(java.util.Date) TimeZone(java.util.TimeZone) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) TimeDuration(org.apache.ofbiz.base.util.TimeDuration) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 34 with GenericServiceException

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

the class ModelForm method addAutoFieldsFromService.

private void addAutoFieldsFromService(AutoFieldsService autoFieldsService, ModelReader entityModelReader, DispatchContext dispatchContext, Set<String> useWhenFields, List<ModelFormFieldBuilder> fieldBuilderList, Map<String, ModelFormFieldBuilder> fieldBuilderMap) {
    // read service def and auto-create fields
    ModelService modelService = null;
    try {
        modelService = dispatchContext.getModelService(autoFieldsService.serviceName);
    } catch (GenericServiceException e) {
        String errmsg = "Error finding Service with name " + autoFieldsService.serviceName + " for auto-fields-service in a form widget";
        Debug.logError(e, errmsg, module);
        throw new IllegalArgumentException(errmsg);
    }
    for (ModelParam modelParam : modelService.getInModelParamList()) {
        if (modelParam.internal) {
            // skip auto params that the service engine populates...
            continue;
        }
        if (modelParam.formDisplay) {
            if (UtilValidate.isNotEmpty(modelParam.entityName) && UtilValidate.isNotEmpty(modelParam.fieldName)) {
                ModelEntity modelEntity;
                try {
                    modelEntity = entityModelReader.getModelEntity(modelParam.entityName);
                    ModelField modelField = modelEntity.getField(modelParam.fieldName);
                    if (modelField != null) {
                        // okay, populate using the entity field info...
                        ModelFormFieldBuilder builder = new ModelFormFieldBuilder();
                        builder.setModelForm(this);
                        builder.setName(modelField.getName());
                        builder.setEntityName(modelEntity.getEntityName());
                        builder.setFieldName(modelField.getName());
                        builder.induceFieldInfoFromEntityField(modelEntity, modelField, autoFieldsService.defaultFieldType);
                        if (UtilValidate.isNotEmpty(autoFieldsService.mapName)) {
                            builder.setMapName(autoFieldsService.mapName);
                        }
                        builder.setRequiredField(!modelParam.optional);
                        addUpdateField(builder, useWhenFields, fieldBuilderList, fieldBuilderMap);
                        // continue to skip creating based on service param
                        continue;
                    }
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
            }
            ModelFormFieldBuilder builder = new ModelFormFieldBuilder();
            builder.setModelForm(this);
            builder.setName(modelParam.name);
            builder.setServiceName(modelService.name);
            builder.setAttributeName(modelParam.name);
            builder.setTitle(modelParam.formLabel);
            builder.setRequiredField(!modelParam.optional);
            builder.induceFieldInfoFromServiceParam(modelService, modelParam, autoFieldsService.defaultFieldType);
            builder.setPosition(autoFieldsService.defaultPosition);
            if (UtilValidate.isNotEmpty(autoFieldsService.mapName)) {
                builder.setMapName(autoFieldsService.mapName);
            }
            addUpdateField(builder, useWhenFields, fieldBuilderList, fieldBuilderMap);
        }
    }
}
Also used : ModelField(org.apache.ofbiz.entity.model.ModelField) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ModelParam(org.apache.ofbiz.service.ModelParam) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) ModelService(org.apache.ofbiz.service.ModelService)

Example 35 with GenericServiceException

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

the class EmailServices method sendMailFromUrl.

/**
 * 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;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) MalformedURLException(java.net.MalformedURLException) HttpClientException(org.apache.ofbiz.base.util.HttpClientException) HttpClient(org.apache.ofbiz.base.util.HttpClient) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) URL(java.net.URL)

Aggregations

GenericServiceException (org.apache.ofbiz.service.GenericServiceException)417 GenericValue (org.apache.ofbiz.entity.GenericValue)339 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)303 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)251 Delegator (org.apache.ofbiz.entity.Delegator)250 Locale (java.util.Locale)246 HashMap (java.util.HashMap)221 BigDecimal (java.math.BigDecimal)139 LinkedList (java.util.LinkedList)79 GeneralException (org.apache.ofbiz.base.util.GeneralException)68 Timestamp (java.sql.Timestamp)66 Map (java.util.Map)54 IOException (java.io.IOException)43 HttpSession (javax.servlet.http.HttpSession)36 ModelService (org.apache.ofbiz.service.ModelService)33 OrderReadHelper (org.apache.ofbiz.order.order.OrderReadHelper)24 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)22 ArrayList (java.util.ArrayList)21 LinkedHashMap (java.util.LinkedHashMap)20 List (java.util.List)20