Example usage for org.springframework.http HttpHeaders setContentType

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

Introduction

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

Prototype

public void setContentType(@Nullable MediaType mediaType) 

Source Link

Document

Set the MediaType media type of the body, as specified by the Content-Type header.

Usage

From source file:cn.org.once.cstack.config.RestHandlerException.java

@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
        HttpHeaders headers, HttpStatus status, WebRequest request) {
    ex.printStackTrace();// w  w w  .java2s.c o m
    headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return handleExceptionInternal(ex, new HttpErrorServer(ex.getLocalizedMessage()), headers,
            HttpStatus.BAD_REQUEST, request);
}

From source file:org.nuvola.tvshowtime.ApplicationLauncher.java

private void loadAccessToken(String deviceCode) {
    String query = new StringBuilder("client_id=").append(TVST_CLIENT_ID).append("&client_secret=")
            .append(TVST_CLIENT_SECRET).append("&code=").append(deviceCode).toString();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    HttpEntity<String> entity = new HttpEntity<>(query, headers);

    ResponseEntity<AccessToken> content = tvShowTimeTemplate.exchange(TVST_ACCESS_TOKEN_URI, POST, entity,
            AccessToken.class);
    accessToken = content.getBody();//from   w w  w. jav  a  2  s  . c o m

    if (accessToken.getResult().equals("OK")) {
        LOG.info("AccessToken from TVShowTime with success : " + accessToken);
        tokenTimer.cancel();

        storeAccessToken();
        processWatchedEpisodes();
    } else {
        if (!accessToken.getMessage().equals("Authorization pending")
                && !accessToken.getMessage().equals("Slow down")) {
            LOG.error("Unexpected error did arrive, please reload the service :-(");
            tokenTimer.cancel();

            System.exit(1);
        }
    }
}

From source file:storage.StorageServiceWrapperController.java

protected ResponseEntity<String> read(@Nonnull final String storageServiceId, @Nonnull final String context,
        @Nonnull final String key) {
    try {/*from w  ww. jav  a2  s.c o  m*/
        final StorageService storageService = getStorageService(storageServiceId);
        if (storageService == null) {
            log.debug("Unable to find storage service with id '{}'", storageServiceId);
            return seleniumFriendlyResponse(HttpStatus.BAD_REQUEST);
        }

        log.debug("Reading from '{}' with context '{}' and key '{}'", storageServiceId, context, key);
        final StorageRecord record = storageService.read(context, key);
        log.debug("Read '{}' from '{}' with context '{}' and key '{}'", record, storageServiceId, context, key);

        if (record == null) {
            return seleniumFriendlyResponse(HttpStatus.NOT_FOUND);
        } else {
            final String serializedStorageRecord = serializer.serialize(record);
            final HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            return new ResponseEntity<>(serializedStorageRecord, httpHeaders, HttpStatus.OK);
        }
    } catch (IOException e) {
        log.debug("An error occurred", e);
        return seleniumFriendlyResponse(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:com.demo.FakeAuthorizator.java

private void doGet(String url) {
    System.out.println("try to send to " + url);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(headers);
    ResponseEntity<String> rese = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
    System.out.println("RESPONSE STRING " + rese.getBody());
}

From source file:com.marklogic.mgmt.admin.AdminManager.java

/**
 * Set whether SSL FIPS is enabled on the cluster or not by running against /v1/eval on the given appServicesPort.
 *///from  w  w w .  j  a v  a2 s.c om
public void setSslFipsEnabled(final boolean enabled, final int appServicesPort) {
    final String xquery = "import module namespace admin = 'http://marklogic.com/xdmp/admin' at '/MarkLogic/admin.xqy'; "
            + "admin:save-configuration(admin:cluster-set-ssl-fips-enabled(admin:get-configuration(), "
            + enabled + "()))";

    invokeActionRequiringRestart(new ActionRequiringRestart() {
        @Override
        public boolean execute() {
            RestTemplate rt = RestTemplateUtil.newRestTemplate(adminConfig.getHost(), appServicesPort,
                    adminConfig.getUsername(), adminConfig.getPassword());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
            map.add("xquery", xquery);
            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(
                    map, headers);
            String url = format("http://%s:%d/v1/eval", adminConfig.getHost(), appServicesPort);
            if (logger.isInfoEnabled()) {
                logger.info("Setting SSL FIPS enabled: " + enabled);
            }
            rt.exchange(url, HttpMethod.POST, entity, String.class);
            if (logger.isInfoEnabled()) {
                logger.info("Finished setting SSL FIPS enabled: " + enabled);
            }
            return true;
        }
    });
}

From source file:org.nuvola.tvshowtime.ApplicationLauncher.java

private void markEpisodeAsWatched(String episode) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add("User-Agent", TVST_USER_AGENT);
    HttpEntity<String> entity = new HttpEntity<>("filename=" + episode, headers);

    String checkinUrl = new StringBuilder(TVST_CHECKIN_URI).append("?access_token=")
            .append(accessToken.getAccess_token()).toString();

    ResponseEntity<Message> content = tvShowTimeTemplate.exchange(checkinUrl, POST, entity, Message.class);
    Message message = content.getBody();

    if (message.getResult().equals("OK")) {
        LOG.info("Mark " + episode + " as watched in TVShowTime");
    } else {/*  w  w  w  . j  a  v  a  2 s  .c  o  m*/
        LOG.error("Error while marking [" + episode + "] as watched in TVShowTime ");
    }

    // Check if we are below the Rate-Limit of the API
    int remainingApiCalls = Integer.parseInt(content.getHeaders().get(TVST_RATE_REMAINING_HEADER).get(0));
    if (remainingApiCalls == 0) {
        try {
            LOG.info("Consumed all available TVShowTime API calls slots, waiting for new slots ...");
            Thread.sleep(MINUTE_IN_MILIS);
        } catch (Exception e) {
            LOG.error(e.getMessage());

            System.exit(1);
        }
    }
}

From source file:org.akaademiwolof.ConfigurationTests.java

@SuppressWarnings("static-access")
//@Test//from  www  .j ava2s.  c o m
public void shouldUpdateWordWhenSendingRequestToController() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    JSONObject requestJson = new JSONObject();
    requestJson.wrap(json);
    System.out.print(requestJson.toString());

    headers.setContentType(MediaType.APPLICATION_JSON);

    HttpEntity<String> entity = new HttpEntity<String>(json, headers);

    ResponseEntity<String> loginResponse = restTemplate.exchange(localhostUrl, HttpMethod.POST, entity,
            String.class);
    if (loginResponse.getStatusCode() == HttpStatus.OK) {
        JSONObject wordJson = new JSONObject(loginResponse.getBody());
        System.out.print(loginResponse.getStatusCode());
        assertThat(wordJson != null);

    } else if (loginResponse.getStatusCode() == HttpStatus.BAD_REQUEST) {
        System.out.print(loginResponse.getStatusCode());
    }

}

From source file:cn.mypandora.controller.BaseUserController.java

/**
 * /*from   ww w .  j a  v a  2 s.  c  o m*/
 */
@ApiOperation(value = "")
@RequestMapping(value = "/down/{currentPage}", method = RequestMethod.GET)
public ResponseEntity<byte[]> down(@PathVariable int currentPage, HttpServletRequest request)
        throws IOException {
    // ???Excel?
    PageInfo<BaseUser> page = new PageInfo<>();
    page.setPageNum(currentPage);
    page = baseUserService.findPageUserByCondition("pageUsers", null, page);
    // ???
    String rootpath = request.getSession().getServletContext().getRealPath("/");
    String fileName = MyDateUtils.getCurrentDate() + XLSX;
    MyExcelUtil.writeExcel(rootpath + "download" + fileName, "sheet1", "ID,??,,,",
            page.getList(), BaseUser.class, "id,username,sex,birthday,credits");
    // 
    File file = new File(rootpath + "download" + fileName);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", fileName);
    return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}

From source file:com.ge.predix.test.utils.ZoneHelper.java

public ResponseEntity<String> deleteServiceFromZac(final String zoneId) throws JsonProcessingException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add(this.acsZoneHeaderName, zoneId);

    HttpEntity<String> requestEntity = new HttpEntity<>(headers);

    ResponseEntity<String> response = this.zacRestTemplate.exchange(
            this.zacUrl + "/v1/registration/" + this.serviceId + "/" + zoneId, HttpMethod.DELETE, requestEntity,
            String.class);
    return response;
}

From source file:com.hpe.elderberry.Taxii10Template.java

private <T> HttpEntity<T> wrapRequest(T body) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(APPLICATION_XML);
    headers.setAccept(singletonList(APPLICATION_XML));
    headers.add("X-TAXII-Services", VID_TAXII_SERVICES_10);
    headers.add("X-TAXII-Content-Type", VID_TAXII_XML_10);
    String binding = conn.getDiscoveryUrl().getScheme().endsWith("s") ? VID_TAXII_HTTPS_10 : VID_TAXII_HTTP_10;
    headers.add("X-TAXII-Protocol", binding);
    return new HttpEntity<>(body, headers);
}