org.springframework.http.MediaType.valueOf()

Here are the examples of the java api org.springframework.http.MediaType.valueOf() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

122 Examples 7

19 View Source File : SampleWebStaticApplicationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Test
public void testCss() {
    ResponseEnreplacedy<String> enreplacedy = this.restTemplate.getForEnreplacedy("/webjars/bootstrap/3.0.3/css/bootstrap.min.css", String.clreplaced);
    replacedertThat(enreplacedy.getStatusCode()).isEqualTo(HttpStatus.OK);
    replacedertThat(enreplacedy.getBody()).contains("body");
    replacedertThat(enreplacedy.getHeaders().getContentType()).isEqualTo(MediaType.valueOf("text/css"));
}

19 View Source File : ContentNegotiatingViewResolverTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void resolveViewNameWithRequestParameter() throws Exception {
    request.addParameter("format", "xls");
    Map<String, MediaType> mapping = Collections.singletonMap("xls", MediaType.valueOf("application/vnd.ms-excel"));
    ParameterContentNegotiationStrategy paramStrategy = new ParameterContentNegotiationStrategy(mapping);
    viewResolver.setContentNegotiationManager(new ContentNegotiationManager(paramStrategy));
    ViewResolver viewResolverMock = mock(ViewResolver.clreplaced);
    viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
    viewResolver.afterPropertiesSet();
    View viewMock = mock(View.clreplaced, "application_xls");
    String viewName = "view";
    Locale locale = Locale.ENGLISH;
    given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null);
    given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock);
    given(viewMock.getContentType()).willReturn("application/vnd.ms-excel");
    View result = viewResolver.resolveViewName(viewName, locale);
    replacedertSame("Invalid view", viewMock, result);
}

19 View Source File : ContentNegotiatingViewResolverTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void resolveViewNameWithAcceptHeader() throws Exception {
    request.addHeader("Accept", "application/vnd.ms-excel");
    Map<String, MediaType> mapping = Collections.singletonMap("xls", MediaType.valueOf("application/vnd.ms-excel"));
    MappingMediaTypeFileExtensionResolver extensionsResolver = new MappingMediaTypeFileExtensionResolver(mapping);
    ContentNegotiationManager manager = new ContentNegotiationManager(new HeaderContentNegotiationStrategy());
    manager.addFileExtensionResolvers(extensionsResolver);
    viewResolver.setContentNegotiationManager(manager);
    ViewResolver viewResolverMock = mock(ViewResolver.clreplaced);
    viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
    View viewMock = mock(View.clreplaced, "application_xls");
    String viewName = "view";
    Locale locale = Locale.ENGLISH;
    given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null);
    given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock);
    given(viewMock.getContentType()).willReturn("application/vnd.ms-excel");
    View result = viewResolver.resolveViewName(viewName, locale);
    replacedertSame("Invalid view", viewMock, result);
}

19 View Source File : ContentAssertionTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void testContentType() throws Exception {
    this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)).andExpect(content().contentType(MediaType.valueOf("text/plain;charset=ISO-8859-1"))).andExpect(content().contentType("text/plain;charset=ISO-8859-1")).andExpect(content().contentTypeCompatibleWith("text/plain")).andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN));
    this.mockMvc.perform(get("/handleUtf8")).andExpect(content().contentType(MediaType.valueOf("text/plain;charset=UTF-8"))).andExpect(content().contentType("text/plain;charset=UTF-8")).andExpect(content().contentTypeCompatibleWith("text/plain")).andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN));
}

19 View Source File : WebStaticApplicationTests.java
License : GNU Affero General Public License v3.0
Project Creator : romeoblog

private void resources(String path, String type) {
    ResponseEnreplacedy<String> enreplacedy = this.restTemplate.getForEnreplacedy(path, String.clreplaced);
    replacedertThat(enreplacedy.getHeaders().getContentType()).isEqualTo(MediaType.valueOf(type));
}

19 View Source File : WebStaticApplicationTests.java
License : GNU Affero General Public License v3.0
Project Creator : romeoblog

// @Test
public void testCss() throws Exception {
    ResponseEnreplacedy<String> enreplacedy = this.restTemplate.getForEnreplacedy("/vendor/bootstrap/css/bootstrap.css", String.clreplaced);
    replacedertThat(enreplacedy.getStatusCode()).isEqualTo(HttpStatus.OK);
    replacedertThat(enreplacedy.getBody()).contains("body");
    replacedertThat(enreplacedy.getHeaders().getContentType()).isEqualTo(MediaType.valueOf("text/css;charset=UTF-8"));
}

19 View Source File : FileBoundary.java
License : MIT License
Project Creator : rieckpil

@GetMapping
public ResponseEnreplacedy<byte[]> getRandomFile() {
    long amountOfFiles = fileEnreplacedyRepository.count();
    Long randomPrimaryKey;
    if (amountOfFiles == 0) {
        return ResponseEnreplacedy.ok(new byte[0]);
    } else if (amountOfFiles == 1) {
        randomPrimaryKey = 1L;
    } else {
        randomPrimaryKey = ThreadLocalRandom.current().nextLong(1, amountOfFiles + 1);
    }
    FileEnreplacedy fileEnreplacedy = fileEnreplacedyRepository.findById(randomPrimaryKey).get();
    HttpHeaders header = new HttpHeaders();
    header.setContentType(MediaType.valueOf(fileEnreplacedy.getContentType()));
    header.setContentLength(fileEnreplacedy.getData().length);
    header.set("Content-Disposition", "attachment; filename=" + fileEnreplacedy.getFileName());
    return new ResponseEnreplacedy<>(fileEnreplacedy.getData(), header, HttpStatus.OK);
}

19 View Source File : HttpAccessLoggingServletStreamFilter.java
License : Apache License 2.0
Project Creator : penggle

protected MediaType getContentType(String contentType) {
    try {
        if (!StringUtils.isEmpty(contentType)) {
            return MediaType.valueOf(contentType);
        }
    } catch (Exception e) {
    }
    return null;
}

19 View Source File : ServletWebUtils.java
License : Apache License 2.0
Project Creator : penggle

/**
 * 根据字符串类型的contentType来获取content-type的枚举对象org.springframework.http.MediaType
 * @param contentType
 * @return
 */
public static MediaType getContentType(String contentType) {
    try {
        if (!StringUtils.isEmpty(contentType)) {
            return MediaType.valueOf(contentType);
        }
    } catch (Exception e) {
    }
    return null;
}

19 View Source File : WebStorageClient.java
License : Apache License 2.0
Project Creator : OctoPerf

@Override
public Flux<StorageWatcherEvent> watch() {
    return webClient.get().uri(uriBuilder -> uriBuilder.path("/files/watch").build()).accept(MediaType.valueOf(MediaType.TEXT_EVENT_STREAM_VALUE)).retrieve().bodyToFlux(StorageWatcherEvent.clreplaced).doOnError(t -> log.error("Failed to watch storage", t)).doOnSubscribe(subscription -> log.info("Watching storage"));
}

19 View Source File : BaseModel.java
License : Apache License 2.0
Project Creator : NotFound403

@SneakyThrows
public JsonNode request(String mchId, HttpMethod method, String url) {
    String xml = this.xml();
    RequestEnreplacedy<String> body = RequestEnreplacedy.method(method, UriComponentsBuilder.fromHttpUrl(url).build().toUri()).contentType(MediaType.valueOf("application/x-www-form-urlencoded;charset=UTF-8")).body(xml);
    ResponseEnreplacedy<String> responseEnreplacedy = this.getRestTemplateClientAuthentication(mchId).exchange(url, method, body, String.clreplaced);
    if (!responseEnreplacedy.getStatusCode().is2xxSuccessful()) {
        throw new PayException("wechat pay v2 error ");
    }
    String result = responseEnreplacedy.getBody();
    return XML_MAPPER.readTree(result);
}

19 View Source File : ContentNegotiationManagerFactoryBean.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Add a mapping from a key, extracted from a path extension or a query
 * parameter, to a MediaType. This is required in order for the parameter
 * strategy to work. Any extensions explicitly registered here are also
 * whitelisted for the purpose of Reflected File Download attack detection
 * (see Spring Framework reference doreplacedentation for more details on RFD
 * attack protection).
 * <p>The path extension strategy will also try to use
 * {@link ServletContext#getMimeType} and JAF (if present) to resolve path
 * extensions. To change this behavior see the {@link #useJaf} property.
 * @param mediaTypes media type mappings
 * @see #addMediaType(String, MediaType)
 * @see #addMediaTypes(Map)
 */
public void setMediaTypes(Properties mediaTypes) {
    if (!CollectionUtils.isEmpty(mediaTypes)) {
        for (Entry<Object, Object> entry : mediaTypes.entrySet()) {
            String extension = ((String) entry.getKey()).toLowerCase(Locale.ENGLISH);
            MediaType mediaType = MediaType.valueOf((String) entry.getValue());
            this.mediaTypes.put(extension, mediaType);
        }
    }
}

19 View Source File : ContentAssertionTests.java
License : Apache License 2.0
Project Creator : langtianya

@Test
public void testContentType() throws Exception {
    this.mockMvc.perform(get("/handle").accept(MediaType.TEXT_PLAIN)).andExpect(content().contentType(MediaType.TEXT_PLAIN)).andExpect(content().contentType("text/plain"));
    this.mockMvc.perform(get("/handleUtf8")).andExpect(content().contentType(MediaType.valueOf("text/plain;charset=UTF-8"))).andExpect(content().contentType("text/plain;charset=UTF-8")).andExpect(content().contentTypeCompatibleWith("text/plain")).andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_PLAIN));
}

19 View Source File : VideoController.java
License : GNU General Public License v2.0
Project Creator : Jigsawk

@GetMapping("/download/{fileId}")
public ResponseEnreplacedy<?> download(@PathVariable String fileId) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf(String.valueOf(MediaType.APPLICATION_OCTET_STREAM)));
    byte[] bytes = parseVideoService.downloadFile(Long.valueOf(fileId), currentUid());
    return new ResponseEnreplacedy<>(bytes, headers, HttpStatus.OK);
}

19 View Source File : FilesizeAndTypeFileValidator.java
License : MIT License
Project Creator : InnovateUKGitHub

private ServiceResult<MediaType> validContentTypeHeader(String contentTypeHeader, MediaTypeContext validMediaTypesContext) {
    List<MediaType> validMediaTypes = validMediaTypesGenerator.apply(validMediaTypesContext);
    if (isBlank(contentTypeHeader)) {
        return serviceFailure(unsupportedMediaTypeError(validMediaTypeErrorHelper.findErrorKey(validMediaTypes), validMediaTypes));
    }
    MediaType mediaType = MediaType.valueOf(contentTypeHeader);
    if (!validMediaTypes.contains(mediaType)) {
        return serviceFailure(unsupportedMediaTypeError(validMediaTypeErrorHelper.findErrorKey(validMediaTypes), validMediaTypes));
    }
    return serviceSuccess(mediaType);
}

19 View Source File : ImageController.java
License : Apache License 2.0
Project Creator : feature-creeps

@PostMapping("rotate")
public ResponseEnreplacedy rotateImage(@RequestParam("image") MultipartFile file, @RequestParam(value = "degrees") String degrees) throws IOException {
    lcu.mdcPut(file.getContentType(), degrees);
    this.eventService.addFieldToActiveEvent("action", "rotate");
    this.eventService.addFieldToActiveEvent("transformation.rotate.degrees", degrees);
    this.eventService.addFieldToActiveEvent("content.type", file.getContentType());
    this.eventService.addFieldToActiveEvent("content.size", file.getBytes().length);
    if (file.getContentType() != null && !file.getContentType().startsWith("image/")) {
        this.eventService.addFieldToActiveEvent("app.error", 1);
        this.eventService.addFieldToActiveEvent("action.failure_reason", "wrong_content_type");
        LOGGER.warn("Wrong content type uploaded: {}", file.getContentType());
        return new ResponseEnreplacedy<>("Wrong content type uploaded: " + file.getContentType(), HttpStatus.BAD_REQUEST);
    }
    // ISSUE: we fail on floating point values
    int intDegrees = Integer.valueOf(degrees);
    LOGGER.info("Receiving {} image to rotate by {} degrees", file.getContentType(), intDegrees);
    byte[] rotatedImage = imageService.rotate(file, intDegrees);
    if (rotatedImage == null) {
        this.eventService.addFieldToActiveEvent("app.error", 1);
        this.eventService.addFieldToActiveEvent("action.failure_reason", "internal_server_error");
        return new ResponseEnreplacedy<>("Failed to rotate image", HttpStatus.INTERNAL_SERVER_ERROR);
    }
    this.eventService.addFieldToActiveEvent("content.transformed.size", rotatedImage.length);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf(file.getContentType()));
    LOGGER.info("Successfully rotated image");
    this.eventService.addFieldToActiveEvent("app.error", 0);
    return new ResponseEnreplacedy<>(rotatedImage, headers, HttpStatus.OK);
}

19 View Source File : ImageController.java
License : Apache License 2.0
Project Creator : feature-creeps

@PostMapping("resize")
public ResponseEnreplacedy resizeImage(@RequestParam("image") MultipartFile file, @RequestParam(value = "factor") String factor) throws IOException {
    lcu.mdcPut(file.getContentType(), factor);
    this.eventService.addFieldToActiveEvent("action", "resize");
    this.eventService.addFieldToActiveEvent("content.type", file.getContentType());
    this.eventService.addFieldToActiveEvent("content.size", file.getBytes().length);
    this.eventService.addFieldToActiveEvent("transformation.resize.factor", factor);
    if (file.getContentType() != null && !file.getContentType().startsWith("image/")) {
        LOGGER.warn("Wrong content type uploaded: {}", file.getContentType());
        this.eventService.addFieldToActiveEvent("app.error", 1);
        this.eventService.addFieldToActiveEvent("action.failure_reason", "wrong_content_type");
        return new ResponseEnreplacedy<>("Wrong content type uploaded: " + file.getContentType(), HttpStatus.BAD_REQUEST);
    }
    Double intFactor = Double.valueOf(factor);
    LOGGER.info("Receiving {} image to resize by {} factor", file.getContentType(), intFactor);
    byte[] resizedImage = imageService.resize(file, intFactor);
    this.eventService.addFieldToActiveEvent("content.transformed.size", resizedImage.length);
    if (resizedImage == null) {
        this.eventService.addFieldToActiveEvent("app.error", 1);
        this.eventService.addFieldToActiveEvent("action.failure_reason", "internal_server_error");
        return new ResponseEnreplacedy<>("Failed to resize image", HttpStatus.INTERNAL_SERVER_ERROR);
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf(file.getContentType()));
    LOGGER.info("Successfully resized image");
    this.eventService.addFieldToActiveEvent("app.error", 0);
    return new ResponseEnreplacedy<>(resizedImage, headers, HttpStatus.OK);
}

19 View Source File : ImageController.java
License : Apache License 2.0
Project Creator : feature-creeps

@PostMapping("flip")
public ResponseEnreplacedy flipImage(@RequestParam("image") MultipartFile file, @RequestParam(value = "vertical") Boolean vertical, @RequestParam(value = "horizontal") Boolean horizontal) throws IOException {
    this.eventService.addFieldToActiveEvent("action", "flip");
    this.eventService.addFieldToActiveEvent("content.type", file.getContentType());
    this.eventService.addFieldToActiveEvent("content.length", file.getBytes().length);
    this.eventService.addFieldToActiveEvent("transformation.flip_vertical", vertical);
    this.eventService.addFieldToActiveEvent("transformation.flip_horizontal", horizontal);
    lcu.mdcPut(file.getContentType(), vertical, horizontal);
    if (file.getContentType() != null && !file.getContentType().startsWith("image/")) {
        LOGGER.warn("Wrong content type uploaded: {}", file.getContentType());
        this.eventService.addFieldToActiveEvent("app.error", 1);
        this.eventService.addFieldToActiveEvent("action.failure_reason", "wrong_content_type");
        return new ResponseEnreplacedy<>("Wrong content type uploaded: " + file.getContentType(), HttpStatus.BAD_REQUEST);
    }
    LOGGER.info("Receiving {} image to flip.", file.getContentType());
    byte[] flippedImage = imageService.flip(file, vertical, horizontal);
    if (flippedImage == null) {
        this.eventService.addFieldToActiveEvent("app.error", 1);
        this.eventService.addFieldToActiveEvent("action.failure_reason", "internal_server_error");
        return new ResponseEnreplacedy<>("Failed to flip image", HttpStatus.INTERNAL_SERVER_ERROR);
    } else {
        this.eventService.addFieldToActiveEvent("content.transformed.length", flippedImage.length);
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf(file.getContentType()));
    LOGGER.info("Successfully flipped image");
    this.eventService.addFieldToActiveEvent("app.error", 0);
    return new ResponseEnreplacedy<>(flippedImage, headers, HttpStatus.OK);
}

19 View Source File : HttpHeaderBuilder.java
License : Apache License 2.0
Project Creator : covid-be-app

public HttpHeaderBuilder contentTypeProtoBuf() {
    headers.setContentType(MediaType.valueOf("application/x-protobuf"));
    return this;
}

19 View Source File : MediaTypeCalculator.java
License : MIT License
Project Creator : bottomless-archive-project

public MediaType calculateMediaType(final DoreplacedentType doreplacedentType) {
    return MediaType.valueOf(doreplacedentType.getMimeType());
}

18 View Source File : RequestResponseBodyMethodProcessorMockTests.java
License : MIT License
Project Creator : Vip-Augus

// SPR-9841
@Test
public void handleReturnValueMediaTypeSuffix() throws Exception {
    String body = "Foo";
    MediaType accepted = MediaType.APPLICATION_XHTML_XML;
    List<MediaType> supported = Collections.singletonList(MediaType.valueOf("application/*+xml"));
    servletRequest.addHeader("Accept", accepted);
    given(stringMessageConverter.canWrite(String.clreplaced, null)).willReturn(true);
    given(stringMessageConverter.getSupportedMediaTypes()).willReturn(supported);
    given(stringMessageConverter.canWrite(String.clreplaced, accepted)).willReturn(true);
    processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest);
    replacedertTrue(mavContainer.isRequestHandled());
    verify(stringMessageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.clreplaced));
}

18 View Source File : ProducerControllerTests.java
License : Apache License 2.0
Project Creator : spring-cloud-samples

@Test
public void should_reject_a_beer_when_person_is_too_young() throws Exception {
    PersonToCheck personToCheck = new PersonToCheck(10);
    // remove::start[]
    this.webTestClient.post().uri("/check").contentType(MediaType.APPLICATION_JSON).syncBody(this.json.write(personToCheck).getJson()).exchange().expectBody().jsonPath("$.status").value(Matchers.equalTo("NOT_OK")).consumeWith(WireMockWebTestClient.verify().jsonPath("$[?(@.age < 20)]").contentType(MediaType.valueOf("application/json")).stub("shouldRejectABeerIfTooYoung")).consumeWith(WebTestClientRestDoreplacedentation.doreplacedent("shouldRejectABeerIfTooYoung", SpringCloudContractRestDocs.dslContract()));
// remove::end[]
}

18 View Source File : ProducerControllerTests.java
License : Apache License 2.0
Project Creator : spring-cloud-samples

@Test
public void should_grant_a_beer_when_person_is_old_enough() throws Exception {
    PersonToCheck personToCheck = new PersonToCheck(34);
    // remove::start[]
    this.webTestClient.post().uri("/check").contentType(MediaType.APPLICATION_JSON).syncBody(this.json.write(personToCheck).getJson()).exchange().expectBody().jsonPath("$.status").value(Matchers.equalTo("OK")).consumeWith(WireMockWebTestClient.verify().jsonPath("$[?(@.age >= 20)]").contentType(MediaType.valueOf("application/json")).stub("shouldGrantABeerIfOldEnough")).consumeWith(WebTestClientRestDoreplacedentation.doreplacedent("shouldGrantABeerIfOldEnough", SpringCloudContractRestDocs.dslContract()));
// remove::end[]
}

18 View Source File : ProducerControllerTests.java
License : Apache License 2.0
Project Creator : spring-cloud-samples

@Test
public void should_grant_a_beer_when_person_is_old_enough() throws Exception {
    PersonToCheck personToCheck = new PersonToCheck(34);
    // remove::start[]
    this.mockMvc.perform(MockMvcRequestBuilders.post("/check").contentType(MediaType.APPLICATION_JSON).content(this.json.write(personToCheck).getJson())).andExpect(jsonPath("$.status").value("OK")).andDo(WireMockRestDocs.verify().jsonPath("$[?(@.age >= 20)]").contentType(MediaType.valueOf("application/json")).stub("shouldGrantABeerIfOldEnough")).andDo(MockMvcRestDoreplacedentation.doreplacedent("shouldGrantABeerIfOldEnough", SpringCloudContractRestDocs.dslContract()));
// remove::end[]
}

18 View Source File : ProducerControllerTests.java
License : Apache License 2.0
Project Creator : spring-cloud-samples

@Test
public void should_reject_a_beer_when_person_is_too_young() throws Exception {
    PersonToCheck personToCheck = new PersonToCheck(10);
    // remove::start[]
    this.mockMvc.perform(MockMvcRequestBuilders.post("/check").contentType(MediaType.APPLICATION_JSON).content(this.json.write(personToCheck).getJson())).andExpect(jsonPath("$.status").value("NOT_OK")).andDo(WireMockRestDocs.verify().jsonPath("$[?(@.age < 20)]").contentType(MediaType.valueOf("application/json")).stub("shouldRejectABeerIfTooYoung")).andDo(MockMvcRestDoreplacedentation.doreplacedent("shouldRejectABeerIfTooYoung", SpringCloudContractRestDocs.dslContract()));
// remove::end[]
}

18 View Source File : ContentNegotiatingViewResolverTests.java
License : Apache License 2.0
Project Creator : SourceHot

@Test
public void resolveViewNameWithRequestParameter() throws Exception {
    request.addParameter("format", "xls");
    Map<String, MediaType> mapping = Collections.singletonMap("xls", MediaType.valueOf("application/vnd.ms-excel"));
    ParameterContentNegotiationStrategy paramStrategy = new ParameterContentNegotiationStrategy(mapping);
    viewResolver.setContentNegotiationManager(new ContentNegotiationManager(paramStrategy));
    ViewResolver viewResolverMock = mock(ViewResolver.clreplaced);
    viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock));
    viewResolver.afterPropertiesSet();
    View viewMock = mock(View.clreplaced, "application_xls");
    String viewName = "view";
    Locale locale = Locale.ENGLISH;
    given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null);
    given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock);
    given(viewMock.getContentType()).willReturn("application/vnd.ms-excel");
    View result = viewResolver.resolveViewName(viewName, locale);
    replacedertThat(result).as("Invalid view").isSameAs(viewMock);
}

18 View Source File : ComponentControllerTest.java
License : Mozilla Public License 2.0
Project Creator : scotiabank

@Test(timeout = 1500L)
public void userDownloadShouldReturn200Status() throws Exception {
    ProjectProperties projectProperties = new ProjectProperties();
    projectProperties.setGroup("com.test");
    projectProperties.setName("hopper-intake");
    projectProperties.setType(ApplicationType.JAVA_SPRING_BOOT_2);
    when(projectCreationService.create(any(ProjectCreation.clreplaced))).thenReturn(null);
    doNothing().when(fileProcessor).createDirectories(any(File.clreplaced));
    this.mvc.perform(post("/api/project/generate").contentType(MediaType.APPLICATION_JSON_UTF8).content(objectMapper.writeValueAsBytes(projectProperties))).andExpect(status().isOk()).andExpect(content().contentType(MediaType.valueOf("application/zip")));
    verify(projectCreationService, times(1)).create(any(ProjectCreation.clreplaced));
}

18 View Source File : DefaultUsernamePasswordAuthenticationFilter.java
License : Apache License 2.0
Project Creator : penggle

protected MediaType getRequestContentType(HttpServletRequest request) {
    try {
        String contentTypeValue = request.getContentType();
        if (!StringUtils.isEmpty(contentTypeValue)) {
            return MediaType.valueOf(contentTypeValue);
        }
    } catch (Exception e) {
    }
    return null;
}

18 View Source File : UserApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * GET /user/{username} : Get user by user name
 *
 * @param username The name that needs to be fetched. Use user1 for testing. (required)
 * @return successful operation (status code 200)
 *         or Invalid username supplied (status code 400)
 *         or User not found (status code 404)
 * @see UserApi#getUserByName
 */
public ResponseEnreplacedy<User> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.", required = true) @PathVariable("username") String username) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"preplacedword\" : \"preplacedword\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) {
            String exampleString = "<User> <id>123456789</id> <username>aeiou</username> <firstName>aeiou</firstName> <lastName>aeiou</lastName> <email>aeiou</email> <preplacedword>aeiou</preplacedword> <phone>aeiou</phone> <userStatus>123</userStatus> </User>";
            ApiUtil.setExampleResponse(request, "application/xml", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : StoreApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * POST /store/order : Place an order for a pet
 *
 * @param body order placed for purchasing the pet (required)
 * @return successful operation (status code 200)
 *         or Invalid Order (status code 400)
 * @see StoreApi#placeOrder
 */
public ResponseEnreplacedy<Order> placeOrder(@ApiParam(value = "order placed for purchasing the pet", required = true) @Valid @RequestBody Order body) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"petId\" : 6, \"quanreplacedy\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) {
            String exampleString = "<Order> <id>123456789</id> <petId>123456789</petId> <quanreplacedy>123</quanreplacedy> <shipDate>2000-01-23T04:56:07.000Z</shipDate> <status>aeiou</status> <complete>true</complete> </Order>";
            ApiUtil.setExampleResponse(request, "application/xml", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : StoreApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * GET /store/order/{order_id} : Find purchase order by ID
 * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
 *
 * @param orderId ID of pet that needs to be fetched (required)
 * @return successful operation (status code 200)
 *         or Invalid ID supplied (status code 400)
 *         or Order not found (status code 404)
 * @see StoreApi#getOrderById
 */
public ResponseEnreplacedy<Order> getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched", required = true) @PathVariable("order_id") Long orderId) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"petId\" : 6, \"quanreplacedy\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) {
            String exampleString = "<Order> <id>123456789</id> <petId>123456789</petId> <quanreplacedy>123</quanreplacedy> <shipDate>2000-01-23T04:56:07.000Z</shipDate> <status>aeiou</status> <complete>true</complete> </Order>";
            ApiUtil.setExampleResponse(request, "application/xml", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : PetApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * POST /pet/{petId}/uploadImage : uploads an image
 *
 * @param petId ID of pet to update (required)
 * @param additionalMetadata Additional data to preplaced to server (optional)
 * @param file file to upload (optional)
 * @return successful operation (status code 200)
 * @see PetApi#uploadFile
 */
public ResponseEnreplacedy<ModelApiResponse> uploadFile(@ApiParam(value = "ID of pet to update", required = true) @PathVariable("petId") Long petId, @ApiParam(value = "Additional data to preplaced to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata, @ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : PetApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * GET /pet/findByStatus : Finds Pets by status
 * Multiple status values can be provided with comma separated strings
 *
 * @param status Status values that need to be considered for filter (required)
 * @return successful operation (status code 200)
 *         or Invalid status value (status code 400)
 * @see PetApi#findPetsByStatus
 */
public ResponseEnreplacedy<List<Pet>> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List<String> status, @ApiIgnore final Pageable pageable) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) {
            String exampleString = "<Pet> <id>123456789</id> <name>doggie</name> <photoUrls> <photoUrls>aeiou</photoUrls> </photoUrls> <tags> </tags> <status>aeiou</status> </Pet>";
            ApiUtil.setExampleResponse(request, "application/xml", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : PetApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * GET /pet/findByTags : Finds Pets by tags
 * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
 *
 * @param tags Tags to filter by (required)
 * @return successful operation (status code 200)
 *         or Invalid tag value (status code 400)
 * @deprecated
 * @see PetApi#findPetsByTags
 */
public ResponseEnreplacedy<List<Pet>> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) List<String> tags, @ApiIgnore final Pageable pageable) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) {
            String exampleString = "<Pet> <id>123456789</id> <name>doggie</name> <photoUrls> <photoUrls>aeiou</photoUrls> </photoUrls> <tags> </tags> <status>aeiou</status> </Pet>";
            ApiUtil.setExampleResponse(request, "application/xml", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : PetApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * GET /pet/{petId} : Find pet by ID
 * Returns a single pet
 *
 * @param petId ID of pet to return (required)
 * @return successful operation (status code 200)
 *         or Invalid ID supplied (status code 400)
 *         or Pet not found (status code 404)
 * @see PetApi#getPetById
 */
public ResponseEnreplacedy<Pet> getPetById(@ApiParam(value = "ID of pet to return", required = true) @PathVariable("petId") Long petId) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) {
            String exampleString = "<Pet> <id>123456789</id> <name>doggie</name> <photoUrls> <photoUrls>aeiou</photoUrls> </photoUrls> <tags> </tags> <status>aeiou</status> </Pet>";
            ApiUtil.setExampleResponse(request, "application/xml", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : FakeClassnameTestApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * PATCH /fake_clreplacedname_test : To test clreplaced name in snake case
 * To test clreplaced name in snake case
 *
 * @param body client model (required)
 * @return successful operation (status code 200)
 * @see FakeClreplacednameTestApi#testClreplacedname
 */
public ResponseEnreplacedy<Client> testClreplacedname(@ApiParam(value = "client model", required = true) @Valid @RequestBody Client body) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"client\" : \"client\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : AnotherFakeApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * PATCH /another-fake/dummy : To test special tags
 * To test special tags and operation ID starting with number
 *
 * @param body client model (required)
 * @return successful operation (status code 200)
 * @see AnotherFakeApi#call123testSpecialTags
 */
public ResponseEnreplacedy<Client> call123testSpecialTags(@ApiParam(value = "client model", required = true) @Valid @RequestBody Client body) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"client\" : \"client\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : PetApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * GET /pet/findByStatus : Finds Pets by status
 * Multiple status values can be provided with comma separated strings
 *
 * @param status Status values that need to be considered for filter (required)
 * @return successful operation (status code 200)
 *         or Invalid status value (status code 400)
 * @see PetApi#findPetsByStatus
 */
public ResponseEnreplacedy<List<Pet>> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List<String> status) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) {
            String exampleString = "<Pet> <id>123456789</id> <name>doggie</name> <photoUrls> <photoUrls>aeiou</photoUrls> </photoUrls> <tags> </tags> <status>aeiou</status> </Pet>";
            ApiUtil.setExampleResponse(request, "application/xml", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : PetApiController.java
License : Apache License 2.0
Project Creator : OpenAPITools

/**
 * GET /pet/findByTags : Finds Pets by tags
 * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
 *
 * @param tags Tags to filter by (required)
 * @return successful operation (status code 200)
 *         or Invalid tag value (status code 400)
 * @deprecated
 * @see PetApi#findPetsByTags
 */
public ResponseEnreplacedy<Set<Pet>> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) Set<String> tags) {
    for (MediaType mediaType : MediaType.parseMediaTypes(request.getHeader("Accept"))) {
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) {
            String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }";
            ApiUtil.setExampleResponse(request, "application/json", exampleString);
            break;
        }
        if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) {
            String exampleString = "<Pet> <id>123456789</id> <name>doggie</name> <photoUrls> <photoUrls>aeiou</photoUrls> </photoUrls> <tags> </tags> <status>aeiou</status> </Pet>";
            ApiUtil.setExampleResponse(request, "application/xml", exampleString);
            break;
        }
    }
    return new ResponseEnreplacedy<>(HttpStatus.NOT_IMPLEMENTED);
}

18 View Source File : SSEControllerTest.java
License : Apache License 2.0
Project Creator : OctoPerf

@Test
public void shouldFailToWatchHeader() {
    // Should match [a-z0-9]*
    final var applicationId = "applicationId";
    webTestClient.get().uri(uriBuilder -> uriBuilder.path("/sse/watch").queryParam("channel", "STORAGE", "RUNTIME", "GIT").build()).header("Authorization", "Bearer user-token").header("ApplicationId", applicationId).accept(MediaType.valueOf(MediaType.TEXT_EVENT_STREAM_VALUE)).exchange().expectStatus().is5xxServerError();
}

18 View Source File : SSEControllerTest.java
License : Apache License 2.0
Project Creator : OctoPerf

@Test
public void shouldFailToWatchForbidden() {
    webTestClient.get().uri(uriBuilder -> uriBuilder.path("/sse/watch").build()).header("Authorization", "Bearer no-role-token").accept(MediaType.valueOf(MediaType.TEXT_EVENT_STREAM_VALUE)).exchange().expectStatus().is4xxClientError();
}

18 View Source File : WebRuntimeEventClient.java
License : Apache License 2.0
Project Creator : OctoPerf

@Override
public Flux<TaskEvent> events() {
    return webClient.get().uri(uriBuilder -> uriBuilder.path("/task/events").build()).accept(MediaType.valueOf(MediaType.TEXT_EVENT_STREAM_VALUE)).retrieve().bodyToFlux(String.clreplaced).doOnSubscribe(subscription -> log.info("Watch task events")).doOnError(t -> log.error("Failed to watch task events", t)).flatMap(sseWrapper -> Mono.fromCallable(() -> {
        final JsonNode node = mapper.readTree(sseWrapper);
        final var type = node.get("type").asText();
        final var clazz = eventClreplacedes.get(type);
        return mapper.readValue(node.get("value").toString(), clazz);
    }));
}

18 View Source File : WebRuntimeClient.java
License : Apache License 2.0
Project Creator : OctoPerf

@Override
public Flux<List<Task>> watchTasks() {
    return webClient.get().uri(uriBuilder -> uriBuilder.path("/task/watch").build()).accept(MediaType.valueOf(MediaType.TEXT_EVENT_STREAM_VALUE)).retrieve().bodyToFlux(new ParameterizedTypeReference<List<Task>>() {
    }).doOnSubscribe(subscription -> log.info("Watch tasks")).doOnError(t -> log.error("Failed to watch tasks", t));
}

18 View Source File : WebRuntimeClient.java
License : Apache License 2.0
Project Creator : OctoPerf

@Override
public Flux<Log> watchLogs() {
    return webClient.get().uri(uriBuilder -> uriBuilder.path("/logs/watch").build()).accept(MediaType.valueOf(MediaType.TEXT_EVENT_STREAM_VALUE)).retrieve().bodyToFlux(Log.clreplaced).doOnSubscribe(subscription -> log.info("Watch logs")).doOnError(t -> log.error("Failed to watch logs", t));
}

18 View Source File : RequestResponseBodyMethodProcessorMockTests.java
License : Apache License 2.0
Project Creator : langtianya

// SPR-9841
@Test
public void handleReturnValueMediaTypeSuffix() throws Exception {
    String body = "Foo";
    MediaType accepted = MediaType.APPLICATION_XHTML_XML;
    List<MediaType> supported = Collections.singletonList(MediaType.valueOf("application/*+xml"));
    servletRequest.addHeader("Accept", accepted);
    given(messageConverter.canWrite(String.clreplaced, null)).willReturn(true);
    given(messageConverter.getSupportedMediaTypes()).willReturn(supported);
    given(messageConverter.canWrite(String.clreplaced, accepted)).willReturn(true);
    processor.handleReturnValue(body, returnTypeStringProduces, mavContainer, webRequest);
    replacedertTrue(mavContainer.isRequestHandled());
    verify(messageConverter).write(eq(body), eq(accepted), isA(HttpOutputMessage.clreplaced));
}

18 View Source File : IlpHttpControllerTest.java
License : Apache License 2.0
Project Creator : interledger4j

private HttpHeaders contentTypeHeader(String contentType) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf(contentType));
    return headers;
}

18 View Source File : MediaTypeTest.java
License : GNU General Public License v3.0
Project Creator : halo-dev

@Test
void parseTest() {
    MediaType mediaType = MediaType.valueOf("image/gif");
    replacedertEquals(MediaType.IMAGE_GIF, mediaType);
}

18 View Source File : MediaTypeTest.java
License : GNU General Public License v3.0
Project Creator : halo-dev

@Test
void includesTest() {
    MediaType mediaType = MediaType.valueOf("image/*");
    boolean isInclude = mediaType.includes(MediaType.IMAGE_GIF);
    replacedertTrue(isInclude);
    isInclude = mediaType.includes(MediaType.IMAGE_JPEG);
    replacedertTrue(isInclude);
    isInclude = mediaType.includes(MediaType.IMAGE_PNG);
    replacedertTrue(isInclude);
    isInclude = mediaType.includes(MediaType.TEXT_HTML);
    replacedertFalse(isInclude);
}

18 View Source File : ImageController.java
License : Apache License 2.0
Project Creator : feature-creeps

@GetMapping(value = "/{id}")
public ResponseEnreplacedy getImage(@PathVariable("id") String id) {
    Image image = imageService.thumbnail(id);
    this.eventService.addFieldToActiveEvent("action", "thumbnail");
    this.eventService.addFieldToActiveEvent("content.imageId", id);
    if (image == null) {
        LOGGER.error("Image with id {} not found", id);
        this.eventService.addFieldToActiveEvent("app.error", 1);
        this.eventService.addFieldToActiveEvent("action.failure_reason", "image_not_found");
        throw new NotFoundException("Image not found");
    }
    loggingContextUtil.mdcPut(image.getContentType());
    LOGGER.info("Returning thumbnail from image with id {}", id);
    imageThumbnailMetricsService.imageThumbnailed(image.getContentType());
    this.eventService.addFieldToActiveEvent("content.transformed.type", image.getContentType());
    this.eventService.addFieldToActiveEvent("content.transformed.size", image.getSize());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf(image.getContentType()));
    this.eventService.addFieldToActiveEvent("app.error", 0);
    return new ResponseEnreplacedy<>(image.getData(), headers, HttpStatus.OK);
}

18 View Source File : PageController.java
License : GNU General Public License v3.0
Project Creator : comixed

/**
 * Retrieves a page's content from either the page cache or the comic file itself.
 *
 * @param page the page
 * @return the content
 * @throws ComicException if the page could not be found in the comic file
 */
private ResponseEnreplacedy<byte[]> getResponseEnreplacedyForPage(Page page) throws ComicException {
    log.debug("creating response enreplacedy for page: id={}", page.getId());
    byte[] content = this.pageCacheService.findByHash(page.getHash());
    if (content == null) {
        log.debug("Fetching content for page");
        final ArchiveAdaptor adaptor = this.comicFileHandler.getArchiveAdaptorFor(page.getComic().getArchiveType());
        try {
            content = adaptor.loadSingleFile(page.getComic(), page.getFilename());
        } catch (ArchiveAdaptorException error) {
            throw new ComicException("failed to load page content", error);
        }
        log.debug("Caching image for hash: {} bytes hash={}", content.length, page.getHash());
        try {
            this.pageCacheService.saveByHash(page.getHash(), content);
        } catch (IOException error) {
            log.error("Failed to add comic page to cache", error);
        }
    }
    String type = this.fileTypeIdentifier.typeFor(new ByteArrayInputStream(content)) + "/" + this.fileTypeIdentifier.subtypeFor(new ByteArrayInputStream(content));
    log.debug("Page type: {}", type);
    return ResponseEnreplacedy.ok().contentLength(content.length).header("Content-Disposition", "attachment; filename=\"" + page.getFilename() + "\"").contentType(MediaType.valueOf(type)).body(content);
}

See More Examples