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:dk.nsi.haiba.lprimporter.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 {//from   w w  w. j  a v  a  2 s .c o  m
        // manual flag is set on the request
        if (manual.equalsIgnoreCase("true")) {
            // flag is true, start the importer in a new thread
            importExecutor.setManualOverride(true);
            Runnable importer = new Runnable() {
                public void run() {
                    importExecutor.doProcess(true);
                }
            };
            importer.run();
        } 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.isLPRDBAlive()) {
            body = "LPR 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 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: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 {//from ww w .j  av a2  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:dk.nsi.haiba.minipasconverter.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 = "" + minipasPreprocessor.isManualOverride();
    } else {//from  w ww .  j  av  a  2  s . c om
        // manual flag is set on the request
        if (manual.equalsIgnoreCase("true")) {
            // flag is true, start the importer in a new thread
            minipasPreprocessor.setManualOverride(true);
            Runnable importer = new Runnable() {
                public void run() {
                    minipasPreprocessor.doManualProcess();
                }
            };
            importer.run();
        } else {
            minipasPreprocessor.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:cn.edu.henu.rjxy.lms.controller.TeaController.java

@RequestMapping("teacher/download")
public ResponseEntity<byte[]> download(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String term = request.getParameter("term");
    String courseName = request.getParameter("courseName");
    String workid = request.getParameter("workid");
    String sn = getCurrentUsername();
    String collage = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherCollege();
    String teacherName = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherName();
    String path = getFileFolder(request) + "uploadhomework/" + term + "/" + collage + "/" + sn + "/"
            + teacherName + "/" + courseName + "/" + workid + "/"; // 
    String fileNamelast = workid + ".zip";//??
    file(getFileFolder(request) + "uploadhomework/" + term + "/" + collage + "/" + sn + "/" + teacherName + "/"
            + "");
    String compress = getFileFolder(request) + "uploadhomework/" + term + "/" + collage + "/" + sn + "/"
            + teacherName + "/" + "" + "/" + fileNamelast;
    //?//from  w  w  w.j  a  v a  2 s . c o m
    ZipCompressor zc = new ZipCompressor(compress);//?   
    zc.compress(path, "", ""); //???
    //?

    File file = new File(compress);
    HttpHeaders headers = new HttpHeaders();
    String fileName = new String(fileNamelast.getBytes("UTF-8"), "iso-8859-1");//???  
    headers.setContentDispositionFormData("attachment", fileName);
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}

From source file:cn.edu.henu.rjxy.lms.controller.TeaController.java

@RequestMapping("teacher/downloadclas")
public ResponseEntity<byte[]> downloadclass(HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String term = request.getParameter("term");
    String courseName = request.getParameter("courseName");
    String workid = request.getParameter("workid");
    String classname = request.getParameter("classname");
    String sn = getCurrentUsername();
    String collage = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherCollege();
    String teacherName = TeacherDao.getTeacherBySn(getCurrentUsername()).getTeacherName();
    String path = getFileFolder(request) + "uploadhomework/" + term + "/" + collage + "/" + sn + "/"
            + teacherName + "/" + courseName + "/" + workid + "/" + classname + "/"; // 
    String fileNamelast = classname + ".zip";//??
    file(getFileFolder(request) + "uploadhomework/" + term + "/" + collage + "/" + sn + "/" + teacherName + "/"
            + "");
    String compress = getFileFolder(request) + "uploadhomework/" + term + "/" + collage + "/" + sn + "/"
            + teacherName + "/" + "" + "/" + fileNamelast;
    //?/*from w  ww .ja  v a 2  s. c  o  m*/
    ZipCompressor zc = new ZipCompressor(compress);//?   
    zc.compress(path, "", ""); //???
    //?

    File file = new File(compress);
    HttpHeaders headers = new HttpHeaders();
    String fileName = new String(fileNamelast.getBytes("UTF-8"), "iso-8859-1");//???  
    headers.setContentDispositionFormData("attachment", fileName);
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
}

From source file:com.playhaven.android.req.PlayHavenRequest.java

public void send(final Context context) {
    final StringHttpMessageConverter stringHttpMessageConverter;

    try {//from   ww w.j  av a  2s . c  om
        /**
        * Charset.availableCharsets() called by StringHttpMessageConverter constructor is not multi-thread safe.
        * Calling it on the main thread to avoid a possible crash.
        * More details here: https://code.google.com/p/android/issues/detail?id=42769
        */
        stringHttpMessageConverter = new StringHttpMessageConverter(Charset.forName(UTF8));
    } catch (Exception e) {
        handleResponse(new PlayHavenException(e.getMessage()));
        return;
    }

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                /**
                 * First, check if we are mocking the URL
                 */
                String mockJsonResponse = getMockJsonResponse();
                if (mockJsonResponse != null) {
                    /**
                     * Mock the response
                     */
                    PlayHaven.v("Mock Response: %s", mockJsonResponse);
                    handleResponse(mockJsonResponse);
                    return;
                }

                /**
                 * Not mocking the response. Do an actual server call.
                 */
                String url = getUrl(context);
                PlayHaven.v("Request(%s) %s: %s", PlayHavenRequest.this.getClass().getSimpleName(), restMethod,
                        url);

                // Add the gzip Accept-Encoding header
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.setAcceptEncoding(ContentCodingType.GZIP);
                requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));

                // Create our REST handler
                RestTemplate rest = new RestTemplate();
                rest.setErrorHandler(new ServerErrorHandler());

                // Capture the JSON for signature verification
                rest.getMessageConverters().add(stringHttpMessageConverter);

                ResponseEntity<String> entity = null;

                switch (restMethod) {
                case POST:
                    SharedPreferences pref = PlayHaven.getPreferences(context);
                    String apiServer = getString(pref, APIServer)
                            + context.getResources().getString(getApiPath(context));
                    url = url.replace(apiServer, "");
                    if (url.startsWith("?") && url.length() > 1)
                        url = url.substring(1);

                    requestHeaders.setContentType(new MediaType("application", "x-www-form-urlencoded"));
                    entity = rest.exchange(apiServer, restMethod, new HttpEntity<>(url, requestHeaders),
                            String.class);
                    break;
                default:
                    entity = rest.exchange(url, restMethod, new HttpEntity<>(requestHeaders), String.class);
                    break;
                }

                String json = entity.getBody();

                List<String> digests = entity.getHeaders().get("X-PH-DIGEST");
                String digest = (digests == null || digests.size() == 0) ? null : digests.get(0);

                validateSignatures(context, digest, json);

                HttpStatus statusCode = entity.getStatusCode();
                PlayHaven.v("Response (%s): %s", statusCode, json);

                serverSuccess(context);
                handleResponse(json);
            } catch (PlayHavenException e) {
                handleResponse(e);
            } catch (IOException e2) {
                handleResponse(new PlayHavenException(e2));
            } catch (Exception e3) {
                handleResponse(new PlayHavenException(e3.getMessage()));
            }
        }
    }).start();
}

From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.java

private CloudResources getKnownRemoteResources(ApplicationArchive archive) throws IOException {
    CloudResources archiveResources = new CloudResources(archive);
    String json = JsonUtil.convertToJson(archiveResources);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(JsonUtil.JSON_MEDIA_TYPE);
    HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
    ResponseEntity<String> responseEntity = getRestTemplate().exchange(getUrl("/v2/resource_match"),
            HttpMethod.PUT, requestEntity, String.class);
    List<CloudResource> cloudResources = JsonUtil.convertJsonToCloudResourceList(responseEntity.getBody());
    return new CloudResources(cloudResources);
}

From source file:org.cloudfoundry.client.lib.rest.CloudControllerClientImpl.java

private HttpEntity<MultiValueMap<String, ?>> generatePartialResourceRequest(
        UploadApplicationPayload application, CloudResources knownRemoteResources) throws IOException {
    MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>(2);
    body.add("application", application);
    ObjectMapper mapper = new ObjectMapper();
    String knownRemoteResourcesPayload = mapper.writeValueAsString(knownRemoteResources);
    body.add("resources", knownRemoteResourcesPayload);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    return new HttpEntity<MultiValueMap<String, ?>>(body, headers);
}

From source file:com.aspose.showcase.qrcodegen.web.api.controller.QRCodeManagementController.java

/**
 * generateQRCode - Main API to generate QR Code
 * // w w  w .  j  a v a  2s .c o  m
 * @throws Exception
 * 
 * 
 */
@RequestMapping(value = "generate", method = RequestMethod.GET, produces = { MediaType.IMAGE_JPEG_VALUE,
        MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_GIF_VALUE, MEDIATYPE_IMAGE_TIFF_VALUE,
        MEDIATYPE_IMAGE_BMP_VALUE })
@ApiOperation(value = "Generate QR Code.")
public ResponseEntity<byte[]> generateQRCode(
        @ApiParam(value = "data", name = "data", required = true) @RequestParam("data") String data,
        @ApiParam(value = "A user-chosen password that can be used with password-based encryption (PBE) Algo PBEWITHMD5AND128BITAES-CBC-OPENSSL)", name = "passKey", required = false) @RequestParam(required = false, value = "passKey") String passKey,
        @ApiParam(value = "ForeColor e.g #000000 (Black - RGB(hex))", name = "foreColor", required = false) @RequestParam(required = false, value = "foreColor") String foreColor,
        @ApiParam(value = "BackgroundColor e.g #FFFFFF (White - RGB(hex))", name = "bgColor", required = false) @RequestParam(required = false, value = "bgColor") String bgColor,
        @ApiParam(value = "L|M|Q|H - Reed-Solomon error correctionCode Level(from low to high) default=Low", name = "ecc", required = false) @RequestParam(required = false, value = "ecc") String ecc,
        @ApiParam(value = "Image Size e.g #150x150", name = "size", required = false) @RequestParam(required = false, value = "size") String size,
        @ApiParam(value = "jpeg|tiff|gif|png|bmp - default=png", name = "format", required = false) @RequestParam(required = false, value = "format") String format,
        @ApiParam(value = "true|false default=false", name = "download", required = false) @RequestParam(required = false, value = "download") boolean download,
        @ApiIgnore @Value("#{request.getHeader('" + ACCEPT_HEADER + "')}") String acceptHeaderValue)
        throws Exception {

    Assert.isTrue(StringUtils.isNotEmpty(data), "Please provide valid data param.");

    LOGGER.debug("Accept Header::" + acceptHeaderValue);

    HttpHeaders responseHeaders = new HttpHeaders();

    if (!(StringUtils.isBlank(passKey))) {
        builder.setCodeText(StringEncryptor.encrypt(data, passKey));
    } else {
        builder.setCodeText(data);
    }

    builder.setImageQuality(ImageQualityMode.Default);
    builder.setSymbologyType(Symbology.QR);
    builder.setCodeLocation(CodeLocation.None);

    builder.setForeColor(getColorValue(foreColor, "#000000"));

    builder.setBackColor(getColorValue(bgColor, "#FFFFFF"));

    builder.setQRErrorLevel(getErrorCorrectCode(ecc, QRErrorLevel.LevelL));

    Dimension imageDimention = geCustomImageSizeDimention(size);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageFormatDTO responseImageTypeDto = getRequestedImageFormat(responseHeaders, acceptHeaderValue, format);

    long startTime = System.currentTimeMillis();

    LOGGER.debug("builder.save Start @  " + startTime);
    byte[] imageInByte;

    if (imageDimention != null) {

        // Set graphics unit
        builder.setGraphicsUnit(GraphicsUnit.Millimeter);

        // Set margins
        builder.getMargins().set(0);

        builder.setForeColor(getColorValue(foreColor, "#000000"));

        builder.setBackColor(getColorValue(bgColor, "#FFFFFF"));

        LOGGER.debug("builder.getGraphicsUnit() ::" + builder.getGraphicsUnit());

        // Get BufferedImage with exact bar code only
        BufferedImage img = builder.getOnlyBarCodeImage();

        LOGGER.debug("img.getWidth() : :" + img.getWidth());
        LOGGER.debug("img.getHeight() :: " + img.getHeight());

        if (imageDimention.getWidth() < img.getWidth()) {
            imageDimention.width = img.getWidth();
        }

        if (imageDimention.getHeight() < img.getHeight()) {
            imageDimention.height = img.getHeight();
        }

        BufferedImage img2 = builder.getCustomSizeBarCodeImage(imageDimention, true);

        MediaType responseType = responseImageTypeDto.getMediaType();
        ImageIO.write(img2, responseType.getSubtype(), baos);
        baos.flush();
        imageInByte = baos.toByteArray();
        baos.close();

    } else {

        builder.setxDimension(1.0f);
        builder.setyDimension(1.0f);

        builder.save(baos, responseImageTypeDto.getBarCodeImageFormat());
        baos.flush();
        imageInByte = baos.toByteArray();
        baos.close();
    }

    long endTime = System.currentTimeMillis();

    LOGGER.debug("builder.save took " + (endTime - startTime) + " milliseconds");

    if (download) {

        MediaType responseType = responseImageTypeDto.getMediaType();
        responseHeaders.setContentType(responseType);
        responseHeaders.add("Content-Disposition",
                "attachment; filename=" + "Aspose_BarCode_QRCodeGen." + responseType.getSubtype());
    }

    return new ResponseEntity<byte[]>(imageInByte, responseHeaders, HttpStatus.CREATED);

}

From source file:org.cloudfoundry.identity.uaa.login.feature.AutologinIT.java

@Test
public void testSimpleAutologinFlow() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

    LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("username", testAccounts.getUserName());
    requestBody.add("password", testAccounts.getPassword());

    //generate an autologin code with our credentials
    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody, headers), Map.class);
    String autologinCode = (String) autologinResponseEntity.getBody().get("code");

    //start the authorization flow - this will issue a login event
    //by using the autologin code
    String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
            .queryParam("redirect_uri", appUrl).queryParam("response_type", "code")
            .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString();

    //rest template that does NOT follow redirects
    RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory());
    headers.remove("Authorization");
    ResponseEntity<Map> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());//w w  w.ja v a  2 s . c  o m
    headers = getAppBasicAuthHttpHeaders();
    headers.add("Cookie", cookies.get(0));

    //if we receive a 200, then we must approve our scopes
    if (HttpStatus.OK == authorizeResponse.getStatusCode()) {
        authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
                .queryParam("user_oauth_approval", "true").build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    }

    //approval is complete, we receive a token code back
    assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode());
    List<String> location = authorizeResponse.getHeaders().get("Location");
    assertEquals(1, location.size());
    String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5);

    //request a token using our code
    String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token")
            .queryParam("response_type", "token").queryParam("grant_type", "authorization_code")
            .queryParam("code", newCode).queryParam("redirect_uri", appUrl).build().toUriString();

    ResponseEntity<Map> tokenResponse = template.exchange(tokenUrl, HttpMethod.POST,
            new HttpEntity<>(new HashMap<String, String>(), headers), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    ResponseEntity<Void> loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertEquals(1, cookies.size());
    headers.clear();
    headers.add("Cookie", cookies.get(0));
    restOperations.exchange(baseUrl + "/profile", HttpMethod.GET, new HttpEntity<>(null, headers), Void.class);

    String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build()
            .toUriString();
    requestBody.clear();
    requestBody.add("clientId", "app");
    requestBody.add("delete", "");
    ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST,
            new HttpEntity<>(requestBody, headers), Void.class);
    assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode());
}