Example usage for org.springframework.http HttpHeaders HttpHeaders

List of usage examples for org.springframework.http HttpHeaders HttpHeaders

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders HttpHeaders.

Prototype

public HttpHeaders() 

Source Link

Document

Construct a new, empty instance of the HttpHeaders object.

Usage

From source file:org.terasoluna.gfw.functionaltest.app.logging.LoggingTest.java

@Test
public void test01_04_checkConsistencyXtrackMDCRequestToResponse() {
    // test Check consistency HTTP Request Header to Response Header
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("X-Track", "12345678901234567890123456789012");
    ResponseEntity<byte[]> response = restTemplate.exchange(
            applicationContextUrl + "/logging/xTrackMDCPutFilter/1_4", HttpMethod.GET,
            new HttpEntity<byte[]>(requestHeaders), byte[].class);

    HttpHeaders headers = response.getHeaders();
    assertThat(headers.getFirst("X-Track"), is("12345678901234567890123456789012"));
}

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  ww  w .j  a  v a2  s  . c o  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.example.securelogin.app.account.AccountController.java

@RequestMapping(value = "/image")
@ResponseBody/*from   w ww .j a  v a2 s.c o m*/
public ResponseEntity<byte[]> showImage(@AuthenticationPrincipal LoggedInUser userDetails) throws IOException {
    AccountImage userImage = accountSharedService.getImage(userDetails.getUsername());
    HttpHeaders headers = new HttpHeaders();
    if (userImage.getExtension().equalsIgnoreCase("png")) {
        headers.setContentType(MediaType.IMAGE_PNG);
    } else if (userImage.getExtension().equalsIgnoreCase("gif")) {
        headers.setContentType(MediaType.IMAGE_GIF);
    } else if (userImage.getExtension().equalsIgnoreCase("jpg")) {
        headers.setContentType(MediaType.IMAGE_JPEG);
    }
    return new ResponseEntity<byte[]>(IOUtils.toByteArray(userImage.getBody()), headers, HttpStatus.OK);
}

From source file:org.avidj.zuul.client.ZuulRestClient.java

@Override
public boolean lock(String sessionId, List<String> path, LockType type, LockScope scope) {
    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    Map<String, String> parameters = new HashMap<>();
    parameters.put("id", sessionId); // set the session id
    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(serviceUrl + lockPath(path))
            .queryParam("t", type(type)).queryParam("s", scope(scope));

    ResponseEntity<String> result = restTemplate.exchange(uriBuilder.build().encode().toUri(), HttpMethod.PUT,
            entity, String.class);

    LOG.info(result.toString());/*from w w  w. j  av  a 2s  .c o  m*/
    HttpStatus code = result.getStatusCode();
    return code.equals(HttpStatus.CREATED);
}

From source file:com.alehuo.wepas2016projekti.controller.ImageController.java

/**
 * Hakee tietokannasta kuvan. Kuvan hakemisessa hydynnetn ETag
 * -otsaketta.//w w w. j a v  a  2s .c o m
 *
 * @param a Autentikointi
 * @param imageUuid Kuvan UUID
 * @param ifNoneMatch If-None-Match -headeri vlimuistia varten
 * @return Kuva
 */
@RequestMapping(value = "/{imageUuid}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<byte[]> getImage(Authentication a, @PathVariable String imageUuid,
        @RequestHeader(required = false, value = "If-None-Match") String ifNoneMatch) {
    if (ifNoneMatch != null) {
        //            LOG.log(Level.INFO, "Kuva ''{0}'' loytyy kayttajan selaimen valimuistista eika sita tarvitse ladata. Kuvaa pyysi kayttaja ''{1}''", new Object[]{imageUuid, a.getName()});
        //Jos If-None-Match -headeri lytyy, niin lhet NOT MODIFIED vastaus
        return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
    }
    Image i = imageService.findOneImageByUuid(imageUuid);
    if (i != null && i.isVisible()) {
        //Luodaan ETag kuvalle
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(i.getContentType()));
        headers.setContentLength(i.getImageData().length);
        headers.setCacheControl("public");
        headers.setExpires(Long.MAX_VALUE);
        headers.setETag("\"" + imageUuid + "\"");
        //            LOG.log(Level.INFO, "Kuva ''{0}'' loytyi tietokannasta, ja sita pyysi kayttaja ''{1}''", new Object[]{imageUuid, a.getName()});
        //Palautetaan kuva uutena resurssina
        return new ResponseEntity<>(i.getImageData(), headers, HttpStatus.CREATED);
    } else {
        //Jos kuvaa ei lydy tietokannasta
        LOG.log(Level.WARNING, "Kuvaa ''{0}'' ei loytynyt tietokannasta, ja sita pyysi kayttaja ''{1}''",
                new Object[] { imageUuid, a.getName() });
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

From source file:dk.nsi.haiba.epimibaimporter.status.StatusReporter.java

@RequestMapping(value = "/status")
public ResponseEntity<String> reportStatus() {

    String manual = request.getParameter("manual");
    if (manual == null || manual.trim().length() == 0) {
        // no value set, use default set in the import executor
        manual = "" + importExecutor.isManualOverride();
    } else {/*w w w  .  ja  va 2 s.c o m*/
        // manual flag is set on the request
        if (manual.equalsIgnoreCase("true")) {
            importExecutor.setManualOverride(true);
            importExecutor.doProcess(true);
        } else {
            importExecutor.setManualOverride(false);
        }
    }

    HttpHeaders headers = new HttpHeaders();
    String body = "OK";
    HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
    body = "OK";

    try {
        if (!statusRepo.isHAIBADBAlive()) {
            body = "HAIBA Database is _NOT_ running correctly";
        } else if (statusRepo.isOverdue()) {
            // last run information is applied to body later
            body = "Is overdue";
        } else {
            status = HttpStatus.OK;
        }
    } catch (Exception e) {
        body = e.getMessage();
    }

    body += "</br>";
    body = addLastRunInformation(body);

    body += "</br>------------------</br>";

    String importProgress = currentImportProgress.getStatus();
    body += importProgress;

    body += "</br>------------------</br>";

    String url = request.getRequestURL().toString();

    body += "<a href=\"" + url + "?manual=true\">Manual start importer</a>";
    body += "</br>";
    body += "<a href=\"" + url + "?manual=false\">Scheduled start importer</a>";
    body += "</br>";
    if (manual.equalsIgnoreCase("true")) {
        body += "status: MANUAL";
    } else {
        // default
        body += "status: SCHEDULED - " + cron;
    }

    headers.setContentType(MediaType.TEXT_HTML);

    return new ResponseEntity<String>(body, headers, status);
}

From source file:com.gazbert.bxbot.rest.api.EngineConfigController.java

/**
 * Updates Engine configuration for the bot.
 *
 * @return 204 'No Content' HTTP status code if engine config was updated successfully, some other HTTP status code otherwise.
 *//*  w ww.  j ava  2s  .  c o m*/
@RequestMapping(value = "/engine", method = RequestMethod.PUT)
public ResponseEntity<?> updateEngine(@AuthenticationPrincipal User user, @RequestBody EngineConfig config) {

    engineConfigService.updateConfig(config);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders
            .setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/").buildAndExpand().toUri());
    return new ResponseEntity<>(null, httpHeaders, HttpStatus.NO_CONTENT);
}

From source file:com.itn.webservices.AdminControllerWebservice.java

@RequestMapping(value = "/food", method = RequestMethod.POST)
public ResponseEntity<Void> createFood(@RequestBody FoodInventory food, UriComponentsBuilder ucBuilder) {
    logger.info("Creating Food " + food.getFoodName());

    if (foodInventoryService.isFoodExist(food)) {
        logger.info("A Food already exist");
        return new ResponseEntity<Void>(HttpStatus.CONFLICT);
    }//  w w w  . j  av  a 2  s  .  co  m

    foodInventoryService.save(food);

    HttpHeaders headers = new HttpHeaders();
    headers.setLocation(ucBuilder.path("/food/{id}").buildAndExpand(food.getId()).toUri());
    return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}

From source file:org.messic.android.util.RestJSONClient.java

/**
 * Rest GET petition to the server at the url param, sending all the post parameters defiend at formData. This post
 * return an object (json marshalling) of class defined at clazz parameter. You should register a
 * {@link RestListener} in order to obtain the returned object, this is because the petition is done in an async
 * process./*from   w  ww. j  a v a  2 s  .c  o  m*/
 * 
 * @param url {@link string} URL to attack
 * @param clazz Class<T/> class that you will marshall to a json object
 * @param rl {@link RestListener} listener to push the object returned
 */
public static <T> void get(final String url, final Class<T> clazz, final RestListener<T> rl) {
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    // Populate the MultiValueMap being serialized and headers in an HttpEntity object to use for the request
    final HttpEntity<MultiValueMap<?, ?>> requestEntity = new HttpEntity<MultiValueMap<?, ?>>(
            new LinkedMultiValueMap<String, Object>(), requestHeaders);

    AsyncTask<Void, Void, Void> at = new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            try {
                ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, clazz);
                rl.response(response.getBody());
            } catch (Exception e) {
                rl.fail(e);
            }
            return null;
        }

    };

    at.execute();
}

From source file:example.users.UserControllerClientTests.java

private UserPayload issueGet(String path, MediaType mediaType) {

    HttpHeaders headers = new HttpHeaders();
    headers.add(HttpHeaders.ACCEPT, mediaType.toString());

    return template.exchange(path, HttpMethod.GET, new HttpEntity<Void>(headers), UserPayload.class).getBody();
}