Example usage for javax.servlet ServletException getMessage

List of usage examples for javax.servlet ServletException getMessage

Introduction

In this page you can find the example usage for javax.servlet ServletException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.aurel.track.admin.customize.category.report.execute.ReportOverviewJasperDesign.java

/**
 * Loads the sizes from a property file//  ww w. j  a  v  a 2 s.  co  m
 * 
 * @return
 */
private static void loadSizesFromFile() {
    PropertiesConfiguration properties = null;
    try {
        properties = HandleHome.getProperties(HandleHome.PDF_EXCEL_EXPORT_FILE,
                ApplicationBean.getInstance().getServletContext());
    } catch (ServletException e) {
        LOGGER.info("Getting the " + HandleHome.PDF_EXCEL_EXPORT_FILE + " configutartions failed with "
                + e.getMessage());
    }
    try {
        pageWidth = properties.getInt("pageWidth", 842);
    } catch (Exception e) {
        LOGGER.warn("Loading the pageWidth failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        pageHeight = properties.getInt("pageHeight", 585);
    } catch (Exception e) {
        LOGGER.warn("Loading the pageHeight failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        leftMargin = properties.getInt("leftMargin", 30);
    } catch (Exception e) {
        LOGGER.warn("Loading the leftMargin failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        rightMargin = properties.getInt("rightMargin", 30);
    } catch (Exception e) {
        LOGGER.warn("Loading the rightMargin failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    columnWidth = pageWidth - leftMargin - rightMargin;
    try {
        topMargin = properties.getInt("topMargin", 20);
    } catch (Exception e) {
        LOGGER.warn("Loading the topMargin failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        bottomMargin = properties.getInt("bottomMargin", 20);
    } catch (Exception e) {
        LOGGER.warn("Loading the bottomMargin failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }

    try {
        groupTextFirstLeftPadding = properties.getInt("groupTextFirstLeftPadding", 5);
    } catch (Exception e) {
        LOGGER.warn("Loading the groupTextFirstLeftPadding failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        groupTextLeftPaddingPace = properties.getInt("groupTextLeftPaddingPace", 20);
    } catch (Exception e) {
        LOGGER.warn("Loading the groupTextLeftPaddingPace failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        imageTopPadding = properties.getInt("imageTopPadding", 2);
    } catch (Exception e) {
        LOGGER.warn("Loading the imageTopPadding failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        imageBottomPadding = properties.getInt("imageBottomPadding", 2);
    } catch (Exception e) {
        LOGGER.warn("Loading the imageBottomPadding failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        textLeftPadding = properties.getInt("textLeftPadding", 3);
    } catch (Exception e) {
        LOGGER.warn("Loading the textLeftPadding failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        textRightPadding = properties.getInt("textRightPadding", 0);
    } catch (Exception e) {
        LOGGER.warn("Loading the textRightPadding failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }

    try {
        issueOverdueIconWidth = properties.getInt("issueOverdueIconWidth", 35);
    } catch (Exception e) {
        LOGGER.warn("Loading the issueOverdueIconWidth failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        budgetExpenseUnitWidth = properties.getInt("budgetExpenseUnitWidth", 35);
    } catch (Exception e) {
        LOGGER.warn("Loading the budgetExpenseUnitWidth failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }

    try {
        detailBandHeight = properties.getInt("detailBandHeight", 13);
    } catch (Exception e) {
        LOGGER.warn("Loading the detailBandHeight failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        groupBandHeight = properties.getInt("groupBandHeight", 13);
    } catch (Exception e) {
        LOGGER.warn("Loading the groupBandHeight failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        pageHeaderBandHeight = properties.getInt("pageHeaderBandHeight", 13);
    } catch (Exception e) {
        LOGGER.warn("Loading the pageHeaderBandHeight failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        detailFontSize = properties.getInt("detailFontSize", 9);
    } catch (Exception e) {
        LOGGER.warn("Loading the detailFontSize failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        groupFontSize = properties.getInt("groupFontSize", 9);
    } catch (Exception e) {
        LOGGER.warn("Loading the groupFontSize failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        pageHeaderFontSize = properties.getInt("pageHeaderFontSize", 9);
    } catch (Exception e) {
        LOGGER.warn("Loading the pageHeaderFontSize failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }

    try {
        scalingFactor = properties.getDouble("scalingFactor", 0.85);
    } catch (Exception e) {
        LOGGER.warn("Loading the scalingFactor failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        longFieldWidthGrid = properties.getInt("longFieldWidthGrid", 500);
    } catch (Exception e) {
        LOGGER.warn("Loading the longFieldWidthGrid failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        longFieldIsPlain = properties.getBoolean("longFieldIsPlain", true);
    } catch (Exception e) {
        LOGGER.warn("Loading the longFieldIsPlain failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        defaultFieldWidth = properties.getInt("defaultFieldWidth", 150);
    } catch (Exception e) {
        LOGGER.warn("Loading the defaultFieldWidth failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        showImageInGrid = properties.getBoolean("showImageInGrid", false);
    } catch (Exception e) {
        LOGGER.warn("Loading the showImageInGrid failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        showAllFieldsInGrid = properties.getBoolean("showAllFieldsInGrid", false);
    } catch (Exception e) {
        LOGGER.warn("Loading the showAllFieldsInGrid failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    try {
        logo = properties.getString("logo", "trackLogo.png").trim();
    } catch (Exception e) {
        LOGGER.warn("Loading the logo failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));

    }
}

From source file:com.softwarementors.extjs.djn.servlet.DirectJNgineServlet.java

protected void createDirectJNgineRouter(ServletConfig configuration) throws ServletException {
    assert configuration != null;

    Timer subtaskTimer = new Timer();
    GlobalConfiguration globalConfiguration = createGlobalConfiguration(configuration);
    String registryConfiguratorClassName = ServletUtils.getParameter(configuration, REGISTRY_CONFIGURATOR_CLASS,
            null);//  ww  w .  j  a va 2s . c o m
    if (logger.isInfoEnabled()) {
        String value = registryConfiguratorClassName;
        if (value == null) {
            value = "";
        }
        logger.info("Servlet GLOBAL configuration: " + REGISTRY_CONFIGURATOR_CLASS + "=" + value);
    }

    Class<? extends ServletRegistryConfigurator> registryConfiguratorClass = getRegistryConfiguratorClass(
            registryConfiguratorClassName);
    List<ApiConfiguration> apiConfigurations = createApiConfigurationsFromServletConfigurationApi(
            configuration);
    subtaskTimer.stop();
    subtaskTimer.logDebugTimeInMilliseconds("Djn initialization: Servlet Configuration Load time");

    subtaskTimer.restart();
    Registry registry = new Registry(globalConfiguration);
    Scanner scanner = new Scanner(registry);
    scanner.scanAndRegisterApiConfigurations(apiConfigurations);
    subtaskTimer.stop();
    subtaskTimer.logDebugTimeInMilliseconds("Djn initialization: Standard Api processing time");

    if (registryConfiguratorClass != null) {
        subtaskTimer.restart();
        performCustomRegistryConfiguration(registryConfiguratorClass, registry, configuration);
        subtaskTimer.stop();
        subtaskTimer.logDebugTimeInMilliseconds("Djn initialization: Custom Registry processing time");
    }

    subtaskTimer.restart();
    try {
        CodeFileGenerator.updateSource(registry, globalConfiguration.getCreateSourceFiles());
        subtaskTimer.stop();
        subtaskTimer.logDebugTimeInMilliseconds("Djn initialization: Api Files creation time");
    } catch (IOException ex) {
        ServletException e = new ServletException("Unable to create DirectJNgine API files", ex);
        logger.fatal(e.getMessage(), e);
        throw e;
    }

    subtaskTimer.restart();

    initializeRouter(globalConfiguration, registry);

    subtaskTimer.stop();
    subtaskTimer.logDebugTimeInMilliseconds("Djn initialization: Request Processor initialization time");
}

From source file:org.ireland.jnetty.dispatch.servlet.ServletConfigImpl.java

/**
 * Maps or exists if any of the patterns in urlPatterns already map to a different servlet
 * // w  w w  .  j  a  va 2s. c o  m
 * @param urlPatterns
 * @return a Set of patterns previously mapped to a different servlet
 */
@Override
public Set<String> addMapping(String... urlPatterns) {

    try {
        Set<String> conflictPattern = new HashSet<String>();

        // server/12t8 vs server/12uc
        for (String urlPattern : urlPatterns) {
            ServletMapping mapping = _servletMapper.getServletMapping(urlPattern);

            if (mapping == null) {
                continue;
            }

            String servletName = mapping.getServletConfig().getServletName();

            if (!_servletName.equals(servletName) && servletName != null) //urlPattern?(?urlPatternServlet)
            {
                if (debug) {
                    log.debug("programmatic addMapping for '" + urlPattern
                            + "' ignored because of existing servlet-mapping to '" + servletName + "'");
                }

                conflictPattern.add(urlPattern);
            }
        }

        if (conflictPattern.size() > 0) {
            return conflictPattern;
        }

        //ServletMappingServletContext
        ServletMapping mapping = _webApp.createNewServletMapping(this);

        for (String urlPattern : urlPatterns) {
            mapping.addURLPattern(urlPattern);
        }

        _webApp.addServletMapping(mapping);

        return Collections.unmodifiableSet(conflictPattern);
    } catch (ServletException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.emc.plants.web.servlets.AccountServlet.java

private void performTask(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String action = null;//w ww  . j  a  v a  2s.  c  om

    action = req.getParameter(Util.ATTR_ACTION);
    Util.debug("action=" + action);

    if (action.equals(ACTION_LOGIN)) {
        try {
            HttpSession session = req.getSession(true);
            String userid = req.getParameter("userid");
            String passwd = req.getParameter("passwd");
            String updating = req.getParameter(Util.ATTR_UPDATING);

            String results = null;
            if (Util.validateString(userid)) {
                results = login.verifyUserAndPassword(userid, passwd);
            } else {
                //user id was invalid, and may contain XSS attack
                results = "\nEmail address was invalid.";
                Util.debug("User id or email address was invalid. id=" + userid);
            }

            // If results have an error msg, return it, otherwise continue.
            if (results != null) {
                // Proliferate UPDATING flag if user is trying to update his account.
                if (updating.equals("true"))
                    req.setAttribute(Util.ATTR_UPDATING, "true");

                req.setAttribute(Util.ATTR_RESULTS, results);
                requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_LOGIN);
            } else {
                // If not logging in for the first time, then clear out the
                // session data for the old user.
                if (session.getAttribute(Util.ATTR_CUSTOMER) != null) {
                    session.removeAttribute(Util.ATTR_CART);
                    session.removeAttribute(Util.ATTR_CART_CONTENTS);
                    session.removeAttribute(Util.ATTR_CHECKOUT);
                    session.removeAttribute(Util.ATTR_ORDERKEY);
                }

                // Store customer userid in HttpSession.
                CustomerInfo customerInfo = login.getCustomerInfo(userid);
                session.setAttribute(Util.ATTR_CUSTOMER, customerInfo);
                Util.debug("updating=" + updating + "=");

                // Was customer trying to edit account information.
                if (updating.equals("true")) {
                    req.setAttribute(Util.ATTR_EDITACCOUNTINFO, customerInfo);

                    requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_ACCOUNT);
                } else {
                    // See if user was in the middle of checking out.
                    Boolean checkingOut = (Boolean) session.getAttribute(Util.ATTR_CHECKOUT);
                    Util.debug("checkingOut=" + checkingOut + "=");
                    if ((checkingOut != null) && (checkingOut.booleanValue())) {
                        Util.debug("must be checking out");
                        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_ORDERINFO);
                    } else {
                        Util.debug("must NOT be checking out");
                        String url;
                        String category = (String) session.getAttribute(Util.ATTR_CATEGORY);

                        // Default to plants
                        Util.debug("category : " + category);
                        if ((category == null) || (category.equals("null"))) {
                            url = Util.PAGE_PROMO;
                        } else {
                            url = Util.PAGE_SHOPPING;
                            req.setAttribute(Util.ATTR_INVITEMS,
                                    catalog.getItemsByCategory(Integer.parseInt(category)));
                        }

                        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
                    }
                }
            }
        } catch (ServletException e) {
            e.printStackTrace();
            req.setAttribute(Util.ATTR_RESULTS, "/nException occurred");
            throw e;
        } catch (Exception e) {
            req.setAttribute(Util.ATTR_RESULTS, "/nException occurred");
            e.printStackTrace();
            throw new ServletException(e.getMessage());
        }
    } else if (action.equals(ACTION_REGISTER)) {
        // Register a new user.
        //         try
        //         {
        String url;
        HttpSession session = req.getSession(true);

        String userid = req.getParameter("userid");
        String password = req.getParameter("passwd");
        String cpassword = req.getParameter("vpasswd");
        String firstName = req.getParameter("fname");
        String lastName = req.getParameter("lname");
        String addr1 = req.getParameter("addr1");
        String addr2 = req.getParameter("addr2");
        String addrCity = req.getParameter("city");
        String addrState = req.getParameter("state");
        String addrZip = req.getParameter("zip");
        String phone = req.getParameter("phone");

        //validate all user input
        //This could be done more eloquently using a framework such as Struts...
        if (!Util.validateString(userid)) {
            req.setAttribute(Util.ATTR_RESULTS, "Email address contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(firstName)) {
            req.setAttribute(Util.ATTR_RESULTS, "First Name contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(lastName)) {
            req.setAttribute(Util.ATTR_RESULTS, "Last Name contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(addr1)) {
            req.setAttribute(Util.ATTR_RESULTS, "Address Line 1 contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(addr2)) {
            req.setAttribute(Util.ATTR_RESULTS, "Address Line 2 contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(addrCity)) {
            req.setAttribute(Util.ATTR_RESULTS, "City contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(addrState)) {
            req.setAttribute(Util.ATTR_RESULTS, "State contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(addrZip)) {
            req.setAttribute(Util.ATTR_RESULTS, "Zip contains invalid characters.");
            url = Util.PAGE_REGISTER;
        } else if (!Util.validateString(phone)) {
            req.setAttribute(Util.ATTR_RESULTS, "Phone Number contains invalid characters.");
            url = Util.PAGE_REGISTER;
        }
        // Make sure passwords match.
        else if (!password.equals(cpassword)) {
            req.setAttribute(Util.ATTR_RESULTS, "Passwords do not match.");
            url = Util.PAGE_REGISTER;
        } else {
            // Create the new user.
            CustomerInfo customerInfo = login.createNewUser(userid, password, firstName, lastName, addr1, addr2,
                    addrCity, addrState, addrZip, phone);

            if (customerInfo != null) {
                // Store customer info in HttpSession.
                session.setAttribute(Util.ATTR_CUSTOMER, customerInfo);

                // See if user was in the middle of checking out.
                Boolean checkingOut = (Boolean) session.getAttribute(Util.ATTR_CHECKOUT);
                if ((checkingOut != null) && (checkingOut.booleanValue())) {
                    url = Util.PAGE_ORDERINFO;
                } else {
                    String category = (String) session.getAttribute(Util.ATTR_CATEGORY);

                    // Default to plants
                    if (category == null) {
                        url = Util.PAGE_PROMO;
                    } else {
                        url = Util.PAGE_SHOPPING;
                        req.setAttribute(Util.ATTR_INVITEMS,
                                catalog.getItemsByCategory(Integer.parseInt(category)));
                    }
                }
            } else {
                url = Util.PAGE_REGISTER;
                req.setAttribute(Util.ATTR_RESULTS, "New user NOT created!");
            }
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
        //         }
        //         catch (CreateException e) { }
    } else if (action.equals(ACTION_ACCOUNT)) {
        String url;
        HttpSession session = req.getSession(true);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);
        if (customerInfo == null) {
            url = Util.PAGE_LOGIN;
            req.setAttribute(Util.ATTR_UPDATING, "true");
            req.setAttribute(Util.ATTR_RESULTS, "\nYou must login first.");
        } else {
            url = Util.PAGE_ACCOUNT;
            req.setAttribute(Util.ATTR_EDITACCOUNTINFO, customerInfo);
        }
        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
    } else if (action.equals(ACTION_ACCOUNTUPDATE)) {
        //         try
        //         {
        String url;
        HttpSession session = req.getSession(true);
        CustomerInfo customerInfo = (CustomerInfo) session.getAttribute(Util.ATTR_CUSTOMER);

        String userid = customerInfo.getCustomerID();
        String firstName = req.getParameter("fname");
        String lastName = req.getParameter("lname");
        String addr1 = req.getParameter("addr1");
        String addr2 = req.getParameter("addr2");
        String addrCity = req.getParameter("city");
        String addrState = req.getParameter("state");
        String addrZip = req.getParameter("zip");
        String phone = req.getParameter("phone");

        // Create the new user.
        customerInfo = login.updateUser(userid, firstName, lastName, addr1, addr2, addrCity, addrState, addrZip,
                phone);
        // Store updated customer info in HttpSession.
        session.setAttribute(Util.ATTR_CUSTOMER, customerInfo);

        // See if user was in the middle of checking out.
        Boolean checkingOut = (Boolean) session.getAttribute(Util.ATTR_CHECKOUT);
        if ((checkingOut != null) && (checkingOut.booleanValue())) {
            url = Util.PAGE_ORDERINFO;
        } else {
            String category = (String) session.getAttribute(Util.ATTR_CATEGORY);

            // Default to plants
            if (category == null) {
                url = Util.PAGE_PROMO;
            } else {
                url = Util.PAGE_SHOPPING;
                req.setAttribute(Util.ATTR_INVITEMS, catalog.getItemsByCategory(Integer.parseInt(category)));
            }
        }

        requestDispatch(getServletConfig().getServletContext(), req, resp, url);
        //         }
        //         catch (CreateException e) { }
    } else if (action.equals(ACTION_SETLOGGING)) {
        String debugSetting = req.getParameter("logging");
        if ((debugSetting == null) || (!debugSetting.equals("debug")))
            Util.setDebug(false);
        else
            Util.setDebug(true);

        requestDispatch(getServletConfig().getServletContext(), req, resp, Util.PAGE_HELP);
    }
}

From source file:org.openbravo.erpCommon.ad_forms.RequisitionToOrder.java

private OBError processPurchaseOrder(VariablesSecureApp vars, String strSelected, String strOrderDate,
        String strVendor, String strPriceListId, String strOrg, String strWarehouse)
        throws IOException, ServletException {
    StringBuffer textMessage = new StringBuffer();
    Connection conn = null;/*from   ww  w .  ja v a  2s . co m*/

    OBError myMessage = null;
    myMessage = new OBError();
    myMessage.setTitle("");

    String strPriceListVersionId = RequisitionToOrderData.getPricelistVersion(this, strPriceListId,
            strOrderDate);
    RequisitionToOrderData[] noprice = RequisitionToOrderData.selectNoPrice(this, vars.getLanguage(),
            strPriceListVersionId, strSelected);
    if (noprice != null && noprice.length > 0) {
        textMessage.append(Utility.messageBD(this, "LinesWithNoPrice", vars.getLanguage())).append("<br><ul>");
        for (int i = 0; i < noprice.length; i++) {
            textMessage.append("<li>").append(noprice[i].product);
        }
        textMessage.append("</ul>");
        myMessage.setType("Error");
        myMessage.setMessage(textMessage.toString());
        return myMessage;
    }

    RequisitionToOrderData[] data1 = RequisitionToOrderData.selectVendorData(this, strVendor);
    if (data1[0].poPaymenttermId == null || data1[0].poPaymenttermId.equals("")) {
        myMessage.setType("Error");
        myMessage.setMessage(Utility.messageBD(this, "VendorWithNoPaymentTerm", vars.getLanguage()));
        return myMessage;
    }
    if ("".equals(RequisitionToOrderData.cBPartnerLocationId(this, strVendor))) {
        myMessage.setType("Error");
        myMessage.setMessage(Utility.messageBD(this, "NoBPLocation", vars.getLanguage()));
        return myMessage;
    }

    try {
        conn = getTransactionConnection();
        String strCOrderId = SequenceIdData.getUUID();
        String docTargetType = RequisitionToOrderData.cDoctypeTarget(conn, this, vars.getClient(), strOrg);
        String strDocumentNo = Utility.getDocumentNo(this, vars, "", "C_Order", docTargetType, docTargetType,
                false, true);
        String cCurrencyId = RequisitionToOrderData.selectCurrency(this, strPriceListId);

        try {
            RequisitionToOrderData.insertCOrder(conn, this, strCOrderId, vars.getClient(), strOrg,
                    vars.getUser(), strDocumentNo, "DR", "CO", "0", docTargetType, strOrderDate, strOrderDate,
                    strOrderDate, strVendor, RequisitionToOrderData.cBPartnerLocationId(this, strVendor),
                    RequisitionToOrderData.billto(this, strVendor).equals("")
                            ? RequisitionToOrderData.cBPartnerLocationId(this, strVendor)
                            : RequisitionToOrderData.billto(this, strVendor),
                    cCurrencyId, isAlternativeFinancialFlow() ? "P" : data1[0].paymentrulepo,
                    data1[0].poPaymenttermId, data1[0].invoicerule.equals("") ? "I" : data1[0].invoicerule,
                    data1[0].deliveryrule.equals("") ? "A" : data1[0].deliveryrule, "I",
                    data1[0].deliveryviarule.equals("") ? "D" : data1[0].deliveryviarule, strWarehouse,
                    strPriceListId, "", "", "", data1[0].poPaymentmethodId);
        } catch (ServletException ex) {
            myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
            releaseRollbackConnection(conn);
            return myMessage;
        }

        int line = 0;
        String strCOrderlineID = "";
        BigDecimal qty = new BigDecimal("0");
        BigDecimal qtyOrder = new BigDecimal("0");
        BigDecimal quantity = new BigDecimal("0");
        BigDecimal quantityOrder = new BigDecimal("0");
        boolean insertLine = false;

        RequisitionToOrderData[] lines = RequisitionToOrderData.linesToOrder(this, strOrderDate, strOrg,
                strWarehouse,
                RequisitionToOrderData.billto(this, strVendor).equals("")
                        ? RequisitionToOrderData.cBPartnerLocationId(this, strVendor)
                        : RequisitionToOrderData.billto(this, strVendor),
                RequisitionToOrderData.cBPartnerLocationId(this, strVendor), cCurrencyId, strPriceListVersionId,
                strSelected);
        for (int i = 0; lines != null && i < lines.length; i++) {
            if ("".equals(lines[i].tax)) {
                RequisitionLine rl = OBDal.getInstance().get(RequisitionLine.class,
                        lines[i].mRequisitionlineId);
                myMessage.setType("Error");
                myMessage.setMessage(String.format(OBMessageUtils.messageBD("NoTaxRequisition"), rl.getLineNo(),
                        rl.getRequisition().getDocumentNo()));
                releaseRollbackConnection(conn);
                return myMessage;
            }

            if (i == 0)
                strCOrderlineID = SequenceIdData.getUUID();
            if (i == lines.length - 1) {
                insertLine = true;
                qtyOrder = qty;
                quantityOrder = quantity;
            } else if (!lines[i + 1].mProductId.equals(lines[i].mProductId)
                    || !lines[i + 1].mAttributesetinstanceId.equals(lines[i].mAttributesetinstanceId)
                    || !lines[i + 1].description.equals(lines[i].description)
                    || !lines[i + 1].priceactual.equals(lines[i].priceactual)
                    || !StringUtils.equals(lines[i + 1].mProductUomId, lines[i].mProductUomId)) {
                insertLine = true;
                qtyOrder = qty;
                qty = new BigDecimal(0);
                quantityOrder = quantity;
                quantity = new BigDecimal(0);
            } else {
                qty = qty.add(new BigDecimal(lines[i].lockqty));
                quantity = quantity.add(new BigDecimal(lines[i].quantityorder));
            }
            lines[i].cOrderlineId = strCOrderlineID;
            if (insertLine) {
                insertLine = false;
                line += 10;
                BigDecimal qtyAux = new BigDecimal(lines[i].lockqty);
                qtyOrder = qtyOrder.add(qtyAux);
                BigDecimal quantityAux = new BigDecimal(lines[i].quantityorder);
                quantityOrder = quantityOrder.add(quantityAux);
                if (log4j.isDebugEnabled())
                    log4j.debug("Lockqty: " + lines[i].lockqty + " qtyorder: " + qtyOrder.toPlainString()
                            + " new BigDecimal: " + (new BigDecimal(lines[i].lockqty)).toString() + " qtyAux: "
                            + qtyAux.toString());

                try {
                    RequisitionToOrderData.insertCOrderline(conn, this, strCOrderlineID, vars.getClient(),
                            strOrg, vars.getUser(), strCOrderId, Integer.toString(line), strVendor,
                            RequisitionToOrderData.cBPartnerLocationId(this, strVendor), strOrderDate,
                            lines[i].needbydate, lines[i].description, lines[i].mProductId,
                            lines[i].mAttributesetinstanceId, strWarehouse, lines[i].mProductUomId,
                            lines[i].cUomId,
                            quantityOrder != null && BigDecimal.ZERO.compareTo(quantityOrder) != 0
                                    ? quantityOrder.toPlainString()
                                    : "",
                            qtyOrder.toPlainString(), cCurrencyId, lines[i].pricelist, lines[i].priceactual,
                            strPriceListId, lines[i].pricelimit, lines[i].tax, "", lines[i].discount,
                            lines[i].grossUnit, lines[i].grossAmt);
                } catch (ServletException ex) {
                    myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                    releaseRollbackConnection(conn);
                    return myMessage;
                }

                strCOrderlineID = SequenceIdData.getUUID();
            }
        }

        unlockRequisitionLines(vars, strSelected);
        for (int i = 0; lines != null && i < lines.length; i++) {
            String strRequisitionOrderId = SequenceIdData.getUUID();
            try {
                RequisitionToOrderData.insertRequisitionOrder(conn, this, strRequisitionOrderId,
                        vars.getClient(), strOrg, vars.getUser(), lines[i].mRequisitionlineId,
                        lines[i].cOrderlineId, lines[i].lockqty);
            } catch (ServletException ex) {
                myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
                releaseRollbackConnection(conn);
                return myMessage;
            }
            if (lines[i].toClose.equals("Y"))
                RequisitionToOrderData.requisitionStatus(conn, this, lines[i].mRequisitionlineId,
                        vars.getUser());
        }

        OBError myMessageAux = cOrderPost(conn, vars, strCOrderId);
        releaseCommitConnection(conn);
        String strWindowName = WindowTabsData.selectWindowInfo(this, vars.getLanguage(), "181");
        textMessage.append(strWindowName).append(" ").append(strDocumentNo).append(": ");
        if (myMessageAux.getMessage().equals(""))
            textMessage.append(Utility.messageBD(this, "Success", vars.getLanguage()));
        else
            textMessage.append(myMessageAux.getMessage());

        myMessage.setType(myMessageAux.getType());
        myMessage.setMessage(textMessage.toString());
        return myMessage;
    } catch (Exception e) {
        try {
            if (conn != null)
                releaseRollbackConnection(conn);
        } catch (Exception ignored) {
        }
        e.printStackTrace();
        log4j.warn("Rollback in transaction");
        myMessage.setType("Error");
        myMessage.setMessage(Utility.messageBD(this, "ProcessRunError", vars.getLanguage()));
        return myMessage;
    }
}

From source file:ch.entwine.weblounge.dispatcher.impl.handler.FeedRequestHandlerImpl.java

/**
 * Compiles the feed based on feed type, version and request parameters.
 * /*  www .j  a va 2  s. c  o m*/
 * @param feedType
 *          feed type
 * @param feedVersion
 *          feed version
 * @param site
 *          the site
 * @param request
 *          the request
 * @param response
 *          the response
 * @return the feed object
 * @throws ContentRepositoryException
 *           if the content repository can't be accessed
 */
private SyndFeed createFeed(String feedType, String feedVersion, Site site, WebloungeRequest request,
        WebloungeResponse response) throws ContentRepositoryException {

    // Extract the subjects. The parameter may be specified multiple times
    // and add more than one subject by separating them using a comma.
    String[] subjectParameter = request.getParameterValues(PARAM_SUBJECT);
    List<String> subjects = new ArrayList<String>();
    if (subjectParameter != null) {
        for (String parameter : subjectParameter) {
            for (String subject : parameter.split(",")) {
                if (StringUtils.isNotBlank(subject))
                    subjects.add(StringUtils.trim(subject));
            }
        }
    }

    // How many entries do we need?
    int limit = DEFAULT_LIMIT;
    String limitParameter = StringUtils.trimToNull(request.getParameter(PARAM_LIMIT));
    if (limitParameter != null) {
        try {
            limit = Integer.parseInt(limitParameter);
        } catch (Throwable t) {
            logger.debug("Non parseable number {} specified as limit", limitParameter);
            limit = DEFAULT_LIMIT;
        }
    }

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
        logger.warn("No content repository found for site '{}'", site);
        return null;
    } else if (contentRepository.isIndexing()) {
        logger.debug("Content repository of site '{}' is currently being indexed", site);
        DispatchUtils.sendServiceUnavailable(request, response);
        return null;
    }

    // User and language
    Language language = request.getLanguage();
    // User user = request.getUser();

    // Determine the feed type
    feedType = feedType.toLowerCase() + "_" + feedVersion;
    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType(feedType);
    feed.setLink(request.getRequestURL().toString());
    feed.setTitle(site.getName());
    feed.setDescription(site.getName());
    feed.setLanguage(language.getIdentifier());
    feed.setPublishedDate(new Date());

    // TODO: Add more feed metadata, ask site

    SearchQuery query = new SearchQueryImpl(site);
    query.withVersion(Resource.LIVE);
    query.withTypes(Page.TYPE);
    query.withLimit(limit);
    query.sortByPublishingDate(Order.Descending);
    for (String subject : subjects) {
        query.withSubject(subject);
    }

    // Load the result and add feed entries
    SearchResult result = contentRepository.find(query);
    List<SyndEntry> entries = new ArrayList<SyndEntry>();
    int items = Math.min(limit, result.getItems().length);

    for (int i = 0; i < items; i++) {
        SearchResultItem item = result.getItems()[i];

        // Get the page
        PageSearchResultItem pageItem = (PageSearchResultItem) item;
        Page page = pageItem.getPage();

        // TODO: Can the page be accessed?

        // Set the page's language to the feed language
        page.switchTo(language);

        // Tag the cache entry
        response.addTag(CacheTag.Resource, page.getIdentifier());

        // If this is to become the most recent entry, let's set the feed's
        // modification date to be that of this entry
        if (entries.size() == 0) {
            feed.setPublishedDate(page.getPublishFrom());
        }

        // Create the entry
        SyndEntry entry = new SyndEntryImpl();
        entry.setPublishedDate(page.getPublishFrom());
        entry.setUpdatedDate(page.getModificationDate());
        entry.setLink(site.getHostname(request.getEnvironment()).toExternalForm() + item.getUrl().getLink());
        entry.setAuthor(page.getCreator().getName());
        entry.setTitle(page.getTitle());
        entry.setUri(page.getIdentifier());

        // Categories
        if (page.getSubjects().length > 0) {
            List<SyndCategory> categories = new ArrayList<SyndCategory>();
            for (String subject : page.getSubjects()) {
                SyndCategory category = new SyndCategoryImpl();
                category.setName(subject);
                categories.add(category);
            }
            entry.setCategories(categories);
        }

        // Try to render the preview pagelets and write them to the feed
        List<SyndContent> entryContent = new ArrayList<SyndContent>();
        Composer composer = new ComposerImpl("preview", page.getPreview());
        StringBuffer renderedContent = new StringBuffer();

        for (Pagelet pagelet : composer.getPagelets()) {
            Module module = site.getModule(pagelet.getModule());
            PageletRenderer renderer = null;
            if (module == null) {
                logger.warn("Skipping pagelet {} in feed due to missing module '{}'", pagelet,
                        pagelet.getModule());
                continue;
            }

            renderer = module.getRenderer(pagelet.getIdentifier());
            if (renderer == null) {
                logger.warn("Skipping pagelet {} in feed due to missing renderer '{}/{}'",
                        new Object[] { pagelet, pagelet.getModule(), pagelet.getIdentifier() });
                continue;
            }

            URL rendererURL = renderer.getRenderer(RendererType.Feed.toString());
            Environment environment = request.getEnvironment();
            if (rendererURL == null)
                rendererURL = renderer.getRenderer();
            if (rendererURL != null) {
                String pageletContent = null;
                try {
                    pagelet.switchTo(language);
                    pageletContent = loadContents(rendererURL, site, page, composer, pagelet, environment);
                    renderedContent.append(pageletContent);
                } catch (ServletException e) {
                    logger.warn("Error processing the pagelet renderer at {}: {}", rendererURL, e.getMessage());
                    DispatchUtils.sendInternalError(request, response);
                } catch (IOException e) {
                    logger.warn("Error processing the pagelet renderer at {}: {}", rendererURL, e.getMessage());
                    DispatchUtils.sendInternalError(request, response);
                }
            }
        }

        if (renderedContent.length() > 0) {
            SyndContent content = new SyndContentImpl();
            content.setType("text/html");
            content.setMode("escaped");
            content.setValue(renderedContent.toString());
            entryContent.add(content);
            entry.setContents(entryContent);
        }

        entries.add(entry);
    }

    feed.setEntries(entries);

    return feed;
}

From source file:org.ireland.jnetty.dispatch.servlet.ServletConfigImpl.java

protected ServletException error(String msg) {
    ServletException e;

    if (_location != null)
        e = new ServletException(_location + msg);
    else//from   w  ww.  j  a v a 2  s  .  c o  m
        e = new ServletException(msg);

    log.warn(e.getMessage());

    return e;
}

From source file:org.ireland.jnetty.dispatch.servlet.ServletConfigImpl.java

protected ServletException error(String msg, Throwable e) {
    ServletException e1;

    if (_location != null)
        e1 = new ServletException(_location + msg, e);
    else/*  ww  w.  ja va  2  s.  c  o m*/
        e1 = new ServletException(msg, e);

    log.warn(e1.getMessage());

    return e1;
}

From source file:de.innovationgate.wgpublisher.filter.WGAFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    WGARequestInformation info = new WGARequestInformation();
    try {/* w w  w. j ava 2 s  . c  om*/
        info.setStartTime(System.currentTimeMillis());
        info.setThread(Thread.currentThread());
        request.setAttribute(WGARequestInformation.REQUEST_ATTRIBUTENAME, info);

        _wgaFilterChain.init(request, chain);

        _currentRequests.put(request, info);

        // F000037B2
        if (_core.getCharacterEncoding() != null) {
            request.setCharacterEncoding(_core.getCharacterEncoding());
            // B000041DA
            response.setCharacterEncoding(_core.getCharacterEncoding());
        }

        // add/ delete jvmRoute
        String lbRoute = _core.getClusterService().getLBRoute();
        if (lbRoute != null && !lbRoute.trim().equals("")) {
            WGCookie jvmRouteCookie = new WGCookie(COOKIE_NAME_LBROUTE, lbRoute);
            jvmRouteCookie.setPath("/");
            jvmRouteCookie.setMaxAge(-1);
            jvmRouteCookie.addCookieHeader((HttpServletResponse) response);
        } else {
            Cookie cookie = getCookie((HttpServletRequest) request, COOKIE_NAME_LBROUTE);
            if (cookie != null) {
                WGCookie jvmRouteCookie = WGCookie.from(cookie);
                jvmRouteCookie.setMaxAge(0);
                jvmRouteCookie.addCookieHeader((HttpServletResponse) response);
            }
        }

        RequestWrapper wrappedRequest = createRequestWrapper(response, (HttpServletRequest) request);
        /*
         *  #00005078: don't store original URL. Store converted URL instead.
         *  Will be used in WGA.urlBuilder() and other sources 
         */
        request.setAttribute(REQATTRIB_ORIGINAL_URL, wrappedRequest.getRequestURL().toString());
        request.setAttribute(REQATTRIB_ORIGINAL_URI, wrappedRequest.getRequestURI());
        request.setAttribute(REQATTRIB_ORIGINAL_QUERYSTRING, wrappedRequest.getQueryString());

        FinalCharacterEncodingResponseWrapper wrappedResponse = createResponseWrapper(response, wrappedRequest);

        _holdRequestsLock.readLock().lock();
        try {
            _wgaFilterChain.doFilter(wrappedRequest, wrappedResponse);
        } finally {
            _holdRequestsLock.readLock().unlock();
        }

        info.setStatusCode(wrappedResponse.getStatusCode());
        info.setStatusMessage(wrappedResponse.getStatusMessage());

        AbstractWGAHttpSessionManager sessionManager = _core.getHttpSessionManager();
        if (sessionManager != null) {
            sessionManager.requestFinished(wrappedRequest, wrappedResponse);
        }
    } catch (ServletException e) {
        info.setStatusCode(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        info.setStatusMessage(e.getMessage());
        _core.getLog().error("Internal Server Error.", e);
        throw e;
    } finally {
        info.setEndTime(System.currentTimeMillis());
        try {
            WGALoggerWrapper logger = _core.getAccessLogger();
            if (logger != null) {
                logger.logRequest(request);
            }
        } catch (Exception e) {
            _core.getLog().error("Unable to log request.", e);
        }

        WGFactory.getInstance().closeSessions();

        if (!Boolean.TRUE.equals(request.getAttribute(WGPDeployer.REQATTRIB_TML_DEPLOYED))
                && info.getEndTime() > info.getStartTime() + REQUEST_LENGTH_NOTIFICATION_THRESHOLD) {

            String uri = ((HttpServletRequest) request).getRequestURI();
            Problem.Vars vars = Problem.var("reqinfo", info)
                    .var("completeurl", ((HttpServletRequest) request).getRequestURL().toString())
                    .var("host", ((HttpServletRequest) request).getServerName()).var("uri", uri);

            String problemKey = "requestProblem.longRequest#" + uri;

            if (info.getDatabase() != null) {
                _core.getProblemRegistry()
                        .addProblem(Problem.create(new FilterRequestOccasion(),
                                new DatabaseScope(info.getDatabase().getDbReference()), problemKey,
                                ProblemSeverity.LOW, vars));
            } else {
                _core.getProblemRegistry().addProblem(
                        Problem.create(new FilterRequestOccasion(), problemKey, ProblemSeverity.LOW, vars));
            }
        }

        // close opened lucene-resultsets
        LuceneManager luceneManager = _core.getLuceneManager();
        if (luceneManager != null) {
            luceneManager.closeOpenedResultSets();
        }

        _currentRequests.remove(request);
    }
}

From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java

protected LookupResult lookupNoCache(HttpServletRequest req, String reqPath) {
    String subject = null, subjectPath = null, jsPath = null, path = null, targetPath = null;
    boolean isVirtualUrl = false, jsPathFound = false;
    URL targetUrl = null;//from  w  w  w  .ja  va  2 s. c  o m

    try {
        WebTopApp wta = WebTopApp.get(req);

        // Builds a convenient URL for the servlet relative URL
        try {
            //String reqPath = req.getPathInfo();
            //logger.trace("Requested path [{}]", reqPath);

            Matcher matcher = PATTERN_VIRTUAL_URL.matcher(reqPath);
            if (matcher.matches()) {
                // Matches URLs like: /{service.id}/{service.version}/{remaining.url.part}
                // Eg. /com.sonicle.webtop.core/5.1.1/laf/default/service.css
                //   {service.id} -> com.sonicle.webtop.core
                //   {service.version} -> 5.1.1
                //   {remaining.url.part} -> laf/default/service.css
                isVirtualUrl = true;
                subject = matcher.group(1);
                path = matcher.group(3);

                if (!wta.getServiceManager().hasService(subject)) {
                    return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
                }
                targetUrl = new URL("http://fake/client/" + subject + "/" + path);

            } else {
                isVirtualUrl = false;
                String[] urlParts = splitPath(reqPath);
                subject = urlParts[0];
                jsPath = wta.getServiceManager().getServiceJsPath(subject);
                jsPathFound = (jsPath != null);
                subjectPath = (jsPathFound) ? jsPath : urlParts[0];
                path = urlParts[1];

                targetUrl = new URL("http://fake/" + subjectPath + "/" + path);
            }
            targetPath = targetUrl.getPath();

            //logger.trace("Translated path [{}]", translPath);
            if (isForbidden(targetPath))
                return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden");

        } catch (MalformedURLException ex1) {
            return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
        }

        if (!isVirtualUrl && path.startsWith("images")) {
            // Addresses domain public images
            // URLs like "/{domainPublicName}/images/{relativePathToFile}"
            // Eg.   "/1bbc048f/images/login.png"
            //      "/1bbc048f/images/sub/login.png"
            WebTopManager wtMgr = wta.getWebTopManager();

            String domainId = wtMgr.publicNameToDomainId(subject);
            if (StringUtils.isBlank(domainId)) {
                // We must support old-style URL using {domainInternetName}
                // instead of {domainPublicName}
                // Eg.   "/sonicle.com/images/login.png"
                domainId = wtMgr.internetNameToDomain(subject);
            }
            if (StringUtils.isBlank(domainId)) {
                return new Error(HttpServletResponse.SC_BAD_REQUEST, "Bad Request");
            }

            return lookupDomainImage(req, targetUrl, domainId);

        } else if (isVirtualUrl && subject.equals(CoreManifest.ID)
                && path.equals("resources/images/login.png")) {
            // Addresses login image
            // URLs like "/{serviceId}/{serviceVersion}/resources/images/login.png"
            // Eg.   "/com.sonicle.webtop.core/5.0.0/images/login.png"
            return lookupLoginImage(req, targetUrl);

        } else if (isVirtualUrl && subject.equals(CoreManifest.ID) && path.equals("resources/license.html")) {
            // Addresses licence page
            // URLs like "/{serviceId}/{serviceVersion}/resources/license.html"
            return lookupLicense(req, targetUrl);

        } else if (!isVirtualUrl && path.startsWith("whatsnew/")) {
            return lookupWhatsnew(req, targetUrl, path, subject);
        } else {
            if (StringUtils.endsWith(targetPath, ".js")) {
                String sessionId = ServletHelper.getSessionID(req);
                if (StringUtils.startsWith(path, "resources/vendor")
                        || StringUtils.startsWith(path, "resources/libs")) {
                    // If targets lib folder, simply return requested file without handling debug versions
                    return lookupJs(req, targetUrl, false);

                } else if (StringUtils.startsWith(path, "boot/")) {
                    return lookupJs(req, targetUrl, isJsDebug());

                } else if (StringUtils.startsWith(FilenameUtils.getBaseName(path), "Locale")) {
                    return lookupLocaleJs(req, targetUrl, subject);

                } else {
                    return lookupJs(req, targetUrl, isJsDebug());
                }

            } else if (StringUtils.startsWith(path, "laf")) {
                return lookupLAF(req, targetUrl, path, subject, subjectPath);

            } else {
                return lookupDefault(req, isVirtualUrl ? ClientCaching.YES : ClientCaching.AUTO, targetUrl);
            }
        }

    } catch (ServletException ex) {
        return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage());
    }
}