List of usage examples for org.springframework.http HttpHeaders setAccept
public void setAccept(List<MediaType> acceptableMediaTypes)
From source file:org.opentides.rest.impl.BaseCrudRestServiceImpl.java
/** * Make sure RestTemplate is properly set. *//*from www . j av a 2 s . c o m*/ @SuppressWarnings("unchecked") @PostConstruct public final void afterPropertiesSet() throws Exception { try { this.entityBeanType = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()) .getActualTypeArguments()[0]; } catch (ClassCastException cc) { // if dao is extended from the generic dao class this.entityBeanType = (Class<T>) ((ParameterizedType) getClass().getSuperclass().getGenericSuperclass()) .getActualTypeArguments()[0]; } // setup entity(headers) for basic authentication. HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); this.entity = new HttpEntity<String>(headers); // setup the rest template if (restTemplate == null) { restTemplate = new RestTemplate(); } Assert.notNull(this.entityBeanType, "Unable to retrieve entityBeanType for " + this.getClass().getSimpleName()); }
From source file:org.apigw.authserver.ServerRunning.java
public ResponseEntity<String> postForString(String path, MultiValueMap<String, String> formData) { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); return client.exchange(getUrl(path), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData, headers), String.class); }
From source file:org.n52.tamis.rest.forward.processes.execute.ExecuteRequestForwarder.java
/** * {@inheritDoc} <br/>//from w w w.j a va 2 s.co m * <br/> * Delegates an incoming execute request to the WPS proxy. * * Has two possible return values depending on the type of execution * (synchronous or asynchronous)! See return description. * * @param parameterValueStore * must contain the URL variable * {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} to * identify the WPS instance and * {@link URL_Constants_TAMIS#PROCESS_ID_VARIABLE_NAME} to * identify the process * * @param requestBody * must be an instance of {@link Execute_HttpPostBody} * @return either a String value representing the location header to the * created job instance (in case of asynchronous execution) * <b>OR</b> an instance of {@link ResultDocument} (in case of * synchronous execution). * @throws IOException */ @Override public Object forwardRequestToWpsProxy(HttpServletRequest request, Object requestBody, ParameterValueStore parameterValueStore) throws IOException { initializeRequestSpecificParameters(parameterValueStore); Execute_HttpPostBody executeBody = null; /* * requestBody must be an instance of Execute_HttpPostBody */ if (requestBody instanceof Execute_HttpPostBody) executeBody = (Execute_HttpPostBody) requestBody; else logger.error( "Request body was expected to be an instance of \"{}\", but was \"{}\". NullPointerException might occur.", Execute_HttpPostBody.class, requestBody.getClass()); // add process Id, since it is not included in the received execute // body, but is needed executeBody.setProcessId(this.getProcessId()); sosRequestConstructor.constructSosGetObservationRequestsForInputs(executeBody); String execute_url_wpsProxy = createTargetURL_WpsProxy(request); /* * To guarantee the existence of the parameter "sync-execute" in the * request-object, the parameter has been added as an attribute to the * request. */ boolean syncExecute_parameter = (boolean) request .getAttribute(ExecuteProcessController.SYNC_EXECUTE_PARAMETER_NAME); execute_url_wpsProxy = append_syncExecute_parameter(syncExecute_parameter, execute_url_wpsProxy); /* * forward execute request to WPS proxy. * * depending on the request parameter "sync-execute" the call should be * realized asynchronously or synchronously. */ URI createdJobUri_wpsProxy = null; /** * content headers! */ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); if (syncExecute_parameter) { // synchronous RestTemplate synchronousExecuteTemplate = new RestTemplate(); /* * execute the POST request synchronously * * the return value will be a result document of the newly created * resource. Thus, we have to extract the jobId from it to manually * build the location header) * */ HttpEntity requestEntity = new HttpEntity(executeBody, headers); ResultDocument resultDocument = synchronousExecuteTemplate.postForObject(execute_url_wpsProxy, requestEntity, ResultDocument.class); /* * the WPS is not conceptualized to offer a StatusRequest against a * job that has been executed synchronously. Hence, any jobID-URL * pointing to a synchronous job will fail (and result in a Bad * Request error or syntax error) * * Hence, we will simply return the ResultDocument! */ return resultDocument; } else { /* * Proceed similar to synchronous, since I just call the WPS proxy * with different sync-execute parameter; * * In opposite to synchronous call, will receive and return the * location header of the newly created job instance */ RestTemplate asynchronousExecuteTemplate = new RestTemplate(); createdJobUri_wpsProxy = asynchronousExecuteTemplate.postForLocation(execute_url_wpsProxy, executeBody); /* * from the result of the execution request against the WPS proxy, * extract the location header and return it. * * the location header points to an URL specific for the WPS proxy! * * What we need is the URL pointing to THIS applications resource. * Hence, we must adapt the URL! --> Basically we have to extract the * job ID and append it to the standard URL path of THIS application. * * createdJobUrl_wpsProxy looks like "<baseUrl-wpsProxy>/processes/{processId}/jobs/{jobId}" */ String jobId = createdJobUri_wpsProxy.getPath().split(URL_Constants_WpsProxy.SLASH_JOBS + "/")[1]; /* * target job URL should look like: "<base-url-tamis>/services/{serviceId}/processes/{processId}/jobs/{jobId}" */ String createdJobUrl = request.getRequestURL().toString(); createdJobUrl = createdJobUrl + URL_Constants_TAMIS.SLASH_JOBS + "/" + jobId; return createdJobUrl; } }
From source file:org.cloudfoundry.identity.uaa.login.feature.OpenIdTokenGrantsIT.java
@Test public void testPasswordGrant() throws Exception { String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("cf:").getBytes())); HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.set("Authorization", basicDigestHeaderValue); LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>(); postBody.add("client_id", "cf"); postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf"); postBody.add("response_type", "token id_token"); postBody.add("grant_type", "password"); postBody.add("username", user.getUserName()); postBody.add("password", "secret"); ResponseEntity<Map> responseEntity = restOperations.exchange(loginUrl + "/oauth/token", HttpMethod.POST, new HttpEntity<>(postBody, headers), Map.class); Assert.assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); Map<String, Object> params = responseEntity.getBody(); Assert.assertTrue(params.get("jti") != null); Assert.assertEquals("bearer", params.get("token_type")); Assert.assertThat((Integer) params.get("expires_in"), Matchers.greaterThan(40000)); String[] scopes = UriUtils.decode((String) params.get("scope"), "UTF-8").split(" "); Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write", "cloud_controller.write", "openid", "cloud_controller.read")); validateToken("access_token", params, scopes); validateToken("id_token", params, scopes); }
From source file:org.cloudfoundry.identity.uaa.login.feature.OpenIdTokenGrantsIT.java
@Test public void testImplicitGrant() throws Exception { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>(); postBody.add("client_id", "cf"); postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf"); postBody.add("response_type", "token id_token"); postBody.add("source", "credentials"); postBody.add("username", user.getUserName()); postBody.add("password", "secret"); ResponseEntity<Void> responseEntity = restOperations.exchange(loginUrl + "/oauth/authorize", HttpMethod.POST, new HttpEntity<>(postBody, headers), Void.class); Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode()); UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation()) .build();/*from w w w. ja va 2s. co m*/ Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost()); Assert.assertEquals("/redirect/cf", locationComponents.getPath()); MultiValueMap<String, String> params = parseFragmentParams(locationComponents); Assert.assertThat(params.get("jti"), not(empty())); Assert.assertEquals("bearer", params.getFirst("token_type")); Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000)); String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" "); Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write", "cloud_controller.write", "openid", "cloud_controller.read")); validateToken("access_token", params.toSingleValueMap(), scopes); validateToken("id_token", params.toSingleValueMap(), scopes); }
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 . j a 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; }
From source file:com.orange.cepheus.cep.EventSinkListenerTest.java
/** * Check that an updateContext is fired when a new event bean arrives *///from ww w . ja v a2 s . c om @Test public void postMessageOnEventUpdate() { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentType(MediaType.APPLICATION_JSON); httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON)); when(statement.getText()).thenReturn("statement"); when(ngsiClient.getRequestHeaders(any())).thenReturn(httpHeaders); // Trigger event update List<ContextAttribute> attributes = new LinkedList<>(); attributes.add(new ContextAttribute("id", "string", "OUT1234")); attributes.add(new ContextAttribute("avgTemp", "double", 10.25)); attributes.add(new ContextAttribute("avgTemp_unit", "string", "celcius")); EventBean[] beans = { buildEventBean("TempSensorAvg", attributes) }; eventSinkListener.update(beans, null, statement, provider); // Capture updateContext when postUpdateContextRequest is called on updateContextRequest, ArgumentCaptor<UpdateContext> updateContextArg = ArgumentCaptor.forClass(UpdateContext.class); ArgumentCaptor<HttpHeaders> headersArg = ArgumentCaptor.forClass(HttpHeaders.class); verify(ngsiClient).updateContext(eq(broker.getUrl()), headersArg.capture(), updateContextArg.capture()); // Check updateContext is valid UpdateContext updateContext = updateContextArg.getValue(); assertEquals(UpdateAction.APPEND, updateContext.getUpdateAction()); assertEquals(1, updateContext.getContextElements().size()); // Check headers are valid HttpHeaders headers = headersArg.getValue(); assertEquals(MediaType.APPLICATION_JSON, headers.getContentType()); assertTrue(headers.getAccept().contains(MediaType.APPLICATION_JSON)); assertEquals("SN", headers.getFirst("Fiware-Service")); assertEquals("SP", headers.getFirst("Fiware-ServicePath")); assertEquals("AUTH_TOKEN", headers.getFirst("X-Auth-Token")); ContextElement contextElement = updateContext.getContextElements().get(0); assertEquals("OUT1234", contextElement.getEntityId().getId()); assertEquals("TempSensorAvg", contextElement.getEntityId().getType()); assertFalse(contextElement.getEntityId().getIsPattern()); assertEquals(1, contextElement.getContextAttributeList().size()); ContextAttribute attr = contextElement.getContextAttributeList().get(0); assertEquals("avgTemp", attr.getName()); assertEquals("double", attr.getType()); assertEquals(10.25, attr.getValue()); assertEquals(1, attr.getMetadata().size()); assertEquals("unit", attr.getMetadata().get(0).getName()); assertEquals("string", attr.getMetadata().get(0).getType()); assertEquals("celcius", attr.getMetadata().get(0).getValue()); }
From source file:sparklr.common.AbstractAuthorizationCodeProviderTests.java
private HttpHeaders getAuthenticatedHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); headers.set("Authorization", "Basic " + new String(Base64.encode("user:password".getBytes()))); if (context.getRestTemplate() != null) { context.getAccessTokenRequest().setHeaders(headers); }/*from ww w.j a v a 2 s.c om*/ return headers; }
From source file:com.athena.peacock.controller.common.component.RHEVMRestTemplate.java
/** * <pre>//from www. j a v a2s . c om * HTTP Header? ?? ?. * </pre> * @return */ private HttpEntity<Object> setHTTPEntity(Object body, String rootElementName) { List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>(); acceptableMediaTypes.add(MediaType.APPLICATION_XML); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setContentType(MediaType.APPLICATION_XML); requestHeaders.setAccept(acceptableMediaTypes); requestHeaders.set(HOST_HEADER_KEY, host); requestHeaders.set(AUTH_HEADER_KEY, getCredential()); if (body != null) { logger.debug("Content Body => {}", marshal(body, rootElementName)); return new HttpEntity<Object>(marshal(body, rootElementName), requestHeaders); } else { return new HttpEntity<Object>(requestHeaders); } }
From source file:org.apigw.authserver.ServerRunning.java
public ResponseEntity<String> postForString(String path, HttpHeaders headers, MultiValueMap<String, String> formData) { HttpHeaders actualHeaders = new HttpHeaders(); actualHeaders.putAll(headers);/*from www .j a v a 2s. c om*/ actualHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED)); return client.exchange(getUrl(path), HttpMethod.POST, new HttpEntity<MultiValueMap<String, String>>(formData, actualHeaders), String.class); }