Search in sources :

Example 6 with Security

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

the class EntityDataServices method importDelimitedFromDirectory.

public static Map<String, Object> importDelimitedFromDirectory(DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    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));
    }
    // get the directory & delimiter
    String rootDirectory = (String) context.get("rootDirectory");
    URL rootDirectoryUrl = UtilURL.fromResource(rootDirectory);
    if (rootDirectoryUrl == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtUnableToLocateRootDirectory", UtilMisc.toMap("rootDirectory", rootDirectory), locale));
    }
    String delimiter = (String) context.get("delimiter");
    if (delimiter == null) {
        // default delimiter is tab
        delimiter = "\t";
    }
    File root = null;
    try {
        root = new File(new URI(rootDirectoryUrl.toExternalForm()));
    } catch (URISyntaxException e) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtUnableToLocateRootDirectoryURI", locale));
    }
    if (!root.exists() || !root.isDirectory() || !root.canRead()) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtRootDirectoryDoesNotExists", locale));
    }
    // get the file list
    List<File> files = getFileList(root);
    if (UtilValidate.isNotEmpty(files)) {
        for (File file : files) {
            try {
                Map<String, Object> serviceCtx = UtilMisc.toMap("file", file, "delimiter", delimiter, "userLogin", userLogin);
                dispatcher.runSyncIgnore("importDelimitedEntityFile", serviceCtx);
            } catch (GenericServiceException e) {
                Debug.logError(e, module);
            }
        }
    } else {
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "EntityExtNoFileAvailableInTheRootDirectory", UtilMisc.toMap("rootDirectory", rootDirectory), locale));
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) URISyntaxException(java.net.URISyntaxException) Security(org.apache.ofbiz.security.Security) URI(java.net.URI) URL(java.net.URL) UtilURL(org.apache.ofbiz.base.util.UtilURL) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) File(java.io.File)

Example 7 with Security

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

the class ServiceUtil method cancelJob.

public static Map<String, Object> cancelJob(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = getLocale(context);
    if (!security.hasPermission("SERVICE_INVOKE_ANY", userLogin)) {
        String errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.no_permission_to_run", locale) + ".";
        return ServiceUtil.returnError(errMsg);
    }
    String jobId = (String) context.get("jobId");
    Map<String, Object> fields = UtilMisc.<String, Object>toMap("jobId", jobId);
    GenericValue job = null;
    try {
        job = EntityQuery.use(delegator).from("JobSandbox").where("jobId", jobId).queryOne();
        if (job != null) {
            job.set("cancelDateTime", UtilDateTime.nowTimestamp());
            job.set("statusId", "SERVICE_CANCELLED");
            job.store();
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        String errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.unable_to_cancel_job", locale) + " : " + fields;
        return ServiceUtil.returnError(errMsg);
    }
    if (job != null) {
        Timestamp cancelDate = job.getTimestamp("cancelDateTime");
        Map<String, Object> result = ServiceUtil.returnSuccess();
        result.put("cancelDateTime", cancelDate);
        // To more easily see current pending jobs and possibly cancel some others
        result.put("statusId", "SERVICE_PENDING");
        return result;
    }
    String errMsg = UtilProperties.getMessage(ServiceUtil.resource, "serviceUtil.unable_to_cancel_job", locale) + " : " + null;
    return ServiceUtil.returnError(errMsg);
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Security(org.apache.ofbiz.security.Security) Timestamp(java.sql.Timestamp)

Example 8 with Security

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

the class CoreEvents method runService.

/**
 * Run a service.
 *  Request Parameters which are used for this event:
 *  SERVICE_NAME      - Name of the service to invoke
 *
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @return Response code string
 */
public static String runService(HttpServletRequest request, HttpServletResponse response) {
    // get the mode and service name
    String serviceName = request.getParameter("serviceName");
    String mode = request.getParameter("mode");
    Locale locale = UtilHttp.getLocale(request);
    if (UtilValidate.isEmpty(serviceName)) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.must_specify_service_name", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    if (UtilValidate.isEmpty(mode)) {
        mode = "sync";
    }
    // now do a security check
    Security security = (Security) request.getAttribute("security");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    // lookup the service definition to see if this service is externally available, if not require the SERVICE_INVOKE_ANY permission
    ModelService modelService = null;
    try {
        modelService = dispatcher.getDispatchContext().getModelService(serviceName);
    } catch (GenericServiceException e) {
        Debug.logError(e, "Error looking up ModelService for serviceName [" + serviceName + "]", module);
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + "[" + serviceName + "]: " + e.toString());
        return "error";
    }
    if (modelService == null) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_name_not_find", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + "[" + serviceName + "]");
        return "error";
    }
    if (!modelService.export && !security.hasPermission("SERVICE_INVOKE_ANY", request.getSession())) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.not_authorized_to_call", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + ".");
        return "error";
    }
    Debug.logInfo("Running service named [" + serviceName + "] from event with mode [" + mode + "]", module);
    // call the service via the ServiceEventHandler which
    // adapts an event to a service.
    Event event = new Event("service", mode, serviceName, false);
    try {
        return seh.invoke(event, null, request, response);
    } catch (EventHandlerException e) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_eventhandler_exception", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + ": " + e.getMessage());
        return "error";
    }
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) Event(org.apache.ofbiz.webapp.control.ConfigXMLReader.Event) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) Security(org.apache.ofbiz.security.Security) ModelService(org.apache.ofbiz.service.ModelService)

Example 9 with Security

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

the class CoreEvents method scheduleService.

/**
 * Schedule a service for a specific time or recurrence
 *  Request Parameters which are used for this service:
 *
 *  SERVICE_NAME      - Name of the service to invoke
 *  SERVICE_TIME      - First time the service will occur
 *  SERVICE_FREQUENCY - The type of recurrence (SECONDLY,MINUTELY,DAILY,etc)
 *  SERVICE_INTERVAL  - The interval of the frequency (every 5 minutes, etc)
 *
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @return Response code string
 */
public static String scheduleService(HttpServletRequest request, HttpServletResponse response) {
    Security security = (Security) request.getAttribute("security");
    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    // Delegator delegator = (Delegator) request.getAttribute("delegator");
    Locale locale = UtilHttp.getLocale(request);
    TimeZone timeZone = UtilHttp.getTimeZone(request);
    Map<String, Object> params = UtilHttp.getParameterMap(request);
    // get the schedule parameters
    String jobName = (String) params.remove("JOB_NAME");
    String serviceName = (String) params.remove("SERVICE_NAME");
    String poolName = (String) params.remove("POOL_NAME");
    String serviceTime = (String) params.remove("SERVICE_TIME");
    String serviceEndTime = (String) params.remove("SERVICE_END_TIME");
    String serviceFreq = (String) params.remove("SERVICE_FREQUENCY");
    String serviceIntr = (String) params.remove("SERVICE_INTERVAL");
    String serviceCnt = (String) params.remove("SERVICE_COUNT");
    String retryCnt = (String) params.remove("SERVICE_MAXRETRY");
    // the frequency map
    Map<String, Integer> freqMap = new HashMap<String, Integer>();
    freqMap.put("SECONDLY", Integer.valueOf(1));
    freqMap.put("MINUTELY", Integer.valueOf(2));
    freqMap.put("HOURLY", Integer.valueOf(3));
    freqMap.put("DAILY", Integer.valueOf(4));
    freqMap.put("WEEKLY", Integer.valueOf(5));
    freqMap.put("MONTHLY", Integer.valueOf(6));
    freqMap.put("YEARLY", Integer.valueOf(7));
    // some defaults
    long startTime = (new Date()).getTime();
    long endTime = 0;
    int maxRetry = -1;
    int count = 1;
    int interval = 1;
    int frequency = RecurrenceRule.DAILY;
    StringBuilder errorBuf = new StringBuilder();
    // make sure we passed a service
    if (serviceName == null) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.must_specify_service", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    // lookup the service definition to see if this service is externally available, if not require the SERVICE_INVOKE_ANY permission
    ModelService modelService = null;
    try {
        modelService = dispatcher.getDispatchContext().getModelService(serviceName);
    } catch (GenericServiceException e) {
        Debug.logError(e, "Error looking up ModelService for serviceName [" + serviceName + "]", module);
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + " [" + serviceName + "]: " + e.toString());
        return "error";
    }
    if (modelService == null) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_name_not_find", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + " [" + serviceName + "]");
        return "error";
    }
    // make the context valid; using the makeValid method from ModelService
    Map<String, Object> serviceContext = new HashMap<String, Object>();
    Iterator<String> ci = modelService.getInParamNames().iterator();
    while (ci.hasNext()) {
        String name = ci.next();
        // don't include userLogin, that's taken care of below
        if ("userLogin".equals(name))
            continue;
        // don't include locale, that is also taken care of below
        if ("locale".equals(name))
            continue;
        Object value = request.getParameter(name);
        // if the parameter wasn't passed and no other value found, don't pass on the null
        if (value == null) {
            value = request.getAttribute(name);
        }
        if (value == null) {
            value = request.getSession().getAttribute(name);
        }
        if (value == null) {
            // still null, give up for this one
            continue;
        }
        if (value instanceof String && ((String) value).length() == 0) {
            // interpreting empty fields as null values for each in back end handling...
            value = null;
        }
        // set even if null so that values will get nulled in the db later on
        serviceContext.put(name, value);
    }
    serviceContext = modelService.makeValid(serviceContext, ModelService.IN_PARAM, true, null, timeZone, locale);
    if (userLogin != null) {
        serviceContext.put("userLogin", userLogin);
    }
    if (locale != null) {
        serviceContext.put("locale", locale);
    }
    if (!modelService.export && !security.hasPermission("SERVICE_INVOKE_ANY", request.getSession())) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.not_authorized_to_call", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    // some conversions
    if (UtilValidate.isNotEmpty(serviceTime)) {
        try {
            Timestamp ts1 = Timestamp.valueOf(serviceTime);
            startTime = ts1.getTime();
        } catch (IllegalArgumentException e) {
            try {
                startTime = Long.parseLong(serviceTime);
            } catch (NumberFormatException nfe) {
                String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_time", locale);
                errorBuf.append(errMsg);
            }
        }
        if (startTime < (new Date()).getTime()) {
            String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_time_already_passed", locale);
            errorBuf.append(errMsg);
        }
    }
    if (UtilValidate.isNotEmpty(serviceEndTime)) {
        try {
            Timestamp ts1 = Timestamp.valueOf(serviceEndTime);
            endTime = ts1.getTime();
        } catch (IllegalArgumentException e) {
            try {
                endTime = Long.parseLong(serviceTime);
            } catch (NumberFormatException nfe) {
                String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_time", locale);
                errorBuf.append(errMsg);
            }
        }
        if (endTime < (new Date()).getTime()) {
            String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_time_already_passed", locale);
            errorBuf.append(errMsg);
        }
    }
    if (UtilValidate.isNotEmpty(serviceIntr)) {
        try {
            interval = Integer.parseInt(serviceIntr);
        } catch (NumberFormatException nfe) {
            String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_interval", locale);
            errorBuf.append(errMsg);
        }
    }
    if (UtilValidate.isNotEmpty(serviceCnt)) {
        try {
            count = Integer.parseInt(serviceCnt);
        } catch (NumberFormatException nfe) {
            String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_count", locale);
            errorBuf.append(errMsg);
        }
    }
    if (UtilValidate.isNotEmpty(serviceFreq)) {
        int parsedValue = 0;
        try {
            parsedValue = Integer.parseInt(serviceFreq);
            if (parsedValue > 0 && parsedValue < 8)
                frequency = parsedValue;
        } catch (NumberFormatException nfe) {
            parsedValue = 0;
        }
        if (parsedValue == 0) {
            if (!freqMap.containsKey(serviceFreq.toUpperCase())) {
                String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.invalid_format_frequency", locale);
                errorBuf.append(errMsg);
            } else {
                frequency = freqMap.get(serviceFreq.toUpperCase()).intValue();
            }
        }
    }
    if (UtilValidate.isNotEmpty(retryCnt)) {
        int parsedValue = -2;
        try {
            parsedValue = Integer.parseInt(retryCnt);
        } catch (NumberFormatException e) {
            parsedValue = -2;
        }
        if (parsedValue > -2) {
            maxRetry = parsedValue;
        } else {
            maxRetry = modelService.maxRetry;
        }
    } else {
        maxRetry = modelService.maxRetry;
    }
    // return the errors
    if (errorBuf.length() > 0) {
        request.setAttribute("_ERROR_MESSAGE_", errorBuf.toString());
        return "error";
    }
    Map<String, Object> syncServiceResult = null;
    // schedule service
    try {
        if (null != request.getParameter("_RUN_SYNC_") && "Y".equals(request.getParameter("_RUN_SYNC_"))) {
            syncServiceResult = dispatcher.runSync(serviceName, serviceContext);
        } else {
            dispatcher.schedule(jobName, poolName, serviceName, serviceContext, startTime, frequency, interval, count, endTime, maxRetry);
        }
    } catch (GenericServiceException e) {
        String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_dispatcher_exception", locale);
        request.setAttribute("_ERROR_MESSAGE_", errMsg + e.getMessage());
        return "error";
    }
    String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.service_scheduled", locale);
    request.setAttribute("_EVENT_MESSAGE_", errMsg);
    if (null != syncServiceResult) {
        request.getSession().setAttribute("_RUN_SYNC_RESULT_", syncServiceResult);
        return "sync_success";
    }
    return "success";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) Security(org.apache.ofbiz.security.Security) Timestamp(java.sql.Timestamp) Date(java.util.Date) ModelService(org.apache.ofbiz.service.ModelService) TimeZone(java.util.TimeZone) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 10 with Security

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

the class UtilCacheEvents method updateEvent.

/**
 * An HTTP WebEvent handler that updates the named cache
 * @param request The HTTP request object for the current JSP or Servlet request.
 * @param response The HTTP response object for the current JSP or Servlet request.
 * @return return an HTTP WebEvent handler that updates the named cache
 */
public static String updateEvent(HttpServletRequest request, HttpServletResponse response) {
    String errMsg = "";
    Locale locale = UtilHttp.getLocale(request);
    Security security = (Security) request.getAttribute("security");
    if (!security.hasPermission("UTIL_CACHE_EDIT", request.getSession())) {
        errMsg = UtilProperties.getMessage(err_resource, "utilCacheEvents.permissionEdit", locale) + ".";
        request.setAttribute("_EVENT_MESSAGE_", errMsg);
        return "error";
    }
    String name = request.getParameter("UTIL_CACHE_NAME");
    if (name == null) {
        errMsg = UtilProperties.getMessage(err_resource, "utilCache.couldNotUpdateCacheSetting", locale) + ".";
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    String maxInMemoryStr = request.getParameter("UTIL_CACHE_MAX_IN_MEMORY");
    String expireTimeStr = request.getParameter("UTIL_CACHE_EXPIRE_TIME");
    String useSoftReferenceStr = request.getParameter("UTIL_CACHE_USE_SOFT_REFERENCE");
    Integer maxInMemory = null;
    Long expireTime = null;
    try {
        maxInMemory = Integer.valueOf(maxInMemoryStr);
    } catch (Exception e) {
    }
    try {
        expireTime = Long.valueOf(expireTimeStr);
    } catch (Exception e) {
    }
    UtilCache<?, ?> utilCache = UtilCache.findCache(name);
    if (utilCache != null) {
        if (maxInMemory != null)
            utilCache.setMaxInMemory(maxInMemory.intValue());
        if (expireTime != null)
            utilCache.setExpireTime(expireTime.longValue());
        if (useSoftReferenceStr != null) {
            utilCache.setUseSoftReference("true".equals(useSoftReferenceStr));
        }
    }
    return "success";
}
Also used : Locale(java.util.Locale) Security(org.apache.ofbiz.security.Security)

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