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:beans.FotoBean.java

public void salvarFoto() {
    try {//from   w ww. ja v a  2  s. co  m
        byte[] fotobyte = FileUtils.readFileToByteArray(fotosalva);
        foto.setArquivo(fotobyte);
        foto.setDataHora(Calendar.getInstance().getTime());

        if (new FotoController().salvar(foto)) {
            listarFotos();
            Util.executarJavascript("PF('dlgfoto').hide()");
            Util.criarMensagem("foto salva");
            Util.atualizarComponente("foto");
            fotosalva.delete();
            abriuWebcam = false;
        }
    } catch (Exception e) {
        Util.criarMensagemErro(e.toString());
    }
}

From source file:com.abm.mainet.water.ui.controller.PlumberLicenseFormController.java

@RequestMapping(method = RequestMethod.POST, params = "getCheckListAndCharges")
public ModelAndView doGetApplicableCheckListAndCharges(HttpServletRequest httpServletRequest) {
    this.bindModel(httpServletRequest);
    long orgId = UserSession.getCurrent().getOrganisation().getOrgid();
    ModelAndView modelAndView = null;//w ww .  jav  a2  s . c o m
    PlumberLicenseFormModel model = this.getModel();
    try {
        for (Iterator<Entry<Long, Set<File>>> it = FileUploadUtility.getCurrent().getFileMap().entrySet()
                .iterator(); it.hasNext();) {
            Entry<Long, Set<File>> entry = it.next();
            if (entry.getKey().longValue() == 0) {
                Set<File> set = entry.getValue();
                File file = set.iterator().next();
                String bytestring = "";
                Base64 base64 = new Base64();
                try {
                    bytestring = base64.encodeToString(FileUtils.readFileToByteArray(file));
                } catch (IOException e) {
                    logger.error("Exception has been occurred in file byte to string conversions", e);
                }
                String plumberImage = file.getName();
                model.setPlumberImage(plumberImage);
                model.getPlumberLicenseReqDTO().setPlumberImage(plumberImage);
                model.getPlumberLicenseReqDTO().setImageByteCode(bytestring);
                break;
            }
        }
        if (model.getPlumberImage() == null || model.getPlumberImage().isEmpty()) {
            this.getModel().addValidationError(ApplicationSession.getInstance()
                    .getMessage("water.plumberLicense.valMsg.uploadPlumberPhoto"));
        } else {
            model.findApplicableCheckListAndCharges(this.getModel().getServiceId(), orgId);
        }
        modelAndView = new ModelAndView("PlumberLicenseFormValidn", "command", model);
        if (model.getBindingResult() != null) {
            modelAndView.addObject(BindingResult.MODEL_KEY_PREFIX + MainetConstants.FORM_NAME,
                    getModel().getBindingResult());
        }
    } catch (Exception ex) {
        modelAndView = defaultExceptionFormView();
    }
    return modelAndView;
}

From source file:com.playonlinux.core.utils.archive.TarTest.java

@Test
public void testGunzip() throws IOException {
    final File inputFile = new File(inputUrl.getPath(), "pol.txt.gz");
    final File outputFile = File.createTempFile("output", "txt");

    new Tar().gunzip(inputFile, outputFile);

    assertEquals("PlayOnLinux", new String(FileUtils.readFileToByteArray(outputFile)));
}

From source file:ezbake.deployer.utilities.PackageDeployer.java

/**
 * Builds an deployment artifact/*from   w ww  .ja  v  a 2s.c  om*/
 *
 * @param artifactMetadata      The metadata from the manifest
 * @param packageFile           The file containing the artifact or package to be deployed
 * @param packageFileName       The file name of the package
 * @param manifestFile          The yml file
 * @param configFiles           A Map of configuration files and their corresponding file names
 * @param applicationSecurityId The application's security id, or null to use the value in the manifest
 * @return A serialized tar file of everything to be deployed
 * @throws IOException         If the files cannot be read
 * @throws DeploymentException If the tar file cannot be created
 */
public static ByteBuffer buildArtifact(ArtifactManifest artifactMetadata, File packageFile,
        String packageFileName, File manifestFile, Map<File, String> configFiles, String applicationSecurityId)
        throws IOException, DeploymentException {
    List<ArtifactDataEntry> injectFiles = new ArrayList<>();
    //check if is a web app, if so send war to deployments directory else send to bin directory
    if (artifactMetadata.getArtifactType() == ArtifactType.WebApp) {
        // If a bin name is given, respect it. Otherwise, default to ROOT.war
        String warName = artifactMetadata.getArtifactInfo().isSetBin()
                ? artifactMetadata.getArtifactInfo().getBin()
                : "ROOT.war";

        injectFiles.add(new ArtifactDataEntry(new TarArchiveEntry(String.format("deployments/%s", warName)),
                FileUtils.readFileToByteArray(packageFile)));
    } else {
        injectFiles.add(new ArtifactDataEntry(new TarArchiveEntry(String.format("bin/%s", packageFileName)),
                FileUtils.readFileToByteArray(packageFile)));
    }

    //add the yml file
    injectFiles.add(new ArtifactDataEntry(new TarArchiveEntry(getFqAppId(artifactMetadata) + "-manifest.yml"),
            FileUtils.readFileToByteArray(manifestFile)));

    //if any option config files add them to the config directory
    for (Map.Entry<File, String> file : configFiles.entrySet()) {
        injectFiles.add(new ArtifactDataEntry(
                new TarArchiveEntry(String.format("%s/%s", Utilities.CONFIG_DIRECTORY, file.getValue())),
                FileUtils.readFileToByteArray(file.getKey())));
    }

    if (applicationSecurityId != null) {
        // Assumption: override manifest's application security id with one from registration form
        // given this is passed to constructor and not based on actual application from manifest
        // only one sec id will be set for n number of manifest as only one manifest is currently supported
        // per deployment
        artifactMetadata.applicationInfo.setSecurityId(applicationSecurityId);
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();

    Utilities.appendFilesInTarArchive(output, injectFiles);
    return ByteBuffer.wrap(output.toByteArray());
}

From source file:net.nicholaswilliams.java.licensing.FileLicenseProvider.java

/**
 * Gets the stored, still-encrypted, still-serialized license content and signature from the persistence store.
 * Returns null (not an empty array) if no license is found.
 *
 * @param context The context for which to get the license
 * @return the signed license data.//from   w  w  w  .  j  a  v  a  2  s .  com
 */
@Override
protected byte[] getLicenseData(Object context) {
    if (context == null)
        throw new IllegalArgumentException("Argument context cannot be null.");

    File file = this.getLicenseFile(context);
    if (file == null || !file.exists() || !file.canRead())
        return null;

    try {
        byte[] data = FileUtils.readFileToByteArray(file);

        if (this.isBase64Encoded()) {
            data = Base64.decodeBase64(data);
        }

        return data;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.edduarte.protbox.core.registry.PbxFile.java

/**
 * Sets the data of the file to the specified data.
 *//*w  w w  . j  av  a  2  s.c  om*/
public void createSnapshotFromFile(File snapshotFile, FolderOption fromFolder) throws ProtboxException {
    logger.info("-------------- " + snapshotFile.getName() + " "
            + new Date(snapshotFile.lastModified()).toString());
    try {
        byte[] fileData;

        if (fromFolder.equals(FolderOption.SHARED)) {
            try {
                fileData = parentRegistry.decrypt(FileUtils.readFileToByteArray(snapshotFile), true);
            } catch (ProtboxException ex) {
                logger.info(
                        "There was a problem while decrypting. Ignoring file " + snapshotFile.getName() + ".",
                        ex);
                return;
            }

        } else {
            fileData = FileUtils.readFileToByteArray(snapshotFile);
        }

        long fileSize = snapshotFile.length();
        Date lastModifiedDate = new Date(snapshotFile.lastModified());
        snapshotStack.push(new Snapshot(fileData, fileSize, lastModifiedDate));

    } catch (IOException ex) {
        throw new ProtboxException(ex);
    }
}

From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadFTest.java

/**
 * In general, we should only have one test method per functional test. This allows for the best parallelism when we
 * execute the tests, especially if the setup takes some time.
 *
 * @throws Exception In case anything (anything at all) goes wrong!
 *//*from  w w  w . ja va2s .com*/
@Test
public void run() throws Exception {
    // We only need one repo server.
    TestRepositoryServer server = newRepositoryServer();

    // Generate some test content
    String path = contentGenerator.newArtifactPath("jar");
    byte[] content = contentGenerator.newBinaryContent(1024);

    // Register the generated content by writing it to the path within the repo server's dir structure.
    // This way when the path is requested it can be downloaded instead of returning a 404.
    server.registerContent(path, content);
    server.registerContent(path + Main.SHA_SUFFIX, sha1Hex(content));
    server.registerContent(path + Main.MD5_SUFFIX, md5Hex(content));

    // Write the plaintext file we'll use as input.
    File plaintextList = temporaryFolder.newFile("artifact-list." + getClass().getSimpleName() + ".txt");
    String pathWithChecksum = contentGenerator.newPlaintextEntryWithChecksum(path, content);
    FileUtils.write(plaintextList, pathWithChecksum);

    Options opts = new Options();
    opts.setBaseUrls(Collections.singletonList(server.getBaseUri()));

    // Capture the downloads here so we can verify the content.
    File downloads = temporaryFolder.newFolder();

    opts.setDownloads(downloads);
    opts.setLocations(Collections.singletonList(plaintextList.getAbsolutePath()));

    // run `new Main(opts).run()` and return the Main instance so we can query it for errors, etc.
    Main finishedMain = run(opts);

    assertThat("Wrong number of downloads logged. Should have been 3 including checksums.",
            finishedMain.getDownloaded(), equalTo(3));
    assertThat("Errors should be empty!", finishedMain.getErrors().isEmpty(), equalTo(true));

    File downloaded = new File(downloads, path);
    assertThat("File: " + path + " doesn't seem to have been downloaded!", downloaded.exists(), equalTo(true));
    assertThat("Downloaded file: " + path + " contains the wrong content!",
            FileUtils.readFileToByteArray(downloaded), equalTo(content));
}

From source file:com.netsteadfast.greenstep.action.CommonLoadUploadFileAction.java

private void loadData(File file) throws ServiceException, Exception {
    if (StringUtils.isBlank(this.oid)) {
        return;//from   w w w .  j  a v  a 2  s.  com
    }
    DefaultResult<SysUploadVO> result = this.sysUploadService.findForNoByteContent(this.oid);
    if (result.getValue() == null) {
        throw new ControllerException(result.getSystemMessage().getValue());
    }
    SysUploadVO uploadData = result.getValue();
    if (YesNo.YES.equals(uploadData.getIsFile())) {
        file = UploadSupportUtils.getRealFile(this.oid);
        if (!file.exists()) {
            return;
        }
        this.inputStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
        this.filename = file.getName();
    } else {
        this.inputStream = new ByteArrayInputStream(UploadSupportUtils.getDataBytes(this.oid));
        this.filename = UploadSupportUtils.generateRealFileName(uploadData.getShowName());
    }
    if ("view".equals(this.type)) {
        if (file != null) {
            try {
                this.contentType = FSUtils.getMimeType(file);
            } catch (Exception e) {
                logger.warn(e.getMessage().toString());
            }
        } else {
            this.contentType = FSUtils.getMimeType(uploadData.getShowName());
        }
    }
    if (!StringUtils.isAsciiPrintable(result.getValue().getShowName())) {
        String userAgent = super.defaultString(super.getHttpServletRequest().getHeader("User-Agent"))
                .toLowerCase();
        if (userAgent.indexOf("firefox") == -1) { // for chrome or other browser.
            this.filename = URLEncoder.encode(result.getValue().getShowName(), Constants.BASE_ENCODING);
        }
        return;
    }
    this.filename = result.getValue().getShowName();
}

From source file:com.cws.esolutions.agent.processors.impl.FileManagerProcessorImpl.java

public FileManagerResponse retrieveFile(final FileManagerRequest request) throws FileManagerException {
    final String methodName = IFileManagerProcessor.CNAME
            + "#retrieveFile(final ApplicationManagerRequest request) throws FileManagerException";

    if (DEBUG) {/*from  w ww .j a  v  a  2  s.co m*/
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileManagerRequest: {}", request);
    }

    FileManagerResponse response = new FileManagerResponse();

    try {
        if (!(FileUtils.getFile(request.getRequestFile()).canRead())) {
            throw new FileManagerException("Unable to read the requested file.");
        }

        if (FileUtils.getFile(request.getRequestFile()).isDirectory()) {
            // list
            File[] fileList = FileUtils.getFile(request.getRequestFile()).listFiles();

            if ((fileList != null) && (fileList.length != 0)) {
                List<String> fileData = new ArrayList<String>();

                for (File file : fileList) {
                    if (DEBUG) {
                        DEBUGGER.debug("File: {}", file);
                    }

                    fileData.add(file.getName());
                }

                response.setDirListing(fileData);
                response.setFilePath(request.getRequestFile());
                response.setRequestStatus(AgentStatus.SUCCESS);
            } else {
                response.setRequestStatus(AgentStatus.FAILURE);
            }

            if (DEBUG) {
                DEBUGGER.debug("FileManagerResponse: {}", response);
            }
        } else {
            // file
            File retrievableFile = FileUtils.getFile(request.getRequestFile());

            if (DEBUG) {
                DEBUGGER.debug("File: {}", retrievableFile);
            }

            if ((retrievableFile.exists()) && (retrievableFile.canRead())) {
                byte[] fileBytes = FileUtils.readFileToByteArray(retrievableFile);

                if (DEBUG) {
                    DEBUGGER.debug("File data: {}", fileBytes);
                }

                response.setChecksum(FileUtils.checksumCRC32(retrievableFile));
                response.setFileData(fileBytes);
                response.setFileName(retrievableFile.getName());
                response.setFilePath(retrievableFile.getPath());
                response.setRequestStatus(AgentStatus.SUCCESS);

                if (DEBUG) {
                    DEBUGGER.debug("FileManagerResponse: {}", response);
                }
            } else {
                response.setRequestStatus(AgentStatus.FAILURE);
            }
        }
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileManagerException(iox.getMessage(), iox);
    }

    return response;
}

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

/**
 * Generate an image (only jpg and gif supported here) into a smaller image according to the {@link FileResolution}
 * /*www.jav  a2 s  .  c o  m*/
 * @param bytes
 * @param extension
 * @param resolution
 * @return
 */
public byte[] generate(File file, String extension, FileResolution resolution) {
    if (StorageUtils.compareExtension("gif", extension)) {
        try {
            return generateGif(FileUtils.readFileToByteArray(file), extension, resolution);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return generateJpeg(file, extension, resolution);
}