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(String message, 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, including a description message.

Usage

From source file:se.curity.examples.oauth.OAuthJwtFilter.java

public void init(FilterConfig filterConfig) throws ServletException {
    ImmutableMultimap<String, String> initParams = initParamsMapFrom(filterConfig);

    _oauthHost = getInitParamValue(InitParams.OAUTH_HOST, initParams);
    int oauthPort = getInitParamValue(InitParams.OAUTH_PORT, initParams, Integer::parseInt);

    String webKeysPath = getInitParamValue(InitParams.JSON_WEB_KEYS_PATH, initParams);

    String scope = getInitParamValue(InitParams.SCOPE, initParams);
    _scopes = scope.split("\\s+");

    Optional<Long> minKidReloadTime = getOptionalInitParamValue(InitParams.MIN_KID_RELOAD_TIME, initParams,
            Long::parseLong);// w w  w  .jav a  2s .  c  om
    _minKidReloadTimeInSeconds = minKidReloadTime.orElse(_minKidReloadTimeInSeconds);

    synchronized (this) {
        if (_jwtValidator == null) {
            try {
                URI webKeysURI = new URI("https", null, _oauthHost, oauthPort, webKeysPath, null, null);
                _jwtValidator = new JwtValidatorWithJwk(webKeysURI, _minKidReloadTimeInSeconds, _httpClient);
            } catch (URISyntaxException e) {
                throw new ServletException("Invalid parameters", e);
            }
            _logger.info("{} successfully initialized", OAuthFilter.class.getSimpleName());
        } else {
            _logger.warn("Attempted to set webkey URI more than once! Ignoring further attempts.");
        }
    }
}

From source file:org.lareferencia.xoai.controller.LROAIDataProvider.java

@RequestMapping("/")
public String indexAction(HttpServletResponse response, Model model) throws ServletException {
    try {//  www. ja  va  2 s .  c  om
        XOAIManager manager = xoaiManagerResolver.getManager();
        model.addAttribute("contexts", manager.getContextManager().getContexts());
        response.setStatus(SC_BAD_REQUEST);
    } catch (XOAIManagerResolverException e) {
        throw new ServletException("Unable to load XOAI manager, please, try again.", e);
        // No message
    }
    return "index";
}

From source file:com.adobe.acs.commons.wcm.impl.VanityDuplicateCheckServlet.java

@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    try {/*  ww  w. java2 s  . c om*/
        final ResourceResolver resolver = request.getResourceResolver();
        final String vanityPath = request.getParameter("vanityPath");
        final String pagePath = request.getParameter("pagePath");
        log.debug("vanity path parameter passed is {}; page path parameter passed is {}", vanityPath, pagePath);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        JSONWriter jsonWriter = new JSONWriter(response.getWriter());
        jsonWriter.array();

        if (StringUtils.isNotBlank(vanityPath)) {
            String xpath = "//element(*)[" + NameConstants.PN_SLING_VANITY_PATH + "='" + vanityPath + "']";
            @SuppressWarnings("deprecation")
            Iterator<Resource> resources = resolver.findResources(xpath, Query.XPATH);
            while (resources.hasNext()) {
                Resource resource = resources.next();
                String path = resource.getPath();
                if (path.startsWith("/content") && !path.equals(pagePath)) {
                    jsonWriter.value(path);
                }
            }

        }
        jsonWriter.endArray();
    } catch (JSONException e) {
        throw new ServletException("Unable to generate JSON result", e);
    }
}

From source file:info.magnolia.cms.filters.AggregatorFilter.java

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

    boolean success;
    try {//from   w  w  w.j a v a2s .c  o  m
        success = collect();
    } catch (AccessDeniedException e) {
        // don't throw further, simply return error and break filter chain
        log.debug(e.getMessage(), e);
        if (!response.isCommitted()) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
        // stop the chain
        return;
    } catch (RepositoryException e) {
        log.error(e.getMessage(), e);
        throw new ServletException(e.getMessage(), e);
    }

    if (!success) {
        log.debug("Resource not found, redirecting request for [{}] to 404 URI", request.getRequestURI());

        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else {
            log.info("Unable to redirect to 404 page, response is already committed. URI was {}",
                    request.getRequestURI());
        }
        // stop the chain
        return;
    }
    chain.doFilter(request, response);
}

From source file:com.tenduke.example.scribeoauth.JwtLoginServlet.java

/**
 * Initializes this servlet.//from ww w .  ja v a 2 s  .c  o  m
 * @param config Servlet configuration.
 * @throws ServletException For errors during init.
 */
@Override
public void init(final ServletConfig config) throws ServletException {
    //
    super.init(config);
    //
    final JSONObject jwtPublicKey = readConfiguration("idp.jwt.publickey.json", config.getServletContext());
    try {
        //
        byte[] publicKeyDecoded = Base64.decodeBase64(jwtPublicKey.getString("publicKey"));
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyDecoded);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        publicKey = keyFactory.generatePublic(keySpec);
    } catch (InvalidKeySpecException | NoSuchAlgorithmException ex) {
        //
        throw new ServletException("No way, basic RSA based key generation failed...", ex);
    }
}

From source file:com.github.matthesrieke.realty.CrawlerServlet.java

@Override
public void init() throws ServletException {
    super.init();

    this.listTemplate = Util.parseStream(getClass().getResourceAsStream("index-template.html"));
    this.groupTemplate = Util.parseStream(getClass().getResourceAsStream("group-template.html"));

    this.properties = new Properties();
    InputStream is = getClass().getResourceAsStream("/config.properties");
    if (is == null) {
        is = getClass().getResourceAsStream("/config.properties.default");
    }/*w  ww  .ja  va  2s  .c om*/
    try {
        this.properties.load(is);
    } catch (IOException e1) {
        logger.warn(e1.getMessage(), e1);
        throw new ServletException("Could not init properties!", e1);
    }

    initializeCrawlers();

    readCrawlingLinks();

    String preferredDatabaseLocation = properties.getProperty("DATABASE_DIR");
    storage = new H2Storage(preferredDatabaseLocation);

    this.timer = new Timer();

    Integer crawlPeriod = Util.getIntegerProperty(this.properties, "crawlPeriodHours", 6);
    logger.info(String.format("Scheduling crawl every %s hours.", crawlPeriod));

    this.timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            logger.info("Starting to parse ad entries...");
            DateTime now = new DateTime();

            int insertedCount = 0;
            int crawlerCount = 0;

            try {
                for (String baseLink : crawlLinks) {
                    logger.info("Baselink = " + baseLink);

                    Crawler crawler;
                    try {
                        crawler = resolveCrawler(baseLink);
                    } catch (UnsupportedBaseLinkException e1) {
                        logger.warn(e1.getMessage(), e1);
                        break;
                    }

                    crawlerCount++;

                    String link;
                    int page = crawler.getFirstPageIndex();
                    while (true) {
                        Thread.sleep(1000);
                        logger.info("Parsing page " + page);

                        link = crawler.prepareLinkForPage(baseLink, page);
                        HttpGet get = new HttpGet(link);
                        page++;

                        CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(
                                RequestConfig.custom().setConnectTimeout(20000).build()).build();
                        try {
                            CloseableHttpResponse resp = client.execute(get);
                            if (resp.getStatusLine().getStatusCode() < HttpStatus.SC_MULTIPLE_CHOICES) {
                                InputStream content = resp.getEntity().getContent();

                                List<Ad> items = parse(content, crawler);
                                if (items == null || items.size() == 0) {
                                    break;
                                }

                                insertedCount += compareAndStoreItems(items, now);

                            } else {
                                break;
                            }
                        } catch (IOException | CrawlerException e) {
                            logger.warn(e.getMessage(), e);
                            Metadata md = new Metadata("Exception during crawl: " + e.getMessage());
                            storage.updateMetadata(md);
                            break;
                        }

                    }

                    logger.info("finished parsing ad entries!");
                }

                Metadata md = new Metadata(String.format("Added %s new entries. %s crawlers have been used",
                        insertedCount, crawlerCount));
                storage.updateMetadata(md);
            } catch (RuntimeException | InterruptedException e) {
                logger.warn(e.getMessage(), e);

                Metadata md = new Metadata("Exception during crawl: " + e.getMessage());
                storage.updateMetadata(md);
            }

        }
    }, 0, 1000 * 60 * 60 * crawlPeriod);
}

From source file:com.predic8.membrane.servlet.embedded.RStudioMembraneServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String queryString = req.getQueryString() == null ? "" : "?" + req.getQueryString();

    Router router;//from w  w w.  j a v a2 s.  com

    // For websockets, the following paths are used by JupyterHub:
    //  /(user/[^/]*)/(api/kernels/[^/]+/channels|terminals/websocket)/?
    // forward to ws(s)://servername:port_number
    //<LocationMatch "/mypath/(user/[^/]*)/(api/kernels/[^/]+/channels|terminals/websocket)(.*)">
    //    ProxyPassMatch ws://localhost:8999/mypath/$1/$2$3
    //    ProxyPassReverse ws://localhost:8999 # this may be superfluous
    //</LocationMatch>
    //        ProxyPass /api/kernels/ ws://192.168.254.23:8888/api/kernels/
    //        ProxyPassReverse /api/kernels/ http://192.168.254.23:8888/api/kernels/
    List<NameValuePair> pairs;
    try {
        //note: HttpClient 4.2 lets you parse the string without building the URI
        pairs = URLEncodedUtils.parse(new URI(queryString), "UTF-8");
    } catch (URISyntaxException e) {
        throw new ServletException("Unexpected URI parsing error on " + queryString, e);
    }
    LinkedHashMap<String, String> params = new LinkedHashMap<>();
    for (NameValuePair pair : pairs) {
        params.put(pair.getName(), pair.getValue());
    }

    String externalIp = Ip.getHost(req.getRequestURL().toString());

    StringBuffer urlBuf = new StringBuffer("http://localhost:");

    String ctxPath = req.getRequestURI();

    int x = ctxPath.indexOf("/rstudio");
    int firstSlash = ctxPath.indexOf('/', x + 1);
    int secondSlash = ctxPath.indexOf('/', firstSlash + 1);
    String portString = ctxPath.substring(firstSlash + 1, secondSlash);
    Integer targetPort;
    try {
        targetPort = Integer.parseInt(portString);
    } catch (NumberFormatException ex) {
        logger.error("Invalid target port in the URL: " + portString);
        return;
    }
    urlBuf.append(portString);

    String newTargetUri = urlBuf.toString() + req.getRequestURI();

    StringBuilder newQueryBuf = new StringBuilder();
    newQueryBuf.append(newTargetUri);
    newQueryBuf.append(queryString);

    URI targetUriObj = null;
    try {
        targetUriObj = new URI(newQueryBuf.toString());
    } catch (Exception e) {
        throw new ServletException("Rewritten targetUri is invalid: " + newTargetUri, e);
    }
    ServiceProxy sp = new ServiceProxy(new ServiceProxyKey(externalIp, "*", "*", -1), "localhost", targetPort);
    //    ServiceProxy sp = new ServiceProxy(
    //            new ServiceProxyKey(
    //                    externalIp, "*", "*", -1),
    //            "localhost", targetPort);
    sp.setTargetURL(newQueryBuf.toString());
    // only set external hostname in case admin console is used
    try {
        router = new HopsRouter(targetUriObj);
        router.add(sp);
        router.init();
        ProxyRule proxy = new ProxyRule(new ProxyRuleKey(-1));
        router.getRuleManager().addProxy(proxy, RuleManager.RuleDefinitionSource.MANUAL);
        router.getRuleManager().addProxy(sp, RuleManager.RuleDefinitionSource.MANUAL);
        new HopsServletHandler(req, resp, router.getTransport(), targetUriObj).run();
    } catch (Exception ex) {
        Logger.getLogger(RStudioMembraneServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.cognifide.actions.msg.push.passive.PushServlet.java

public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {
    if (!authenticate(request, response)) {
        return;/*from   w w  w  .j a va 2s. c  om*/
    }
    response.setContentType("text/plain; charset=utf-8");

    synchronized (connectionHold) {
        connectionHold.notifyAll();
    }
    synchronized (this) {
        writer = response.getWriter();
    }
    try {
        synchronized (connectionHold) {
            connectionHold.wait();
        }
    } catch (InterruptedException e) {
        throw new ServletException("Interrupted", e);
    }
}

From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java

@Override
public void init(final ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);

    final String proxyURL = getProxyURL();
    try {/* ww w  .j a  va2  s  . c om*/
        _targetUri = new URI(proxyURL);
    } catch (final Exception e) {
        final String message = "Error constructing uri: " + proxyURL;
        LOG.log(Level.SEVERE, message, e);
        throw new ServletException(message, e);
    }
    _target = _targetUri.toString();

    _client = HttpClientBuilder.create().disableRedirectHandling().build();
}

From source file:com.imaginea.mongodb.controllers.TroubleShootController.java

/**
 * Handles a GET Request at path mViewer/admin for changing the logger level
 *
 * @param request  Request made by user//from   ww w.ja v a 2s. com
 * @param response
 * @throws ServletException ,IOException,IllegalArgumentException
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, IllegalArgumentException {

    response.setContentType("application/x-json");
    PrintWriter out = response.getWriter();
    JSONObject respObj = new JSONObject();

    String loggerLevel = request.getParameter("level");

    try {

        if (!logLevels.containsKey(loggerLevel)) {
            JSONObject error = new JSONObject();
            error.put("code", ErrorCodes.LOGGING_LEVEL_UNDEFINED);
            error.put("message", "Undefined Logging level");
            JSONObject temp = new JSONObject();
            temp.put("error", error);
            respObj.put("response", temp);

        } else {

            Level newLevel = logLevels.get(loggerLevel);

            Logger rootLogger = LogManager.getRootLogger(); // To get the
            // Root Logger

            String oldLevel = rootLogger.getEffectiveLevel().toString();
            rootLogger.setLevel(newLevel);

            JSONObject temp = new JSONObject();
            temp.put("result", "Logger Level Changed from " + oldLevel + " to " + rootLogger.getLevel());
            respObj.put("response", temp);
        }
        out.write(respObj.toString());
        out.close();
    } catch (JSONException e) {
        throw new ServletException("Error forming JSON Object in Servlet", e.getCause());
    }

}