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.pesc.cds.web.TranscriptRequestController.java

private void sendDocument(File outboxFile, String endpointURI, Transaction tx, String fileFormat,
        String documentType, String department) throws IOException {

    byte[] fileSignature = pkiService.createDigitalSignature(new FileInputStream(outboxFile),
            pkiService.getSigningKeys().getPrivate());
    try {//from  www.  ja va  2s  . c o m

        LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("recipient_id", tx.getRecipientId());
        map.add("sender_id", tx.getSenderId());
        map.add("signer_id", localServerId);
        map.add("file_format", fileFormat);
        map.add("document_type", documentType);
        map.add("department", department);
        map.add("transaction_id", tx.getId());
        map.add("ack_url", localServerWebServiceURL);
        map.add("file", new FileSystemResource(outboxFile));
        map.add("signature", new ByteArrayResource(fileSignature) {
            @Override
            public String getFilename() {
                return "signature.dat";
            }
        });

        org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.MULTIPART_FORM_DATA);

        ResponseEntity<String> response = restTemplate.exchange(endpointURI, HttpMethod.POST,
                new org.springframework.http.HttpEntity<Object>(map, headers), String.class);

        if (response.getStatusCode() != HttpStatus.OK) {
            throw new IllegalArgumentException(
                    "Failed to send document.  Reason: " + response.getStatusCode().getReasonPhrase());
        }

        log.info(response.getStatusCode().getReasonPhrase());

    } catch (ResourceAccessException e) {

        //Force the OAuth client to retrieve the token again whenever it is used again.

        restTemplate.getOAuth2ClientContext().setAccessToken(null);

        tx.setError(e.getMessage());
        transactionService.update(tx);

        log.error(e);
        throw new IllegalArgumentException(e);

    } catch (Exception e) {

        tx.setError(e.getMessage());
        transactionService.update(tx);

        log.error(e);

        throw new IllegalArgumentException(e);

    }

}

From source file:org.springframework.cloud.config.server.EncryptionController.java

@RequestMapping(value = "/key", method = RequestMethod.POST, params = { "password" })
public ResponseEntity<Map<String, Object>> uploadKeyStore(@RequestParam("file") MultipartFile file,
        @RequestParam("password") String password, @RequestParam("alias") String alias) {

    Map<String, Object> body = new HashMap<String, Object>();
    body.put("status", "OK");

    try {/*from  w w w .ja v a  2 s .c  om*/
        ByteArrayResource resource = new ByteArrayResource(file.getBytes());
        KeyPair keyPair = new KeyStoreKeyFactory(resource, password.toCharArray()).getKeyPair(alias);
        encryptor = new RsaSecretEncryptor(keyPair);
        body.put("publicKey", ((RsaKeyHolder) encryptor).getPublicKey());
    } catch (IOException e) {
        throw new KeyFormatException();
    }

    return new ResponseEntity<Map<String, Object>>(body, HttpStatus.CREATED);

}

From source file:org.springframework.cloud.stream.app.scriptable.transform.processor.ScriptableTransformProcessorConfiguration.java

@Bean
@Transformer(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public MessageProcessor<?> transformer() {
    String language = this.properties.getLanguage();
    String script = this.properties.getScript();
    logger.info(String.format("Input script is '%s', language is '%s'", script, language));
    Resource scriptResource = new ByteArrayResource(decodeScript(script).getBytes()) {

        // TODO until INT-3976
        @Override/*from   w  w  w .j  av  a  2 s  .c o m*/
        public String getFilename() {
            // Only the groovy script processor enforces this requirement for a name
            return "StaticScript";
        }

    };
    return Scripts.script(scriptResource).lang(language).variableGenerator(this.scriptVariableGenerator).get();
}

From source file:org.springframework.integration.samples.mailattachments.MimeMessageParsingTest.java

private ByteArrayResource getFileData(String filename) {

    final InputStream attachmentInputStream = MimeMessageParsingTest.class.getResourceAsStream(filename);

    Assert.assertNotNull("Resource not found: " + filename, attachmentInputStream);

    ByteArrayResource byteArrayResource = null;

    try {/*from   w  ww  .  ja v a2s. c  o m*/
        byteArrayResource = new ByteArrayResource(IOUtils.toByteArray(attachmentInputStream));
        attachmentInputStream.close();
    } catch (IOException e1) {
        Assert.fail();
    }

    return byteArrayResource;

}

From source file:org.springframework.ldap.itest.AbstractLdapTemplateIntegrationTest.java

@Before
public void cleanAndSetup() throws NamingException, IOException {
    Resource ldifResource = getLdifFileResource();
    if (!LdapUtils.newLdapName(base).equals(LdapUtils.newLdapName(DEFAULT_BASE))) {
        List<String> lines = IOUtils.readLines(ldifResource.getInputStream());

        StringWriter sw = new StringWriter();
        PrintWriter writer = new PrintWriter(sw);
        for (String line : lines) {
            writer.println(StringUtils.replace(line, DEFAULT_BASE, base));
        }//from  ww w  .  j  a va  2 s.com

        writer.flush();
        ldifResource = new ByteArrayResource(sw.toString().getBytes("UTF8"));
    }

    LdapTestUtils.cleanAndSetup(contextSource, getRoot(), ldifResource);
}

From source file:org.springframework.ldap.test.LdifPopulator.java

@Override
public void afterPropertiesSet() throws Exception {
    Assert.notNull(contextSource, "ContextSource must be specified");
    Assert.notNull(resource, "Resource must be specified");

    if (!LdapUtils.newLdapName(base).equals(LdapUtils.newLdapName(defaultBase))) {
        List<String> lines = IOUtils.readLines(resource.getInputStream());

        StringWriter sw = new StringWriter();
        PrintWriter writer = new PrintWriter(sw);
        for (String line : lines) {
            writer.println(StringUtils.replace(line, defaultBase, base));
        }//from ww  w  .  j  ava  2s  . c  o m

        writer.flush();
        resource = new ByteArrayResource(sw.toString().getBytes("UTF8"));
    }

    if (clean) {
        LdapTestUtils.clearSubContexts(contextSource, LdapUtils.emptyLdapName());
    }

    LdapTestUtils.loadLdif(contextSource, resource);
}

From source file:org.springframework.xd.jdbc.SingleTableDatabaseInitializer.java

private Resource substitutePlaceholdersForResource(Resource resource) {

    StringBuilder script = new StringBuilder();

    try {// w  ww  . j a v a2  s.  c  o  m
        EncodedResource er = new EncodedResource(resource);
        LineNumberReader lnr = new LineNumberReader(er.getReader());
        String line = lnr.readLine();
        while (line != null) {
            if (tableName != null && line.contains(TABLE_PLACEHOLDER)) {
                logger.debug(
                        "Substituting '" + TABLE_PLACEHOLDER + "' with '" + tableName + "' in '" + line + "'");
                line = line.replace(TABLE_PLACEHOLDER, tableName);
            }
            if (line.contains(COLUMNS_PLACEHOLDER)) {
                logger.debug(
                        "Substituting '" + COLUMNS_PLACEHOLDER + "' with '" + columns + "' in '" + line + "'");
                line = line.replace(COLUMNS_PLACEHOLDER, columns);
            }
            script.append(line + "\n");
            line = lnr.readLine();
        }
        lnr.close();
        return new ByteArrayResource(script.toString().getBytes());
    } catch (IOException e) {
        throw new InvalidDataAccessResourceUsageException("Unable to read script " + resource, e);
    }
}

From source file:org.teiid.spring.autoconfigure.RedirectionSchemaInitializer.java

List<Resource> generatedScripts() {
    List<Resource> resources = Collections.emptyList();

    for (PersistentClass clazz : metadata.getEntityBindings()) {
        org.hibernate.mapping.Table ormTable = clazz.getTable();
        String tableName = ormTable.getQuotedName();
        if (this.schema.getTable(tableName) != null) {
            org.hibernate.mapping.Column c = new org.hibernate.mapping.Column(
                    RedirectionSchemaBuilder.ROW_STATUS_COLUMN);
            c.setSqlTypeCode(TypeFacility.getSQLTypeFromRuntimeType(Integer.class));
            c.setSqlType(JDBCSQLTypeInfo.getTypeName(TypeFacility.getSQLTypeFromRuntimeType(Integer.class)));
            ormTable.addColumn(c);/*from w w w  . ja va2s.c  o  m*/
            ormTable.setName(tableName + TeiidConstants.REDIRECTED_TABLE_POSTFIX);
        }
    }

    List<String> statements = createScript(metadata, dialect, true);
    StringBuilder sb = new StringBuilder();
    for (String s : statements) {
        // we have no need for sequences in the redirected scenario, they are fed from
        // other side.
        if (s.startsWith("drop sequence") || s.startsWith("create sequence")) {
            continue;
        }
        sb.append(s).append(";\n");
    }
    logger.debug("Redirected Schema:\n" + sb.toString());
    resources = Arrays.asList(new ByteArrayResource(sb.toString().getBytes()));
    return resources;
}

From source file:org.trpr.platform.servicefw.impl.spring.web.ServiceController.java

/** Controller for deploy page (called from modify) */
@RequestMapping(value = { "/deploy/services/{serviceName}" }, method = RequestMethod.POST)
public String deploy(ModelMap model, @ModelAttribute("services") String serviceName,
        @RequestParam(defaultValue = "") String XMLFileContents) {
    model.addAttribute("serviceName", serviceName);

    try {//from  w  w  w  .  ja v a2 s  . c  o  m
        this.configurationService.modifyConfig(this.constructServiceKey(serviceName),
                new ByteArrayResource(XMLFileContents.getBytes()));
    } catch (Exception e) {
        model.addAttribute("XMLFileError", "Unable to deploy file");
        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",
                getContents(this.configurationService.getConfig(this.constructServiceKey(serviceName))));
        return "modifyConfig";
    }
    //Loading success
    model.addAttribute("SuccessMessage", "Successfully Deployed the new Handler Configuration");
    Resource handlerFile = this.configurationService.getConfig(this.constructServiceKey(serviceName));
    model.addAttribute("XMLFileContents", getContents(handlerFile));
    try {
        model.addAttribute("XMLFileName", handlerFile.getURI());
    } catch (IOException e) {
        model.addAttribute("XMLFileName", "File not found");
    }
    return "viewConfig";
}

From source file:org.wso2.security.tools.automation.manager.handler.MailHandler.java

/**
 * Send an email with an attachment//from  w w w.  j a v  a2 s  .  com
 *
 * @param to                 To whom the email is sent
 * @param subject            Email subject
 * @param body               Email body
 * @param inputStream        Input stream of an attachment
 * @param attachmentFileName Attachment file name
 * @throws MessagingException Exceptions thrown by the Messaging classes
 * @throws IOException        Signals that an I/O exception of some sort has occurred
 */
public void sendMail(String to, String subject, String body, InputStream inputStream, String attachmentFileName)
        throws MessagingException, IOException {
    LOGGER.info("Sending email");
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
    mimeMessageHelper.setSubject(subject);
    mimeMessageHelper.setTo(to);
    mimeMessageHelper.setText(body);
    mimeMessageHelper.addAttachment(attachmentFileName,
            new ByteArrayResource(IOUtils.toByteArray(inputStream)));
    mailSender.send(mimeMessageHelper.getMimeMessage());
}