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:com.baidu.jprotobuf.rpc.client.HttpRPCServerTest.java

@Test
public void testSimpleRPC() {
    // google protobuf defined idl 
    String idl = "package pkg; " + "option java_package = \"com.baidu.bjf.remoting.protobuf.simplestring\";"
            + "option java_outer_classname = \"StringTypeClass\";"
            + "message StringMessage { required string msg = 1;}  ";

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

    HttpRPCServer httpRPCServer = null;// w ww  .j  ava 2 s .com
    try {
        // RPC Server  ?
        httpRPCServer = new HttpRPCServer(8080, 10);

        IDLServiceExporter idlServiceExporter = new IDLServiceExporter();
        idlServiceExporter.setInputIDL(resource);
        idlServiceExporter.setOutputIDL(resource);
        idlServiceExporter.setServiceName("SimpleTest");
        idlServiceExporter.setInvoker(new ServerInvoker() {

            @Override
            public void invoke(IDLProxyObject input, IDLProxyObject output) throws Exception {

                if (input != null) { // if has request
                    Object msg = input.get("msg");
                    System.out.println("Get 'msg' from request value =" + msg);
                }

                if (output != null) { // if need response result
                    output.put("msg", "new message");
                }

            }
        });
        idlServiceExporter.afterPropertiesSet();

        // RPC?
        HttpServerRequestHandler httpHandler = new HttpServerRequestHandler(idlServiceExporter);
        httpRPCServer.addRPCHandler(httpHandler);

        // ? RPC Server
        // ?RPC?url?: http://localhost:8080/{serviceExporter.getServiceName}
        httpRPCServer.start();

        // 
        IDLProxyFactoryBean idlProxyFactoryBean = new IDLProxyFactoryBean();
        idlProxyFactoryBean.setServiceUrl("http://localhost:8080/SimpleTest");
        idlProxyFactoryBean.setInputIDL(resource);
        idlProxyFactoryBean.setOutputIDL(resource);
        idlProxyFactoryBean.afterPropertiesSet();

        ClientInvoker<IDLProxyObject, IDLProxyObject> invoker = idlProxyFactoryBean.getObject();

        // send request
        IDLProxyObject input = invoker.getInput();
        if (input != null) {
            input.put("msg", "hello message.");
        }
        IDLProxyObject result = invoker.invoke(input);
        if (result != null) {
            Object msg = result.get("msg");
            Assert.assertEquals("new message", msg);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (httpRPCServer != null) {
            httpRPCServer.stop(0);
        }
    }
}

From source file:io.lavagna.model.MailConfig.java

private JavaMailSender toMailSender() {
    JavaMailSenderImpl r = new JavaMailSenderImpl();
    r.setDefaultEncoding("UTF-8");
    r.setHost(host);/*from  w w w.  j a v  a2s.  c o m*/
    r.setPort(port);
    r.setProtocol(protocol);
    r.setUsername(username);
    r.setPassword(password);
    if (properties != null) {
        try {
            Properties prop = PropertiesLoaderUtils.loadProperties(
                    new EncodedResource(new ByteArrayResource(properties.getBytes("UTF-8")), "UTF-8"));
            r.setJavaMailProperties(prop);
        } catch (IOException e) {
            LOG.warn("error while setting the mail sender properties", e);
        }
    }
    return r;
}

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

@Test
public void testLoadResourceWithSelectedDocuments() throws Exception {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(new Resource[] {
            new ByteArrayResource("foo: 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"));
}

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

@Test
public void testActiveProfilesFromYaml() throws Exception {

    Mockito.when(context.getResource(Matchers.anyString()))
            .thenReturn(new ByteArrayResource("spring_profiles: bar".getBytes()));

    initializer.initialize(context);/*from  ww  w .  j  ava2  s  .  c o  m*/

    assertEquals("bar", environment.getActiveProfiles()[0]);

}

From source file:nl.surfnet.coin.teams.service.impl.GroupServiceBasicAuthentication10aTest.java

@Test
public void testGetGroupMembersEntryFaultyHttpResponse() {
    super.setResponseResource(new ByteArrayResource("not-even-valid-json".getBytes()));
    super.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    GroupMembersEntry groupMembersEntry = groupService.getGroupMembersEntry(provider, "personId", "whatever", 0,
            0);//from  www.ja v  a 2  s.  co m
    assertTrue(groupMembersEntry.getEntry().isEmpty());
}

From source file:de.pksoftware.springstrap.sapi.controller.UpdateController.java

@RequestMapping(value = "/update-client", produces = "application/zip")
public HttpEntity<ByteArrayResource> updateClient() throws IOException, URISyntaxException {
    //String archiveFileName = clientSystemConfig.system.id + "-" + clientSystemConfig.system.version + ".zip";

    String archiveFileName = "springstrap-server.zip";

    //File file = new File("/home/pksoftware/dev-temp/ui5os-server-temp/" + archiveFileName);

    /*/*from  w  ww  .  j a  v a 2 s.c  o m*/
    if(file.exists()){
       logger.info("Update already packaged: {}", file.getAbsolutePath());
               
       FileInputStream fin = new FileInputStream(file);
       byteArray = new byte[(int)file.length()];
               
       // Reads up to certain bytes of data from this input stream into an array of bytes.
       fin.read(byteArray);
               
       fin.close();
    }
    else{
    */
    logger.info("Building update package...");

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    WebappZipper zipper = new WebappZipper(outputStream, servletContext);

    zipper.addResource("classpath*:/webjar/**", false);

    //zipper.addResource("/system/**", servletContext);
    zipper.addResource("/apps/**", true);
    zipper.addResource("/lib/**", true);

    zipper.addResource("/admin.html", true);
    zipper.addResource("/account.html", true);
    zipper.addResource("/microapp.html", true);

    zipper.close();

    byteArray = outputStream.toByteArray();

    outputStream.close();

    /*
    FileOutputStream fop = new FileOutputStream(file);
    fop.write(byteArray);
    fop.flush();
    fop.close();
    */
    //}

    //Send response

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentLength(byteArray.length);
    headers.set("Content-Disposition", "attachment; filename=\"" + archiveFileName + "\"");

    return new HttpEntity<ByteArrayResource>(new ByteArrayResource(byteArray), headers);

}

From source file:ca.intelliware.ihtsdo.mlds.web.rest.MemberResource.java

private ResponseEntity<?> downloadFile(HttpServletRequest request, File file) throws SQLException, IOException {
    if (file == null) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    } else if (file.getLastUpdated() != null) {
        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        long lastUpdatedSecondsFloor = file.getLastUpdated().getMillis() / 1000 * 1000;
        if (ifModifiedSince != -1 && lastUpdatedSecondsFloor <= ifModifiedSince) {
            return new ResponseEntity<>(HttpStatus.NOT_MODIFIED);
        }//from   ww w  .j  a  v a2  s. c  o m
    }

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(MediaType.valueOf(file.getMimetype()));
    httpHeaders.setContentLength(file.getContent().length());
    httpHeaders.setContentDispositionFormData("file", file.getFilename());
    if (file.getLastUpdated() != null) {
        httpHeaders.setLastModified(file.getLastUpdated().getMillis());
    }

    byte[] byteArray = IOUtils.toByteArray(file.getContent().getBinaryStream());
    org.springframework.core.io.Resource contents = new ByteArrayResource(byteArray);
    return new ResponseEntity<org.springframework.core.io.Resource>(contents, httpHeaders, HttpStatus.OK);
}

From source file:alfio.util.TemplateManager.java

public String renderTemplate(Event event, TemplateResource templateResource, Map<String, Object> model,
        Locale locale) {/*from   w w w.j a va  2s . c o m*/
    return uploadedResourceManager
            .findCascading(event.getOrganizationId(), event.getId(), templateResource.getSavedName(locale))
            .map(resource -> render(new ByteArrayResource(resource), model, locale,
                    templateResource.getTemplateOutput()))
            .orElseGet(() -> renderTemplate(templateResource, model, locale));
}

From source file:com.ezsource_mobile.fileservice.FileService.java

public FileUploadResponse[] uploadFile(final MultipartFile[] files, final String relativePath,
        final HttpServletRequest httpServletRequest) {
    LOGGER.debug("start of uploadFile method");

    final RestTemplate restTemplate = new RestTemplate();
    FileUploadResponse[] result;/*w  ww  . j  av  a2  s .  c om*/
    try {
        final String url = getFileUploadUrl(httpServletRequest);
        final String fileName = files[0].getOriginalFilename();

        final LinkedMultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>();
        final ByteArrayResource contentsAsResource = new ByteArrayResource(files[0].getBytes()) {
            @Override
            public String getFilename() {
                return fileName;
            }
        };
        body.add("files", contentsAsResource);

        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.add("Authorization",
                "Basic " + Base64.encodeBase64String(new StringBuilder(securityService.getUserName())
                        .append(":").append(getHash()).toString().getBytes()));

        final HttpEntity<LinkedMultiValueMap<String, Object>> request = new HttpEntity<LinkedMultiValueMap<String, Object>>(
                body, headers);
        result = restTemplate.postForObject(url, request, FileUploadResponse[].class);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    LOGGER.debug("end of uploadFile method" + result);
    return result;

}

From source file:com.aurora.mail.service.MailService.java

/**
 * @param to/*from   w  ww.  ja  v  a2s  .  c om*/
 * @param subject
 * @param content
 * @param isMultipart
 * @param isHtml
 */
@Async
public void sendEmailWithAttachment(String to, String subject, String content, final String attachmentFileName,
        final byte[] attachmentBytes, final String attachmentContentType, boolean isMultipart, boolean isHtml) {
    log.debug("Send e-mail to user '{}'!", to);

    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);

    // Prepare message using a Spring helper
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, CharEncoding.UTF_8);
        message.setTo(to);
        message.setFrom(from);
        message.setSubject(subject);
        message.setText(content, isHtml);

        // Add the attachment
        message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);
        javaMailSender.send(mimeMessage);
        log.debug("Sent e-mail to User '{}'!", to);
    } catch (Exception e) {
        log.error("E-mail could not be sent to user '{}', exception is: {}", to, e.getMessage());
    }
}