Example usage for org.apache.commons.io IOUtils toByteArray

List of usage examples for org.apache.commons.io IOUtils toByteArray

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils toByteArray.

Prototype

public static byte[] toByteArray(String input) throws IOException 

Source Link

Document

Get the contents of a String as a byte[] using the default character encoding of the platform.

Usage

From source file:net.jadler.stubbing.Request.java

public Request(String method, URI requestUri, Map<String, List<String>> headers, InputStream body,
        InetSocketAddress localAddress, InetSocketAddress remoteAddress, String encoding) throws IOException {
    this.method = method;
    this.requestUri = requestUri;
    this.encoding = encoding != null ? encoding : "ISO-8859-1"; //HTTP default
    this.body = IOUtils.toByteArray(body);
    this.headers = copyHeaders(headers);
    this.parameters = readParameters();
    this.localAddress = localAddress;
    this.remoteAddress = remoteAddress;
}

From source file:com.example.controller.ImageController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String save(HttpServletRequest req, HttpServletResponse res, HttpSession session)
        throws IOException, FileUploadException, ClassNotFoundException, SQLException {

    // Get the image representation
    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(req);
    FileItemStream imageItem = iter.next();
    InputStream imgStream = imageItem.openStream();

    // construct our entity objects
    Blob imageBlob = new Blob(IOUtils.toByteArray(imgStream));
    MyImages myImage = new MyImages(imageBlob);

    // persist image
    Users us = (Users) session.getAttribute("user");
    String user = us.getUsername();
    if (MyImageDao.getImage(user) != null) {
        MyImageDao.updateImage(user, imageBlob);
        return "profile";
    } else {/*from w  ww.  j a  v a  2 s .  c  o m*/
        MyImageDao.addImage(user, myImage);
    }
    // respond to query
    return "Home";
}

From source file:com.enonic.cms.core.mail.AbstractSendMailService.java

public final void sendMail(AbstractMailTemplate template) {
    try {/*from   w ww .  ja va 2s  .  co  m*/
        MessageSettings settings = new MessageSettings();

        setFromSettings(template, settings);

        settings.setBody(template.getBody());

        final MimeMessageHelper message = createMessage(settings,
                template.isHtml() || !template.getAttachments().isEmpty());
        message.setSubject(template.getSubject());

        final Map<String, InputStream> attachments = template.getAttachments();

        for (final Map.Entry<String, InputStream> attachment : attachments.entrySet()) {
            message.addAttachment(attachment.getKey(),
                    new ByteArrayResource(IOUtils.toByteArray(attachment.getValue())));
        }

        if (template.isHtml()) {
            message.setText("[You need html supported mail client to read this email]", template.getBody());
        } else {
            message.setText(template.getBody());
        }

        if (template.getMailRecipients().size() == 0) {
            this.log.info("No recipients specified, mail not sent.");
        }

        for (MailRecipient recipient : template.getMailRecipients()) {
            if (recipient.getEmail() != null) {
                final MailRecipientType type = recipient.getType();

                switch (type) {
                case TO_RECIPIENT:
                    message.addTo(recipient.getEmail(), recipient.getName());
                    break;
                case BCC_RECIPIENT:
                    message.addBcc(recipient.getEmail(), recipient.getName());
                    break;
                case CC_RECIPIENT:
                    message.addCc(recipient.getEmail(), recipient.getName());
                    break;
                default:
                    throw new RuntimeException("Unknown recipient type: " + type);
                }
            }
        }

        sendMessage(message);
    } catch (Exception e) {
        this.log.error("Failed to send mail", e);
    }
}

From source file:net.nicholaswilliams.java.licensing.samples.SampleFilePrivateKeyDataProvider.java

/**
 * This method returns the data from the file containing the encrypted
 * private key from the public/private key pair. The contract for this
 * method can be fulfilled by storing the data in a byte array literal
 * in the source code itself./*from  www.j  av a 2 s.c  o m*/
 *
 * @return the encrypted file contents from the private key file.
 * @throws KeyNotFoundException if the key data could not be retrieved; an acceptable message or chained cause must be provided.
 */
public byte[] getEncryptedPrivateKeyData() throws KeyNotFoundException {
    try {
        return IOUtils.toByteArray(this.getClass().getResourceAsStream("sample.private.key"));
    } catch (IOException e) {
        throw new KeyNotFoundException("The private key file was not found.", e);
    }
}

From source file:mytubermiserver.RMIClient.java

public void upload(String fileName, InputStream videoStream)
        throws RemoteException, NotBoundException, IOException {
    try (OutputStream ostream = RemoteOutputStreamClient.wrap(server.uploadOutputStream(fileName))) {
        ostream.write(IOUtils.toByteArray(videoStream));
        ostream.flush();//from w w  w  .ja va  2s  .  c o m
        ostream.close();
        server.saveInDatabase(fileName);
    }
}

From source file:de.brendamour.jpasskit.signing.PKPassTemplateFolder.java

@Override
public Map<String, ByteBuffer> getAllFiles() throws IOException {
    Map<String, ByteBuffer> allFiles = new HashMap<>();
    for (File file : new File(pathToTemplateDirectory).listFiles()) {
        byte[] byteArray = IOUtils.toByteArray(new FileInputStream(file));
        String filePath = file.getAbsolutePath().replace(pathToTemplateDirectory, "");
        allFiles.put(filePath, ByteBuffer.wrap(byteArray));
    }/* w  w w.ja v a  2s .  c  o m*/
    return allFiles;
}

From source file:com.egs.blog.auth.UserRegister.java

public String registerUser() {
    User user = new User();
    user.setUsername(userName);// w  w w .j a va 2 s . c o  m
    user.setEmail(email);
    user.setPassword(password);
    user.setFirstname(firstName);
    user.setLastname(lastName);
    if (user.getImageNeme() == null) {
        user.setImageNeme("def.jpg");
    }

    InputStream input;
    try {
        input = file.getInputStream();
        byte[] image = IOUtils.toByteArray(input); // Apache commons IO.
        user.setImageData(image);
    } catch (IOException ex) {
        Logger.getLogger(UserRegister.class.getName()).log(Level.SEVERE, null, ex);
    }

    User registeredUser = userService.userRegister(user);
    if (user != null) {
        sessionContext.setUser(registeredUser);
        return "home";
    } else {
        return null;
    }
}

From source file:com.sysunite.weaver.nifi.FilterXMLNodesTest.java

@Test
public void testOnTrigger() {

    try {//from w  w  w  . j a v  a2s  . com
        String file = "slagboom.xml";

        byte[] contents = FileUtils
                .readFileToByteArray(new File(getClass().getClassLoader().getResource(file).getFile()));

        InputStream in = new ByteArrayInputStream(contents);

        InputStream cont = new ByteArrayInputStream(IOUtils.toByteArray(in));

        // Generate a test runner to mock a processor in a flow
        TestRunner runner = TestRunners.newTestRunner(new FilterXMLNodes());

        // Add properites
        runner.setProperty(FilterXMLNodes.PROP_NODE, "FunctionalPhysicalObject");
        runner.setProperty(FilterXMLNodes.PROP_NODE_ATTRIBUTE, "name");
        runner.setProperty(FilterXMLNodes.PROP_PREGMATCH, "(.*)AB(.*)CT(.*)");

        // Add the content to the runner
        runner.enqueue(cont);

        // Run the enqueued content, it also takes an int = number of contents queued
        runner.run();

        // All results were processed with out failure
        //runner.assertQueueEmpty();

        // If you need to read or do aditional tests on results you can access the content
        List<MockFlowFile> results = runner.getFlowFilesForRelationship(FilterXMLNodes.MY_RELATIONSHIP);
        //assertTrue("1 match", results.size() == 1);

        System.out.println("aantal gevonden: " + results.size());

        //MockFlowFile result = results.get(0);
        //String resultValue = new String(runner.getContentAsByteArray(result));
        //System.out.println("Match: " + IOUtils.toString(runner.getContentAsByteArray(result)));
    } catch (IOException e) {
        System.out.println("FOUT!!");
        System.out.println(e.getStackTrace());
    }
}

From source file:com.github.cutstock.excel.model.ExcelProfileTitle.java

private void initDefaultSettings() {
    //      style = ExcelUtil.getStyle(CellType.TITLE.type());
    InputStream is = null;/*  ww  w.j av  a 2s .  co  m*/
    try {
        is = getClass().getClassLoader().getResourceAsStream("resources/excel_logo.jpg");
        logo = IOUtils.toByteArray(is);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.github.zdsiyan.maven.plugin.smartconfig.internal.XPathConfigurator.java

@Override
public ByteArrayOutputStream execute(InputStream in, Charset charset, List<PointHandle> pointhandles)
        throws IOException {
    try {//from  w w w.ja v  a2s.com
        VTDGen vtdGen = new VTDGen();
        vtdGen.setDoc(IOUtils.toByteArray(in));
        vtdGen.parse(true);

        VTDNav vtdNav = vtdGen.getNav();
        VTDUtils utils = new VTDUtils(vtdNav);
        AutoPilot autoPilot = new AutoPilot(vtdNav);
        XMLModifier xmlModifier = new XMLModifier(vtdNav);

        for (PointHandle point : pointhandles) {
            switch (point.getMode()) {
            case insert:
                xmlModifier = utils.insert(autoPilot, xmlModifier, point.getExpression(), point.getValue());
                break;
            case delete:
                xmlModifier = utils.delete(autoPilot, xmlModifier, point.getExpression());
                break;
            case replace:
            default:
                xmlModifier = utils.update(autoPilot, xmlModifier, point.getExpression(), point.getValue());
                break;
            }
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        xmlModifier.output(out);
        return out;
    } catch (Exception ex) {
        // FIXME
        throw new RuntimeException(ex);
    }
}