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.avego.oauth.migration.OauthDataMigratorTest.java

private void initTestTokenData(InMemTestOauthMigrationDao dao) throws IOException {
    Map<String, OauthAccessTokenRecord> accessTokens = new HashMap<String, OauthAccessTokenRecord>();
    OauthAccessTokenRecord tokenRecord = new OauthAccessTokenRecord();
    tokenRecord.setTokenId("test-token");
    tokenRecord.setAuthentication(FileUtils.readFileToByteArray(getTestFile("auth2.dat")));
    tokenRecord.setAuthenticationId("test");
    tokenRecord.setClientId("test");
    tokenRecord.setRefreshToken("test");
    tokenRecord.setToken(FileUtils.readFileToByteArray(getTestFile("token1.dat")));
    tokenRecord.setUserName("test");
    accessTokens.put(tokenRecord.getTokenId(), tokenRecord);
    dao.setAccessTokens(accessTokens);//  ww w . j  av a 2  s . co  m

    Map<String, OauthRefreshTokenRecord> refreshTokens = new HashMap<String, OauthRefreshTokenRecord>();
    OauthRefreshTokenRecord refreshTokenRecord = new OauthRefreshTokenRecord();
    refreshTokenRecord.setAuthentication(FileUtils.readFileToByteArray(getTestFile("auth2.dat")));
    refreshTokenRecord.setToken(FileUtils.readFileToByteArray(getTestFile("refreshtoken1.dat")));
    refreshTokenRecord.setTokenId("test-refresh-token");
    refreshTokens.put(refreshTokenRecord.getTokenId(), refreshTokenRecord);
    dao.setRefreshTokens(refreshTokens);
}

From source file:com.chiorichan.factory.event.PostImageProcessor.java

@EventHandler()
public void onEvent(PostEvalEvent event) {
    try {//from ww  w .j av  a  2 s. c  om
        if (event.context().contentType() == null
                || !event.context().contentType().toLowerCase().startsWith("image"))
            return;

        float x = -1;
        float y = -1;

        boolean cacheEnabled = AppConfig.get().getBoolean("advanced.processors.imageProcessorCache", true);
        boolean grayscale = false;

        ScriptingContext context = event.context();
        HttpRequestWrapper request = context.request();
        Map<String, String> rewrite = request.getRewriteMap();

        if (rewrite != null) {
            if (rewrite.get("serverSideOptions") != null) {
                String[] params = rewrite.get("serverSideOptions").trim().split("_");

                for (String p : params)
                    if (p.toLowerCase().startsWith("width") && x < 0)
                        x = Integer.parseInt(p.substring(5));
                    else if ((p.toLowerCase().startsWith("x") || p.toLowerCase().startsWith("w"))
                            && p.length() > 1 && x < 0)
                        x = Integer.parseInt(p.substring(1));
                    else if (p.toLowerCase().startsWith("height") && y < 0)
                        y = Integer.parseInt(p.substring(6));
                    else if ((p.toLowerCase().startsWith("y") || p.toLowerCase().startsWith("h"))
                            && p.length() > 1 && y < 0)
                        y = Integer.parseInt(p.substring(1));
                    else if (p.toLowerCase().equals("thumb")) {
                        x = 150;
                        y = 0;
                        break;
                    } else if (p.toLowerCase().equals("bw") || p.toLowerCase().equals("grayscale"))
                        grayscale = true;
            }

            if (request.getArgument("width") != null && request.getArgument("width").length() > 0)
                x = request.getArgumentInt("width");

            if (request.getArgument("height") != null && request.getArgument("height").length() > 0)
                y = request.getArgumentInt("height");

            if (request.getArgument("w") != null && request.getArgument("w").length() > 0)
                x = request.getArgumentInt("w");

            if (request.getArgument("h") != null && request.getArgument("h").length() > 0)
                y = request.getArgumentInt("h");

            if (request.getArgument("thumb") != null) {
                x = 150;
                y = 0;
            }

            if (request.hasArgument("bw") || request.hasArgument("grayscale"))
                grayscale = true;
        }

        // Tests if our Post Processor can process the current image.
        List<String> readerFormats = Arrays.asList(ImageIO.getReaderFormatNames());
        List<String> writerFormats = Arrays.asList(ImageIO.getWriterFormatNames());
        if (context.contentType() != null
                && !readerFormats.contains(context.contentType().split("/")[1].toLowerCase()))
            return;

        int inx = event.context().buffer().readerIndex();
        BufferedImage img = ImageIO.read(new ByteBufInputStream(event.context().buffer()));
        event.context().buffer().readerIndex(inx);

        if (img == null)
            return;

        float w = img.getWidth();
        float h = img.getHeight();
        float w1 = w;
        float h1 = h;

        if (x < 1 && y < 1) {
            x = w;
            y = h;
        } else if (x > 0 && y < 1) {
            w1 = x;
            h1 = x * (h / w);
        } else if (y > 0 && x < 1) {
            w1 = y * (w / h);
            h1 = y;
        } else if (x > 0 && y > 0) {
            w1 = x;
            h1 = y;
        }

        boolean resize = w1 > 0 && h1 > 0 && w1 != w && h1 != h;
        boolean argb = request.hasArgument("argb") && request.getArgument("argb").length() == 8;

        if (!resize && !argb && !grayscale)
            return;

        // Produce a unique encapsulated id based on this image processing request
        String encapId = SecureFunc.md5(context.filename() + w1 + h1 + request.getArgument("argb") + grayscale);
        File tmp = context.site() == null ? AppConfig.get().getDirectoryCache()
                : context.site().directoryTemp();
        File file = new File(tmp, encapId + "_" + new File(context.filename()).getName());

        if (cacheEnabled && file.exists()) {
            event.context().resetAndWrite(FileUtils.readFileToByteArray(file));
            return;
        }

        Image image = resize ? img.getScaledInstance(Math.round(w1), Math.round(h1),
                AppConfig.get().getBoolean("advanced.processors.useFastGraphics", true) ? Image.SCALE_FAST
                        : Image.SCALE_SMOOTH)
                : img;

        // TODO Report malformed parameters to user

        if (argb) {
            FilteredImageSource filteredSrc = new FilteredImageSource(image.getSource(),
                    new RGBColorFilter((int) Long.parseLong(request.getArgument("argb"), 16)));
            image = Toolkit.getDefaultToolkit().createImage(filteredSrc);
        }

        BufferedImage rtn = new BufferedImage(Math.round(w1), Math.round(h1), img.getType());
        Graphics2D graphics = rtn.createGraphics();
        graphics.drawImage(image, 0, 0, null);
        graphics.dispose();

        if (grayscale) {
            ColorConvertOp op = new ColorConvertOp(ColorSpace.getInstance(ColorSpace.CS_GRAY), null);
            op.filter(rtn, rtn);
        }

        if (resize)
            Log.get().info(EnumColor.GRAY + "Resized image from " + Math.round(w) + "px by " + Math.round(h)
                    + "px to " + Math.round(w1) + "px by " + Math.round(h1) + "px");

        if (rtn != null) {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();

            if (context.contentType() != null
                    && writerFormats.contains(context.contentType().split("/")[1].toLowerCase()))
                ImageIO.write(rtn, context.contentType().split("/")[1].toLowerCase(), bs);
            else
                ImageIO.write(rtn, "png", bs);

            if (cacheEnabled && !file.exists())
                FileUtils.writeByteArrayToFile(file, bs.toByteArray());

            event.context().resetAndWrite(bs.toByteArray());
        }
    } catch (Throwable e) {
        e.printStackTrace();
    }

    return;
}

From source file:com.falkonry.TestAddFactsStream.java

/**
 * Should create datastream and add fact data in JSON format
 * @throws Exception/*from   w  w  w  .  j a v a  2  s . c o m*/
 */
@Test
public void createDatastreamWithJsonFactsAndRetriveFacts() throws Exception {

    Datastream ds = new Datastream();
    ds.setName("Test-DS-" + Math.random());
    TimeObject time = new TimeObject();
    time.setIdentifier("time");
    time.setFormat("iso_8601");
    time.setZone("GMT");
    Signal signal = new Signal();
    signal.setTagIdentifier("tag");
    signal.setValueIdentifier("value");
    signal.setDelimiter("_");
    signal.setIsSignalPrefix(false);

    Field field = new Field();
    field.setSiganl(signal);
    field.setTime(time);
    ds.setField(field);
    Datasource dataSource = new Datasource();
    dataSource.setType("STANDALONE");
    ds.setDatasource(dataSource);

    Datastream datastream = falkonry.createDatastream(ds);
    datastreams.add(datastream);

    List<Assessment> assessments = new ArrayList<Assessment>();
    AssessmentRequest assessmentRequest = new AssessmentRequest();
    assessmentRequest.setName("Health");
    assessmentRequest.setDatastream(datastream.getId());
    assessmentRequest.setAssessmentRate("PT1S");
    Assessment assessment = falkonry.createAssessment(assessmentRequest);
    assessments.add(assessment);
    Assert.assertEquals(assessment.getName(), assessmentRequest.getName());

    Map<String, String> options = new HashMap<String, String>();

    String data = "{\"time\" : \"2016-03-01 01:01:01\", \"tag\" : \"signal1_entity1\", \"value\" : 3.4}";
    falkonry.addInput(datastream.getId(), data, options);

    File file = new File("res/factsData.json");
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));

    InputStatus response = falkonry.addFactsStream(assessment.getId(), byteArrayInputStream, null);
    Assert.assertEquals(response.getAction(), "ADD_FACT_DATA");
    Assert.assertEquals(response.getStatus(), "PENDING");

    String asmtId = "743cveg32hkwl2";
    Assessment asmtResponse = falkonry.getAssessment(asmtId);

    // Get Facts
    HttpResponseFormat factsResponse = falkonry.getFactsData(assessment.getId(), options);
    Assert.assertEquals(factsResponse.getResponse().length() > 0, true);

}

From source file:app.common.upload.shapeways.oauth.ModelUploadOauthRunner.java

private String encodeModel(File modelFile) throws IOException {
    byte[] fileBytes = FileUtils.readFileToByteArray(modelFile);
    return Base64.encodeBase64String(fileBytes);
}

From source file:iqq.app.module.QQAccountModule.java

private void handleRecentAccountFind() {
    IMResourceService resources = getContext().getSerivce(IMService.Type.RESOURCE);
    File userDir = resources.getFile("user");
    if (!userDir.exists()) {
        userDir.mkdirs();//from ww  w .  j  ava2 s .c  o  m
    }
    entryMap = new HashMap<String, QQAccountEntry>();
    List<QQAccount> result = new ArrayList<QQAccount>();
    for (File dir : userDir.listFiles()) {
        if (dir.isDirectory()) {
            File datFile = new File(dir, FILE);
            if (datFile.exists()) {
                try {
                    AESKeyPair key = genAesKeyPair(dir.getName());
                    byte[] data = FileUtils.readFileToByteArray(datFile);
                    byte[] plain = UIUtils.Crypt.AESDecrypt(data, key.key, key.iv);
                    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(plain));
                    QQAccountEntry entry = (QQAccountEntry) in.readObject();
                    QQAccount account = new QQAccount();
                    account.setNickname(entry.nickname);
                    account.setUsername(entry.username);
                    account.setPassword(entry.password);
                    account.setStatus(entry.status);
                    if (entry.face != null) {
                        try {
                            BufferedImage face = ImageIO.read(new ByteArrayInputStream(entry.face));
                            account.setFace(face);
                        } catch (IOException e) {
                            LOG.warn("read account face error!", e);
                        }
                    }
                    result.add(account);
                    entryMap.put(account.getUsername(), entry);
                } catch (ClassNotFoundException e) {
                    LOG.warn("read account data error!", e);
                } catch (IOException e) {
                    LOG.warn("read account data error!", e);
                }
            }
        }
    }
    broadcastIMEvent(IMEventType.RECENT_ACCOUNT_UPDATE, result);
}

From source file:de.undercouch.gradle.tasks.download.DownloadTaskPluginTest.java

/**
 * Tests if a single file can be downloaded to a directory
 * @throws Exception if anything goes wrong
 *///ww  w.j  av a2s  .  com
@Test
public void downloadSingleFileToDir() throws Exception {
    Download t = makeProjectAndTask();
    t.src(makeSrc(TEST_FILE_NAME));
    File dst = folder.newFolder();
    t.dest(dst);
    t.execute();

    byte[] dstContents = FileUtils.readFileToByteArray(new File(dst, TEST_FILE_NAME));
    assertArrayEquals(contents, dstContents);
}

From source file:io.kodokojo.config.module.SecurityModule.java

private SecretKey provideAesKey(File keyFile) {
    try {/*from w ww.  jav  a 2 s  . co m*/
        byte[] keyByteArray = FileUtils.readFileToByteArray(keyFile);
        return new SecretKeySpec(keyByteArray, "AES");
    } catch (IOException e) {
        throw new RuntimeException(
                "Unable to read key file from following path: '" + keyFile.getAbsolutePath() + "'.", e);
    }
}

From source file:com.validation.manager.core.tool.Tool.java

public static File createZipFile(List<File> files, String zipName) throws FileNotFoundException, IOException {
    if (!zipName.endsWith(".zip")) {
        zipName += ".zip";
    }/*from ww w  .  j  av  a 2 s  .  co  m*/
    File f = new File(zipName);
    if (f.getParentFile() != null) {
        f.getParentFile().mkdirs();
    }
    try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f))) {
        files.forEach(file -> {
            try {
                ZipEntry ze = new ZipEntry(file.getName());
                out.putNextEntry(ze);
                byte[] data = FileUtils.readFileToByteArray(file);
                out.write(data, 0, data.length);
                out.closeEntry();
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        });
    }
    return f;
}

From source file:edu.unc.lib.dl.update.AtomDCToMODSFilterTest.java

@Test
public void replaceMODSWithDCTerms() throws Exception {
    InputStream entryPart = new FileInputStream(new File("src/test/resources/atompub/metadataDC.xml"));
    Abdera abdera = new Abdera();
    Parser parser = abdera.getParser();
    Document<Entry> entryDoc = parser.parse(entryPart);
    Entry entry = entryDoc.getRoot();//from  w w  w. j  a  va2  s.  c om

    AccessClient accessClient = mock(AccessClient.class);

    MIMETypedStream modsStream = new MIMETypedStream();
    File raf = new File("src/test/resources/testmods.xml");
    byte[] bytes = FileUtils.readFileToByteArray(raf);
    modsStream.setStream(bytes);
    modsStream.setMIMEType("text/xml");
    when(accessClient.getDatastreamDissemination(any(PID.class),
            eq(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()), anyString())).thenReturn(modsStream);

    PID pid = new PID("uuid:test");

    AtomPubMetadataUIP uip = new AtomPubMetadataUIP(pid, "testuser", UpdateOperation.REPLACE, entry);
    uip.storeOriginalDatastreams(accessClient);

    filter.doFilter(uip);

    Element dcTitleElement = uip.getIncomingData().get(AtomPubMetadataParserUtil.ATOM_DC_DATASTREAM);
    String dcTitle = dcTitleElement.getChildText("title", JDOMNamespaceUtil.DCTERMS_NS);

    Element oldMODSElement = uip.getOriginalData().get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName());
    String oldMODSTitle = oldMODSElement.getChild("titleInfo", JDOMNamespaceUtil.MODS_V3_NS)
            .getChildText("title", JDOMNamespaceUtil.MODS_V3_NS);

    Element modsElement = uip.getModifiedData().get(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName());
    String newMODSTitle = modsElement.getChild("titleInfo", JDOMNamespaceUtil.MODS_V3_NS).getChildText("title",
            JDOMNamespaceUtil.MODS_V3_NS);

    assertEquals("Title", dcTitle);
    assertEquals("Hiring and recruitment practices in academic libraries", oldMODSTitle);
    assertEquals(dcTitle, newMODSTitle);

    assertEquals(1, uip.getOriginalData().size());
    assertEquals(1, uip.getModifiedData().size());
    assertEquals(2, uip.getIncomingData().size());
}

From source file:com.amazon.aws.samplecode.travellog.util.DataLoader.java

/**
 * This method will go into a specified directory and load all the data
 * into the journal.  The file structure is made up of a series of
 * property files to provide a simple name/value pair matching that can
 * then be loaded through our SimpleJPA objects.
 *
 * The journal object is in a file "journal" and then entries are in sequential
 * order like this://  w ww. j  a  va  2s  .  c  o m
 *
 * <ul>
 * <li>entry.1</li>
 * <li>entry.2</li>
 * <li>entry.3</li>
 * <ul>
 *
 * Photo metadata is stored with a prefix like this:
 * <ul>
 * <li>photo.[entry #].[sequence].txt</li>
 * </ul>
 *
 * So for example, photos associated with entry #2 would be as follows:
 * <ul>
 * <li>photo.1.1</li>
 * <li>photo.1.2</li>
 * </ul>
 *
 * Photos will be loaded in the order of the sequence id.  The txt file contains
 * a property "file" that points to the actual image that should be loaded.
 *
 * Comments use the same nomenclature as photos.
 *
 * @param directory the directory where the imported data has been extracted to
 * @throws IOException
 * @throws ParseException
 */
private void loadData(File directory) throws IOException, ParseException {

    //Load journal
    File journalFile = new File(directory, "journal");
    Properties journalProps = new Properties();
    journalProps.load(new FileInputStream(journalFile));
    journal = buildJournalFromProps(journalProps);
    dao.saveJournal(journal);

    //Load entries
    File[] entries = directory.listFiles(new EntryFilter());
    for (File entryFile : entries) {
        Properties entryProps = new Properties();
        entryProps.load(new FileInputStream(entryFile));
        Entry entry = buildEntryFromProps(entryProps);
        dao.saveEntry(entry);

        //Parse out entry id
        String[] entryNameSplit = entryFile.getName().split("\\.");
        int entryId = Integer.parseInt(entryNameSplit[1]);
        entryMap.put(entryId, entry);
    }

    //Load photos
    File[] photos = directory.listFiles(new PhotoFilter());

    for (File photoFile : photos) {
        Properties photoProps = new Properties();
        photoProps.load(new FileInputStream(photoFile));
        Photo photo = buildPhotoFromProps(photoProps);

        //Parse out entry id
        String[] photoNameSplit = photoFile.getName().split("\\.");
        int entryId = Integer.parseInt(photoNameSplit[1]);
        Entry entry = entryMap.get(entryId);

        photo.setEntry(entry);
        dao.savePhoto(photo);

        //Load jpeg file
        String fileName = photoProps.getProperty("file");
        File file = new File(directory, fileName);
        byte[] photoData = FileUtils.readFileToByteArray(file);
        photo = S3PhotoUtil.storePhoto(photo, photoData);
        dao.savePhoto(photo);

    }

    //Load comments
    File[] comments = directory.listFiles(new CommentFilter());

    for (File commentFile : comments) {
        Properties commentProps = new Properties();
        commentProps.load(new FileInputStream(commentFile));
        Comment comment = buildCommentFromProps(commentProps);

        //Parse out entry id
        String[] commentNameSplit = commentFile.getName().split("\\.");
        int entryId = Integer.parseInt(commentNameSplit[1]);
        Entry entry = entryMap.get(entryId);

        comment.setEntry(entry);
        dao.saveCommenter(comment.getCommenter());
        dao.saveComment(comment);
    }
}