List of usage examples for org.springframework.http HttpHeaders add
@Override public void add(String headerName, @Nullable String headerValue)
From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java
@Test public void testAddSubscription_OK() throws Exception { HttpHeaders responseHeader = new HttpHeaders(); responseHeader.add("Location", "/v2/subscriptions/abcde98765"); mockServer.expect(requestTo(baseURL + "/v2/subscriptions")).andExpect(method(HttpMethod.POST)) .andExpect(header("Content-Type", MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.subject.entities[0].type").value("Room")) .andExpect(jsonPath("$.subject.condition.attributes[0]").value("temperature")) .andExpect(jsonPath("$.subject.condition.expression.q").value("temperature>40")) .andRespond(withNoContent().headers(responseHeader)); SubjectEntity subjectEntity = new SubjectEntity(); subjectEntity.setType(Optional.of("Room")); Condition condition = new Condition(); condition.setAttributes(Collections.singletonList("temperature")); condition.setExpression("q", "temperature>40"); SubjectSubscription subjectSubscription = new SubjectSubscription(Collections.singletonList(subjectEntity), condition);// ww w . j av a 2 s . co m List<String> attributes = new ArrayList<>(); attributes.add("temperature"); attributes.add("humidity"); Notification notification = new Notification(attributes, new URL("http://localhost:1234")); notification.setThrottling(Optional.of(new Long(5))); Subscription subscription = new Subscription(); subscription.setSubject(subjectSubscription); subscription.setNotification(notification); subscription.setExpires(Instant.parse("2016-04-05T14:00:00.20Z")); assertEquals("abcde98765", ngsiClient.addSubscription(subscription).get()); }
From source file:com.orange.ngsi2.client.Ngsi2ClientTest.java
@Test public void testAddSubscription_returnEmpty() throws Exception { HttpHeaders responseHeader = new HttpHeaders(); responseHeader.add("Location", ""); mockServer.expect(requestTo(baseURL + "/v2/subscriptions")).andExpect(method(HttpMethod.POST)) .andExpect(header("Content-Type", MediaType.APPLICATION_JSON_VALUE)) .andExpect(jsonPath("$.subject.entities[0].type").value("Room")) .andExpect(jsonPath("$.subject.condition.attributes[0]").value("temperature")) .andExpect(jsonPath("$.subject.condition.expression.q").value("temperature>40")) .andRespond(withNoContent().headers(responseHeader)); SubjectEntity subjectEntity = new SubjectEntity(); subjectEntity.setType(Optional.of("Room")); Condition condition = new Condition(); condition.setAttributes(Collections.singletonList("temperature")); condition.setExpression("q", "temperature>40"); SubjectSubscription subjectSubscription = new SubjectSubscription(Collections.singletonList(subjectEntity), condition);/*from w ww .j av a2s . c om*/ List<String> attributes = new ArrayList<>(); attributes.add("temperature"); attributes.add("humidity"); Notification notification = new Notification(attributes, new URL("http://localhost:1234")); notification.setThrottling(Optional.of(new Long(5))); Subscription subscription = new Subscription(); subscription.setSubject(subjectSubscription); subscription.setNotification(notification); subscription.setExpires(Instant.parse("2016-04-05T14:00:00.20Z")); assertEquals("", ngsiClient.addSubscription(subscription).get()); }
From source file:org.jbr.commons.rest.RestEndpointAspect.java
/** * Aspect that surrounds a bound RESTful controller method to provide the * following enhanced functionality:/*from w w w . jav a2s . co m*/ * * @param joinPoint * Provides reflective access to both the state available at a * join point and static information about it. * @param responseType * the {@link ResponseType} annotation which is used to specify * the response class for the bound controller method * @throws Throwable * any encountered error is passed through */ @SuppressWarnings({ "rawtypes", "unchecked" }) @Around(value = "@annotation(responseTimer)", argNames = "joinPoint, responseTimer") public Object around(final ProceedingJoinPoint joinPoint, final RestEndpoint responseTimer) throws Throwable { // start execution timer final Date startTime = startTimer(); // execute wrapped method final Object returnValue = joinPoint.proceed(); // halt and record execution timer final long elapsedTime = System.currentTimeMillis() - startTime.getTime(); LOG.debug("elapsed time for {} is {}ms", joinPoint, elapsedTime); // handle response entity if (returnValue instanceof ResponseEntity<?>) { final ResponseEntity<?> entity = (ResponseEntity<?>) returnValue; final HttpHeaders headers = new HttpHeaders(); // transfer any existing headers, if enabled if (responseTimer.transferHeaders()) { headers.putAll(entity.getHeaders()); } // transfer self link as Location header, if CREATED reponse if (entity.getStatusCode().equals(HttpStatus.CREATED)) { if (entity.getBody() instanceof ResourceSupport) { final ResourceSupport resource = (ResourceSupport) entity.getBody(); if (resource.getId() != null) { headers.setLocation(new URI(resource.getId().getHref())); } } } // save elapsed time header headers.add(HEADER_RESPONSE_ID, generatedResponseIdentifier()); headers.add(HEADER_START_TIME, DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(startTime)); headers.add(HEADER_ELAPSED_TIME, String.valueOf(elapsedTime)); // return new response entity return new ResponseEntity(entity.getBody(), headers, entity.getStatusCode()); } // handle non-response entity else { return returnValue; } }
From source file:org.client.two.service.OAuthAuthenticationService.java
public String getAuthorizationCode(String accessTokenA, String redirectUri, String appTokenClientTwo) { RestOperations rest = new RestTemplate(); HttpHeaders headersA = new HttpHeaders(); headersA.set("Authorization", "Bearer " + accessTokenA); ResponseEntity<String> resAuth2 = rest .exchange(// w w w .j av a 2 s . co m MessageFormat.format( "{0}/oauth/authorize?" + "client_id={1}&response_type=code&redirect_uri={2}&scope=WRITE", oauthServerBaseURL, appTokenClientTwo, redirectUri), HttpMethod.POST, new HttpEntity<String>(headersA), String.class); String sessionId = resAuth2.getHeaders().get("Set-Cookie").get(0); int p1 = sessionId.indexOf("=") + 1; int p2 = sessionId.indexOf(";"); sessionId = sessionId.substring(p1, p2); headersA.add("Cookie", "JSESSIONID=" + sessionId); resAuth2 = rest.exchange( MessageFormat.format("{0}/oauth/authorize?" + "user_oauth_approval=true&authorize=Authorize", oauthServerBaseURL), HttpMethod.POST, new HttpEntity<String>(headersA), String.class); String code = resAuth2.getHeaders().get("location").get(0); p1 = code.lastIndexOf("=") + 1; code = code.substring(p1); return code; }
From source file:com.highcharts.export.controller.ExportController.java
@RequestMapping(method = { RequestMethod.POST, RequestMethod.GET }) public HttpEntity<byte[]> exporter(@RequestParam(value = "svg", required = false) String svg, @RequestParam(value = "type", required = false) String type, @RequestParam(value = "filename", required = false) String filename, @RequestParam(value = "width", required = false) String width, @RequestParam(value = "scale", required = false) String scale, @RequestParam(value = "options", required = false) String options, @RequestParam(value = "globaloptions", required = false) String globalOptions, @RequestParam(value = "constr", required = false) String constructor, @RequestParam(value = "callback", required = false) String callback, @RequestParam(value = "callbackHC", required = false) String callbackHC, @RequestParam(value = "async", required = false, defaultValue = "false") Boolean async, @RequestParam(value = "jsonp", required = false, defaultValue = "false") Boolean jsonp, HttpServletRequest request, HttpSession session) throws ServletException, InterruptedException, SVGConverterException, NoSuchElementException, PoolException, TimeoutException, IOException, ZeroRequestParameterException { MimeType mime = getMime(type); String randomFilename = null; String jsonpCallback = ""; boolean isAndroid = request.getHeader("user-agent") != null && request.getHeader("user-agent").contains("Android"); if ("GET".equalsIgnoreCase(request.getMethod())) { // Handle redirect downloads for Android devices, these come in without request parameters String tempFile = (String) session.getAttribute("tempFile"); session.removeAttribute("tempFile"); if (tempFile != null && !tempFile.isEmpty()) { logger.debug("filename stored in session, read and stream from filesystem"); String basename = FilenameUtils.getBaseName(tempFile); String extension = FilenameUtils.getExtension(tempFile); return getFile(basename, extension); }// w w w .ja v a 2 s . c om } // check for visitors who don't know this domain is really only for the exporting service ;) if (request.getParameterMap().isEmpty()) { throw new ZeroRequestParameterException(); } /* Most JSONP implementations use the 'callback' request parameter and this overwrites * the original callback parameter for chart creation with Highcharts. If JSONP is * used we recommend using the requestparameter callbackHC as the callback for Highcharts. * store the callback method name and reset the callback parameter, * otherwise it will be used when creation charts */ if (jsonp) { async = true; jsonpCallback = callback; callback = null; if (callbackHC != null) { callback = callbackHC; } } if (isAndroid || MimeType.PDF.equals(mime) || async) { randomFilename = createRandomFileName(mime.name().toLowerCase()); } /* If randomFilename is not null, then we want to save the filename in session, in case of GET is used later on*/ if (isAndroid) { logger.debug("storing randomfile in session: " + FilenameUtils.getName(randomFilename)); session.setAttribute("tempFile", FilenameUtils.getName(randomFilename)); } String output = convert(svg, mime, width, scale, options, constructor, callback, globalOptions, randomFilename); ByteArrayOutputStream stream; HttpHeaders headers = new HttpHeaders(); if (async) { String link = TempDir.getDownloadLink(randomFilename); stream = new ByteArrayOutputStream(); if (jsonp) { StringBuilder sb = new StringBuilder(jsonpCallback); sb.append("('"); sb.append(link); sb.append("')"); stream.write(sb.toString().getBytes("utf-8")); headers.add("Content-Type", "text/javascript; charset=utf-8"); } else { stream.write(link.getBytes("utf-8")); headers.add("Content-Type", "text/html; charset=UTF-8"); } } else { headers.add("Content-Type", mime.getType() + "; charset=utf-8"); if (randomFilename != null && randomFilename.equals(output)) { stream = writeFileToStream(randomFilename); } else { boolean base64 = !mime.getExtension().equals("svg"); stream = outputToStream(output, base64); } filename = getFilename(filename); headers.add("Content-Disposition", "attachment; filename=" + filename.replace(" ", "_") + "." + mime.name().toLowerCase()); } headers.setContentLength(stream.size()); return new HttpEntity<byte[]>(stream.toByteArray(), headers); }
From source file:org.openscience.cdk.app.DepictController.java
private HttpEntity<byte[]> makeResponse(byte[] bytes, String contentType) { HttpHeaders header = new HttpHeaders(); String type = contentType.substring(0, contentType.indexOf('/')); String subtype = contentType.substring(contentType.indexOf('/') + 1, contentType.length()); header.setContentType(new MediaType(type, subtype)); header.add("Access-Control-Allow-Origin", "*"); header.set(HttpHeaders.CACHE_CONTROL, "max-age=31536000"); header.setContentLength(bytes.length); return new HttpEntity<>(bytes, header); }
From source file:org.messic.server.facade.controllers.rest.SongController.java
@ApiMethod(path = "/services/songs/{songSid}/dlna", verb = ApiVerb.GET, description = "Get the audio binary from a song resource of an album for a dlna service", produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE }) @ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"), @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"), @ApiError(code = IOMessicRESTException.VALUE, description = "IO error trying to get the audio resource") }) @RequestMapping(value = "/{songSid}/dlna", method = { RequestMethod.GET, RequestMethod.HEAD }) @ResponseStatus(HttpStatus.OK)//from ww w . java2s . c o m @ResponseBody @ApiResponseObject public ResponseEntity getSongDLNA( @ApiParam(name = "songSid", description = "SID of the song resource we want to download", paramType = ApiParamType.PATH, required = true) @PathVariable Long songSid, HttpServletRequest request, HttpServletResponse response) throws NotAuthorizedMessicRESTException, IOMessicRESTException, UnknownMessicRESTException { User user = SecurityUtil.getCurrentUser(); try { HttpHeaders headers = new HttpHeaders(); // TODO some mp3 songs fail with application/octet-stream // MP3 files must have the content type of audio/mpeg or application/octet-stream // ogg files must have the content type of application/ogg headers.setContentType(MediaType.parseMediaType("audio/mpeg")); headers.setConnection("close"); headers.add("EXT", null); headers.add("Accept-Ranges", "bytes"); headers.add("transferMode.dlna.org", "Streaming"); headers.add("contentFeatures.dlna.org", "DLNA.ORG_PN=MP3;DLNA.ORG_OP=01;DLNA.ORG_CI=0"); headers.add("realTimeInfo.dlna.org", "DLNA.ORG_TLAG=*"); headers.setDate(System.currentTimeMillis()); if (request.getHeader("Range") == null) { APISong.AudioSongStream ass = songAPI.getAudioSong(user, songSid); headers.setContentLength(ass.contentLength); headers.add("Content-Range", "bytes 0-" + ass.contentLength + "/" + ass.contentLength); InputStreamResource inputStreamResource = new InputStreamResource(ass.is); if (request.getMethod().equalsIgnoreCase("GET")) { return new ResponseEntity(inputStreamResource, headers, HttpStatus.OK); } else { return new ResponseEntity<byte[]>(new byte[0], headers, HttpStatus.OK); } } else { APISong.AudioSongStream ass = songAPI.getAudioSong(user, songSid); String range = request.getHeader("Range"); String[] sbytes = range.split("=")[1].split("-"); int from = Integer.valueOf(sbytes[0]); int to = (int) ass.contentLength; if (sbytes.length > 1) { to = Integer.valueOf(sbytes[1]); } headers.setContentLength(to - from); headers.add("Content-Range", "bytes " + from + "-" + to + "/" + ass.contentLength); if (request.getMethod().equalsIgnoreCase("GET")) { UtilSubInputStream usi = new UtilSubInputStream(ass.is, from, to); InputStreamResource inputStreamResource = new InputStreamResource(usi); return new ResponseEntity(inputStreamResource, headers, HttpStatus.OK); } else { return new ResponseEntity<byte[]>(new byte[0], headers, HttpStatus.OK); } } } catch (IOException ioe) { log.error("failed!", ioe); throw new IOMessicRESTException(ioe); } catch (Exception e) { throw new UnknownMessicRESTException(e); } }
From source file:org.client.one.service.OAuthAuthenticationService.java
public String getAuthorizationCode(String accessTokenA, String redirectUri, String appTokenClientTwo) { RestOperations rest = new RestTemplate(); HttpHeaders headersA = new HttpHeaders(); headersA.set("Authorization", "Bearer " + accessTokenA); ResponseEntity<String> resAuth2 = rest .exchange(/* ww w. ja v a 2 s . c o m*/ MessageFormat.format( "{0}/oauth/authorize?" + "client_id={1}&response_type=code&scope=WRITE&redirect_uri={2}", oauthServerBaseURL, appTokenClientTwo, redirectUri), HttpMethod.POST, new HttpEntity<String>(headersA), String.class); String sessionId = resAuth2.getHeaders().get("Set-Cookie").get(0); int p1 = sessionId.indexOf("=") + 1; int p2 = sessionId.indexOf(";"); sessionId = sessionId.substring(p1, p2); headersA.add("Cookie", "JSESSIONID=" + sessionId); resAuth2 = rest.exchange( MessageFormat.format("{0}/oauth/authorize?" + "user_oauth_approval=true&authorize=Authorize", oauthServerBaseURL), HttpMethod.POST, new HttpEntity<String>(headersA), String.class); String code = resAuth2.getHeaders().get("location").get(0); p1 = code.lastIndexOf("=") + 1; code = code.substring(p1); return code; }
From source file:com.formkiq.web.AbstractIntegrationTest.java
/** * Get Bearer Authorization./*from w w w . j ava2 s . co m*/ * @param token String * @return HttpHeaders */ protected HttpHeaders getBearerAuthorization(final String token) { HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Bearer " + token); return headers; }
From source file:com.formkiq.web.AbstractIntegrationTest.java
/** * Sends Rest API./*from www.j a v a 2 s .c o m*/ * @param <T> Type of Response * @param method HttpMethod * @param url String * @param responseType {@link Class} * @param acceptableMediaTypes {@link List} * @return ResponseEntity<String> */ protected <T> ResponseEntity<T> exchangeRest(final HttpMethod method, final String url, final Class<T> responseType, final List<MediaType> acceptableMediaTypes) { HttpHeaders headers = new HttpHeaders(); headers.add("User-Agent", "Dummy User Agent"); headers.setAccept(acceptableMediaTypes); HttpEntity<String> e = new HttpEntity<>("parameters", headers); ResponseEntity<T> entity = getTemplate().exchange(url, method, e, responseType); return entity; }