Example usage for org.apache.commons.io FileUtils readFileToByteArray

List of usage examples for org.apache.commons.io FileUtils readFileToByteArray

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readFileToByteArray.

Prototype

public static byte[] readFileToByteArray(File file) throws IOException 

Source Link

Document

Reads the contents of a file into a byte array.

Usage

From source file:com.music.Generator.java

public byte[] toMp3(byte[] midi) throws Exception {
    //allowing a maximum number users to generate tracks at the same time so that the system remains stable (midi->wav->mp3 is heavy)
    semaphore.acquire();/* w ww .j  ava 2  s  .  com*/
    try {
        File wav = File.createTempFile("gen", ".wav");
        long start = System.currentTimeMillis();
        try (OutputStream fos = new BufferedOutputStream(new FileOutputStream(wav))) {
            Midi2WavRenderer.midi2wav(new ByteArrayInputStream(midi), fos);
            IOUtils.write(midi, fos);
        }
        logger.info("midi2wav conversion took: " + (System.currentTimeMillis() - start) + " millis");
        start = System.currentTimeMillis();
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        AudioAttributes audio = new AudioAttributes();
        //            audio.setBitRate(36000);
        //            audio.setSamplingRate(20000);
        attrs.setAudioAttributes(audio);
        attrs.setThreads(1);
        File mp3 = File.createTempFile("gen", ".mp3");
        encoder.encode(wav, mp3, attrs);
        logger.info("wav2mp3 conversion took: " + (System.currentTimeMillis() - start) + " millis");
        wav.delete(); //cleanup the big wav file
        byte[] mp3Bytes = FileUtils.readFileToByteArray(mp3);
        mp3.delete();
        return mp3Bytes;
    } finally {
        semaphore.release();
    }
}

From source file:de.unisaarland.swan.export.ExportUtil.java

private void createZipEntry(File file, ZipOutputStream zos) throws IOException {
    zos.putNextEntry(new ZipEntry(file.getName()));
    zos.write(FileUtils.readFileToByteArray(file));
    zos.closeEntry();/*from   w  w w. j  a v a  2 s  .  c  o m*/
}

From source file:com.t3.model.AssetManager.java

/**
 * Retrieve the asset from the persistent cache. If the asset is not in the cache, or loading from the cache failed
 * then this function returns null./*from   w  w w  .j a  v  a 2  s  . c  om*/
 * 
 * @param id
 *            MD5 of the requested asset
 * @return Asset from the cache
 */
private static Asset getFromPersistentCache(MD5Key id) {

    if (id == null || id.toString().length() == 0) {
        return null;
    }

    if (!assetIsInPersistentCache(id)) {
        return null;
    }

    File assetFile = getAssetCacheFile(id);

    try {
        byte[] data = FileUtils.readFileToByteArray(assetFile);
        Properties props = getAssetInfo(id);

        Asset asset = new Asset(props.getProperty(NAME), data);

        if (!asset.getId().equals(id)) {
            log.error("MD5 for asset " + asset.getName() + " corrupted");
        }

        assetMap.put(id, asset);

        return asset;
    } catch (IOException ioe) {
        log.error("Could not load asset from persistent cache", ioe);
        return null;
    }

}

From source file:$.ManagerService.java

/**
     * This will download the agent for given device type
     *//from   w  w w .  j av a2s.  co  m
     * @param deviceName name of the device which is to be created
     * @param sketchType name of sketch type
     * @return agent archive
     */
    @Path("manager/device/{sketch_type}/download")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response downloadSketch(@QueryParam("deviceName") String deviceName,
            @PathParam("sketch_type") String sketchType) {
        try {
            ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
            Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
            response.type("application/zip");
            response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
            return response.build();
        } catch (IllegalArgumentException ex) {
            return Response.status(400).entity(ex.getMessage()).build();//bad request
        } catch (DeviceManagementException ex) {
            return Response.status(500).entity(ex.getMessage()).build();
        } catch (AccessTokenException ex) {
            return Response.status(500).entity(ex.getMessage()).build();
        } catch (DeviceControllerException ex) {
            return Response.status(500).entity(ex.getMessage()).build();
        } catch (IOException ex) {
            return Response.status(500).entity(ex.getMessage()).build();
        }
    }

From source file:io.fabric8.maven.enricher.fabric8.IconEnricher.java

private String convertIconFileToURL(File iconFile, String iconRef) throws IOException {
    long length = iconFile.length();

    int sizeK = Math.round(length / 1024);

    byte[] bytes = FileUtils.readFileToByteArray(iconFile);
    byte[] encoded = Base64.encodeBase64(bytes);

    int base64SizeK = Math.round(encoded.length / 1024);

    if (base64SizeK < Configs.asInt(getConfig(Config.maximumDataUrlSizeK))) {
        String mimeType = URLConnection.guessContentTypeFromName(iconFile.getName());
        return "data:" + mimeType + ";charset=UTF-8;base64," + new String(encoded);
    } else {//w  ww .j  a v a 2 s . com
        File iconSourceFile = new File(appConfigDir, iconFile.getName());
        if (iconSourceFile.exists()) {
            File rootProjectFolder = getRootProjectFolder();
            if (rootProjectFolder != null) {
                String relativePath = FileUtil.getRelativePath(rootProjectFolder, iconSourceFile).toString();
                String relativeParentPath = FileUtil
                        .getRelativePath(rootProjectFolder, getProject().getBasedir()).toString();
                String urlPrefix = getConfig(Config.urlPrefix);
                if (StringUtils.isBlank(urlPrefix)) {
                    Scm scm = getProject().getScm();
                    if (scm != null) {
                        String url = scm.getUrl();
                        if (url != null) {
                            String[] prefixes = { "http://github.com/", "https://github.com/" };
                            for (String prefix : prefixes) {
                                if (url.startsWith(prefix)) {
                                    url = "https://cdn.rawgit.com/" + url.substring(prefix.length());
                                    break;
                                }
                            }
                            if (url.endsWith(relativeParentPath)) {
                                url = url.substring(0, url.length() - relativeParentPath.length());
                            }
                            urlPrefix = url;
                        }
                    }
                }
                if (StringUtils.isBlank(urlPrefix)) {
                    log.warn(
                            "No iconUrlPrefix defined or could be found via SCM in the pom.xml so cannot add an icon URL!");
                } else {
                    return String.format("%s/%s/%s", urlPrefix, getConfig(Config.branch), relativePath);
                }
            }
        } else {
            String embeddedIcon = embeddedIconsInConsole(iconRef, "img/icons/");
            if (embeddedIcon != null) {
                return embeddedIcon;
            } else {
                log.warn("Cannot find url for icon to use %s", iconRef);
            }
        }
    }
    return null;
}

From source file:au.org.ala.spatial.util.RecordsSmall.java

public int[] getUniqueIdx() throws Exception {
    File f = new File(filename + "records.csv.small.pointsUniqueIdx");

    int size = (int) f.length() / 4;
    int[] all = new int[size];

    byte[] e = FileUtils.readFileToByteArray(f);

    ByteBuffer bb = ByteBuffer.wrap(e);

    for (int i = 0; i < size; i++) {
        all[i] = bb.getInt();/*from w w w . j a  v a 2  s.  co  m*/
    }

    return all;
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlPage2Test.java

/**
 * @throws Exception if the test fails//from   w  w  w . j ava  2 s.  com
 */
@Test
public void save_image() throws Exception {
    final String html = "<html><body><img src='" + URL_SECOND + "'></body></html>";

    final URL url = getClass().getClassLoader().getResource("testfiles/tiny-jpg.img");
    final FileInputStream fis = new FileInputStream(new File(url.toURI()));
    final byte[] directBytes = IOUtils.toByteArray(fis);
    fis.close();

    final WebClient webClient = getWebClientWithMockWebConnection();
    final MockWebConnection webConnection = getMockWebConnection();

    webConnection.setResponse(URL_FIRST, html);
    final List<NameValuePair> emptyList = Collections.emptyList();
    webConnection.setResponse(URL_SECOND, directBytes, 200, "ok", "image/jpg", emptyList);

    final HtmlPage page = webClient.getPage(URL_FIRST);
    final HtmlImage img = page.getFirstByXPath("//img");
    assertEquals(URL_SECOND.toString(), img.getSrcAttribute());
    final File tmpFolder = tmpFolderProvider_.newFolder("hu");
    final File file = new File(tmpFolder, "hu_HtmlPageTest_save2.html");
    final File imgFile = new File(tmpFolder, "hu_HtmlPageTest_save2/second.jpeg");
    page.save(file);
    assertTrue(file.exists());
    assertTrue(file.isFile());
    final byte[] loadedBytes = FileUtils.readFileToByteArray(imgFile);
    assertTrue(loadedBytes.length > 0);
    assertEquals(URL_SECOND.toString(), img.getSrcAttribute());
}

From source file:de.micromata.genome.gwiki.plugin.rogmp3_1_0.RogMp3ActionBean.java

public Object onServiceTitleMp3Merged() {
    Title title = db.getTitleByPk(tit);/*from   w ww .  j a v  a  2  s . c o m*/
    List<Track> tracks = title.getTracks();
    String userName = getWikiContext().getWikiWeb().getAuthorization().getCurrentUserName(getWikiContext());
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {
        for (Track track : tracks) {
            byte[] trdata = FileUtils.readFileToByteArray(track.getMp3Path());
            bout.write(trdata);
            if (upUseOnServeFile == true) {
                db.getUsageDb().addListen(userName, track.getPk(), tit, mediaPk);
            }
        }
        serveFile(bout.toByteArray(), title.getNameOnFs() + ".mp3", "audio/mpeg");
    } catch (IOException ex) {
        wikiContext.addSimpleValidationError("Cannot find track: " + ex.getMessage());
        return super.onInit();
    }
    // db.getUsageDb().addListen(userName, trackPk, tit, mediaPk);
    return noForward();
}

From source file:ddf.catalog.transformer.resource.ResourceMetacardTransformerTest.java

private void testGetResource(Metacard metacard, String filePath, MimeType mimeType, CatalogFramework framework,
        boolean expectSuccess) throws Exception {

    ResourceMetacardTransformer resourceTransformer = new ResourceMetacardTransformer(framework);

    BinaryContent binaryContent = resourceTransformer.transform(metacard, new HashMap<String, Serializable>());

    byte[] fileContents = FileUtils.readFileToByteArray(new File(filePath));

    byte[] contentsFromResults = IOUtils.toByteArray(binaryContent.getInputStream());
    if (expectSuccess) {
        assertEquals(binaryContent.getMimeTypeValue(), mimeType.toString());
        assertTrue(Arrays.equals(fileContents, contentsFromResults));
    }//from   w  w  w .j  a  va  2 s .  co  m
}

From source file:ddf.catalog.transformer.resource.TestResourceMetacardTransformer.java

private void testGetResource(Metacard metacard, String filePath, MimeType mimeType, CatalogFramework framework,
        boolean expectSuccess) throws Exception {

    ResourceMetacardTransformer resourceTransformer = new ResourceMetacardTransformer(framework);

    BinaryContent binaryContent = resourceTransformer.transform(metacard, new HashMap<String, Serializable>());

    byte[] fileContents = FileUtils.readFileToByteArray(new File(filePath));

    byte[] contentsFromResults = IOUtils.toByteArray(binaryContent.getInputStream());
    if (expectSuccess) {
        assertEquals(binaryContent.getMimeTypeValue(), mimeType.toString());
        assertTrue(Arrays.equals(fileContents, contentsFromResults));
    }/* www .j a  v a2  s  . c  om*/

}