Example usage for org.springframework.core.io ByteArrayResource ByteArrayResource

List of usage examples for org.springframework.core.io ByteArrayResource ByteArrayResource

Introduction

In this page you can find the example usage for org.springframework.core.io ByteArrayResource ByteArrayResource.

Prototype

public ByteArrayResource(byte[] byteArray) 

Source Link

Document

Create a new ByteArrayResource .

Usage

From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializerTests.java

@Test
public void testLoadServletConfiguredResource() throws Exception {

    Mockito.when(servletConfig.getInitParameter("environmentConfigLocations")).thenReturn("foo.yml");
    Mockito.when(context.getResource(Matchers.eq("foo.yml")))
            .thenReturn(new ByteArrayResource("foo: bar\nspam:\n  foo: baz".getBytes()));

    initializer.initialize(context);/*from w  w  w.  j  a  va2 s. co m*/

    assertEquals("bar", environment.getProperty("foo"));
    assertEquals("baz", environment.getProperty("spam.foo"));

}

From source file:com.wooki.test.unit.ConversionsTest.java

@Test(enabled = true)
public void testAPTConversion() {
    String result = /*
                     * generator .adaptContent(
                     */"<h2>SubTitle</h2><p>Lorem ipsum</p><h3>SubTitle2</h3><p>Lorem ipsum</p>"/* ) */;

    Resource resource = new ByteArrayResource(result.getBytes());
    InputStream xhtml = toXHTMLConvertor.performTransformation(resource);
    logger.debug("Document to xhtml ok");
    InputStream apt = toAPTConvertor.performTransformation(new InputStreamResource(xhtml));
    logger.debug("xhtml to apt ok");
    File aptFile;//  w  w  w.j  a va  2s .  c o  m
    try {
        aptFile = File.createTempFile("wooki", ".apt");
        FileOutputStream fos = new FileOutputStream(aptFile);
        logger.debug("APT File is " + aptFile.getAbsolutePath());
        byte[] content = null;
        int available = 0;
        while ((available = apt.available()) > 0) {
            content = new byte[available];
            apt.read(content);
            fos.write(content);
        }
        fos.flush();
        fos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.cloudfoundry.identity.uaa.config.YamlPropertiesFactoryBeanTests.java

@Test
public void testLoadNull() throws Exception {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(new Resource[] { new ByteArrayResource("foo: bar\nspam:".getBytes()) });
    Properties properties = factory.getObject();
    assertEquals("bar", properties.get("foo"));
    assertEquals("", properties.get("spam"));
}

From source file:ch.tatool.core.module.initializer.SpringExecutorInitializer.java

@SuppressWarnings("unchecked")
protected Map<String, DataExporter> getModuleExporters(String configurationXML) {
    // try loading the configuration
    XmlBeanFactory beanFactory = null;// ww w  . j  a v a  2 s. c  om
    try {
        beanFactory = new XmlBeanFactory(new ByteArrayResource(configurationXML.getBytes()));
    } catch (BeansException be) {
        logger.error("Unable to load Tatool file.", be);
        throw new RuntimeException("Unable to load Tatool file.", be);
    }

    // see whether we have properties
    if (beanFactory.containsBean("moduleExporters")) {
        Map<String, DataExporter> exporters = (Map<String, DataExporter>) beanFactory
                .getBean("moduleExporters");
        return exporters;
    } else {
        return Collections.emptyMap();
    }
}

From source file:org.jasig.portlet.blackboardvcportlet.service.impl.MailTemplateServiceImpl.java

public void sendMail(final MailTask mt) {
    try {/* w ww.jav  a2 s.  com*/
        MimeMessagePreparator messagePreparator = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true);

                if (mt.getMeetingInvite() != null) {
                    CalendarOutputter outputter = new CalendarOutputter();
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    outputter.setValidating(false);
                    outputter.output(mt.getMeetingInvite(), os);

                    message.addAttachment("invite.ics", new ByteArrayResource(os.toByteArray()));
                }

                message.setFrom(mt.getFrom() != null ? mt.getFrom() : defaultFromAddress);

                if (mt.getTo() != null) {
                    String[] toArray = mt.getTo().toArray(new String[mt.getTo().size()]);
                    message.setTo(toArray);
                }
                if (mt.getSubject() != null) {
                    message.setSubject(mt.getSubject());
                } else {
                    switch (mt.getTemplate()) {
                    case MODERATOR:
                        message.setSubject(moderatorSubject);
                        break;
                    case INTERNAL_PARTICIPANT:
                        message.setSubject(internalParticipantSubject);
                        break;
                    case EXTERNAL_PARTICIPANT:
                        message.setSubject(externalParticipantSubject);
                        break;
                    case SESSION_DELETION:
                        message.setSubject(sessionDeletionSubject);
                        break;
                    default:
                        message.setSubject("");
                    }
                }

                message.setText(buildEmailMessage(mt), false);
            }
        };
        mailSender.send(messagePreparator);
    } catch (Exception e) {
        logger.error("Issue with sending email", e);
    }
}

From source file:org.cloudfoundry.identity.uaa.login.saml.IdentityProviderConfiguratorTests.java

private void parseYaml(String sampleYaml) {
    YamlMapFactoryBean factory = new YamlMapFactoryBean();
    factory.setResolutionMethod(YamlProcessor.ResolutionMethod.OVERRIDE_AND_IGNORE);
    List<Resource> resources = new ArrayList<>();
    ByteArrayResource resource = new ByteArrayResource(sampleYaml.getBytes());
    resources.add(resource);// www . j a v a 2 s.  c  o m
    factory.setResources(resources.toArray(new Resource[resources.size()]));
    Map<String, Object> tmpdata = factory.getObject();
    data = new HashMap<>();
    for (Map.Entry<String, Object> entry : ((Map<String, Object>) tmpdata.get("providers")).entrySet()) {
        data.put(entry.getKey(), (Map<String, Object>) entry.getValue());
    }
}

From source file:cherry.foundation.mail.MailSendHandlerImplTest.java

@Test
public void testSendNowAttached() throws Exception {
    LocalDateTime now = LocalDateTime.now();
    MailSendHandler handler = create(now);

    ArgumentCaptor<MimeMessagePreparator> preparator = ArgumentCaptor.forClass(MimeMessagePreparator.class);
    doNothing().when(mailSender).send(preparator.capture());

    final File file = File.createTempFile("test_", ".txt", new File("."));
    file.deleteOnExit();/*from ww  w .j a v a  2 s . co  m*/
    try {

        try (OutputStream out = new FileOutputStream(file)) {
            out.write("attach2".getBytes());
        }

        final DataSource dataSource = new DataSource() {
            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getName() {
                return "name3.txt";
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream("attach3".getBytes());
            }

            @Override
            public String getContentType() {
                return "text/plain";
            }
        };

        long messageId = handler.sendNow("loginId", "messageName", "from@addr", asList("to@addr"),
                asList("cc@addr"), asList("bcc@addr"), "subject", "body", new AttachmentPreparator() {
                    @Override
                    public void prepare(Attachment attachment) throws MessagingException {
                        attachment.add("name0.txt", new ByteArrayResource("attach0".getBytes()));
                        attachment.add("name1.bin", new ByteArrayResource("attach1".getBytes()),
                                "application/octet-stream");
                        attachment.add("name2.txt", file);
                        attachment.add("name3.txt", dataSource);
                    }
                });

        Session session = Session.getDefaultInstance(new Properties());
        MimeMessage message = new MimeMessage(session);
        preparator.getValue().prepare(message);

        assertEquals(0L, messageId);
        assertEquals(1, message.getRecipients(RecipientType.TO).length);
        assertEquals(parse("to@addr")[0], message.getRecipients(RecipientType.TO)[0]);
        assertEquals(1, message.getRecipients(RecipientType.CC).length);
        assertEquals(parse("cc@addr")[0], message.getRecipients(RecipientType.CC)[0]);
        assertEquals(1, message.getRecipients(RecipientType.BCC).length);
        assertEquals(parse("bcc@addr")[0], message.getRecipients(RecipientType.BCC)[0]);
        assertEquals(1, message.getFrom().length);
        assertEquals(parse("from@addr")[0], message.getFrom()[0]);
        assertEquals("subject", message.getSubject());

        MimeMultipart mm = (MimeMultipart) message.getContent();
        assertEquals(5, mm.getCount());
        assertEquals("body", ((MimeMultipart) mm.getBodyPart(0).getContent()).getBodyPart(0).getContent());

        assertEquals("name0.txt", mm.getBodyPart(1).getFileName());
        assertEquals("text/plain", mm.getBodyPart(1).getContentType());
        assertEquals("attach0", mm.getBodyPart(1).getContent());

        assertEquals("name1.bin", mm.getBodyPart(2).getDataHandler().getName());
        assertEquals("application/octet-stream", mm.getBodyPart(2).getDataHandler().getContentType());
        assertEquals("attach1", new String(
                ByteStreams.toByteArray((InputStream) mm.getBodyPart(2).getDataHandler().getContent())));

        assertEquals("name2.txt", mm.getBodyPart(3).getFileName());
        assertEquals("text/plain", mm.getBodyPart(3).getContentType());
        assertEquals("attach2", mm.getBodyPart(3).getContent());

        assertEquals("name3.txt", mm.getBodyPart(4).getFileName());
        assertEquals("text/plain", mm.getBodyPart(4).getContentType());
        assertEquals("attach3", mm.getBodyPart(4).getContent());
    } finally {
        file.delete();
    }
}

From source file:org.cloudfoundry.identity.uaa.config.YamlPropertiesFactoryBeanTests.java

@Test
public void testLoadArrayOfString() throws Exception {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(new Resource[] { new ByteArrayResource("foo:\n- bar\n- baz".getBytes()) });
    Properties properties = factory.getObject();
    assertEquals("bar", properties.get("foo[0]"));
    assertEquals("baz", properties.get("foo[1]"));
    assertEquals("bar,baz", properties.get("foo"));
}

From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializerTests.java

@Test
public void testLoadContextConfiguredResource() throws Exception {

    Mockito.when(servletContext.getInitParameter("environmentConfigLocations")).thenReturn("foo.yml");
    Mockito.when(context.getResource(Matchers.eq("foo.yml")))
            .thenReturn(new ByteArrayResource("foo: bar\nspam:\n  foo: baz".getBytes()));

    initializer.initialize(context);//  w w w  . ja  va 2 s . co m

    assertEquals("bar", environment.getProperty("foo"));
    assertEquals("baz", environment.getProperty("spam.foo"));

}

From source file:ch.tatool.app.service.impl.ModuleServiceImpl.java

private Map<String, DataExporter> getModuleExportersFromXML(byte[] configurationXML) {
    // try loading the configuration
    XmlBeanFactory beanFactory = null;// www. ja v  a2  s.  c o m
    if (configurationXML != null) {
        try {
            beanFactory = new XmlBeanFactory(new ByteArrayResource(configurationXML));
        } catch (BeansException be) {
            // TODO: inform user that module configuration is broken
            throw new RuntimeException("Unable to load Tatool file.", be);
        }

        // see whether we have exporters
        if (beanFactory.containsBean("moduleExporters")) {
            Map<String, DataExporter> exporters = (Map<String, DataExporter>) beanFactory
                    .getBean("moduleExporters");
            return exporters;
        } else {
            return Collections.emptyMap();
        }
    } else {
        return null;
    }
}