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:com.hpe.elderberry.Taxii10Template.java

private <T> HttpEntity<T> wrapRequest(T body) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(APPLICATION_XML);
    headers.setAccept(singletonList(APPLICATION_XML));
    headers.add("X-TAXII-Services", VID_TAXII_SERVICES_10);
    headers.add("X-TAXII-Content-Type", VID_TAXII_XML_10);
    String binding = conn.getDiscoveryUrl().getScheme().endsWith("s") ? VID_TAXII_HTTPS_10 : VID_TAXII_HTTP_10;
    headers.add("X-TAXII-Protocol", binding);
    return new HttpEntity<>(body, headers);
}

From source file:eu.freme.common.rest.OwnedResourceManagingController.java

@RequestMapping(value = "/{identifier}", method = RequestMethod.PUT)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> putEntityById(@PathVariable("identifier") String identifier,
        @RequestParam(value = visibilityParameterName, required = false) String visibility,
        @RequestParam(value = descriptionParameterName, required = false) String description,
        @RequestParam(value = newOwnerParameterName, required = false) String ownerName,
        @RequestParam Map<String, String> allParams, @RequestHeader Map<String, String> allHeaders,
        @RequestBody(required = false) String postBody) {
    try {//from  w ww  .  jav a  2 s . c  o  m
        Entity entity = entityDAO.findOneByIdentifier(identifier);

        if (!entityDAO.hasWriteAccess(entity))
            throw new AccessDeniedException("Access denied");

        updateEntity(entity, postBody, allParams, allHeaders);

        if (!Strings.isNullOrEmpty(visibility)) {
            entity.setVisibility(OwnedResource.Visibility.getByString(visibility));
        }

        if (!Strings.isNullOrEmpty(description)) {
            entity.setDescription(description);
        }

        entityDAO.save(entity);

        if (!Strings.isNullOrEmpty(ownerName)) {
            User owner = userDAO.getRepository().findOneByName(ownerName);
            if (owner == null)
                throw new BadRequestException(
                        "Can not change owner of the entity. User \"" + ownerName + "\" does not exist.");
            entity = entityDAO.updateOwner(entity, owner);
        }
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", SerializationFormatMapper.JSON);
        return new ResponseEntity<>(entity.toJson(), responseHeaders, HttpStatus.OK);
    } catch (AccessDeniedException ex) {
        logger.error(ex.getMessage(), ex);
        throw new eu.freme.common.exception.AccessDeniedException(ex.getMessage());
    } catch (BadRequestException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (org.json.JSONException ex) {
        logger.error(ex.getMessage(), ex);
        throw new BadRequestException(
                "The JSON object is incorrectly formatted. Problem description: " + ex.getMessage());
    } catch (FREMEHttpException ex) {
        logger.error(ex.getMessage());
        throw ex;
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        throw new FREMEHttpException(ex.getMessage());
    }
}

From source file:khs.trouble.service.impl.TroubleService.java

public String exception(String serviceName, String instanceId, String ltoken) {
    if (token != ltoken) {
        throw new RuntimeException("Invalid Access Token");
    }/* www .j a  v  a2 s.co m*/

    String url = FormatUrl.url(serviceInstanceURL(serviceName, instanceId) + "/trouble/exception", ssl);

    // invoke kill api...
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN));
    headers.add("token", token);
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    try {
        restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        eventService.exception(serviceName, url);
    } catch (Exception e) {
        eventService.attempted("Attempted to throw exception at service " + serviceName + " at " + url
                + " Failed due to exception " + e.getMessage());
    }
    return serviceName;
}

From source file:khs.trouble.service.impl.TroubleService.java

public String memory(String serviceName, String instanceId, String ltoken) {
    if (token != ltoken) {
        throw new RuntimeException("Invalid Access Token");
    }/*from   ww  w .  ja  va 2  s.com*/

    String url = FormatUrl.url(serviceInstanceURL(serviceName, instanceId) + "/trouble/memory", ssl);

    // invoke memory api...
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN));
    headers.add("token", token);
    headers.add("timeout", "" + timeout);
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    try {
        restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        eventService.memory(serviceName, url);
    } catch (Exception e) {
        eventService.attempted("Attempted to consume memory at service " + serviceName + " at " + url
                + " Failed due to exception " + e.getMessage());
    }
    return serviceName;
}

From source file:khs.trouble.service.impl.TroubleService.java

public String kill(String serviceName, String instanceId, String ltoken) {
    if (token != ltoken) {
        throw new RuntimeException("Invalid Access Token");
    }/* w  w w . j  ava2  s .  c  o  m*/

    String url = FormatUrl.url(serviceInstanceURL(serviceName, instanceId) + "trouble/kill", ssl);

    // invoke kill api...
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN));
    headers.add("token", token);
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    try {
        // int instanceCount = registry.instanceCount(serviceName);
        ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        if (result.getStatusCode() == HttpStatus.OK) {
            eventService.killed(serviceName, url);
            // monitorServiceRecovery(serviceName, instanceCount);
        }
    } catch (Exception e) {
        eventService.attempted("Attempted to Kill service " + serviceName + " at " + url
                + " Failed due to exception " + e.getMessage());
    }
    return serviceName;
}

From source file:fr.treeptik.cloudunit.cli.rest.RestUtils.java

/**
 * sendPostCommand//  w  ww  .j a  v  a2  s .c o  m
 *
 * @param url
 * @param parameters
 * @return
 * @throws ClientProtocolException
 */
public Map<String, Object> sendPostForUpload(String url, Map<String, Object> parameters) {
    RestTemplate restTemplate = new RestTemplate();
    List<HttpMessageConverter<?>> mc = restTemplate.getMessageConverters();
    mc.add(new MappingJacksonHttpMessageConverter());
    restTemplate.setMessageConverters(mc);
    MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<String, Object>();
    postParams.setAll(parameters);
    Map<String, Object> response = new HashMap<String, Object>();
    HttpHeaders headers = new HttpHeaders();
    headers.set("Content-Type", "multipart/form-data");
    headers.set("Accept", "application/json");
    headers.add("Cookie", "JSESSIONID=" + localContext.getCookieStore().getCookies().get(0).getValue());
    org.springframework.http.HttpEntity<Object> request = new org.springframework.http.HttpEntity<Object>(
            postParams, headers);
    ResponseEntity<?> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
    String body = result.getBody().toString();
    MediaType contentType = result.getHeaders().getContentType();
    HttpStatus statusCode = result.getStatusCode();
    response.put("content-type", contentType);
    response.put("statusCode", statusCode);
    response.put("body", body);

    return response;

}

From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java

public void refreshToken() {
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath);
    // Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in
    builder.queryParam("grant_type", "refresh_token");
    builder.queryParam("refresh_token", refreshToken);

    // Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code)
    HttpHeaders headers = new HttpHeaders();
    Encoder encoder = Base64.getEncoder();
    headers.add("Authorization",
            "Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes()));

    HttpEntity<String> entity = new HttpEntity<>("", headers);
    ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, OAuth2AccessToken.class);

    assertEquals(HttpStatus.OK, result2.getStatusCode());

    // Obtain and keep the token
    accessToken = result2.getBody().getValue();
    assertNotNull(accessToken);//from w w w .j av  a 2 s. co  m

    refreshToken = result2.getBody().getRefreshToken().getValue();
    assertNotNull(refreshToken);
}

From source file:khs.trouble.service.impl.TroubleService.java

public void spawnLoadThread(final String serviceName, String instanceId, final long sleep) {

    Runnable run = new Runnable() {

        public void run() {
            try {

                String url = FormatUrl.url(serviceInstanceURL(serviceName, instanceId) + "/trouble/load", ssl);

                // invoke kill api...
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN));
                headers.add("token", token);
                headers.add("timeout", "" + timeout);
                HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

                try {
                    restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
                } catch (Exception e) {
                    eventService.attempted("Attempted to Load service " + serviceName + " at " + url
                            + " Failed due to exception " + e.getMessage());
                }/*ww  w. j  ava 2s  . com*/
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    Thread thread = new Thread(run);
    thread.start();
}

From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java

@Test
public void obtainTokenFromOuth2LoginEndpoint() throws Exception {
    obtainAuthorizationCode();/*  w  w  w  .  ja  va  2  s . c  o m*/
    UriComponentsBuilder builder = UriComponentsBuilder
            .fromHttpUrl(authServerBaseUrl + oauth2TokenEndpointPath);
    // Here we don't authenticate the user, we authenticate the client and we pass the authcode proving that the user has accepted and loged in        
    builder.queryParam("client_id", getClientId());
    builder.queryParam("grant_type", "authorization_code");
    builder.queryParam("code", authorizationCode);
    builder.queryParam("redirect_uri", "http://anywhere");

    // Add Basic Authorization headers for CLIENT authentication (user was authenticated in previous request (authorization code)
    HttpHeaders headers = new HttpHeaders();
    Encoder encoder = Base64.getEncoder();
    headers.add("Authorization",
            "Basic " + encoder.encodeToString((getClientId() + ":" + getClientSecret()).getBytes()));

    HttpEntity<String> entity = new HttpEntity<>("", headers);
    ResponseEntity<OAuth2AccessToken> result2 = restTemplate.exchange(builder.build().encode().toUri(),
            HttpMethod.POST, entity, OAuth2AccessToken.class);

    // This means the user was correctly authenticated, then a redirection was performed to /oauth/authorize to obtain the token.
    // Then the token was sucessfully obtained (authenticating the client properly) and a last redirection was performed to the 
    // redirect_uri with the token after #
    assertEquals(HttpStatus.OK, result2.getStatusCode());

    // Obtain and keep the token
    accessToken = result2.getBody().getValue();
    assertNotNull(accessToken);

    refreshToken = result2.getBody().getRefreshToken().getValue();
    assertNotNull(refreshToken);
}

From source file:org.trustedanalytics.servicebroker.gearpump.service.CloudFoundryService.java

private String createUaaClient(String clientId, String clientName, String clientSecret, String redirectUri,
        String token) throws DashboardServiceException {
    LOGGER.info("Creating new UAA client");
    String body = String.format(CREATE_UAA_CLIENT_BODY_TEMPLATE, clientId, clientName, clientSecret,
            "http://" + redirectUri + REDIRECT_URI_SUFIX);

    HttpHeaders headers = new HttpHeaders();
    headers.add(AUTHORIZATION_HEADER, token);
    headers.add(CONTENT_TYPE_HEADER, "application/json");

    ResponseEntity<String> response = executeWithHeaders(CREATE_UAA_CLIENT_URL, HttpMethod.POST, body, headers,
            uaaApiEndpoint);// w ww  . j  a  v a 2 s  .c om
    LOGGER.debug("Created UAA client: {}", response.getBody());
    return response.getBody();
}