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:ch.ralscha.extdirectspring.controller.RouterControllerPollTest.java

@Test
public void pollRequiredHeaderWithValue() throws Exception {
    Map<String, String> params = new LinkedHashMap<String, String>();
    params.put("id", "1");

    HttpHeaders headers = new HttpHeaders();
    headers.add("header", "headerValue");
    headers.add("anotherName", "headerValue1");
    headers.add("anotherName", "headerValue2");

    ExtDirectPollResponse resp = ControllerUtil.performPollRequest(mockMvc, "pollProvider",
            "messageRequestHeader2", "messageRequestHeader2", params, headers);

    assertThat(resp).isNotNull();//from  w w w.j  a  v a 2s  .c om
    assertThat(resp.getType()).isEqualTo("event");
    assertThat(resp.getName()).isEqualTo("messageRequestHeader2");
    assertThat(resp.getData()).isEqualTo("1;headerValue1");
    assertThat(resp.getWhere()).isNull();
    assertThat(resp.getMessage()).isNull();

    params.clear();
    params.put("id", "2");

    resp = ControllerUtil.performPollRequest(mockMvc, "pollProvider", "messageRequestHeader2",
            "messageRequestHeader2", params, null, null, true);

    assertThat(resp).isNotNull();
    assertThat(resp.getType()).isEqualTo("exception");
    assertThat(resp.getName()).isEqualTo("messageRequestHeader2");
    assertThat(resp.getData()).isNull();
    assertThat(resp.getWhere()).isNull();
    assertThat(resp.getMessage()).isEqualTo("Server Error");

    params.clear();
    params.put("id", "3");
    headers = new HttpHeaders();
    headers.add("header", "headerValue");
    resp = ControllerUtil.performPollRequest(mockMvc, "pollProvider", "messageRequestHeader2",
            "messageRequestHeader2", params, headers, null, true);

    assertThat(resp).isNotNull();
    assertThat(resp.getType()).isEqualTo("exception");
    assertThat(resp.getName()).isEqualTo("messageRequestHeader2");
    assertThat(resp.getData()).isNull();
    assertThat(resp.getWhere()).isNull();
    assertThat(resp.getMessage()).isEqualTo("Server Error");
}

From source file:com.companyname.plat.commons.client.HttpRestfulClient.java

private HttpHeaders getHeaders() {
    HttpHeaders headers = this.getUnsecuredHeaders();

    String auth = ((getUserName() == null) ? "" : getUserName()) + ":"
            + ((getPassword() == null) ? "" : getPassword());

    if (":".equals(auth)) {
        return headers;
    }/*from   w  w  w  . j  av a 2  s  .  com*/

    byte[] encodedAuth = Base64.encode(auth.getBytes(Charset.forName("US-ASCII")));
    String authHeader = "Basic " + new String(encodedAuth);
    logger.info("http Restfule client has a header auth: " + authHeader);
    headers.add("Authorization", authHeader);
    return headers;
}

From source file:eu.freme.broker.eservices.ELink.java

@RequestMapping(value = "/e-link/documents", method = RequestMethod.POST)
@Secured({ "ROLE_USER", "ROLE_ADMIN" })
public ResponseEntity<String> enrich(@RequestParam(value = "templateid", required = true) String templateIdStr,
        @RequestHeader(value = "Accept", required = false) String acceptHeader,
        @RequestHeader(value = "Content-Type", required = false) String contentTypeHeader,
        @RequestBody String postBody, @RequestParam Map<String, String> allParams) {
    try {/*from w  w  w.  j a  v  a  2  s.  c o m*/

        Long templateId;
        try {
            templateId = new Long(templateIdStr);
        } catch (NumberFormatException e) {
            logger.error(e);
            String msg = "Parameter templateid is required to be a numeric value.";
            throw new BadRequestException(msg);
        }

        // int templateId = validateTemplateID(templateIdStr);
        NIFParameterSet nifParameters = this.normalizeNif(postBody, acceptHeader, contentTypeHeader, allParams,
                false);

        // templateDAO.findOneById(templateIdStr);
        // Check read access and retrieve the template
        Template template = templateDAO.findOneById(templateId);

        HashMap<String, String> templateParams = new HashMap<>();

        for (Map.Entry<String, String> entry : allParams.entrySet()) {
            if (!nifParameterFactory.isNIFParameter(entry.getKey())) {
                templateParams.put(entry.getKey(), entry.getValue());
            }
        }

        Model inModel = rdfConversionService.unserializeRDF(nifParameters.getInput(),
                nifParameters.getInformat());
        inModel = dataEnricher.enrichWithTemplate(inModel, template, templateParams);

        HttpHeaders responseHeaders = new HttpHeaders();
        String serialization = rdfConversionService.serializeRDF(inModel, nifParameters.getOutformat());
        responseHeaders.add("Content-Type", nifParameters.getOutformat().contentType());
        return new ResponseEntity<>(serialization, responseHeaders, HttpStatus.OK);
    } catch (AccessDeniedException ex) {
        logger.error(ex.getMessage(), ex);
        throw new eu.freme.broker.exception.AccessDeniedException();
    } catch (BadRequestException ex) {
        logger.error(ex.getMessage(), ex);
        throw ex;
    } catch (OwnedResourceNotFoundException ex) {
        logger.error(ex.getMessage());
        throw new TemplateNotFoundException(ex.getMessage());
    } catch (org.apache.jena.riot.RiotException ex) {
        logger.error("Invalid NIF document. " + ex.getMessage(), ex);
        throw new InvalidNIFException(ex.getMessage());
    } catch (Exception ex) {
        logger.error("Internal service problem. Please contact the service provider.", ex);
        throw new InternalServerErrorException("Unknown problem. Please contact us.");
    }
}

From source file:bjerne.gallery.controller.GalleryController.java

/**
 * Method used to return the binary of a gallery file (
 * {@link GalleryFile#getActualFile()} ). This method handles 304 redirects
 * (if file has not changed) and range headers if requested by browser. The
 * range parts is particularly important for videos. The correct response
 * status is set depending on the circumstances.
 * <p>/*from  w  w w .  ja va  2s.c o  m*/
 * NOTE: the range logic should NOT be considered a complete implementation
 * - it's a bare minimum for making requests for byte ranges work.
 * 
 * @param request
 *            Request
 * @param galleryFile
 *            Gallery file
 * @return The binary of the gallery file, or a 304 redirect, or a part of
 *         the file.
 * @throws IOException
 *             If there is an issue accessing the binary file.
 */
private ResponseEntity<InputStreamResource> returnResource(WebRequest request, GalleryFile galleryFile)
        throws IOException {
    LOG.debug("Entering returnResource()");
    if (request.checkNotModified(galleryFile.getActualFile().lastModified())) {
        return null;
    }
    File file = galleryFile.getActualFile();
    String contentType = galleryFile.getContentType();
    String rangeHeader = request.getHeader(HttpHeaders.RANGE);
    long[] ranges = getRangesFromHeader(rangeHeader);
    long startPosition = ranges[0];
    long fileTotalSize = file.length();
    long endPosition = ranges[1] != 0 ? ranges[1] : fileTotalSize - 1;
    long contentLength = endPosition - startPosition + 1;
    LOG.debug("contentLength: {}, file length: {}", contentLength, fileTotalSize);

    LOG.debug("Returning resource {} as inputstream. Start position: {}", file.getCanonicalPath(),
            startPosition);
    InputStream boundedInputStream = new BoundedInputStream(new FileInputStream(file), endPosition + 1);

    InputStream is = new BufferedInputStream(boundedInputStream, 65536);
    InputStreamResource inputStreamResource = new InputStreamResource(is);
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.setContentLength(contentLength);
    responseHeaders.setContentType(MediaType.valueOf(contentType));
    responseHeaders.add(HttpHeaders.ACCEPT_RANGES, "bytes");
    if (StringUtils.isNotBlank(rangeHeader)) {
        is.skip(startPosition);
        String contentRangeResponseHeader = "bytes " + startPosition + "-" + endPosition + "/" + fileTotalSize;
        responseHeaders.add(HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader);
        LOG.debug("{} was not null but {}. Adding header {} to response: {}", HttpHeaders.RANGE, rangeHeader,
                HttpHeaders.CONTENT_RANGE, contentRangeResponseHeader);
    }
    HttpStatus status = (startPosition == 0 && contentLength == fileTotalSize) ? HttpStatus.OK
            : HttpStatus.PARTIAL_CONTENT;
    LOG.debug("Returning {}. Status: {}, content-type: {}, {}: {}, contentLength: {}", file, status,
            contentType, HttpHeaders.CONTENT_RANGE, responseHeaders.get(HttpHeaders.CONTENT_RANGE),
            contentLength);
    return new ResponseEntity<InputStreamResource>(inputStreamResource, responseHeaders, status);
}

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

@Test
public void testMethod4() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.add("header", "headerValue");
    ControllerUtil.sendAndReceive(mockMvc, headers, "remoteProviderOptional", "method4", "1;v;headerValue", 1,
            "v");
}

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

@Test
public void testMethod7a() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.add("header", "headerValue");
    ControllerUtil.sendAndReceiveWithSession(mockMvc, headers, "remoteProviderOptional", "method7",
            "headerValue");
}

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

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

    ControllerUtil.sendAndReceive(mockMvc, headers, "remoteProviderOptional", "method6", "headerValue1");
}

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

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

    ControllerUtil.sendAndReceive(mockMvc, headers, "remoteProviderOptional", "method8",
            "100;default1;default2;lastHeader", 100);
}

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

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

    ControllerUtil.sendAndReceive(mockMvc, headers, "remoteProviderOptional", "method5", "11;headerValue1", 11);
}