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:test.unit.be.fedict.eid.applet.service.IdentityDataMessageHandlerTest.java

public void testHandleMessageCorruptIntegritySignature() throws Exception {
    // setup// w  w  w  .j  a  va2  s. co  m
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(),
            "CN=TestNationalRegistration", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null,
            null);

    ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class);
    Map<String, String> httpHeaders = new HashMap<String, String>();
    HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class);
    HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class);

    EasyMock.expect(mockServletConfig.getInitParameter("IdentityIntegrityService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("IdentityIntegrityServiceClass"))
            .andStubReturn(IdentityIntegrityTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass"))
            .andStubReturn(AuditTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("SkipNationalNumberCheck")).andStubReturn(null);

    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_ADDRESS_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_CERTIFICATES_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_PHOTO_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);

    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address");

    byte[] idFile = "foobar-id-file".getBytes();
    IdentityDataMessage message = new IdentityDataMessage();
    message.idFile = idFile;

    message.identitySignatureFile = "foobar-signature".getBytes();
    message.rrnCertFile = certificate.getEncoded();

    // prepare
    EasyMock.replay(mockServletConfig, mockHttpSession, mockServletRequest);

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    try {
        this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession);
        fail();
    } catch (ServletException e) {
        LOG.debug("expected exception: " + e.getMessage(), e);
        LOG.debug("exception type: " + e.getClass().getName());
        // verify
        EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest);
        assertNull(IdentityIntegrityTestService.getCertificate());
        assertEquals("remote-address", AuditTestService.getAuditIntegrityRemoteAddress());
    }
}

From source file:test.unit.be.fedict.eid.applet.service.IdentityDataMessageHandlerTest.java

public void testHandleMessageInvalidIntegritySignature() throws Exception {
    // setup/*from  w  ww.  ja  v  a  2 s . c om*/
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(),
            "CN=TestNationalRegistration", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null,
            null);

    ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class);
    Map<String, String> httpHeaders = new HashMap<String, String>();
    HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class);
    HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class);

    EasyMock.expect(mockServletConfig.getInitParameter("IdentityIntegrityService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("IdentityIntegrityServiceClass"))
            .andStubReturn(IdentityIntegrityTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass"))
            .andStubReturn(AuditTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("SkipNationalNumberCheck")).andStubReturn(null);

    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address");

    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_ADDRESS_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_CERTIFICATES_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockHttpSession.getAttribute(RequestContext.INCLUDE_PHOTO_SESSION_ATTRIBUTE))
            .andStubReturn(false);
    EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES))
            .andReturn(null);

    byte[] idFile = "foobar-id-file".getBytes();
    IdentityDataMessage message = new IdentityDataMessage();
    message.idFile = idFile;

    KeyPair intruderKeyPair = MiscTestUtils.generateKeyPair();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(intruderKeyPair.getPrivate());
    signature.update(idFile);
    byte[] idFileSignature = signature.sign();
    message.identitySignatureFile = idFileSignature;
    message.rrnCertFile = certificate.getEncoded();

    // prepare
    EasyMock.replay(mockServletConfig, mockHttpSession, mockServletRequest);

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    try {
        this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession);
        fail();
    } catch (ServletException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // verify
        EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest);
        assertNull(IdentityIntegrityTestService.getCertificate());
        assertEquals("remote-address", AuditTestService.getAuditIntegrityRemoteAddress());
    }
}

From source file:com.kurento.kmf.content.internal.base.AbstractHttpContentSession.java

@Override
protected void sendErrorAnswerOnInitialContext(int code, String description) {
    if (useControlProtocol) {
        super.sendErrorAnswerOnInitialContext(code, description);
    } else {//  w w  w . j  a v a2  s  .  c  o  m
        try {
            ServletUtils.sendHttpError((HttpServletRequest) initialAsyncCtx.getRequest(),
                    (HttpServletResponse) initialAsyncCtx.getResponse(), ExceptionUtils.getHttpErrorCode(code),
                    description);
        } catch (ServletException e) {
            getLogger().error(e.getMessage(), e);
            throw new KurentoMediaFrameworkException(e, 20026);
        }
    }
}

From source file:com.kurento.kmf.content.internal.base.AbstractHttpContentSession.java

@Override
protected void sendRejectOnInitialContext(int code, String description) {
    if (useControlProtocol) {
        super.sendRejectOnInitialContext(code, description);
    } else {//from  ww  w . ja va 2 s  .  co  m
        try {
            ServletUtils.sendHttpError((HttpServletRequest) initialAsyncCtx.getRequest(),
                    (HttpServletResponse) initialAsyncCtx.getResponse(), ExceptionUtils.getHttpErrorCode(code),
                    description);
        } catch (ServletException e) {
            getLogger().error(e.getMessage(), e);
            throw new KurentoMediaFrameworkException(e, 20026);
        }
    }
}

From source file:org.xdi.oxauth.auth.AuthenticationFilter.java

private void processBearerAuth(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        FilterChain filterChain) {/*from  www  .  ja v a 2s. c o m*/
    try {
        String header = servletRequest.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {
            // Immutable object
            //servletRequest.getParameterMap().put("access_token", new String[]{accessToken});
            filterChain.doFilter(servletRequest, servletResponse);
        }
    } catch (ServletException ex) {
        log.info("Bearer authorization failed: {0}", ex, ex.getMessage());
    } catch (IOException ex) {
        log.info("Bearer authorization failed: {0}", ex, ex.getMessage());
    } catch (Exception ex) {
        log.info("Bearer authorization failed: {0}", ex, ex.getMessage());
    }
}

From source file:com.persistent.cloudninja.controller.CloudNinjaAuthFilter.java

private void forwardToLandingPage(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, FilterChain chain, CloudNinjaUser cloudNinjaUser) {
    UserActivityQueue userActivityQueue = UserActivityQueue.getUserActivityQueue();
    String tenantId = null;//ww  w. jav  a 2s  .  co m

    synchronized (userActivityQueue) {
        try {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            String date = dateFormat.format(calendar.getTime());

            UserActivityQueueMessage message;
            String cookie = httpServletRequest.getAttribute("cookieNameAttr").toString();
            tenantId = AuthFilterUtils.getFieldValueFromCookieString(CloudNinjaConstants.COOKIE_TENANTID_PREFIX,
                    cookie);

            message = new UserActivityQueueMessage(tenantId, cloudNinjaUser.getMemberId(),
                    dateFormat.parse(date));

            userActivityQueue.add(message);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    try {
        rsBundle = ResourceBundle.getBundle("acs");
        String landingPageURL = "/" + tenantId;
        landingPageURL = landingPageURL + rsBundle.getString("tenant.dashboard.landing.page.url").trim();
        httpServletRequest.getRequestDispatcher(landingPageURL).forward(httpServletRequest,
                httpServletResponse);
    } catch (ServletException exception) {
        logger.error(exception.getMessage());
        exception.printStackTrace();
    } catch (IOException exception) {
        logger.error(exception.getMessage());
        exception.printStackTrace();
    }

}

From source file:test.unit.be.fedict.eid.applet.service.SignatureDataMessageHandlerTest.java

@Test
public void testHandleMessageInvalidSignature() throws Exception {
    // setup//from  w  w w. j av a  2  s  .  c  om
    KeyPair keyPair = MiscTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusYears(1);
    X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test", notBefore,
            notAfter, null, keyPair.getPrivate(), true, 0, null, null);

    ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class);
    Map<String, String> httpHeaders = new HashMap<String, String>();
    HttpSession mockHttpSession = EasyMock.createMock(HttpSession.class);
    HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class);

    EasyMock.expect(mockServletConfig.getInitParameter("AuditService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("AuditServiceClass"))
            .andStubReturn(AuditTestService.class.getName());
    EasyMock.expect(mockServletConfig.getInitParameter("SignatureService")).andStubReturn(null);
    EasyMock.expect(mockServletConfig.getInitParameter("SignatureServiceClass"))
            .andStubReturn(SignatureTestService.class.getName());

    EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("remote-address");

    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    byte[] document = "hello world".getBytes();
    byte[] digestValue = messageDigest.digest(document);
    EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_VALUE_SESSION_ATTRIBUTE))
            .andStubReturn(digestValue);
    EasyMock.expect(mockHttpSession.getAttribute(SignatureDataMessageHandler.DIGEST_ALGO_SESSION_ATTRIBUTE))
            .andStubReturn("SHA-1");

    SignatureDataMessage message = new SignatureDataMessage();
    message.certificateChain = new LinkedList<X509Certificate>();
    message.certificateChain.add(certificate);

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(keyPair.getPrivate());
    signature.update("foobar-document".getBytes());
    byte[] signatureValue = signature.sign();
    message.signatureValue = signatureValue;

    // prepare
    EasyMock.replay(mockServletConfig, mockHttpSession, mockServletRequest);

    // operate
    AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance);
    this.testedInstance.init(mockServletConfig);
    try {
        this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, mockHttpSession);
        fail();
    } catch (ServletException e) {
        LOG.debug("expected exception: " + e.getMessage());
        // verify
        EasyMock.verify(mockServletConfig, mockHttpSession, mockServletRequest);
        assertNull(SignatureTestService.getSignatureValue());
        assertEquals("remote-address", AuditTestService.getAuditSignatureRemoteAddress());
        assertEquals(certificate, AuditTestService.getAuditSignatureClientCertificate());
    }
}

From source file:org.apache.myfaces.context.servlet.ServletExternalContextImpl.java

public void dispatch(String requestURI) throws IOException, FacesException {
    RequestDispatcher requestDispatcher = _servletRequest.getRequestDispatcher(requestURI);

    // If there is no dispatcher, send NOT_FOUND
    if (requestDispatcher == null) {
        ((HttpServletResponse) _servletResponse).sendError(HttpServletResponse.SC_NOT_FOUND);

        return;//from   w  w w . jav  a 2  s .  c o  m
    }

    try {
        requestDispatcher.forward(_servletRequest, _servletResponse);
    } catch (ServletException e) {
        if (e.getMessage() != null) {
            throw new FacesException(e.getMessage(), e);
        } else {
            throw new FacesException(e);
        }
    }
}

From source file:org.zilverline.core.TestIndexException.java

/**
 * This methods tests ServletException and 1.4 Throwable cause hierarchy.
 *///from ww w. j a v  a 2  s  .c  o  m
public void testExceptionHierarchy() {
    try {
        try {
            throw new Exception("Error");
        } catch (Exception e) {
            try {
                throw new IndexException("Error in Index", e);
            } catch (IndexException ie) {
                throw new ServletException("Error in Servlet", ie);
            }
        }
    } catch (ServletException se) {
        Throwable rootCause = se.getRootCause();
        Throwable seCause = se.getCause();

        assertNotNull(rootCause);
        assertNull(seCause);
        assertEquals("Error in Index", rootCause.getMessage());

        Throwable cause = rootCause.getCause();

        assertNotNull(cause);
        assertEquals("Error", cause.getMessage());
        assertEquals("Error in Servlet", se.getMessage());
    }
}

From source file:org.apache.geronimo.daytrader.javaee6.web.TradeAppServlet.java

/**
 * Main service method for TradeAppServlet
 * //from w  ww .j  av a 2 s  .  c o  m
 * @param request
 *            Object that encapsulates the request to the servlet
 * @param response
 *            Object that encapsulates the response from the servlet
 */
@SuppressWarnings("deprecation")
public void performTask(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String action = null;
    String userID = null;
    // String to create full dispatch path to TradeAppServlet w/ request
    // Parameters
    String dispPath = null; // Dispatch Path to TradeAppServlet

    resp.setContentType("text/html");
    TradeServletAction tsAction = new TradeServletAction();

    // Dyna - need status string - prepended to output
    action = req.getParameter("action");

    ServletContext ctx = getServletConfig().getServletContext();

    if (action == null) {
        tsAction.doWelcome(ctx, req, resp, "");
        return;
    } else if (action.equals("login")) {
        userID = req.getParameter("uid");
        String passwd = req.getParameter("passwd");
        String inScenario = req.getParameter("inScenario");
        try {
            tsAction.doLogin(ctx, req, resp, userID, passwd);
        } catch (ServletException se) {
            tsAction.doWelcome(ctx, req, resp, se.getMessage());
        }
        return;
    } else if (action.equals("register")) {
        userID = req.getParameter("user id");
        String passwd = req.getParameter("passwd");
        String cpasswd = req.getParameter("confirm passwd");
        String fullname = req.getParameter("Full Name");
        String ccn = req.getParameter("Credit Card Number");
        String money = req.getParameter("money");
        String email = req.getParameter("email");
        String smail = req.getParameter("snail mail");
        tsAction.doRegister(ctx, req, resp, userID, passwd, cpasswd, fullname, ccn, money, email, smail);
        return;
    } else if (action.equals("registerproxy")) {
        String code = req.getParameter("code");
        String state = req.getParameter("state");
        String foros = "code=" + code + "&client_id=" + CLIENT_ID +
        //               "&client_secret=" +CLIENT_SECRET + "&grant_type=authorization_code&redirect_uri=http://localhost:8080/daytrader/app?action=registerproxy";
                "&client_secret=" + CLIENT_SECRET + "&grant_type=authorization_code&redirect_uri=" + HOST_URL
                + "daytrader/app?action=registerproxy";

        String url = "https://accounts.google.com/o/oauth2/token";
        System.out.println("Url:" + url);
        HttpClient client = new HttpClient();
        PostMethod httppost = new PostMethod(url);
        //httppost
        httppost.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        //ByteArrayRequestEntity entity = new ByteArrayRequestEntity(foros.getBytes("UTF-8"));
        //httppost.set
        System.out.println("Foros :" + foros);
        httppost.addParameter("grant_type", "authorization_code");
        httppost.addParameter("code", code);
        httppost.addParameter("client_id", CLIENT_ID);
        httppost.addParameter("client_secret", CLIENT_SECRET);

        //httppost.addParameter("redirect_uri","http://localhost:8080/daytrader/app?action=registerproxy" );      

        // httppost.setRequestBody(foros);
        // httppost.setEntity(entity);

        httppost.addParameter("redirect_uri", HOST_URL + "daytrader/app?action=registerproxy");

        // httppost.setRequestBody(foros);
        // httppost.setEntity(entity);

        String accessToken = null;
        try {
            // client.set

            int responseCode = client.executeMethod(httppost);
            String jsonResponse = httppost.getResponseBodyAsString();

            System.out.println("jsonResponse:" + jsonResponse);
            JSONObject jsonParser = new JSONObject(jsonResponse);
            accessToken = (String) jsonParser.getString("access_token");
            System.out.println("Access Token:" + accessToken);

            GetMethod userInfoGet = new GetMethod(GOOGLE_SSO_URL + accessToken);

            String googleId = null;
            String email = null;
            String name = null;
            String firstName = null;
            String lastName = null;
            try {
                responseCode = client.executeMethod(userInfoGet);
                String userInfo = userInfoGet.getResponseBodyAsString();

                JSONObject userInfoParser = new JSONObject(userInfo);

                googleId = (String) userInfoParser.getString("id");
                email = (String) userInfoParser.getString("email");
                name = (String) userInfoParser.getString("name");
                firstName = (String) userInfoParser.getString("given_name");
                lastName = (String) userInfoParser.getString("family_name");
                userID = email;
                try {//tsAction.
                    String results = "";
                    try {
                        tsAction.doCheck(ctx, req, resp, userID, results);
                        tsAction.doLogin(ctx, req, resp, userID);
                    } catch (Exception ex) {
                        results = "NOT_FOUND";
                        tsAction.doRegister(ctx, req, resp, email, "password", "password",
                                firstName + " " + lastName, "CCN", "500", email, "Please update Address");
                        req.getRequestDispatcher("/app?action=login&uid=" + email + "&passwd=password")
                                .forward(req, resp);
                    }
                    /*Log.error("Looking for request status: "+ results);
                    if (results.equals("FOUND"))
                               
                    else */

                } catch (Exception ex) {
                    //tsAction.doLogin(ctx, req, resp, userID, passwd);
                }

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

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

    }

    // The rest of the operations require the user to be logged in -
    // Get the Session and validate the user.
    HttpSession session = req.getSession();
    userID = (String) session.getAttribute("uidBean");

    if (userID == null) {
        System.out.println("TradeAppServlet service error: User Not Logged in");
        tsAction.doWelcome(ctx, req, resp, "User Not Logged in");
        return;
    }
    if (action.equals("quotes")) {
        String symbols = req.getParameter("symbols");
        tsAction.doQuotes(ctx, req, resp, userID, symbols);
    } else if (action.equals("buy")) {
        String symbol = req.getParameter("symbol");
        String quantity = req.getParameter("quantity");
        tsAction.doBuy(ctx, req, resp, userID, symbol, quantity);
    } else if (action.equals("sell")) {
        int holdingID = Integer.parseInt(req.getParameter("holdingID"));
        tsAction.doSell(ctx, req, resp, userID, new Integer(holdingID));
    } else if (action.equals("portfolio") || action.equals("portfolioNoEdge")) {
        tsAction.doPortfolio(ctx, req, resp, userID, "Portfolio as of " + new java.util.Date());
    } else if (action.equals("logout")) {
        tsAction.doLogout(ctx, req, resp, userID);
    } else if (action.equals("home")) {
        tsAction.doHome(ctx, req, resp, userID, "Ready to Trade");
    } else if (action.equals("account")) {
        tsAction.doAccount(ctx, req, resp, userID, "");
    } else if (action.equals("update_profile")) {
        String password = req.getParameter("password");
        String cpassword = req.getParameter("cpassword");
        String fullName = req.getParameter("fullname");
        String address = req.getParameter("address");
        String creditcard = req.getParameter("creditcard");
        String email = req.getParameter("email");
        tsAction.doAccountUpdate(ctx, req, resp, userID, password == null ? "" : password.trim(),
                cpassword == null ? "" : cpassword.trim(), fullName == null ? "" : fullName.trim(),
                address == null ? "" : address.trim(), creditcard == null ? "" : creditcard.trim(),
                email == null ? "" : email.trim());
    } else {
        System.out.println("TradeAppServlet: Invalid Action=" + action);
        tsAction.doWelcome(ctx, req, resp, "TradeAppServlet: Invalid Action" + action);
    }
}