Search in sources :

Example 1 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class ProductEvents method updateAllKeywords.

/**
 * Updates/adds keywords for all products
 *
 * @param request HTTPRequest object for the current request
 * @param response HTTPResponse object for the current request
 * @return String specifying the exit status of this event
 */
public static String updateAllKeywords(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Security security = (Security) request.getAttribute("security");
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    String updateMode = "CREATE";
    String errMsg = null;
    String doAll = request.getParameter("doAll");
    // check permissions before moving on...
    if (!security.hasEntityPermission("CATALOG", "_" + updateMode, request.getSession())) {
        Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode);
        errMsg = UtilProperties.getMessage(resource, "productevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    EntityCondition condition = null;
    if (!"Y".equals(doAll)) {
        List<EntityCondition> condList = new LinkedList<>();
        condList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.NOT_EQUAL, "N")));
        if ("true".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.ignore.variants", delegator))) {
            condList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("isVariant", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("isVariant", EntityOperator.NOT_EQUAL, "Y")));
        }
        if ("true".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.ignore.discontinued.sales", delegator))) {
            condList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("salesDiscontinuationDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp)));
        }
        condition = EntityCondition.makeCondition(condList, EntityOperator.AND);
    } else {
        condition = EntityCondition.makeCondition(EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("autoCreateKeywords", EntityOperator.NOT_EQUAL, "N"));
    }
    int numProds = 0;
    int errProds = 0;
    boolean beganTx = false;
    try {
        // begin the transaction
        beganTx = TransactionUtil.begin(7200);
    } catch (GenericTransactionException gte) {
        Debug.logError(gte, "Unable to begin transaction", module);
    }
    try (EntityListIterator entityListIterator = EntityQuery.use(delegator).from("Product").where(condition).queryIterator()) {
        try {
            if (Debug.infoOn()) {
                long count = EntityQuery.use(delegator).from("Product").where(condition).queryCount();
                Debug.logInfo("========== Found " + count + " products to index ==========", module);
            }
        } catch (GenericEntityException gee) {
            Debug.logWarning(gee, gee.getMessage(), module);
            Map<String, String> messageMap = UtilMisc.toMap("gee", gee.toString());
            errMsg = UtilProperties.getMessage(resource, "productevents.error_getting_product_list", messageMap, UtilHttp.getLocale(request));
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            return "error";
        }
        GenericValue product;
        while ((product = entityListIterator.next()) != null) {
            try {
                KeywordIndex.indexKeywords(product, "Y".equals(doAll));
            } catch (GenericEntityException e) {
                Debug.logWarning("[ProductEvents.updateAllKeywords] Could not create product-keyword (write error); message: " + e.getMessage(), module);
                errProds++;
            }
            numProds++;
            if (numProds % 500 == 0) {
                Debug.logInfo("Keywords indexed for " + numProds + " so far", module);
            }
        }
    } catch (GenericEntityException e) {
        try {
            TransactionUtil.rollback(beganTx, e.getMessage(), e);
        } catch (GenericTransactionException e1) {
            Debug.logError(e1, module);
        }
        return "error";
    } catch (Throwable t) {
        Debug.logError(t, module);
        request.setAttribute("_ERROR_MESSAGE_", t.getMessage());
        try {
            TransactionUtil.rollback(beganTx, t.getMessage(), t);
        } catch (GenericTransactionException e2) {
            Debug.logError(e2, module);
        }
        return "error";
    }
    // commit the transaction
    try {
        TransactionUtil.commit(beganTx);
    } catch (GenericTransactionException e) {
        Debug.logError(e, module);
    }
    if (errProds == 0) {
        Map<String, String> messageMap = UtilMisc.toMap("numProds", Integer.toString(numProds));
        errMsg = UtilProperties.getMessage(resource, "productevents.keyword_creation_complete_for_products", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_EVENT_MESSAGE_", errMsg);
        return "success";
    } else {
        Map<String, String> messageMap = UtilMisc.toMap("numProds", Integer.toString(numProds));
        messageMap.put("errProds", Integer.toString(errProds));
        errMsg = UtilProperties.getMessage(resource, "productevents.keyword_creation_complete_for_products_with_errors", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Security(org.apache.ofbiz.security.Security) Timestamp(java.sql.Timestamp) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class WorkEffortServices method getWorkEffortEventsByPeriod.

/**
 * Get Work Efforts by period.
 * <p>
 * This method takes the following parameters:
 * </p>
 * <ul>
 *   <li>start - TimeStamp (Period start date/time)</li>
 *   <li>numPeriods - Integer</li>
 *   <li>periodType - Integer (see java.util.Calendar)</li>
 *   <li>eventStatus - String</li>
 *   <li>partyId - String</li>
 *   <li>partyIds - List</li>
 *   <li>facilityId - String</li>
 *   <li>fixedAssetId - String</li>
 *   <li>filterOutCanceledEvents - Boolean</li>
 *   <li>entityExprList - List</li>
 * </ul>
 * <p>
 * The method will find all matching Work Effort events and return them as a List called
 * <b>periods</b> - one List element per period. It also returns a
 * <b>maxConcurrentEntries</b> Integer - which indicates the maximum number of
 * Work Efforts found in one period.
 * </p>
 * <p>
 * Each <b>periods</b> list element is a Map containing the following
 * key/value pairs:
 * </p>
 * <ul>
 *   <li>start - TimeStamp (Period start date/time)</li>
 *   <li>end - TimeStamp (Period end date/time)</li>
 *   <li>calendarEntries - List of Maps. Each Map contains the following key/value pairs</li>
 *   <li><ul>
 *       <li>workEffort - GenericValue</li>
 *       <li>periodSpan - Integer (Number of periods this Work Effort spans)</li>
 *       <li>startOfPeriod - Boolean (true if this is the first occurrence in the period range)</li>
 *   </ul></li>
 * </ul>
 */
public static Map<String, Object> getWorkEffortEventsByPeriod(DispatchContext ctx, Map<String, ? extends Object> context) {
    /*
         To create testdata for  this function for  fixedasset/facility

        1) go to Manufacturing -> JobShop, then click on "create new Production run":
                https://localhost:8443/manufacturing/control/CreateProductionRun
        2) enter as productId "PROD_MANUF", quantity 1, start date tomorrow and press the submit button
    `    3) in the next screen, click on the "Confirm" link (top part of the sccreen)

        Now you have a confirmed production run (starting tomorrow) happening in facility "WebStoreWarehouse",
        with a task happening in fixed asset "WORKCENTER_COST"

        In the calendars screen, selecting the proper facility you should see the work effort associated to the production run;
        if you select the proper fixed asset you should see the task.

         */
    Delegator delegator = ctx.getDelegator();
    Security security = ctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    TimeZone timeZone = (TimeZone) context.get("timeZone");
    Timestamp startDay = (Timestamp) context.get("start");
    Integer numPeriodsInteger = (Integer) context.get("numPeriods");
    String calendarType = (String) context.get("calendarType");
    if (UtilValidate.isEmpty(calendarType)) {
        // This is a bad idea. This causes the service to return only those work efforts that are assigned
        // to the current user even when the service parameters have nothing to do with the current user.
        calendarType = "CAL_PERSONAL";
    }
    String partyId = (String) context.get("partyId");
    Collection<String> partyIds = UtilGenerics.checkCollection(context.get("partyIds"));
    String facilityId = (String) context.get("facilityId");
    String fixedAssetId = (String) context.get("fixedAssetId");
    String workEffortTypeId = (String) context.get("workEffortTypeId");
    Boolean filterOutCanceledEvents = (Boolean) context.get("filterOutCanceledEvents");
    if (filterOutCanceledEvents == null) {
        filterOutCanceledEvents = Boolean.FALSE;
    }
    // To be returned, the max concurrent entries for a single period
    int maxConcurrentEntries = 0;
    Integer periodTypeObject = (Integer) context.get("periodType");
    int periodType = 0;
    if (periodTypeObject != null) {
        periodType = periodTypeObject.intValue();
    }
    int numPeriods = 0;
    if (numPeriodsInteger != null) {
        numPeriods = numPeriodsInteger.intValue();
    }
    // get a timestamp (date) for the beginning of today and for beginning of numDays+1 days from now
    // Commenting this out because it interferes with periods that do not start at the beginning of the day
    Timestamp startStamp = startDay;
    Timestamp endStamp = UtilDateTime.adjustTimestamp(startStamp, periodType, 1, timeZone, locale);
    long periodLen = endStamp.getTime() - startStamp.getTime();
    endStamp = UtilDateTime.adjustTimestamp(startStamp, periodType, numPeriods, timeZone, locale);
    // Get the WorkEfforts
    List<GenericValue> validWorkEfforts = null;
    Collection<String> partyIdsToUse = partyIds;
    if (partyIdsToUse == null) {
        partyIdsToUse = new HashSet<>();
    }
    if (UtilValidate.isNotEmpty(partyId)) {
        if (partyId.equals(userLogin.getString("partyId")) || security.hasEntityPermission("WORKEFFORTMGR", "_VIEW", userLogin)) {
            partyIdsToUse.add(partyId);
        } else {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError, "WorkEffortPartyPermissionError", UtilMisc.toMap("partyId", partyId), locale));
        }
    } else {
        if ("CAL_PERSONAL".equals(calendarType) && UtilValidate.isNotEmpty(userLogin.getString("partyId"))) {
            partyIdsToUse.add(userLogin.getString("partyId"));
        }
    }
    // cancelled status id's
    List<EntityCondition> cancelledCheckAndList = UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "EVENT_CANCELLED"), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "CAL_CANCELLED"), EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "PRUN_CANCELLED"));
    List<EntityCondition> entityExprList = UtilGenerics.checkList(context.get("entityExprList"));
    if (entityExprList == null) {
        entityExprList = getDefaultWorkEffortExprList(calendarType, partyIdsToUse, workEffortTypeId, cancelledCheckAndList);
    }
    if (UtilValidate.isNotEmpty(facilityId)) {
        entityExprList.add(EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId));
    }
    if (UtilValidate.isNotEmpty(fixedAssetId)) {
        entityExprList.add(EntityCondition.makeCondition("fixedAssetId", EntityOperator.EQUALS, fixedAssetId));
    }
    // should have at least a start date
    EntityCondition startDateRequired = EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("estimatedStartDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("actualStartDate", EntityOperator.NOT_EQUAL, null)), EntityJoinOperator.OR);
    List<EntityCondition> periodCheckAndlList = UtilMisc.<EntityCondition>toList(startDateRequired, // the startdate should be less than the period end
    EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("actualStartDate", EntityOperator.EQUALS, null), EntityCondition.makeCondition("estimatedStartDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("estimatedStartDate", EntityOperator.LESS_THAN_EQUAL_TO, endStamp)), EntityJoinOperator.AND), EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("actualStartDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("actualStartDate", EntityOperator.LESS_THAN_EQUAL_TO, endStamp)), EntityJoinOperator.AND)), EntityJoinOperator.OR), // if the completion date is not null then it should be larger than the period start
    EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(// can also be empty
    EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("estimatedCompletionDate", EntityOperator.EQUALS, null), EntityCondition.makeCondition("actualCompletionDate", EntityOperator.EQUALS, null)), EntityJoinOperator.AND), // check estimated value if the actual is not provided
    EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("actualCompletionDate", EntityOperator.EQUALS, null), EntityCondition.makeCondition("estimatedCompletionDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("estimatedCompletionDate", EntityOperator.GREATER_THAN_EQUAL_TO, startStamp)), EntityJoinOperator.AND), // at last check the actual value
    EntityCondition.makeCondition(UtilMisc.<EntityCondition>toList(EntityCondition.makeCondition("actualCompletionDate", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("actualCompletionDate", EntityOperator.GREATER_THAN_EQUAL_TO, startStamp)), EntityJoinOperator.AND)), EntityJoinOperator.OR));
    entityExprList.addAll(periodCheckAndlList);
    try {
        List<GenericValue> tempWorkEfforts = null;
        if (UtilValidate.isNotEmpty(partyIdsToUse)) {
            tempWorkEfforts = EntityQuery.use(delegator).from("WorkEffortAndPartyAssignAndType").where(entityExprList).orderBy("estimatedStartDate").filterByDate().queryList();
        } else {
            tempWorkEfforts = EntityQuery.use(delegator).from("WorkEffort").where(entityExprList).orderBy("estimatedStartDate").queryList();
        }
        if (!"CAL_PERSONAL".equals(calendarType) && UtilValidate.isNotEmpty(fixedAssetId)) {
            // Get "new style" work efforts
            tempWorkEfforts.addAll(EntityQuery.use(delegator).from("WorkEffortAndFixedAssetAssign").where(entityExprList).orderBy("estimatedStartDate").filterByDate().queryList());
        }
        validWorkEfforts = WorkEffortWorker.removeDuplicateWorkEfforts(tempWorkEfforts);
    } catch (GenericEntityException e) {
        Debug.logWarning(e, module);
    }
    // Split the WorkEffort list into a map with entries for each period, period start is the key
    List<Map<String, Object>> periods = new LinkedList<>();
    if (validWorkEfforts != null) {
        List<DateRange> periodRanges = new LinkedList<>();
        for (int i = 0; i < numPeriods; i++) {
            Timestamp curPeriodStart = UtilDateTime.adjustTimestamp(startStamp, periodType, i, timeZone, locale);
            Timestamp curPeriodEnd = UtilDateTime.adjustTimestamp(curPeriodStart, periodType, 1, timeZone, locale);
            curPeriodEnd = new Timestamp(curPeriodEnd.getTime() - 1);
            periodRanges.add(new DateRange(curPeriodStart, curPeriodEnd));
        }
        try {
            // Process recurring work efforts
            Set<GenericValue> exclusions = new HashSet<>();
            Set<GenericValue> inclusions = new HashSet<>();
            DateRange range = new DateRange(startStamp, endStamp);
            Calendar cal = UtilDateTime.toCalendar(startStamp, timeZone, locale);
            for (GenericValue workEffort : validWorkEfforts) {
                if (UtilValidate.isNotEmpty(workEffort.getString("tempExprId"))) {
                    // check if either the workeffort is public or the requested party is a member
                    if (UtilValidate.isNotEmpty(partyIdsToUse) && !"WES_PUBLIC".equals(workEffort.getString("scopeEnumId")) && !partyIdsToUse.contains(workEffort.getString("partyId"))) {
                        continue;
                    }
                    // if the workeffort has actual date time, using temporal expression has no sense
                    if (UtilValidate.isNotEmpty(workEffort.getTimestamp("actualStartDate")) || UtilValidate.isNotEmpty(workEffort.getTimestamp("actualCompletionDate"))) {
                        continue;
                    }
                    TemporalExpression tempExpr = TemporalExpressionWorker.getTemporalExpression(delegator, workEffort.getString("tempExprId"));
                    DateRange weRange = new DateRange(workEffort.getTimestamp("estimatedStartDate"), workEffort.getTimestamp("estimatedCompletionDate"));
                    Set<Date> occurrences = tempExpr.getRange(range, cal);
                    for (Date occurrence : occurrences) {
                        for (DateRange periodRange : periodRanges) {
                            if (periodRange.includesDate(occurrence)) {
                                GenericValue cloneWorkEffort = (GenericValue) workEffort.clone();
                                TimeDuration duration = TimeDuration.fromNumber(workEffort.getDouble("estimatedMilliSeconds"));
                                if (!duration.isZero()) {
                                    Calendar endCal = UtilDateTime.toCalendar(occurrence, timeZone, locale);
                                    Date endDate = duration.addToCalendar(endCal).getTime();
                                    cloneWorkEffort.set("estimatedStartDate", new Timestamp(occurrence.getTime()));
                                    cloneWorkEffort.set("estimatedCompletionDate", new Timestamp(endDate.getTime()));
                                } else {
                                    cloneWorkEffort.set("estimatedStartDate", periodRange.startStamp());
                                    cloneWorkEffort.set("estimatedCompletionDate", periodRange.endStamp());
                                }
                                if (weRange.includes(cloneWorkEffort.getTimestamp("estimatedStartDate"))) {
                                    inclusions.add(cloneWorkEffort);
                                }
                            }
                        }
                    }
                    exclusions.add(workEffort);
                }
            }
            validWorkEfforts.removeAll(exclusions);
            validWorkEfforts.addAll(inclusions);
        } catch (GenericEntityException e) {
            Debug.logWarning(e, module);
        }
        // For each period in the set we check all work efforts to see if they fall within range
        boolean firstEntry = true;
        for (DateRange periodRange : periodRanges) {
            List<Map<String, Object>> curWorkEfforts = new LinkedList<>();
            Map<String, Object> entry = new HashMap<>();
            for (GenericValue workEffort : validWorkEfforts) {
                Timestamp startDate = workEffort.getTimestamp("estimatedStartDate");
                if (workEffort.getTimestamp("actualStartDate") != null) {
                    startDate = workEffort.getTimestamp("actualStartDate");
                }
                Timestamp endDate = workEffort.getTimestamp("estimatedCompletionDate");
                if (workEffort.getTimestamp("actualCompletionDate") != null) {
                    endDate = workEffort.getTimestamp("actualCompletionDate");
                }
                if (endDate == null) {
                    endDate = startDate;
                }
                DateRange weRange = new DateRange(startDate, endDate);
                if (periodRange.intersectsRange(weRange)) {
                    Map<String, Object> calEntry = new HashMap<>();
                    calEntry.put("workEffort", workEffort);
                    long length = ((weRange.end().after(endStamp) ? endStamp.getTime() : weRange.end().getTime()) - (weRange.start().before(startStamp) ? startStamp.getTime() : weRange.start().getTime()));
                    int periodSpan = (int) Math.ceil((double) length / periodLen);
                    if (length % periodLen == 0 && startDate.getTime() > periodRange.start().getTime()) {
                        periodSpan++;
                    }
                    calEntry.put("periodSpan", Integer.valueOf(periodSpan));
                    DateRange calEntryRange = new DateRange((weRange.start().before(startStamp) ? startStamp : weRange.start()), (weRange.end().after(endStamp) ? endStamp : weRange.end()));
                    calEntry.put("calEntryRange", calEntryRange);
                    if (firstEntry) {
                        // If this is the first period any valid entry is starting here
                        calEntry.put("startOfPeriod", Boolean.TRUE);
                        firstEntry = false;
                    } else {
                        boolean startOfPeriod = ((weRange.start().getTime() - periodRange.start().getTime()) >= 0);
                        calEntry.put("startOfPeriod", Boolean.valueOf(startOfPeriod));
                    }
                    curWorkEfforts.add(calEntry);
                }
            }
            int numEntries = curWorkEfforts.size();
            if (numEntries > maxConcurrentEntries) {
                maxConcurrentEntries = numEntries;
            }
            entry.put("start", periodRange.startStamp());
            entry.put("end", periodRange.endStamp());
            entry.put("calendarEntries", curWorkEfforts);
            entry.put("calendarEntriesByDateRange", groupCalendarEntriesByDateRange(periodRange, curWorkEfforts));
            periods.add(entry);
        }
    }
    Map<String, Object> result = new HashMap<>();
    result.put("periods", periods);
    result.put("maxConcurrentEntries", Integer.valueOf(maxConcurrentEntries));
    return result;
}
Also used : Locale(java.util.Locale) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Security(org.apache.ofbiz.security.Security) Timestamp(java.sql.Timestamp) DateRange(org.apache.ofbiz.base.util.DateRange) TimeDuration(org.apache.ofbiz.base.util.TimeDuration) HashSet(java.util.HashSet) GenericValue(org.apache.ofbiz.entity.GenericValue) TemporalExpression(org.apache.ofbiz.service.calendar.TemporalExpression) Calendar(com.ibm.icu.util.Calendar) LinkedList(java.util.LinkedList) Date(java.util.Date) TimeZone(java.util.TimeZone) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 3 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class WorkEffortServices method getWorkEffort.

public static Map<String, Object> getWorkEffort(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Security security = ctx.getSecurity();
    Map<String, Object> resultMap = new HashMap<>();
    String workEffortId = (String) context.get("workEffortId");
    GenericValue workEffort = null;
    try {
        workEffort = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", workEffortId).queryOne();
    } catch (GenericEntityException e) {
        Debug.logWarning(e, module);
    }
    Boolean canView = null;
    List<GenericValue> workEffortPartyAssignments = null;
    Boolean tryEntity = null;
    GenericValue currentStatus = null;
    if (workEffort == null) {
        tryEntity = Boolean.FALSE;
        canView = Boolean.TRUE;
        String statusId = (String) context.get("currentStatusId");
        if (UtilValidate.isNotEmpty(statusId)) {
            try {
                currentStatus = EntityQuery.use(delegator).from("StatusItem").where("statusId", statusId).cache().queryOne();
            } catch (GenericEntityException e) {
                Debug.logWarning(e, module);
            }
        }
    } else {
        // get a list of workEffortPartyAssignments, if empty then this user CANNOT view the event, unless they have permission to view all
        if (userLogin != null && userLogin.get("partyId") != null && workEffortId != null) {
            try {
                workEffortPartyAssignments = EntityQuery.use(delegator).from("WorkEffortPartyAssignment").where("workEffortId", workEffortId, "partyId", userLogin.get("partyId")).queryList();
            } catch (GenericEntityException e) {
                Debug.logWarning(e, module);
            }
        }
        canView = (UtilValidate.isNotEmpty(workEffortPartyAssignments)) ? Boolean.TRUE : Boolean.FALSE;
        if (!canView.booleanValue() && security.hasEntityPermission("WORKEFFORTMGR", "_VIEW", userLogin)) {
            canView = Boolean.TRUE;
        }
        tryEntity = Boolean.TRUE;
        if (workEffort.get("currentStatusId") != null) {
            try {
                currentStatus = EntityQuery.use(delegator).from("StatusItem").where("statusId", workEffort.get("currentStatusId")).cache().queryOne();
            } catch (GenericEntityException e) {
                Debug.logWarning(e, module);
            }
        }
    }
    if (workEffortId != null) {
        resultMap.put("workEffortId", workEffortId);
    }
    if (workEffort != null) {
        resultMap.put("workEffort", workEffort);
    }
    if (canView != null) {
        resultMap.put("canView", canView);
    }
    if (workEffortPartyAssignments != null) {
        resultMap.put("partyAssigns", workEffortPartyAssignments);
    }
    if (tryEntity != null) {
        resultMap.put("tryEntity", tryEntity);
    }
    if (currentStatus != null) {
        resultMap.put("currentStatusItem", currentStatus);
    }
    return resultMap;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Security(org.apache.ofbiz.security.Security)

Example 4 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class PreferenceWorker method checkCopyPermission.

/**
 * Checks preference copy permissions. Returns hasPermission=true if permission
 * is granted.
 * <p>Users can copy from any set of preferences to their own preferences.
 * Copying to another user's preferences requires <a href="#ADMIN_PERMISSION">ADMIN_PERMISSION</a>
 * permission.</p>
 * @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> checkCopyPermission(DispatchContext ctx, Map<String, ?> context) {
    boolean hasPermission = false;
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    if (userLogin != null) {
        String userLoginId = userLogin.getString("userLoginId");
        // is an optional parameters which defaults to the logged on user
        String userLoginIdArg = (String) context.get(LOGINID_PARAMETER_NAME);
        if (userLoginIdArg == null || userLoginId.equals(userLoginIdArg)) {
            // users can copy to their own preferences
            hasPermission = true;
        } else {
            Security security = ctx.getSecurity();
            hasPermission = security.hasPermission(ADMIN_PERMISSION, userLogin);
        }
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("hasPermission", hasPermission);
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Security(org.apache.ofbiz.security.Security)

Example 5 with Security

use of org.apache.ofbiz.security.Security in project ofbiz-framework by apache.

the class EntityDataServices method reencryptPrivateKeys.

public static Map<String, Object> reencryptPrivateKeys(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    Security security = dctx.getSecurity();
    Locale locale = (Locale) context.get("locale");
    // check permission
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    if (!security.hasPermission("ENTITY_MAINT", userLogin)) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtServicePermissionNotGranted", locale));
    }
    String oldKey = (String) context.get("oldKey");
    String newKey = (String) context.get("newKey");
    AesCipherService cipherService = new AesCipherService();
    try {
        List<GenericValue> rows = EntityQuery.use(delegator).from("EntityKeyStore").queryList();
        for (GenericValue row : rows) {
            byte[] keyBytes = Base64.decodeBase64(row.getString("keyText"));
            Debug.logInfo("Processing entry " + row.getString("keyName") + " with key: " + row.getString("keyText"), module);
            if (oldKey != null) {
                Debug.logInfo("Decrypting with old key: " + oldKey, module);
                try {
                    keyBytes = cipherService.decrypt(keyBytes, Base64.decodeBase64(oldKey)).getBytes();
                } catch (Exception e) {
                    Debug.logInfo("Failed to decrypt with Shiro cipher; trying with old cipher", module);
                    try {
                        keyBytes = DesCrypt.decrypt(DesCrypt.getDesKey(Base64.decodeBase64(oldKey)), keyBytes);
                    } catch (Exception e1) {
                        Debug.logError(e1, module);
                        return ServiceUtil.returnError(e1.getMessage());
                    }
                }
            }
            String newKeyText;
            if (newKey != null) {
                Debug.logInfo("Encrypting with new key: " + oldKey, module);
                newKeyText = cipherService.encrypt(keyBytes, Base64.decodeBase64(newKey)).toBase64();
            } else {
                newKeyText = Base64.encodeBase64String(keyBytes);
            }
            Debug.logInfo("Storing new encrypted value: " + newKeyText, module);
            row.setString("keyText", newKeyText);
            row.store();
        }
    } catch (GenericEntityException gee) {
        Debug.logError(gee, module);
        return ServiceUtil.returnError(gee.getMessage());
    }
    delegator.clearAllCaches();
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) AesCipherService(org.apache.shiro.crypto.AesCipherService) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Security(org.apache.ofbiz.security.Security) URISyntaxException(java.net.URISyntaxException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GeneralException(org.apache.ofbiz.base.util.GeneralException)

Aggregations

Security (org.apache.ofbiz.security.Security)79 GenericValue (org.apache.ofbiz.entity.GenericValue)69 Delegator (org.apache.ofbiz.entity.Delegator)60 Locale (java.util.Locale)56 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)54 HashMap (java.util.HashMap)36 Timestamp (java.sql.Timestamp)27 LinkedList (java.util.LinkedList)27 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)20 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)18 Map (java.util.Map)12 HttpSession (javax.servlet.http.HttpSession)7 GeneralException (org.apache.ofbiz.base.util.GeneralException)7 BigDecimal (java.math.BigDecimal)6 List (java.util.List)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 Date (java.util.Date)4 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)4 File (java.io.File)3