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:org.mitreid.multiparty.web.ResourceController.java

/**
 * @param resourceSet/*  w w  w.j  a v a 2  s .  c om*/
 * @param protectionAccessTokenValue 
 * @param client 
 * @param server 
 * @return
 */
private String getTicket(SharedResourceSet resourceSet, MultipartyServerConfiguration server,
        RegisteredClient client, String protectionAccessTokenValue) {

    JsonObject requestJson = new JsonObject();
    requestJson.addProperty("resource_set_id", resourceSet.getRsid());
    JsonArray scopes = new JsonArray();
    requestJson.add("resource_set_scopes", scopes);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Bearer " + protectionAccessTokenValue);

    HttpEntity<String> request = new HttpEntity<String>(requestJson.toString(), headers);

    HttpEntity<String> responseEntity = restTemplate.postForEntity(server.getPermissionRegistrationEndpoint(),
            request, String.class);

    JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();

    String ticket = rso.get("ticket").getAsString();

    return ticket;
}

From source file:org.mitreid.multiparty.web.ClientController.java

@RequestMapping(value = "claims_submitted")
public String claimsSubmissionCallback(@RequestParam("authorization_state") String authorizationState,
        @RequestParam("state") String returnState, @RequestParam("ticket") String ticket, HttpSession session,
        Model m) {/*from  w ww  .j a va 2s .  c  o  m*/

    // get our saved information out of the session
    String savedState = (String) session.getAttribute(STATE_SESSION_VAR);
    String savedResource = (String) session.getAttribute(RESOURCE_SESSION_VAR);
    String savedAuthServerUri = (String) session.getAttribute(AUTHSERVERURI_SESSION_VAR);

    // make sure the state matches
    if (Strings.isNullOrEmpty(returnState) || !returnState.equals(savedState)) {
        // it's an error if it doesn't
        logger.error("Unable to match states");
        return "home";
    }

    if (authorizationState.equals("claims_submitted")) {
        // claims have been submitted, let's go try to get a token again
        // find the AS we need to talk to (maybe discover)
        MultipartyServerConfiguration server = serverConfig.getServerConfiguration(savedAuthServerUri);

        // find the client configuration (maybe register)
        RegisteredClient client = clientConfig.getClientConfiguration(server);

        HttpHeaders tokenHeaders = new HttpHeaders();
        tokenHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // send request to the token endpoint
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();

        params.add("client_id", client.getClientId());
        params.add("client_secret", client.getClientSecret());
        params.add("grant_type", "urn:ietf:params:oauth:grant_type:multiparty-delegation");
        params.add("ticket", ticket);
        //params.add("scope", "read write");

        HttpEntity<MultiValueMap<String, String>> tokenRequest = new HttpEntity<>(params, tokenHeaders);

        ResponseEntity<String> tokenResponse = restTemplate.postForEntity(server.getTokenEndpointUri(),
                tokenRequest, String.class);
        JsonObject o = parser.parse(tokenResponse.getBody()).getAsJsonObject();

        if (o.has("error")) {
            if (o.get("error").getAsString().equals("need_info")) {
                // if we get need info, redirect

                JsonObject details = o.get("error_details").getAsJsonObject();

                // this is the URL to send the user to
                String claimsEndpoint = details.get("requesting_party_claims_endpoint").getAsString();
                String newTicket = details.get("ticket").getAsString();

                // set a state value for our return
                String state = UUID.randomUUID().toString();
                session.setAttribute(STATE_SESSION_VAR, state);

                // save bits about the request we were trying to make
                session.setAttribute(RESOURCE_SESSION_VAR, savedResource);
                session.setAttribute(AUTHSERVERURI_SESSION_VAR, savedAuthServerUri);

                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(claimsEndpoint)
                        .queryParam("client_id", client.getClientId()).queryParam("ticket", newTicket)
                        .queryParam("claims_redirect_uri", client.getClaimsRedirectUris().iterator().next()) // get the first one and punt
                        .queryParam("state", state);

                return "redirect:" + builder.build();
            } else {
                // it's an error we don't know how to deal with, give up
                logger.error("Unknown error from token endpoint: " + o.get("error").getAsString());
                return "home";
            }
        } else {
            // if we get an access token, try it again

            String accessTokenValue = o.get("access_token").getAsString();
            acccessTokenService.saveAccesstoken(savedResource, accessTokenValue);

            HttpHeaders headers = new HttpHeaders();
            if (!Strings.isNullOrEmpty(accessTokenValue)) {
                headers.add("Authorization", "Bearer " + accessTokenValue);
            }

            HttpEntity<Object> request = new HttpEntity<>(headers);

            ResponseEntity<String> responseEntity = restTemplate.exchange(savedResource, HttpMethod.GET,
                    request, String.class);

            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                // if we get back data, display it
                JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();
                m.addAttribute("label", rso.get("label").getAsString());
                m.addAttribute("value", rso.get("value").getAsString());
                return "home";
            } else {
                logger.error("Unable to get a token");
                return "home";
            }
        }
    } else {
        logger.error("Unknown response from claims endpoing: " + authorizationState);
        return "home";
    }

}

From source file:org.mitreid.multiparty.web.ResourceController.java

/**
 * @param incomingAccessToken//from w  w  w.ja  va  2 s  . co  m
 * @param server
 * @param client
 * @param protectionAccessTokenValue
 * @return
 */
private JsonObject introspectToken(String incomingAccessToken, MultipartyServerConfiguration server,
        RegisteredClient client, String protectionAccessTokenValue) {

    // POST to the introspection endpoint and get the results

    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("token", incomingAccessToken);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add("Authorization", "Bearer " + protectionAccessTokenValue);

    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);

    HttpEntity<String> responseEntity = restTemplate.postForEntity(server.getIntrospectionEndpointUri(),
            request, String.class);

    JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();

    return rso;
}

From source file:de.zib.vold.client.VolDClient.java

/**
 * Insert a set of keys./*  www .  j a  v  a2  s. c om*/
 */
public void insert(String source, Map<Key, Set<String>> map, final long timeStamp) {
    // guard
    {
        log.trace("Insert: " + map.toString());

        // nothing to do here?
        if (0 == map.size())
            return;

        checkState();

        if (null == map) {
            throw new IllegalArgumentException("null is no valid argument!");
        }
    }

    // build greatest common scope
    String commonscope;
    {
        List<String> scopes = new ArrayList<String>(map.size());

        for (Key k : map.keySet()) {
            scopes.add(k.get_scope());
        }

        commonscope = getGreatestCommonPrefix(scopes);
    }

    // build variable map
    String url;
    {
        url = buildURL(commonscope, null);
        log.debug("INSERT URL: " + url);
    }

    // build request body
    MultiValueMap<String, String> request = new LinkedMultiValueMap<String, String>();
    {
        for (Map.Entry<Key, Set<String>> entry : map.entrySet()) {
            // remove common prefix from scope
            String scope = entry.getKey().get_scope().substring(commonscope.length());
            String type = entry.getKey().get_type();
            String keyname = entry.getKey().get_keyname();

            URIKey key = new URIKey(source, scope, type, keyname, false, false, enc);
            String urikey = key.toURIString();

            for (String value : entry.getValue()) {
                request.add(urikey, value);
            }
        }
    }

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.add("TIMESTAMP", String.valueOf(timeStamp));
    HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
            request, requestHeaders);
    final ResponseEntity<HashMap> responseEntity = rest.exchange(url, HttpMethod.PUT, requestEntity,
            HashMap.class);
    //rest.put( url, request );
}

From source file:de.zib.vold.client.VolDClient.java

/**
 * Refresh a set of keys.//w  w  w  . j a  v a2  s . c  om
 *
 * @param source The source of the keys.
 * @param set The set keys to refresh.
 * @param timeStamp The timeStamp of this operation
 */
public Map<String, String> refresh(String source, Set<Key> set, final long timeStamp) {
    // guard
    {
        log.trace("Refresh: " + set.toString());

        checkState();

        if (null == set) {
            throw new IllegalArgumentException("null is no valid argument!");
        }
    }

    // build greatest common scope
    String commonscope;
    {
        List<String> scopes = new ArrayList<String>(set.size());

        for (Key k : set) {
            scopes.add(k.get_scope());
        }

        commonscope = getGreatestCommonPrefix(scopes);
    }

    // build request body
    Set<Key> keys = new HashSet<Key>();
    {
        for (Key entry : set) {
            // remove common prefix from scope
            final String scope = entry.get_scope().substring(commonscope.length());
            final String type = entry.get_type();
            final String keyname = entry.get_keyname();

            keys.add(new Key(scope, type, keyname));
        }
    }

    // build variable map
    String url;
    {
        url = buildURL(commonscope, keys);
        log.debug("REFRESH URL: " + url);
    }

    // get response from Server
    ResponseEntity<Map> responseEntity;
    {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("TIMESTAMP", String.valueOf(timeStamp));
        HttpEntity<Map<String, String>> requestEntity = new HttpEntity<Map<String, String>>(null,
                requestHeaders);
        responseEntity = rest.exchange(url, HttpMethod.POST, requestEntity, Map.class);
        //Object obj = rest.postForEntity( url, null, HashMap.class );
    }

    return responseEntity.getBody();
}

From source file:org.mitreid.multiparty.web.ResourceController.java

private String registerResourceSet(Principal p, String issuer, MultipartyServerConfiguration server,
        String accessTokenValue) {
    JsonObject requestJson = new JsonObject();
    /*//from  w w w.ja  v a2 s. c  om
     rs.setId(getAsLong(o, "_id"));
    rs.setName(getAsString(o, "name"));
    rs.setIconUri(getAsString(o, "icon_uri"));
    rs.setType(getAsString(o, "type"));
    rs.setScopes(getAsStringSet(o, "scopes"));
    rs.setUri(getAsString(o, "uri"));
            
     */
    requestJson.addProperty("name", p.getName() + "'s Resources");
    JsonArray scopes = new JsonArray();
    scopes.add(new JsonPrimitive("read"));
    scopes.add(new JsonPrimitive("write"));
    requestJson.add("resource_set_scopes", scopes);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", "Bearer " + accessTokenValue);

    HttpEntity<String> request = new HttpEntity<String>(requestJson.toString(), headers);

    HttpEntity<String> responseEntity = restTemplate.postForEntity(server.getResourceSetRegistrationEndpoint(),
            request, String.class);

    JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();
    String location = responseEntity.getHeaders().getLocation().toString();

    SharedResourceSet srs = new SharedResourceSet();
    srs.setIssuer(issuer);
    srs.setRsid(rso.get("_id").getAsString());
    srs.setUserAccessPolicyUri(rso.get("user_access_policy_uri").getAsString());
    srs.setLocation(location);

    resourceService.shareResourceForUser(srs, p);

    return "redirect:";
}

From source file:org.mitreid.multiparty.web.ClientController.java

@RequestMapping(value = "/fetch", method = RequestMethod.POST, consumes = MimeTypeUtils.APPLICATION_FORM_URLENCODED_VALUE)
public String fetch(@RequestParam("resource") String resource, Model m, HttpSession session) {

    // get the access token if we have one
    String accessTokenValue = acccessTokenService.getAccessToken(resource);

    // send our request to the resource

    HttpHeaders headers = new HttpHeaders();
    if (!Strings.isNullOrEmpty(accessTokenValue)) {
        headers.add("Authorization", "Bearer " + accessTokenValue);
    }/*from  ww w.  j a  v a 2s. co  m*/

    @SuppressWarnings("rawtypes")
    HttpEntity request = new HttpEntity<>(headers);

    ResponseEntity<String> responseEntity = restTemplate.exchange(resource, HttpMethod.GET, request,
            String.class);

    if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
        // if we get back data, display it
        JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();
        m.addAttribute("label", rso.get("label").getAsString());
        m.addAttribute("value", rso.get("value").getAsString());
        return "home";
    } else {
        // if we get back an error, try to get an access token
        List<String> authHeaders = responseEntity.getHeaders().get(HttpHeaders.WWW_AUTHENTICATE);
        // assume there's only one auth header for now
        String authHeader = Iterators.getOnlyElement(authHeaders.iterator());

        // parse the header to get the good bits
        String authServerUri = null;
        String ticket = null;
        Iterable<String> parts = Splitter.on(",").split(authHeader.substring("UMA ".length()));
        for (String part : parts) {
            List<String> subparts = Splitter.on("=").splitToList(part.trim());
            if (subparts.get(0).equals("as_uri")) {
                authServerUri = subparts.get(1);
                // strip quotes
                authServerUri = authServerUri.substring(1, authServerUri.length() - 1);
            } else if (subparts.get(0).equals("ticket")) {
                ticket = subparts.get(1);
                // strip quotes
                ticket = ticket.substring(1, ticket.length() - 1);
            }
        }

        // find the AS we need to talk to (maybe discover)
        MultipartyServerConfiguration server = serverConfig.getServerConfiguration(authServerUri);

        // find the client configuration (maybe register)
        RegisteredClient client = clientConfig.getClientConfiguration(server);

        HttpHeaders tokenHeaders = new HttpHeaders();
        tokenHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // send request to the token endpoint
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();

        params.add("client_id", client.getClientId());
        params.add("client_secret", client.getClientSecret());
        params.add("grant_type", "urn:ietf:params:oauth:grant_type:multiparty-delegation");
        params.add("ticket", ticket);
        //params.add("scope", "read write");

        HttpEntity<MultiValueMap<String, String>> tokenRequest = new HttpEntity<>(params, tokenHeaders);

        ResponseEntity<String> tokenResponse = restTemplate.postForEntity(server.getTokenEndpointUri(),
                tokenRequest, String.class);
        JsonObject o = parser.parse(tokenResponse.getBody()).getAsJsonObject();

        if (o.has("error")) {
            if (o.get("error").getAsString().equals("need_info")) {
                // if we get need info, redirect

                JsonObject details = o.get("error_details").getAsJsonObject();

                // this is the URL to send the user to
                String claimsEndpoint = details.get("requesting_party_claims_endpoint").getAsString();
                String newTicket = details.get("ticket").getAsString();

                // set a state value for our return
                String state = UUID.randomUUID().toString();
                session.setAttribute(STATE_SESSION_VAR, state);

                // save bits about the request we were trying to make
                session.setAttribute(RESOURCE_SESSION_VAR, resource);
                session.setAttribute(AUTHSERVERURI_SESSION_VAR, authServerUri);

                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(claimsEndpoint)
                        .queryParam("client_id", client.getClientId()).queryParam("ticket", newTicket)
                        .queryParam("claims_redirect_uri", client.getClaimsRedirectUris().iterator().next()) // get the first one and punt
                        .queryParam("state", state);

                return "redirect:" + builder.build();
            } else {
                // it's an error we don't know how to deal with, give up
                logger.error("Unknown error from token endpoint: " + o.get("error").getAsString());
                return "home";
            }
        } else {
            // if we get an access token, try it again

            accessTokenValue = o.get("access_token").getAsString();
            acccessTokenService.saveAccesstoken(resource, accessTokenValue);

            headers = new HttpHeaders();
            if (!Strings.isNullOrEmpty(accessTokenValue)) {
                headers.add("Authorization", "Bearer " + accessTokenValue);
            }

            request = new HttpEntity<>(headers);

            responseEntity = restTemplate.exchange(resource, HttpMethod.GET, request, String.class);

            if (responseEntity.getStatusCode().equals(HttpStatus.OK)) {
                // if we get back data, display it
                JsonObject rso = parser.parse(responseEntity.getBody()).getAsJsonObject();
                m.addAttribute("label", rso.get("label").getAsString());
                m.addAttribute("value", rso.get("value").getAsString());
                return "home";
            } else {
                logger.error("Unable to get a token");
                return "home";
            }
        }

    }

}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerPollTest.java

@Test
public void pollMultipleHeaders1() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.add("last", "lastHeader");

    ExtDirectPollResponse resp = ControllerUtil.performPollRequest(mockMvc, "pollProvider",
            "messageRequestHeader5", "messageRequestHeader5", null, headers);
    assertThat(resp).isNotNull();//from   w  w w.  j  a  v  a  2s  . com
    assertThat(resp.getType()).isEqualTo("event");
    assertThat(resp.getName()).isEqualTo("messageRequestHeader5");
    assertThat(resp.getData()).isEqualTo("null;default1;default2;lastHeader");
    assertThat(resp.getWhere()).isNull();
    assertThat(resp.getMessage()).isNull();
}

From source file:ch.ralscha.extdirectspring.controller.RouterControllerPollTest.java

@Test
public void pollRequiredHeaderWithoutValue() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.add("header", "headerValue");

    ExtDirectPollResponse resp = ControllerUtil.performPollRequest(mockMvc, "pollProvider",
            "messageRequestHeader1", "messageRequestHeader1", null, headers);

    assertThat(resp).isNotNull();/*from ww  w  .  j av a 2s  .  c  o  m*/
    assertThat(resp.getType()).isEqualTo("event");
    assertThat(resp.getName()).isEqualTo("messageRequestHeader1");
    assertThat(resp.getData()).isEqualTo("null;null;headerValue");
    assertThat(resp.getWhere()).isNull();
    assertThat(resp.getMessage()).isNull();
}

From source file:com.epl.ticketws.services.QueryService.java

public T query(String url, String method, String accept, Class<T> rc, Map<String, String> parameters) {

    try {/*from www .  ja  va 2  s .co m*/
        URI uri = new URL(url).toURI();
        long timestamp = new Date().getTime();

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

        String stringToSign = getStringToSign(uri, httpMethod.name(), timestamp, parameters);

        // logger.info("String to sign: " + stringToSign);
        String authorization = generate_HMAC_SHA1_Signature(stringToSign, password + license);
        // logger.info("Authorization string: " + authorization);

        // Setting Headers
        HttpHeaders headers = new HttpHeaders();
        if (accept.equalsIgnoreCase("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", terminal);
        headers.add("OB_User", user);
        headers.add("OB_Channel", channel);
        headers.add("OB_POS", pos);
        headers.add("Content-Type", "application/x-www-form-urlencoded");

        HttpEntity<String> entity;

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

        RestTemplate restTemplate = new RestTemplate(
                new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
        List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
        interceptors.add(new LoggingRequestInterceptor());
        restTemplate.setInterceptors(interceptors);

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

        if (accept.equalsIgnoreCase("json")) {
            restTemplate.getMessageConverters().add(0,
                    new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter());
        } else {
            restTemplate.getMessageConverters().add(0,
                    new org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter());
        }

        ResponseEntity<T> response = restTemplate.exchange(uri, httpMethod, entity, rc);

        if (!response.getStatusCode().is2xxSuccessful())
            throw new HttpClientErrorException(response.getStatusCode());

        return response.getBody();
    } catch (HttpClientErrorException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (SignatureException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (URISyntaxException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
    return null;
}