Search in sources :

Example 1 with WebAppConfigurationException

use of org.apache.ofbiz.webapp.control.WebAppConfigurationException in project ofbiz-framework by apache.

the class ServiceMultiEventHandler method invoke.

/**
 * @see org.apache.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public String invoke(Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException {
    // TODO: consider changing this to use the new UtilHttp.parseMultiFormData method
    // make sure we have a valid reference to the Service Engine
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    if (dispatcher == null) {
        throw new EventHandlerException("The local service dispatcher is null");
    }
    DispatchContext dctx = dispatcher.getDispatchContext();
    if (dctx == null) {
        throw new EventHandlerException("Dispatch context cannot be found");
    }
    // get the details for the service(s) to call
    String mode = SYNC;
    String serviceName = null;
    if (UtilValidate.isEmpty(event.path)) {
        mode = SYNC;
    } else {
        mode = event.path;
    }
    // we only support SYNC mode in this handler
    if (!SYNC.equals(mode)) {
        throw new EventHandlerException("Async mode is not supported");
    }
    // nake sure we have a defined service to call
    serviceName = event.invoke;
    if (serviceName == null) {
        throw new EventHandlerException("Service name (eventMethod) cannot be null");
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module);
    // some needed info for when running the service
    Locale locale = UtilHttp.getLocale(request);
    TimeZone timeZone = UtilHttp.getTimeZone(request);
    HttpSession session = request.getSession();
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    // get the service model to generate context(s)
    ModelService modelService = null;
    try {
        modelService = dctx.getModelService(serviceName);
    } catch (GenericServiceException e) {
        throw new EventHandlerException("Problems getting the service model", e);
    }
    if (modelService == null) {
        throw new EventHandlerException("Problems getting the service model");
    }
    if (Debug.verboseOn())
        Debug.logVerbose("[Processing]: SERVICE Event", module);
    if (Debug.verboseOn())
        Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module);
    // check if we are using per row submit
    boolean useRowSubmit = request.getParameter("_useRowSubmit") == null ? false : "Y".equalsIgnoreCase(request.getParameter("_useRowSubmit"));
    // check if we are to also look in a global scope (no delimiter)
    boolean checkGlobalScope = request.getParameter("_checkGlobalScope") == null ? true : !"N".equalsIgnoreCase(request.getParameter("_checkGlobalScope"));
    // The number of multi form rows is retrieved
    int rowCount = UtilHttp.getMultiFormRowCount(request);
    if (rowCount < 1) {
        throw new EventHandlerException("No rows to process");
    }
    // some default message settings
    String errorPrefixStr = UtilProperties.getMessage("DefaultMessagesUiLabels", "service.error.prefix", locale);
    String errorSuffixStr = UtilProperties.getMessage("DefaultMessagesUiLabels", "service.error.suffix", locale);
    String messagePrefixStr = UtilProperties.getMessage("DefaultMessagesUiLabels", "service.message.prefix", locale);
    String messageSuffixStr = UtilProperties.getMessage("DefaultMessagesUiLabels", "service.message.suffix", locale);
    // prepare the error message and success message lists
    List<Object> errorMessages = new LinkedList<Object>();
    List<String> successMessages = new LinkedList<String>();
    // Check the global-transaction attribute of the event from the controller to see if the
    // event should be wrapped in a transaction
    String requestUri = RequestHandler.getRequestUri(request.getPathInfo());
    ConfigXMLReader.ControllerConfig controllerConfig;
    try {
        controllerConfig = ConfigXMLReader.getControllerConfig(ConfigXMLReader.getControllerConfigURL(servletContext));
    } catch (WebAppConfigurationException e) {
        throw new EventHandlerException(e);
    }
    boolean eventGlobalTransaction;
    try {
        eventGlobalTransaction = controllerConfig.getRequestMapMap().get(requestUri).event.globalTransaction;
    } catch (WebAppConfigurationException e) {
        throw new EventHandlerException(e);
    }
    Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet();
    // big try/finally to make sure commit or rollback are run
    boolean beganTrans = false;
    String returnString = null;
    try {
        if (eventGlobalTransaction) {
            // start the global transaction
            try {
                beganTrans = TransactionUtil.begin(modelService.transactionTimeout * rowCount);
            } catch (GenericTransactionException e) {
                throw new EventHandlerException("Problem starting multi-service global transaction", e);
            }
        }
        // now loop throw the rows and prepare/invoke the service for each
        for (int i = 0; i < rowCount; i++) {
            String curSuffix = UtilHttp.getMultiRowDelimiter() + i;
            boolean rowSelected = false;
            if (UtilValidate.isNotEmpty(request.getAttribute(UtilHttp.getRowSubmitPrefix() + i))) {
                rowSelected = request.getAttribute(UtilHttp.getRowSubmitPrefix() + i) == null ? false : "Y".equalsIgnoreCase((String) request.getAttribute(UtilHttp.getRowSubmitPrefix() + i));
            } else {
                rowSelected = request.getParameter(UtilHttp.getRowSubmitPrefix() + i) == null ? false : "Y".equalsIgnoreCase(request.getParameter(UtilHttp.getRowSubmitPrefix() + i));
            }
            // make sure we are to process this row
            if (useRowSubmit && !rowSelected) {
                continue;
            }
            // build the context
            Map<String, Object> serviceContext = new HashMap<String, Object>();
            for (ModelParam modelParam : modelService.getInModelParamList()) {
                String paramName = modelParam.name;
                // don't include userLogin, that's taken care of below
                if ("userLogin".equals(paramName))
                    continue;
                // don't include locale, that is also taken care of below
                if ("locale".equals(paramName))
                    continue;
                // don't include timeZone, that is also taken care of below
                if ("timeZone".equals(paramName))
                    continue;
                Object value = null;
                if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) {
                    Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, modelParam.stringMapPrefix, curSuffix);
                    value = paramMap;
                } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) {
                    List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, modelParam.stringListSuffix, null);
                    value = paramList;
                } else {
                    // check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't
                    value = request.getAttribute(paramName + curSuffix);
                    // first check for request parameters
                    if (value == null) {
                        String name = paramName + curSuffix;
                        ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session, serviceName, dctx.getDelegator());
                        String[] paramArr = request.getParameterValues(name);
                        if (paramArr != null) {
                            if (paramArr.length > 1) {
                                value = Arrays.asList(paramArr);
                            } else {
                                value = paramArr[0];
                            }
                        }
                    }
                    // if the parameter wasn't passed and no other value found, check the session
                    if (value == null) {
                        value = session.getAttribute(paramName + curSuffix);
                    }
                    // now check global scope
                    if (value == null) {
                        if (checkGlobalScope) {
                            String[] gParamArr = request.getParameterValues(paramName);
                            if (gParamArr != null) {
                                if (gParamArr.length > 1) {
                                    value = Arrays.asList(gParamArr);
                                } else {
                                    value = gParamArr[0];
                                }
                            }
                            if (value == null) {
                                value = request.getAttribute(paramName);
                            }
                            if (value == null) {
                                value = session.getAttribute(paramName);
                            }
                        }
                    }
                    // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes})
                    if (value == null) {
                        value = UtilHttp.makeParamValueFromComposite(request, paramName + curSuffix, locale);
                    }
                    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(paramName, value);
            // Debug.logInfo("In ServiceMultiEventHandler got value [" + value + "] for input parameter [" + paramName + "] for service [" + serviceName + "]", module);
            }
            // get only the parameters for this service - converted to proper type
            serviceContext = modelService.makeValid(serviceContext, ModelService.IN_PARAM, true, null, timeZone, locale);
            // include the UserLogin value object
            if (userLogin != null) {
                serviceContext.put("userLogin", userLogin);
            }
            // include the Locale object
            if (locale != null) {
                serviceContext.put("locale", locale);
            }
            // include the TimeZone object
            if (timeZone != null) {
                serviceContext.put("timeZone", timeZone);
            }
            // Debug.logInfo("ready to call " + serviceName + " with context " + serviceContext, module);
            // invoke the service
            Map<String, Object> result = null;
            try {
                result = dispatcher.runSync(serviceName, serviceContext);
            } catch (ServiceAuthException e) {
                // not logging since the service engine already did
                errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i + "): " + e.getNonNestedMessage());
            } catch (ServiceValidationException e) {
                // not logging since the service engine already did
                request.setAttribute("serviceValidationException", e);
                List<String> errors = e.getMessageList();
                if (errors != null) {
                    for (String message : errors) {
                        errorMessages.add("Service invocation error on row (" + i + "): " + message);
                    }
                } else {
                    errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i + "): " + e.getNonNestedMessage());
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Service invocation error", module);
                errorMessages.add(messagePrefixStr + "Service invocation error on row (" + i + "): " + e.getNested() + messageSuffixStr);
            }
            if (result == null) {
                returnString = ModelService.RESPOND_SUCCESS;
            } else {
                // check for an error message
                String errorMessage = ServiceUtil.makeErrorMessage(result, messagePrefixStr, messageSuffixStr, "", "");
                if (UtilValidate.isNotEmpty(errorMessage)) {
                    errorMessages.add(errorMessage);
                }
                // get the success messages
                if (UtilValidate.isNotEmpty(result.get(ModelService.SUCCESS_MESSAGE))) {
                    String newSuccessMessage = (String) result.get(ModelService.SUCCESS_MESSAGE);
                    if (!successMessages.contains(newSuccessMessage)) {
                        successMessages.add(newSuccessMessage);
                    }
                }
                if (UtilValidate.isNotEmpty(result.get(ModelService.SUCCESS_MESSAGE_LIST))) {
                    List<String> newSuccessMessages = UtilGenerics.<String>checkList(result.get(ModelService.SUCCESS_MESSAGE_LIST));
                    for (int j = 0; j < newSuccessMessages.size(); j++) {
                        String newSuccessMessage = newSuccessMessages.get(j);
                        if (!successMessages.contains(newSuccessMessage)) {
                            successMessages.add(newSuccessMessage);
                        }
                    }
                }
            }
            // set the results in the request
            if ((result != null) && (result.entrySet() != null)) {
                for (Map.Entry<String, Object> rme : result.entrySet()) {
                    String resultKey = rme.getKey();
                    Object resultValue = rme.getValue();
                    if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey) && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey) && !ModelService.SUCCESS_MESSAGE.equals(resultKey) && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) {
                        // set the result to request w/ and w/o a suffix to handle both cases: to have the result in each iteration and to prevent its overriding
                        request.setAttribute(resultKey + curSuffix, resultValue);
                        request.setAttribute(resultKey, resultValue);
                    }
                }
            }
        }
    } finally {
        if (errorMessages.size() > 0) {
            if (eventGlobalTransaction) {
                // rollback the global transaction
                try {
                    TransactionUtil.rollback(beganTrans, "Error in multi-service event handling: " + errorMessages.toString(), null);
                } catch (GenericTransactionException e) {
                    Debug.logError(e, "Could not rollback multi-service global transaction", module);
                }
            }
            errorMessages.add(0, errorPrefixStr);
            errorMessages.add(errorSuffixStr);
            StringBuilder errorBuf = new StringBuilder();
            for (Object em : errorMessages) {
                errorBuf.append(em + "\n");
            }
            request.setAttribute("_ERROR_MESSAGE_", errorBuf.toString());
            returnString = "error";
        } else {
            if (eventGlobalTransaction) {
                // commit the global transaction
                try {
                    TransactionUtil.commit(beganTrans);
                } catch (GenericTransactionException e) {
                    Debug.logError(e, "Could not commit multi-service global transaction", module);
                    throw new EventHandlerException("Commit multi-service global transaction failed");
                }
            }
            if (successMessages.size() > 0) {
                request.setAttribute("_EVENT_MESSAGE_LIST_", successMessages);
            }
            returnString = "success";
        }
    }
    return returnString;
}
Also used : Locale(java.util.Locale) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException) DispatchContext(org.apache.ofbiz.service.DispatchContext) LinkedList(java.util.LinkedList) List(java.util.List) GenericValue(org.apache.ofbiz.entity.GenericValue) ServiceAuthException(org.apache.ofbiz.service.ServiceAuthException) ServiceValidationException(org.apache.ofbiz.service.ServiceValidationException) HttpSession(javax.servlet.http.HttpSession) ModelParam(org.apache.ofbiz.service.ModelParam) LinkedList(java.util.LinkedList) ModelService(org.apache.ofbiz.service.ModelService) TimeZone(java.util.TimeZone) ConfigXMLReader(org.apache.ofbiz.webapp.control.ConfigXMLReader) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) HashMap(java.util.HashMap) Map(java.util.Map) RequestMap(org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap)

Example 2 with WebAppConfigurationException

use of org.apache.ofbiz.webapp.control.WebAppConfigurationException in project ofbiz-framework by apache.

the class WidgetWorker method determineAutoLinkType.

public static String determineAutoLinkType(String linkType, String target, String targetType, HttpServletRequest request) {
    if ("auto".equals(linkType)) {
        if ("intra-app".equals(targetType)) {
            String requestUri = (target.indexOf('?') > -1) ? target.substring(0, target.indexOf('?')) : target;
            ServletContext servletContext = request.getSession().getServletContext();
            RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_");
            ConfigXMLReader.RequestMap requestMap = null;
            try {
                requestMap = rh.getControllerConfig().getRequestMapMap().get(requestUri);
            } catch (WebAppConfigurationException e) {
                Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module);
            }
            if (requestMap != null && requestMap.event != null) {
                return "hidden-form";
            }
        }
        return "anchor";
    }
    return linkType;
}
Also used : ConfigXMLReader(org.apache.ofbiz.webapp.control.ConfigXMLReader) RequestHandler(org.apache.ofbiz.webapp.control.RequestHandler) ServletContext(javax.servlet.ServletContext) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException)

Example 3 with WebAppConfigurationException

use of org.apache.ofbiz.webapp.control.WebAppConfigurationException in project ofbiz-framework by apache.

the class CatalogAltUrlSeoTransform method getWriter.

@Override
public Writer getWriter(final Writer out, final Map args) throws TemplateModelException, IOException {
    final StringBuilder buf = new StringBuilder();
    final boolean fullPath = checkArg(args, "fullPath", false);
    final boolean secure = checkArg(args, "secure", false);
    return new Writer(out) {

        public void write(char[] cbuf, int off, int len) throws IOException {
            buf.append(cbuf, off, len);
        }

        public void flush() throws IOException {
            out.flush();
        }

        public void close() throws IOException {
            try {
                Environment env = Environment.getCurrentEnvironment();
                BeanModel req = (BeanModel) env.getVariable("request");
                String previousCategoryId = getStringArg(args, "previousCategoryId");
                String productCategoryId = getStringArg(args, "productCategoryId");
                String productId = getStringArg(args, "productId");
                String url = "";
                Object prefix = env.getVariable("urlPrefix");
                String viewSize = getStringArg(args, "viewSize");
                String viewIndex = getStringArg(args, "viewIndex");
                String viewSort = getStringArg(args, "viewSort");
                String searchString = getStringArg(args, "searchString");
                if (req != null) {
                    HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();
                    StringBuilder newURL = new StringBuilder();
                    if (UtilValidate.isNotEmpty(productId)) {
                        if (SeoConfigUtil.isCategoryUrlEnabled(request.getContextPath())) {
                            url = CatalogUrlSeoTransform.makeProductUrl(request, productId, productCategoryId, previousCategoryId);
                        } else {
                            url = CatalogUrlFilter.makeProductUrl(request, previousCategoryId, productCategoryId, productId);
                        }
                    } else {
                        if (SeoConfigUtil.isCategoryUrlEnabled(request.getContextPath())) {
                            url = CatalogUrlSeoTransform.makeCategoryUrl(request, productCategoryId, previousCategoryId, viewSize, viewIndex, viewSort, searchString);
                        } else {
                            url = CatalogUrlFilter.makeCategoryUrl(request, previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
                        }
                    }
                    // make the link
                    if (fullPath) {
                        try {
                            OfbizUrlBuilder builder = OfbizUrlBuilder.from(request);
                            builder.buildHostPart(newURL, "", secure);
                        } catch (WebAppConfigurationException e) {
                            Debug.logError(e.getMessage(), module);
                        }
                    }
                    newURL.append(url);
                    out.write(newURL.toString());
                } else if (prefix != null) {
                    Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
                    LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
                    Locale locale = (Locale) args.get("locale");
                    String prefixString = ((StringModel) prefix).getAsString();
                    prefixString = prefixString.replaceAll("&#47;", "/");
                    String contextPath = prefixString;
                    int lastSlashIndex = prefixString.lastIndexOf('/');
                    if (lastSlashIndex > -1 && lastSlashIndex < prefixString.length()) {
                        contextPath = prefixString.substring(prefixString.lastIndexOf('/'));
                    }
                    if (UtilValidate.isNotEmpty(productId)) {
                        GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
                        ProductContentWrapper wrapper = new ProductContentWrapper(dispatcher, product, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator));
                        if (SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
                            url = CatalogUrlSeoTransform.makeProductUrl(delegator, wrapper, prefixString, contextPath, productCategoryId, previousCategoryId, productId);
                        } else {
                            url = CatalogUrlFilter.makeProductUrl(wrapper, null, prefixString, previousCategoryId, productCategoryId, productId);
                        }
                    } else {
                        GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", productCategoryId).queryOne();
                        CategoryContentWrapper wrapper = new CategoryContentWrapper(dispatcher, productCategory, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator));
                        if (SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
                            url = CatalogUrlSeoTransform.makeCategoryUrl(delegator, wrapper, prefixString, productCategoryId, previousCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
                        } else {
                            url = CatalogUrlFilter.makeCategoryUrl(delegator, wrapper, null, prefixString, previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
                        }
                    }
                    out.write(url);
                } else {
                    out.write(buf.toString());
                }
            } catch (TemplateModelException | GenericEntityException e) {
                throw new IOException(e.getMessage());
            }
        }
    };
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) TemplateModelException(freemarker.template.TemplateModelException) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) BeanModel(freemarker.ext.beans.BeanModel) OfbizUrlBuilder(org.apache.ofbiz.webapp.OfbizUrlBuilder) CategoryContentWrapper(org.apache.ofbiz.product.category.CategoryContentWrapper) IOException(java.io.IOException) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Delegator(org.apache.ofbiz.entity.Delegator) ProductContentWrapper(org.apache.ofbiz.product.product.ProductContentWrapper) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Environment(freemarker.core.Environment) Writer(java.io.Writer)

Example 4 with WebAppConfigurationException

use of org.apache.ofbiz.webapp.control.WebAppConfigurationException in project ofbiz-framework by apache.

the class OfbizCatalogAltUrlTransform method getWriter.

@Override
public Writer getWriter(final Writer out, final Map args) throws TemplateModelException, IOException {
    final StringBuilder buf = new StringBuilder();
    final boolean fullPath = checkArg(args, "fullPath", false);
    final boolean secure = checkArg(args, "secure", false);
    return new Writer(out) {

        @Override
        public void write(char[] cbuf, int off, int len) throws IOException {
            buf.append(cbuf, off, len);
        }

        @Override
        public void flush() throws IOException {
            out.flush();
        }

        @Override
        public void close() throws IOException {
            try {
                Environment env = Environment.getCurrentEnvironment();
                BeanModel req = (BeanModel) env.getVariable("request");
                String previousCategoryId = getStringArg(args, "previousCategoryId");
                String productCategoryId = getStringArg(args, "productCategoryId");
                String productId = getStringArg(args, "productId");
                String url = "";
                Object prefix = env.getVariable("urlPrefix");
                String viewSize = getStringArg(args, "viewSize");
                String viewIndex = getStringArg(args, "viewIndex");
                String viewSort = getStringArg(args, "viewSort");
                String searchString = getStringArg(args, "searchString");
                if (req != null) {
                    HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();
                    StringBuilder newURL = new StringBuilder();
                    if (UtilValidate.isNotEmpty(productId)) {
                        url = CatalogUrlFilter.makeProductUrl(request, previousCategoryId, productCategoryId, productId);
                    } else {
                        url = CatalogUrlFilter.makeCategoryUrl(request, previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
                    }
                    // make the link
                    if (fullPath) {
                        OfbizUrlBuilder builder = OfbizUrlBuilder.from(request);
                        builder.buildHostPart(newURL, url, secure);
                    }
                    newURL.append(url);
                    out.write(newURL.toString());
                } else if (prefix != null) {
                    Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
                    LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
                    Locale locale = (Locale) args.get("locale");
                    if (UtilValidate.isNotEmpty(productId)) {
                        GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
                        ProductContentWrapper wrapper = new ProductContentWrapper(dispatcher, product, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator));
                        url = CatalogUrlFilter.makeProductUrl(wrapper, null, ((StringModel) prefix).getAsString(), previousCategoryId, productCategoryId, productId);
                    } else {
                        GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", productCategoryId).queryOne();
                        CategoryContentWrapper wrapper = new CategoryContentWrapper(dispatcher, productCategory, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator));
                        url = CatalogUrlFilter.makeCategoryUrl(delegator, wrapper, null, ((StringModel) prefix).getAsString(), previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString);
                    }
                    out.write(url);
                } else {
                    out.write(buf.toString());
                }
            } catch (TemplateModelException | GenericEntityException | WebAppConfigurationException e) {
                throw new IOException(e.getMessage());
            }
        }
    };
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) TemplateModelException(freemarker.template.TemplateModelException) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) BeanModel(freemarker.ext.beans.BeanModel) OfbizUrlBuilder(org.apache.ofbiz.webapp.OfbizUrlBuilder) CategoryContentWrapper(org.apache.ofbiz.product.category.CategoryContentWrapper) IOException(java.io.IOException) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException) HttpServletRequest(javax.servlet.http.HttpServletRequest) Delegator(org.apache.ofbiz.entity.Delegator) ProductContentWrapper(org.apache.ofbiz.product.product.ProductContentWrapper) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) Environment(freemarker.core.Environment) Writer(java.io.Writer)

Example 5 with WebAppConfigurationException

use of org.apache.ofbiz.webapp.control.WebAppConfigurationException in project ofbiz-framework by apache.

the class SeoContextFilter method doFilter.

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String uri = httpRequest.getRequestURI();
    boolean forwarded = forwardUri(httpResponse, uri);
    if (forwarded) {
        return;
    }
    URL controllerConfigURL = ConfigXMLReader.getControllerConfigURL(config.getServletContext());
    ControllerConfig controllerConfig = null;
    Map<String, ConfigXMLReader.RequestMap> requestMaps = null;
    try {
        controllerConfig = ConfigXMLReader.getControllerConfig(controllerConfigURL);
        requestMaps = controllerConfig.getRequestMapMap();
    } catch (WebAppConfigurationException e) {
        Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module);
        throw new ServletException(e);
    }
    Set<String> uris = requestMaps.keySet();
    // test to see if we have come through the control servlet already, if not do the processing
    String requestPath = null;
    String contextUri = null;
    if (httpRequest.getAttribute(ControlFilter.FORWARDED_FROM_SERVLET) == null) {
        requestPath = httpRequest.getServletPath();
        if (requestPath == null)
            requestPath = "";
        if (requestPath.lastIndexOf('/') > 0) {
            if (requestPath.indexOf('/') == 0) {
                requestPath = '/' + requestPath.substring(1, requestPath.indexOf('/', 1));
            } else {
                requestPath = requestPath.substring(1, requestPath.indexOf('/'));
            }
        }
        String requestInfo = httpRequest.getServletPath();
        if (requestInfo == null)
            requestInfo = "";
        if (requestInfo.lastIndexOf('/') >= 0) {
            requestInfo = requestInfo.substring(0, requestInfo.lastIndexOf('/')) + "/*";
        }
        StringBuilder contextUriBuffer = new StringBuilder();
        if (httpRequest.getContextPath() != null) {
            contextUriBuffer.append(httpRequest.getContextPath());
        }
        if (httpRequest.getServletPath() != null) {
            contextUriBuffer.append(httpRequest.getServletPath());
        }
        if (httpRequest.getPathInfo() != null) {
            contextUriBuffer.append(httpRequest.getPathInfo());
        }
        contextUri = contextUriBuffer.toString();
        List<String> pathItemList = StringUtil.split(httpRequest.getPathInfo(), "/");
        String viewName = "";
        if (pathItemList != null) {
            viewName = pathItemList.get(0);
        }
        String requestUri = UtilHttp.getRequestUriFromTarget(httpRequest.getRequestURI());
        // check to make sure the requested url is allowed
        if (!allowedPathList.contains(requestPath) && !allowedPathList.contains(requestInfo) && !allowedPathList.contains(httpRequest.getServletPath()) && !allowedPathList.contains(requestUri) && !allowedPathList.contains("/" + viewName) && (UtilValidate.isEmpty(requestPath) && UtilValidate.isEmpty(httpRequest.getServletPath()) && !uris.contains(viewName))) {
            String filterMessage = "[Filtered request]: " + contextUri;
            if (redirectPath == null) {
                if (UtilValidate.isEmpty(viewName)) {
                    // redirect without any url change in browser
                    RequestDispatcher rd = request.getRequestDispatcher(SeoControlServlet.getDefaultPage());
                    rd.forward(request, response);
                } else {
                    int error = 404;
                    if (UtilValidate.isNotEmpty(errorCode)) {
                        try {
                            error = Integer.parseInt(errorCode);
                        } catch (NumberFormatException nfe) {
                            Debug.logWarning(nfe, "Error code specified would not parse to Integer : " + errorCode, module);
                        }
                    }
                    filterMessage = filterMessage + " (" + error + ")";
                    httpResponse.sendError(error, contextUri);
                    request.setAttribute("filterRequestUriError", contextUri);
                }
            } else {
                filterMessage = filterMessage + " (" + redirectPath + ")";
                if (!redirectPath.toLowerCase(Locale.getDefault()).startsWith("http")) {
                    redirectPath = httpRequest.getContextPath() + redirectPath;
                }
                // httpResponse.sendRedirect(redirectPath);
                if ("".equals(uri) || "/".equals(uri)) {
                    // redirect without any url change in browser
                    RequestDispatcher rd = request.getRequestDispatcher(redirectPath);
                    rd.forward(request, response);
                } else {
                    // redirect with url change in browser
                    httpResponse.setStatus(SeoConfigUtil.getDefaultResponseCode());
                    httpResponse.setHeader("Location", redirectPath);
                }
            }
            Debug.logWarning(filterMessage, module);
            return;
        } else if ((allowedPathList.contains(requestPath) || allowedPathList.contains(requestInfo) || allowedPathList.contains(httpRequest.getServletPath()) || allowedPathList.contains(requestUri) || allowedPathList.contains("/" + viewName)) && !webServlets.contains(httpRequest.getServletPath())) {
            request.setAttribute(SeoControlServlet.REQUEST_IN_ALLOW_LIST, Boolean.TRUE);
        }
    }
    // we're done checking; continue on
    chain.doFilter(httpRequest, httpResponse);
}
Also used : ControllerConfig(org.apache.ofbiz.webapp.control.ConfigXMLReader.ControllerConfig) HttpServletResponse(javax.servlet.http.HttpServletResponse) URL(java.net.URL) WebAppConfigurationException(org.apache.ofbiz.webapp.control.WebAppConfigurationException) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException)

Aggregations

WebAppConfigurationException (org.apache.ofbiz.webapp.control.WebAppConfigurationException)6 Locale (java.util.Locale)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 GenericValue (org.apache.ofbiz.entity.GenericValue)3 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)3 ConfigXMLReader (org.apache.ofbiz.webapp.control.ConfigXMLReader)3 Environment (freemarker.core.Environment)2 BeanModel (freemarker.ext.beans.BeanModel)2 TemplateModelException (freemarker.template.TemplateModelException)2 IOException (java.io.IOException)2 Writer (java.io.Writer)2 Delegator (org.apache.ofbiz.entity.Delegator)2 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)2 CategoryContentWrapper (org.apache.ofbiz.product.category.CategoryContentWrapper)2 ProductContentWrapper (org.apache.ofbiz.product.product.ProductContentWrapper)2 OfbizUrlBuilder (org.apache.ofbiz.webapp.OfbizUrlBuilder)2 RequestMap (org.apache.ofbiz.webapp.control.ConfigXMLReader.RequestMap)2 RequestHandler (org.apache.ofbiz.webapp.control.RequestHandler)2 URL (java.net.URL)1 HashMap (java.util.HashMap)1