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:com.square.print.core.service.implementations.EditiqueServiceImpl.java

@Override
public FichierDto genererPdfDocumentsBulletinsAdhesion(
        DocumentsBulletinsAdhesionDto documentsBulletinsAdhesionDto) {
    try {/*w  w w  .j a  v a  2s  .  c  o m*/
        final byte[] contenuFichier = IOUtils.toByteArray(this.getClass().getResourceAsStream("/matrice.pdf"));
        final FichierDto fichier = new FichierDto("", Magic.getMagicMatch(contenuFichier).getMimeType(),
                contenuFichier);
        return fichier;
    } catch (IOException e) {
        throw new TechnicalException(e.getMessage(), e);
    } catch (MagicParseException e) {
        throw new TechnicalException(e.getMessage(), e);
    } catch (MagicMatchNotFoundException e) {
        throw new TechnicalException(e.getMessage(), e);
    } catch (MagicException e) {
        throw new TechnicalException(e.getMessage(), e);
    }
}

From source file:alluxio.master.block.MultiWorkerIntegrationTest.java

@Test
public void writeLargeFile() throws Exception {
    int fileSize = NUM_WORKERS * WORKER_MEMORY_SIZE_BYTES;
    AlluxioURI file = new AlluxioURI("/test");
    FileSystem fs = mResource.get().getClient();
    // Write a file large enough to fill all the memory of all the workers.
    FileSystemTestUtils.createByteFile(fs, file.getPath(), fileSize, CreateFileOptions.defaults()
            .setWriteType(WriteType.MUST_CACHE).setLocationPolicy(new RoundRobinPolicy()));
    URIStatus status = fs.getStatus(file);
    assertEquals(100, status.getInMemoryPercentage());
    try (FileInStream inStream = fs.openFile(file)) {
        assertEquals(fileSize, IOUtils.toByteArray(inStream).length);
    }//from  www  .ja  v  a  2s  .c om
}

From source file:es.uma.inftel.blog.servlet.RegistroServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/* w ww.ja  v  a  2s .  co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    String username = request.getParameter("username");
    String password = request.getParameter("password");

    RegistroViewFacade registroViewFacade = new RegistroViewFacade(postFacade);

    RequestDispatcher registroRequestDispatcher = request.getRequestDispatcher("registro.jsp");
    if (username == null && password == null) {
        request.setAttribute("registroView", registroViewFacade.createView(false));
        registroRequestDispatcher.forward(request, response);
        return;
    }

    String email = request.getParameter("email");

    Part filePart = request.getPart("avatar");
    InputStream inputStream = filePart.getInputStream();
    byte[] avatar = IOUtils.toByteArray(inputStream);

    Usuario usuario = registrarUsuario(username, password, email, avatar);
    if (usuario == null) {
        request.setAttribute("registroView", registroViewFacade.createView(true));
        registroRequestDispatcher.forward(request, response);
    } else {
        HttpSession session = request.getSession();
        session.setAttribute("usuario", usuario);
        response.sendRedirect("index");
    }
}

From source file:net.netheos.pcsapi.BytesIOTest.java

private void checkByteSource(ByteSource bs, byte[] expectedContent) throws IOException {
    assertEquals(70, bs.length());/*from   w w  w  . j  a va  2 s  .c  om*/

    InputStream is = bs.openStream();
    byte[] b = IOUtils.toByteArray(is);
    assertTrue(Arrays.equals(expectedContent, b));
    is.close();

    // Create a range view of this byte source : 25 bytes starting at offset 5 :
    RangeByteSource rbs = new RangeByteSource(bs, 5, 25);
    assertEquals(25, rbs.length());
    is = rbs.openStream();

    try {
        b = new byte[1];
        is.read(b);
        assertEquals("1", new String(b, PcsUtils.UTF8));

        b = new byte[3];
        is.read(b);
        assertEquals("", new String(b, PcsUtils.UTF8));

        b = new byte[100];
        int len = is.read(b);
        assertEquals(21, len);
        final String actual = new String(b, 0, 21, PcsUtils.UTF8);
        assertEquals(" file is the test con", actual);

        b = new byte[100];
        len = is.read(b);
        assertEquals(0, len);

    } finally {
        IOUtils.closeQuietly(is);
    }

    // Now decorate again with a progress byte source
    StdoutProgressListener pl = new StdoutProgressListener();
    ProgressByteSource pbs = new ProgressByteSource(rbs, pl);
    assertEquals(rbs.length(), pbs.length());
    is = pbs.openStream();

    try {
        assertEquals(pbs.length(), pl.getTotal());
        assertEquals(0, pl.getCurrent());
        assertFalse(pl.isAborted());

        b = new byte[1];
        is.read(b);
        assertEquals(1, pl.getCurrent());

        b = new byte[10];
        is.read(b);
        assertEquals(11, pl.getCurrent());

        b = new byte[500];
        int len = is.read(b);
        assertEquals(14, len);
        assertEquals(25, pl.getCurrent());

    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:edu.unc.lib.dl.data.ingest.solr.indexing.DocumentIndexingPackageFactoryTest.java

@Test
public void testCreateDocumentIndexingPackageWithMDContents() throws Exception {

    byte[] stream = IOUtils.toByteArray(getClass().getResourceAsStream("/datastream/mdContents.xml"));

    when(datastream.getStream()).thenReturn(stream);
    when(accessClient.getDatastreamDissemination(any(PID.class), eq(Datastream.MD_CONTENTS.getName()),
            anyString())).thenReturn(datastream);

    DocumentIndexingPackage dip = dipFactory.createDocumentIndexingPackageWithMDContents(new PID("pid"));

    assertNotNull("Factory must return a dip", dip);
    assertNotNull("Factory must have assigned md contents", dip.getMdContents());

    verify(accessClient).getDatastreamDissemination(any(PID.class), eq(Datastream.MD_CONTENTS.getName()),
            anyString());/* w  w w  .  ja v a  2 s. com*/
}

From source file:de.micromata.genome.gwiki.web.StaticFileServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String uri = req.getPathInfo();
    String servletp = req.getServletPath();
    String respath = servletp + uri;
    if (uri == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;//from ww  w  . j a v  a  2s  .  c  om
    }

    InputStream is = getServletContext().getResourceAsStream(respath);
    if (is == null) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    long nt = new Date().getTime() + TimeInMillis.DAY;
    String mime = MimeUtils.getMimeTypeFromFile(respath);
    if (StringUtils.equals(mime, "application/x-shockwave-flash")) {
        resp.setHeader("Cache-Control", "cache, must-revalidate");
        resp.setHeader("Pragma", "public");
    }
    resp.setDateHeader("Expires", nt);
    resp.setHeader("Cache-Control", "max-age=86400, public");
    if (mime != null) {
        resp.setContentType(mime);
    }

    byte[] data = IOUtils.toByteArray(is);
    IOUtils.closeQuietly(is);
    resp.setContentLength(data.length);
    IOUtils.write(data, resp.getOutputStream());
}

From source file:com.leclercb.commons.api.license.LicenseManager.java

public LicenseManager(InputStream publicKey, InputStream privateKey) throws Exception {
    byte[] pubdata = IOUtils.toByteArray(publicKey);
    byte[] privdata = null;

    if (privateKey != null) {
        privdata = IOUtils.toByteArray(privateKey);
    }//  w w  w. j  a  v a2 s .  c  om

    this.encryptionManager = new EncryptionManager(pubdata, privdata);
}

From source file:info.magnolia.test.mock.jcr.MockValue.java

public MockValue(Object value, int type) {
    this.type = type;
    Object valueToSet;//from www.  j ava 2s .c  o  m
    try {
        if (value instanceof InputStream) {
            valueToSet = new String(IOUtils.toByteArray((InputStream) value));
        } else if (value instanceof Integer) {
            valueToSet = (long) ((Integer) value).intValue();
        } else {
            valueToSet = value;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    this.value = valueToSet;
}

From source file:com.teasoft.teavote.util.Signature.java

private PrivateKey getPrivateKey() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    Resource resource = res.getResource("classpath:xormeSafui");
    byte[] privKeyBytes;
    try (InputStream privKeyInputStream = resource.getInputStream()) {
        privKeyBytes = IOUtils.toByteArray(privKeyInputStream);
        privKeyBytes = Base64.decodeBase64(privKeyBytes);
    }//www.j  a v  a2  s .  c  o m
    PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("DSA");
    PrivateKey privKey = keyFactory.generatePrivate(privKeySpec);
    return privKey;
}

From source file:ee.ria.xroad.proxy.testsuite.testcases.Utf8BomAttachment2.java

@Override
protected void validateNormalResponse(Message receivedResponse) throws Exception {
    RequestHash requestHashFromResponse = ((SoapMessageImpl) receivedResponse.getSoap()).getHeader()
            .getRequestHash();/*  ww  w  .j  a  va2 s.c  om*/

    byte[] requestFileBytes = IOUtils.toByteArray(getRequestInput(false).getRight());
    byte[] requestSoapBytes = Arrays.copyOfRange(requestFileBytes, 64,
            1156 + getQueryId().getBytes("UTF-8").length);

    byte[] requestHash = CryptoUtils.calculateDigest(
            CryptoUtils.getAlgorithmId(requestHashFromResponse.getAlgorithmId()), requestSoapBytes);

    if (!Arrays.areEqual(requestHash, CryptoUtils.decodeBase64(requestHashFromResponse.getHash()))) {
        throw new RuntimeException("Request message hash does not match request message");
    }
}