List of usage examples for org.springframework.http HttpHeaders set
@Override public void set(String headerName, @Nullable String headerValue)
From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java
@Test public void basicAuthenticationFlowTest() throws Exception { // Login first TestLoginInfo loginInfo = login();//w w w. jav a 2 s. c o m // Calling protected remotelog service RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO(); logRequestVO.setMessage("Test mesage!"); logRequestVO.setLogLevel("DEBUG"); HttpHeaders headers = new HttpHeaders(); headers.set("Cookie", loginInfo.getJsessionid()); HttpEntity<RemoteLogRequestVO> entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath); // Try without token first - It should be 'Forbidden' // http://springinpractice.com/2012/04/08/sending-cookies-with-resttemplate ResponseEntity<String> responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityRemotelog, String.class); assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode()); // Try now with the CSRF token - It should work well // This implies passing JSESSIONID and CSRF Token headers.set(DEFAULT_CSRF_HEADER_NAME, loginInfo.getXsrfToken()); entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityRemotelog, String.class); assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode()); // Calling here logout builder = UriComponentsBuilder .fromHttpUrl("http://localhost:" + port + basicAuthenticationLogoutEndpointPath); HttpEntity<Void> entityLogout = new HttpEntity<Void>(headers); responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityLogout, String.class); assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode()); // Try to call remotelog again (after logout) // This implies passing JSESSIONID and CSRF Token - We expect this not to work as the CSRF token has been removed and the session invalidated entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityRemotelog, String.class); assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode()); }
From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java
@Test public void simpleAuthenticationFlowTest() throws Exception { // Login first TestLoginInfo loginInfo = login();//from w w w.j av a2 s .c om // Calling protected remotelog service RemoteLogRequestVO logRequestVO = new RemoteLogRequestVO(); logRequestVO.setMessage("Test mesage!"); logRequestVO.setLogLevel("DEBUG"); HttpHeaders headers = new HttpHeaders(); headers.set("Cookie", loginInfo.getJsessionid()); HttpEntity<RemoteLogRequestVO> entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl("http://localhost:" + port + baseApiPath + remoteLogEndpointPath); // Try without token first - It should be 'Forbidden' // http://springinpractice.com/2012/04/08/sending-cookies-with-resttemplate ResponseEntity<String> responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityRemotelog, String.class); assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode()); // Try now with the CSRF token - It should work well // This implies passing JSESSIONID and CSRF Token headers.set(DEFAULT_CSRF_HEADER_NAME, loginInfo.getXsrfToken()); entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityRemotelog, String.class); assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode()); // Calling here logout builder = UriComponentsBuilder .fromHttpUrl("http://localhost:" + port + basicAuthenticationLogoutEndpointPath); HttpEntity<Void> entityLogout = new HttpEntity<Void>(headers); responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityLogout, String.class); assertEquals(HttpStatus.OK, responseEntityRemotelog.getStatusCode()); // Try to call remotelog again (after logout) // This implies passing JSESSIONID and CSRF Token - We expect this not to work as the CSRF token has been removed and the session invalidated entityRemotelog = new HttpEntity<RemoteLogRequestVO>(logRequestVO, headers); responseEntityRemotelog = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.POST, entityRemotelog, String.class); assertEquals(HttpStatus.FORBIDDEN, responseEntityRemotelog.getStatusCode()); }
From source file:cn.org.once.cstack.cli.rest.RestUtils.java
/** * /*from w w w . ja v a2s . c o m*/ * /** sendPostCommand * * @param url * @param parameters * @return * @throws ClientProtocolException */ public Map<String, Object> sendPostForUpload(String url, Map<String, Object> parameters) { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setBufferRequestBody(false); RestTemplate restTemplate = new RestTemplate(requestFactory); List<HttpMessageConverter<?>> mc = restTemplate.getMessageConverters(); mc.add(new MappingJackson2HttpMessageConverter()); 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()); HttpEntity<Object> request = new 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(STATUS_CODE, statusCode); response.put(BODY, body); return response; }
From source file:sparklr.common.AbstractEmptyAuthorizationCodeProviderTests.java
protected HttpHeaders getAuthenticatedHeaders() { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML)); headers.set("Authorization", getBasicAuthentication()); if (context.getRestTemplate() != null) { context.getAccessTokenRequest().setHeaders(headers); }// ww w.j a v a 2s . com return headers; }
From source file:org.starfishrespect.myconsumption.server.business.sensors.flukso.FluksoRetriever.java
/** * Tries to retrieve data for the sensor in the given interval and for the * given precision. All other retrieve methods use this * * @param start start of the interval * @param end end of the interval * @param resolution precision wanted./* w w w . j a va 2 s . c om*/ * @return the retrieved data * @throws RetrieveException if any error occurs */ private SensorData retrieve(Date start, Date end, int resolution) throws RetrieveException { SensorData data = new SensorData(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/json"); headers.set("X-Version", "1.0"); headers.set("X-Token", sensor.getToken()); HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); String url = "https://api.flukso.net/sensor/" + sensor.getFluksoId() + "?start=" + (start.getTime() / 1000) + "&end=" + (end.getTime() / 1000) + "&resolution=" + resolutionParam(resolution) + "&unit=watt"; try { ArrayList<ArrayList> retrieved = restTemplate.exchange(url, HttpMethod.GET, entity, ArrayList.class) .getBody(); boolean valuesFound = false; for (ArrayList measurement : retrieved) { if (measurement.size() < 2) { continue; } if (!(measurement.get(0) instanceof Integer) || !(measurement.get(1) instanceof Integer)) { continue; } valuesFound = true; int timestamp = (Integer) measurement.get(0); int value = (Integer) measurement.get(1); // timestamp - resolution because timestamp is the end time data.addMeasurement(timestamp - resolution, value); } if (!valuesFound) { data.setMayHaveMoreData(false); } } catch (HttpClientErrorException httpException) { throw new RequestException(httpException.getStatusCode().value(), "Cannot retrieve data."); } catch (ResourceAccessException resourceException) { throw new RetrieveException("Resource exceptions"); } catch (RestClientException restException) { throw new InvalidDataException("Non-valid data"); } return data; }
From source file:com.acc.test.ProductWebServiceTest.java
protected HttpHeaders getXMLHeaders() { final HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/xml"); return headers; }
From source file:com.acc.test.ProductWebServiceTest.java
protected HttpHeaders getJSONHeaders() { final HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/json"); return headers; }
From source file:comsat.sample.ui.method.SampleMethodSecurityApplicationTests.java
private void getCsrf(MultiValueMap<String, String> form, HttpHeaders headers) { ResponseEntity<String> page = new TestRestTemplate() .getForEntity("http://localhost:" + this.port + "/login", String.class); String cookie = page.getHeaders().getFirst("Set-Cookie"); headers.set("Cookie", cookie); String body = page.getBody(); Matcher matcher = Pattern.compile("(?s).*name=\"_csrf\".*?value=\"([^\"]+).*").matcher(body); matcher.find();/*from w w w.j a v a 2 s . c o m*/ form.set("_csrf", matcher.group(1)); }
From source file:org.jasig.portlet.degreeprogress.dao.xml.HttpDegreeProgressDaoImpl.java
/** * Get a request entity prepared for basic authentication. *//*from w ww . j av a 2s . c o m*/ protected HttpEntity<?> getRequestEntity(PortletRequest request) { String username = usernameEvaluator.evaluate(request); String password = passwordEvaluator.evaluate(request); if (log.isDebugEnabled()) { boolean hasPassword = password != null; log.debug("Preparing HttpEntity for user '" + username + "' (password provided = " + hasPassword + ")"); } HttpHeaders requestHeaders = new HttpHeaders(); String authString = username.concat(":").concat(password); String encodedAuthString = new Base64().encodeToString(authString.getBytes()); requestHeaders.set("Authorization", "Basic ".concat(encodedAuthString)); HttpEntity<?> rslt = new HttpEntity<Object>(requestHeaders); return rslt; }
From source file:org.energyos.espi.thirdparty.web.NotificationController.java
@Async private void doImportAsynchronously(String subscriptionUri) { // The import related to a subscription is performed here (in a separate // thread)//from www .j a v a 2s. c o m // This must be provably secure b/c the access_token is visible here String threadName = Thread.currentThread().getName(); System.out.printf("Start Asynchronous Input: %s: %s\n ", threadName, subscriptionUri); String resourceUri = subscriptionUri; String accessToken = ""; Authorization authorization = null; RetailCustomer retailCustomer = null; if (subscriptionUri.indexOf("?") > -1) { // Does message contain a query // element resourceUri = subscriptionUri.substring(0, subscriptionUri.indexOf("?")); // Yes, remove the query // element } if (resourceUri.contains("sftp://")) { try { String command = "sftp mget " + resourceUri.substring(resourceUri.indexOf("sftp://")); System.out.println("[Manage] Restricted Management Interface"); System.out.println("[Manage] Request: " + command); Process p = Runtime.getRuntime().exec(command); // the sftp script will get the file and make a RESTful api call // to add it into the workspace. } catch (IOException e1) { System.out.printf("**** [Manage] Error: %s\n", e1.toString()); } catch (Exception e) { System.out.printf("**** [Manage] Error: %s\n", e.toString()); } } else { try { if ((resourceUri.contains("/Batch/Bulk")) || (resourceUri.contains("/Authorization"))) { // mutate the resourceUri to be of the form .../Batch/Bulk resourceUri = (resourceUri .substring(0, resourceUri.indexOf("/resource/") + "/resource/".length()) .concat("Batch/Bulk")); } else { if (resourceUri.contains("/Subscription")) { // mutate the resourceUri for the form // /Subscription/{subscriptionId}/** String temp = resourceUri .substring(resourceUri.indexOf("/Subscription/") + "/Subscription/".length()); if (temp.contains("/")) { resourceUri = resourceUri .substring(0, resourceUri.indexOf("/Subscription") + "/Subscription".length()) .concat(temp.substring(0, temp.indexOf("/"))); } } } Authorization x = resourceService.findById(2L, Authorization.class); if (x.getResourceURI().equals(resourceUri)) { System.out.println("ResourceURIs Equal:" + resourceUri); } else { System.out.println("ResourceURIs Not - Equal:" + resourceUri); } authorization = resourceService.findByResourceUri(resourceUri, Authorization.class); retailCustomer = authorization.getRetailCustomer(); accessToken = authorization.getAccessToken(); try { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("Authorization", "Bearer " + accessToken); @SuppressWarnings({ "unchecked", "rawtypes" }) HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); // get the subscription HttpEntity<String> httpResult = restTemplate.exchange(subscriptionUri, HttpMethod.GET, requestEntity, String.class); // import it into the repository ByteArrayInputStream bs = new ByteArrayInputStream(httpResult.getBody().toString().getBytes()); importService.importData(bs, retailCustomer.getId()); } catch (Exception e) { // Log exception so that issue can be investigated include // stack trace to help locate issue System.out.printf( "\nNotificationController -- Asynchronous Input:\n Cause = %s\n Description = %s\n\n", e.getClass(), e.getMessage()); e.printStackTrace(); } } catch (EmptyResultDataAccessException e) { // No authorization, so log the fact and move on. It will // get imported later System.out.printf( "\nNotificationController -- Asynchronous Input:\n Cause = %s\n Description = %s\n\n", e.getClass(), e.getMessage()); } } System.out.printf("Asynchronous Input Completed %s: %s\n", threadName, resourceUri); }