@ApiOperation("Returns a Defendant Response copy for a given claim external id") @GetMapping( value = "/defendantResponseCopy/{externalId}", produces = MediaType.APPLICATION_PDF_VALUE ) public ResponseEntity<ByteArrayResource> defendantResponseCopy( @ApiParam("Claim external id") @PathVariable("externalId") @NotBlank String externalId ) { byte[] pdfDocument = documentsService.generateDefendantResponseCopy(externalId); return ResponseEntity .ok() .contentLength(pdfDocument.length) .body(new ByteArrayResource(pdfDocument)); }
@ApiOperation("Returns a sealed claim copy for a given claim external id") @GetMapping( value = "/legalSealedClaim/{externalId}", produces = MediaType.APPLICATION_PDF_VALUE ) public ResponseEntity<ByteArrayResource> legalSealedClaim( @ApiParam("Claim external id") @PathVariable("externalId") @NotBlank String externalId, @RequestHeader(HttpHeaders.AUTHORIZATION) String authorisation ) { byte[] pdfDocument = documentsService.getLegalSealedClaim(externalId, authorisation); return ResponseEntity .ok() .contentLength(pdfDocument.length) .body(new ByteArrayResource(pdfDocument)); }
@ApiOperation("Returns a County Court Judgement for a given claim external id") @GetMapping( value = "/ccj/{externalId}", produces = MediaType.APPLICATION_PDF_VALUE ) public ResponseEntity<ByteArrayResource> countyCourtJudgement( @ApiParam("Claim external id") @PathVariable("externalId") @NotBlank String externalId ) { byte[] pdfDocument = documentsService.generateCountyCourtJudgement(externalId); return ResponseEntity .ok() .contentLength(pdfDocument.length) .body(new ByteArrayResource(pdfDocument)); }
@ApiOperation("Returns a settlement agreement for a given claim external id") @GetMapping( value = "/settlementAgreement/{externalId}", produces = MediaType.APPLICATION_PDF_VALUE ) public ResponseEntity<ByteArrayResource> settlementAgreement( @ApiParam("Claim external id") @PathVariable("externalId") @NotBlank String externalId ) { byte[] pdfDocument = documentsService.generateSettlementAgreement(externalId); return ResponseEntity .ok() .contentLength(pdfDocument.length) .body(new ByteArrayResource(pdfDocument)); }
@ApiOperation("Returns a Defendant Response receipt for a given claim external id") @GetMapping( value = "/defendantResponseReceipt/{externalId}", produces = MediaType.APPLICATION_PDF_VALUE ) public ResponseEntity<ByteArrayResource> defendantResponseReceipt( @ApiParam("Claim external id") @PathVariable("externalId") @NotBlank String externalId ) { byte[] pdfDocument = documentsService.generateDefendantResponseReceipt(externalId); return ResponseEntity .ok() .contentLength(pdfDocument.length) .body(new ByteArrayResource(pdfDocument)); }
@ApiOperation("Returns a Claim Issue receipt for a given claim external id") @GetMapping( value = "/claimIssueReceipt/{externalId}", produces = MediaType.APPLICATION_PDF_VALUE ) public ResponseEntity<ByteArrayResource> claimIssueReceipt( @ApiParam("Claim external id") @PathVariable("externalId") @NotBlank String externalId ) { byte[] pdfDocument = documentsService.generateClaimIssueReceipt(externalId); return ResponseEntity .ok() .contentLength(pdfDocument.length) .body(new ByteArrayResource(pdfDocument)); }
/** * Gets x509 cRL from attribute. Retrieves the binary attribute value, * decodes it to base64, and fetches it as a byte-array resource. * * @param aval the attribute, which may be null if it's not found * @return the x 509 cRL from attribute * @throws Exception if attribute not found or could could not be decoded. */ protected X509CRL fetchX509CRLFromAttribute(final LdapAttribute aval) throws Exception { if (aval != null) { final byte[] val = aval.getBinaryValue(); if (val == null || val.length == 0) { throw new CertificateException("Empty attribute. Can not download CRL from ldap"); } final byte[] decoded64 = CompressionUtils.decodeBase64ToByteArray(val); if (decoded64 == null) { throw new CertificateException("Could not decode the attribute value to base64"); } logger.debug("Retrieved CRL from ldap as byte array decoded in base64. Fetching..."); return super.fetch(new ByteArrayResource(decoded64)); } throw new CertificateException("Attribute not found. Can not retrieve CRL"); }
/** * Gets x509 cRL from attribute. Retrieves the binary attribute value, * decodes it to base64, and fetches it as a byte-array resource. * * @param aval the attribute, which may be null if it's not found * @return the x 509 cRL from attribute * @throws IOException the exception thrown if resources cant be fetched * @throws CRLException the exception thrown if resources cant be fetched * @throws CertificateException if connection to ldap fails, or attribute to get the revocation list is unavailable */ protected X509CRL fetchX509CRLFromAttribute(final LdapAttribute aval) throws CertificateException, IOException, CRLException { if (aval != null && aval.isBinary()) { final byte[] val = aval.getBinaryValue(); if (val == null || val.length == 0) { throw new CertificateException("Empty attribute. Can not download CRL from ldap"); } final byte[] decoded64 = EncodingUtils.decodeBase64(val); if (decoded64 == null) { throw new CertificateException("Could not decode the attribute value to base64"); } LOGGER.debug("Retrieved CRL from ldap as byte array decoded in base64. Fetching..."); return super.fetch(new ByteArrayResource(decoded64)); } throw new CertificateException("Attribute not found. Can not retrieve CRL"); }
@Test public void test() { InputStreamSource source = new ByteArrayResource(this.expectedText.getBytes(StandardCharsets.UTF_8)); assertThat(source).isNotNull(); PhotoLocationExtraPhotosKeywordCSVParser parser = new PhotoLocationExtraPhotosKeywordCSVParser(source); assertThat(parser).isNotNull(); Map<String, List<String>> parsedMap = null; try { parsedMap = parser.parse(); } catch (IOException e) { // TODO Auto-generated catch block fail("exception on parse: "+ e.getMessage()); } assertThat(parsedMap).isNotNull(); assertThat(parsedMap.size()).isEqualTo(3); assertThat(parsedMap.keySet()).contains("DSC00305.txt","DSC00498.txt","DSC00520.txt"); List<String> photo1 = parsedMap.get("DSC00305.txt"); assertThat(photo1.size()).isEqualTo(2); assertThat(photo1.get(0)).isNotNull(); assertThat(photo1.get(0)).isEqualTo(bosque.getName()); assertThat(photo1.get(1)).isNotNull(); assertThat(photo1.get(1)).isEqualTo(montanias.getName()); }
@Test public void testTagPoolParser () throws BuenOjoCSVParserException { TagPoolCSVParser parser = new TagPoolCSVParser(new ByteArrayResource(csvString.getBytes(StandardCharsets.UTF_8))); Course course = new Course(); course.setId(new Long(1000)); try { List<Tag> tags = parser.parse(course); assertThat(tags).isNotNull().isNotEmpty(); assertThat(tags.size()).isNotZero().isEqualTo(7); assertThat(tags.get(0).getNumber()).isEqualTo(1); assertThat(tags.get(1).getNumber()).isEqualTo(2); List<TagPool> tagPool = parser.parseTagPool(); assertThat(tagPool).isNotNull().isNotEmpty(); assertThat(tagPool.size()).isNotZero().isEqualTo(11); } catch (IOException e) { Fail.fail(e.getMessage()); } }
@Test public void testKeywordParsing() { String level = "\"\",\"Niveles\",\"Paisaje\"\n\"1\",\"5:20\",\"Colinas,Llano,Veg media,Veg escasa\""; InputStreamSource source =new ByteArrayResource(level.getBytes(StandardCharsets.UTF_8)); PhotoLocationLandscapeLevelsCSVParser parser = new PhotoLocationLandscapeLevelsCSVParser(source); try { List<String> keywords = parser.parseKeywords(); assertThat(keywords).isNotNull(); assertThat(keywords.size()).isEqualTo(4); } catch (IOException | BuenOjoCSVParserException e) { fail(e.getMessage()); } }
@Test public void testLandscapeLevelParsing() { String level = "\"\",\"Niveles\",\"Paisaje\"\n\"1\",\"5:20\",\"Colinas,Llano,Veg media,Veg escasa\""; InputStreamSource source =new ByteArrayResource(level.getBytes(StandardCharsets.UTF_8)); PhotoLocationLandscapeLevelsCSVParser parser = new PhotoLocationLandscapeLevelsCSVParser(source); try { Integer[] levels = parser.parseLevels(); assertThat(levels).isNotNull(); assertThat(levels.length).isEqualTo(2); assertThat(levels[0]).isNotNull().isEqualTo(5); assertThat(levels[1]).isNotNull().isEqualTo(20); } catch (BuenOjoCSVParserException | IOException e) { fail(e.getMessage()); } }
@Override public void sendEmail(@NonNull final Mail _mail, @NonNull final String _body, @Nullable final String _attachmentFilename, @Nullable final byte[] _pdfAttachment) { try { // Prepare message using a Spring helper final MimeMessage mimeMessage = mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, (_pdfAttachment != null), StandardCharsets.UTF_8.name()); message.setSubject("Tifoon Scan Report"); message.setFrom(_mail.getSender()); message.setTo(_mail.getRecipient()); message.setText(_body, true); if (_attachmentFilename != null && _pdfAttachment != null) { message.addAttachment(_attachmentFilename, new ByteArrayResource(_pdfAttachment)); } // Send mail mailSender.send(mimeMessage); } catch (MessagingException _e) { log.error("Failed to send e-mail", _e); } }
@GetMapping("{size}/{fileName:.+}") public ResponseEntity<Resource> cut(@PathVariable String fileName, @PathVariable String size) throws IOException { try { Resource file = storageService.loadAsResource(fileName); String fileExtendName = fileName.substring(fileName.lastIndexOf(".") + 1); String[] wh = size.split("_"); int w = Integer.parseInt(wh[0]); int h = Integer.parseInt(wh[1]); return ResponseEntity .ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+fileName+"\"") .body(new ByteArrayResource(ImageUtil.compress(file.getInputStream(), fileExtendName, w, h))); } catch (IOException e) { e.printStackTrace(); return ResponseEntity .ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+fileName+"\"") .body(new ByteArrayResource(new byte[]{})); } }
private HttpEntity<MultiValueMap<String, Object>> buildRequestEntity(byte[] packaged, String notifyToken, String notifyUrl) { MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); HttpHeaders textHeaders = new HttpHeaders(); textHeaders.setContentType(MediaType.TEXT_PLAIN); HttpHeaders binaryHeaders = new HttpHeaders(); binaryHeaders.setContentDispositionFormData("file", SUBMISSION_FILENAME); map.add("file", new HttpEntity<>(new ByteArrayResource(packaged), binaryHeaders)); map.add("token", new HttpEntity<>(notifyToken, textHeaders)); map.add("notify", new HttpEntity<>(notifyUrl, textHeaders)); return new HttpEntity<>(map); }
/** * Converts the 2-dimensional byte array of file data, which includes the name of the file as * bytes followed by the byte content of the file, for all files being transmitted by Gfsh to the * GemFire Manager. * <p/> * * @param fileData a 2 dimensional byte array of files names and file content. * @return an array of Spring Resource objects encapsulating the details (name and content) of * each file being transmitted by Gfsh to the GemFire Manager. * @see org.springframework.core.io.ByteArrayResource * @see org.springframework.core.io.Resource * @see org.apache.geode.management.internal.cli.CliUtil#bytesToData(byte[][]) * @see org.apache.geode.management.internal.cli.CliUtil#bytesToNames(byte[][]) */ public static Resource[] convert(final byte[][] fileData) { if (fileData != null) { final String[] fileNames = CliUtil.bytesToNames(fileData); final byte[][] fileContent = CliUtil.bytesToData(fileData); final List<Resource> resources = new ArrayList<Resource>(fileNames.length); for (int index = 0; index < fileNames.length; index++) { final String filename = fileNames[index]; resources.add(new ByteArrayResource(fileContent[index], String.format("Contents of JAR file (%1$s).", filename)) { @Override public String getFilename() { return filename; } }); } return resources.toArray(new Resource[resources.size()]); } return new Resource[0]; }
@APIDeprecated( name = "/api/v1/pdf-generator/html", docLink = "https://github.com/hmcts/cmc-pdf-service#standard-api", expiryDate = "2018-02-08", note = "Please use `/pdfs` instead.") @ApiOperation("Returns a PDF file generated from provided HTML/Twig template and placeholder values") @PostMapping( value = "/html", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces = MediaType.APPLICATION_PDF_VALUE ) public ResponseEntity<ByteArrayResource> generateFromHtml( @ApiParam("A HTML/Twig file. CSS should be embedded, images should be embedded using Data URI scheme") @RequestParam("template") MultipartFile template, @ApiParam("A JSON structure with values for placeholders used in template file") @RequestParam("placeholderValues") String placeholderValues ) { log.debug("Received a PDF generation request"); byte[] pdfDocument = htmlToPdf.convert(asBytes(template), asMap(placeholderValues)); log.debug("PDF generated"); return ResponseEntity .ok() .contentLength(pdfDocument.length) .body(new ByteArrayResource(pdfDocument)); }
@Override public void send(NotificationType type, Recipient recipient, String attachment) throws MessagingException, IOException { final String subject = env.getProperty(type.getSubject()); final String text = MessageFormat.format(env.getProperty(type.getText()), recipient.getAccountName()); MimeMessage message = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setTo(recipient.getEmail()); helper.setSubject(subject); helper.setText(text); if (StringUtils.hasLength(attachment)) { helper.addAttachment(env.getProperty(type.getAttachment()), new ByteArrayResource(attachment.getBytes())); } mailSender.send(message); log.info("{} email notification has been send to {}", type, recipient.getEmail()); }
@Override protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { WxMediaResource wxMediaResource = new WxMediaResource(inputMessage); if (wxMediaResource.isUrlMedia() && !clazz.isAssignableFrom(WxMediaResource.class)) { throw new WxApiException("不支持的返回类型,接口返回了url"); } if (InputStreamResource.class == clazz) { return new InputStreamResource(wxMediaResource.getInputStream()); } else if (clazz.isAssignableFrom(WxMediaResource.class)) { return wxMediaResource; } else if (clazz.isAssignableFrom(ByteArrayResource.class)) { return new ByteArrayResource(wxMediaResource.getBody()); } else if (clazz.isAssignableFrom(FileSystemResource.class)) { return new FileSystemResource(wxMediaResource.getFile()); } // else if (clazz.isAssignableFrom(File.class)) { // return wxMediaResource.getFile(); // } throw new WxApiException("不支持的返回类型"); }
@Test @SuppressWarnings("unchecked") public void flattenedMapIsSameAsPropertiesButOrdered() { this.processor.setResources(new ByteArrayResource( "foo: bar\nbar:\n spam: bucket".getBytes())); this.processor.process(new MatchCallback() { @Override public void process(Properties properties, Map<String, Object> map) { assertEquals("bucket", properties.get("bar.spam")); assertEquals(2, properties.size()); Map<String, Object> flattenedMap = processor.getFlattenedMap(map); assertEquals("bucket", flattenedMap.get("bar.spam")); assertEquals(2, flattenedMap.size()); assertTrue(flattenedMap instanceof LinkedHashMap); Map<String, Object> bar = (Map<String, Object>) map.get("bar"); assertEquals("bucket", bar.get("spam")); } }); }
@Test public void testFirstFound() throws Exception { this.factory.setResolutionMethod(YamlProcessor.ResolutionMethod.FIRST_FOUND); this.factory.setResources(new AbstractResource() { @Override public String getDescription() { return "non-existent"; } @Override public InputStream getInputStream() throws IOException { throw new IOException("planned"); } }, new ByteArrayResource("foo:\n spam: bar".getBytes())); assertEquals(1, this.factory.getObject().size()); }
protected void createTable() { StringBuilder sb = new StringBuilder(); sb.append("CREATE TABLE if not exists `leopard_domainwhitelist` ("); sb.append("`domain` varchar(50) NOT NULL DEFAULT '',"); sb.append("`username` varchar(50) NOT NULL DEFAULT '',"); sb.append("`posttime` datetime NOT NULL DEFAULT '1970-01-01 00:00:00',"); sb.append("`comment` varchar(255) NOT NULL DEFAULT '',"); sb.append("PRIMARY KEY (`domain`)"); sb.append(");"); String sql = sb.toString(); Resource scripts = new ByteArrayResource(sql.getBytes()); DatabasePopulator populator = new ResourceDatabasePopulator(scripts); try { DatabasePopulatorUtils.execute(populator, jdbcTemplate.getDataSource()); } catch (ScriptStatementFailedException e) { } }
/** * Creates a multivalue map containing a file with a name and a caption */ protected MultiValueMap<String, Object> createUploadMap(String filename, String caption) { MultiValueMap<String, Object> map = new LinkedMultiValueMap<>(); byte[] bytes = filename.getBytes(); map.add("name", filename); map.add("caption", caption); ByteArrayResource file = new ByteArrayResource(bytes){ @Override public String getFilename(){ return filename; } }; map.add("file", file); return map; }
/** * Converts the 2-dimensional byte array of file data, which includes the name of the file as bytes followed by * the byte content of the file, for all files being transmitted by Gfsh to the GemFire Manager. * <p/> * @param fileData a 2 dimensional byte array of files names and file content. * @return an array of Spring Resource objects encapsulating the details (name and content) of each file being * transmitted by Gfsh to the GemFire Manager. * @see org.springframework.core.io.ByteArrayResource * @see org.springframework.core.io.Resource * @see com.gemstone.gemfire.management.internal.cli.CliUtil#bytesToData(byte[][]) * @see com.gemstone.gemfire.management.internal.cli.CliUtil#bytesToNames(byte[][]) */ public static Resource[] convert(final byte[][] fileData) { if (fileData != null) { final String[] fileNames = CliUtil.bytesToNames(fileData); final byte[][] fileContent = CliUtil.bytesToData(fileData); final List<Resource> resources = new ArrayList<Resource>(fileNames.length); for (int index = 0; index < fileNames.length; index++) { final String filename = fileNames[index]; resources.add(new ByteArrayResource(fileContent[index], String.format("Contents of JAR file (%1$s).", filename)) { @Override public String getFilename() { return filename; } }); } return resources.toArray(new Resource[resources.size()]); } return new Resource[0]; }
@Deprecated private Foo bindFoo(final String values) throws Exception { Properties properties = PropertiesLoaderUtils .loadProperties(new ByteArrayResource(values.getBytes())); if (this.usePropertySource) { MutablePropertySources propertySources = new MutablePropertySources(); propertySources.addFirst(new PropertiesPropertySource("test", properties)); this.factory.setPropertySources(propertySources); } else { this.factory.setProperties(properties); } this.factory.afterPropertiesSet(); return this.factory.getObject(); }
/** * Determines the name to be used for the provided resource. * * @param resource * the resource to get the name for * @return the name of the resource */ protected String determineResourceName(final Resource resource) { String resourceName = null; if (resource instanceof ContextResource) { resourceName = ((ContextResource) resource).getPathWithinContext(); } else if (resource instanceof ByteArrayResource) { resourceName = resource.getDescription(); } else { try { resourceName = resource.getFile().getAbsolutePath(); } catch (IOException e) { resourceName = resource.getFilename(); } } return resourceName; }
@Bean @Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT) public MessageProcessor<?> transformer() { String language = this.properties.getLanguage(); String script = this.properties.getScript(); logger.info(String.format("Input script is '%s', language is '%s'", script, language)); Resource scriptResource = new ByteArrayResource(decodeScript(script).getBytes()) { // TODO until INT-3976 @Override public String getFilename() { // Only the groovy script processor enforces this requirement for a name return "StaticScript"; } }; return Scripts.script(scriptResource) .lang(language) .variableGenerator(this.scriptVariableGenerator) .get(); }
/** * 注册bean * * @author gaoxianglong * * @param nodePathValue * value 从配置中心订阅的配置信息 * * @param resourceType * 注册中心类型 * * @return void */ public static void register(String value, String resourceType) { if (null == aContext || null == value) return; ConfigurableApplicationContext cfgContext = (ConfigurableApplicationContext) aContext; DefaultListableBeanFactory beanfactory = (DefaultListableBeanFactory) cfgContext.getBeanFactory(); /* * 将配置中心获取的配置信息与当前上下文中的ioc容器进行合并,不需要手动移除之前的bean, * 调用loadBeanDefinitions()方法时会进行自动移除 */ new XmlBeanDefinitionReader(beanfactory).loadBeanDefinitions(new ByteArrayResource(value.getBytes())); final String defaultBeanName = "jdbcTemplate"; String[] beanNames = beanfactory.getBeanDefinitionNames(); for (String beanName : beanNames) { /* 替换上下文中缺省beanName为jdbcTemplate的JdbcTemplate的引用 */ if (defaultBeanName.equals(beanName)) { GetJdbcTemplate.setJdbcTemplate((JdbcTemplate) beanfactory.getBean(defaultBeanName)); } else { /* 实例化所有所有未实例化的bean */ beanfactory.getBean(beanName); } } }
@Test public void fetchingImageShouldWork() { given(imageService.findOneImage(any())) .willReturn(Mono.just( new ByteArrayResource("data".getBytes()))); webClient .get().uri("/images/alpha.png/raw") .exchange() .expectStatus().isOk() .expectBody(String.class).isEqualTo("data"); verify(imageService).findOneImage("alpha.png"); verifyNoMoreInteractions(imageService); }
public byte[] downloadDocument(String authorisation, String documentSelfPath) { Document documentMetadata = documentMetadataDownloadClient.getDocumentMetadata(authorisation, documentSelfPath); ResponseEntity<Resource> responseEntity = documentDownloadClient.downloadBinary(authorisation, URI.create(documentMetadata.links.binary.href).getPath()); ByteArrayResource resource = (ByteArrayResource) responseEntity.getBody(); return resource.getByteArray(); }