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.trpr.platform.batch.impl.spring.web.JobConfigController.java

/**
 * This method handles all the configuration changes:
 *    Uploading of XML File/*from   w  w  w. jav a2  s .  co m*/
 *    Uploading of dependency
 *    Saving the changes in XML File
 */
@RequestMapping(value = "configuration/modify/jobs/{jobName}", method = RequestMethod.POST)
public String editJob(ModelMap model, @RequestParam(value = "jobName") String[] jobNames,
        @RequestParam(defaultValue = "") String XMLFileContents,
        @RequestParam(defaultValue = "0") MultipartFile jobFile,
        @RequestParam(defaultValue = "0") MultipartFile depFile,
        @RequestParam(defaultValue = "0") String identifier) throws Exception {

    List<String> jobNameList = Arrays.asList(jobNames);
    //FOr getter methods, such as getJobdependency, any of the jobNames among the list would do
    String jobName = jobNameList.get(0);
    //Button 1: Upload XML
    if (identifier.equals("Upload file")) {
        String jobFileName = jobFile.getOriginalFilename();
        //Check if file is empty or doesn't have an extension
        if (jobFile.isEmpty() || (jobFileName.lastIndexOf('.') < 0)) {
            model.addAttribute("XMLFileError", "File is Empty or invalid. Only .xml files can be uploaded");
        } else if (!jobFileName.substring(jobFileName.lastIndexOf('.')).equals(".xml")) {//Check if file is .xml
            model.addAttribute("XMLFileError", "Only .xml files can be uploaded");
        } else { //Read file to view
            byte[] buffer = jobFile.getBytes();
            XMLFileContents = new String(buffer);
            model.addAttribute("XMLFileContents", XMLFileContents);
        }
    } else if (identifier.equals("Upload dependency")) {
        //Button 2: Upload dependencies
        String depFileName = depFile.getOriginalFilename();
        if (depFile.isEmpty() || (depFileName.lastIndexOf('.') < 0)) {
            model.addAttribute("DepFileError", "File is Empty or invalid. Only .jar files can be uploaded");
        } else if (!depFileName.substring(depFileName.lastIndexOf('.')).equals(".jar")) { //Check if file is valid
            model.addAttribute("DepFileError", "Only .jar files can be uploaded");
        } else {//Move uploaded file
            //Check if file hasn't been added already
            if (jobConfigService.getJobDependencyList(jobName) != null
                    && jobConfigService.getJobDependencyList(jobName).contains(depFileName)) {
                model.addAttribute("DepFileError", "The filename is already added. Overwriting");
            }
            jobConfigService.addJobDependency(jobNameList, depFile.getOriginalFilename(), depFile.getBytes());
        }
    } else { //Button 3: Save. Overwrite the modified XML File
        LOGGER.info("Request to deploy jobConfig file for: " + jobNameList);
        try {
            //Set XML File
            this.jobConfigService.setJobConfig(jobNameList, new ByteArrayResource(XMLFileContents.getBytes()));
            this.jobConfigService.deployJob(jobNameList);
        } catch (Exception e) {
            LOGGER.info("Error while deploying job", e);
            //View: Add Error and rest of the attributes
            //Get stacktrace as string
            StringWriter errors = new StringWriter();
            e.printStackTrace(new PrintWriter(errors));
            model.addAttribute("LoadingError", errors.toString());
            if (errors.toString() == null) {
                model.addAttribute("LoadingError", "Unexpected error");
            }
            model.addAttribute("XMLFileContents", XMLFileContents.trim());
            model.addAttribute("jobName", jobNameList);
            if (jobConfigService.getJobDependencyList(jobName) != null) {
                model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName));
            }
            model.addAttribute("XMLFileContents", XMLFileContents.trim());
            //Redirect
            return "configuration/modify/jobs/job";
        }
        //Loading worked. Deploy to all hosts
        if (this.jobConfigService.getSyncService() != null)
            this.jobConfigService.getSyncService().deployJobToAllHosts(jobName);
        //Redirect to job configuration page. Load the view details
        model.addAttribute("SuccessMessage", "The job was successfully deployed!");
        model.addAttribute("jobName", jobName);
        //Push jobs to all servers
        if (jobConfigService.getJobDependencyList(jobName) != null) {
            model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName));
        }
        model.addAttribute("XMLFileContents", XMLFileContents.trim());
        String jobDirectory = this.jobConfigService.getJobStoreURI(jobName).getPath();
        model.addAttribute("JobDirectoryName",
                jobDirectory.substring(jobDirectory.lastIndexOf('/') + 1) + "/lib");
        return "configuration/jobs/job";
    }
    //Update the view
    model.addAttribute("jobName", jobNameList);
    if (jobConfigService.getJobDependencyList(jobName) != null) {
        model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName));
    }
    model.addAttribute("XMLFileContents", XMLFileContents);
    //Redirect to modify page
    return "configuration/modify/jobs/job";
}

From source file:eu.trentorise.smartcampus.citizenportal.service.EmailService.java

public void sendMailWithInline(final String recipientName, final String recipientEmail,
        final String imageResourceName, final byte[] imageBytes, final String imageContentType,
        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"));
    ctx.setVariable("imageResourceName", imageResourceName); // so that we can reference it from HTML

    // 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 inline image");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);//from   w w  w.j av  a 2  s.  c  o m

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

    // Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
    final InputStreamSource imageSource = new ByteArrayResource(imageBytes);
    message.addInline(imageResourceName, imageSource, imageContentType);

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

}

From source file:ch.algotrader.service.LookupServiceTest.java

@Override
@After/*from w  w w. jav a  2  s.c om*/
public void cleanup() throws Exception {

    ResourceDatabasePopulator dbPopulator = new ResourceDatabasePopulator();
    dbPopulator.addScript(new ByteArrayResource("DROP ALL OBJECTS".getBytes(Charsets.US_ASCII)));

    DatabasePopulatorUtils.execute(dbPopulator, dataSource);

    TransactionSynchronizationManager.unbindResource(sessionFactory);

    if (this.session != null) {

        if (this.session.isOpen()) {
            this.session.close();
        }
    }

    cacheManager.clear();
}

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

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

    Resource resource = new ByteArrayResource(result.getBytes());

    /** Generate Latex */
    InputStream xhtml = toXHTMLConvertor.performTransformation(resource);
    InputStream improvedXhtml = toImprovedXHTML4LatexConvertor
            .performTransformation(new InputStreamResource(xhtml));
    InputStream latex = toLatexConvertor.performTransformation(new InputStreamResource(improvedXhtml));
    logger.debug("xhtml to apt ok");
    File latexFile;//ww w  .  j  av  a  2  s.  c  o  m
    try {
        latexFile = File.createTempFile("wooki", ".latex");
        FileOutputStream fos = new FileOutputStream(latexFile);
        logger.debug("latex File is " + latexFile.getAbsolutePath());
        byte[] content = null;
        int available = 0;
        while ((available = latex.available()) > 0) {
            content = new byte[available];
            latex.read(content);
            fos.write(content);
        }
        fos.flush();
        fos.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java

/**
 * Loads the global database reportDefinitions if they haven't been loaded yet
 * This is a stub.//from   ww w .ja v a2 s. c om
 */
private List loadReportsFromDB() {
    List<ReportDefinition> reportDefArray = new ArrayList<ReportDefinition>();
    List<ReportDefinitionXmlFile> reportDefs = getHibernateTemplate()
            .findByNamedQuery("findReportDefinitionFiles");

    for (ReportDefinitionXmlFile xmlFile : reportDefs) {
        ListableBeanFactory beanFactory = new XmlBeanFactory(new ByteArrayResource(xmlFile.getXmlFile()),
                getBeanFactory());
        ReportDefinition repDef = getReportDefBean(beanFactory);
        repDef.finishLoading();
        repDef.setDbLoaded(true);
        if (isValidWorksiteType(repDef.getSiteType()) && isValidRole(repDef.getRole())
                && hasWarehouseSetting(repDef.getUsesWarehouse())) {
            reportDefArray.add(repDef);
        }
    }
    Collections.sort(reportDefArray, new ReportDefinition.ReportDefinitionComparator());
    return reportDefArray;

}

From source file:net.solarnetwork.node.settings.ca.CASettingsService.java

@Override
public Iterable<BackupResource> getBackupResources() {
    // create resource from our settings CSV data
    ByteArrayOutputStream byos = new ByteArrayOutputStream();
    try {/*ww w . j  a va2s . co  m*/
        OutputStreamWriter writer = new OutputStreamWriter(byos, "UTF-8");
        exportSettingsCSV(writer);
    } catch (IOException e) {
        log.error("Unable to create settings backup resource", e);
    }
    List<BackupResource> resources = new ArrayList<BackupResource>(1);
    resources.add(new ResourceBackupResource(new ByteArrayResource(byos.toByteArray()),
            BACKUP_RESOURCE_SETTINGS_CSV));
    return resources;
}

From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java

public boolean importResource(Id worksiteId, String nodeId)
        throws UnsupportedFileTypeException, ImportException, RuntimeException {

    String id = getContentHosting().resolveUuid(nodeId);
    try {//from   ww  w. j a  v a 2  s .  com
        ContentResource resource = getContentHosting().getResource(id);
        MimeType mimeType = new MimeType(resource.getContentType());

        if (mimeType.equals(new MimeType("application/xml")) || mimeType.equals(new MimeType("text/xml"))) {
            ListableBeanFactory beanFactory = new XmlBeanFactory(new ByteArrayResource(resource.getContent()),
                    getBeanFactory());
            ReportDefinitionXmlFile bean = importReport(resource);
            if (bean != null) {
                saveReportDef(bean, beanFactory);
            }
            return bean != null;
        } else {
            throw new UnsupportedFileTypeException("Unsupported file type");
        }

    } catch (ServerOverloadException soe) {
        logger.warn(soe);

    } catch (PermissionException pe) {
        logger.warn("Failed loading content: no permission to view file", pe);
    } catch (TypeException te) {
        logger.warn("Wrong type", te);
    } catch (IdUnusedException iue) {
        logger.warn("UnusedId: ", iue);
    }
    return false;
}

From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java

protected void updateDefinition(ReportsDefinitionWrapper wrapper, ReportDefinitionXmlFile def) {
    try {/* w w  w.j  a v a2 s.  com*/

        InputStream stream = wrapper.getParentClass().getResourceAsStream(wrapper.getDefinitionFileLocation());
        if (stream == null) {
            throw new RuntimeException(
                    "Loaded Report Definition failed: " + wrapper.getDefinitionFileLocation());
        }
        Set xslFilesToBeRemoved = new HashSet();

        if (def.getReportXslFiles() != null) {
            xslFilesToBeRemoved.addAll(def.getReportXslFiles());
        } else {
            def.setReportXslFiles(new HashSet());
        }
        def.setXmlFile(readStreamToBytes(
                wrapper.getParentClass().getResourceAsStream(wrapper.getDefinitionFileLocation())));

        ListableBeanFactory beanFactory = new XmlBeanFactory(
                new ByteArrayResource(readStreamToBytes(
                        wrapper.getParentClass().getResourceAsStream(wrapper.getDefinitionFileLocation()))),
                getBeanFactory());
        ReportDefinition repDef = getReportDefBean(beanFactory);
        List xsls = repDef.getXsls();
        for (Iterator i = xsls.iterator(); i.hasNext();) {
            ReportXsl xsl = (ReportXsl) i.next();
            ReportXslFile xslFile = new ReportXslFile();
            if (wrapper.getParentClass().getResourceAsStream(xsl.getXslLink()) != null) {
                xslFile.setXslFile(
                        readStreamToBytes(wrapper.getParentClass().getResourceAsStream(xsl.getXslLink())));
                xslFile.setXslFileHash(DigestUtils.md5Hex(xslFile.getXslFile()));
            }
            //xslFile.setReportDefId(repDef.getIdString());
            xslFile.setReportXslFileRef(xsl.getXslLink());
            if (def.getReportXslFiles().contains(xslFile)) {
                xslFilesToBeRemoved.remove(xslFile);
            } else {
                def.getReportXslFiles().add(xslFile);
            }
        }

        for (Iterator<ReportXslFile> i = xslFilesToBeRemoved.iterator(); i.hasNext();) {
            ReportXslFile removedFile = i.next();
            def.getReportXslFiles().remove(removedFile);
        }
        getHibernateTemplate().saveOrUpdate(def);
    } catch (Exception e) {
        throw new RuntimeException("Loaded report def failed", e);
    }
}

From source file:objective.taskboard.utils.IOUtilities.java

public static Resource asResource(byte[] bytes) {
    return new ByteArrayResource(bytes);
}