Example usage for org.springframework.http HttpHeaders add

List of usage examples for org.springframework.http HttpHeaders add

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders add.

Prototype

@Override
public void add(String headerName, @Nullable String headerValue) 

Source Link

Document

Add the given, single header value under the given name.

Usage

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 {//w w w.  ja  va2s .co  m
            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:es.onebox.rest.utils.service.QueryService.java

/**
 * Main method to perform request to Onebox REST API.
 *
 * @param authenticationForm/*  w  w w .jav  a  2  s .  co m*/
 * @param queryForm
 * @return Response form request
 */
public ResponseDTO query(AuthenticationForm authenticationForm, QueryForm queryForm) {

    ResponseDTO responseDTO = new ResponseDTO();
    Exception ex = null;

    try {

        URL url = new URL(queryForm.getUrl());
        URI uri = url.toURI();

        Date date = new Date();
        long timestamp = date.getTime();

        HttpMethod httpMethod;

        if (queryForm.getMethod().equalsIgnoreCase("post")) {
            httpMethod = HttpMethod.POST;
        } else {
            httpMethod = HttpMethod.GET;
        }

        // Getting String to encode with HMAC-SHA1
        // First step in the signing algorithm
        String stringToSign = getStringToSign(uri, httpMethod.name(), timestamp, queryForm);

        logger.info("String to sign: " + stringToSign);

        // Encoding String
        // This is the actual authorization string that will be sent in the request
        String authorization = generate_HMAC_SHA1_Signature(stringToSign,
                authenticationForm.getPassword() + authenticationForm.getLicense());

        logger.info("Authorization string: " + authorization);

        // Adding to return object
        responseDTO.setDate(date);
        responseDTO.setStringToSign(stringToSign);
        responseDTO.setAuthorization(authorization);

        // Setting Headers
        HttpHeaders headers = new HttpHeaders();

        if (queryForm.getAccept().equals("json")) {
            headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        } else {
            headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
        }

        headers.add("Authorization", authorization);
        headers.add("OB_DATE", "" + timestamp);
        headers.add("OB_Terminal", authenticationForm.getTerminal());
        headers.add("OB_User", authenticationForm.getUser());
        headers.add("OB_Channel", authenticationForm.getChannelId());
        headers.add("OB_POS", authenticationForm.getPos());

        // Adding Headers to return object
        responseDTO.setHttpHeaders(headers);

        HttpEntity<String> entity;

        if (httpMethod == HttpMethod.POST) {
            // Adding post parameters to POST body
            String parameterStringBody = queryForm.getParametersAsString();
            entity = new HttpEntity<String>(parameterStringBody, headers);
            logger.info("POST Body: " + parameterStringBody);
        } else {
            entity = new HttpEntity<String>(headers);
        }

        // Creating rest client
        RestTemplate restTemplate = new RestTemplate();

        // Converting to UTF-8. OB Rest replies in windows charset.
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));

        // Performing request to Onebox REST API
        ResponseEntity<String> result = restTemplate.exchange(uri, httpMethod, entity, String.class);

        // TODO this functionlity is to map response to objetcs. It is not finished. Only placed here for POC
        /*
        if (queryForm.getMapResponse().booleanValue()) {
        ResponseEntity<EventSearchBean> event = restTemplate.exchange(uri, httpMethod, entity, EventSearchBean.class);
        }
        */

        // Adding response to return object
        responseDTO.setResponseEntity(result);

        logger.debug(result.toString());

    } catch (HttpClientErrorException e) {
        logger.error(e.getMessage());
        ex = e;
        e.printStackTrace();
        responseDTO.setError(e);
        responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters"));
    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
        ex = e;
        e.printStackTrace();
        responseDTO.setError(e);
        responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters"));
    } catch (SignatureException e) {
        logger.error(e.getMessage());
        ex = e;
        e.printStackTrace();
        responseDTO.setError(e);
        responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters"));
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
        ex = e;
        e.printStackTrace();
        responseDTO.setError(e);
        responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.parameters"));
    } catch (Exception e) {
        logger.error(e.getMessage());
        ex = e;
        e.printStackTrace();
        responseDTO.setError(e);
        responseDTO.setAdditionalErrorMessage(AppUtils.getMessage("error.request.authentication"));
    } finally {
        if (ex != null && ex instanceof HttpServerErrorException) {
            HttpServerErrorException e2 = (HttpServerErrorException) ex;
            ResponseEntity<String> responseEntity = new ResponseEntity<String>(e2.getResponseHeaders(),
                    HttpStatus.INTERNAL_SERVER_ERROR);

            List<String> ob_error_codes = e2.getResponseHeaders().get("OB_Error_Code");

            String ob_error_code;
            ResponseErrorCodesEnum ob_error = null;

            if (ob_error_codes != null && ob_error_codes.size() == 1) {
                ob_error_code = ob_error_codes.get(0);
                try {
                    ob_error = ResponseErrorCodesEnum.valueOf("ERROR_" + ob_error_code);
                } catch (Exception e) {
                    logger.error("API ERROR CODE NOT DEFINED: " + "ERROR_" + ob_error_code);
                }
                responseDTO.setObResponseErrorCode(ob_error);
            }

            responseDTO.setResponseEntity(responseEntity);
        }
    }

    return responseDTO;
}

From source file:eu.europa.ec.grow.espd.ted.TedService.java

private HttpHeaders createHeaders(final String username, final String password) {
    String plainCreds = username + ":" + password;
    String base64Creds = BaseEncoding.base64().encode(plainCreds.getBytes());

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.AUTHORIZATION, "Basic " + base64Creds);
    headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
    return headers;
}

From source file:eu.serco.dhus.server.http.webapp.wps.controller.WpsAdfSearchController.java

@RequestMapping(value = "/auxiliaries/download", method = { RequestMethod.GET })
public ResponseEntity<?> downloadAuxiliaries(@RequestParam(value = "uuid", defaultValue = "") String uuid,
        @RequestParam(value = "filename", defaultValue = "file") String filename) {

    try {/*from  w w w .  j ava 2  s  . c  om*/
        String hashedString = ConfigurationManager.getHashedConnectionString();
        //SD-1928 add download filename archive extension
        String downloadFilename = (filename.endsWith(DOWNLOAD_EXT)) ? (filename) : filename + DOWNLOAD_EXT;

        String urlString = ConfigurationManager.getExternalDHuSHost() + "odata/v1/Products('" + uuid
                + "')/$value";
        logger.info("urlString:::: " + urlString);
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "Basic " + hashedString);
        InputStream is = conn.getInputStream();
        InputStreamResource isr = new InputStreamResource(is);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Authorization", "Basic " + hashedString);
        httpHeaders.add("Content-disposition", "attachment; filename=" + downloadFilename);
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        return new ResponseEntity<>(isr, httpHeaders, HttpStatus.OK);

    } catch (Exception e) {

        logger.error(" Failed to download Auxiliary File.");
        e.printStackTrace();
        return new ResponseEntity<>("{\"code\":\"unauthorized\"}", HttpStatus.UNAUTHORIZED);
    }

}

From source file:eu.simpaticoproject.ife.controller.ProxyController.java

@RequestMapping(value = "/api/proxy/textenrich", method = RequestMethod.GET)
public @ResponseBody HttpEntity<String> textEnrichment(@RequestParam String text, @RequestParam String lex,
        HttpServletRequest request) throws Exception {

    String urlToCall = textEnrichUrl;
    if (Utils.isNotEmpty(request.getQueryString())) {
        urlToCall = urlToCall + "?lang=it&lex=" + URLEncoder.encode(lex, "UTF-8") + "&text="
                + URLEncoder.encode(text, "UTF-8");
    }//from w  ww . ja  v a  2 s  . c o m
    if (logger.isInfoEnabled()) {
        logger.info("textenrich:" + urlToCall);
    }
    GetMethod responseConnection = HTTPUtils.getConnection(urlToCall, null, null, null, null, request);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", "application/json; charset=UTF-8");
    InputStream is = responseConnection.getResponseBodyAsStream();
    byte[] byteStream = IOUtils.toByteArray(is);
    String body = new String(byteStream, "UTF-8");
    return new HttpEntity<String>(body, headers);
}

From source file:eu.simpaticoproject.ife.controller.ProxyController.java

@RequestMapping(value = "/api/proxy/wikipedia", method = RequestMethod.GET)
public @ResponseBody HttpEntity<byte[]> wikipedia(@RequestParam String content, HttpServletRequest request)
        throws Exception {

    String urlToCall = wikipediaUrl;
    if (Utils.isNotEmpty(request.getQueryString())) {
        urlToCall = urlToCall + "?action=parse&contentmodel=wikitext&prop=text&format=json&page="
                + URLEncoder.encode(content, "UTF-8");
    }//from  www  . j a  va 2  s  .co m
    if (logger.isInfoEnabled()) {
        logger.info("wikipedia:" + urlToCall);
    }
    GetMethod responseConnection = HTTPUtils.getConnection(urlToCall, null, null, null, null, request);

    HttpHeaders headers = new HttpHeaders();
    Header[] responseHeaders = responseConnection.getResponseHeaders();
    for (Header header : responseHeaders) {
        headers.add(header.getName(), header.getValue());
    }
    InputStream is = responseConnection.getResponseBodyAsStream();
    byte[] byteStream = IOUtils.toByteArray(is);
    return new HttpEntity<byte[]>(byteStream, headers);
}

From source file:eu.simpaticoproject.ife.controller.ProxyController.java

@RequestMapping(value = "/api/proxy/definitions/{word}", method = RequestMethod.GET)
public @ResponseBody HttpEntity<String> definitions(@PathVariable String word, HttpServletRequest request)
        throws Exception {

    String urlToCall = definitionsUrl;
    if (Utils.isNotEmpty(word)) {
        urlToCall = urlToCall.replaceAll("\\{word\\}", word);
    }//from w w  w .java 2 s . c  o  m
    if (logger.isInfoEnabled()) {
        logger.info("definitions:" + urlToCall);
    }
    GetMethod responseConnection = HTTPUtils.getConnection(urlToCall, null, null, null, null, request);

    HttpHeaders headers = new HttpHeaders();
    Header[] responseHeaders = responseConnection.getResponseHeaders();
    for (Header header : responseHeaders) {
        headers.add(header.getName(), header.getValue());
    }
    headers.setContentType(MediaType.APPLICATION_XML);
    InputStream is = responseConnection.getResponseBodyAsStream();
    byte[] byteStream = IOUtils.toByteArray(is);
    String body = new String(byteStream, "UTF-8");
    return new HttpEntity<String>(body, headers);
}

From source file:eu.simpaticoproject.ife.controller.ProxyController.java

@RequestMapping(value = "/api/proxy/synonyms/{word}", method = RequestMethod.GET)
public @ResponseBody HttpEntity<String> synonyms(@PathVariable String word, HttpServletRequest request)
        throws Exception {

    String urlToCall = synonymsUrl;
    if (Utils.isNotEmpty(word)) {
        urlToCall = urlToCall.replaceAll("\\{word\\}", word);
    }/*  w w  w .  ja  v  a  2  s. c om*/
    if (logger.isInfoEnabled()) {
        logger.info("synonyms:" + urlToCall);
    }
    GetMethod responseConnection = HTTPUtils.getConnection(urlToCall, null, null, null, null, request);

    HttpHeaders headers = new HttpHeaders();
    Header[] responseHeaders = responseConnection.getResponseHeaders();
    for (Header header : responseHeaders) {
        headers.add(header.getName(), header.getValue());
    }
    headers.setContentType(MediaType.APPLICATION_XML);
    InputStream is = responseConnection.getResponseBodyAsStream();
    byte[] byteStream = IOUtils.toByteArray(is);
    String body = new String(byteStream, "UTF-8");
    return new HttpEntity<String>(body, headers);
}

From source file:eu.simpaticoproject.ife.controller.ProxyController.java

@RequestMapping(value = "/api/proxy/translations/{word}", method = RequestMethod.GET)
public @ResponseBody HttpEntity<String> translations(@PathVariable String word, HttpServletRequest request)
        throws Exception {

    String urlToCall = translationsUrl;
    if (Utils.isNotEmpty(word)) {
        urlToCall = urlToCall.replaceAll("\\{word\\}", word);
    }/*from www .  jav  a2 s.c o  m*/
    if (logger.isInfoEnabled()) {
        logger.info("translations:" + urlToCall);
    }
    GetMethod responseConnection = HTTPUtils.getConnection(urlToCall, null, null, null, null, request);

    HttpHeaders headers = new HttpHeaders();
    Header[] responseHeaders = responseConnection.getResponseHeaders();
    for (Header header : responseHeaders) {
        headers.add(header.getName(), header.getValue());
    }
    headers.setContentType(MediaType.APPLICATION_XML);
    InputStream is = responseConnection.getResponseBodyAsStream();
    byte[] byteStream = IOUtils.toByteArray(is);
    String body = new String(byteStream, "UTF-8");
    return new HttpEntity<String>(body, headers);
}

From source file:eu.simpaticoproject.ife.controller.ProxyController.java

@RequestMapping(value = "/api/proxy/images", method = RequestMethod.GET)
public @ResponseBody HttpEntity<String> images(HttpServletRequest request) throws Exception {

    String urlToCall = imagesUrl;
    if (Utils.isNotEmpty(request.getQueryString())) {
        urlToCall = urlToCall + "?" + request.getQueryString();
    }//from  w  ww. j  a v  a 2s .c om
    if (logger.isInfoEnabled()) {
        logger.info("images:" + urlToCall);
    }
    GetMethod responseConnection = HTTPUtils.getConnection(urlToCall, imagesKeyName, imagesKeyValue, null, null,
            request);

    HttpHeaders headers = new HttpHeaders();
    Header[] responseHeaders = responseConnection.getResponseHeaders();
    for (Header header : responseHeaders) {
        headers.add(header.getName(), header.getValue());
    }
    InputStream is = responseConnection.getResponseBodyAsStream();
    byte[] byteStream = IOUtils.toByteArray(is);
    String body = new String(byteStream, "UTF-8");
    return new HttpEntity<String>(body, headers);
}