Example usage for javax.servlet.http HttpServletResponse SC_MOVED_TEMPORARILY

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

Introduction

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

Prototype

int SC_MOVED_TEMPORARILY

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

Click Source Link

Document

Status code (302) indicating that the resource has temporarily moved to another location, but that future references should still use the original URI to access the resource.

Usage

From source file:nl.nn.adapterframework.http.HttpSender.java

public String extractResult(HttpMethod httpmethod, ParameterResolutionContext prc, HttpServletResponse response,
        String fileName) throws SenderException, IOException {
    int statusCode = httpmethod.getStatusCode();
    boolean ok = false;
    if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey())) {
        prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode));
        ok = true;// www.j a  v a2 s. c  om
    } else {
        if (statusCode == HttpServletResponse.SC_OK) {
            ok = true;
        } else {
            if (isIgnoreRedirects()) {
                if (statusCode == HttpServletResponse.SC_MOVED_PERMANENTLY
                        || statusCode == HttpServletResponse.SC_MOVED_TEMPORARILY
                        || statusCode == HttpServletResponse.SC_TEMPORARY_REDIRECT) {
                    ok = true;
                }
            }
        }
    }
    if (!ok) {
        throw new SenderException(getLogPrefix() + "httpstatus " + statusCode + ": "
                + httpmethod.getStatusText() + " body: " + getResponseBodyAsString(httpmethod));
    }
    if (response == null) {
        if (fileName == null) {
            if (isBase64()) {
                return getResponseBodyAsBase64(httpmethod);
            } else if (StringUtils.isNotEmpty(getStoreResultAsStreamInSessionKey())) {
                prc.getSession().put(getStoreResultAsStreamInSessionKey(),
                        new ReleaseConnectionAfterReadInputStream(httpmethod,
                                httpmethod.getResponseBodyAsStream()));
                return "";
            } else if (StringUtils.isNotEmpty(getStoreResultAsByteArrayInSessionKey())) {
                InputStream is = httpmethod.getResponseBodyAsStream();
                prc.getSession().put(getStoreResultAsByteArrayInSessionKey(), IOUtils.toByteArray(is));
                return "";
            } else if (isMultipartResponse()) {
                return handleMultipartResponse(httpmethod.getResponseHeader("Content-Type").getValue(),
                        httpmethod.getResponseBodyAsStream(), prc, httpmethod);
            } else {
                //return httpmethod.getResponseBodyAsString();
                return getResponseBodyAsString(httpmethod);
            }
        } else {
            InputStream is = httpmethod.getResponseBodyAsStream();
            File file = new File(fileName);
            Misc.streamToFile(is, file);
            return fileName;
        }
    } else {
        streamResponseBody(httpmethod, response);
        return "";
    }
}

From source file:nz.co.fortytwo.signalk.processor.RestApiProcessor.java

@Override
public void process(Exchange exchange) throws Exception {
    // the Restlet request should be available if needed
    HttpServletRequest request = exchange.getIn(HttpMessage.class).getRequest();
    HttpSession session = request.getSession();
    if (logger.isDebugEnabled()) {

        logger.debug("Request = " + exchange.getIn().getHeader(Exchange.HTTP_SERVLET_REQUEST).getClass());
        logger.debug("Session = " + session.getId());
    }/* w  w w.ja  va2  s.  c  om*/

    if (session.getId() != null) {
        exchange.getIn().setHeader(REST_REQUEST, "true");
        String remoteAddress = request.getRemoteAddr();
        String localAddress = request.getLocalAddr();
        if (Util.sameNetwork(localAddress, remoteAddress)) {
            exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.INTERNAL_IP);
        } else {
            exchange.getIn().setHeader(SignalKConstants.MSG_TYPE, SignalKConstants.EXTERNAL_IP);
        }
        exchange.getIn().setHeader(SignalKConstants.MSG_SRC_IP, remoteAddress);
        exchange.getIn().setHeader(SignalKConstants.MSG_SRC_IP_PORT, request.getRemotePort());
        exchange.getIn().setHeader(SignalKConstants.MSG_SRC_BUS, "rest." + remoteAddress.replace('.', '_'));
        exchange.getIn().setHeader(WebsocketConstants.CONNECTION_KEY, session.getId());

        String path = (String) exchange.getIn().getHeader(Exchange.HTTP_URI);
        if (logger.isDebugEnabled()) {
            logger.debug(exchange.getIn().getHeaders());
            logger.debug(path);
        }

        if (logger.isDebugEnabled())
            logger.debug("Processing the path = " + path);
        if (!isValidPath(path)) {
            exchange.getIn().setBody("Bad Request");
            exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "text/plain");
            exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, HttpServletResponse.SC_BAD_REQUEST);
            // response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("GET")) {
            processGet(exchange, path);
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("PUT")) {
            processPut(exchange, path);
        }
        if (exchange.getIn().getHeader(Exchange.HTTP_METHOD).equals("POST")) {
            if (exchange.getIn().getBody() instanceof StreamCache) {
                StreamCache cache = exchange.getIn().getBody(StreamCache.class);
                ByteArrayOutputStream writer = new ByteArrayOutputStream();
                cache.writeTo(writer);
                if (logger.isDebugEnabled())
                    logger.debug("Reading the POST request:" + writer.toString());
                exchange.getIn().setBody(writer.toString());

                // POST here
                if (logger.isDebugEnabled())
                    logger.debug("Processing the POST request:" + exchange.getIn().getBody());
            } else {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Skipping processing the POST request:" + exchange.getIn().getBody().getClass());
            }
        }

    } else {
        // HttpServletResponse response =
        // exchange.getIn(HttpMessage.class).getResponse();
        exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, HttpServletResponse.SC_MOVED_TEMPORARILY);
        // constant("http://somewhere.com"))
        exchange.getIn().setHeader("Location", SignalKConstants.SIGNALK_AUTH);
        exchange.getIn().setBody("Authentication Required");
    }

}

From source file:org.alfresco.module.vti.handler.alfresco.AlfrescoDwsServiceHandler.java

/**
 * @see org.alfresco.module.vti.handler.DwsServiceHandler#handleRedirect(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///from ww  w.j a v  a2s  . c  om
public void handleRedirect(HttpServletRequest req, HttpServletResponse resp) throws HttpException, IOException {

    String uri = VtiPathHelper.removeSlashes(req.getRequestURI());
    String docLibPath = null;

    if (uri.contains("documentLibrary") && req.getAttribute("VALID_SITE_URL") != null) {
        int pos = uri.indexOf("documentLibrary");
        docLibPath = URLDecoder.decode(uri.substring(pos + "documentLibrary".length()));
        uri = uri.substring(0, pos + "documentLibrary".length()) + ".vti";
    }

    String redirectTo;

    if (!uri.endsWith(".vti")) {
        if (logger.isDebugEnabled())
            logger.debug("Redirection to site in browser");
        if (req.getParameter("calendar") != null) {
            redirectTo = pagesMap.get("calendar");
        } else {
            redirectTo = pagesMap.get("siteInBrowser");
        }

        // Are they redirecting to the root, or one particular site?
        String alfrescoContext = pathHelper.getAlfrescoContext();
        if (alfrescoContext != null && alfrescoContext.length() > 0
                && req.getRequestURI().equals(alfrescoContext)) {
            redirectTo = "";
        } else {
            String siteName = uri.substring(uri.lastIndexOf('/') + 1);
            if (siteName.contains(VtiPathHelper.ALTERNATE_PATH_SITE_IDENTIFICATOR)) {
                try {
                    NodeRef siteRef = new NodeRef(pathHelper.getRootNodeRef().getStoreRef(),
                            siteName.replace(VtiPathHelper.ALTERNATE_PATH_SITE_IDENTIFICATOR, ""));
                    siteName = nodeService.getProperty(siteRef, ContentModel.PROP_NAME).toString();
                } catch (Exception e) {
                }
            }
            redirectTo = redirectTo.replace("...", siteName);
        }

        if (logger.isDebugEnabled())
            logger.debug("Redirection URI: " + redirectTo);
    } else {
        // gets the action is performed
        String action = uri.substring(uri.lastIndexOf("/") + 1, uri.indexOf(".vti"));
        if (logger.isDebugEnabled())
            logger.debug("Redirection to specific action: " + action);
        // gets the uri for redirection from configuration
        redirectTo = pagesMap.get(action);
        if (action.equals("userInformation")) {
            // redirect to user profile
            final String userID = req.getParameter("ID");

            String userName = AuthenticationUtil.runAs(new RunAsWork<String>() {
                public String doWork() throws Exception {
                    return (String) nodeService.getProperty(new NodeRef(userID), ContentModel.PROP_USERNAME);
                }
            }, authenticationComponent.getSystemUserName());

            redirectTo = redirectTo.replace("...", URLEncoder.encode(userName));
        } else {
            // redirect to site information (dashboard, site members ...)
            String[] parts = uri.split("/");
            String siteName = parts[parts.length - 2];
            redirectTo = redirectTo.replace("...", siteName);
            if (action.equals("documentLibrary") && docLibPath != null && docLibPath.length() != 0) {
                redirectTo = redirectTo + "#path=" + ShareUtils.encode(docLibPath);
            }
        }
        String doc = req.getParameter("doc");
        if (doc != null) {
            final String[] docParts = doc.split("/");
            final String docSiteName = docParts[1];

            String docNodeRefID = AuthenticationUtil.runAs(new RunAsWork<String>() {
                public String doWork() throws Exception {
                    SiteInfo siteInfo = siteService.getSite(docSiteName);
                    List<String> docPathElements = new ArrayList<String>();
                    for (int i = 2; i < docParts.length; i++) {
                        docPathElements.add(docParts[i]);
                    }
                    String nodeRefID = null;
                    try {
                        nodeRefID = fileFolderService.resolveNamePath(siteInfo.getNodeRef(), docPathElements)
                                .getNodeRef().getId();
                    } catch (FileNotFoundException e) {
                        throw new AlfrescoRuntimeException("Cannot find file for extract node information", e);
                    }
                    return nodeRefID;
                }
            }, authenticationComponent.getSystemUserName());

            redirectTo = redirectTo + "?nodeRef=workspace://SpacesStore/" + docNodeRefID;
        }
        if (logger.isDebugEnabled())
            logger.debug("Redirection URI: " + redirectTo);

    }

    String redirectionUrl = shareUtils.getShareHostWithPort() + shareUtils.getShareContext() + redirectTo;
    if (logger.isDebugEnabled())
        logger.debug("Executing redirect to URL: '" + redirectionUrl + "'.");

    resp.setHeader("Location", redirectionUrl);
    resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
}

From source file:org.alfresco.repo.web.scripts.publishing.AuthCallbackWebScript.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    Map<String, String[]> params = new TreeMap<String, String[]>();
    Map<String, String[]> headers = new TreeMap<String, String[]>();

    for (String paramName : req.getParameterNames()) {
        params.put(paramName, req.getParameterValues(paramName));
    }//from   w  ww . j  a  v a  2  s. co m

    for (String header : req.getHeaderNames()) {
        headers.put(header, req.getHeaderValues(header));
    }

    if (log.isDebugEnabled()) {
        log.debug("templateVars = " + templateVars);
        log.debug("params = " + params);
        log.debug("headers = " + headers);
    }

    String channelNodeUuid = templateVars.get("node_id");
    String channelNodeStoreProtocol = templateVars.get("store_protocol");
    String channelNodeStoreId = templateVars.get("store_id");

    NodeRef channelNodeRef = new NodeRef(channelNodeStoreProtocol, channelNodeStoreId, channelNodeUuid);
    Channel channel = channelService.getChannelById(channelNodeRef.toString());

    ChannelType.AuthStatus authStatus = channel.getChannelType().acceptAuthorisationCallback(channel, headers,
            params);

    if (ChannelType.AuthStatus.RETRY.equals(authStatus)) {
        AuthUrlPair authoriseUrls = channel.getChannelType().getAuthorisationUrls(channel,
                channelAuthHelper.getAuthoriseCallbackUrl(channelNodeRef));
        String authRequestUrl = authoriseUrls.authorisationRequestUrl;
        if (authRequestUrl == null) {
            authRequestUrl = channelAuthHelper.getDefaultAuthoriseUrl(channelNodeRef);
        }
        status.setCode(HttpServletResponse.SC_MOVED_TEMPORARILY);
        status.setLocation(authRequestUrl);
    }
    Map<String, Object> model = new TreeMap<String, Object>();
    model.put("authStatus", authStatus.name());
    return model;
}

From source file:org.apache.archiva.webdav.AbstractRepositoryServletTestCase.java

protected WebResponse getWebResponse(WebRequest webRequest) //, boolean followRedirect )
        throws Exception {

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(webRequest.getUrl().getPath());
    request.addHeader("User-Agent", "Apache Archiva unit test");

    request.setMethod(webRequest.getHttpMethod().name());

    if (webRequest.getHttpMethod() == HttpMethod.PUT) {
        PutMethodWebRequest putRequest = PutMethodWebRequest.class.cast(webRequest);
        request.setContentType(putRequest.contentType);
        request.setContent(IOUtils.toByteArray(putRequest.inputStream));
    }/*w w  w.j a v a 2s .  c  o m*/

    if (webRequest instanceof MkColMethodWebRequest) {
        request.setMethod("MKCOL");
    }

    final MockHttpServletResponse response = execute(request);

    if (response.getStatus() == HttpServletResponse.SC_MOVED_PERMANENTLY
            || response.getStatus() == HttpServletResponse.SC_MOVED_TEMPORARILY) {
        String location = response.getHeader("Location");
        log.debug("follow redirect to {}", location);
        return getWebResponse(new GetMethodWebRequest(location));
    }

    return new WebResponse(null, null, 1) {
        @Override
        public String getContentAsString() {
            try {
                return response.getContentAsString();
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        @Override
        public int getStatusCode() {
            return response.getStatus();
        }

        @Override
        public String getResponseHeaderValue(String headerName) {
            return response.getHeader(headerName);
        }
    };
}

From source file:org.apache.archiva.webdav.RepositoryServletNoProxyTest.java

@Test
public void testGetNoProxySnapshotRedirectToTimestampedSnapshot() throws Exception {
    String commonsLangQuery = "commons-lang/commons-lang/2.1-SNAPSHOT/commons-lang-2.1-SNAPSHOT.jar";
    String commonsLangMetadata = "commons-lang/commons-lang/2.1-SNAPSHOT/maven-metadata.xml";
    String commonsLangJar = "commons-lang/commons-lang/2.1-SNAPSHOT/commons-lang-2.1-20050821.023400-1.jar";
    String expectedArtifactContents = "dummy-commons-lang-snapshot-artifact";

    archivaConfiguration.getConfiguration().getWebapp().getUi().setApplicationUrl("http://localhost");

    File artifactFile = new File(repoRootInternal, commonsLangJar);
    artifactFile.getParentFile().mkdirs();
    FileUtils.writeStringToFile(artifactFile, expectedArtifactContents, Charset.defaultCharset());

    File metadataFile = new File(repoRootInternal, commonsLangMetadata);
    metadataFile.getParentFile().mkdirs();
    FileUtils.writeStringToFile(metadataFile, createVersionMetadata("commons-lang", "commons-lang",
            "2.1-SNAPSHOT", "20050821.023400", "1", "20050821.023400"));

    WebRequest webRequest = new GetMethodWebRequest("http://localhost/repository/internal/" + commonsLangQuery);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI(webRequest.getUrl().getPath());
    request.addHeader("User-Agent", "Apache Archiva unit test");
    request.setMethod(webRequest.getHttpMethod().name());

    final MockHttpServletResponse response = execute(request);

    assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, response.getStatus());

    assertEquals("http://localhost/repository/internal/" + commonsLangJar, response.getHeader("Location"));
}

From source file:org.apache.roller.weblogger.webservices.oauth.AuthorizationServlet.java

private void returnToConsumer(HttpServletRequest request, HttpServletResponse response, OAuthAccessor accessor)
        throws IOException, ServletException {

    // send the user back to site's callBackUrl
    String callback = request.getParameter("oauth_callback");
    if ("none".equals(callback) && accessor.consumer.callbackURL != null
            && accessor.consumer.callbackURL.length() > 0) {
        // first check if we have something in our properties file
        callback = accessor.consumer.callbackURL;
    }/*from   ww w.  j av a  2  s.  co m*/

    if ("none".equals(callback)) {
        // no call back it must be a client
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("You have successfully authorized for consumer key '" + accessor.consumer.consumerKey
                + "'. Please close this browser window and click continue" + " in the client.");
        out.close();
    } else {
        // if callback is not passed in, use the callback from config
        if (callback == null || callback.length() <= 0)
            callback = accessor.consumer.callbackURL;
        String token = accessor.requestToken;
        if (token != null && callback != null) {
            callback = OAuth.addParameters(callback, "oauth_token", token);
        }

        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", callback);
    }
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.AuthenticationResponseCodeTest.java

@Test
public void testWithNonHtmlAcceptHeaderIncorrectCredentials() throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "garbage"));
    params.add(new NameValuePair("j_password", "garbage"));

    List<Header> headers = new ArrayList<Header>();
    headers.add(new Header("User-Agent", "Mozilla/5.0 Sling Integration Test"));

    assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check", HttpServletResponse.SC_MOVED_TEMPORARILY,
            params, headers, null);/*w  ww .j a  v a  2s.  c o m*/
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.SelectorAuthenticationResponseCodeTest.java

@Test
public void testWithAcceptHeaderIncorrectCredentials() throws Exception {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "garbage"));
    params.add(new NameValuePair("j_password", "garbage"));

    // simulate a browser request
    List<Header> headers = new ArrayList<Header>();
    headers.add(new Header("User-Agent", "Mozilla/5.0 Sling Integration Test"));

    HttpMethod post = assertPostStatus(HttpTest.HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_MOVED_TEMPORARILY, params, headers, null);

    final String location = post.getResponseHeader("Location").getValue();
    assertNotNull(location);/*from  w  w  w .ja  v  a2  s  .  c o m*/
    assertTrue(location.startsWith(HttpTest.HTTP_BASE_URL + "/system/sling/selector/login?"));
    assertTrue(location.contains("resource=%2F"));
    assertTrue(location.contains("j_reason=INVALID_CREDENTIALS"));
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.login.RedirectOnLoginErrorTest.java

/**
 * Test SLING-2165.  Login Error should redirect back to the referrer
 * login page./* w ww  . j  a v a 2 s . c  o  m*/
 *
 * @throws Exception
 */
public void testRedirectToLoginFormAfterLoginError() throws Exception {
    //login failure
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("j_username", "___bogus___"));
    params.add(new NameValuePair("j_password", "not_a_real_user"));
    final String loginPageUrl = String.format("%s/system/sling/form/login", HTTP_BASE_URL);
    PostMethod post = (PostMethod) assertPostStatus(HTTP_BASE_URL + "/j_security_check",
            HttpServletResponse.SC_MOVED_TEMPORARILY, params, null, loginPageUrl);

    final Header locationHeader = post.getResponseHeader("Location");
    String location = locationHeader.getValue();
    int queryStrStart = location.indexOf('?');
    if (queryStrStart != -1) {
        location = location.substring(0, queryStrStart);
    }
    assertEquals("Expected to remain on the form/login page", loginPageUrl, location);
}