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:org.messic.server.facade.controllers.rest.AlbumController.java

@ApiMethod(path = "/services/albums/{albumCode}?fileName=xxxxx", verb = ApiVerb.PUT, description = "Upload a resource for an album. This resources are stored at the temporal folder, waiting until save Album process. The client must post the binary content of the resource.", produces = {
        MediaType.APPLICATION_JSON_VALUE,
        MediaType.APPLICATION_XML_VALUE }, consumes = { MediaType.APPLICATION_OCTET_STREAM_VALUE })
@ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"),
        @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"),
        @ApiError(code = IOMessicRESTException.VALUE, description = "IO internal server error"), })
@RequestMapping(value = "/{albumCode}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.OK)/*from w w  w .  jav a2  s.c o  m*/
@ResponseBody
@ApiResponseObject
public HttpEntity<HttpStatus> uploadResource(@ApiBodyObject HttpEntity<byte[]> requestEntity,
        HttpServletResponse response, HttpSession session,
        @ApiParam(name = "albumCode", description = "code for the album owner of the resource.. This code is the reference for others resources that could be uploaded, and so on", paramType = ApiParamType.PATH, required = true) @PathVariable String albumCode,
        @ApiParam(name = "fileName", description = "file name of the resource", paramType = ApiParamType.QUERY, required = true) @RequestParam("fileName") String fileName)
        throws IOMessicRESTException, UnknownMessicRESTException, NotAuthorizedMessicRESTException {

    User user = SecurityUtil.getCurrentUser();
    try {
        byte[] payload = requestEntity.getBody();
        albumAPI.uploadResource(user, albumCode, HtmlUtils.htmlUnescape(fileName), payload);
    } catch (IOException ioe) {
        log.error("failed!", ioe);
        throw new IOMessicRESTException(ioe);
    } catch (Exception e) {
        log.error("failed!", e);
        throw new UnknownMessicRESTException(e);
    }

    return new HttpEntity<HttpStatus>(HttpStatus.OK);
}

From source file:org.messic.server.facade.controllers.rest.SongController.java

@ApiMethod(path = "/services/songs/{songSids}/zip", verb = ApiVerb.GET, description = "Get a set of songs zipped", produces = {
        MediaType.APPLICATION_OCTET_STREAM_VALUE })
@ApiErrors(apierrors = { @ApiError(code = UnknownMessicRESTException.VALUE, description = "Unknown error"),
        @ApiError(code = NotAuthorizedMessicRESTException.VALUE, description = "Forbidden access"),
        @ApiError(code = IOMessicRESTException.VALUE, description = "IO error trying to get the songs resources") })
@RequestMapping(value = "/{songSids}/zip", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)/*from   w w w . ja va 2 s . c o  m*/
@ResponseBody
@ApiResponseObject
public void getSongsZip(
        @ApiParam(name = "songSids", description = "song sids SEPARATED BY :", paramType = ApiParamType.PATH, required = true) @PathVariable String songSids,
        HttpServletResponse response)
        throws NotAuthorizedMessicRESTException, IOMessicRESTException, UnknownMessicRESTException {

    User user = SecurityUtil.getCurrentUser();
    try {
        ArrayList<Long> sids = new ArrayList<Long>();
        String[] s = songSids.split(":");
        for (String sid : s) {
            sids.add(Long.valueOf(sid));
        }

        String fileName = URLEncoder.encode("messic-songlist.zip", "UTF-8");
        response.setHeader("Content-disposition", "attachment; filename=\"" + fileName + "\"");

        songAPI.getSongsZip(user, sids, response.getOutputStream());
    } catch (IOException ioe) {
        log.error("failed!", ioe);
        throw new IOMessicRESTException(ioe);
    } catch (Exception e) {
        log.error("failed!", e);
        throw new UnknownMessicRESTException(e);
    }
}

From source file:org.bonitasoft.web.designer.controller.PageResourceTest.java

@Test
public void should_download_page_asset() throws Exception {
    Path expectedFile = widgetRepositoryPath.resolve("pbLabel/pbLabel.js");
    when(pageAssetService.findAssetPath("page-id", "asset.js", AssetType.JAVASCRIPT.getPrefix()))
            .thenReturn(expectedFile);//ww  w  . j  av a  2s.com

    mockMvc.perform(get("/rest/pages/page-id/assets/js/asset.js")).andExpect(status().isOk())
            .andExpect(content().bytes(readAllBytes(expectedFile)))
            .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
            .andExpect(header().string("Content-Length", String.valueOf(expectedFile.toFile().length())))
            .andExpect(header().string("Content-Disposition", "attachment; filename=\"pbLabel.js\""))
            .andExpect(content().encoding("UTF-8"));
}

From source file:org.bonitasoft.web.designer.controller.WidgetResourceTest.java

@Test
public void should_download_widget_asset() throws Exception {
    Path expectedFile = widgetRepositoryPath.resolve("pbLabel/pbLabel.js");
    when(widgetAssetService.findAssetPath("widget-id", "asset.js", AssetType.JAVASCRIPT.getPrefix()))
            .thenReturn(expectedFile);//  ww w . ja va  2  s .c  o m

    mockMvc.perform(get("/rest/widgets/widget-id/assets/js/asset.js")).andExpect(status().isOk())
            .andExpect(content().bytes(readAllBytes(expectedFile)))
            .andExpect(content().contentType(MediaType.APPLICATION_OCTET_STREAM_VALUE))
            .andExpect(header().string("Content-Length", String.valueOf(expectedFile.toFile().length())))
            .andExpect(header().string("Content-Disposition", "attachment; filename=\"pbLabel.js\""))
            .andExpect(content().encoding("UTF-8"));
}

From source file:com.netflix.genie.web.controllers.JobRestControllerIntegrationTest.java

private String submitJob(final int documentationId, final JobRequest jobRequest,
        @Nullable final List<MockMultipartFile> attachments) throws Exception {
    if (attachments != null) {
        final RestDocumentationFilter createResultFilter = RestAssuredRestDocumentation.document(
                "{class-name}/" + documentationId + "/submitJobWithAttachments/",
                HeaderDocumentation.requestHeaders(HeaderDocumentation.headerWithName(HttpHeaders.CONTENT_TYPE)
                        .description(MediaType.MULTIPART_FORM_DATA_VALUE)), // Request headers
                RequestDocumentation.requestParts(
                        RequestDocumentation.partWithName("request").description(
                                "The job request JSON. Content type must be application/json for part"),
                        RequestDocumentation.partWithName("attachment").description(
                                "An attachment file. There can be multiple. Type should be octet-stream")), // Request parts
                Snippets.LOCATION_HEADER // Response Headers
        );/*from  w  ww . ja  v a  2s .  c  om*/

        final RequestSpecification jobRequestSpecification = RestAssured.given(this.getRequestSpecification())
                .filter(createResultFilter).contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
                .multiPart("request", GenieObjectMapper.getMapper().writeValueAsString(jobRequest),
                        MediaType.APPLICATION_JSON_VALUE);

        for (final MockMultipartFile attachment : attachments) {
            jobRequestSpecification.multiPart("attachment", attachment.getOriginalFilename(),
                    attachment.getBytes(), MediaType.APPLICATION_OCTET_STREAM_VALUE);
        }

        return this.getIdFromLocation(jobRequestSpecification.when().port(this.port).post(JOBS_API).then()
                .statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
                .header(HttpHeaders.LOCATION, Matchers.notNullValue()).extract().header(HttpHeaders.LOCATION));
    } else {
        // Use regular POST
        final RestDocumentationFilter createResultFilter = RestAssuredRestDocumentation.document(
                "{class-name}/" + documentationId + "/submitJobWithoutAttachments/",
                Snippets.CONTENT_TYPE_HEADER, // Request headers
                Snippets.getJobRequestRequestPayload(), // Request Fields
                Snippets.LOCATION_HEADER // Response Headers
        );

        return this.getIdFromLocation(RestAssured.given(this.getRequestSpecification())
                .filter(createResultFilter).contentType(MediaType.APPLICATION_JSON_VALUE)
                .body(GenieObjectMapper.getMapper().writeValueAsBytes(jobRequest)).when().port(this.port)
                .post(JOBS_API).then().statusCode(Matchers.is(HttpStatus.ACCEPTED.value()))
                .header(HttpHeaders.LOCATION, Matchers.notNullValue()).extract().header(HttpHeaders.LOCATION));
    }
}

From source file:com.netflix.genie.web.controllers.JobRestControllerIntegrationTest.java

/**
 * Test to make sure we can submit a job with attachments.
 *
 * @throws Exception on any error//  ww  w.j  a va 2  s .  c om
 */
@Test
public void canSubmitJobWithAttachments() throws Exception {
    final List<String> commandArgs = Lists.newArrayList("-c", "'echo hello world'");

    final List<ClusterCriteria> clusterCriteriaList = Lists
            .newArrayList(new ClusterCriteria(Sets.newHashSet(LOCALHOST_CLUSTER_TAG)));

    final String setUpFile = this.resourceLoader.getResource(BASE_DIR + "job" + FILE_DELIMITER + "jobsetupfile")
            .getFile().getAbsolutePath();

    final File attachment1File = this.resourceLoader.getResource(BASE_DIR + "job/query.sql").getFile();

    final MockMultipartFile attachment1;
    try (InputStream is = new FileInputStream(attachment1File)) {
        attachment1 = new MockMultipartFile("attachment", attachment1File.getName(),
                MediaType.APPLICATION_OCTET_STREAM_VALUE, is);
    }

    final File attachment2File = this.resourceLoader.getResource(BASE_DIR + "job/query2.sql").getFile();

    final MockMultipartFile attachment2;
    try (InputStream is = new FileInputStream(attachment2File)) {
        attachment2 = new MockMultipartFile("attachment", attachment2File.getName(),
                MediaType.APPLICATION_OCTET_STREAM_VALUE, is);
    }
    final Set<String> commandCriteria = Sets.newHashSet(BASH_COMMAND_TAG);
    final JobRequest jobRequest = new JobRequest.Builder(JOB_NAME, JOB_USER, JOB_VERSION, clusterCriteriaList,
            commandCriteria).withCommandArgs(commandArgs).withDisableLogArchival(true).withSetupFile(setUpFile)
                    .withDescription(JOB_DESCRIPTION).build();

    this.waitForDone(this.submitJob(4, jobRequest, Lists.newArrayList(attachment1, attachment2)));
}

From source file:com.netflix.genie.web.controllers.JobRestControllerIntegrationTests.java

/**
 * Test to make sure we can submit a job with attachments.
 *
 * @throws Exception on any error/*w w w .j  a v a 2  s  .c  om*/
 */
@Test
public void canSubmitJobWithAttachments() throws Exception {
    final String commandArgs = "-c 'echo hello world'";

    final String clusterTag = "localhost";
    final List<ClusterCriteria> clusterCriteriaList = Lists
            .newArrayList(new ClusterCriteria(Sets.newHashSet(clusterTag)));

    final String setUpFile = this.resourceLoader.getResource(BASE_DIR + "job" + FILE_DELIMITER + "jobsetupfile")
            .getFile().getAbsolutePath();

    final File attachment1File = this.resourceLoader.getResource(BASE_DIR + "job/query.sql").getFile();

    final MockMultipartFile attachment1;
    try (final InputStream is = new FileInputStream(attachment1File)) {
        attachment1 = new MockMultipartFile("attachment", attachment1File.getName(),
                MediaType.APPLICATION_OCTET_STREAM_VALUE, is);
    }

    final File attachment2File = this.resourceLoader.getResource(BASE_DIR + "job/query2.sql").getFile();

    final MockMultipartFile attachment2;
    try (final InputStream is = new FileInputStream(attachment2File)) {
        attachment2 = new MockMultipartFile("attachment", attachment2File.getName(),
                MediaType.APPLICATION_OCTET_STREAM_VALUE, is);
    }
    final Set<String> commandCriteria = Sets.newHashSet("bash");
    final JobRequest jobRequest = new JobRequest.Builder(JOB_NAME, JOB_USER, JOB_VERSION, commandArgs,
            clusterCriteriaList, commandCriteria).withDisableLogArchival(true).withSetupFile(setUpFile)
                    .withDescription(JOB_DESCRIPTION).build();

    this.waitForDone(this.submitJob(4, jobRequest, Lists.newArrayList(attachment1, attachment2)));
}

From source file:com.phoenixnap.oss.ramlapisync.naming.NamingHelper.java

/**
 * Converts an http contentType into a qualifier that can be used within a Java method
 * /*from   w  ww  . ja v  a 2 s  .com*/
 * @param contentType The content type to convert application/json
 * @return qualifier, example V1Html
 */
public static String convertContentTypeToQualifier(String contentType) {
    //lets start off simple since qualifers are better if they are simple :)
    //if we have simple standard types lets add some heuristics
    if (contentType.equals(MediaType.APPLICATION_JSON_VALUE)) {
        return "AsJson";
    }

    if (contentType.equals(MediaType.APPLICATION_OCTET_STREAM_VALUE)) {
        return "AsBinary";
    }

    if (contentType.equals(MediaType.TEXT_PLAIN_VALUE) || contentType.equals(MediaType.TEXT_HTML_VALUE)) {
        return "AsText";
    }

    //we have a non standard type. lets see if we have a version
    Matcher versionMatcher = CONTENT_TYPE_VERSION.matcher(contentType);
    if (versionMatcher.find()) {
        String version = versionMatcher.group(1);

        if (version != null) {
            return StringUtils.capitalize(version).replace(".", "_");
        }
    }

    //if we got here we have some sort of funky content type. deal with it
    int seperatorIndex = contentType.indexOf("/");
    if (seperatorIndex != -1 && seperatorIndex < contentType.length()) {
        String candidate = contentType.substring(seperatorIndex + 1).toLowerCase();
        String out = "";
        if (candidate.contains("json")) {
            candidate = candidate.replace("json", "");
            out += "AsJson";
        }

        candidate = StringUtils.deleteAny(candidate, " ,.+=-'\"\\|~`#$%^&\n\t");
        if (StringUtils.hasText(candidate)) {
            out = StringUtils.capitalize(candidate) + out;
        }
        return "_" + out;
    }
    return "";
}

From source file:eionet.webq.converter.MultipartFileToUserFileConverterTest.java

@Test
public void setsContentTypeFromMultipartFile() throws Exception {
    String expectedContentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
    UserFile result = fileConverter/*from   w ww  .  j a  v a2  s  .c om*/
            .convert(createMultipartFile(expectedContentType, "attachment-content".getBytes())).iterator()
            .next();
    assertThat(result.getContentType(), equalTo(expectedContentType));
}