Here are the examples of the java api org.springframework.core.io.ByteArrayResource taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
102 Examples
19
View Source File : HttpRangeTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
// gh-23576
@Test
public void toResourceRegionStartingAtResourceByteCount() {
byte[] bytes = "Spring Framework".getBytes(StandardCharsets.UTF_8);
ByteArrayResource resource = new ByteArrayResource(bytes);
HttpRange range = HttpRange.createByteRange(resource.contentLength());
replacedertThatIllegalArgumentException().isThrownBy(() -> range.toResourceRegion(resource));
}
19
View Source File : HttpRangeTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void toResourceRegionsValidations() {
byte[] bytes = "12345".getBytes(StandardCharsets.UTF_8);
ByteArrayResource resource = new ByteArrayResource(bytes);
// 1. Below length
List<HttpRange> belowLengthRanges = HttpRange.parseRanges("bytes=0-1,2-3");
List<ResourceRegion> regions = HttpRange.toResourceRegions(belowLengthRanges, resource);
replacedertThat(regions.size()).isEqualTo(2);
// 2. At length
List<HttpRange> atLengthRanges = HttpRange.parseRanges("bytes=0-1,2-4");
replacedertThatIllegalArgumentException().isThrownBy(() -> HttpRange.toResourceRegions(atLengthRanges, resource));
}
19
View Source File : HttpRangeTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void toResourceRegionIllegalLength() {
ByteArrayResource resource = mock(ByteArrayResource.clreplaced);
given(resource.contentLength()).willReturn(-1L);
HttpRange range = HttpRange.createByteRange(0, 9);
replacedertThatIllegalArgumentException().isThrownBy(() -> range.toResourceRegion(resource));
}
19
View Source File : CompetitionStatusControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void exportBankDetails() throws Exception {
Long compereplacedionId = 123L;
ByteArrayResource result = new ByteArrayResource("My content!".getBytes());
when(bankDetailsRestServiceMock.downloadByCompereplacedion(compereplacedionId)).thenReturn(restSuccess(result));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd_HH-mm");
mockMvc.perform(get("/compereplacedion/123/status/bank-details/export")).andExpect(status().isOk()).andExpect(content().contentType(("text/csv"))).andExpect(header().string("Content-Type", "text/csv")).andExpect(header().string("Content-disposition", "attachment;filename=" + String.format("Bank_details_%s_%s.csv", compereplacedionId, ZonedDateTime.now().format(formatter)))).andExpect(content().string("My content!"));
verify(bankDetailsRestServiceMock).downloadByCompereplacedion(123L);
}
19
View Source File : FinanceChecksNotesAddNoteController.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_NOTES_SECTION')")
@GetMapping("/attachment/{attachmentId}")
@ResponseBody
public ResponseEnreplacedy<ByteArrayResource> downloadAttachment(@P("projectId") @PathVariable Long projectId, @PathVariable Long organisationId, @PathVariable Long attachmentId, UserResource loggedInUser, HttpServletRequest request) {
partnerOrganisationRestService.getPartnerOrganisation(projectId, organisationId);
List<Long> attachments = loadAttachmentsFromCookie(request, projectId, organisationId);
if (attachments.contains(attachmentId)) {
ByteArrayResource fileContent = financeCheckService.downloadFile(attachmentId);
FileEntryResource fileInfo = financeCheckService.getAttachmentInfo(attachmentId);
return getFileResponseEnreplacedy(fileContent, fileInfo);
} else {
throw new ObjectNotFoundException("Cannot find note attachment " + attachmentId + " for organisation " + organisationId + " and project project " + projectId, emptyList());
}
}
19
View Source File : CompetitionManagementApplicationController.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@SecuredBySpring(value = "TODO", description = "TODO")
@PreAuthorize("hasAnyAuthority('project_finance', 'comp_admin', 'support', 'innovation_lead', 'stakeholder', 'external_finance')")
@GetMapping("/{applicationId}/forminput/{formInputId}/file/{fileEntryId}/download")
@ResponseBody
public ResponseEnreplacedy<ByteArrayResource> downloadQuestionFile(@PathVariable("applicationId") final Long applicationId, @PathVariable("formInputId") final Long formInputId, @PathVariable("fileEntryId") final Long fileEntryId, UserResource user) throws ExecutionException, InterruptedException {
long applicantProcessRoleId = formInputResponseRestService.getByFormInputIdAndApplication(formInputId, applicationId).getSuccess().get(0).getUpdatedBy();
final ByteArrayResource resource = formInputResponseRestService.getFile(formInputId, applicationId, applicantProcessRoleId, fileEntryId).getSuccess();
final FormInputResponseFileEntryResource fileDetails = formInputResponseRestService.getFileDetails(formInputId, applicationId, applicantProcessRoleId, fileEntryId).getSuccess();
return getFileResponseEnreplacedy(resource, fileDetails.getFileEntryResource());
}
19
View Source File : TestCaseController.java
License : Apache License 2.0
Project Creator : google
License : Apache License 2.0
Project Creator : google
@CrossOrigin(origins = "*")
@RequestMapping(value = "/exportProjectToZip", method = RequestMethod.GET)
public ResponseEnreplacedy<Resource> exportProjectToZip(@RequestParam(value = "projectId") String projectId, @RequestParam(value = "projectName") String projectName) throws IOException, UicdException {
ZipFile file = testCasesImportExportManager.zipAndExport(projectId, projectName, "");
HttpHeaders header = new HttpHeaders();
header.add(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", projectName));
header.add("Cache-Control", "no-cache, no-store, must-revalidate");
header.add("Pragma", "no-cache");
header.add("Expires", "0");
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(file.getFile().toPath()));
return ResponseEnreplacedy.ok().headers(header).contentLength(file.getFile().length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(resource);
}
19
View Source File : FunctionalityResource.java
License : Apache License 2.0
Project Creator : Decathlon
License : Apache License 2.0
Project Creator : Decathlon
/**
* Returns a streamable resource which will contains the wanted functionalities exported in the wanted format.
*
* @param projectCode the code of the project which contains the wanted functionalities.
* @param functionalities the wanted functionalities' ids
* @param exportType the wanted export format
* @return a streamable byte array which represents the exported functionalities for download.
*/
@GetMapping("/export")
public ResponseEnreplacedy<Resource> export(@PathVariable String projectCode, @RequestParam List<Long> functionalities, @RequestParam String exportType, @RequestParam Map<String, String> additionalParams) {
try {
// Remove the already known params catched by the global mapping
additionalParams.remove("functionalities");
additionalParams.remove("exportType");
ByteArrayResource resource = service.generateExport(functionalities, exportType, additionalParams);
return ResponseEnreplacedy.ok().contentLength(resource.contentLength()).contentType(MediaType.parseMediaType("application/octet-stream")).body(resource);
} catch (BadRequestException ex) {
return ResponseUtil.handle(ex);
}
}
19
View Source File : DummyController.java
License : Apache License 2.0
Project Creator : controller-logger
License : Apache License 2.0
Project Creator : controller-logger
@RequestMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public void uploadFile(@RequestBody ByteArrayResource file) {
// no-op
}
19
View Source File : UserService.java
License : GNU Affero General Public License v3.0
Project Creator : Alovoa
License : GNU Affero General Public License v3.0
Project Creator : Alovoa
public ResponseEnreplacedy<Resource> getUserdata() throws Exception {
User user = authService.getCurrentUser();
UserGdpr ug = UserGdpr.userToUserGdpr(user);
String json = objectMapper.writeValuereplacedtring(ug);
ByteArrayResource resource = new ByteArrayResource(json.getBytes());
MediaType mediaType = MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
return new ResponseEnreplacedy<Resource>(resource, headers, HttpStatus.OK);
}
18
View Source File : NoSnakeYamlPropertySourceLoaderTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void load() throws Exception {
ByteArrayResource resource = new ByteArrayResource("foo:\n bar: spam".getBytes());
replacedertThatIllegalStateException().isThrownBy(() -> this.loader.load("resource", resource)).withMessageContaining("Attempted to load resource but snakeyaml was not found on the clreplacedpath");
}
18
View Source File : HttpRangeTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test(expected = IllegalArgumentException.clreplaced)
public void toResourceRegionIllegalLength() {
ByteArrayResource resource = mock(ByteArrayResource.clreplaced);
given(resource.contentLength()).willReturn(-1L);
HttpRange range = HttpRange.createByteRange(0, 9);
range.toResourceRegion(resource);
}
18
View Source File : HttpRangeTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Test
public void toResourceRegionsValidations() {
byte[] bytes = "12345".getBytes(StandardCharsets.UTF_8);
ByteArrayResource resource = new ByteArrayResource(bytes);
// 1. Below length
List<HttpRange> ranges = HttpRange.parseRanges("bytes=0-1,2-3");
List<ResourceRegion> regions = HttpRange.toResourceRegions(ranges, resource);
replacedertEquals(2, regions.size());
// 2. At length
ranges = HttpRange.parseRanges("bytes=0-1,2-4");
try {
HttpRange.toResourceRegions(ranges, resource);
fail();
} catch (IllegalArgumentException ex) {
// Expected..
}
}
18
View Source File : NoteController.java
License : GNU General Public License v2.0
Project Creator : singerdmx
License : GNU General Public License v2.0
Project Creator : singerdmx
@PostMapping(NOTE_EXPORT_PDF_ROUTE)
public ResponseEnreplacedy<Object> exportNoteAsPdf(@NotNull @PathVariable Long noteId, @NotNull @RequestBody ExportProjecreplacedemParams params) {
String username = MDC.get(UserClient.USER_NAME_KEY);
com.bulletjournal.repository.models.Note note = noteDaoJpa.getProjecreplacedem(noteId, username);
try {
String html = freeMarkerClient.convertProjecreplacedemIntoPdfHtml(note, params.getContents());
ByteArrayResource resource = PdfConverter.projecreplacedemHtmlToPdf(html);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=note.pdf");
return ResponseEnreplacedy.status(HttpStatus.OK).headers(headers).contentLength(resource.contentLength()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
} catch (IOException | TemplateException e) {
LOGGER.error("Failed to convert note into HTML string - " + e);
return ResponseEnreplacedy.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to get note as PDF.");
}
}
18
View Source File : JobBuiltFileService.java
License : Apache License 2.0
Project Creator : PaaS-TA
License : Apache License 2.0
Project Creator : PaaS-TA
private ByteArrayResource procGetBuiltFileByteArrayResourceForJava(CustomJob customJob) throws IOException {
// GET SERVICE INSTANCES DETAIL FROM DATABASE
String ciServerUrl = restTemplateService.send(Constants.TARGET_COMMON_API, REQ_SERVICE_INSTANCES_URL + customJob.getServiceInstancesId(), HttpMethod.GET, null, ServiceInstances.clreplaced).getCiServerUrl();
// CREATE JSch SESSION BOSH_1.0 SCP로 파일 다운로드 기능으로 개발된 코드 BOSH_2.0에서는 사용불가
// Session session = procCreateJSchSession(ciServerUrl);
//
// if (session == null) {
// throw new IOException("JSch SESSION ERROR");
// }
//
// String builderType = customJob.getBuilderType();
// String requestFile = ciServerWorkspacePath + customJob.getJobGuid();
//
// if (String.valueOf(JobConfig.BuilderType.GRADLE).equals(builderType)) {
// requestFile += "/build/libs/*.war";
// }
//
// if (String.valueOf(JobConfig.BuilderType.MAVEN).equals(builderType)) {
// requestFile += "/target/*.war";
// }
//
// String command = "scp -f " + requestFile;
// Channel channel = session.openChannel("exec");
// ((ChannelExec) channel).setCommand(command);
//
// OutputStream out = channel.getOutputStream();
// InputStream in = channel.getInputStream();
//
// channel.connect();
// ByteArrayResource byteArrayResource = procGetByteArrayResource(in, out);
// session.disconnect();
String builderType = customJob.getBuilderType();
String requestFile = ciServerUrl + "/job/" + customJob.getJobGuid();
if (String.valueOf(JobConfig.BuilderType.GRADLE).equals(builderType)) {
requestFile += "/ws/build/libs/";
}
if (String.valueOf(JobConfig.BuilderType.MAVEN).equals(builderType)) {
requestFile += "/ws/target/";
}
Map<String, String> fileInfo = getFileUrl(requestFile);
if (fileInfo.get("URL") != null && fileInfo.get("FILE_NAME") != null) {
ByteArrayResource byteArrayResource = procGetByteArrayResource(fileInfo.get("FILE_NAME"), fileInfo.get("URL"));
return byteArrayResource;
} else {
return null;
}
}
18
View Source File : GrantOfferLetterControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testDownloadSignedGrantOfferLetterByLead() throws Exception {
FileEntryResource fileDetails = newFileEntryResource().withName("A name").build();
ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes());
when(grantOfferLetterService.getSignedGrantOfferLetterFile(123L)).thenReturn(Optional.of(fileContents));
when(grantOfferLetterService.getSignedGrantOfferLetterFileDetails(123L)).thenReturn(Optional.of(fileDetails));
when(projectService.isUserLeadPartner(123L, 1L)).thenReturn(true);
MvcResult result = mockMvc.perform(get("/project/{projectId}/offer/signed-download", 123L)).andExpect(status().isOk()).andReturn();
replacedertEquals("My content!", result.getResponse().getContentreplacedtring());
replacedertEquals("inline; filename=\"" + fileDetails.getName() + "\"", result.getResponse().getHeader("Content-Disposition"));
}
18
View Source File : GrantOfferLetterControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testDownloadAdditionalContract() throws Exception {
FileEntryResource fileDetails = newFileEntryResource().withName("A name").build();
ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes());
when(grantOfferLetterService.getAdditionalContractFile(123L)).thenReturn(Optional.of(fileContents));
when(grantOfferLetterService.getAdditionalContractFileDetails(123L)).thenReturn(Optional.of(fileDetails));
MvcResult result = mockMvc.perform(get("/project/{projectId}/offer/additional-contract", 123L)).andExpect(status().isOk()).andReturn();
replacedertEquals("My content!", result.getResponse().getContentreplacedtring());
replacedertEquals("inline; filename=\"" + fileDetails.getName() + "\"", result.getResponse().getHeader("Content-Disposition"));
}
18
View Source File : ProjectFinanceChecksControllerQueriesTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testDownloadAttachmentFailsNoInfo() throws Exception {
ByteArrayResource bytes = new ByteArrayResource("File contents".getBytes());
when(financeCheckServiceMock.downloadFile(1L)).thenReturn(bytes);
when(financeCheckServiceMock.getAttachmentInfo(1L)).thenThrow(new ForbiddenActionException());
MvcResult result = mockMvc.perform(get("/project/123/finance-checks/attachment/1")).andExpect(status().isForbidden()).andExpect(view().name("forbidden")).andReturn();
MockHttpServletResponse response = result.getResponse();
// replacedert that there is no content
replacedertEquals("", response.getContentreplacedtring());
replacedertNull(response.getHeader("Content-Disposition"));
replacedertEquals(0, response.getContentLength());
}
18
View Source File : DocumentsControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void downloadDoreplacedent() throws Exception {
long projectId = 1L;
long doreplacedentConfigId = 2L;
ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes());
FileEntryResource fileEntryDetails = newFileEntryResource().withName("Risk Register").build();
when(doreplacedentsRestService.getFileContents(projectId, doreplacedentConfigId)).thenReturn(restSuccess(Optional.of(fileContents)));
when(doreplacedentsRestService.getFileEntryDetails(projectId, doreplacedentConfigId)).thenReturn(restSuccess(Optional.of(fileEntryDetails)));
MvcResult result = mockMvc.perform(get("/project/" + projectId + "/doreplacedent/config/" + doreplacedentConfigId + "/download")).andExpect(status().isOk()).andReturn();
replacedertEquals("My content!", result.getResponse().getContentreplacedtring());
replacedertEquals("inline; filename=\"" + fileEntryDetails.getName() + "\"", result.getResponse().getHeader("Content-Disposition"));
}
18
View Source File : FinanceChecksQueriesControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testDownloadAttachmentFailsNoInfo() throws Exception {
ByteArrayResource bytes = new ByteArrayResource("File contents".getBytes());
when(financeCheckServiceMock.downloadFile(1L)).thenReturn(bytes);
when(financeCheckServiceMock.getAttachmentInfo(1L)).thenThrow(new ForbiddenActionException());
MvcResult result = mockMvc.perform(get("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/query/attachment/1?query_section=Eligibility")).andExpect(status().isForbidden()).andExpect(view().name("forbidden")).andReturn();
MockHttpServletResponse response = result.getResponse();
// replacedert that there is no content
replacedertEquals("", response.getContentreplacedtring());
replacedertEquals(null, response.getHeader("Content-Disposition"));
replacedertEquals(0, response.getContentLength());
}
18
View Source File : FinanceChecksNotesControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testDownloadAttachmentFailsNoInfo() throws Exception {
ByteArrayResource bytes = new ByteArrayResource("File contents".getBytes());
when(financeCheckServiceMock.downloadFile(1L)).thenReturn(bytes);
when(financeCheckServiceMock.getAttachmentInfo(1L)).thenThrow(new ForbiddenActionException());
MvcResult result = mockMvc.perform(get("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/note/attachment/1")).andExpect(status().isForbidden()).andExpect(view().name("forbidden")).andReturn();
MockHttpServletResponse response = result.getResponse();
// replacedert that there is no content
replacedertEquals("", response.getContentreplacedtring());
replacedertEquals(null, response.getHeader("Content-Disposition"));
replacedertEquals(0, response.getContentLength());
}
18
View Source File : CompetitionManagementApplicationControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void downloadAsInternalUser() throws Exception {
Role.internalRoles().forEach(role -> {
try {
setLoggedInUser(newUserResource().withRolesGlobal(singletonList(role)).build());
Long formInputId = 35L;
long applicationId = 2L;
long compereplacedionId = 3L;
// mapping role ordinal as process role (just for mocking)
long processRoleId = role.ordinal();
long fileEntryId = 5L;
List<FormInputResponseResource> inputResponse = newFormInputResponseResource().withUpdatedBy(processRoleId).build(1);
when(formInputResponseRestService.getByFormInputIdAndApplication(formInputId, applicationId)).thenReturn(RestResult.restSuccess(inputResponse));
ByteArrayResource bar = new ByteArrayResource("File contents".getBytes());
when(formInputResponseRestService.getFile(formInputId, applicationId, processRoleId, fileEntryId)).thenReturn(restSuccess(bar));
FileEntryResource fileEntryResource = newFileEntryResource().with(id(999L)).withName("file1").withMediaType("text/csv").build();
FormInputResponseFileEntryResource formInputResponseFileEntryResource = new FormInputResponseFileEntryResource(fileEntryResource, 123L, 456L, 789L, fileEntryId);
when(formInputResponseRestService.getFileDetails(formInputId, applicationId, processRoleId, fileEntryId)).thenReturn(RestResult.restSuccess(formInputResponseFileEntryResource));
mockMvc.perform(get("/compereplacedion/" + compereplacedionId + "/application/" + applicationId + "/forminput/" + formInputId + "/file/" + fileEntryId + "/download")).andExpect(status().isOk()).andExpect(content().contentType(("text/csv"))).andExpect(header().string("Content-Type", "text/csv")).andExpect(header().string("Content-disposition", "inline; filename=\"file1\"")).andExpect(content().string("File contents"));
verify(formInputResponseRestService).getFile(formInputId, applicationId, processRoleId, fileEntryId);
verify(formInputResponseRestService).getFileDetails(formInputId, applicationId, processRoleId, fileEntryId);
} catch (Exception e) {
fail();
}
});
}
18
View Source File : AbstractContentGroupController.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@GetMapping("/{compereplacedionId}/edit/{contentGroupId}")
public ResponseEnreplacedy<ByteArrayResource> getFileDetails(Model model, @PathVariable(COMPEreplacedION_ID_KEY) long compereplacedionId, @PathVariable("contentGroupId") long contentGroupId) {
CompereplacedionResource compereplacedion = compereplacedionRestService.getCompereplacedionById(compereplacedionId).getSuccess();
if (!compereplacedion.isNonIfs() && !compereplacedionSetupService.hasInitialDetailsBeenPreviouslySubmitted(compereplacedionId)) {
throw new IllegalStateException("The compereplacedion 'Initial Details' section should be completed first.");
}
final ByteArrayResource resource = publicContentService.downloadAttachment(contentGroupId);
FileEntryResource fileDetails = publicContentService.getFileDetails(contentGroupId);
return getFileResponseEnreplacedy(resource, fileDetails);
}
18
View Source File : ApplicationDownloadController.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@GetMapping("/{applicationFinanceId}/finance-download")
@ResponseBody
public ResponseEnreplacedy<ByteArrayResource> downloadApplicationFinanceFile(@PathVariable("applicationFinanceId") final Long applicationFinanceId) {
final ByteArrayResource resource = financeService.getFinanceDoreplacedentByApplicationFinance(applicationFinanceId).getSuccess();
final FileEntryResource fileDetails = financeService.getFinanceEntryByApplicationFinanceId(applicationFinanceId).getSuccess();
return getFileResponseEnreplacedy(resource, fileDetails);
}
18
View Source File : ProjectFinanceAttachmentRestServiceTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void test_download() throws Exception {
final Long fileId = 912L;
ByteArrayResource expected = new ByteArrayResource("1u6536748".getBytes());
setupGetWithRestResultExpectations(baseURL + "/download/" + fileId, ByteArrayResource.clreplaced, expected, OK);
final ByteArrayResource response = service.download(fileId).getSuccess();
replacedertSame(expected, response);
}
18
View Source File : ContentGroupRestServiceMocksTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void test_getFile() {
Long groupId = 1L;
String expectedUrl = CONTENT_GROUP_REST_URL + "get-file-contents/" + groupId;
ByteArrayResource returnedFileContents = new ByteArrayResource("Retrieved content".getBytes());
setupGetWithRestResultExpectations(expectedUrl, ByteArrayResource.clreplaced, returnedFileContents, OK);
ByteArrayResource actual = service.getFile(groupId).getSuccess();
replacedertThat(actual, equalTo(returnedFileContents));
}
18
View Source File : ContentGroupRestServiceMocksTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void test_getFileAnonymous() {
Long groupId = 1L;
String expectedUrl = CONTENT_GROUP_REST_URL + "get-file-contents/" + groupId;
ByteArrayResource returnedFileContents = new ByteArrayResource("Retrieved content".getBytes());
setupGetWithRestResultAnonymousExpectations(expectedUrl, ByteArrayResource.clreplaced, returnedFileContents, OK);
ByteArrayResource actual = service.getFileAnonymous(groupId).getSuccess();
replacedertThat(actual, equalTo(returnedFileContents));
}
18
View Source File : GrantOfferLetterRestServiceImplTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testGetSignedAdditionalContractFileContent() {
String expectedUrl = projectRestURL + "/123/signed-additional-contract";
ByteArrayResource returnedFileContents = new ByteArrayResource("Retrieved content".getBytes());
setupGetWithRestResultExpectations(expectedUrl, ByteArrayResource.clreplaced, returnedFileContents, OK);
ByteArrayResource retrievedFileEntry = service.getSignedAdditionalContractFile(123L).getSuccess().get();
replacedertEquals(returnedFileContents, retrievedFileEntry);
}
18
View Source File : GrantOfferLetterRestServiceImplTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testGetSignedGrantOfferLetterFileContent() {
String expectedUrl = projectRestURL + "/123/signed-grant-offer";
ByteArrayResource returnedFileContents = new ByteArrayResource("Retrieved content".getBytes());
setupGetWithRestResultExpectations(expectedUrl, ByteArrayResource.clreplaced, returnedFileContents, OK);
ByteArrayResource retrievedFileEntry = service.getSignedGrantOfferLetterFile(123L).getSuccess().get();
replacedertEquals(returnedFileContents, retrievedFileEntry);
}
18
View Source File : GrantOfferLetterRestServiceImplTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testGetGeneratedGrantOfferLetterFileContent() {
String expectedUrl = projectRestURL + "/123/grant-offer";
ByteArrayResource returnedFileContents = new ByteArrayResource("Retrieved content".getBytes());
setupGetWithRestResultExpectations(expectedUrl, ByteArrayResource.clreplaced, returnedFileContents, OK);
ByteArrayResource retrievedFileEntry = service.getGrantOfferFile(123L).getSuccess().get();
replacedertEquals(returnedFileContents, retrievedFileEntry);
}
18
View Source File : DocumentsRestServiceImplTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void getFileContents() {
String url = String.format("%s/%s/doreplacedent/config/%s/file-contents", projectRestURL, projectId, doreplacedentConfigId);
ByteArrayResource expectedFileContents = new ByteArrayResource("Retrieved content".getBytes());
setupGetWithRestResultExpectations(url, ByteArrayResource.clreplaced, expectedFileContents, OK);
ByteArrayResource retrievedFileContents = service.getFileContents(projectId, doreplacedentConfigId).getSuccess().get();
replacedertEquals(expectedFileContents, retrievedFileContents);
}
18
View Source File : BankDetailsRestServiceImplTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testDownloadByCompereplacedion() {
Long compereplacedionId = 123L;
ByteArrayResource returnedFileContents = new ByteArrayResource("Retrieved content".getBytes());
String url = compereplacedionRestURL + "/" + compereplacedionId + "/bank-details/export";
setupGetWithRestResultExpectations(url, ByteArrayResource.clreplaced, returnedFileContents, OK);
ByteArrayResource retrievedFileEntry = service.downloadByCompereplacedion(123L).getSuccess();
replacedertEquals(returnedFileContents, retrievedFileEntry);
}
18
View Source File : InterviewResponseRestServiceImplTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void downloadResponse() throws Exception {
final long applicationId = 912L;
ByteArrayResource expected = new ByteArrayResource("1u6536748".getBytes());
setupGetWithRestResultExpectations(format("%s/%s", interviewResponseRestUrl, applicationId), ByteArrayResource.clreplaced, expected, OK);
final ByteArrayResource response = service.downloadResponse(applicationId).getSuccess();
replacedertSame(expected, response);
}
18
View Source File : InterviewAssignmentRestServiceImplTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void downloadFeedback() throws Exception {
final long applicationId = 912L;
ByteArrayResource expected = new ByteArrayResource("1u6536748".getBytes());
setupGetWithRestResultExpectations(format("%s/%s/%s", REST_URL, "feedback", applicationId), ByteArrayResource.clreplaced, expected, OK);
final ByteArrayResource response = service.downloadFeedback(applicationId).getSuccess();
replacedertSame(expected, response);
}
18
View Source File : EuGrantTransferRestServiceImplTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void downloadGrantAgreement() {
final long applicationId = 912L;
ByteArrayResource expected = new ByteArrayResource("1u6536748".getBytes());
setupGetWithRestResultExpectations(format("%s/%s/%s", REST_URL, "grant-agreement", applicationId), ByteArrayResource.clreplaced, expected, OK);
final ByteArrayResource response = service.downloadGrantAgreement(applicationId).getSuccess();
replacedertSame(expected, response);
}
18
View Source File : OverheadFileRestServiceMocksTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testGetOverheadFileUsingProjectFinanceRowId() {
String expectedUrl = overheadFileRestURL + "/project-overhead-calculation-doreplacedent?overheadId=123";
ByteArrayResource returnedFileContents = new ByteArrayResource("Retrieved content".getBytes());
setupGetWithRestResultExpectations(expectedUrl, ByteArrayResource.clreplaced, returnedFileContents, OK);
ByteArrayResource retrievedFileEntry = service.getOverheadFileUsingProjectFinanceRowId(123L).getSuccess();
replacedertEquals(returnedFileContents, retrievedFileEntry);
}
18
View Source File : OverheadFileRestServiceMocksTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testGetOverheadFileContent() {
String expectedUrl = overheadFileRestURL + "/overhead-calculation-doreplacedent?overheadId=123";
ByteArrayResource returnedFileContents = new ByteArrayResource("Retrieved content".getBytes());
setupGetWithRestResultExpectations(expectedUrl, ByteArrayResource.clreplaced, returnedFileContents, OK);
ByteArrayResource retrievedFileEntry = service.getOverheadFile(123L).getSuccess();
replacedertEquals(returnedFileContents, retrievedFileEntry);
}
18
View Source File : FileDownloadController.java
License : MIT License
Project Creator : HouariZegai
License : MIT License
Project Creator : HouariZegai
@GetMapping("/downloadFile")
public ResponseEnreplacedy<Resource> download() throws IOException {
File file = new File(DOWNLOAD_FOLDER + "Logo_Teletic_Italic.png");
Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=teletic_data.png");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEnreplacedy.ok().headers(headers).contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
}
18
View Source File : SpringWebClientFlowableHttpClient.java
License : Apache License 2.0
Project Creator : flowable
License : Apache License 2.0
Project Creator : flowable
protected HttpResponse toFlowableHttpResponse(ResponseEnreplacedy<ByteArrayResource> response) {
HttpResponse responseInfo = new HttpResponse();
responseInfo.setStatusCode(response.getStatusCodeValue());
responseInfo.setReason(response.getStatusCode().getReasonPhrase());
responseInfo.setHttpHeaders(toFlowableHeaders(response.getHeaders()));
ByteArrayResource body = response.getBody();
if (body != null) {
MediaType contentType = response.getHeaders().getContentType();
byte[] bodyBytes = body.getByteArray();
if (contentType != null && contentType.getCharset() != null) {
responseInfo.setBody(new String(bodyBytes, contentType.getCharset()));
} else {
responseInfo.setBody(new String(bodyBytes));
}
}
return responseInfo;
}
18
View Source File : BlacklistController.java
License : GNU Affero General Public License v3.0
Project Creator : agnitas-org
License : GNU Affero General Public License v3.0
Project Creator : agnitas-org
@GetMapping("/download.action")
public ResponseEnreplacedy<Resource> download(ComAdmin admin) throws Exception {
int companyId = admin.getCompanyID();
Locale locale = admin.getLocale();
String fileName = "blacklist.csv";
String mediaType = "text/csv";
List<BlacklistDto> recipientList = blacklistService.getAll(companyId);
String csvContent = csvTableGenerator.generate(recipientList, locale);
byte[] byteResource = csvContent.getBytes(StandardCharsets.UTF_8);
ByteArrayResource resource = new ByteArrayResource(byteResource);
// UAL
String activityLogAction = "download blacklist";
String activityLogDescription = "Row count: " + recipientList.size();
userActivityLogService.writeUserActivityLog(admin, activityLogAction, activityLogDescription, logger);
return ResponseEnreplacedy.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + fileName).contentLength(byteResource.length).contentType(MediaType.parseMediaType(mediaType)).body(resource);
}
17
View Source File : JacksonTesterIntegrationTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Test
public void readWithResourceAndView() throws Exception {
this.objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
ByteArrayResource resource = new ByteArrayResource(JSON.getBytes());
ObjectContent<ExampleObjectWithView> content = this.jsonWithView.forView(ExampleObjectWithView.TestView.clreplaced).read(resource);
replacedertThat(content.getObject().getName()).isEqualTo("Spring");
replacedertThat(content.getObject().getAge()).isEqualTo(0);
}
17
View Source File : ByteCodeLoadingFunctionTests.java
License : Apache License 2.0
Project Creator : spring-cloud
License : Apache License 2.0
Project Creator : spring-cloud
@Test
public void compileSupplier() throws Exception {
CompiledFunctionFactory<Supplier<String>> compiled = new SupplierCompiler<String>(String.clreplaced.getName()).compile("foos", "() -> \"foo\"", "String");
ByteArrayResource resource = new ByteArrayResource(compiled.getGeneratedClreplacedBytes(), "foos");
ByteCodeLoadingSupplier<String> supplier = new ByteCodeLoadingSupplier<>(resource);
supplier.afterPropertiesSet();
replacedertThat(supplier instanceof FunctionFactoryMetadata);
replacedertThat(FunctionFactoryUtils.isFluxSupplier(supplier.getFactoryMethod())).isFalse();
replacedertThat(supplier.get()).isEqualTo("foo");
}
17
View Source File : HttpRangeTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void toResourceRegion() {
byte[] bytes = "Spring Framework".getBytes(StandardCharsets.UTF_8);
ByteArrayResource resource = new ByteArrayResource(bytes);
HttpRange range = HttpRange.createByteRange(0, 5);
ResourceRegion region = range.toResourceRegion(resource);
replacedertThat(region.getResource()).isEqualTo(resource);
replacedertThat(region.getPosition()).isEqualTo(0L);
replacedertThat(region.getCount()).isEqualTo(6L);
}
17
View Source File : ReportWs.java
License : MIT License
Project Creator : shzlw
License : MIT License
Project Creator : shzlw
@RequestMapping(value = "/pdf", method = RequestMethod.POST, produces = MediaType.APPLICATION_PDF_VALUE)
@Transactional(readOnly = true)
public ResponseEnreplacedy<?> exportToPdf(@RequestBody ExportRequest exportRequest, HttpServletRequest request) {
User user = (User) request.getAttribute(Constants.HTTP_REQUEST_ATTR_USER);
exportRequest.setSessionKey(user.getSessionKey());
try {
byte[] pdfData = httpClient.postJson(appProperties.getExportServerUrl(), mapper.writeValuereplacedtring(exportRequest));
ByteArrayResource resource = new ByteArrayResource(pdfData);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + exportRequest.getReportName() + ".pdf");
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEnreplacedy.ok().headers(headers).contentLength(pdfData.length).contentType(MediaType.parseMediaType("application/octet-stream")).body(resource);
} catch (IOException e) {
return new ResponseEnreplacedy<String>(HttpStatus.NO_CONTENT);
}
}
17
View Source File : KafkaController.java
License : GNU General Public License v2.0
Project Creator : sanri1993
License : GNU General Public License v2.0
Project Creator : sanri1993
/**
* kafka 连接的创建需要依赖于 zookeeper
* @param kafkaConnectParam
*/
@PostMapping(value = "/connect/create", consumes = "application/yaml")
public void createConnect(@RequestBody String yamlConfig) throws IOException {
ByteArrayResource byteArrayResource = new ByteArrayResource(yamlConfig.getBytes());
List<PropertySource<?>> load = yamlPropertySourceLoader.load("a", byteArrayResource);
Iterable<ConfigurationPropertySource> from = ConfigurationPropertySources.from(load);
Binder binder = new Binder(from);
BindResult<KafkaConnectParam> bind = binder.bind("", KafkaConnectParam.clreplaced);
KafkaConnectParam kafkaConnectParam = bind.get();
kafkaService.createConnect(kafkaConnectParam);
}
17
View Source File : WebClientFeaturesTest.java
License : Apache License 2.0
Project Creator : kptfh
License : Apache License 2.0
Project Creator : kptfh
@Test
public void shouldMirrorResourceReactiveWithZeroCopying() {
byte[] data = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ByteArrayResource resource = new ByteArrayResource(data);
Flux<DataBuffer> returned = client.mirrorResourceReactiveWithZeroCopying(resource);
replacedertThat(DataBufferUtils.join(returned).block().asByteBuffer()).isEqualTo(wrap(data));
}
17
View Source File : GrantOfferLetterControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testDownloadUnsignedGrantOfferLetter() throws Exception {
FileEntryResource fileDetails = newFileEntryResource().withName("A name").build();
ByteArrayResource fileContents = new ByteArrayResource("My content!".getBytes());
when(grantOfferLetterService.getGrantOfferFile(123L)).thenReturn(Optional.of(fileContents));
when(grantOfferLetterService.getGrantOfferFileDetails(123L)).thenReturn(Optional.of(fileDetails));
MvcResult result = mockMvc.perform(get("/project/{projectId}/offer/download", 123L)).andExpect(status().isOk()).andReturn();
replacedertEquals("My content!", result.getResponse().getContentreplacedtring());
replacedertEquals("inline; filename=\"" + fileDetails.getName() + "\"", result.getResponse().getHeader("Content-Disposition"));
}
17
View Source File : GrantOfferLetterControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testDownloadAnnexFileSuccess() throws Exception {
Long projectId = 1L;
FileEntryResource annexFileEntryResource = FileEntryResourceBuilder.newFileEntryResource().withName("annex-file.pdf").build();
byte[] content = "HelloWorld".getBytes();
ByteArrayResource annexByteArrayResource = new ByteArrayResource(content);
when(grantOfferLetterService.getAdditionalContractFile(projectId)).thenReturn(Optional.of(annexByteArrayResource));
when(grantOfferLetterService.getAdditionalContractFileDetails(projectId)).thenReturn(Optional.of(annexFileEntryResource));
MvcResult result = mockMvc.perform(get("/project/" + projectId + "/grant-offer-letter/additional-contract")).andExpect(status().isOk()).andReturn();
MockHttpServletResponse response = result.getResponse();
replacedertEquals("HelloWorld", response.getContentreplacedtring());
replacedertEquals("inline; filename=\"annex-file.pdf\"", response.getHeader("Content-Disposition"));
replacedertEquals(10, response.getContentLength());
}
17
View Source File : GrantOfferLetterControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testDownloadSignedGrantOfferLetterSuccess() throws Exception {
Long projectId = 1L;
FileEntryResource annexFileEntryResource = FileEntryResourceBuilder.newFileEntryResource().withName("annex-file.pdf").build();
byte[] content = "HelloWorld".getBytes();
ByteArrayResource annexByteArrayResource = new ByteArrayResource(content);
when(grantOfferLetterService.getSignedGrantOfferLetterFile(projectId)).thenReturn(Optional.of(annexByteArrayResource));
when(grantOfferLetterService.getSignedGrantOfferLetterFileDetails(projectId)).thenReturn(Optional.of(annexFileEntryResource));
MvcResult result = mockMvc.perform(get("/project/" + projectId + "/grant-offer-letter/signed-grant-offer-letter")).andExpect(status().isOk()).andReturn();
MockHttpServletResponse response = result.getResponse();
replacedertEquals("HelloWorld", response.getContentreplacedtring());
replacedertEquals("inline; filename=\"annex-file.pdf\"", response.getHeader("Content-Disposition"));
replacedertEquals(10, response.getContentLength());
}
17
View Source File : FinanceCheckController.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CHECKS_SECTION')")
@GetMapping("/organisation/{organisationId}/jes-file")
@ResponseBody
public ResponseEnreplacedy<ByteArrayResource> downloadJesFile(@PathVariable("projectId") final Long projectId, @PathVariable("organisationId") Long organisationId) {
ProjectResource project = projectService.getById(projectId);
ApplicationResource application = applicationService.getById(project.getApplication());
ApplicationFinanceResource applicationFinanceResource = financeService.getApplicationFinanceByApplicationIdAndOrganisationId(application.getId(), organisationId);
if (applicationFinanceResource.getFinanceFileEntry() != null) {
FileEntryResource jesFileEntryResource = financeService.getFinanceEntry(applicationFinanceResource.getFinanceFileEntry()).getSuccess();
ByteArrayResource jesByteArrayResource = financeService.getFinanceDoreplacedentByApplicationFinance(applicationFinanceResource.getId()).getSuccess();
return FileDownloadControllerUtils.getFileResponseEnreplacedy(jesByteArrayResource, jesFileEntryResource);
}
return new ResponseEnreplacedy<>(null, null, HttpStatus.NO_CONTENT);
}
See More Examples