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.biopax.validator.ws.ValidatorController.java

/**
 * JSP pages and RESTful web services controller, the main one that checks BioPAX data.
 * All parameter names are important, i.e., these are part of public API (for clients)
 * // w w  w  .ja  v  a  2  s . c  o  m
 * Framework's built-in parameters:
 * @param request the web request object (may contain multi-part data, i.e., multiple files uploaded)
 * @param response 
 * @param mvcModel Spring MVC Model
 * @param writer HTTP response writer
 * 
 * BioPAX Validator/Normalizer query parameters:
 * @param url
 * @param retDesired
 * @param autofix
 * @param filter
 * @param maxErrors
 * @param profile
 * @param normalizer binds to three boolean options: normalizer.fixDisplayName, normalizer.inferPropertyOrganism, normalizer.inferPropertyDataSource
 * @return
 * @throws IOException
 */
@RequestMapping(value = "/check", method = RequestMethod.POST)
public String check(HttpServletRequest request, HttpServletResponse response, Model mvcModel, Writer writer,
        @RequestParam(required = false) String url, @RequestParam(required = false) String retDesired,
        @RequestParam(required = false) Boolean autofix, @RequestParam(required = false) Behavior filter,
        @RequestParam(required = false) Integer maxErrors, @RequestParam(required = false) String profile,
        //normalizer!=null when called from the JSP; 
        //but it's usually null when from the validator-client or a web script
        @ModelAttribute("normalizer") Normalizer normalizer) throws IOException {
    Resource resource = null; // a resource to validate

    // create the response container
    ValidatorResponse validatorResponse = new ValidatorResponse();

    if (url != null && url.length() > 0) {
        if (url != null)
            log.info("url : " + url);
        try {
            resource = new UrlResource(url);
        } catch (MalformedURLException e) {
            mvcModel.addAttribute("error", e.toString());
            return "check";
        }

        try {
            Validation v = execute(resource, resource.getDescription(), maxErrors, autofix, filter, profile,
                    normalizer);
            validatorResponse.addValidationResult(v);
        } catch (Exception e) {
            return errorResponse(mvcModel, "check", "Exception: " + e);
        }

    } else if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Map files = multiRequest.getFileMap();
        Assert.state(!files.isEmpty(), "No files to validate");
        for (Object o : files.values()) {
            MultipartFile file = (MultipartFile) o;
            String filename = file.getOriginalFilename();
            // a workaround (for some reason there is always a no-name-file;
            // this might be a javascript isue)
            if (file.getBytes().length == 0 || filename == null || "".equals(filename))
                continue;

            log.info("check : " + filename);

            resource = new ByteArrayResource(file.getBytes());

            try {
                Validation v = execute(resource, filename, maxErrors, autofix, filter, profile, normalizer);
                validatorResponse.addValidationResult(v);
            } catch (Exception e) {
                return errorResponse(mvcModel, "check", "Exception: " + e);
            }

        }
    } else {
        return errorResponse(mvcModel, "check", "No BioPAX input source provided!");
    }

    if ("xml".equalsIgnoreCase(retDesired)) {
        response.setContentType("application/xml");
        ValidatorUtils.write(validatorResponse, writer, null);
    } else if ("html".equalsIgnoreCase(retDesired)) {
        /* could also use ValidatorUtils.write with a xml-to-html xslt source
         but using JSP here makes it easier to keep the same style, header, footer*/
        mvcModel.addAttribute("response", validatorResponse);
        return "groupByCodeResponse";
    } else { // owl only
        response.setContentType("text/plain");
        // write all the OWL results one after another TODO any better solution?
        for (Validation result : validatorResponse.getValidationResult()) {
            if (result.getModelData() != null)
                writer.write(result.getModelData() + NEWLINE);
            else
                // empty result
                writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<rdf:RDF></rdf:RDF>" + NEWLINE);
        }
    }

    return null; // (Writer is used instead)
}

From source file:org.jasig.schedassist.impl.relationship.advising.AdvisorListRelationshipDataSourceImplTest.java

/**
 * Test readResource function with {@link ByteArrayResource}/
 * /* ww  w.  j av  a2 s. com*/
 * @throws Exception
 */
@Test
public void testReadResource() throws Exception {
    String example1 = "student1@wisc.edu;One,Test Student;0000000001;9010000001;Graduate;L&S;College of Letters and Science;4.000;1092;Fall 2008-2009;87.000;PHD 922L&S;;NWD;G922L;Sociology - LS;PHD 922L&S;Sociology PHD-L&S;Sociology;advisor1@wisc.edu;One,Advisor;1000000001;9020000001;ADVR;Academic";
    String example2 = "student2@wisc.edu;Two,Test Student;0000000002;9010000002;Senior;NUR;School of Nursing;3.556;1094;Spring 2008-2009;128.000;NUR 712;;NWD;NUR;Nursing Undergraduate;NUR 712;Nursing NUR;Nursing;advisor2@wisc.edu;Two,Advisor;1000000002;9020000002;ADVR;Academic";
    StringBuilder builder = new StringBuilder();
    builder.append(example1);
    builder.append("\n");
    builder.append(example2);

    ByteArrayResource sampleResource = new ByteArrayResource(builder.toString().getBytes());

    AdvisorListRelationshipDataSourceImpl dataSource = new AdvisorListRelationshipDataSourceImpl();
    List<StudentAdvisorAssignment> records = dataSource.readResource(sampleResource, "1094");
    Assert.assertEquals(1, records.size());
    StudentAdvisorAssignment record = records.get(0);
    Assert.assertEquals("1000000002", record.getAdvisorEmplid());
    Assert.assertEquals("Nursing Undergraduate", record.getAdvisorRelationshipDescription());
    Assert.assertEquals("0000000002", record.getStudentEmplid());
    Assert.assertEquals("1094", record.getTermNumber());
    Assert.assertEquals("Spring 2008-2009", record.getTermDescription());
    Assert.assertEquals("Academic", record.getAdvisorType());

    records = dataSource.readResource(sampleResource, "1092");
    Assert.assertEquals(2, records.size());
}

From source file:dk.nsi.minlog.test.utils.SoapHeaders.java

public static Resource getSoapEnvelope(String payload) throws Exception {
    orgUsingID.setNameFormat(NameFormat.MEDCOM_CVRNUMBER);
    orgUsingID.setValue("25520041");

    props = SignatureUtil.setupCryptoProviderForJVM();
    File validMocesVault = new File(
            Thread.currentThread().getContextClassLoader().getResource("validMocesVault.jks").getFile());
    assertTrue("validMocesVault.jks could not be found at " + validMocesVault.getAbsolutePath(),
            validMocesVault.exists());/* w w  w  . jav  a 2  s.c o m*/

    vault = new FileBasedCredentialVault(props, validMocesVault, keystorePassword);
    federation = new SOSITestFederation(props);
    factory = new SOSIFactory(federation, vault, props);

    String soapRequest = SOAP_HEADER_OPEN + getHeaderElements() + SOAP_HEADER_CLOSE + SOAP_BODY_OPEN + payload
            + SOAP_BODY_CLOSE + SOAP_ENV_CLOSE;

    return new ByteArrayResource(soapRequest.getBytes("UTF-8"));
}

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

@Test
public void testLoadArrayOfObject() throws Exception {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(new Resource[] { new ByteArrayResource(
            "foo:\n- bar:\n    spam: crap\n- baz\n- one: two\n  three: four".getBytes()) });
    Properties properties = factory.getObject();
    // System.err.println(properties);
    assertEquals("crap", properties.get("foo[0].bar.spam"));
    assertEquals("baz", properties.get("foo[1]"));
    assertEquals("two", properties.get("foo[2].one"));
    assertEquals("four", properties.get("foo[2].three"));
    assertEquals("{bar={spam=crap}},baz,{one=two, three=four}", properties.get("foo"));
}

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

@Test
public void testLoadReplacedResource() throws Exception {

    System.setProperty("APPLICATION_CONFIG_URL", "file:foo/uaa.yml");

    Mockito.when(context.getResource(Matchers.eq("file:foo/uaa.yml")))
            .thenReturn(new ByteArrayResource("foo: bar\nspam:\n  foo: baz".getBytes()));

    initializer.initialize(context);/*w  w  w  .  j  av a2  s  .  c  o m*/

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

}

From source file:it.jugpadova.blo.ParticipantBo.java

public void sendCertificateToAllParticipants(long eventId, String baseUrl) {
    WebContext wctx = WebContextFactory.get();
    ScriptSession session = wctx.getScriptSession();
    Util util = new Util(session);
    List<Participant> participantList = participantDao.findPresentParticipantsByEventId(eventId);
    int total = participantList.size();
    int count = 0;
    for (Participant participant : participantList) {
        try {//from w  w  w.j av  a  2 s . c  om
            Event event = participant.getEvent();
            InputStream jugCertificateTemplate = jugBo
                    .retrieveJugCertificateTemplate(event.getOwner().getJug().getId());
            byte[] certificate = buildCertificate(jugCertificateTemplate,
                    participant.getFirstName() + " " + participant.getLastName(), event.getTitle(),
                    event.getStartDate(), event.getOwner().getJug().getName());
            ByteArrayResource attachment = new ByteArrayResource(certificate);
            sendEmail(participant, baseUrl, "Your certificate is here",
                    "it/jugpadova/participant-certificate.vm", attachment,
                    "certificate" + event.getId() + ".pdf");
            participant.setLastCertificateSentDate(new Date());
            count++;
            util.setValue("sentCertificatesMessage", "Sent " + count + " of " + total + " certificates");
        } catch (Exception ex) {
            logger.error("Error generating certificates", ex);
        }
    }
    logger.info("Sent " + count + " certificates for the event " + eventId);
}

From source file:org.eclipse.gemini.blueprint.test.internal.util.jar.JarCreator.java

/**
 * Resolve the jar content based on its path. Will return a map containing
 * the entries relative to the jar root path as keys and Spring Resource
 * pointing to the actual resources as values. It will also determine the
 * packages contained by this package.//from   w ww.j ava2s  . c  o  m
 * 
 * @return
 */
public Map resolveContent() {
    Resource[][] resources = resolveResources();

    URL rootURL;
    String rootP = getRootPath();
    try {
        rootURL = new URL(rootP);
    } catch (MalformedURLException ex) {
        throw (RuntimeException) new IllegalArgumentException("illegal root path given " + rootP).initCause(ex);
    }
    String rootPath = StringUtils.cleanPath(rootURL.getPath());

    // remove duplicates
    Map entries = new TreeMap();
    // save contained bundle packages
    containedPackages.clear();

    // empty stream used for folders
    Resource folderResource = new ByteArrayResource(new byte[0]);

    // add folder entries also
    for (int i = 0; i < resources.length; i++) {
        for (int j = 0; j < resources[i].length; j++) {
            String relativeName = determineRelativeName(rootPath, resources[i][j]);
            // be consistent when adding resources to jar
            if (!relativeName.startsWith("/"))
                relativeName = "/" + relativeName;
            entries.put(relativeName, resources[i][j]);

            // look for class entries
            if (relativeName.endsWith(CLASS_EXT)) {

                // determine package (exclude first char)
                String clazzName = relativeName.substring(1, relativeName.length() - CLASS_EXT.length())
                        .replace('/', '.');
                // remove class name
                int index = clazzName.lastIndexOf('.');
                if (index > 0)
                    clazzName = clazzName.substring(0, index);
                // add it to the collection
                containedPackages.add(clazzName);
            }

            String token = relativeName;
            // get folder and walk up to the root
            if (addFolders) {
                // add META-INF
                entries.put("/META-INF/", folderResource);
                int slashIndex;
                // stop at root folder
                while ((slashIndex = token.lastIndexOf('/')) > 1) {
                    // add the folder with trailing /
                    entries.put(token.substring(0, slashIndex + 1), folderResource);
                    // walk the tree
                    token = token.substring(0, slashIndex);
                }
                // add root folder
                //entries.put("/", folderResource);
            }
        }
    }

    if (log.isTraceEnabled())
        log.trace("The following packages were discovered in the bundle: " + containedPackages);

    return entries;
}

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

@Test
public void testLoadReplacedResourceFromFileLocation() throws Exception {

    System.setProperty("APPLICATION_CONFIG_FILE", "foo/uaa.yml");

    Mockito.when(context.getResource(Matchers.eq("file:foo/uaa.yml")))
            .thenReturn(new ByteArrayResource("foo: bar\nspam:\n  foo: baz".getBytes()));

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

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

}

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

/**
 * Checks whether a configuration xml is valid or not.
 *///from   w w  w . j  a va2 s  . c  o m
protected Element loadRootElementFromSpringXML(String configXML) {
    // try loading the configuration
    XmlBeanFactory beanFactory = null;
    try {
        beanFactory = new XmlBeanFactory(new ByteArrayResource(configXML.getBytes()));
    } catch (BeansException be) {
        logger.error("Unable to load Tatool file.", be);
        throw new RuntimeException("Unable to load Tatool file.");
    }

    // check whether we have the mandatory beans (rootElement)
    if (!beanFactory.containsBean(ROOT_ELEMENT)) {
        logger.error("Unable to load Tatool file. Root element missing!");
        throw new CreationException("Unable to load Tatool file. Root element missing!");
    }

    // fetch the rootElement
    try {
        Element root = (Element) beanFactory.getBean(ROOT_ELEMENT);
        return root;
    } catch (RuntimeException e) {
        String[] errors = e.getMessage().split(";");
        throw new CreationException(errors[errors.length - 1]);
    }
}

From source file:gr.abiss.calipso.service.EmailService.java

@Async
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   www. j  a va2  s  . c  o  m

    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("email-withattachment.html", ctx);
    LOGGER.info("Sending email body: " + htmlContent);
    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);

}