Example usage for javax.servlet.http HttpServletResponse SC_FOUND

List of usage examples for javax.servlet.http HttpServletResponse SC_FOUND

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_FOUND.

Prototype

int SC_FOUND

To view the source code for javax.servlet.http HttpServletResponse SC_FOUND.

Click Source Link

Document

Status code (302) indicating that the resource reside temporarily under a different URI.

Usage

From source file:org.wso2.carbon.identity.oauth.ui.client.OAuth2AuthzClient.java

public String handleAuthorizationRequest(HttpServletRequest request, HttpServletResponse response)
        throws OAuthSystemException {

    OAuth2Parameters oauth2Params = (OAuth2Parameters) request.getSession()
            .getAttribute(OAuthConstants.OAUTH2_PARAMS);

    // user has denied the authorization. Send back the error code.
    if ("true".equals(request.getParameter("deny"))) {
        return OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND)
                .setError(OAuth2ErrorCodes.ACCESS_DENIED).location(oauth2Params.getRedirectURI())
                .setState(oauth2Params.getState()).buildQueryMessage().getLocationUri();
    }/*w  w  w  .  ja  v a 2s  .c  o  m*/

    try {
        OAuth2AuthorizeRespDTO authzRespDTO = authorize(request, oauth2Params);
        // Authentication Failure, send back to the login page
        if (!authzRespDTO.getAuthenticated()) {
            return "../../carbon/oauth/oauth2_authn_ajaxprocessor.jsp?auth_status=failed";
        }

        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);

        OAuthResponse oauthResponse;

        // user is authorized.
        if (authzRespDTO.getAuthorized()) {

            if (ResponseType.CODE.toString().equals(oauth2Params.getResponseType())) {
                builder.setCode(authzRespDTO.getAuthorizationCode());
            } else if (ResponseType.TOKEN.toString().equals(oauth2Params.getResponseType())) {
                builder.setAccessToken(authzRespDTO.getAccessToken());
                builder.setExpiresIn(String.valueOf(60 * 60));
            }

            builder.setParam("state", oauth2Params.getState());
            String redirectURL = authzRespDTO.getCallbackURI();
            oauthResponse = builder.location(redirectURL).buildQueryMessage();

        } else {
            OAuthProblemException oauthException = OAuthProblemException.error(authzRespDTO.getErrorCode(),
                    authzRespDTO.getErrorMsg());
            oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(oauthException)
                    .location(authzRespDTO.getCallbackURI()).setState(oauth2Params.getState())
                    .buildQueryMessage();
        }
        response.setStatus(HttpServletResponse.SC_FOUND);
        request.getSession().removeAttribute(OAuthConstants.OAUTH2_PARAMS);
        return oauthResponse.getLocationUri();

    } catch (OAuthProblemException e) {
        log.error(e.getError(), e.getCause());
        return OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e)
                .location(oauth2Params.getRedirectURI()).buildQueryMessage().getLocationUri();
    }
}

From source file:com.google.api.server.spi.handlers.ExplorerHandlerTest.java

private void testHandle(String scheme, int port, String expectedLocation) throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setScheme(scheme);//from w  w  w.j  a  v a 2 s .  c om
    request.setServerName("localhost");
    request.setServerPort(port);
    request.setRequestURI("/_ah/api/explorer/");
    MockHttpServletResponse response = new MockHttpServletResponse();
    ExplorerHandler handler = new ExplorerHandler();
    EndpointsContext context = new EndpointsContext("GET", "explorer", request, response);
    handler.handle(context);

    assertThat(response.getStatus()).isEqualTo(HttpServletResponse.SC_FOUND);
    assertThat(response.getHeader("Location")).isEqualTo(expectedLocation);
}

From source file:com.google.api.server.spi.EndpointsServletTest.java

@Test
public void explorer() throws IOException {
    req.setRequestURI("/_ah/api/explorer/");
    req.setMethod("GET");

    servlet.service(req, resp);/*from  w  w w  . ja v  a2s .  c o  m*/

    assertThat(resp.getStatus()).isEqualTo(HttpServletResponse.SC_FOUND);
    assertThat(resp.getHeader("Location")).isEqualTo(
            "http://apis-explorer.appspot.com/apis-explorer/?base=" + API_ROOT + "&root=" + API_ROOT);
}

From source file:org.piraso.web.base.PirasoResponseWrapperTest.java

@Test
public void testSetStatus() throws Exception {
    wrapper.setStatus(HttpServletResponse.SC_ACCEPTED);
    assertEquals(HttpServletResponse.SC_ACCEPTED, entry.getStatus());

    wrapper.setStatus(HttpServletResponse.SC_FOUND, "found");
    assertEquals(HttpServletResponse.SC_FOUND, entry.getStatus());
    assertEquals("found", entry.getStatusReason());
}

From source file:org.wso2.carbon.identity.oauth.endpoint.expmapper.InvalidRequestExceptionMapper.java

@Override
public Response toResponse(InvalidRequestParentException exception) {

    if (exception instanceof InvalidRequestException) {
        try {/*from   w w w .  ja  v  a2s  .c  o m*/
            return buildErrorResponse(exception, HttpServletResponse.SC_FOUND,
                    OAuth2ErrorCodes.INVALID_REQUEST);
        } catch (URISyntaxException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while getting endpoint error page URL", e);
            }
            return handleInternalServerError();
        }
    } else if (exception instanceof AccessDeniedException) {
        try {
            return buildErrorResponse(exception, HttpServletResponse.SC_FOUND, OAuth2ErrorCodes.ACCESS_DENIED);
        } catch (URISyntaxException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while getting endpoint error page URL", e);
            }
            return handleInternalServerError();
        }
    } else if (exception instanceof InvalidApplicationClientException) {
        try {
            return buildErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, exception,
                    OAuth2ErrorCodes.INVALID_CLIENT);
        } catch (OAuthSystemException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while getting endpoint error page URL", e);
            }
            return handleInternalServerError();
        }
    } else if (exception instanceof BadRequestException) {
        try {
            return buildErrorResponse(exception, HttpServletResponse.SC_BAD_REQUEST,
                    OAuth2ErrorCodes.INVALID_REQUEST);
        } catch (URISyntaxException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while getting endpoint error page URL", e);
            }
            return handleInternalServerError();
        }
    } else if (exception instanceof TokenEndpointBadRequestException
            || exception instanceof RevokeEndpointBadRequestException) {
        try {
            return buildErrorResponse(HttpServletResponse.SC_BAD_REQUEST, exception,
                    OAuth2ErrorCodes.INVALID_REQUEST);
        } catch (OAuthSystemException e) {
            if (log.isDebugEnabled()) {
                log.debug("OAuth System error while token invoking token/revoke endpoints", e);
            }
            return handleInternalServerError();
        }

    } else if (exception instanceof TokenEndpointAccessDeniedException) {
        try {
            return buildErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, exception,
                    OAuth2ErrorCodes.INVALID_CLIENT);
        } catch (OAuthSystemException e) {
            if (log.isDebugEnabled()) {
                log.debug("OAuth System error while token invoking token endpoint", e);
            }
            return handleInternalServerError();
        }
    } else if (exception instanceof RevokeEndpointAccessDeniedException) {
        try {
            return buildRevokeUnauthorizedErrorResponse(exception);
        } catch (OAuthSystemException e) {
            if (log.isDebugEnabled()) {
                log.debug("OAuth System error while revoke invoking revoke endpoint", e);
            }
            return handleInternalServerError();
        }
    } else if (exception instanceof ConsentHandlingFailedException) {
        try {
            return buildErrorResponseConsentHandlingFailure(exception);
        } catch (URISyntaxException e) {
            if (log.isDebugEnabled()) {
                log.debug("Error while getting endpoint error page URL", e);
            }
            return handleInternalServerError();
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("OAuth System error while processing request: ", exception);
        }
        return handleInternalServerError();
    }
}

From source file:org.testdwr.custom.CustomResponseServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    String homePage = request.getContextPath() + request.getServletPath() + "/";

    // Redirect from root dir without trailing slash to with trailing slash
    if (pathInfo == null) {
        response.sendRedirect(homePage);
        return;/*from w w  w  . j  a va2s.  co m*/
    }
    // Send home page
    else if (pathInfo.equals("/") || pathInfo.startsWith("/page")) {
        InputStream in = getClass().getResourceAsStream(RESOURCE_HELP);
        if (in == null) {
            log.error("Missing file " + RESOURCE_HELP);
            response.sendError(500, "Missing file " + RESOURCE_HELP);
        } else {
            response.setContentType("text/html");
            ServletOutputStream out = response.getOutputStream();
            CopyUtils.copy(in, out);
        }
    }
    // Send empty page
    else if (pathInfo.startsWith("/empty")) {
        response.setContentType("text/html");
    }
    // Handle redirects
    else if (pathInfo.matches("\\/redirect\\/[1-9][0-9][0-9]\\/.*")) {
        String responseCodeStr = pathInfo.substring(10, 10 + 3);
        int responseCode = Integer.parseInt(responseCodeStr);
        String redirectPath = URLDecoder.decode(pathInfo.substring(13), "utf-8");
        redirectPath = request.getContextPath() + request.getServletPath() + redirectPath;

        log.info("Sending " + responseCode + ":" + redirectPath + "(" + pathInfo + ")");
        switch (responseCode) {
        case HttpServletResponse.SC_MULTIPLE_CHOICES:
        case HttpServletResponse.SC_MOVED_PERMANENTLY:
        case HttpServletResponse.SC_FOUND:
        case HttpServletResponse.SC_SEE_OTHER:
            response.setHeader("Location", "/" + redirectPath);
            response.setStatus(responseCode);
            break;

        case HttpServletResponse.SC_TEMPORARY_REDIRECT:
            response.sendRedirect(redirectPath);
            break;

        default:
            response.sendError(responseCode, "/" + redirectPath);
            break;
        }
    }
    // Send 404
    else {
        response.sendError(404);
    }
}

From source file:org.piraso.web.base.PirasoResponseWrapperTest.java

@Test
public void testSetStatusWithReason() throws Exception {
    wrapper.setStatus(HttpServletResponse.SC_FOUND, "found");
    assertEquals(HttpServletResponse.SC_FOUND, entry.getStatus());
    assertEquals("found", entry.getStatusReason());
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AuthorizeController.java

@RequestMapping("/authentication")
public Object authorize(HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
    try {//  w  ww  .  jav a  2 s  .  c o m

        // OAuth ?
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);

        // id?
        if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                    .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION).buildJSONMessage();
            return new ResponseEntity<String>(response.getBody(),
                    HttpStatus.valueOf(response.getResponseStatus()));
        }

        Subject subject = SecurityUtils.getSubject();
        // ?
        if (!subject.isAuthenticated()) {
            if (!login(subject, request)) {// ?
                // TODO
                HttpHeaders headers = new HttpHeaders();
                headers.setLocation(new URI(loginUrl));
                return new ResponseEntity<Object>(headers, HttpStatus.UNAUTHORIZED);
            }
        }

        String username = (String) subject.getPrincipal();
        // ???
        String authorizationCode = null;
        // responseType??CODE?TOKEN
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
        // OAuth?
        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);
        if (responseType.equals(ResponseType.CODE.toString())) {
            authorizationCode = oauthIssuerImpl.authorizationCode();
            oAuthService.addAuthCode(authorizationCode, username);
            // ??
            builder.setCode(authorizationCode);
        } else if (responseType.equals(ResponseType.TOKEN.toString())) {
            final String accessToken = oauthIssuerImpl.accessToken();
            oAuthService.addAccessToken(accessToken, username);
            builder.setAccessToken(accessToken);
            builder.setParam("token_type", TokenType.BEARER.toString());
            builder.setExpiresIn(oAuthService.getExpireIn());
        }

        // ???
        String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);

        // ?
        final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();

        // ?OAuthResponseResponseEntity?
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity<Object>(headers, HttpStatus.valueOf(response.getResponseStatus()));
    } catch (OAuthProblemException e) {
        // ?
        String redirectUri = e.getRedirectUri();
        if (OAuthUtils.isEmpty(redirectUri)) {
            // redirectUri
            return new ResponseEntity<String>("OAuth callback url needs to be provided by client!!!",
                    HttpStatus.NOT_FOUND);
        }

        // ??error=
        final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e)
                .location(redirectUri).buildQueryMessage();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity<Object>(headers, HttpStatus.valueOf(response.getResponseStatus()));
    }
}

From source file:net.ymate.module.oauth.impl.ImplicitGrantProcessor.java

@Override
public OAuthResponse process(HttpServletRequest request) throws Exception {
    OAuthResponse _response;/*from  w w w  .  ja  va2  s  . com*/
    try {
        OAuthAuthzRequest _oauthRequest = new OAuthAuthzRequest(request);
        if (!StringUtils.equalsIgnoreCase(__responseType.toString(), _oauthRequest.getResponseType())) {
            _response = buildError(IOAuth.ErrorType.UNSUPPORTED_RESPONSE_TYPE);
        } else {
            Set<String> _scopes = _oauthRequest.getScopes();
            _scopes.add(IOAuth.Const.SCOPE_SNSAPI_BASE);
            //
            String _uid = getParam(IOAuth.Const.UID).toStringValue();
            String _redirectURI = _oauthRequest.getRedirectURI();
            //
            if (StringUtils.isBlank(_uid)) {
                _response = buildError(IOAuth.ErrorType.INVALID_USER);
            } else if (StringUtils.isBlank(_redirectURI)) {
                _response = buildError(IOAuth.ErrorType.INVALID_REDIRECT_URI);
            } else if (!getOwner().getScopeNames().containsAll(_scopes)) {
                _response = buildError(IOAuth.ErrorType.INVALID_SCOPE);
            } else {
                OAuthClientBean _client = getClient(_oauthRequest.getClientId());
                if (_client == null) {
                    _response = buildError(IOAuth.ErrorType.INVALID_CLIENT);
                } else if (!_client.checkDomain(_redirectURI)) {
                    _response = buildError(IOAuth.ErrorType.REDIRECT_URI_MISMATCH);
                } else {
                    String _scope = OAuthUtils.encodeScopes(_scopes);
                    String _state = _oauthRequest.getState();
                    if ("POST".equalsIgnoreCase(request.getMethod())) {
                        if (!getParam(IOAuth.Const.AUTHORIZED).toBooleanValue()) {
                            _response = OAuthASResponse
                                    .authorizationResponse(request, HttpServletResponse.SC_FOUND)
                                    .location(_redirectURI)
                                    .setParam(org.apache.oltu.oauth2.common.OAuth.OAUTH_STATE, _state)
                                    .buildQueryMessage();
                        } else {
                            _response = __doParseResponseType(request, _client.getClientId(), _redirectURI,
                                    _scope, _uid, _state);
                        }
                    } else {
                        OAuthClientUserBean _clientUser = getClientUser(_client.getClientId(), _uid,
                                IdType.UID);
                        if (_scopes.size() > 1 && (_clientUser == null || !_clientUser.isAuthorized())) {
                            // ??
                            throw new NeedAuthorizationException(_client, _uid, _oauthRequest.getScopes());
                        } else {
                            _response = __doParseResponseType(request, _client.getClientId(), _redirectURI,
                                    _scope, _uid, _state);
                        }
                    }
                }
            }
        }
    } catch (OAuthProblemException e) {
        _response = buildError(e);
    }
    return _response;
}

From source file:edu.harvard.i2b2.fhirserver.ws.OAuth2AuthzEndpoint.java

@GET
@Path("authorize")
public Response authorize(@Context HttpServletRequest request, @Context HttpRequest httprequest)
        throws URISyntaxException, OAuthSystemException {
    String authorizationCode = null;
    try {// w w w .  jav  a  2s . c  om
        logger.trace("got request to authorize for OAuth2");
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);
        OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

        // build response according to response_type
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);

        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);

        String redirectURI = oauthRequest.getRedirectURI();
        String state = oauthRequest.getState();
        final OAuthResponse Oresponse = builder.location(redirectURI).buildQueryMessage();
        URI url = new URI(Oresponse.getLocationUri());
        Response response = Response.status(Oresponse.getResponseStatus()).location(url).build();
        if (url == null)
            throw new OAuthSystemException("redirectURI is missing");

        HttpSession session = request.getSession();

        String finalUri = successfulResponse(request);
        // finalUri+="&state="+state;
        logger.info("generated finalUri:" + finalUri);
        session.setAttribute("redirectUri", oauthRequest.getRedirectURI());
        session.setAttribute("clientId", oauthRequest.getClientId());
        session.setAttribute("state", oauthRequest.getState());
        session.setAttribute("scope", oauthRequest.getScopes());

        session.setAttribute("finalUri", finalUri);

        String clientId = (String) oauthRequest.getClientId();
        if (isClientIdValid(clientId) == true) {

            String uri = HttpHelper.getBasePath(request).toString() + "../i2b2/login.xhtml";
            logger.trace("redirecting to:" + uri);
            return Response.status(Status.MOVED_PERMANENTLY).location(new URI(uri))
                    .header("session_id", request.getSession().getId()).build();

        } else
            return Response.status(Status.UNAUTHORIZED).entity("clientId IsNotValid").build();

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).header("xreason", e.getMessage())
                .build();
    }
}