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:es.uma.inftel.blog.servlet.PerfilServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from w ww  .j a  v  a  2s .co  m
 *
 * @param request servlet request
 * @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");

    BaseView baseView = new BaseView();
    BaseViewFacade<BaseView> baseViewFacade = new BaseViewFacade<>(postFacade);
    baseViewFacade.initView(baseView);

    RequestDispatcher requestDispatcher = request.getRequestDispatcher("perfil.jsp");
    String password = request.getParameter("password");
    if (password == null) {
        request.setAttribute("perfilView", baseView);
        requestDispatcher.forward(request, response);
    }

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

    Part filePart = request.getPart("avatar");
    byte[] avatar = null;
    if (!filePart.getSubmittedFileName().isEmpty()) {
        InputStream inputStream = filePart.getInputStream();
        avatar = IOUtils.toByteArray(inputStream);
    }

    HttpSession session = request.getSession();
    Usuario usuario = (Usuario) session.getAttribute("usuario");

    modificarUsuario(usuario, password, email, avatar);
    response.sendRedirect("perfil");

}

From source file:de.cismet.cids.custom.wunda_blau.search.actions.VermessungsUnterlagenPortalDownloadAction.java

@Override
public Object execute(final Object body, final ServerActionParameter... params) {
    final String schluessel = (String) body;
    InputStream inputStream = null;
    try {/* www . j ava 2 s  . co m*/
        final String downloadFrom = VermessungsunterlagenHelper.getInstance().getProperties().getDownloadFrom();
        if (VermessungsunterlagenProperties.FROM_WEBDAV.equals(downloadFrom)) {
            final String tmp = VermessungsunterlagenHelper.getInstance().getProperties().getWebDavPath();
            final String webDavPath = (tmp.isEmpty() ? "" : ("/" + tmp)) + "/"
                    + VermessungsunterlagenHelper.DIR_PREFIX + "_" + schluessel + ".zip";
            inputStream = VermessungsunterlagenHelper.getInstance().downloadFromWebDAV(webDavPath);
        } else if (VermessungsunterlagenProperties.FROM_FTP.equals(downloadFrom)) {
            final String tmp = VermessungsunterlagenHelper.getInstance().getProperties().getFtpPath();
            final String ftpZipPath = (tmp.isEmpty() ? "" : ("/" + tmp)) + "/"
                    + VermessungsunterlagenHelper.DIR_PREFIX + "_" + schluessel + ".zip";
            inputStream = VermessungsunterlagenHelper.getInstance().downloadFromFTP(ftpZipPath);
        }
        return IOUtils.toByteArray(inputStream);
    } catch (final Exception ex) {
        return new Exception("Fehler beim Herunterladen der Zip-Datei.", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:de.fichtelmax.asn1.ASN1PrinterTest.java

@Test
public void printX509() throws IOException, CertificateException {
    byte[] x509Bytes = IOUtils.toByteArray(ASN1Printer.class.getResourceAsStream("/certificate.crt"));

    cut.print(x509Bytes);//from w ww  . j av a 2  s .c om

    verify(out, never()).println(ASN1Printer.INCOMPLETE_MESSAGE);
}

From source file:net.peterkuterna.appengine.apps.devoxxsched.util.Md5Calculator.java

private byte[] getResponse(final String requestUri) {
    try {/*w  ww. j a v  a  2 s.c o m*/
        URL url = new URL(requestUri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-agent", "Devoxx Schedule AppEngine Backend");
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(120 * 1000);
        connection.setRequestProperty("Cache-Control", "no-cache,max-age=0");
        connection.setRequestProperty("Pragma", "no-cache");
        InputStream response = connection.getInputStream();
        log.info("response = " + connection.getResponseCode());
        if (connection.getResponseCode() == 200) {
            return IOUtils.toByteArray(response);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

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

@Override
public Map<String, ByteBuffer> getAllFiles() throws IOException {
    Map<String, ByteBuffer> allFiles = new HashMap<>();
    for (Entry<String, InputStream> entry : files.entrySet()) {
        byte[] byteArray = IOUtils.toByteArray(entry.getValue());
        String filePath = entry.getKey();
        allFiles.put(filePath, ByteBuffer.wrap(byteArray));
    }//from w  w w  .ja v a  2s . c o  m
    return allFiles;
}

From source file:io.swagger.inflector.processors.BinaryProcessor.java

@Override
public Object process(MediaType mediaType, InputStream entityStream, JavaType javaType) {
    try {//  w  w w. j a  v a  2 s . c om
        return IOUtils.toByteArray(entityStream);
    } catch (IOException e) {
        LOGGER.error("unable to extract entity from content-type `" + mediaType + "` to byte[]", e);
    }
    return null;
}

From source file:edu.ubb.bsc.rest.RestSheetMusicUpload.java

/**
 * /** Upload sheet music//from   w w w .  j a va2 s .  co  m
 * 
 * @param uploadedInputStreamPdf
 * @param uploadedInputStreamSound
 * @param name
 * @param length
 * @param license
 * @param genre_id
 * @param request
 * @return
 * @throws JSONException
 */
@POST
@Path("/upload")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({ MediaType.APPLICATION_JSON })
public String uploadSheetMusic(@FormDataParam("filepdf") InputStream uploadedInputStreamPdf,
        @FormDataParam("filesound") InputStream uploadedInputStreamSound, @FormDataParam("name") String name,
        @FormDataParam("length") Integer length, @FormDataParam("license") String license,
        @FormDataParam("genre_id") Integer genre_id, @FormDataParam("instrumentList") List<FormDataBodyPart> v1,
        @Context HttpServletRequest request) throws JSONException {

    SheetMusicServiceImpl service;
    JSONObject jo = new JSONObject();

    try {
        SheetMusic sm = new SheetMusic();
        sm.setName(name);
        sm.setLength(length);
        sm.setLicense(license);
        sm.setUploadDate(new Date());
        sm.setViewsNum(0);

        byte[] bytesPdf = IOUtils.toByteArray(uploadedInputStreamPdf);
        sm.setFilePdf(bytesPdf);
        if (bytesPdf.length < 10) {
            throw new ServiceException("PDF File not valide!");
        }

        SongGenre sg = new SongGenre();
        sg.setSongGenreId(genre_id);
        sm.setSongGenre(sg);

        // Logged in user
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("logged-user");
        System.out.println("Logged in user: " + user);
        sm.setUser(user);

        byte[] bytesSound = IOUtils.toByteArray(uploadedInputStreamSound);
        sm.setFileSound(bytesSound);
        if (bytesSound.length < 10) {
            throw new ServiceException("Sound File not valide!");
        }
        System.err.println(sm);

        service = new SheetMusicServiceImpl();
        service.insertSheetmusic(sm);

        // Insert InstrumentSheetmusic n-m relation
        try {
            for (FormDataBodyPart instrId : v1) {
                String v = instrId.getValueAs(String.class);
                System.out.println("Form: " + v);
                String[] id = v.split(",");
                for (String string : id) {
                    Instrument i = new Instrument();
                    InstrumentSheetMusicServiceImpl ishmImpl = new InstrumentSheetMusicServiceImpl();
                    i.setInstrumentId(Integer.parseInt(string));
                    InstrumentSheetmusic ism = new InstrumentSheetmusic();

                    ism.setInstrument(i);
                    ism.setSheetMusic(sm);

                    ishmImpl.insertInstrumentSheetmusic(ism);
                }
            }
        } catch (NumberFormatException ex) {
        }

        log.info("Sheetmusic uploaded");

    } catch (ServiceException e) {
        jo.put("message", "Error in saving sheet music! " + e);
        jo.put("alert_type", "alert alert-danger");
        log.error("Error in saving sheet music!", e);
        return jo.toString();
    } catch (IOException e) {
        jo.put("message", "Error, file failed!");
        jo.put("alert_type", "alert alert-danger");
        log.error("Error, file failed!", e);
        return jo.toString();
    } catch (Exception e) {
        jo.put("message", "Error in saving sheet music! " + e);
        jo.put("alert_type", "alert alert-danger");
        log.error("Error in saving sheet music!", e);
        return jo.toString();
    }

    jo.put("message", "Upload was successfull!");
    jo.put("alert_type", "alert alert-success");
    return jo.toString();
}

From source file:com.splicemachine.derby.impl.sql.execute.operations.export.ExportFileTest.java

@Test
public void getOutputStream_createsStreamConnectedToExpectedFile() throws IOException {

    // given//from  w w  w. j a v  a 2 s . c  o m
    ExportParams exportParams = ExportParams.withDirectory(temporaryFolder.getRoot().getAbsolutePath());
    ExportFile exportFile = new ExportFile(exportParams, testTaskId(), dfs);
    final byte[] EXPECTED_CONTENT = ("splice for the win" + RandomStringUtils.randomAlphanumeric(1000))
            .getBytes("utf-8");

    // when
    OutputStream outputStream = exportFile.getOutputStream();
    outputStream.write(EXPECTED_CONTENT);
    outputStream.close();

    // then
    File expectedFile = new File(temporaryFolder.getRoot(), "export_82010203042A060708.csv");
    assertTrue(expectedFile.exists());
    Assert.assertArrayEquals(EXPECTED_CONTENT, IOUtils.toByteArray(new FileInputStream(expectedFile)));
}

From source file:gobblin.crypto.RotatingAESCodecTest.java

@Test
public void testStreams() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {
    final byte[] toWrite = "hello world".getBytes();

    SimpleCredentialStore credStore = new SimpleCredentialStore();
    RotatingAESCodec encryptor = new RotatingAESCodec(credStore);
    ByteArrayOutputStream sink = new ByteArrayOutputStream();
    OutputStream os = encryptor.encodeOutputStream(sink);
    os.write(toWrite);// w  w w .j av  a 2 s.  co  m
    os.close();
    byte[] encryptedBytes = sink.toByteArray();

    manuallyDecodeAndVerifyBytes(toWrite, encryptedBytes, credStore);

    // Try with stream
    InputStream decoderIn = encryptor.decodeInputStream(new ByteArrayInputStream(encryptedBytes));
    byte[] decoded = IOUtils.toByteArray(decoderIn);
    Assert.assertEquals(decoded, toWrite, "Expected decoded output to match encoded output");
}

From source file:com.lightboxtechnologies.ingest.InfoPutter.java

public int run(String[] args) throws DecoderException, IOException {
    if (args.length != 3) {
        System.err.println("Usage: InfoPutter <imageID> <friendly_name> <pathToImageOnHDFS>");
        return 1;
    }/*  w w w. ja v a2s  .  c om*/

    final Configuration conf = getConf();

    final String imageID = args[0];
    final String friendlyName = args[1];
    final String imgPath = args[2];

    HTable imgTable = null;

    try {
        imgTable = HBaseTables.summon(conf, HBaseTables.IMAGES_TBL_B, HBaseTables.IMAGES_COLFAM_B);

        // check whether the image ID is in the images table
        final byte[] hash = new Hex().decode(imageID.getBytes());

        final Get get = new Get(hash);
        final Result result = imgTable.get(get);

        if (result.isEmpty()) {
            // row does not exist, add it

            final byte[] friendly_col = "friendly_name".getBytes();
            final byte[] json_col = "json".getBytes();
            final byte[] path_col = "img_path".getBytes();

            final byte[] friendly_b = friendlyName.getBytes();
            final byte[] json_b = IOUtils.toByteArray(System.in);
            final byte[] path_b = imgPath.getBytes();

            final Put put = new Put(hash);
            put.add(HBaseTables.IMAGES_COLFAM_B, friendly_col, friendly_b);
            put.add(HBaseTables.IMAGES_COLFAM_B, json_col, json_b);
            put.add(HBaseTables.IMAGES_COLFAM_B, path_col, path_b);

            imgTable.put(put);

            return 0;
        } else {
            // row exists, fail!
            return 1;
        }
    } finally {
        if (imgTable != null) {
            imgTable.close();
        }
    }
}