Search in sources :

Example 6 with GeneralRuntimeException

use of org.apache.ofbiz.base.util.GeneralRuntimeException in project ofbiz-framework by apache.

the class StringUtilTests method testFromHexString.

public void testFromHexString() {
    assertEquals("16 bytes", new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, StringUtil.fromHexString("000102030405060708090a0b0c0d0e0f"));
    GeneralRuntimeException caught = null;
    try {
        StringUtil.fromHexString("0-");
    } catch (GeneralRuntimeException e) {
        caught = e;
    } finally {
        assertNotNull("bad-char", caught);
    }
}
Also used : GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException)

Example 7 with GeneralRuntimeException

use of org.apache.ofbiz.base.util.GeneralRuntimeException in project ofbiz-framework by apache.

the class EntityListIterator method hasNext.

/**
 * PLEASE NOTE: Because of the nature of the JDBC ResultSet interface this method can be very inefficient.
 * It is much better to just use next() until it returns null
 * For example, you could use the following to iterate through the results in an EntityListIterator:
 *
 * GenericValue nextValue = null;
 * while ((nextValue = (GenericValue)
 * this.next()) != null) { ... }
 */
public boolean hasNext() {
    if (!haveShowHasNextWarning) {
        // DEJ20050207 To further discourage use of this, and to find existing use, always log a big warning showing where it is used:
        Exception whereAreWe = new Exception();
        Debug.logWarning(whereAreWe, "For performance reasons do not use the EntityListIterator.hasNext() method, just call next() until it returns null; see JavaDoc comments in the EntityListIterator class for details and an example", module);
        haveShowHasNextWarning = true;
    }
    try {
        if (resultSet.isLast() || resultSet.isAfterLast()) {
            return false;
        }
        // if we are not in the first or beforeFirst positions and we haven't made any values yet, the result set is empty so return false
        return haveMadeValue || resultSet.isBeforeFirst() || resultSet.isFirst();
    } catch (SQLException e) {
        tryCloseWithWarning("Warning: auto-closed EntityListIterator because of exception: " + e.toString());
        throw new GeneralRuntimeException("Error while checking to see if this is the last result", e);
    }
}
Also used : GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException) SQLException(java.sql.SQLException) GenericResultSetClosedException(org.apache.ofbiz.entity.GenericResultSetClosedException) GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException) SQLException(java.sql.SQLException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 8 with GeneralRuntimeException

use of org.apache.ofbiz.base.util.GeneralRuntimeException in project ofbiz-framework by apache.

the class OrderServices method processOrderPayments.

public static Map<String, Object> processOrderPayments(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String orderId = (String) context.get("orderId");
    Locale locale = (Locale) context.get("locale");
    OrderReadHelper orh = new OrderReadHelper(delegator, orderId);
    String productStoreId = orh.getProductStoreId();
    // check if order was already cancelled / rejected
    GenericValue orderHeader = orh.getOrderHeader();
    String orderStatus = orderHeader.getString("statusId");
    if ("ORDER_CANCELLED".equals(orderStatus) || "ORDER_REJECTED".equals(orderStatus)) {
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource, "OrderProcessOrderPaymentsStatusInvalid", locale) + orderStatus);
    }
    // process the payments
    if (!"PURCHASE_ORDER".equals(orh.getOrderTypeId())) {
        GenericValue productStore = ProductStoreWorker.getProductStore(productStoreId, delegator);
        Map<String, Object> paymentResp = null;
        try {
            Debug.logInfo("Calling process payments...", module);
            paymentResp = CheckOutHelper.processPayment(orderId, orh.getOrderGrandTotal(), orh.getCurrency(), productStore, userLogin, false, false, dispatcher, delegator);
        } catch (GeneralException | GeneralRuntimeException e) {
            Debug.logError(e, module);
            return ServiceUtil.returnError(e.getMessage());
        }
        if (ServiceUtil.isError(paymentResp)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderProcessOrderPayments", locale), null, null, paymentResp);
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) Delegator(org.apache.ofbiz.entity.Delegator) GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException)

Example 9 with GeneralRuntimeException

use of org.apache.ofbiz.base.util.GeneralRuntimeException in project ofbiz-framework by apache.

the class CategoryContentWrapper method getProductCategoryContentAsText.

public static void getProductCategoryContentAsText(String productCategoryId, GenericValue productCategory, String prodCatContentTypeId, Locale locale, String mimeTypeId, Delegator delegator, LocalDispatcher dispatcher, Writer outWriter, boolean cache) throws GeneralException, IOException {
    if (productCategoryId == null && productCategory != null) {
        productCategoryId = productCategory.getString("productCategoryId");
    }
    if (delegator == null && productCategory != null) {
        delegator = productCategory.getDelegator();
    }
    if (UtilValidate.isEmpty(mimeTypeId)) {
        mimeTypeId = EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator);
    }
    if (delegator == null) {
        throw new GeneralRuntimeException("Unable to find a delegator to use!");
    }
    List<GenericValue> categoryContentList = EntityQuery.use(delegator).from("ProductCategoryContent").where("productCategoryId", productCategoryId, "prodCatContentTypeId", prodCatContentTypeId).orderBy("-fromDate").cache(cache).filterByDate().queryList();
    GenericValue categoryContent = EntityUtil.getFirst(categoryContentList);
    if (categoryContent != null) {
        // when rendering the category content, always include the Product Category and ProductCategoryContent records that this comes from
        Map<String, Object> inContext = new HashMap<String, Object>();
        inContext.put("productCategory", productCategory);
        inContext.put("categoryContent", categoryContent);
        ContentWorker.renderContentAsText(dispatcher, categoryContent.getString("contentId"), outWriter, inContext, locale, mimeTypeId, null, null, cache);
        return;
    }
    String candidateFieldName = ModelUtil.dbNameToVarName(prodCatContentTypeId);
    ModelEntity categoryModel = delegator.getModelEntity("ProductCategory");
    if (categoryModel.isField(candidateFieldName)) {
        if (productCategory == null) {
            productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", productCategoryId).cache().queryOne();
        }
        if (productCategory != null) {
            String candidateValue = productCategory.getString(candidateFieldName);
            if (UtilValidate.isNotEmpty(candidateValue)) {
                outWriter.write(candidateValue);
                return;
            }
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException) HashMap(java.util.HashMap) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity)

Example 10 with GeneralRuntimeException

use of org.apache.ofbiz.base.util.GeneralRuntimeException in project ofbiz-framework by apache.

the class CmsEvents method cms.

public static String cms(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    ServletContext servletContext = request.getSession().getServletContext();
    HttpSession session = request.getSession();
    VisualTheme visualTheme = UtilHttp.getVisualTheme(request);
    Writer writer = null;
    Locale locale = UtilHttp.getLocale(request);
    String webSiteId = (String) session.getAttribute("webSiteId");
    if (webSiteId == null) {
        webSiteId = WebSiteWorker.getWebSiteId(request);
        if (webSiteId == null) {
            request.setAttribute("_ERROR_MESSAGE_", "Not able to run CMS application; no webSiteId defined for WebApp!");
            return "error";
        }
    }
    // is this a default request or called from a defined request mapping
    String targetRequest = (String) request.getAttribute("targetRequestUri");
    String actualRequest = (String) request.getAttribute("thisRequestUri");
    if (targetRequest != null) {
        targetRequest = targetRequest.replaceAll("\\W", "");
    } else {
        targetRequest = "";
    }
    if (actualRequest != null) {
        actualRequest = actualRequest.replaceAll("\\W", "");
    } else {
        actualRequest = "";
    }
    // place holder for the content id
    String contentId = null;
    String mapKey = null;
    String pathInfo = null;
    String displayMaintenancePage = (String) session.getAttribute("displayMaintenancePage");
    if (UtilValidate.isNotEmpty(displayMaintenancePage) && "Y".equalsIgnoreCase(displayMaintenancePage)) {
        try {
            writer = response.getWriter();
            GenericValue webSiteContent = EntityQuery.use(delegator).from("WebSiteContent").where("webSiteId", webSiteId, "webSiteContentTypeId", "MAINTENANCE_PAGE").filterByDate().queryFirst();
            if (webSiteContent != null) {
                ContentWorker.renderContentAsText(dispatcher, webSiteContent.getString("contentId"), writer, null, locale, "text/html", null, null, true);
                return "success";
            } else {
                request.setAttribute("_ERROR_MESSAGE_", "Not able to display maintenance page for [" + webSiteId + "]");
                return "error";
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        } catch (IOException e) {
            throw new GeneralRuntimeException("Error in the response writer/output stream while rendering content.", e);
        } catch (GeneralException e) {
            throw new GeneralRuntimeException("Error rendering content", e);
        }
    } else {
        // If an override view is present then use that in place of request.getPathInfo()
        String overrideViewUri = (String) request.getAttribute("_CURRENT_CHAIN_VIEW_");
        if (UtilValidate.isNotEmpty(overrideViewUri)) {
            pathInfo = overrideViewUri;
        } else {
            pathInfo = request.getPathInfo();
            if (targetRequest.equals(actualRequest) && pathInfo != null) {
                // was called directly -- path info is everything after the request
                String[] pathParsed = pathInfo.split("/", 3);
                if (pathParsed.length > 2) {
                    pathInfo = pathParsed[2];
                } else {
                    pathInfo = null;
                }
            }
        // if called through the default request, there is no request in pathinfo
        }
        // if path info is null or path info is / (i.e application mounted on root); check for a default content
        if (pathInfo == null || "/".equals(pathInfo)) {
            GenericValue defaultContent = null;
            try {
                defaultContent = EntityQuery.use(delegator).from("WebSiteContent").where("webSiteId", webSiteId, "webSiteContentTypeId", "DEFAULT_PAGE").orderBy("-fromDate").filterByDate().cache().queryFirst();
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
            if (defaultContent != null) {
                pathInfo = defaultContent.getString("contentId");
            }
        }
        // check for path alias first
        if (pathInfo != null) {
            // clean up the pathinfo for parsing
            pathInfo = pathInfo.trim();
            if (pathInfo.startsWith("/")) {
                pathInfo = pathInfo.substring(1);
            }
            if (pathInfo.endsWith("/")) {
                pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
            }
            GenericValue pathAlias = null;
            try {
                pathAlias = EntityQuery.use(delegator).from("WebSitePathAlias").where("webSiteId", webSiteId, "pathAlias", pathInfo).orderBy("-fromDate").cache().filterByDate().queryOne();
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
            if (pathAlias != null) {
                String alias = pathAlias.getString("aliasTo");
                contentId = pathAlias.getString("contentId");
                mapKey = pathAlias.getString("mapKey");
                if (contentId == null && UtilValidate.isNotEmpty(alias)) {
                    if (!alias.startsWith("/")) {
                        alias = "/" + alias;
                    }
                    RequestDispatcher rd = request.getRequestDispatcher(request.getServletPath() + alias);
                    try {
                        rd.forward(request, response);
                    } catch (ServletException e) {
                        Debug.logError(e, module);
                        return "error";
                    } catch (IOException e) {
                        Debug.logError(e, module);
                        return "error";
                    }
                    // null to not process any views
                    return null;
                }
            }
            // get the contentId/mapKey from URL
            if (contentId == null) {
                if (Debug.verboseOn())
                    Debug.logVerbose("Current PathInfo: " + pathInfo, module);
                String[] pathSplit = pathInfo.split("/");
                if (Debug.verboseOn())
                    Debug.logVerbose("Split pathinfo: " + pathSplit.length, module);
                contentId = pathSplit[0];
                if (pathSplit.length > 1) {
                    mapKey = pathSplit[1];
                }
            }
            // verify the request content is associated with the current website
            int statusCode = -1;
            boolean hasErrorPage = false;
            if (contentId != null) {
                try {
                    statusCode = verifyContentToWebSite(delegator, webSiteId, contentId);
                } catch (GeneralException e) {
                    Debug.logError(e, module);
                    throw new GeneralRuntimeException(e.getMessage(), e);
                }
            } else {
                statusCode = HttpServletResponse.SC_NOT_FOUND;
            }
            // We try to find a specific Error page for this website concerning the status code
            if (statusCode != HttpServletResponse.SC_OK) {
                GenericValue errorContainer = null;
                try {
                    errorContainer = EntityQuery.use(delegator).from("WebSiteContent").where("webSiteId", webSiteId, "webSiteContentTypeId", "ERROR_ROOT").orderBy("fromDate").filterByDate().cache().queryFirst();
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
                if (errorContainer != null) {
                    if (Debug.verboseOn())
                        Debug.logVerbose("Found error containers: " + errorContainer, module);
                    GenericValue errorPage = null;
                    try {
                        errorPage = EntityQuery.use(delegator).from("ContentAssocViewTo").where("contentIdStart", errorContainer.getString("contentId"), "caContentAssocTypeId", "TREE_CHILD", "contentTypeId", "DOCUMENT", "caMapKey", String.valueOf(statusCode)).filterByDate().queryFirst();
                    } catch (GenericEntityException e) {
                        Debug.logError(e, module);
                    }
                    if (errorPage != null) {
                        if (Debug.verboseOn()) {
                            Debug.logVerbose("Found error pages " + statusCode + " : " + errorPage, module);
                        }
                        contentId = errorPage.getString("contentId");
                    } else {
                        if (Debug.verboseOn()) {
                            Debug.logVerbose("No specific error page, falling back to the Error Container for " + statusCode, module);
                        }
                        contentId = errorContainer.getString("contentId");
                    }
                    mapKey = null;
                    hasErrorPage = true;
                }
                // We try to find a generic content Error page concerning the status code
                if (!hasErrorPage) {
                    try {
                        GenericValue errorPage = EntityQuery.use(delegator).from("Content").where("contentId", "CONTENT_ERROR_" + statusCode).cache().queryOne();
                        if (errorPage != null) {
                            if (Debug.verboseOn())
                                Debug.logVerbose("Found generic page " + statusCode, module);
                            contentId = errorPage.getString("contentId");
                            mapKey = null;
                            hasErrorPage = true;
                        }
                    } catch (GenericEntityException e) {
                        Debug.logError(e, module);
                    }
                }
            }
            if (statusCode == HttpServletResponse.SC_OK || hasErrorPage) {
                // create the template map
                MapStack<String> templateMap = MapStack.create();
                ScreenRenderer.populateContextForRequest(templateMap, null, request, response, servletContext);
                templateMap.put("statusCode", statusCode);
                // make the link prefix
                ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
                RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
                templateMap.put("_REQUEST_HANDLER_", rh);
                response.setStatus(statusCode);
                try {
                    writer = response.getWriter();
                    // TODO: replace "screen" to support dynamic rendering of different output
                    if (visualTheme == null) {
                        String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator);
                        visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
                    }
                    FormStringRenderer formStringRenderer = new MacroFormRenderer(visualTheme.getModelTheme().getFormRendererLocation("screen"), request, response);
                    templateMap.put("formStringRenderer", formStringRenderer);
                    // if use web analytics
                    List<GenericValue> webAnalytics = EntityQuery.use(delegator).from("WebAnalyticsConfig").where("webSiteId", webSiteId).queryList();
                    // render
                    if (UtilValidate.isNotEmpty(webAnalytics) && hasErrorPage) {
                        ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true, webAnalytics);
                    } else if (UtilValidate.isEmpty(mapKey)) {
                        ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true);
                    } else {
                        ContentWorker.renderSubContentAsText(dispatcher, contentId, writer, mapKey, templateMap, locale, "text/html", true);
                    }
                } catch (TemplateException e) {
                    throw new GeneralRuntimeException(String.format("Error creating form renderer while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
                } catch (IOException e) {
                    throw new GeneralRuntimeException(String.format("Error in the response writer/output stream while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
                } catch (GeneralException e) {
                    throw new GeneralRuntimeException(String.format("Error rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
                }
                return "success";
            } else {
                String contentName = null;
                String siteName = null;
                try {
                    GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
                    if (content != null && UtilValidate.isNotEmpty(content.getString("contentName"))) {
                        contentName = content.getString("contentName");
                    } else {
                        request.setAttribute("_ERROR_MESSAGE_", "Content: [" + contentId + "] is not a publish point for the current website: [" + webSiteId + "]");
                        return "error";
                    }
                    siteName = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne().getString("siteName");
                } catch (GenericEntityException e) {
                    Debug.logError(e, module);
                }
                request.setAttribute("_ERROR_MESSAGE_", "Content: " + contentName + " [" + contentId + "] is not a publish point for the current website: " + siteName + " [" + webSiteId + "]");
                return "error";
            }
        }
    }
    String siteName = null;
    GenericValue webSite = null;
    try {
        webSite = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne();
        if (webSite != null) {
            siteName = webSite.getString("siteName");
        }
        if (siteName == null) {
            siteName = "Not specified";
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (webSite != null) {
        request.setAttribute("_ERROR_MESSAGE_", "Not able to find a page to display for website: " + siteName + " [" + webSiteId + "] not even a default page!");
    } else {
        request.setAttribute("_ERROR_MESSAGE_", "Not able to find a page to display, not even a default page AND the website entity record for WebSiteId:" + webSiteId + " could not be found");
    }
    return "error";
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) TemplateException(freemarker.template.TemplateException) HttpSession(javax.servlet.http.HttpSession) MacroFormRenderer(org.apache.ofbiz.widget.renderer.macro.MacroFormRenderer) IOException(java.io.IOException) RequestDispatcher(javax.servlet.RequestDispatcher) ServletException(javax.servlet.ServletException) Delegator(org.apache.ofbiz.entity.Delegator) GeneralRuntimeException(org.apache.ofbiz.base.util.GeneralRuntimeException) RequestHandler(org.apache.ofbiz.webapp.control.RequestHandler) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) FormStringRenderer(org.apache.ofbiz.widget.renderer.FormStringRenderer) ServletContext(javax.servlet.ServletContext) VisualTheme(org.apache.ofbiz.widget.renderer.VisualTheme) Writer(java.io.Writer)

Aggregations

GeneralRuntimeException (org.apache.ofbiz.base.util.GeneralRuntimeException)20 GenericValue (org.apache.ofbiz.entity.GenericValue)11 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)6 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)6 HashMap (java.util.HashMap)5 MessageDigest (java.security.MessageDigest)3 ArrayList (java.util.ArrayList)3 Locale (java.util.Locale)3 Delegator (org.apache.ofbiz.entity.Delegator)3 IOException (java.io.IOException)2 BigDecimal (java.math.BigDecimal)2 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)2 SQLException (java.sql.SQLException)2 SecretKeyFactory (javax.crypto.SecretKeyFactory)2 PBEKeySpec (javax.crypto.spec.PBEKeySpec)2 GeneralException (org.apache.ofbiz.base.util.GeneralException)2 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)2 TemplateException (freemarker.template.TemplateException)1 Writer (java.io.Writer)1