Example usage for javax.servlet.http HttpServletResponse SC_MOVED_PERMANENTLY

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

Introduction

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

Prototype

int SC_MOVED_PERMANENTLY

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

Click Source Link

Document

Status code (301) indicating that the resource has permanently moved to a new location, and that future references should use a new URI with their requests.

Usage

From source file:com.enonic.cms.server.service.portal.mvc.controller.PortalRenderResponseServer.java

private ModelAndView serveRedirectToSitePath(SitePath toSitePath, int redirectStatus,
        HttpServletResponse httpResponse, HttpServletRequest httpRequest) throws IOException {

    SiteBasePath siteBasePath = SiteBasePathResolver.resolveSiteBasePath(httpRequest, toSitePath.getSiteKey());
    SiteBasePathAndSitePath siteBasePathAndSitePath = new SiteBasePathAndSitePath(siteBasePath, toSitePath);

    SiteBasePathAndSitePathToStringBuilder siteBasePathAndSitePathToStringBuilder = new SiteBasePathAndSitePathToStringBuilder();
    siteBasePathAndSitePathToStringBuilder.setEncoding("UTF-8");
    siteBasePathAndSitePathToStringBuilder.setHtmlEscapeParameterAmps(false);
    siteBasePathAndSitePathToStringBuilder.setIncludeFragment(true);
    siteBasePathAndSitePathToStringBuilder.setIncludeParamsInPath(true);
    siteBasePathAndSitePathToStringBuilder.setUrlEncodePath(true);
    String redirectUrl = siteBasePathAndSitePathToStringBuilder.toString(siteBasePathAndSitePath);

    String encodedRedirectUrl = httpResponse.encodeRedirectURL(redirectUrl);

    if (redirectStatus == HttpServletResponse.SC_MOVED_PERMANENTLY) {
        httpResponse.setStatus(redirectStatus);
        httpResponse.setHeader("Location", encodedRedirectUrl);
        return null;
    } else {/*from w  ww. j  a v a2 s  .c  o  m*/
        httpResponse.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
        httpResponse.setHeader("Location", encodedRedirectUrl);
        return null;
    }
}

From source file:org.bibsonomy.webapp.util.spring.controller.MinimalisticControllerSpringWrapper.java

/**
 * instantiates, initializes and runs the MinimalisticController
 * /*from   ww w  .j  a  v  a  2 s  . com*/
 * @see org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@SuppressWarnings("unchecked")
@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    ((RequestLogic) getApplicationContext().getBean("requestLogic")).setRequest(request); // hack but thats springs fault
    ((ResponseLogic) getApplicationContext().getBean("responseLogic")).setResponse(response); // hack but thats springs fault
    final MinimalisticController<T> controller = (MinimalisticController<T>) getApplicationContext()
            .getBean(controllerBeanName);
    /**
     * Controller is put into request.
     * 
     * FIXME: is this still neccessary?
     * 
     * SuppressValidation retrieves controller from request again!
     */
    request.setAttribute(CONTROLLER_ATTR_NAME, controller);

    /*
     * DEBUG: log request attributes
     */
    if (log.isDebugEnabled()) {
        final Enumeration<?> e = request.getAttributeNames();
        while (e.hasMoreElements()) {
            log.debug(e.nextElement().toString());
        }
    }

    final T command = controller.instantiateCommand();

    /*
     * put context into command
     * 
     * TODO: in the future this is hopefully no longer needed, since the wrapper
     * only exists to transfer request attributes into the command.
     */
    command.setContext((RequestWrapperContext) request.getAttribute(RequestWrapperContext.class.getName()));

    /*
     * set validator for this instance
     */
    if (controller instanceof ValidationAwareController<?>) {
        this.setValidator(((ValidationAwareController<T>) controller).getValidator());
    }

    /*
     * bind request attributes to command
     */
    final ServletRequestDataBinder binder = bindAndValidate(request, command);
    final BindException errors = new BindException(binder.getBindingResult());
    if (controller instanceof ErrorAware) {
        ((ErrorAware) controller).setErrors(errors);
    }

    View view;

    /*
     * define error view
     */
    if (controller instanceof AjaxController) {
        view = Views.AJAX_ERRORS;
    } else {
        view = Views.ERROR;
    }

    try {
        view = controller.workOn(command);
    } catch (final MalformedURLSchemeException malformed) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        errors.reject("error.http.notFound", malformed.getMessage());
        log.warn("Could not complete controller (invalid URL scheme) : " + malformed.getMessage());
    } catch (final AccessDeniedException ad) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        errors.reject(ad.getMessage());
        log.warn("Could not complete controller (AccessDeniedException), occured in: " + ad.getStackTrace()[0]
                + ", msg is: " + ad.getMessage());
    } catch (final ServiceUnavailableException e) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        response.setHeader("Retry-After", Long.toString(e.getRetryAfter()));
        errors.reject(e.getMessage(), new Object[] { e.getRetryAfter() }, "Service unavailable");
        /*
         *  this exception is only thrown in UserLoginController
         *  if desired, add some logging there. Otherwise, our error logs get
         *  cluttered.(dbe)
         */
        // log.warn("Could not complete controller (Service unavailable): " + e.getMessage());
    } catch (final ResourceMovedException e) {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location",
                urlGenerator.getPostUrl(e.getResourceType(), e.getNewIntraHash(), e.getUserName()));
    } catch (final ResourceNotFoundException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        errors.reject("error.post.notfound", e.getMessage()); // FIXME: it would be better, to show the specific 404 view
    } catch (final org.springframework.security.access.AccessDeniedException ex) {
        /*
         * we rethrow the exception here in order that Spring Security can
         * handle the exception (saving request and redirecting to the login
         * page (if user is not logged in) or to the access denied page)
         */
        throw ex;
    } catch (final Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        errors.reject("error.internal", new Object[] { ex }, "Internal Server Error: " + ex.getMessage());
        log.error("Could not complete controller (general exception) for request /" + request.getRequestURI()
                + "?" + request.getQueryString() + " with referer " + request.getHeader("Referer"), ex);
    }

    log.debug("Exception catching block passed, putting comand+errors into model.");

    final Map<String, Object> model = new HashMap<String, Object>();
    model.put(getCommandName(), command);

    /*
     * put errors into model 
     */
    model.putAll(errors.getModel());

    log.debug("Returning model and view.");

    /**
     * If the view is already a Spring view, use it directly.
     * The primal reason for the this workaround is, that Spring's RedirctView
     * automatically appends the model parameters to each redirected URL. This
     * can only be avoided by calling setExposeModelAttributes(false) on the 
     * RedirectView. Hence, we must directly create a redirect view instead of 
     * using a "redirect:..." URL.  
     */
    if (org.springframework.web.servlet.View.class.isAssignableFrom(view.getClass())) {
        return new ModelAndView((org.springframework.web.servlet.View) view, model);
    }

    return new ModelAndView(view.getName(), model);
}

From source file:org.ambraproject.wombat.controller.ArticleAssetController.java

/**
 * Redirect to a given link. (We can't just return a {@link org.springframework.web.servlet.view.RedirectView} because
 * we ordinarily want to pass the raw response to {@link #forwardAssetResponse}. So we mess around with it directly.)
 *///from  w  w  w  .  j  av a 2 s  .com
private void redirectTo(HttpServletResponse response, String location) {
    response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    response.setHeader(HttpHeaders.LOCATION, location);
}

From source file:com.tc.utils.XSPUtils.java

public static void redirectPermanently(String url) {
    XSPUtils.getResponse().setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
    XSPUtils.getResponse().setHeader("Location", url);
}

From source file:org.bibsonomy.rest.RestServlet.java

/**
 * @param request/* w w w  .j  a v  a 2s  .  com*/
 *            the servletrequest
 * @param response
 *            the servletresponse
 * @param method
 *            httpMethod to use, see {@link HttpMethod}
 * @throws IOException
 */
private void handle(final HttpServletRequest request, final HttpServletResponse response,
        final HttpMethod method) throws IOException {
    log.debug("Incoming Request: " + method.name() + " " + request.getRequestURL() + " from IP "
            + request.getHeader("x-forwarded-for"));
    final long start = System.currentTimeMillis();

    try {
        // validate the requesting user's authorization
        final LogicInterface logic = validateAuthorization(request);

        // parse the request object to retrieve a list with all items of the
        // http request
        final MultiPartRequestParser parser = new MultiPartRequestParser(request);

        // choose rendering format (defaults to xml)
        final RenderingFormat renderingFormat = RESTUtils.getRenderingFormatForRequest(
                request.getParameterMap(), request.getHeader(HeaderUtils.HEADER_ACCEPT),
                request.getContentType());

        // create Context
        final Reader reader = RESTUtils.getInputReaderForStream(request.getInputStream(), REQUEST_ENCODING);
        final Context context = new Context(method, getPathInfo(request), renderingFormat, this.urlRenderer,
                reader, parser.getList(), logic, request.getParameterMap(), additionalInfos);

        // validate request
        context.canAccess();

        // set some response headers
        final String userAgent = request.getHeader(HeaderUtils.HEADER_USER_AGENT);
        log.debug("[USER-AGENT] " + userAgent);
        response.setContentType(context.getContentType(userAgent));
        response.setCharacterEncoding(RESPONSE_ENCODING);

        // send answer
        if (method.equals(HttpMethod.POST)) {
            // if a POST request completes successfully this means that a
            // resource has been created
            response.setStatus(HttpServletResponse.SC_CREATED);
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
        }

        // just define an ByteArrayOutputStream to store all outgoing data
        final ByteArrayOutputStream cachingStream = new ByteArrayOutputStream();
        context.perform(cachingStream);

        /*
         * XXX: note: cachingStream.size() !=
         * cachingStream.toString().length() !! the correct value is the
         * first one!
         */
        response.setContentLength(cachingStream.size());

        // some more logging
        log.debug("Size of output sent:" + cachingStream.size());
        final long elapsed = System.currentTimeMillis() - start;
        log.debug("Processing time: " + elapsed + " ms");

        cachingStream.writeTo(response.getOutputStream());
    } catch (final AuthenticationException e) {
        log.warn(e.getMessage());
        response.setHeader("WWW-Authenticate",
                "Basic realm=\"" + RestProperties.getInstance().getBasicRealm() + "\"");
        sendError(request, response, HttpURLConnection.HTTP_UNAUTHORIZED, e.getMessage());
    } catch (final InternServerException e) {
        log.error(e.getMessage());
        sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (final NoSuchResourceException e) {
        log.error(e.getMessage());
        sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (final BadRequestOrResponseException e) {
        log.error(e.getMessage());
        sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (final AccessDeniedException e) {
        log.error(e.getMessage());
        sendError(request, response, HttpServletResponse.SC_FORBIDDEN, e.getMessage());
    } catch (final ResourceMovedException e) {
        log.error(e.getMessage());
        /*
         * sending new location TODO: add date using
         */
        response.setHeader("Location", urlRenderer.createHrefForResource(e.getUserName(), e.getNewIntraHash()));
        sendError(request, response, HttpServletResponse.SC_MOVED_PERMANENTLY, e.getMessage());
    } catch (final DatabaseException e) {
        final StringBuilder returnMessage = new StringBuilder("");
        for (final String hash : e.getErrorMessages().keySet()) {
            for (final ErrorMessage em : e.getErrorMessages(hash)) {
                log.error(em.toString());
                returnMessage.append(em.toString() + "\n ");
            }
        }
        sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, returnMessage.toString());

    } catch (final Exception e) {
        log.error(e, e);
        // well, lets fetch each and every error...
        sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:nl.nn.adapterframework.extensions.akamai.NetStorageSender.java

@Override
public String extractResult(HttpResponseHandler responseHandler, ParameterResolutionContext prc)
        throws SenderException, IOException {
    int statusCode = responseHandler.getStatusLine().getStatusCode();

    boolean ok = false;
    if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey())) {
        prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode));
        ok = true;/*from w w  w .  j a  v a  2s.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 + ": "
                + responseHandler.getStatusLine().getReasonPhrase() + " body: "
                + getResponseBodyAsString(responseHandler));
    }

    XmlBuilder result = new XmlBuilder("result");

    HttpServletResponse response = (HttpServletResponse) prc.getSession()
            .get(IPipeLineSession.HTTP_RESPONSE_KEY);
    if (response == null) {
        XmlBuilder statuscode = new XmlBuilder("statuscode");
        statuscode.setValue(statusCode + "");
        result.addSubElement(statuscode);

        String responseString = getResponseBodyAsString(responseHandler);
        responseString = XmlUtils.skipDocTypeDeclaration(responseString.trim());
        responseString = XmlUtils.skipXmlDeclaration(responseString);

        if (statusCode == HttpURLConnection.HTTP_OK) {
            XmlBuilder message = new XmlBuilder("message");
            message.setValue(responseString, false);
            result.addSubElement(message);
        } else {
            // Validate Server-Time drift
            String dateString = responseHandler.getHeader("Date");
            if (!StringUtils.isEmpty(dateString)) {
                Date currentDate = new Date();
                DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
                long responseDate = 0;

                try {
                    Date date = format.parse(dateString);
                    responseDate = date.getTime();
                } catch (Exception e) {
                }

                if (responseDate != 0 && currentDate.getTime() - responseDate > 30 * 1000)
                    throw new SenderException(
                            "Local server Date is more than 30s out of sync with Remote server");
            }
            XmlBuilder message = new XmlBuilder("error");
            message.setValue(responseString);
            result.addSubElement(message);

            log.warn(String.format("Unexpected Response from Server: %d %s\n%s", statusCode, responseString,
                    responseHandler.getHeaderFields()));
        }
    }

    return result.toXML();
}

From source file:com.boylesoftware.web.Router.java

/**
 * Send redirect to the same request URI (including the query string), but
 * over HTTPS.//ww w  .  j av a2 s  . com
 *
 * @param webapp The web-application.
 * @param request The HTTP request.
 * @param response The HTTP response.
 */
private void sendRedirectToSecureURI(final AbstractWebApplication webapp, final HttpServletRequest request,
        final HttpServletResponse response) {

    LooseCannon.heel();

    try (final PooledStringBuffer buf = StringBufferPool.get()) {
        final StringBuilder redirectURL = buf.getStringBuilder();

        redirectURL.append("https://").append(request.getServerName());

        final int httpsPort = webapp.getHTTPSPort();
        if (httpsPort != 443)
            redirectURL.append(':').append(httpsPort);

        redirectURL.append(request.getRequestURI());

        final String queryString = request.getQueryString();
        if (queryString != null)
            redirectURL.append('?').append(queryString);

        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location", redirectURL.toString());
    }
}

From source file:org.fao.geonet.services.inspireatom.AtomPredefinedFeed.java

/**
 * Main entry point for local dataset ATOM feed download.
 *
 * @param spIdentifier the spatial dataset identifier
 * @param spNamespace the spatial dataset namespace (not used for the moment)
 * @param crs the crs of the dataset/*from   w  w  w . j a v  a  2  s .  c  o  m*/
 * @param language the language to be used for translation of title, etc. in the resulting dataset ATOM feed
 * @param q the searchTerms for filtering of the spatial datasets
 * @param webRequest the request object
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/" + InspireAtomUtil.LOCAL_DOWNLOAD_DATASET_URL_SUFFIX)
@ResponseBody
public HttpEntity<byte[]> localDatasetDownload(
        @RequestParam("spatial_dataset_identifier_code") String spIdentifier,
        @RequestParam(value = "spatial_dataset_identifier_namespace", required = false) String spNamespace,
        @RequestParam(value = "crs", required = false) String crs,
        @RequestParam(value = "language", required = false) String language,
        @RequestParam(value = "q", required = false) String searchTerms, NativeWebRequest webRequest)
        throws Exception {
    ServiceContext context = createServiceContext(Geonet.DEFAULT_LANGUAGE,
            webRequest.getNativeRequest(HttpServletRequest.class));

    SettingManager sm = context.getBean(SettingManager.class);
    boolean inspireEnable = sm.getValueAsBool(Settings.SYSTEM_INSPIRE_ENABLE);
    if (!inspireEnable) {
        Log.info(Geonet.ATOM, "INSPIRE is disabled");
        throw new OperationNotAllowedEx("INSPIRE option is not enabled on this catalog.");
    }

    Map<String, Object> params = getDefaultXSLParams(sm, context, context.getLanguage());
    if (StringUtils.isNotBlank(crs)) {
        crs = URLDecoder.decode(crs, Constants.ENCODING);
        params.put("requestedCrs", crs);
    }
    if (StringUtils.isNotBlank(searchTerms)) {
        params.put("searchTerms", searchTerms.toLowerCase());
    }
    Element feed = InspireAtomUtil.getDatasetFeed(context, spIdentifier, spNamespace, params, language);
    Map<Integer, Element> crsCounts = new HashMap<Integer, Element>();
    ;
    Namespace ns = Namespace.getNamespace("http://www.w3.org/2005/Atom");
    if (crs != null) {
        crsCounts = countDatasetsForCrs(feed, crs, ns);
    } else {
        List<Element> entries = (feed.getChildren("entry", ns));
        if (entries.size() == 1) {
            crsCounts.put(1, entries.get(0));
        }
    }
    int downloadCount = crsCounts.size() > 0 ? crsCounts.keySet().iterator().next() : 0;
    Element selectedEntry = crsCounts.get(downloadCount);

    // No download  for the CRS specified
    if (downloadCount == 0) {
        throw new Exception("No downloads available for dataset (spatial_dataset_identifier_code: "
                + spIdentifier + ", spatial_dataset_identifier_namespace: " + spNamespace + ", crs: " + crs
                + ", searchTerms: " + searchTerms + ")");

        // Only one download for the CRS specified
    } else if (downloadCount == 1) {
        String type = null;
        Element link = selectedEntry.getChild("link", ns);
        if (link != null) {
            type = link.getAttributeValue("type");
        }
        HttpServletResponse nativeRes = webRequest.getNativeResponse(HttpServletResponse.class);
        nativeRes.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        //            nativeRes.setHeader("Location", selectedEntry.getChildText("id",ns));
        return redirectResponse(selectedEntry.getChildText("id", ns));
        // Otherwise, return a feed with the downloads for the specified CRS
    } else {
        // Filter the dataset feed by CRS code.
        InspireAtomUtil.filterDatasetFeedByCrs(feed, crs);
        return writeOutResponse(Xml.getString(feed), "application", "atom+xml");
    }
}

From source file:com.openedit.BaseWebPageRequest.java

/**
 * This was added because a customer needed it for google indexes. 
 * I wonder if we can not just use permenanet redirects all the time?
 * @param inPath/*from  w w  w. java2s . c o m*/
 */
public void redirectPermanently(String inPath) {
    String home = (String) getPageValue("home");
    try {
        if (inPath != null) {
            log.debug("Perma redirect to: " + inPath);
            if (!inPath.startsWith("http")) {
                inPath = home + inPath;
            }
            putPageValue("redirect", inPath);
            if (getResponse() != null) {
                getResponse().setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                getResponse().setHeader("Location", inPath);
                getResponse().flushBuffer();
            } else {
                log.error("No response set");
            }
            setHasRedirected(true);
        }
    } catch (IOException e) {
        throw new OpenEditRuntimeException(e);
    }

}