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:org.ireland.jnetty.webapp.WebApp.java

/**
 * Adds a new or augments existing registration
 * //from  w ww  . ja  v a 2 s.  c om
 * @since 3.0
 */
private ServletRegistration.Dynamic addServlet(String servletName, String servletClassName,
        Class<? extends Servlet> servletClass, Servlet servlet) {

    try {
        ServletConfigImpl config = (ServletConfigImpl) getServletRegistration(servletName);

        if (config == null) {
            config = createNewServletConfig();

            config.setServletName(servletName);
            config.setServletClass(servletClassName);
            config.setServletClass(servletClass);
            config.setServlet(servlet);

            addServlet(config);
        } else {
            if (config.getClassName() == null)
                config.setServletClass(servletClassName);

            if (config.getServletClass() == null)
                config.setServletClass(servletClass);

            if (config.getServlet() == null)
                config.setServlet(servlet);
        }

        if (debug) {
            log.debug("dynamic servlet added [name: '" + servletName + "', class: '" + servletClassName
                    + "'] (in " + this + ")");
        }

        return config;
    } catch (ServletException e) {
        // spec declares no throws so far
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.platform.web.common.requestcontroller.filter.NuxeoRequestControllerFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;

    if (log.isDebugEnabled()) {
        log.debug(doFormatLogMessage(httpRequest, "Entering NuxeoRequestController filter"));
    }/*from w  w  w.  j  a va 2s . c o m*/

    ServletContext servletContext = httpRequest.getServletContext();
    ServletHelper.setServletContext(servletContext);

    doInitIfNeeded();

    RequestFilterConfig config = rcm.getConfigForRequest(httpRequest);

    boolean useSync = config.needSynchronization();
    boolean useTx = config.needTransaction();

    // Add cache header if needed
    if (httpRequest.getMethod().equals("GET")) {
        boolean isCached = config.isCached();
        if (isCached) {
            addCacheHeader(httpResponse, config.isPrivate(), config.getCacheTime());
        }
    }

    if (!useSync && !useTx) {
        if (log.isDebugEnabled()) {
            log.debug(doFormatLogMessage(httpRequest,
                    "Existing NuxeoRequestController filter: nothing to be done"));
        }

        try {
            chain.doFilter(request, response);
        } catch (ServletException e) {
            if (DownloadHelper.isClientAbortError(e)) {
                DownloadHelper.logClientAbort(e);
            } else {
                throw e;
            }
        }
        return;
    }

    if (log.isDebugEnabled()) {
        log.debug(
                doFormatLogMessage(httpRequest, "Handling request with tx=" + useTx + " and sync=" + useSync));
    }

    boolean sessionSynched = false;
    if (useSync) {
        sessionSynched = simpleSyncOnSession(httpRequest);
    }
    boolean txStarted = false;
    try {
        if (useTx) {
            txStarted = ServletHelper.startTransaction(httpRequest);
            if (txStarted) {
                if (config.needTransactionBuffered()) {
                    response = new BufferingHttpServletResponse(httpResponse);
                }
            }
        }
        chain.doFilter(request, response);
    } catch (RuntimeException | IOException | ServletException e) {
        if (txStarted) {
            if (log.isDebugEnabled()) {
                log.debug(doFormatLogMessage(httpRequest, "Marking transaction for RollBack"));
            }
            TransactionHelper.setTransactionRollbackOnly();
        }
        if (DownloadHelper.isClientAbortError(e)) {
            DownloadHelper.logClientAbort(e);
        } else {
            log.error(doFormatLogMessage(httpRequest, "Unhandled error was caught by the Filter"), e);
            throw new ServletException(e);
        }
    } finally {
        if (txStarted) {
            try {
                TransactionHelper.commitOrRollbackTransaction();
            } catch (TransactionRuntimeException e) {
                // commit failed, report this to the client before stopping buffering
                ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                        e.getMessage());
                throw e;
            } finally {
                if (config.needTransactionBuffered()) {
                    ((BufferingHttpServletResponse) response).stopBuffering();
                }
            }
        }
        if (sessionSynched) {
            simpleReleaseSyncOnSession(httpRequest);
        }

        ServletHelper.removeServletContext();

        if (log.isDebugEnabled()) {
            log.debug(doFormatLogMessage(httpRequest, "Exiting NuxeoRequestController filter"));
        }
    }
}

From source file:org.openbravo.client.application.AlertManagementActionHandler.java

private JSONArray getAlertRules() {
    // Get alert rules visible for context's the role/user.
    StringBuffer whereClause = new StringBuffer();
    whereClause.append(" as ar ");
    whereClause/*from   ww  w.ja  v a 2 s .c  om*/
            .append("\nwhere exists (select 1 from ar." + AlertRule.PROPERTY_ADALERTRECIPIENTLIST + " as arr");
    whereClause.append("\n    where arr." + AlertRecipient.PROPERTY_USERCONTACT + ".id = :user");
    whereClause.append("\n      or (");
    whereClause.append("arr." + AlertRecipient.PROPERTY_USERCONTACT + " is null");
    whereClause.append("\n          and arr." + AlertRecipient.PROPERTY_ROLE + ".id = :role))");

    OBQuery<AlertRule> alertRulesQuery = OBDal.getInstance().createQuery(AlertRule.class,
            whereClause.toString());
    alertRulesQuery.setNamedParameter("user", OBContext.getOBContext().getUser().getId());
    alertRulesQuery.setNamedParameter("role", OBContext.getOBContext().getRole().getId());

    JSONArray alertRules = new JSONArray();
    try {
        if (alertRulesQuery.count() > 0) {
            for (AlertRule alertRule : alertRulesQuery.list()) {
                JSONObject alertRuleJson = null;

                // Adding alert rule if it has not filter clause. In case it has, it will be added only in
                // case it returns data after applying the filter clause.
                if (alertRule.getFilterClause() == null) {
                    alertRuleJson = new JSONObject();
                    alertRuleJson.put("name", alertRule.getIdentifier());
                    alertRuleJson.put("alertRuleId", alertRule.getId());
                    if (alertRule.getTab() != null) {
                        alertRuleJson.put("tabId", alertRule.getTab().getId());
                    } else {
                        alertRuleJson.put("tabId", "");
                    }
                }

                String filterClause = null;
                if (alertRule.getFilterClause() != null) {
                    try {
                        filterClause = new UsedByLink().getWhereClause(
                                RequestContext.get().getVariablesSecureApp(), "", alertRule.getFilterClause());
                    } catch (ServletException e) {
                        throw new IllegalStateException(e);
                    }
                    final String sql = "select * from AD_ALERT where ISACTIVE='Y'" + " AND AD_CLIENT_ID "
                            + OBDal.getInstance().getReadableClientsInClause() + " AND AD_ORG_ID "
                            + OBDal.getInstance().getReadableOrganizationsInClause()
                            + " AND AD_ALERTRULE_ID = ? " + (filterClause == null ? "" : filterClause);
                    final SQLQuery sqlQuery = OBDal.getInstance().getSession().createSQLQuery(sql)
                            .addEntity(Alert.ENTITY_NAME);
                    sqlQuery.setParameter(0, alertRule.getId());

                    try {
                        log4j.debug("Alert " + alertRule.getName() + " (" + alertRule.getId() + ") - SQL:'"
                                + sql + "' - Rows: " + sqlQuery.list().size());
                        // It is not possible to add an SQL filter clause to the grid's default datasource.
                        // A String with the alert_id's to filter the grid's so only alerts with access are
                        // shown.
                        if (sqlQuery.list().size() > 0) {
                            // Alert rule returns data, adding it to list of alert rules.
                            alertRuleJson = new JSONObject();
                            alertRuleJson.put("name", alertRule.getIdentifier());
                            alertRuleJson.put("alertRuleId", alertRule.getId());
                            if (alertRule.getTab() != null) {
                                alertRuleJson.put("tabId", alertRule.getTab().getId());
                            } else {
                                alertRuleJson.put("tabId", "");
                            }

                            String filterAlerts = "";
                            @SuppressWarnings("unchecked")
                            List<Alert> alerts = sqlQuery.list();
                            for (Alert alert : alerts) {
                                if (!filterAlerts.isEmpty()) {
                                    filterAlerts += ", ";
                                }
                                filterAlerts += "'" + alert.getId() + "'";
                            }
                            alertRuleJson.put("alerts", filterAlerts);

                        }
                    } catch (SQLGrammarException e) {
                        log4j.error("An error has ocurred when trying to process the alerts: " + e.getMessage(),
                                e);
                    }
                }
                if (alertRuleJson != null) {
                    alertRules.put(alertRuleJson);
                }
            }
        }
    } catch (JSONException e) {
        log.error("Error executing action: " + e.getMessage(), e);
    }

    return alertRules;
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Registration6() throws Exception {
    String expected = "Servlet has already been registered:";
    try {/* w ww  .j  av  a 2 s.  c  o m*/
        ExtendedHttpService extendedHttpService = (ExtendedHttpService) getHttpService();

        Servlet servlet = new BaseServlet();

        extendedHttpService.registerServlet("/blah1", servlet, null, null);
        extendedHttpService.registerServlet("/blah2", servlet, null, null);
    } catch (ServletException se) {
        Assert.assertTrue(se.getMessage().startsWith(expected));

        return;
    }

    Assert.fail();
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Registration14() throws Exception {
    Servlet initError = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override/*from www . ja  v  a2  s  . c om*/
        public void init(ServletConfig config) throws ServletException {
            throw new ServletException("Init error.");
        }

    };
    ExtendedHttpService extendedHttpService = (ExtendedHttpService) getHttpService();
    try {
        extendedHttpService.registerServlet("/foo", initError, null, null);
        fail("Expected an init failure.");
    } catch (ServletException e) {
        //expected
        assertEquals("Wrong exception message.", "Init error.", e.getMessage());
    }
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Registration17() throws Exception {
    Filter initError = new Filter() {

        @Override//from   w  w  w  .  ja v a  2 s .co m
        public void init(FilterConfig filterConfig) throws ServletException {
            throw new ServletException("Init error.");
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            // nothing
        }

        @Override
        public void destroy() {
            // nothing
        }
    };
    ExtendedHttpService extendedHttpService = (ExtendedHttpService) getHttpService();
    try {
        extendedHttpService.registerFilter("/foo", initError, null, null);
        fail("Expected an init failure.");
    } catch (ServletException e) {
        //expected
        assertEquals("Wrong exception message.", "Init error.", e.getMessage());
    }
}

From source file:com.aurel.track.admin.user.userLevel.UserLevelsFromFile.java

/**
 * Loads the user levels/*from ww  w.  j av  a 2s .  c  o  m*/
 * This is a map of maps. The outer map is for each user level, and the inner
 * map contains the settings for each user level
 * @return
 */
public Map<Integer, SortedMap<String, Boolean>> loadUserLevels() {
    Map<Integer, SortedMap<String, Boolean>> locUserLevelsMap = new HashMap<Integer, SortedMap<String, Boolean>>();
    userDefinedExtraUserLevelsMap = new HashMap<String, Integer>();
    localeMap = new HashMap<Integer, Map<String, String>>();
    String ON = "on";
    String OFF = "off";
    PropertiesConfiguration propertiesConfiguration = null;
    if (this.initDataDir == null) {
        //get from <TRACKPLUS_HOME> probably migrate
        propertiesConfiguration = PropertiesConfigurationHelper
                .getPathnamePropFile(HandleHome.getTrackplus_Home(), HandleHome.USER_LEVELS_FILE);
    } else {
        //get from application context
        try {
            propertiesConfiguration = PropertiesConfigurationHelper.loadServletContextPropFile(
                    ApplicationBean.getInstance().getServletContext(), initDataDir,
                    HandleHome.USER_LEVELS_FILE);
        } catch (ServletException e) {
        }
    }
    Pattern LEVEL_PATTERN = Pattern.compile("Level([0-9]+)");
    if (propertiesConfiguration != null) {
        Iterator<String> keys = propertiesConfiguration.getKeys();
        // First path through, we cannot assume it is sorted
        while (keys.hasNext()) {
            String key = keys.next();
            Matcher match = LEVEL_PATTERN.matcher(key);
            if (match.matches()) {
                Integer levelNumber = Integer.parseInt(match.group(1));
                String value = propertiesConfiguration.getString(key);
                userDefinedExtraUserLevelsMap.put(value, levelNumber);
                Map<String, String> localizedLevelsMap = new HashMap<String, String>();
                localeMap.put(levelNumber, localizedLevelsMap);
            }
        }
        keys = propertiesConfiguration.getKeys();
        while (keys.hasNext()) {
            String key = keys.next();
            Matcher match = LEVEL_PATTERN.matcher(key);
            if (match.matches()) {
                Integer levelNumber = Integer.parseInt(match.group(1));
                String value = propertiesConfiguration.getString(key);
                userDefinedExtraUserLevelsMap.put(value, levelNumber);
            } else {
                String[] keyParts = key.split("\\.");
                if (keyParts != null && keyParts.length > 1) {
                    String userLevelName = keyParts[0];
                    if (userLevelName != null && !"".equals(userLevelName)) {
                        String userLevelRightName = key.substring(userLevelName.length() + 1);
                        Integer userLevelID = userLevelNameToID(userLevelName);
                        if (userLevelID == null) {
                            LOGGER.info("No user level specified for " + userLevelName + " (key: " + key + ")");
                            continue;
                        }
                        SortedMap<String, Boolean> userLevelMap = locUserLevelsMap.get(userLevelID);
                        if (userLevelMap == null) {
                            userLevelMap = new TreeMap<String, Boolean>();
                            locUserLevelsMap.put(userLevelID, userLevelMap);
                        }
                        String value = propertiesConfiguration.getString(key);

                        if (keyParts[1] != null && "locale".equals(keyParts[1])) {
                            if (keyParts[2] != null && userLevelID != null) {
                                if (localeMap.get(userLevelID) != null) {
                                    localeMap.get(userLevelID).put(keyParts[2], value);
                                    continue;
                                }
                            }
                        }
                        if (value != null && !"".equals(value) && userLevelRightName != null
                                && !"".equals(userLevelRightName)) {
                            if (ON.equals(value)) {
                                userLevelMap.put(userLevelRightName, Boolean.TRUE);
                            } else {
                                if (OFF.equals(value)) {
                                    userLevelMap.put(userLevelRightName, Boolean.FALSE);
                                } else {
                                    try {
                                        userLevelMap.put(userLevelRightName, Boolean.valueOf(value));
                                    } catch (Exception e) {
                                        LOGGER.info("The value " + value + " for key " + key
                                                + " can't be converted to a boolean " + e.getMessage());
                                        LOGGER.debug(ExceptionUtils.getStackTrace(e));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    this.userLevelsMap = locUserLevelsMap;
    return locUserLevelsMap;
}

From source file:ch.entwine.weblounge.preview.xhtmlrenderer.XhtmlRendererPagePreviewGenerator.java

/**
 * {@inheritDoc}/*from  w  w w  .  j a v  a2 s .c  o  m*/
 * 
 * @see ch.entwine.weblounge.common.content.PreviewGenerator#createPreview(ch.entwine.weblounge.common.content.Resource,
 *      ch.entwine.weblounge.common.site.Environment,
 *      ch.entwine.weblounge.common.language.Language,
 *      ch.entwine.weblounge.common.content.image.ImageStyle, String,
 *      java.io.InputStream, java.io.OutputStream)
 */
public void createPreview(Resource<?> resource, Environment environment, Language language, ImageStyle style,
        String format, InputStream is, OutputStream os) throws IOException {

    if (!isRenderingEnvironmentSane) {
        logger.debug("Skipping page preview rendering as environment is not sane");
        return;
    }

    if (resource == null)
        throw new IllegalArgumentException("Resource cannot be null");

    ImagePreviewGenerator imagePreviewGenerator = null;
    synchronized (previewGenerators) {
        if (previewGenerators.size() == 0) {
            logger.debug("Unable to generate page previews since no image renderer is available");
            return;
        }
        imagePreviewGenerator = previewGenerators.get(0);
    }

    ResourceURI uri = resource.getURI();
    Site site = uri.getSite();
    String html = null;
    try {
        URL pageURL = new URL(UrlUtils.concat(site.getHostname(environment).toExternalForm(),
                PAGE_HANDLER_PREFIX, uri.getIdentifier()));
        html = render(pageURL, site, environment, language, resource.getVersion());
        if (StringUtils.isBlank(html)) {
            logger.warn("Error rendering preview of page " + uri.getPath());
            return;
        }
        html = HTMLUtils.escapeHtml(HTMLUtils.unescape(html));
    } catch (ServletException e) {
        logger.warn("Error rendering page " + uri.getPath(), e);
        throw new IOException(e);
    }

    // Try to convert html to xhtml
    HtmlCleaner cleaner = new HtmlCleaner();
    CleanerProperties xhtmlProperties = cleaner.getProperties();
    TagNode xhtmlNode = cleaner.clean(html);
    if (xhtmlNode == null) {
        logger.warn("Error creating well-formed document from page {}", resource);
        return;
    }

    File xhtmlFile = null;
    is = new ByteArrayInputStream(html.getBytes("UTF-8"));

    // Write the resource content to disk. This step is needed, as the preview
    // generator can only handle files.
    try {
        xhtmlFile = File.createTempFile("xhtml", ".xml");
        Serializer xhtmlSerializer = new SimpleXmlSerializer(xhtmlProperties);
        xhtmlSerializer.writeToFile(xhtmlNode, xhtmlFile.getAbsolutePath(), "UTF-8");
    } catch (IOException e) {
        logger.error("Error creating temporary copy of file content at " + xhtmlFile, e);
        FileUtils.deleteQuietly(xhtmlFile);
        throw e;
    } finally {
        IOUtils.closeQuietly(is);
    }

    File imageFile = File.createTempFile("xhtml-preview", "." + PREVIEW_FORMAT);
    FileOutputStream imageFos = null;

    // Render the page and write back to client
    try {
        int screenshotWidth = DEFAULT_SCREENSHOT_WIDTH;
        int screenshotHeight = DEFAULT_SCREENSHOT_HEIGHT;
        if (style != null && style.getWidth() > 0 && style.getHeight() > 0) {
            screenshotHeight = (int) ((float) screenshotWidth / (float) style.getWidth() * style.getHeight());
        }

        // Create the renderer. Due to a synchronization bug in the software,
        // this needs to be synchronized
        Java2DRenderer renderer = null;
        try {
            synchronized (this) {
                renderer = new Java2DRenderer(xhtmlFile, screenshotWidth, screenshotHeight);
            }
        } catch (Throwable t) {
            if (isRenderingEnvironmentSane) {
                logger.warn("Error creating Java 2D renderer for previews: {}" + t.getMessage());
                logger.warn("Page preview rendering will be switched off");
                isRenderingEnvironmentSane = false;
            }
            logger.debug("Error creating Java 2D renderer for preview of page {}: {}" + uri.getPath(),
                    t.getMessage());
            return;
        }

        // Configure the renderer
        renderer.getSharedContext().setBaseURL(site.getHostname().toExternalForm());
        renderer.getSharedContext().setInteractive(false);

        // Make sure the renderer is using a user agent that will correctly
        // resolve urls
        WebloungeUserAgent agent = userAgents.get(site.getIdentifier());
        if (agent == null) {
            agent = new WebloungeUserAgent(site.getHostname().getURL());
            userAgents.put(site.getIdentifier(), agent);
        }
        renderer.getSharedContext().setUserAgentCallback(agent);

        // Render the page to an image
        BufferedImage img = renderer.getImage();
        FSImageWriter imageWriter = new FSImageWriter(PREVIEW_FORMAT);
        imageFos = new FileOutputStream(imageFile);
        imageWriter.write(img, imageFos);

    } catch (IOException e) {
        logger.error("Error creating temporary copy of file content at " + xhtmlFile, e);
        throw e;
    } catch (XRRuntimeException e) {
        logger.warn("Error rendering page content at " + uri + ": " + e.getMessage());
        throw e;
    } catch (HeadlessException e) {
        logger.warn("Headless error while trying to render page preview: " + e.getMessage());
        logger.warn("Page preview rendering will be switched off");
        isRenderingEnvironmentSane = false;
        throw e;
    } catch (Throwable t) {
        logger.warn("Error rendering page content at " + uri + ": " + t.getMessage(), t);
        throw new IOException(t);
    } finally {
        IOUtils.closeQuietly(imageFos);
        FileUtils.deleteQuietly(xhtmlFile);
    }

    FileInputStream imageIs = null;

    // Scale the image to the correct size
    try {
        imageIs = new FileInputStream(imageFile);
        imagePreviewGenerator.createPreview(resource, environment, language, style, PREVIEW_FORMAT, imageIs,
                os);
    } catch (IOException e) {
        logger.error("Error creating temporary copy of file content at " + xhtmlFile, e);
        throw e;
    } catch (Throwable t) {
        logger.warn("Error scaling page preview at " + uri + ": " + t.getMessage(), t);
        throw new IOException(t);
    } finally {
        IOUtils.closeQuietly(imageIs);
        FileUtils.deleteQuietly(imageFile);
    }

}