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 testLog4jFileFromYaml() throws Exception {
    Mockito.when(context.getResource(Matchers.anyString()))
            .thenReturn(new ByteArrayResource("logging:\n  file: /tmp/bar.log".getBytes()));
    initializer.initialize(context);/*from  w ww.ja v  a 2s .com*/
    assertEquals("/tmp/bar.log", System.getProperty("LOG_FILE"));
}

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

@Test
public void testLoadResourceWithDefaultMatch() throws Exception {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setMatchDefault(true);// w w  w. j a  v a2  s  . co m
    factory.setResources(new Resource[] {
            new ByteArrayResource("one: two\n---\nfoo: bar\nspam: baz\n---\nfoo: bag\nspam: bad".getBytes()) });
    factory.setDocumentMatchers(Collections.singletonMap("foo", "bag"));
    Properties properties = factory.getObject();
    assertEquals("bag", properties.get("foo"));
    assertEquals("bad", properties.get("spam"));
    assertEquals("two", properties.get("one"));
}

From source file:com.consol.citrus.mail.message.MailMessageConverter.java

@Override
public void convertOutbound(MimeMailMessage mimeMailMessage, Message message,
        MailEndpointConfiguration endpointConfiguration) {
    MailMessage mailMessage = getMailMessage(message, endpointConfiguration);

    try {/*ww w  .  j  a  va2  s. c o  m*/
        mimeMailMessage.setFrom(mailMessage.getFrom());
        mimeMailMessage.setTo(StringUtils.commaDelimitedListToStringArray(mailMessage.getTo()));

        if (StringUtils.hasText(mailMessage.getCc())) {
            mimeMailMessage.setCc(StringUtils.commaDelimitedListToStringArray(mailMessage.getCc()));
        }

        if (StringUtils.hasText(mailMessage.getBcc())) {
            mimeMailMessage.setBcc(StringUtils.commaDelimitedListToStringArray(mailMessage.getBcc()));
        }

        mimeMailMessage.setReplyTo(
                mailMessage.getReplyTo() != null ? mailMessage.getReplyTo() : mailMessage.getFrom());
        mimeMailMessage.setSentDate(new Date());
        mimeMailMessage.setSubject(mailMessage.getSubject());
        mimeMailMessage.setText(mailMessage.getBody().getContent());

        if (mailMessage.getBody().hasAttachments()) {
            for (AttachmentPart attachmentPart : mailMessage.getBody().getAttachments().getAttachments()) {
                mimeMailMessage.getMimeMessageHelper().addAttachment(attachmentPart.getFileName(),
                        new ByteArrayResource(attachmentPart.getContent()
                                .getBytes(Charset.forName(attachmentPart.getCharsetName()))),
                        attachmentPart.getContentType());
            }
        }
    } catch (MessagingException e) {
        throw new CitrusRuntimeException("Failed to create mail mime message", e);
    }
}

From source file:alfio.util.TemplateManager.java

public String renderString(String template, Map<String, Object> model, Locale locale,
        TemplateOutput templateOutput) {
    return render(new ByteArrayResource(template.getBytes(StandardCharsets.UTF_8)), model, locale,
            templateOutput);/*  ww w . j av a2 s.c  o  m*/
}

From source file:org.springframework.cloud.config.server.environment.VaultEnvironmentRepository.java

@Override
public Environment findOne(String application, String profile, String label) {

    String state = request.getHeader(STATE_HEADER);
    String newState = this.watch.watch(state);

    String[] profiles = StringUtils.commaDelimitedListToStringArray(profile);
    List<String> scrubbedProfiles = scrubProfiles(profiles);

    List<String> keys = findKeys(application, scrubbedProfiles);

    Environment environment = new Environment(application, profiles, label, null, newState);

    for (String key : keys) {
        // read raw 'data' key from vault
        String data = read(key);/*w w w  . j  a  v a 2  s.c  o  m*/
        if (data != null) {
            // data is in json format of which, yaml is a superset, so parse
            final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            yaml.setResources(new ByteArrayResource(data.getBytes()));
            Properties properties = yaml.getObject();

            if (!properties.isEmpty()) {
                environment.add(new PropertySource("vault:" + key, properties));
            }
        }
    }

    return environment;
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobAlertImpl.java

protected static void attachException(MimeMessageHelper messageHelper, ExceptionInfo exceptionInfo)
        throws MessagingException {
    Throwable exception = exceptionInfo.getException();
    if (exception == null) {
        return;//www.j a v  a  2 s .c  om
    }

    ByteArrayOutputStream bufOut = new ByteArrayOutputStream();
    PrintStream printOut = new PrintStream(bufOut);
    exception.printStackTrace(printOut);
    printOut.flush();

    String attachmentName = "exception_" + System.identityHashCode(exception) + ".txt";
    messageHelper.addAttachment(attachmentName, new ByteArrayResource(bufOut.toByteArray()));
}

From source file:org.trpr.platform.batch.impl.spring.web.SynchronizationController.java

/**
 * Receiver methods start/*from   w  w w  .j  a  va2  s  . c  o m*/
 * These methods receive the job configuration files, dependency files and job loading requests.
 * This method is synchronized as 2 job requests cannot be processed simultaneously
 */
@RequestMapping(value = SynchronizationController.PUSH_URL, method = RequestMethod.POST)
public synchronized String jobReceiver(ModelMap model, @RequestParam String jobName,
        @RequestParam(value = "jobConfig") MultipartFile jobConfig,
        @RequestParam(value = "depFiles[]", required = false) MultipartFile[] depFiles) {
    jobName = jobName.trim();
    LOGGER.info("Push job request received for job: " + jobName);
    //Upload configuration file
    if (this.jobService.contains(jobName)) {
        LOGGER.info("Warning: " + jobName + " already exists. Modifying old file");
    }
    try {
        //Set XML File
        List<String> jobNames = new LinkedList<String>();
        jobNames.add(jobName);
        this.jobConfigService.setJobConfig(jobNames, new ByteArrayResource(jobConfig.getBytes()));
        LOGGER.info("Success in deploying configuration file for: " + jobName);
        model.addAttribute("Message", "success");
    } catch (Exception e) {
        model.addAttribute("Message", "Error while writing the job config file");
        LOGGER.warn("Unable to deploy the job. Please check that you have write permission. Nested exception: "
                + e.getMessage());
        return "sync/Message";
    }
    //Upload dependency Files
    if (depFiles != null && depFiles.length != 0) { //Dep files exist
        for (MultipartFile depFile : depFiles) {
            try {
                //Set dependencies
                LOGGER.info("Request to deploy file: " + jobName + " " + depFile.getOriginalFilename() + " "
                        + depFile.getSize());
                List<String> jobNames = new LinkedList<String>();
                jobNames.add(jobName);
                this.jobConfigService.addJobDependency(jobNames, depFile.getOriginalFilename(),
                        depFile.getBytes());
                LOGGER.info("Success in deploying dependency file for: " + jobName);
                model.addAttribute("Message", "success");
            } catch (Exception e) {
                LOGGER.error("Exception while deploying Dependency file: ", e);
                model.addAttribute("Message",
                        "Unexpected error while deploying dependencyFile: " + depFile.getOriginalFilename());
            }
        }
    }
    LOGGER.info("Deploy request");
    //Deploy request
    try {
        List<String> jobNames = new LinkedList<String>();
        jobNames.add(jobName);
        this.jobConfigService.deployJob(jobNames);
        LOGGER.info("Success in deploying: " + jobName);
        model.addAttribute("Message", "success");
    } catch (Exception e) {
        LOGGER.error("Error while deploying job: " + jobName, e);
        model.addAttribute("Message", "Unexpected error while loading: " + jobName);
    }
    return "sync/Message";
}

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

@Test
public void testLog4jPathFromYaml() throws Exception {
    Mockito.when(context.getResource(Matchers.anyString()))
            .thenReturn(new ByteArrayResource("logging:\n  path: /tmp/log/bar".getBytes()));
    initializer.initialize(context);/* ww  w .j  a v a 2s  .c  om*/
    assertEquals("/tmp/log/bar", System.getProperty("LOG_PATH"));
}

From source file:be.roots.taconic.pricingguide.service.MailServiceImpl.java

@Override
public void sendReport(DateTime lastMonth, String filename, byte[] report) throws MessagingException {

    final MimeMessageHelper helper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);

    helper.setFrom(fromEmail);//from  ww w  .  j a  v  a  2s  .  c  o m

    if (StringUtils.isEmpty(testEmail)) {
        helper.setTo(reportRecipientEmail.split(","));
    } else {
        helper.setTo(testEmail.split(","));
    }

    if (!StringUtils.isEmpty(bccEmail)) {
        helper.setBcc(bccEmail.split(","));
    }

    helper.setSubject(documentTitle + " requests for " + lastMonth.toString(DefaultUtil.FORMAT_MONTH));

    final String body = "Dear<br>" + "<br>" + "Attached you find the overview of " + documentTitle
            + " requests for " + lastMonth.toString(DefaultUtil.FORMAT_MONTH) + ".<br>" + "<br>"
            + "Taconic Biosciences, Inc.<br>" + "One Hudson City Centre<br>" + "Hudson, New York 12534<br>"
            + "North America +1 888 822-6642<br>" + "Europe +45 70 23 04 05<br>" + "info@taconic.com<br>"
            + "www.taconic.com";

    helper.setText(body, true);

    helper.addAttachment(filename, new ByteArrayResource(report));

    javaMailSender.send(helper.getMimeMessage());

}

From source file:thymeleafexamples.springmail.service.EmailService.java

public void sendMailWithAttachment(final String recipientName, final String recipientEmail,
        final String attachmentFileName, final byte[] attachmentBytes, final String attachmentContentType,
        final Locale locale) throws MessagingException {

    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("subscriptionDate", new Date());
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));

    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true /* multipart */, "UTF-8");
    message.setSubject("Example HTML email with attachment");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);/*from  w w w  .jav a2 s .c o  m*/

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("email-withattachment.html", ctx);
    message.setText(htmlContent, true /* isHtml */);

    // Add the attachment
    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);
    message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);

    // Send mail
    this.mailSender.send(mimeMessage);

}