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:edu.unc.lib.dl.cdr.sword.managers.ContainerManagerTest.java

@Test
public void getEntryCredentials() throws Exception {
    DepositReceipt resultReceipt = mock(DepositReceipt.class);

    DepositReportingUtil depositReportingUtil = mock(DepositReportingUtil.class);
    when(depositReportingUtil.retrieveDepositReceipt(any(PID.class), any(SwordConfigurationImpl.class)))
            .thenReturn(resultReceipt);//from   w ww .j  a v a2 s . c o m

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

    TripleStoreQueryService tripleStoreQueryService = mock(TripleStoreQueryService.class);

    Map<String, String> disseminations = new HashMap<String, String>();
    disseminations.put(pid.getURI() + "/" + ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName(), "text/xml");
    disseminations.put(pid.getURI() + "/" + ContentModelHelper.Datastream.DATA_FILE.getName(), "image/jpg");

    when(tripleStoreQueryService.fetchDisseminatorMimetypes(any(PID.class))).thenReturn(disseminations);

    File modsFile = new File("src/test/resources/modsDocument.xml");
    byte[] modsBytes = FileUtils.readFileToByteArray(modsFile);
    MIMETypedStream mimeStream = new MIMETypedStream();
    mimeStream.setStream(modsBytes);

    GroupsThreadStore.storeGroups(new AccessGroupSet());
    AccessControlService aclService = mock(AccessControlService.class);
    ObjectAccessControlsBean objectACLs = mock(ObjectAccessControlsBean.class);
    when(objectACLs.hasPermission(any(AccessGroupSet.class), any(Permission.class))).thenReturn(true);
    when(aclService.getObjectAccessControls(any(PID.class))).thenReturn(objectACLs);

    AccessClient accessClient = mock(AccessClient.class);
    when(accessClient.getDatastreamDissemination(any(PID.class),
            eq(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()), anyString())).thenReturn(mimeStream);

    ContainerManagerImpl containerManager = new ContainerManagerImpl();
    containerManager.setDepositReportingUtil(depositReportingUtil);
    containerManager.setTripleStoreQueryService(tripleStoreQueryService);
    containerManager.setAccessClient(accessClient);
    containerManager.setAclService(aclService);

    String editIRI = "http://localhost" + SwordConfigurationImpl.EDIT_PATH + "/" + pid.getPid();

    AuthCredentials auth = new AuthCredentials("testuser", "", null);

    // Check to make sure that not finding the user's onyen is not the end of the world
    when(objectACLs.hasPermission(any(AccessGroupSet.class), any(Permission.class))).thenReturn(true);
    try {
        DepositReceipt receipt = containerManager.getEntry(editIRI, null, auth, config);
        assertNotNull(receipt);
    } catch (SwordAuthException e) {
        fail();
    }

    when(objectACLs.hasPermission(any(AccessGroupSet.class), any(Permission.class))).thenReturn(false);
    try {
        containerManager.getEntry(editIRI, null, auth, config);
        fail();
    } catch (SwordError e) {
        //pass
    }
    GroupsThreadStore.clearGroups();
}

From source file:ezbake.azkaban.submitter.AzkabanSubmitter.java

private void run(CmdLineParser parser) throws TException, IOException, CmdLineException {
    if (!(submit)) {
        throw new CmdLineException(parser, "Must provide -u option to client");
    }/*from  w  w w. ja  v  a 2  s.  c  o  m*/

    final EzConfiguration config;
    try {
        config = new EzConfiguration();
    } catch (EzConfigurationLoaderException e) {
        throw new IOException(e);
    }

    config.getProperties().setProperty(EzBakePropertyConstants.EZBAKE_SECURITY_ID, securityId);

    if (submit) {
        if (Strings.isNullOrEmpty(projectId))
            throw new CmdLineException(parser, "Pipeline ID required for submission");
        File zipFile = new File(pathToTarGz);
        byte[] fileBytes = FileUtils.readFileToByteArray(zipFile);
        UploaderResult result = submit(ByteBuffer.wrap(fileBytes), projectId);
        System.out.println("Upload " + (result.hasError() ? "FAILED" : "SUCCESSFUL"));
    }
}

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

/**
 * Test if a single file can be downloaded successfully with quiet mode
 * @throws Exception if anything went wrong
 *//*from   w ww  . j av a2  s.c o  m*/
@Test
public void downloadSingleFileWithQuietMode() throws Exception {
    assertTaskSuccess(download(new Parameters(singleSrc, dest, true, false, true, false, true)));
    assertTrue(destFile.isFile());
    assertArrayEquals(contents, FileUtils.readFileToByteArray(destFile));
}

From source file:eu.planets_project.services.datatypes.Content.java

/**
 * Create content by value (actually embedded in the request).
 * @param value The value file for the content.
 * @return A content instance with the specified value
 *//*from  www . jav a 2  s  .  c o  m*/
public static DigitalObjectContent byValue(final File value) {
    if (!value.exists()) {
        throw new IllegalArgumentException("Given file does not exist: " + value);
    }
    try {
        return new ImmutableContent(FileUtils.readFileToByteArray(value));
    } catch (IOException e) {
        e.printStackTrace();
    }
    throw new IllegalStateException("Could not create content for file: " + value);
}

From source file:com.adguard.compiler.LocaleUtils.java

public static void convertFromChromeToFirefoxLocales(File chromeLocalesDir) throws IOException {

    for (File file : chromeLocalesDir.listFiles()) {

        File chromeLocaleFile = new File(file, "messages.json");
        if (!SupportedLocales.supported(file.getName())) {
            FileUtils.deleteQuietly(file);
            continue;
        }//from  w w  w . j av a2s  .c o  m

        String firefoxLocale = StringUtils.replace(file.getName(), "_", "-");
        File appLocaleFile = new File(chromeLocalesDir, firefoxLocale + ".properties");

        byte[] content = FileUtils.readFileToByteArray(chromeLocaleFile);
        Map map = objectMapper.readValue(content, Map.class);
        StringBuilder sb = new StringBuilder();
        for (Object key : map.keySet()) {
            String message = (String) ((Map) map.get(key)).get("message");
            message = message.replaceAll("\n", "\\\\n");
            sb.append(key).append("=").append(message);
            sb.append(System.lineSeparator());
        }
        FileUtils.writeStringToFile(appLocaleFile, sb.toString(), "utf-8");
        FileUtils.deleteQuietly(file);
    }
}

From source file:com.aliyun.odps.mapred.unittest.UTContext.java

/**
 * ??.//from  w  ww.ja  v  a2 s .com
 * 
 * <p>
 *  {@link Mapper}  {@link Reducer} ???
 * 
 * @param resourceName
 *          ???
 * @param file
 *          ?
 * @throws IOException
 */
public void setFileResource(String resourceName, File file) throws IOException {
    checkResource(resourceName, file);
    setFileResource(resourceName, FileUtils.readFileToByteArray(file));
}

From source file:cn.com.report.HtmlServlet3.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    InputStream is = HtmlServlet3.class.getResourceAsStream("templatedesign1.jrxml");
    resp.setContentType("application/pdf");

    OutputStream out = resp.getOutputStream();
    JasperPdfExporterBuilder pdfExporter = export.pdfExporter(out);
    try {/*  w  w w  . j a va 2  s.c  o m*/
        JasperReportBuilder report = report();
        report.setTemplate(Templates.reportTemplate).setParameters(createParameters()).setTemplateDesign(is)
                .columns(col.column("Item", "item", type.stringType()),
                        col.column("?", "quantity", type.integerType()),
                        col.column("Unit price", "unitprice", type.integerType()))
                //.title(Templates.createTitleComponent("JasperTemplateDesign1"))
                .setDataSource(createDataSource())
        //           .show(false)
        ;
        ;
        File tempFile = File.createTempFile("web", ".pdf");
        report.toPdf(new FileOutputStream(tempFile));
        out.write(FileUtils.readFileToByteArray(tempFile));
        System.out.println("%%%%%%%%%%" + tempFile.getCanonicalPath());
        //         report.toPdf(pdfExporter);//?pdf?  
    } catch (DRException e) {
        e.printStackTrace();
    }
    out.close();
}

From source file:io.appium.java_client.ios.PushesFiles.java

/**
 * Saves base64 encoded data as a media file on the remote mobile device.
 * The server should have ifuse/*from  ww w.ja  v a  2  s  . c  o  m*/
 * libraries installed and configured properly for this feature to work
 * on real devices.
 *
 * @see <a href="https://github.com/libimobiledevice/ifuse">iFuse GitHub page</a>
 * @see <a href="https://github.com/osxfuse/osxfuse/wiki/FAQ">osxFuse FAQ</a>
 *
 * @param remotePath See the documentation on {@link #pushFile(String, byte[])}
 * @param file Is an existing local file to be written to the remote device
 * @throws IOException when there are problems with a file or current file system
 */
default void pushFile(String remotePath, File file) throws IOException {
    checkNotNull(file, "A reference to file should not be NULL");
    if (!file.exists()) {
        throw new IOException(String.format("The given file %s doesn't exist", file.getAbsolutePath()));
    }
    pushFile(remotePath, Base64.encodeBase64(FileUtils.readFileToByteArray(file)));
}

From source file:com.talis.platform.testsupport.StubCallDefn.java

public StubCallDefn andReturn(final int status, final File entity, final String type) throws IOException {
    return andReturn(status, FileUtils.readFileToByteArray(entity), type);
}

From source file:com.validation.manager.core.server.core.AttachmentServer.java

public void addFile(File f, String fileName) {
    try {/* www.  java2  s  .  c o m*/
        if (f != null && f.isFile() && f.exists()) {
            byte[] array = FileUtils.readFileToByteArray(f);
            setFile(array);
            setFileName(fileName);
            String ext = FilenameUtils.getExtension(getFileName());
            if (ext != null) {
                //Set attachment type
                setAttachmentType(AttachmentTypeServer.getTypeForExtension(ext));
            }
            if (getAttachmentType() == null) {
                //Set as undefined
                setAttachmentType(AttachmentTypeServer.getTypeForExtension(""));
            }
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}