@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 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()); } }
/** * Create an Activation Framework DataSource for the given InputStreamSource. * @param inputStreamSource the InputStreamSource (typically a Spring Resource) * @param contentType the content type * @param name the name of the DataSource * @return the Activation Framework DataSource */ protected DataSource createDataSource( final InputStreamSource inputStreamSource, final String contentType, final String name) { return new DataSource() { @Override public InputStream getInputStream() throws IOException { return inputStreamSource.getInputStream(); } @Override public OutputStream getOutputStream() { throw new UnsupportedOperationException("Read-only javax.activation.DataSource"); } @Override public String getContentType() { return contentType; } @Override public String getName() { return name; } }; }
/** * Create an Activation Framework DataSource for the given InputStreamSource. * @param inputStreamSource the InputStreamSource (typically a Spring Resource) * @param contentType the content type * @param name the name of the DataSource * @return the Activation Framework DataSource */ protected DataSource createDataSource( final InputStreamSource inputStreamSource, final String contentType, final String name) { return new DataSource() { public InputStream getInputStream() throws IOException { return inputStreamSource.getInputStream(); } public OutputStream getOutputStream() { throw new UnsupportedOperationException("Read-only javax.activation.DataSource"); } public String getContentType() { return contentType; } public String getName() { return name; } }; }
public EmailAttachment(InputStreamSource data, String contentType, String filename) { requireNonNull(data); requireNonNull(contentType); requireNonNull(filename); this.data = data; this.contentType = contentType; this.filename = filename; }
@Override public Credential fromRequestBody(final MultiValueMap<String, String> requestBody) { final String cert = requestBody.getFirst(CERTIFICATE); LOGGER.debug("Certificate in the request body: [{}]", cert); if (StringUtils.isBlank(cert)) { return super.fromRequestBody(requestBody); } final InputStream is = new ByteArrayInputStream(cert.getBytes()); final InputStreamSource iso = new InputStreamResource(is); final X509Certificate certificate = CertUtils.readCertificate(iso); final X509CertificateCredential credential = new X509CertificateCredential(new X509Certificate[]{certificate}); credential.setCertificate(certificate); return credential; }
/** * Read certificate. * * @param resource the resource to read the cert from * @return the x 509 certificate */ public static X509Certificate readCertificate(final InputStreamSource resource) { try (InputStream in = resource.getInputStream()) { return CertUtil.readCertificate(in); } catch (final IOException e) { throw new RuntimeException("Error reading certificate " + resource, e); } }
public List<PhotoLocationKeyword> keywordsFromFile(InputStreamSource source, Course course) throws IOException{ return keywordsFromFile(source).stream().map((keyword) -> { keyword.setCourse(course); return keyword; }).collect(Collectors.toList()); }
/** * Create a solution for an {@link ImageCompletionExercise} from it's id and the CSV source * @param courseId * @param source * @param dryRun won't save anything. just for testing * @return the persisted {@link ImageCompletionSolution} * @throws BuenOjoCSVParserException * @throws BuenOjoInconsistencyException */ public ImageCompletionSolution createSolutionForExerciseFromCSVSource(ImageCompletionExercise exercise, InputStreamSource source, Boolean dryRun) throws BuenOjoCSVParserException, BuenOjoInconsistencyException { List<Tag> tagList = tagRepository.findByCourseOrderByNumber(exercise.getCourse()); if (tagList == null || tagList.size() == 0) { throw new BuenOjoInconsistencyException("No hay etiquetas cargadas para el curso ["+exercise.getCourse()+"]"); } ImageCompletionSolution solution = new ImageCompletionSolution(); ImageCompletionSolutionCSVParser parser = new ImageCompletionSolutionCSVParser(source, tagList); List<TagPair> tagPairs = null; try { tagPairs = parser.parse(); } catch (IOException e) { throw new BuenOjoCSVParserException(e.getMessage()); } tagPairRepository.save(tagPairs); solutionRepository.save(solution); HashSet<Tag> tagSet = new HashSet<>(); solution.setTagPairs(new HashSet<TagPair>(tagPairs)); for (TagPair tagPair : tagPairs) { tagPair.setImageCompletionSolution(solution); tagSet.add(tagPair.getTag()); } solution.setImageCompletionExercise(exercise); solutionRepository.save(solution); exercise.setImageCompletionSolution(solution); exercise.setTags(tagSet); imageCompletionExerciseRepository.save(exercise); return solution; }
public void parseAndInject(PhotoLocationExercise exercise, InputStreamSource inputStreamSource) throws BuenOjoCSVParserException, IOException{ CSVParser parser = CSVFormat.RFC4180.withHeader().withDelimiter(',').withAllowMissingColumnNames(true).parse(new InputStreamReader(inputStreamSource.getInputStream())); List<CSVRecord> records = parser.getRecords(); if (records.size() > 1) { throw new BuenOjoCSVParserException("El archivo contiene más de un ejercicio"); } if (records.size() == 0) { throw new BuenOjoCSVParserException("El archivo de ejericio es inválido"); } CSVRecord record = records.get(0); String name = record.get(MetadataColumns.name); String description = record.get(MetadataColumns.description); String difficulty = record.get(MetadataColumns.difficulty); String seconds = record.get(MetadataColumns.seconds); String totalScore = record.get(MetadataColumns.totalScore.ordinal()); String imageName = record.get(MetadataColumns.imageName.ordinal()); exercise.setDescription(description); exercise.setName(name); exercise.setDifficulty(difficultyFromString(difficulty)); exercise.setTotalTimeInSeconds(new Integer(seconds)); exercise.setTotalScore(new Float(totalScore)); exercise.setExtraPhotosCount(3); List<PhotoLocationImage> imgs = photoLocationImageRepository.findAll(); Optional<PhotoLocationImage> opt = imgs.stream().filter(p -> p.getImage().getName().equals(imageName)).collect(Collectors.toList()).stream().findFirst(); if (!opt.isPresent()){ throw new BuenOjoCSVParserException("la imagen '"+imageName+"' no existe en la base de datos"); } PhotoLocationImage img = opt.get(); img.setKeywords(exercise.getLandscapeKeywords()); photoLocationImageRepository.save(img); exercise.setTerrainPhoto(img); }
public ImageCompletionTipCSVParser (InputStreamSource source, Course course, TagRepository tagRepository, ImageResourceRepository imageRepository){ this.inputStreamSource = source; this.course = course; this.tagRepository = tagRepository; this.imageRepository = imageRepository; }
private void sendSimpleMailWithAttachment(final String fromAddress, final List<String> toAddress, final List<String> ccAddress, final String subject, final String mailContent, final List<MultipartFile> attachFiles) { mailSender.send(new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); messageHelper.setFrom(fromAddress); messageHelper.setTo(toAddress.toArray(new String[toAddress.size()])); if (ccAddress != null && ccAddress.size() > 0) { messageHelper.setCc(ccAddress.toArray(new String[ccAddress.size()])); } messageHelper.setSubject(subject); messageHelper.setText(mailContent); for (final MultipartFile attachFile : attachFiles) { // determines if there is an upload file, attach it to the e-mail if (attachFile != null) { String attachName = attachFile.getOriginalFilename(); messageHelper.addAttachment(attachName, new InputStreamSource() { @Override public InputStream getInputStream() throws IOException { return attachFile.getInputStream(); } }); } else { log.info("Attached file is Empty. Skipping the file " + attachFile + " in mail."); } } } }); }
/** * 暂时只支持这几种类型 * * @param paramType * @return dummy */ public static boolean isMutlipart(Class paramType) { return (byte[].class == paramType || InputStream.class.isAssignableFrom(paramType) || Reader.class.isAssignableFrom(paramType) || File.class.isAssignableFrom(paramType) || InputStreamSource.class.isAssignableFrom(paramType)); }
/** * 处理附件 * * @param emailVo * @param msgHelper * @throws javax.mail.MessagingException */ private void handlerAttachments(EmailVo emailVo, MimeMessageHelper msgHelper) throws MessagingException { if (emailVo.getAttachmentVos() != null) {// 检查附件 for (AttachmentVo attachmentVo : emailVo.getAttachmentVos()) { File attachment = attachmentVo.getAttachment(); if (attachment == null) { InputStream inputStream = attachmentVo.getAttachmentInputStream(); if (attachmentVo.getAttachmentName() == null) { attachmentVo.setAttachmentName(new Date().toString()); } InputStreamSource inputStreamSource = new InputStreamResource(inputStream); msgHelper.addAttachment(attachmentVo.getAttachmentName(), inputStreamSource); } else { if (attachmentVo.getAttachmentName() == null) { attachmentVo.setAttachmentName(attachment.getName()); } try { msgHelper.addAttachment(MimeUtility.encodeWord(attachmentVo.getAttachmentName()), attachment); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } }
@Override public void sendMessage(String emailFrom, String emailTo, String subject, String template, HashMap<String, Object> staticResources, HashMap<String, Object> dynamicResources) throws Exception { String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, "UTF-8", dynamicResources); // configure mail helper MimeMessage message = javaMailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); // configure multipart email configuration: css and images inside helper.setFrom(emailFrom); helper.setTo(emailTo); helper.setSubject(subject); helper.setText(text, true); // configure html email Iterator<String> iter = staticResources.keySet().iterator(); while(iter.hasNext()) { String key = (String)iter.next(); InputStreamSource val = (InputStreamSource)staticResources.get(key); helper.addInline(key, val, "text/html"); } // send message in OSGi envirotment ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(javax.mail.Session.class.getClassLoader()); javaMailSender.send(message); } catch (Exception e) { throw new Exception(e); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } }
public Attachment(String fileName, InputStreamSource inputStreamSource, String contentType) { this.fileName = fileName; this.inputStreamSource = inputStreamSource; this.contentType = contentType; }
public InputStreamSource getInputStreamSource() { return inputStreamSource; }
public void setInputStreamSource(InputStreamSource inputStreamSource) { this.inputStreamSource = inputStreamSource; }
public InputStreamSource getData() { return data; }
public List<PhotoLocationKeyword> keywordsFromFile(InputStreamSource source) throws IOException{ PhotoLocationKeywordsParser parser = new PhotoLocationKeywordsParser(source); List<PhotoLocationKeyword> keywords = parser.parse(); return keywords; }
public ImageCompletionSolution createSolutionForExerciseIdFromCSVSource(Long exerciseId, InputStreamSource source) throws BuenOjoCSVParserException, BuenOjoInconsistencyException { ImageCompletionExercise exercise = imageCompletionExerciseRepository.findOne(exerciseId); return createSolutionForExerciseFromCSVSource(exercise, source); }
public PhotoLocationSightPairCSVParser(InputStreamSource inputStreamSource) { super(); this.inputStreamSource = inputStreamSource; }
public ImageCompletionSolutionCSVParser (InputStreamSource source, List <Tag> tagList){ this.inputStreamSource = source; this.tagList = tagList; }
public PhotoLocationExtraPhotosKeywordCSVParser(InputStreamSource source) { this.inputStreamSource = source; }
public PhotoLocationLandscapeLevelsCSVParser(InputStreamSource inputStreamSource) { super(); this.inputStreamSource = inputStreamSource; }
public PhotoLocationKeywordsParser(InputStreamSource source) { this.inputStreamSource = source; }
@Test public void testSolutionParser () { String tagPairList = "\"id\",\"etiqueta\"\n\"0\",\"1\"\n\"1\",\"20\"\n\"2\",\"26\"\n\"3\",\"19\"\n\"4\",\"30\""; InputStreamSource source =new ByteArrayResource(tagPairList.getBytes(StandardCharsets.UTF_8)); ImageCompletionSolutionCSVParser parser = new ImageCompletionSolutionCSVParser(source, tags); try { List<TagPair> tagPair = parser.parse(); assertThat(tagPair).isNotNull(); assertThat(tagPair.size()).isEqualTo(5); } catch (IOException e) { Fail.fail(e.getMessage()); } }
private void sendVelocityTemplateMailWithAttachment(final String fromAddress, final List<String> toAddress, final List<String> ccAddress, final String subject, final Map<String, Object> modelForMailContent, final String templateName, final boolean isTemplateHtml, final List<MultipartFile> attachFiles) throws Exception { MimeMessagePreparator preparator = new MimeMessagePreparator() { @Override public void prepare(MimeMessage mimeMessage) throws Exception { MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject(subject); helper.setFrom(fromAddress); helper.setTo(toAddress.toArray(new String[toAddress.size()])); if (ccAddress != null && ccAddress.size() > 0) { helper.setCc(ccAddress.toArray(new String[ccAddress.size()])); } String text = geVelocityTemplateContent(modelForMailContent, templateName); log.debug("Template Name :" + templateName + "Template content : " + text); // use the true flag to indicate you need a multipart message helper.setText(text, isTemplateHtml); for (final MultipartFile attachFile : attachFiles) { // determines if there is an upload file, attach it to the e-mail if (attachFile != null) { log.info("inside attachFile not null block"); String attachName = attachFile.getOriginalFilename(); helper.addAttachment(attachName, new InputStreamSource() { @Override public InputStream getInputStream() throws IOException { return attachFile.getInputStream(); } }); } else { log.info("Attached file is Empty. Skipping the file " + attachFile + " in mail."); } } } }; try { mailSender.send(preparator); log.debug("Template Mail with attachment successfully sent !! \nFrom Addres: " + fromAddress + " To Address: " + toAddress + " CC Address: " + ccAddress + "\n Subject: " + subject); } catch (MailException ex) { log.error("Error Sending template Email: " + ex); throw new Exception("Error Sending Velocity Template mail with attachment. " + ex.getMessage(), ex); } }
public Map<String, InputStreamSource> getAttachments() { return attachments; }
public void setAttachments(Map<String, InputStreamSource> attachments) { this.attachments = attachments; }
public void addAttachment(String name, InputStreamSource attachment) { attachments.put(name, attachment); }
public Map<String, InputStreamSource> getInlines() { return inlines; }
public void setInlines(Map<String, InputStreamSource> inlines) { this.inlines = inlines; }
public void addInline(String name, InputStreamSource inline) { inlines.put(name, inline); }
public void add(String filename, InputStreamSource source) throws MessagingException { mimeMessageHelper.addAttachment(filename, source); }