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:be.fedict.eid.idp.sp.protocol.saml2.AbstractAuthenticationResponseServlet.java

/**
 * Get the required servlet init param/*from  w w w .j a  va 2  s .  co  m*/
 * 
 * @param parameterName
 *            parameter name
 * @param config
 *            Servlet Config
 * @return the required param value
 * @throws ServletException
 *             no value was found.
 */
protected String getRequiredInitParameter(String parameterName, ServletConfig config) throws ServletException {

    String value = config.getInitParameter(parameterName);
    if (null == value) {
        throw new ServletException(parameterName + " init-param is required");
    }
    return value;
}

From source file:com.mindmutex.draugiem.DraugiemHttpFilter.java

@Override
public void init(FilterConfig filterConfig) throws ServletException {
    String configPath = filterConfig.getInitParameter("configPath");
    if (configPath == null) {
        configPath = DEFAULT_CONFIG_PATH;
    }/*from  w w w.  jav a 2 s .c  o m*/

    ClassLoader classLoader = getClass().getClassLoader();
    InputStream inputStream = classLoader.getResourceAsStream(configPath);
    if (inputStream == null) {
        throw new ServletException("unable to load configuration file: " + configPath);
    }
    configuration = new Properties();
    try {
        configuration.load(inputStream);
    } catch (IOException ex) {
        throw new ServletException(ex);
    }
    configureFilter();

    logger.info("Initialised");
}

From source file:com.mockey.ui.ConfigurationInfoAJAXServlet.java

/**
 * /*w  w  w  .  j a  va 2 s.c o  m*/
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    ProxyServerModel proxyInfo = store.getProxy();
    String transientState = req.getParameter("transient_state");

    try {
        if (transientState != null) {
            store.setReadOnlyMode(new Boolean(transientState));
        }
    } catch (Exception e) {
        logger.error("Unable to set transient state with value: " + transientState, e);
    }

    resp.setContentType("application/json");
    PrintWriter out = resp.getWriter();
    try {
        JSONObject responseObject = new JSONObject();
        JSONObject messageObject = new JSONObject();
        messageObject.put("proxy_enabled", Boolean.toString(proxyInfo.isProxyEnabled()));
        messageObject.put("transient_state", store.getReadOnlyMode());
        Long twistInfoId = store.getUniversalTwistInfoId();
        TwistInfo twistInfo = store.getTwistInfoById(twistInfoId);
        if (twistInfo != null) {
            messageObject.put("twist_enabled", true);
            messageObject.put("twist-id", twistInfo.getId());
            messageObject.put("twist-name", twistInfo.getName());

        } else {
            messageObject.put("twist_enabled", false);
        }
        resp.setContentType("application/json;");
        responseObject.put("result", messageObject);

        out.println(responseObject.toString());
    } catch (JSONException e) {
        throw new ServletException(e);
    }
    out.flush();
    out.close();
    return;
}

From source file:com.tremolosecurity.proxy.auth.saml2.Saml2SingleLogout.java

@Override
public void handleLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    if (request == null || response == null) {
        //do nothing
        return;//w ww  .j a  v a2  s.c  o  m
    }

    String xmlAlg = SAML2Auth.xmlDigSigAlgs.get(digSigAlg);

    if (xmlAlg == null) {
        throw new ServletException("Unknown Signiture algorithm : '" + digSigAlg + "'");
    }

    String javaAlg = SAML2Auth.javaDigSigAlgs.get(digSigAlg);

    UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG);

    ConfigManager cfgMgr = holder.getConfig();

    LogoutRequestBuilder lrb = new LogoutRequestBuilder();
    LogoutRequest lr = lrb.buildObject();

    DateTime dt = new DateTime();
    lr.setIssueInstant(dt);

    lr.setDestination(logoutURL);

    byte[] idBytes = new byte[20];
    random.nextBytes(idBytes);

    String id = "f" + Hex.encodeHexString(idBytes);
    lr.setID(id);

    IssuerBuilder ib = new IssuerBuilder();
    Issuer issuer = ib.buildObject();
    issuer.setValue(assertionConsumerServiceURL);
    lr.setIssuer(issuer);

    NameIDBuilder nidbpb = new NameIDBuilder();
    NameID nid = nidbpb.buildObject();
    //nidp.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
    nid.setFormat(nameIDFormat);

    //nid.setSPNameQualifier(assertionConsumerServiceURL);
    nid.setValue(nameID);
    lr.setNameID(nid);

    SessionIndexBuilder sib = new SessionIndexBuilder();
    SessionIndex si = sib.buildObject();
    si.setSessionIndex(sessionIndex);
    lr.getSessionIndexes().add(si);

    try {
        // Get the Subject marshaller
        Marshaller marshaller = new LogoutRequestMarshaller();

        // Marshall the Subject
        //Element assertionElement = marshaller.marshall(lr);

        String xml = OpenSAMLUtils.xml2str(lr);
        xml = xml.substring(xml.indexOf("?>") + 2);

        if (logger.isDebugEnabled()) {
            logger.debug("=======AuthnRequest============");
            logger.debug(xml);
            logger.debug("=======AuthnRequest============");
        }

        byte[] bxml = xml.getBytes("UTF-8");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
                new Deflater(Deflater.BEST_COMPRESSION, true));

        compressor.write(bxml);
        compressor.flush();
        compressor.close();

        String b64 = new String(Base64.encodeBase64(baos.toByteArray()));
        StringBuffer redirURL = new StringBuffer();
        StringBuffer query = new StringBuffer();

        idBytes = new byte[20];
        random.nextBytes(idBytes);

        query.append("SAMLRequest=").append(URLEncoder.encode(b64, "UTF-8")).append("&RelayState=")
                .append(URLEncoder.encode(Hex.encodeHexString(idBytes), "UTF-8"));

        query.append("&SigAlg=").append(URLEncoder.encode(xmlAlg, "UTF-8"));
        //http://www.w3.org/2000/09/xmldsig#rsa-sha1

        java.security.Signature signer = java.security.Signature.getInstance(javaAlg);

        PrivateKey sigKey = cfgMgr.getPrivateKey(signingKeyAlias);

        if (sigKey == null) {
            throw new ServletException("Signing Key : '" + signingKeyAlias + "' not found");
        }

        signer.initSign(sigKey);
        signer.update(query.toString().getBytes("UTF-8"));
        String base64Sig = new String(Base64.encodeBase64(signer.sign()));
        query.append("&Signature=").append(URLEncoder.encode(base64Sig, "UTF-8"));

        redirURL.append(logoutURL).append("?").append(query.toString());

        if (logger.isDebugEnabled()) {
            logger.debug("Logout URL : '" + redirURL.toString() + "'");
        }

        //((ProxyResponse) response).removeHeader("Location");
        response.sendRedirect(redirURL.toString());

    } catch (Exception e) {
        throw new ServletException("Could not generate logout request", e);
    }

}

From source file:ar.com.zauber.commons.web.filter.JSONPRequestFilter.java

/**
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 *//*from   w  w w. ja va  2s. c om*/
public final void doFilter(final ServletRequest request, final ServletResponse response,
        final FilterChain chain) throws IOException, ServletException {
    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("This filter can " + " only process HttpServletRequest requests");
    }

    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final String callback = httpRequest.getParameter(callbackParameterName);

    if (StringUtils.isNotBlank(callback) && acceptsJSONP(httpRequest)) {
        ServletOutputStream out = response.getOutputStream();
        out.print(callback + "(");
        chain.doFilter(request, response);
        out.print(");");
        response.setContentType(responseContentType);
    } else {
        chain.doFilter(request, response);
    }
}

From source file:org.ambraproject.cas.filter.GetGuidReturnEmailFilter.java

/**
 * Set the Database Service (which will be used to query the user's Email Address) by way of
 *   the Web Application Context, which is managed by the supporting framework.
 *
 * @param filterConfig Standard Filter configuration values, most notably the Servlet Context
 * @throws ServletException Thrown if there is a problem getting or setting the Database Service
 *///  ww  w .  j a  va2s.c  om
public void init(final FilterConfig filterConfig) throws ServletException {
    try {
        databaseService = (DatabaseService) WebApplicationContextUtils
                .getWebApplicationContext(filterConfig.getServletContext()).getBean("databaseService");
    } catch (final Exception e) {
        log.error("Failed to initialize GetGuidReturnEmailFilter.", e);
        throw new ServletException(e);
    }
}

From source file:BubbleChartDemo.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    Connection conn = null;//from   ww w  .java  2  s  . c  om
    Statement stmt = null;
    ResultSet rs = null;
    ResultSetMetaData rsm = null;

    OutputStream out = response.getOutputStream();
    try {

        DefaultXYZDataset dataset = new DefaultXYZDataset();
        double[] x = { 2.1, 2.3, 2.3, 2.2, 2.2, 1.8, 1.8, 1.9, 2.3, 3.8 };
        double[] y = { 14.1, 11.1, 10.0, 8.8, 8.7, 8.4, 5.4, 4.1, 4.1, 25 };
        double[] z = { 2.4, 2.7, 2.7, 2.2, 2.2, 2.2, 2.1, 2.2, 1.6, 4 };
        double[][] series = new double[][] { x, y, z };
        dataset.addSeries("Series 1", series);

        JFreeChart chart = ChartFactory.createBubbleChart("Bubble Chart Demo 1", "X", "Y", dataset,
                PlotOrientation.HORIZONTAL, true, true, true);
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setForegroundAlpha(0.65f);

        XYItemRenderer renderer = plot.getRenderer();
        renderer.setSeriesPaint(0, Color.blue);

        // increase the margins to account for the fact that the auto-range
        // doesn't take into account the bubble size...
        NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
        domainAxis.setLowerMargin(0.15);
        domainAxis.setUpperMargin(0.15);
        NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setLowerMargin(0.15);
        rangeAxis.setUpperMargin(0.15);

        response.setContentType("image/png");
        int width = 800;
        int height = 600;
        ChartUtilities.writeChartAsPNG(out, chart, width, height);

    } catch (Exception e) {
        throw new ServletException(e);
    }

}

From source file:edu.umd.cs.submitServer.servlets.ImportProject.java

/**
 * The doPost method of the servlet. <br>
 * //from  w w  w .  j  a va 2s  .com
 * This method is called when a form has its tag value method equals to
 * post.
 * 
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    FileItem fileItem = null;
    boolean transactionSuccess = false;
    try {
        conn = getConnection();

        // MultipartRequestFilter is required
        MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
        Course course = (Course) request.getAttribute(COURSE);
        StudentRegistration canonicalStudentRegistration = StudentRegistration.lookupByStudentRegistrationPK(
                multipartRequest.getIntParameter("canonicalStudentRegistrationPK", 0), conn);

        fileItem = multipartRequest.getFileItem();

        conn.setAutoCommit(false);
        /*
         * 20090608: changed TRANSACTION_READ_COMMITTED to
         * TRANSACTION_REPEATABLE_READ to make transaction compatible with
         * innodb in MySQL 5.1, which defines READ_COMMITTED as unsafe for
         * use with standard binary logging. For more information, see:
         * <http
         * ://dev.mysql.com/doc/refman/5.1/en/set-transaction.html#isolevel_read
         * -committed>
         */
        conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);

        Project project = Project.importProject(fileItem.getInputStream(), course, canonicalStudentRegistration,
                conn);

        conn.commit();
        transactionSuccess = true;

        String redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
        response.sendRedirect(redirectUrl);

    } catch (ClassNotFoundException e) {
        throw new ServletException(e);
    } catch (SQLException e) {
        throw new ServletException(e);
    } finally {
        rollbackIfUnsuccessfulAndAlwaysReleaseConnection(transactionSuccess, request, conn);
    }
}

From source file:com.bluexml.xforms.actions.EditFormAction.java

/**
 * Finds the appropriate form for the object being edited and sets some page info.
 * //from www .  j a  va2  s. com
 * @param pageBean
 * @param editBean
 * @param targetForms
 *            the comma separated list of target forms, initially added in the modeler and
 *            written in the XHTML template
 * @throws ServletException
 */
private void resolvePageInfo(PageInfoBean pageBean, EditNodeBean editBean, String targetForms)
        throws ServletException {
    String[] forms = StringUtils.split(targetForms, ',');
    boolean found = false;
    if (forms == null) {
        found = resolvePageInfoClass(pageBean, editBean);
    } else {
        found = resolvePageInfoForm(pageBean, editBean, forms);
    }
    if (found == false) {
        throw new ServletException("No generated form able to edit this object was found.");
    }
}

From source file:com.jaspersoft.jasperserver.api.metadata.user.service.impl.JIPortletAuthenticationProcessingFilter.java

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

    if (logger.isDebugEnabled()) {
        logger.debug("Trusted Host Authentication.");
    }/*from  www .java 2 s .co m*/

    String incomingIPAddress = request.getRemoteAddr();
    // if not from trusted host, skip this filter totally
    if ((incomingIPAddress == null) || (!isFromTrustedHost(incomingIPAddress))) {
        chain.doFilter(request, response);
        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Requested from Trusted Host IP:" + incomingIPAddress);
    }

    List roleList = new ArrayList();

    if (!(request instanceof HttpServletRequest)) {
        throw new ServletException("Can only process HttpServletRequest");
    }

    if (!(response instanceof HttpServletResponse)) {
        throw new ServletException("Can only process HttpServletResponse");
    }

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Credentials credentials = getUserCredentials(httpRequest);
    String userName = credentials.getUserName();
    String password = credentials.getPassword();

    if ((userName == null) || (userName.trim().length() == 0)) {
        chain.doFilter(request, response);
        return;
    }

    // skip any actions when the authentication object already exists.
    Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
    if ((existingAuth != null) && (existingAuth.getName().equals(userName))
            && (existingAuth.isAuthenticated())) {
        // if already authenticated, set the trusted host flag so that 
        // subsequent filters (such as the Basic auth filter) know it's a
        // portlet authentication
        request.setAttribute("fromTrustedHost", "true");

        chain.doFilter(request, response);
        return;
    }

    // starting the flow       
    // user exist
    if (doesUserExist(userName)) {
        // is it an internal user
        if (isInternalUser(userName)) {
            String oldPassword = getUserPaswordFromRepository(userName);
            // update password if they are different
            if (!haveSamePassword(oldPassword, password)) {
                updatePassword(userName, password);
                if (logger.isDebugEnabled()) {
                    logger.debug("Updated Password for User:" + userName);
                }
            }
        }
        // get list of role
        roleList = getUserRoleList(userName);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Created New User:" + userName);
        }
        // create an internal user
        roleList.add("ROLE_USER");
        roleList.add("ROLE_PORTLET");
        createUserWithRoles(userName, password, roleList, false);
    }
    SecurityContextHolder.getContext()
            .setAuthentication(createAuthenticationObject(userName, password, roleList, request));
    // it's authenticated thru trusted host
    request.setAttribute("fromTrustedHost", "true");

    if (logger.isDebugEnabled()) {
        logger.debug("Created Authentication Object within JIPortletAuthenticationProcessingFilter");
    }

    chain.doFilter(request, response);
}