Example usage for javax.servlet ServletException ServletException

List of usage examples for javax.servlet ServletException ServletException

Introduction

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

Prototype


public ServletException(Throwable rootCause) 

Source Link

Document

Constructs a new servlet exception when the servlet needs to throw an exception and include a message about the "root cause" exception that interfered with its normal operation.

Usage

From source file:com.adobe.cq.wcm.core.components.internal.servlets.WorkflowModelDataSourceServlet.java

@Override
protected void doGet(@Nonnull SlingHttpServletRequest request, @Nonnull SlingHttpServletResponse response)
        throws ServletException, IOException {
    try {//  w w  w .j  a v a2  s .  co  m
        WorkflowSession workflowSession = request.getResourceResolver().adaptTo(WorkflowSession.class);
        ArrayList<Resource> resources = new ArrayList<>();
        if (workflowSession != null) {
            WorkflowModel[] models = workflowSession.getModels();
            for (WorkflowModel model : models) {
                resources.add(new WorkflowModelResource(model, request.getResourceResolver()));
            }
        }
        SimpleDataSource dataSource = new SimpleDataSource(resources.iterator());
        request.setAttribute(DataSource.class.getName(), dataSource);
    } catch (WorkflowException e) {
        throw new ServletException(e);
    }
}

From source file:au.edu.uq.cmm.benny.Benny.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    Properties props = new Properties();
    InputStream is = getClass().getResourceAsStream(PROPS_RESOURCE);
    if (is == null) {
        throw new ServletException("Cannot find resource: " + PROPS_RESOURCE);
    }/*ww  w .  jav  a 2s  .  c  om*/
    try {
        props.load(is);
    } catch (IOException ex) {
        throw new ServletException("Cannot load the configuration properties in resource " + PROPS_RESOURCE);
    }
    try {
        realm = props.getProperty("benny.realm");
        authenticator = new AclsAuthenticator(props.getProperty("benny.serverHost"),
                Integer.parseInt(props.getProperty("benny.serverPort")),
                Integer.parseInt(props.getProperty("benny.serverTimeout")),
                props.getProperty("benny.dummyFacility"), props.getProperty("benny.localHostId"));
    } catch (Exception ex) {
        throw new ServletException("Cannot instantiate the authenticator");
    }
}

From source file:dhbw.ka.mwi.businesshorizon2.SpringApplicationServlet.java

/**
 * Diese Methode wird einmal beim Initialisieren aufgerufen. Dort werden die Konfigurationseinstellungen
 * aus der web.xml gelesen. Darueberhinaus wird ein Spring-Application-Context aus der servletConfig
 * geholt, mit dem es moeglich ist, Beans mit Session-Scope zu erzeugen.
 * /*  w  ww .j ava2 s  . c om*/
 * @author Christian Gahlert
 */
@SuppressWarnings("unchecked")
@Override
public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    applicationBean = servletConfig.getInitParameter("applicationBean");

    if (applicationBean == null) {
        throw new ServletException("ApplicationBean not specified in servlet parameters");
    }

    applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletConfig.getServletContext());
    applicationClass = (Class<? extends Application>) applicationContext.getType(applicationBean);
}

From source file:io.fabric8.apiman.ui.ConfigurationServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 * Grabs the authToken from the user's sessions and sticks it in the config.js using
 * a token replacement of the token '@token@'.
 *///  www. j a v a2 s.  c om
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String authToken = (String) request.getSession().getAttribute(LinkServlet.AUTH_TOKEN);
    log.info("AuthToken = " + authToken);
    InputStream is = null;
    String configFile = null;
    if (authToken == null) {
        log.debug("No authToken in the user's session with id " + request.getSession().getId());
        is = getClass().getResourceAsStream("/apimanui/apiman/f8-config-bkwrds-compatible.js");
        configFile = IOUtils.toString(is);
    } else {
        is = getClass().getResourceAsStream("/apimanui/apiman/f8-config.js");
        configFile = IOUtils.toString(is);
        configFile = configFile.replace("@token@", authToken);
    }
    try {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/javascript");
        response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
        response.setDateHeader("Expires", 0);
        response.getOutputStream().write(configFile.getBytes("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
    } catch (Exception e) {
        throw new ServletException(e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.liulangf.pattern.gof.behavioral.chain.jakarta.simple.ExampleServlet.java

/**
 * <p>Configure a {@link ServletWebContext} for the current request, and
 * pass it to the <code>execute()</code> method of the specified
 * {@link Command}, loaded from our configured {@link Catalog}.</p>
 *
 * @param request The request we are processing
 * @param response The response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 *//*  w  ww .  jav a 2 s .c om*/
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    CatalogFactory factory = CatalogFactory.getInstance();
    Catalog catalog = factory.getCatalog(servletName);
    if (catalog == null) {
        catalog = factory.getCatalog();
    }

    ServletWebContext context = new ServletWebContext(getServletContext(), request, response);
    Command command = catalog.getCommand("COMMAND_MAPPER");
    try {
        command.execute(context);
    } catch (Exception e) {
        throw new ServletException(e);
    }

}

From source file:com.ait.tooling.server.core.servlet.FileUploadServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.info("STARTING UPLOAD");

    try {/*  w w  w  .ja  va  2s. co  m*/
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

        ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);

        fileUpload.setSizeMax(FILE_SIZE_LIMIT);

        List<FileItem> items = fileUpload.parseRequest(request);

        for (FileItem item : items) {
            if (item.isFormField()) {
                logger.info("Received form field");

                logger.info("Name: " + item.getFieldName());

                logger.info("Value: " + item.getString());
            } else {
                logger.info("Received file");

                logger.info("Name: " + item.getName());

                logger.info("Size: " + item.getSize());
            }
            if (false == item.isFormField()) {
                if (item.getSize() > FILE_SIZE_LIMIT) {
                    response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                            "File size exceeds limit");

                    return;
                }
                // Typically here you would process the file in some way:
                // InputStream in = item.getInputStream();
                // ...

                if (false == item.isInMemory()) {
                    item.delete();
                }
            }
        }
    } catch (Exception e) {
        logger.error("Throwing servlet exception for unhandled exception", e);

        throw new ServletException(e);
    }
}

From source file:ch.frankel.vaadin.spring.SpringApplicationServlet.java

/**
 * Get the application bean in Spring's context.
 * /*w  w w .j a  v  a2 s  .c  o m*/
 * @see AbstractApplicationServlet#getNewApplication(HttpServletRequest)
 */
@Override
protected Application getNewApplication(HttpServletRequest request) throws ServletException {

    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

    if (wac == null) {

        throw new ServletException("Cannot get an handle on Spring's context. Is Spring running?"
                + "Check there's an org.springframework.web.context.ContextLoaderListener configured.");
    }

    Object bean = wac.getBean(name);

    if (!(bean instanceof Application)) {

        throw new ServletException("Bean " + name + " is not of expected class Application");
    }

    return (Application) bean;
}

From source file:io.druid.security.kerberos.DruidKerberosAuthenticationHandler.java

@Override
public void init(Properties config) throws ServletException {
    try {//from   ww  w  .  j av a  2s .  c om
        String principal = config.getProperty(PRINCIPAL);
        if (principal == null || principal.trim().length() == 0) {
            throw new ServletException("Principal not defined in configuration");
        }
        keytab = config.getProperty(KEYTAB, keytab);
        if (keytab == null || keytab.trim().length() == 0) {
            throw new ServletException("Keytab not defined in configuration");
        }
        if (!new File(keytab).exists()) {
            throw new ServletException("Keytab does not exist: " + keytab);
        }

        // use all SPNEGO principals in the keytab if a principal isn't
        // specifically configured
        final String[] spnegoPrincipals;
        if (principal.equals("*")) {
            spnegoPrincipals = KerberosUtil.getPrincipalNames(keytab, Pattern.compile("HTTP/.*"));
            if (spnegoPrincipals.length == 0) {
                throw new ServletException("Principals do not exist in the keytab");
            }
        } else {
            spnegoPrincipals = new String[] { principal };
        }

        String nameRules = config.getProperty(NAME_RULES, null);
        if (nameRules != null) {
            KerberosName.setRules(nameRules);
        }

        for (String spnegoPrincipal : spnegoPrincipals) {
            log.info("Login using keytab %s, for principal %s", keytab, spnegoPrincipal);
            final KerberosAuthenticator.DruidKerberosConfiguration kerberosConfiguration = new KerberosAuthenticator.DruidKerberosConfiguration(
                    keytab, spnegoPrincipal);
            final LoginContext loginContext = new LoginContext("", serverSubject, null, kerberosConfiguration);
            try {
                loginContext.login();
            } catch (LoginException le) {
                log.warn(le, "Failed to login as [%s]", spnegoPrincipal);
                throw new AuthenticationException(le);
            }
            loginContexts.add(loginContext);
        }
        try {
            gssManager = Subject.doAs(serverSubject, new PrivilegedExceptionAction<GSSManager>() {

                @Override
                public GSSManager run() throws Exception {
                    return GSSManager.getInstance();
                }
            });
        } catch (PrivilegedActionException ex) {
            throw ex.getException();
        }
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
}

From source file:com.bluexml.side.framework.alfresco.shareLanguagePicker.LanguageSetter.java

public static String getLanguageFromLayoutParam(HttpServletRequest req, RequestContext context)
        throws ServletException {
    logger.debug("# getLanguageFromLayoutParam ...");
    User user = context.getUser();//from  www  .j a  v a  2 s.com
    String userId = context.getUserId();
    String urlLang = req.getParameter(SHARE_LANG);
    HttpSession currentSession = req.getSession();
    String sessionLang = (String) currentSession.getAttribute(SHARE_LANG);
    if (logger.isTraceEnabled()) {
        logger.trace("urlLang : " + urlLang);
        logger.trace("sessionLang : " + sessionLang);
    }

    // set language

    String language = null;
    // is no user or guest use browser language
    if (user != null && !userId.toLowerCase().equals("guest")) {
        if (urlLang != null) {
            language = urlLang;
            if (logger.isDebugEnabled()) {
                logger.debug("Use language in url :" + urlLang);
            }
        } else if (sessionLang != null && currentSession.getAttribute(userSessionok) != null) {
            // only if language already loaded from preference
            if (logger.isDebugEnabled()) {
                logger.debug("Use language stored in session :" + sessionLang);
            }
            language = sessionLang;

        } else {
            // initialize user language
            try {
                language = getUserLanguage(userId, req);
                logger.debug("Use language from user preferences :" + language);

            } catch (ConnectorServiceException e) {
                throw new ServletException(e);
            } catch (JSONException e) {
                throw new ServletException(e);
            }
            if (language == null) {
                // language not yet set so use default from browser
                language = getLanguageFromBrowser(req);
                logger.debug("Use language from browser :" + language);
            }
            currentSession.setAttribute(userSessionok, true);
        }
    } else {
        // language not yet set so use default from browser
        language = getLanguageFromBrowser(req);
        logger.debug("no user or Guest, use language from browser :" + language);
    }

    return language;

}

From source file:com.adobe.acs.commons.analysis.jcrchecksum.impl.servlets.JSONDumpServlet.java

public final void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   w  w w . j a v  a 2 s.  c o  m*/
        this.handleCORS(request, response);
        this.handleRequest(request, response);
    } catch (RepositoryException e) {
        throw new ServletException(e);
    }
}