Example usage for org.springframework.http MediaType APPLICATION_OCTET_STREAM_VALUE

List of usage examples for org.springframework.http MediaType APPLICATION_OCTET_STREAM_VALUE

Introduction

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

Prototype

String APPLICATION_OCTET_STREAM_VALUE

To view the source code for org.springframework.http MediaType APPLICATION_OCTET_STREAM_VALUE.

Click Source Link

Document

A String equivalent of MediaType#APPLICATION_OCTET_STREAM .

Usage

From source file:fr.lille1_univ.car_tprest.jetty.web.UpweeController.java

/**
* A call that is used to download the file in the pat corresponding to the filename
*//* ww w  .  j  a  va  2 s .  c  o  m*/
@CrossOrigin
@RequestMapping(method = {
        RequestMethod.GET }, value = "/api/files/download/**", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void download(HttpServletRequest request, @RequestParam(value = "file", required = true) String filename,
        HttpServletResponse response) {
    try {
        response.addHeader("Content-disposition", "attachment;filename=" + filename);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        String decodedfileName = "";
        decodedfileName = java.net.URLDecoder.decode(filename, "UTF-8");
        InputStream stream = this.fileSystemService
                .getFile(getFullFileRequestPath("/api/files/download/**", request, decodedfileName));
        IOUtils.copy(stream, response.getOutputStream());
        response.flushBuffer();
        stream.close();

    } catch (Exception e) {
        l.e("Unable to get file");
        e.printStackTrace();
    }
}

From source file:org.ambraproject.wombat.controller.SearchController.java

/**
 * Performs a csv export of a search.//from www . j av a 2s.  co m
 *
 * @param request HttpServletRequest
 * @param model   model that will contain search results
 * @param site    site the request originates from
 * @param params  all URL parameters
 * @return String indicating template location
 * @throws IOException
 */

@RequestMapping(name = "csvExport", value = "/csvExport", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public FileSystemResource csvExport(HttpServletRequest request, Model model, HttpServletResponse response,
        @SiteParam Site site, @RequestParam MultiValueMap<String, String> params) throws IOException {
    final Integer totalRows = Integer.parseInt(params.getFirst("rows"));
    final String filename = String.format("solrCsvExport-%s-q-%s.csv", Instant.now(), params.getFirst("q"));
    response.setHeader("Content-Disposition", "attachment; filename=" + filename);
    return convertToCsvFile(collateCsvResults(request, model, site, params, totalRows));
}

From source file:org.apache.geode.management.internal.web.controllers.ShellCommandsController.java

private ResponseEntity<InputStreamResource> getFileDownloadResponse(CommandResult commandResult) {
    HttpHeaders respHeaders = new HttpHeaders();
    Path filePath = commandResult.getFileToDownload();
    try {//from  ww  w  . j a  v  a  2  s  . c om
        InputStreamResource isr = new InputStreamResource(new FileInputStream(filePath.toFile()));
        respHeaders.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        return new ResponseEntity<>(isr, respHeaders, HttpStatus.OK);
    } catch (Exception e) {
        throw new RuntimeException("IO Error writing file to output stream", e);
    } finally {
        FileUtils.deleteQuietly(filePath.toFile());
    }
}

From source file:org.apache.geode.management.internal.web.http.support.HttpRequesterTest.java

@Test
public void extractResponseOfFileDownload() throws Exception {
    File responseFile = temporaryFolder.newFile();
    FileUtils.writeStringToFile(responseFile, "some file contents", "UTF-8");
    requester = new HttpRequester();
    response = new MockClientHttpResponse(new FileInputStream(responseFile), HttpStatus.OK);
    response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
    Object result = requester.extractResponse(response);
    Path fileResult = (Path) result;
    assertThat(fileResult).hasSameContentAs(responseFile.toPath());
}

From source file:org.apache.servicecomb.demo.springmvc.client.CodeFirstRestTemplateSpringmvc.java

private void testUpload(RestTemplate template, String cseUrlPrefix) throws IOException {
    String file1Content = "hello world";
    File file1 = File.createTempFile(" ", ".txt");
    FileUtils.writeStringToFile(file1, file1Content);

    String file2Content = " bonjour";
    File someFile = File.createTempFile("upload2", ".txt");
    FileUtils.writeStringToFile(someFile, file2Content);

    String expect = String.format("%s:%s:%s\n" + "%s:%s:%s", file1.getName(), MediaType.TEXT_PLAIN_VALUE,
            file1Content, someFile.getName(), MediaType.TEXT_PLAIN_VALUE, file2Content);

    String result = testRestTemplateUpload(template, cseUrlPrefix, file1, someFile);
    TestMgr.check(expect, result);/*from   w ww. j a  va 2s.c o  m*/

    MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
    map.add("file1", new FileSystemResource(file1));

    result = template.postForObject(cseUrlPrefix + "/upload1", new HttpEntity<>(map), String.class);

    result = uploadPartAndFile.fileUpload(new FilePart(null, file1), someFile);
    TestMgr.check(expect, result);

    expect = String.format("null:%s:%s\n" + "%s:%s:%s", MediaType.APPLICATION_OCTET_STREAM_VALUE, file1Content,
            someFile.getName(), MediaType.TEXT_PLAIN_VALUE, file2Content);
    result = uploadStreamAndResource.fileUpload(
            new ByteArrayInputStream(file1Content.getBytes(StandardCharsets.UTF_8)),
            new PathResource(someFile.getAbsolutePath()));
    TestMgr.check(expect, result);
}

From source file:org.fao.geonet.monitor.service.LogConfig.java

/**
 * Download the log file in a ZIP./*  ww  w.j  av  a 2 s .co m*/
 */
@RequestMapping(value = "/{lang}/log/file", produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE })
@ResponseBody
public void getLog(HttpServletResponse response) throws IOException {
    if (isAppenderLogFileLoaded()) {
        File file = new File(fileAppender.getFile());

        // create ZIP FILE

        String fname = String.valueOf(Calendar.getInstance().getTimeInMillis());

        // set headers for the response
        response.setContentType("application/zip");
        response.setContentLength((int) file.length());
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", "export-log-" + fname + ".zip");
        response.setHeader(headerKey, headerValue);

        int read = 0;
        byte[] bytes = new byte[1024];
        ZipOutputStream zos = null;
        ZipEntry ze;
        InputStream in = null;
        try {
            zos = new ZipOutputStream(response.getOutputStream());
            ze = new ZipEntry(file.getName());
            zos.putNextEntry(ze);
            in = new FileInputStream(file);
            while ((read = in.read(bytes)) != -1) {
                zos.write(bytes, 0, read);
            }
        } finally {
            IOUtils.closeQuietly(in);
            if (zos != null)
                zos.flush();
            IOUtils.closeQuietly(zos);
        }
    } else {
        throw new RuntimeException("No log file found for download. Check logger configuration.");
    }
}

From source file:org.geogig.geoserver.rest.GeoGigWebAPIIntegrationTest.java

private void testGetRemoteObject(ObjectId oid) throws Exception {
    GeoGIG geogig = geogigData.getGeogig();

    final String resource = BASE_URL + "/repo/objects/";
    final String url = resource + oid.toString();

    MockHttpServletResponse servletResponse;
    InputStream responseStream;/*from  ww  w .ja  v a2s.  c  o  m*/

    servletResponse = getAsServletResponse(url);
    assertEquals(200, servletResponse.getStatus());

    String contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
    assertEquals(contentType, servletResponse.getContentType());

    responseStream = getBinaryInputStream(servletResponse);

    ObjectSerializingFactory factory = DataStreamSerializationFactoryV1.INSTANCE;

    RevObject actual = factory.read(oid, responseStream);
    RevObject expected = geogig.command(RevObjectParse.class).setObjectId(oid).call().get();
    assertEquals(expected, actual);
}

From source file:org.openflamingo.web.fs.HdfsBrowserController.java

/**
 * ?? .//from   w  w w  .ja va  2 s .c o  m
 *
 * @return REST Response JAXB Object
 */
@RequestMapping(value = "download", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public ResponseEntity download(HttpServletResponse res, @RequestParam String path,
        @RequestParam(defaultValue = "") String engineId) {
    HttpHeaders headers = new HttpHeaders();
    if (org.apache.commons.lang.StringUtils.isEmpty(path)) {
        headers.set("message", message("S_FS_SERVICE", "INVALID_PARAMETER", null));
        return new ResponseEntity(headers, HttpStatus.BAD_REQUEST);
    }

    String filename = FileUtils.getFilename(path);

    try {
        FileSystemCommand command = new FileSystemCommand();
        command.putObject("path", path);
        command.putObject("filename", filename);

        Engine engine = engineService.getEngine(Long.parseLong(engineId));
        FileSystemService fileSystemService = (FileSystemService) lookupService.getService(RemoteService.HDFS,
                engine);
        byte[] bytes = fileSystemService.load(getContext(engine), command);

        res.setHeader("Content-Length", "" + bytes.length);
        res.setHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM_VALUE);
        res.setHeader("Content-Disposition", MessageFormatter.format("form-data; name={}; filename={}",
                URLEncoder.encode(path, CHARSET), URLEncoder.encode(filename, CHARSET)).getMessage());
        res.setStatus(200);
        FileCopyUtils.copy(bytes, res.getOutputStream());
        res.flushBuffer();
        return new ResponseEntity(HttpStatus.OK);
    } catch (Exception ex) {
        headers.set("message", ex.getMessage());
        if (ex.getCause() != null)
            headers.set("cause", ex.getCause().getMessage());
        return new ResponseEntity(headers, HttpStatus.BAD_REQUEST);
    }
}

From source file:ubic.gemma.web.controller.expression.arrayDesign.ArrayDesignControllerImpl.java

@Override
@RequestMapping(value = "/downloadAnnotationFile.html", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ModelAndView downloadAnnotationFile(HttpServletRequest request, HttpServletResponse response) {

    String arrayDesignIdStr = request.getParameter("id");
    if (arrayDesignIdStr == null) {
        // should be a validation error, on 'submit'.
        throw new EntityNotFoundException("Must provide a platform name or Id");
    }/* ww  w.  j  a  v  a2  s.c o  m*/

    String fileType = request.getParameter("fileType");
    if (fileType == null)
        fileType = ArrayDesignAnnotationService.STANDARD_FILE_SUFFIX;
    else if (fileType.equalsIgnoreCase("noParents"))
        fileType = ArrayDesignAnnotationService.NO_PARENTS_FILE_SUFFIX;
    else if (fileType.equalsIgnoreCase("bioProcess"))
        fileType = ArrayDesignAnnotationService.BIO_PROCESS_FILE_SUFFIX;
    else
        fileType = ArrayDesignAnnotationService.STANDARD_FILE_SUFFIX;

    ArrayDesign arrayDesign = arrayDesignService.load(Long.parseLong(arrayDesignIdStr));
    String fileBaseName = ArrayDesignAnnotationServiceImpl.mungeFileName(arrayDesign.getShortName());
    String fileName = fileBaseName + fileType + ArrayDesignAnnotationService.ANNOTATION_FILE_SUFFIX;

    File f = new File(ArrayDesignAnnotationService.ANNOT_DATA_DIR + fileName);

    if (!f.exists() || !f.canRead()) {
        try {
            // Experimental. Ideally make a background process. But usually these files should be available anyway...
            log.info("Annotation file not found, creating for " + arrayDesign);
            annotationFileService.create(arrayDesign, true);
            f = new File(ArrayDesignAnnotationService.ANNOT_DATA_DIR + fileName);
            if (!f.exists() || !f.canRead()) {
                throw new IOException("Created but could not read?");
            }
        } catch (Exception e) {
            log.error(e, e);
            throw new RuntimeException("The file could not be found and could not be created for "
                    + arrayDesign.getShortName() + " (" + e.getMessage() + "). " + "Please contact "
                    + SUPPORT_EMAIL + " for assistance");
        }
    }

    try (InputStream reader = new BufferedInputStream(new FileInputStream(f))) {

        response.setHeader("Content-disposition", "attachment; filename=" + fileName);
        response.setContentLength((int) f.length());
        // response.setContentType( "application/x-gzip" ); // see Bug4206

        try (OutputStream outputStream = response.getOutputStream()) {

            byte[] buf = new byte[1024];
            int len;
            while ((len = reader.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            reader.close();

        } catch (IOException ioe) {
            log.warn("Failure during streaming of annotation file " + fileName + " Error: " + ioe);
        }
    } catch (FileNotFoundException e) {
        log.warn("Annotation file " + fileName + " can't be found at " + e);
        return null;
    } catch (IOException e) {
        log.warn("Annotation file " + fileName + " could not be read: " + e.getMessage());
        return null;
    }
    return null;
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentDataFetchController.java

/**
 * Regular spring MVC request to fetch a file that already has been generated. It is assumed that the file is in the
 * DATA_DIR.//  ww  w  . j a  v  a 2  s  .c o m
 *
 * @param response response
 * @param request  request
 */
@RequestMapping(value = "/getData.html", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    this.download(response, ExpressionDataFileService.DATA_DIR + request.getParameter("file"), null);
}