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:com.muk.services.api.impl.PayPalPaymentService.java

private String getTokenHeader() {
    final Cache cache = cacheManager.getCache(ServiceConstants.CacheNames.paymentApiTokenCache);
    final String token = "paypal";
    ValueWrapper valueWrapper = cache.get(token);
    String cachedHeader = StringUtils.EMPTY;

    if (valueWrapper == null || valueWrapper.get() == null) {
        try {//w  ww .j  a  v a2 s .co  m
            final String value = securityCfgService.getPayPalClientId() + ":"
                    + keystoreService.getPBEKey(securityCfgService.getPayPalClientId());

            final HttpHeaders headers = new HttpHeaders();
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.add(HttpHeaders.AUTHORIZATION,
                    "Basic " + nonceService.encode(value.getBytes(StandardCharsets.UTF_8)));

            final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
            body.add("grant_type", "client_credentials");

            final HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(
                    body, headers);

            final ResponseEntity<JsonNode> response = restTemplate.postForEntity(
                    securityCfgService.getPayPalUri() + "/oauth2/token", request, JsonNode.class);

            cache.put(token, response.getBody().get("access_token").asText());
            valueWrapper = cache.get(token);
            cachedHeader = (String) valueWrapper.get();
        } catch (final IOException ioEx) {
            LOG.error("Failed read keystore", ioEx);
            cachedHeader = StringUtils.EMPTY;
        } catch (final GeneralSecurityException secEx) {
            LOG.error("Failed to get key", secEx);
            cachedHeader = StringUtils.EMPTY;
        }
    } else {
        cachedHeader = (String) valueWrapper.get();
    }

    return "Bearer " + cachedHeader;
}

From source file:com.muk.services.api.impl.PayPalPaymentService.java

private ResponseEntity<JsonNode> send(String path, JsonNode payload) {
    final HttpHeaders headers = new HttpHeaders();

    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add(HttpHeaders.AUTHORIZATION, getTokenHeader());

    return restTemplate.postForEntity(securityCfgService.getPayPalUri() + path,
            new HttpEntity<JsonNode>(payload, headers), JsonNode.class);
}

From source file:com.muk.services.api.impl.StripePaymentService.java

private ResponseEntity<JsonNode> send(String path, JsonNode payload) {
    final HttpHeaders headers = new HttpHeaders();

    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.add(HttpHeaders.AUTHORIZATION, getTokenHeader());

    final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
    final Iterator<Entry<String, JsonNode>> nodes = payload.fields();

    while (nodes.hasNext()) {
        final Map.Entry<String, JsonNode> entry = nodes.next();

        if (entry.getValue().isObject()) {
            final String key = entry.getKey();
            final Iterator<Entry<String, JsonNode>> metadataNodes = entry.getValue().fields();

            while (metadataNodes.hasNext()) {
                final Map.Entry<String, JsonNode> element = metadataNodes.next();
                body.add(key + "[\"" + element.getKey() + "\"]", element.getValue().asText());
            }/*from   w w w .  j  a v  a  2s. c om*/
        } else {
            body.add(entry.getKey(), entry.getValue().asText());
        }
    }

    return restTemplate.postForEntity(securityCfgService.getStripeUri() + path,
            new HttpEntity<MultiValueMap<String, String>>(body, headers), JsonNode.class);
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

private <T> ResponseEntity<T> exchangeForType(String url, HttpMethod method,
        MultiValueMap<String, String> formData, HttpHeaders headers, Class<T> returnType) {
    if (headers.getContentType() == null) {
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }//from w  ww.j  a  v a 2s .co  m

    final ResponseEntity<T> response = restTemplate.exchange(url, method,
            new HttpEntity<MultiValueMap<String, String>>(formData, headers), returnType);

    return response;
}

From source file:com.muk.services.util.GoogleOAuthService.java

private String requestAccessToken(String jwt) {
    final HttpHeaders headers = new HttpHeaders();
    String token = "error";

    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    final MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>();
    body.add("grant_type", TOKEN_GRANT);
    body.add("assertion", jwt);

    try {/*from   ww  w .jav a  2 s.  c  om*/
        final ResponseEntity<JsonNode> response = restTemplate.postForEntity(JWT_AUD,
                new HttpEntity<MultiValueMap<String, String>>(body, headers), JsonNode.class);

        token = response.getBody().get("access_token").asText();
    } catch (final HttpClientErrorException httpClientEx) {
        LOG.error("Failed to request token.", httpClientEx);
    }

    return token;
}

From source file:com.orange.ngsi.client.NgsiClient.java

/**
 * The default HTTP request headers, depends on the host supporting xml or json
 * @param url/*from   www .  ja  va  2  s  .c  o  m*/
 * @return the HTTP request headers.
 */
public HttpHeaders getRequestHeaders(String url, HttpServletRequest request) {
    HttpHeaders requestHeaders = new HttpHeaders();

    MediaType mediaType = MediaType.APPLICATION_JSON;
    //        if (request != null && request.getAttribute("Content-Type") != null 
    //              && !request.getAttribute("Content-Type").equals("application/json")){
    ////           MediaType mediaType = MediaType.APPLICATION_JSON;
    //           if (url == null || protocolRegistry.supportXml(url)) {
    //               mediaType = MediaType.APPLICATION_XML;
    //           }
    //        }
    if ((url == null || protocolRegistry.supportXml(url)) && !isJsonContentType(request)) {
        mediaType = MediaType.APPLICATION_XML;
    }

    requestHeaders.setContentType(mediaType);
    requestHeaders.setAccept(Collections.singletonList(mediaType));

    if (request != null) {
        requestHeaders.add("Fiware-Service", request.getHeader("Fiware-Service"));
        requestHeaders.add("Fiware-ServicePath", request.getHeader("Fiware-ServicePath"));
    }

    return requestHeaders;
}

From source file:com.oriental.manage.controller.merchant.settleManage.MerchantContranctController.java

@RequestMapping("/downEnclosure")
@RequiresPermissions("org-contaract_down")
public ResponseEntity<byte[]> downEnclosure(String id) {

    try {/*from  w  ww . j av  a2  s .  c om*/
        ContractInfo contractInfo = contractService.queryById(id);
        String path = downloadTempDir.concat("/").concat(contractInfo.getCompanyCode()).concat("/");
        FileUtilsExt.writeFile(path);
        String[] pathList = { contractInfo.getDfsBankFile(), contractInfo.getDfsBizLicenseCert(),
                contractInfo.getDfsContAttach(), contractInfo.getDfsOpenBankCert(),
                contractInfo.getDfsOrganizationCodeCert(), contractInfo.getDfsRatePayerCert(),
                contractInfo.getDfsTaxRegisterCert() };
        for (String dfsPath : pathList) {
            if (StringUtils.isNotBlank(dfsPath)) {
                DfsFileInfo dfsFileInfo = new DfsFileInfo();
                dfsFileInfo.setDfsFullFilename(dfsPath);
                List<DfsFileInfo> fileInfoList = iDfsFileInfoService.searchDfsFileInfo(dfsFileInfo);
                if (null != fileInfoList && fileInfoList.size() > 0) {
                    DfsFileInfo dfsFileInfo1 = fileInfoList.get(0);
                    fastDFSPoolUtil.download(dfsFileInfo1.getDfsGroupname(), dfsFileInfo1.getDfsFullFilename(),
                            path.concat(dfsFileInfo1.getLocalFilename()));
                }
            }
        }
        String localFileName = downloadTempDir.concat("/").concat(contractInfo.getCompanyCode())
                .concat("???.zip");
        FileUtilsExt.zipFile(Arrays.asList(new File(path).listFiles()), localFileName);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", new String(
                contractInfo.getCompanyCode().concat("???.zip").getBytes("UTF-8"), "ISO-8859-1"));
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(localFileName)), headers,
                HttpStatus.CREATED);
    } catch (Exception e) {
        log.error("", e);
    }
    return null;
}

From source file:com.sitewhere.rest.client.SiteWhereClient.java

protected <S, T> S sendBinary(String url, HttpMethod method, T input, Class<S> clazz, Map<String, String> vars)
        throws SiteWhereSystemException {
    try {//from ww  w  . ja va 2 s .  c om
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", getAuthHeader());
        headers.add(ISiteWhereWebConstants.HEADER_TENANT_TOKEN, getTenantAuthToken());
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        HttpEntity<T> entity = new HttpEntity<T>(input, headers);
        ResponseEntity<S> response = getClient().exchange(url, method, entity, clazz, vars);
        return response.getBody();
    } catch (ResourceAccessException e) {
        if (e.getCause() instanceof SiteWhereSystemException) {
            throw (SiteWhereSystemException) e.getCause();
        }
        throw new RuntimeException(e);
    }
}

From source file:com.sitewhere.web.rest.controllers.AssignmentsController.java

/**
 * Get the default symbol for a device assignment.
 * //from   w  w  w  .ja v  a  2 s. c  o m
 * @param token
 * @param servletRequest
 * @param response
 * @return
 * @throws SiteWhereException
 */
@RequestMapping(value = "/{token}/symbol", method = RequestMethod.GET)
@ResponseBody
@ApiOperation(value = "Get default symbol for assignment")
public ResponseEntity<byte[]> getDeviceAssignmentSymbol(
        @ApiParam(value = "Assignment token", required = true) @PathVariable String token,
        HttpServletRequest servletRequest, HttpServletResponse response) throws SiteWhereException {
    Tracer.start(TracerCategory.RestApiCall, "getDeviceAssignmentSymbol", LOGGER);
    try {
        IDeviceAssignment assignment = assureAssignmentWithoutUserValidation(token, servletRequest);
        IEntityUriProvider provider = DefaultEntityUriProvider.getInstance();
        ISymbolGeneratorManager symbols = SiteWhere.getServer()
                .getDeviceCommunication(getTenant(servletRequest, false)).getSymbolGeneratorManager();
        ISymbolGenerator generator = symbols.getDefaultSymbolGenerator();
        if (generator != null) {
            byte[] image = generator.getDeviceAssigmentSymbol(assignment, provider);

            final HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            return new ResponseEntity<byte[]>(image, headers, HttpStatus.CREATED);
        } else {
            return null;
        }
    } finally {
        Tracer.stop(LOGGER);
    }
}

From source file:com.teasoft.teavote.controller.BackupController.java

@RequestMapping(value = "/api/teavote/back-up", method = RequestMethod.GET)
@ResponseBody//from  w ww. jav a  2 s . c o m
public HttpEntity<byte[]> backup(HttpServletRequest request, HttpServletResponse response) throws Exception {

    HttpHeaders httpHeaders = new HttpHeaders();

    String dbName = env.getProperty("teavote.db");
    String dbUserName = env.getProperty("teavote.user");
    String dbPassword = utilities.getPassword();
    DateFormat df = new SimpleDateFormat("dd_MM_yyyy_HH_mm_ss");
    Date dateobj = new Date();
    String fileName = "teavote_backup_" + df.format(dateobj) + ".sql";
    String path = new ConfigLocation().getConfigPath() + File.separator + fileName;
    if (!utilities.backupDB(dbName, dbUserName, dbPassword, path)) {
        return null;
    }
    //Sign file
    sig.signData(path);
    File backupFile = new File(path);
    byte[] bytes;
    try (InputStream backupInputStream = new FileInputStream(backupFile)) {
        httpHeaders.setContentType(MediaType.TEXT_PLAIN);
        httpHeaders.setContentDispositionFormData("Backup", fileName);
        bytes = IOUtils.toByteArray(backupInputStream);
        backupInputStream.close();
    }
    backupFile.delete();
    return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
}