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 static void main(String[] args) throws Exception {
    Score score1 = new Score();
    Read.midi(score1, "c:/tmp/gen.midi");
    for (Part part : score1.getPartArray()) {
        System.out.println(part.getInstrument());
    }/*  ww  w .ja va2s . c om*/
    new StartupListener().contextInitialized(null);
    Generator generator = new Generator();
    generator.configLocation = "c:/config/music";
    generator.maxConcurrentGenerations = 5;
    generator.init();

    UserPreferences prefs = new UserPreferences();
    prefs.setElectronic(Ternary.YES);
    //prefs.setSimpleMotif(Ternary.YES);
    //prefs.setMood(Mood.MAJOR);
    //prefs.setDrums(Ternary.YES);
    //prefs.setClassical(true);
    prefs.setAccompaniment(Ternary.YES);
    prefs.setElectronic(Ternary.YES);
    final ScoreContext ctx = generator.generatePiece();
    Score score = ctx.getScore();
    for (Part part : score.getPartArray()) {
        System.out.println(part.getTitle() + ": " + part.getInstrument());
    }

    System.out.println("Metre: " + ctx.getMetre()[0] + "/" + ctx.getMetre()[1]);
    System.out.println(ctx);
    Write.midi(score, "c:/tmp/gen.midi");

    new Thread(new Runnable() {

        @Override
        public void run() {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setBounds(0, 0, 500, 500);
            frame.setVisible(true);
            Part part = ctx.getParts().get(PartType.MAIN);
            Note[] notes = part.getPhrase(0).getNoteArray();
            List<Integer> pitches = new ArrayList<Integer>();
            for (Note note : notes) {
                if (!note.isRest()) {
                    pitches.add(note.getPitch());
                }
            }
            GraphicsPanel gp = new GraphicsPanel(pitches);
            frame.setContentPane(gp);
        }
    }).start();

    DecimalFormat df = new DecimalFormat("#.##");

    for (Part part : score.getPartArray()) {
        StringBuilder sb = new StringBuilder();
        printStatistics(ctx, part);
        System.out.println("------------ " + part.getTitle() + "-----------------");
        Phrase[] phrases = part.getPhraseArray();
        for (Phrase phr : phrases) {
            if (phr instanceof ExtendedPhrase) {
                sb.append("Contour=" + ((ExtendedPhrase) phr).getContour() + " ");
            }
            double measureSize = 0;
            int measures = 0;
            double totalLength = 0;
            List<String> pitches = new ArrayList<String>();
            List<String> lengths = new ArrayList<String>();
            System.out.println("((Phrase notes: " + phr.getNoteArray().length + ")");
            for (Note note : phr.getNoteArray()) {
                if (!note.isRest()) {
                    int degree = 0;
                    if (phr instanceof ExtendedPhrase) {
                        degree = Arrays.binarySearch(((ExtendedPhrase) phr).getScale().getDefinition(),
                                note.getPitch() % 12);
                    }
                    pitches.add(String.valueOf(note.getPitch() + " (" + degree + ") "));
                } else {
                    pitches.add(" R ");
                }
                lengths.add(df.format(note.getRhythmValue()));
                measureSize += note.getRhythmValue();
                totalLength += note.getRhythmValue();
                ;
                if (measureSize >= ctx.getNormalizedMeasureSize()) {
                    pitches.add(" || ");
                    lengths.add(" || " + (measureSize > ctx.getNormalizedMeasureSize() ? "!" : ""));
                    measureSize = 0;
                    measures++;
                }
            }
            sb.append(pitches.toString() + "\r\n");
            sb.append(lengths.toString() + "\r\n");
            if (part.getTitle().equals(PartType.MAIN.getTitle())) {
                sb.append("\r\n");
            }
            System.out.println("Phrase measures: " + measures);
            System.out.println("Phrase length: " + totalLength);
        }
        System.out.println(sb.toString());
    }

    MutingPrintStream.ignore.set(true);
    Write.midi(score, "c:/tmp/gen.midi");
    MutingPrintStream.ignore.set(null);
    Play.midi(score);

    generator.toMp3(FileUtils.readFileToByteArray(new File("c:/tmp/gen.midi")));
}

From source file:eu.freme.broker.integration_tests.EInternationalizationTest.java

@Test
public void testOdt() throws IOException, UnirestException {

    File file = new File("src/test/resources/e-internationalization/odt-test.odt");
    byte[] data = FileUtils.readFileToByteArray(file);

    HttpResponse<String> response = Unirest.post(super.getBaseUrl() + "/e-entity/freme-ner/documents")
            .queryString("language", "en").queryString("dataset", "dbpedia")
            .queryString("informat", "application/x-openoffice").body(data).asString();

    assertEquals(response.getStatus(), 200);
    assertTrue(response.getBody().length() > 0);
}

From source file:in.cs654.chariot.ashva.AshvaProcessor.java

/**
 * This function takes in request, executes the request and returns the response.
 * The request is written into /tmp/<request_id>.req file. While running the docker container, /tmp dir is mounted
 * to /tmp of the container. This enables ease of data exchange. TODO encryption
 * Docker runs the request and puts the result into /tmp/<request_id>.res.
 * If the request specifies a timeout, it is picked up, else default timeout is set for the process to run
 * @param request containing function_name and other required information
 * @return response of the request/*from ww w.j  ava  2 s.c om*/
 */
private static BasicResponse handleTaskProcessingRequest(BasicRequest request) {
    final String requestID = request.getRequestId();
    try {
        final byte[] serializedBytes = AvroUtils.requestToBytes(request);
        final FileOutputStream fos = new FileOutputStream("/tmp/" + requestID + ".req");
        fos.write(serializedBytes);
        fos.close();
        String timeoutString = request.getExtraData().get("chariot_timeout");
        Long timeout;
        if (timeoutString != null) {
            timeout = Long.parseLong(timeoutString);
        } else {
            timeout = PROCESS_DEFAULT_TIMEOUT;
        }

        final String dockerImage = Mongo.getDockerImage(request.getDeviceId());
        final String cmd = "docker run -v /tmp:/tmp " + dockerImage + " /bin/chariot " + requestID;
        final Process process = Runtime.getRuntime().exec(cmd);
        TimeoutProcess timeoutProcess = new TimeoutProcess(process);
        timeoutProcess.start();
        try {
            timeoutProcess.join(timeout); // milliseconds
            if (timeoutProcess.exit != null) {
                File file = new File("/tmp/" + requestID + ".res");
                byte[] bytes = FileUtils.readFileToByteArray(file);
                LOGGER.info("Response generated for request " + requestID);
                return AvroUtils.bytesToResponse(bytes);
            } else {
                LOGGER.severe("Timeout in generating response for request " + requestID);
                return ResponseFactory.getTimeoutErrorResponse(request);
            }
        } catch (InterruptedException ignore) {
            timeoutProcess.interrupt();
            Thread.currentThread().interrupt();
            LOGGER.severe("Error in generating response for request " + requestID);
            return ResponseFactory.getErrorResponse(request);
        } finally {
            process.destroy();
        }
    } catch (IOException ignore) {
        LOGGER.severe("Error in generating response for request: " + requestID);
        return ResponseFactory.getErrorResponse(request);
    }
}

From source file:it.av.youeat.service.RistoranteServiceTest.java

@Test
public void testRistoranteService() throws YoueatException, IOException {

    Ristorante a = new Ristorante();
    a.setName("RistoAlessandro");
    a.setCity(getNocity());//  w w w  .j  a  v  a2  s . co  m
    a.setCountry(getNocountry());
    a.setDescriptions(getDescriptionI18ns());
    a = ristoranteService.insert(a, user);

    assertNotNull(a.getRevisions());
    assertEquals(a.getRevisions().size(), 1);

    Collection<Ristorante> all = ristoranteService.getAll();
    assertNotNull(all);
    assertTrue(all.size() > 0);

    // a = ristoranteService.getByPath(a.getPath());
    a = ristoranteService.getByID(a.getId());
    assertNotNull("A is null", a);
    assertEquals("Invalid value for test", "RistoAlessandro", a.getName());
    assertNotNull(a.getDescriptions());
    assertNotNull(a.getDescriptions().get(0));
    assertTrue(a.getDescriptions().get(0).getDescription().equals("description"));

    a = ristoranteService.addRate(a, user, 1);

    // assertTrue(ristoranteService.hasUsersAlreadyRated(a, user));

    assertTrue(a.getRates().size() > 0);
    assertTrue(a.getRates().get(0).getRate() == 1);

    try {
        a = ristoranteService.addRate(a, user, 1);
        fail("Exception doesn't throw on multi rated operation");
    } catch (Exception e) {
        // expected
    }
    a = ristoranteService.getByID(a.getId());
    assertTrue("Rates losts after update ", a.getRates().get(0).getRate() == 1);

    a = ristoranteService.update(a, user);

    all = ristoranteService.getAll();
    assertNotNull(all);
    assertTrue(all.size() > 0);

    all = ristoranteService.getAllSimple();
    assertNotNull(all);
    assertTrue(all.size() > 0);

    a.setName("newName");
    a = ristoranteService.update(a, user);

    a = ristoranteService.getByID(a.getId());
    assertNotNull("A is null", a);
    assertEquals("Invalid value for test", "newName", a.getName());

    // add a picture
    RistorantePicture img = new RistorantePicture();
    img.setPicture(
            FileUtils.readFileToByteArray(new File(this.getClass().getResource("images/test.png").getFile())));
    a.addPicture(img);
    a = ristoranteService.update(a, user);

    a = ristoranteService.getByID(a.getId());
    assertNotNull("A is null", a.getPictures());
    assertEquals("Invalid value for test", 1, a.getPictures().size());

    List<City> cities = ristoranteService.getCityWithRisto();
    assertTrue(cities.size() > 0);

    List<Country> countries = ristoranteService.getCountryWithRisto();
    assertTrue(countries.size() > 0);

    a.setLatitude(1);
    a.setLongitude(2);

    ristoranteService.updateLatitudeLongitude(a);

    Location loc = ristorantePositionService.getByRistorante(a).getWhere();

    assertTrue(1 == loc.getLatitude().value);
    assertTrue(2 == loc.getLongitude().value);

    ristoranteService.remove(a);
}

From source file:com.xpn.xwiki.plugin.svg.SVGPlugin.java

public byte[] readSVGImage(File ofile) throws IOException {
    return FileUtils.readFileToByteArray(ofile);
}

From source file:edu.umn.msi.tropix.grid.io.transfer.impl.TransferContextFactoryImplTest.java

public void upload(final UploadType type) throws Exception {
    final TransferServiceContextReference ref = new TransferServiceContextReference();
    final GlobusCredential proxy = EasyMock.createMock(GlobusCredential.class);
    final Credential credential = Credentials.get(proxy);
    final OutputContext uc = factory.getUploadContext(ref, credential);
    final File file = File.createTempFile("tpx", "");
    file.deleteOnExit();//  ww  w  .  j  a v  a2 s.  c o m
    FileUtils.writeStringToFile(file, "Moo!");
    final ByteArrayOutputStream bStream = new ByteArrayOutputStream();
    utils.put(EasyMockUtils.copy(bStream), EasyMock.same(ref), EasyMock.same(proxy));
    if (type.equals(UploadType.EXCEPTION)) {
        EasyMock.expectLastCall().andThrow(new Exception());
    }
    EasyMock.replay(utils);
    if (type.equals(UploadType.FILE) || type.equals(UploadType.EXCEPTION)) {
        uc.put(file);
    } else if (type.equals(UploadType.STREAM)) {
        uc.put(new FileInputStream(file));
    } else if (type.equals(UploadType.BYTES)) {
        uc.put(FileUtils.readFileToByteArray(file));
    }
    EasyMock.verify(utils);
    assert "Moo!".equals(new String(bStream.toByteArray()));
}

From source file:hudson.plugins.testlink.result.ResultSeeker.java

/**
 * Retrieves the file content encoded in Base64.
 * //from  ww  w. j a  v a2  s.  c  o  m
 * @param file
 *            file to read the content.
 * @return file content encoded in Base64.
 * @throws IOException
 */
protected String getBase64FileContent(File file) throws IOException {
    byte[] fileData = FileUtils.readFileToByteArray(file);
    return Base64.encodeBase64String(fileData);
}

From source file:de.mpg.imeji.logic.storage.transform.ImageGeneratorManager.java

/**
 * Uses the {@link ImageGenerator} to transform the bytes into a jpg
 * //from   w ww.  j a  v  a 2  s.  c o m
 * @param bytes
 * @param extension
 * @return
 */
private byte[] toJpeg(File file, String extension) {
    byte[] jpeg = null;
    Iterator<ImageGenerator> it = generators.iterator();
    if (StorageUtils.compareExtension(extension, "jpg"))
        try {
            return FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    while (it.hasNext() && (jpeg == null || jpeg.length == 0)) {
        try {
            ImageGenerator imageGenerator = it.next();
            jpeg = imageGenerator.generateJPG(file, extension);
        } catch (Exception e) {
            logger.warn("Error generating image", e);
        }
    }
    if (jpeg == null || jpeg.length == 0)
        throw new RuntimeException("Unsupported file format (requested was " + extension + ")");
    return jpeg;
}

From source file:com.github.dactiv.fear.service.service.account.AccountService.java

/**
 * ??// w  w w .  j  av  a 2  s  .  com
 *
 * @param userId  id
 * @param size   ?
 *
 * @return ? byte 
 */
public byte[] getUserPortrait(Integer userId, PortraitSize size) throws IOException {
    String path = principalPortraitPath + userId + File.separator + size.getName();

    File f = new File(path);

    if (!f.exists()) {
        return new byte[0];
    }

    return FileUtils.readFileToByteArray(new File(path));
}

From source file:com.github.seqware.queryengine.impl.TmpFileStorage.java

private Atom handleFileGivenClass(File file, Class cl) throws IOException {
    byte[] objData;
    objData = FileUtils.readFileToByteArray(file);
    assert (cl != null && objData != null);
    Atom suspect = (Atom) serializer.deserialize(objData, cl);
    return suspect;
}