Example usage for org.springframework.http HttpStatus MOVED_PERMANENTLY

List of usage examples for org.springframework.http HttpStatus MOVED_PERMANENTLY

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus MOVED_PERMANENTLY.

Prototype

HttpStatus MOVED_PERMANENTLY

To view the source code for org.springframework.http HttpStatus MOVED_PERMANENTLY.

Click Source Link

Document

301 Moved Permanently .

Usage

From source file:ru.mystamps.web.controller.SeriesController.java

@GetMapping(Url.ADD_SERIES_WITH_COUNTRY_PAGE)
public View showFormWithCountry(@PathVariable("slug") String country, RedirectAttributes redirectAttributes) {

    redirectAttributes.addAttribute("country", country);

    RedirectView view = new RedirectView();
    view.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
    view.setUrl(Url.ADD_SERIES_PAGE);//from ww  w .  j a  v a2  s.c om

    return view;
}

From source file:edu.colorado.orcid.impl.OrcidServicePublicImpl.java

protected Document fetchOrcidDocument(String url) throws OrcidHttpException {

    try {/*from   www  .  jav  a  2 s .c  om*/
        ResponseEntity<DOMSource> responseEntity = orcidRestTemplate.getForEntity(url, DOMSource.class);
        HttpStatus statusCode = responseEntity.getStatusCode();
        DOMSource orcidInput = responseEntity.getBody();
        Document orcidDocument = (Document) orcidInput.getNode();

        // Handle deprecated ORCID iD, which returns HTTP 301 status code
        if (statusCode == HttpStatus.MOVED_PERMANENTLY) {
            OrcidHttpException e = new OrcidHttpException("ORCID iD Deprecated");
            e.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
            try {
                e.setDocument(OrcidUtil.documentXml(orcidDocument));
            } catch (TransformerException te) {
                String msg = "Error setting XML document: " + te.getMessage();
                e.setDocument(msg);
            }
            String errorDesc = orcidDocument.getElementsByTagName("error-desc").item(0).getTextContent();
            e.setOrcidPrimaryRecord(extractOrcid(errorDesc)); //Set ORCID primary record value in exception
            throw e;
        } else if (!(statusCode == HttpStatus.OK)) {
            OrcidHttpException e = new OrcidHttpException("Error fetching URL: " + url);
            e.getStatusCode();
            try {
                e.setDocument(OrcidUtil.documentXml(orcidDocument));
            } catch (TransformerException te) {
                String msg = "Error setting XML document: " + te.getMessage();
                e.setDocument(msg);
            }
            throw e;
        }

        return orcidDocument;

    } catch (HttpClientErrorException e) {
        OrcidHttpException ohe = new OrcidHttpException(e);
        ohe.setStatusCode(e.getStatusCode());
        throw ohe;
    }
}

From source file:de.hybris.platform.acceleratorstorefrontcommons.controllers.pages.AbstractPageController.java

/**
 * Checks request URL against properly resolved URL and returns null if url is proper or redirection string if not.
 *
 * @param request/* w  w  w  . j ava2  s  . c o  m*/
 *           - request that contains current URL
 * @param response
 *           - response to write "301 Moved Permanently" status to if redirected
 * @param resolvedUrlPath
 *           - properly resolved URL
 * @return null if url is properly resolved or redirection string if not
 * @throws UnsupportedEncodingException
 */
protected String checkRequestUrl(final HttpServletRequest request, final HttpServletResponse response,
        final String resolvedUrlPath) throws UnsupportedEncodingException {
    try {
        final String resolvedUrl = response.encodeURL(request.getContextPath() + resolvedUrlPath);
        final String requestURI = URIUtil.decode(request.getRequestURI(), "utf-8");
        final String decoded = URIUtil.decode(resolvedUrl, "utf-8");
        if (StringUtils.isNotEmpty(requestURI) && requestURI.endsWith(decoded)) {
            return null;
        } else {
            //  org.springframework.web.servlet.View.RESPONSE_STATUS_ATTRIBUTE = "org.springframework.web.servlet.View.responseStatus"
            request.setAttribute("org.springframework.web.servlet.View.responseStatus",
                    HttpStatus.MOVED_PERMANENTLY);
            final String queryString = request.getQueryString();
            if (queryString != null && !queryString.isEmpty()) {
                return "redirect:" + resolvedUrlPath + "?" + queryString;
            }
            return "redirect:" + resolvedUrlPath;
        }
    } catch (final URIException e) {
        LOGGER.error("URIException:" + e.getMessage(), e);
        throw new UnsupportedEncodingException(e.getMessage());
    }
}

From source file:com.epam.cme.storefront.controllers.pages.AbstractPageController.java

/**
 * Checks request URL against properly resolved URL and returns null if url is proper or
 * redirection string if not./*from   ww w  . j a v  a  2s .c  om*/
 * 
 * @param request
 *            - request that contains current URL
 * @param response
 *            - response to write "301 Moved Permanently" status to if redirected
 * @param resolvedUrl
 *            - properly resolved URL
 * @return null if url is properly resolved or redirection string if not
 * @throws UnsupportedEncodingException
 */
protected String checkRequestUrl(final HttpServletRequest request, final HttpServletResponse response,
        final String resolvedUrl) throws UnsupportedEncodingException {
    try {
        final String requestURI = URIUtil.decode(request.getRequestURI(), "utf-8");
        final String decoded = URIUtil.decode(resolvedUrl, "utf-8");
        if (StringUtils.isNotEmpty(requestURI) && requestURI.endsWith(decoded)) {
            return null;
        } else {
            request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.MOVED_PERMANENTLY);
            final String queryString = request.getQueryString();
            if (queryString != null && !queryString.isEmpty()) {
                return "redirect:" + resolvedUrl + "?" + queryString;
            }
            return "redirect:" + resolvedUrl;
        }
    } catch (final URIException e) {
        throw new UnsupportedEncodingException();
    }
}

From source file:com.exxonmobile.ace.hybris.storefront.controllers.pages.AbstractPageController.java

/**
 * Checks request URL against properly resolved URL and returns null if url is proper or redirection string if not.
 * /* w w w  .ja  v a2 s  .com*/
 * @param request
 *           - request that contains current URL
 * @param response
 *           - response to write "301 Moved Permanently" status to if redirected
 * @param resolvedUrlPath
 *           - properly resolved URL
 * @return null if url is properly resolved or redirection string if not
 * @throws UnsupportedEncodingException
 */
protected String checkRequestUrl(final HttpServletRequest request, final HttpServletResponse response,
        final String resolvedUrlPath) throws UnsupportedEncodingException {
    try {
        final String resolvedUrl = response.encodeURL(request.getContextPath() + resolvedUrlPath);
        final String requestURI = URIUtil.decode(request.getRequestURI(), "utf-8");
        final String decoded = URIUtil.decode(resolvedUrl, "utf-8");
        if (StringUtils.isNotEmpty(requestURI) && requestURI.endsWith(decoded)) {
            return null;
        } else {
            request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.MOVED_PERMANENTLY);
            final String queryString = request.getQueryString();
            if (queryString != null && !queryString.isEmpty()) {
                return "redirect:" + resolvedUrlPath + "?" + queryString;
            }
            return "redirect:" + resolvedUrlPath;
        }
    } catch (final URIException e) {
        throw new UnsupportedEncodingException();
    }
}

From source file:de.hybris.platform.addonsupport.controllers.page.AbstractAddOnPageController.java

/**
 * Checks request URL against properly resolved URL and returns null if url is proper or redirection string if not.
 * // w ww  .  j a  va 2s.  c o  m
 * @param request
 *           - request that contains current URL
 * @param response
 *           response to write "301 Moved Permanently" status to if redirected
 * @param resolvedUrlPath
 *           - properly resolved URL
 * @param responseStatusAttributeName
 *           - response attribute name to which write the "301 Moved Permanently" status
 * @return null if url is properly resolved or redirection string if not
 * @throws UnsupportedEncodingException
 */
protected String checkRequestUrl(final HttpServletRequest request, final HttpServletResponse response,
        final String resolvedUrlPath, final String responseStatusAttributeName)
        throws UnsupportedEncodingException {
    try {
        final String resolvedUrl = response.encodeURL(request.getContextPath() + resolvedUrlPath);
        final String requestURI = URIUtil.decode(request.getRequestURI(), "utf-8");
        final String decoded = URIUtil.decode(resolvedUrl, "utf-8");
        if (StringUtils.isNotEmpty(requestURI) && requestURI.endsWith(decoded)) {
            return null;
        } else {
            request.setAttribute(responseStatusAttributeName, HttpStatus.MOVED_PERMANENTLY);
            final String queryString = request.getQueryString();
            if (queryString != null && !queryString.isEmpty()) {
                return "redirect:" + resolvedUrlPath + "?" + queryString;
            }
            return "redirect:" + resolvedUrlPath;
        }
    } catch (final URIException e) {
        throw new UnsupportedEncodingException();
    }
}

From source file:eionet.webq.web.interceptor.CdrAuthorizationInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String authorization = request.getHeader(AUTHORIZATION_HEADER);
    //        if (true) return PROCEED;
    if (StringUtils.isNotEmpty(authorization) || request.getParameter("auth") != null) {
        // if Basic auth is present in the request, then try to log in to CDR to test if it is valid token for given domain.
        // "auth" parameter is just meant for testing the CDR API in development environment - WebQ asks to authenticate.
        HttpHeaders headers = new HttpHeaders();
        headers.add(AUTHORIZATION_HEADER, authorization);
        //            return PROCEED;
        try {/*from w ww. ja va2s.  c om*/
            ResponseEntity<String> loginResponse = restOperations.postForEntity(
                    extractCdrUrl(request) + "/" + cdrLoginMethod, new HttpEntity<Object>(headers),
                    String.class);
            LOGGER.info("Response code received from CDR basic authorization request "
                    + loginResponse.getStatusCode());
            return PROCEED;
        } catch (HttpStatusCodeException e) {
            if (e.getStatusCode() != HttpStatus.UNAUTHORIZED) {
                LOGGER.warn("Authorization against CDR failed with unexpected HTTP status code", e);
            }
        }
    } else {
        // if Basic auth is not present, then test if user is already authorised in this domain
        // by using provided cookies to fetch CDR envelope properties page.
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            HttpHeaders headers = new HttpHeaders();
            for (Cookie cookie : cookies) {
                // put ZopeId parameter to request header. It works only when the value is surrounded with quotes.
                headers.add("Cookie", cookiesConverter.convertCookieToString(cookie));
            }
            String urlToFetch = extractCdrEnvelopeUrl(request) + "/" + cdrEnvelopePropertiesMethod;
            //ResponseEntity<String> loginResponse = restOperations.exchange(urlToFetch, HttpMethod.GET,
            //        new HttpEntity<Object>(headers), String.class);

            HttpResponse responseFromCdr = fetchUrlWithoutRedirection(urlToFetch, headers);
            try {
                int statusCode = responseFromCdr.getStatusLine().getStatusCode();

                LOGGER.info("Response code received from CDR envelope request using cookies " + statusCode);
                if (statusCode == HttpStatus.OK.value()) {
                    request.setAttribute(PARSED_COOKIES_ATTRIBUTE,
                            cookiesConverter.convertCookiesToString(cookies));
                    return PROCEED;
                } else if ((statusCode == HttpStatus.MOVED_PERMANENTLY.value()
                        || statusCode == HttpStatus.MOVED_TEMPORARILY.value())
                        && responseFromCdr.getFirstHeader("Location") != null) {
                    // redirect to CDR login page
                    String redirectUrl = extractCdrUrl(request)
                            + responseFromCdr.getFirstHeader("Location").getValue();
                    LOGGER.info("Redirect to " + redirectUrl);
                    response.sendRedirect(redirectUrl);
                }
            } catch (HttpStatusCodeException e) {
                if (e.getStatusCode() != HttpStatus.UNAUTHORIZED) {
                    LOGGER.warn("Fetching CDR envelope page failed with unexpected HTTP status code", e);
                }
            }
        }
    }

    if (isFailureCountsEqualsToAllowedFailuresCount()) {
        request.setAttribute(AUTHORIZATION_FAILED_ATTRIBUTE, AUTHORIZATION_FAILED_ATTRIBUTE);
        session.removeAttribute(AUTHORIZATION_TRY_COUNT);
        return PROCEED;
    }

    increaseFailedAuthorizationsCount();
    response.addHeader("WWW-Authenticate", "Basic realm=\"Please login to use webforms.\"");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return STOP_REQUEST_PROPAGATION;
}

From source file:net.canadensys.dataportal.occurrence.controller.OccurrenceController.java

/**
 * Resource contact message sending form.
 * //from   ww w. j  a v a 2 s. c o m
 * @param ipt
 *            resource identifier (sourcefileid).
 * @return
 */
@RequestMapping(value = "/occurrences/{auto_id}", method = RequestMethod.POST)
@I18nTranslation(resourceName = "occurrence", translateFormat = "/occurrences/{}")
public ModelAndView handleResourceContactMsg(@PathVariable String auto_id, HttpServletRequest request) {
    OccurrenceModel occModel = occurrenceService.loadOccurrenceModel(auto_id, true);
    ResourceMetadataModel resourceInformationModel = occurrenceService
            .loadResourceMetadataModel(occModel.getSourcefileid());
    // Get resource contacts:
    Set<ContactModel> contacts = resourceInformationModel.getContacts();

    // URL from the previous URL accessed that led to the contact form:
    Locale locale = RequestContextUtils.getLocale(request);
    HashMap<String, Object> modelRoot = new HashMap<String, Object>();

    // Get full URL:
    String occurrenceUrl = I18nUrlBuilder.generateI18nResourcePath(locale.getLanguage(),
            OccurrencePortalConfig.I18N_TRANSLATION_HANDLER.getTranslationFormat("occurrence"),
            new String[] { auto_id });
    String domainName = request.getParameter("domainName");
    occurrenceUrl = domainName + request.getContextPath() + occurrenceUrl;
    // Set common stuff
    ControllerHelper.setPageHeaderVariables(request, "contact", new String[] { auto_id }, appConfig, modelRoot);

    Map<String, Object> templateData = new HashMap<String, Object>();
    ContactModel contact = null;
    for (ContactModel rcm : contacts) {
        if (rcm.getRole().equalsIgnoreCase("contact")) {
            contact = rcm;
            // Add contacts information
            modelRoot.put("contact", contact);
            break;
        }
    }

    String mailto = contact.getEmail();
    String nameto = contact.getName();

    if (mailto != null && !mailto.equalsIgnoreCase("")) {
        String namefrom = request.getParameter("name");
        String mailfrom = request.getParameter("email");
        String message = request.getParameter("message");
        // Later change to fetch from properties file
        // (resourcecontact.subject).
        String subject = request.getParameter("subject");
        templateData.put("subject", subject);
        templateData.put("mailto", mailto);
        templateData.put("nameto", nameto);
        templateData.put("mailfrom", mailfrom);
        templateData.put("namefrom", namefrom);
        templateData.put("message", message);
        templateData.put("occurrenceUrl", occurrenceUrl);
        templateData.put("time", new SimpleDateFormat("EEEE, dd-MM-yyyy HH:mm z", locale).format(new Date()));
        String templateName = appConfig.getContactEmailTemplateName(locale);
        boolean sent = mailSender.sendMessage(mailto, subject, templateData, templateName);
        LOGGER.error("*** Email enviado para o publicador: " + sent);
    }
    // Redirect back to occurrence:

    RedirectView rv = new RedirectView(occurrenceUrl);
    rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
    return new ModelAndView(rv);
}

From source file:net.canadensys.dataportal.occurrence.controller.OccurrenceController.java

/**
 * Resource contact message feedback sending form.
 * //from w  w  w. j a  v a2 s.c  om
 * @param ipt
 *            resource identifier (sourcefileid).
 * @return
 */
@RequestMapping(value = "/feedback", method = RequestMethod.POST)
@I18nTranslation(resourceName = "feedback", translateFormat = "/feedback")
public ModelAndView handleFeedbackMsg(HttpServletRequest request) {
    // URL from the previous URL accessed that led to the contact form:
    Locale locale = RequestContextUtils.getLocale(request);
    HashMap<String, Object> modelRoot = new HashMap<String, Object>();

    // Set common stuff
    ControllerHelper.setPageHeaderVariables(request, "feedback", new String[] {}, appConfig, modelRoot);

    Map<String, Object> templateData = new HashMap<String, Object>();

    String namefrom = request.getParameter("name");
    String mailfrom = request.getParameter("email");
    String message = request.getParameter("message");
    String subject = request.getParameter("subject");
    String mailto = request.getParameter("mailto");
    LOGGER.error("*** " + subject);
    templateData.put("mailfrom", mailfrom);
    templateData.put("namefrom", namefrom);
    templateData.put("message", message);
    templateData.put("time", new SimpleDateFormat("EEEE, dd-MM-yyyy HH:mm z", locale).format(new Date()));
    String templateName = appConfig.getContactEmailTemplateName(locale);
    mailSender.sendMessage(mailto, subject, templateData, templateName);

    // Redirect back to main page
    RedirectView rv = new RedirectView(request.getContextPath());
    rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
    return new ModelAndView(rv);
}