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.oriental.manage.controller.merchant.settleManage.MerchantContranctController.java

@RequestMapping("/downEnclosure")
@RequiresPermissions("org-contaract_down")
public ResponseEntity<byte[]> downEnclosure(String id) {

    try {//w  w  w  .  ja  va2 s.c  o  m
        ContractInfo contractInfo = contractService.queryById(id);
        String path = downloadTempDir.concat("/").concat(contractInfo.getCompanyCode()).concat("/");
        FileUtilsExt.writeFile(path);
        String[] pathList = { contractInfo.getDfsBankFile(), contractInfo.getDfsBizLicenseCert(),
                contractInfo.getDfsContAttach(), contractInfo.getDfsOpenBankCert(),
                contractInfo.getDfsOrganizationCodeCert(), contractInfo.getDfsRatePayerCert(),
                contractInfo.getDfsTaxRegisterCert() };
        for (String dfsPath : pathList) {
            if (StringUtils.isNotBlank(dfsPath)) {
                DfsFileInfo dfsFileInfo = new DfsFileInfo();
                dfsFileInfo.setDfsFullFilename(dfsPath);
                List<DfsFileInfo> fileInfoList = iDfsFileInfoService.searchDfsFileInfo(dfsFileInfo);
                if (null != fileInfoList && fileInfoList.size() > 0) {
                    DfsFileInfo dfsFileInfo1 = fileInfoList.get(0);
                    fastDFSPoolUtil.download(dfsFileInfo1.getDfsGroupname(), dfsFileInfo1.getDfsFullFilename(),
                            path.concat(dfsFileInfo1.getLocalFilename()));
                }
            }
        }
        String localFileName = downloadTempDir.concat("/").concat(contractInfo.getCompanyCode())
                .concat("???.zip");
        FileUtilsExt.zipFile(Arrays.asList(new File(path).listFiles()), localFileName);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", new String(
                contractInfo.getCompanyCode().concat("???.zip").getBytes("UTF-8"), "ISO-8859-1"));
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(localFileName)), headers,
                HttpStatus.CREATED);
    } catch (Exception e) {
        log.error("", e);
    }
    return null;
}

From source file:com.floreantpos.ui.model.MenuItemForm.java

protected void doSelectImageFile() {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    int option = fileChooser.showOpenDialog(POSUtil.getBackOfficeWindow());

    if (option == JFileChooser.APPROVE_OPTION) {
        File imageFile = fileChooser.getSelectedFile();
        try {/*from w  w w . j  a  v  a2s.c  om*/
            byte[] itemImage = FileUtils.readFileToByteArray(imageFile);
            int imageSize = itemImage.length / 1024;

            if (imageSize > 20) {
                POSMessageDialog.showMessage(Messages.getString("MenuItemForm.0")); //$NON-NLS-1$
                itemImage = null;
                return;
            }

            ImageIcon imageIcon = new ImageIcon(
                    new ImageIcon(itemImage).getImage().getScaledInstance(80, 80, Image.SCALE_SMOOTH));
            lblImagePreview.setIcon(imageIcon);

            MenuItem menuItem = (MenuItem) getBean();
            menuItem.setImageData(itemImage);

        } catch (IOException e) {
            PosLog.error(getClass(), e);
        }
    }
}

From source file:eu.planets_project.services.migration.kakadu.KakaduDecodeMigration.java

/**
 * {@inheritDoc}/*www.  ja  v a 2s.  c  o  m*/
 * @see eu.planets_project.services.migrate.Migrate#migrate(eu.planets_project.services.datatypes.DigitalObject,
 *      java.net.URI, java.net.URI,
 *      eu.planets_project.services.datatypes.Parameter)
 */
public MigrateResult migrate(final DigitalObject digitalObject, URI inputFormat, URI outputFormat,
        List<Parameter> parameters) {

    // Start timing...
    ServicePerformanceHelper sph = new ServicePerformanceHelper();

    requestParametersList = parameters;
    Properties props = new Properties();
    try {

        String strRsc = "/eu/planets_project/services/migration/kakadu/kakadu.properties";
        props.load(this.getClass().getResourceAsStream(strRsc));
        // config vars
        this.kakadu_install_dir = props.getProperty("kakadu.install.dir");
        this.kakadu_app_name = props.getProperty("kakadu.app2.name");

    } catch (Exception e) {
        // // config vars
        this.kakadu_install_dir = "C:/Programme/Kakadu";
        this.kakadu_app_name = "kdu_expand";
    }
    log.info("Using kakadu install directory: " + this.kakadu_install_dir);
    log.info("Using kakadu application name: " + this.kakadu_app_name);

    init();
    // Initialise parameters with default values
    initParameters();
    getExtensions(inputFormat, outputFormat);

    /*
     * We just return a new digital object with the same required arguments
     * as the given:
     */
    byte[] binary = null;
    InputStream inputStream = digitalObject.getContent().getInputStream();

    // write input stream to temporary file
    tmpInFile = DigitalObjectUtils.toFile(digitalObject); //TODO need extension?

    // Record time take to load the input data:
    sph.loaded();

    if (!(tmpInFile.exists() && tmpInFile.isFile() && tmpInFile.canRead())) {
        log.severe("Unable to create temporary input file!");
        return null;
    }
    log.info("Temporary input file created: " + tmpInFile.getAbsolutePath());

    // outfile name
    String outFileStr = tmpInFile.getAbsolutePath().replaceAll(inputFmtExt, "tif");

    log.info("Output file name: " + outFileStr);

    StringBuffer serviceReportMessage = new StringBuffer();
    // run command
    ProcessRunner runner = new ProcessRunner();
    List<String> command = new ArrayList<String>();
    // setting up command
    // -i source.tif -o destination.jp2 Creversible=yes -rate -,1,0.5,0.25 Clevels=5
    command.add(this.kakadu_app_name);
    command.add("-i");
    command.add(tmpInFile.getAbsolutePath());
    command.add("-o");
    command.add(outFileStr);
    for (Parameter requestParm : requestParametersList) {
        ServiceParameter servParm = kduServiceParameters.getParameter(requestParm.getName());
        if (servParm != null) {
            servParm.setRequestValue(requestParm.getValue());
            if (servParm.isValid())
                command.addAll(servParm.getCommandListItems());
            else
                serviceReportMessage.append(servParm.getStatusMessage());
        } else
            serviceReportMessage.append(
                    "Parameter skipped: Service does not support parameter '" + requestParm.getName() + "'. ");
    }

    runner.setCommand(command);
    runner.setInputStream(inputStream);
    //timeout after 10 minutes, e.g. the tool crashed
    runner.setTimeout(600000);
    log.info("Executing command (update): " + command.toString() + " ...");

    long startMillis = System.currentTimeMillis();
    runner.run();
    long endMillis = System.currentTimeMillis();

    int return_code = runner.getReturnCode();
    if (return_code != 0) {
        log.severe("Kakadu conversion error code: " + Integer.toString(return_code));
        log.severe(runner.getProcessErrorAsString());
        return null;
    }
    if (return_code == -1) {
        //in this case the time-out occurred 
        ServiceReport report = new ServiceReport(Type.ERROR, Status.TOOL_ERROR,
                "process runner time-out occurred after 10 minutes of tool unresponsiveness");
        return new MigrateResult(null, report);
    }

    tmpOutFile = new File(outFileStr);
    ServiceReport report;

    // read byte array from temporary file
    if (tmpOutFile.isFile() && tmpOutFile.canRead()) {
        try {
            binary = FileUtils.readFileToByteArray(tmpOutFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //get the measured proeprties to return
        List<Property> retProps = sph.getPerformanceProperties();
        retProps.add(ServiceProperties.createToolRunnerTimeProperty(endMillis - startMillis));

        report = new ServiceReport(Type.INFO, Status.SUCCESS,
                serviceReportMessage.toString() + "Wrote: " + tmpOutFile, retProps);
    } else {
        String message = "Error: Unable to read temporary file " + tmpOutFile.getAbsolutePath();
        log.severe(message);
        report = new ServiceReport(Type.ERROR, Status.INSTALLATION_ERROR,
                serviceReportMessage.toString() + message);
    }

    DigitalObject newDO = null;

    newDO = new DigitalObject.Builder(Content.byValue(binary)).build();

    return new MigrateResult(newDO, report);
}

From source file:be.fedict.eid.idp.admin.webapp.bean.RPBean.java

@Override
@Begin(join = true)/*from  w w w. j a va  2  s  .c  o m*/
public void uploadListener(UploadEvent event) throws IOException {
    UploadItem item = event.getUploadItem();
    this.log.debug(item.getContentType());
    this.log.debug(item.getFileSize());
    this.log.debug(item.getFileName());
    if (null == item.getData()) {
        // meaning createTempFiles is set to true in the SeamFilter
        this.certificateBytes = FileUtils.readFileToByteArray(item.getFile());
    } else {
        this.certificateBytes = item.getData();
    }

    try {
        X509Certificate certificate = CryptoUtil.getCertificate(this.certificateBytes);
        this.log.debug("certificate: " + certificate);
        this.selectedRP.setCertificate(certificate);
    } catch (CertificateException e) {
        this.facesMessages.addToControl("upload", "Invalid certificate");
    }
}

From source file:algorithm.OpenStegoRandomLSBSteganography.java

@Override
public List<RestoredFile> restore(File carrier) throws IOException {
    List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
    File tmpDir = new File("tmpDir");
    tmpDir.mkdir();//from  w  w  w. j  av  a  2 s.c om
    try {
        String[] args = new String[] { "java", "-jar", LIBRARY_DIRECTORY + "openstego.jar", "extract", "-a",
                "RandomLSB", "-sf", "" + carrier.toPath(), "-xd", "" + tmpDir.toPath() };
        Process process = Runtime.getRuntime().exec(args);
        process.waitFor();
        InputStream inputStream = process.getInputStream();
        byte b[] = new byte[inputStream.available()];
        inputStream.read(b, 0, b.length);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    String originalCarrierPath = "";
    if (tmpDir.listFiles().length == 1) {
        File tmpMessage = tmpDir.listFiles()[0];
        byte[] payloadSegmentBytes = FileUtils.readFileToByteArray(tmpMessage);
        PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(payloadSegmentBytes);
        RestoredFile message = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName());
        message.originalFilePath = payloadSegment.getPayloadPath();
        originalCarrierPath = payloadSegment.getCarrierPath();
        FileUtils.writeByteArrayToFile(message, payloadSegment.getPayloadBytes());
        message.validateChecksum(payloadSegment.getPayloadChecksum());
        message.restorationNote = "Payload can be restored correctly.";
        message.wasPayload = true;
        restoredFiles.add(message);
    }
    FileUtils.forceDelete(tmpDir);
    RestoredFile copiedCarrier = new RestoredFile(RESTORED_DIRECTORY + carrier.getName());
    FileUtils.copyFile(carrier, copiedCarrier);
    copiedCarrier.wasCarrier = true;
    copiedCarrier.checksumValid = false;
    copiedCarrier.restorationNote = "The carrier can't be restored with this steganography algorithm. It still contains the embedded payload file(s).";
    copiedCarrier.originalFilePath = originalCarrierPath;
    restoredFiles.add(copiedCarrier); // The carrier can not be restored;
    for (RestoredFile file : restoredFiles) {
        file.algorithm = this;
        for (RestoredFile relatedFile : restoredFiles) {
            if (file != relatedFile) {
                file.relatedFiles.add(relatedFile);
            }
        }
    }
    return restoredFiles;
}

From source file:eu.planets_project.services.migration.kakadu.KakaduCompressMigration.java

/**
 * {@inheritDoc}/* www. j av  a 2  s .  com*/
 * @see eu.planets_project.services.migrate.Migrate#migrate(eu.planets_project.services.datatypes.DigitalObject,
 *      java.net.URI, java.net.URI,
 *      eu.planets_project.services.datatypes.Parameter)
 */
public MigrateResult migrate(final DigitalObject digitalObject, URI inputFormat, URI outputFormat,
        List<Parameter> parameters) {

    // Start timing...
    ServicePerformanceHelper sph = new ServicePerformanceHelper();

    requestParametersList = parameters;
    Properties props = new Properties();
    try {

        String strRsc = "/eu/planets_project/services/migration/kakadu/kakadu.properties";
        props.load(this.getClass().getResourceAsStream(strRsc));
        // config vars
        this.kakadu_install_dir = props.getProperty("kakadu.install.dir");
        this.kakadu_app_name = props.getProperty("kakadu.app.name");

    } catch (Exception e) {
        // // config vars
        this.kakadu_install_dir = "C:/Programme/Kakadu";
        this.kakadu_app_name = "kdu_compress";
    }
    log.info("Using kakadu install directory: " + this.kakadu_install_dir);
    log.info("Using kakadu application name: " + this.kakadu_app_name);

    init();
    // Initialise parameters with default values
    initParameters();
    getExtensions(inputFormat, outputFormat);

    /*
     * We just return a new digital object with the same required arguments
     * as the given:
     */
    byte[] binary = null;
    InputStream inputStream = digitalObject.getContent().getInputStream();

    // write input object to temporary file
    tmpInFile = DigitalObjectUtils.toFile(digitalObject); //TODO need extension?

    // Record time take to load the input data:
    sph.loaded();

    if (!(tmpInFile.exists() && tmpInFile.isFile() && tmpInFile.canRead())) {
        log.severe("Unable to create temporary input file!");
        return null;
    }
    log.info("Temporary input file created: " + tmpInFile.getAbsolutePath());

    // outfile name
    String outFileStr = tmpInFile.getAbsolutePath().replaceAll(inputFmtExt, "jp2");

    log.info("Output file name: " + outFileStr);

    StringBuffer serviceReportMessage = new StringBuffer();
    // run command
    ProcessRunner runner = new ProcessRunner();
    List<String> command = new ArrayList<String>();
    // setting up command
    // -i source.tif -o destination.jp2 Creversible=yes -rate -,1,0.5,0.25 Clevels=5
    command.add(this.kakadu_app_name);
    command.add("-i");
    command.add(tmpInFile.getAbsolutePath());
    command.add("-o");
    command.add(outFileStr);
    for (Parameter requestParm : requestParametersList) {
        ServiceParameter servParm = kduServiceParameters.getParameter(requestParm.getName());
        if (servParm != null) {
            servParm.setRequestValue(requestParm.getValue());
            if (servParm.isValid())
                command.addAll(servParm.getCommandListItems());
            else
                serviceReportMessage.append(servParm.getStatusMessage());
        } else
            serviceReportMessage.append(
                    "Parameter skipped: Service does not support parameter '" + requestParm.getName() + "'. ");
    }

    runner.setCommand(command);
    runner.setInputStream(inputStream);
    //timeout after 10 minutes, e.g. the tool crashed
    runner.setTimeout(600000);
    log.info("Executing command (update): " + command.toString() + " ...");

    long startMillis = System.currentTimeMillis();
    runner.run();
    long endMillis = System.currentTimeMillis();
    int return_code = runner.getReturnCode();
    if (return_code != 0) {
        log.severe("Kakadu conversion error code: " + Integer.toString(return_code));
        log.severe(runner.getProcessErrorAsString());
        return null;
    }
    if (return_code == -1) {
        //in this case the time-out occurred 
        ServiceReport report = new ServiceReport(Type.ERROR, Status.TOOL_ERROR,
                "process runner time-out occurred after 10 minutes of tool unresponsiveness");
        return new MigrateResult(null, report);
    }

    tmpOutFile = new File(outFileStr);
    ServiceReport report;

    // read byte array from temporary file
    if (tmpOutFile.isFile() && tmpOutFile.canRead()) {
        try {
            binary = FileUtils.readFileToByteArray(tmpOutFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //get the measured proeprties to return
        List<Property> retProps = sph.getPerformanceProperties();
        retProps.add(ServiceProperties.createToolRunnerTimeProperty(endMillis - startMillis));

        report = new ServiceReport(Type.INFO, Status.SUCCESS,
                serviceReportMessage.toString() + "Wrote: " + tmpOutFile, retProps);
    } else {
        String message = "Error: Unable to read temporary file " + tmpOutFile.getAbsolutePath();
        log.severe(message);
        report = new ServiceReport(Type.ERROR, Status.INSTALLATION_ERROR,
                serviceReportMessage.toString() + message);
    }

    //build the returning digital object
    DigitalObject newDO = null;
    newDO = new DigitalObject.Builder(Content.byValue(binary)).build();

    return new MigrateResult(newDO, report);
}

From source file:be.fedict.trust.admin.portal.bean.TrustPointBean.java

/**
 * {@inheritDoc}/*ww  w  .jav a 2 s.c  om*/
 */
@Begin(join = true)
public void uploadListener(UploadEvent event) throws IOException {
    UploadItem item = event.getUploadItem();
    this.log.debug(item.getContentType());
    this.log.debug(item.getFileSize());
    this.log.debug(item.getFileName());
    if (null == item.getData()) {
        // meaning createTempFiles is set to true in the SeamFilter
        this.certificateBytes = FileUtils.readFileToByteArray(item.getFile());
    } else {
        this.certificateBytes = item.getData();
    }
}

From source file:com.googlecode.dex2jar.reader.DexFileReader.java

/**
 * read dex from a file/*from  ww w.  jav  a  2 s.co m*/
 * 
 * @param file
 *            a dex/odex file or a zip file contains classes.dex
 * @throws IOException
 */
public DexFileReader(File file) throws IOException {
    this(FileUtils.readFileToByteArray(file));
}

From source file:com.jaspersoft.studio.editor.defaults.DefaultManager.java

/**
 * Load the current default template set, creating it's model structure
 *///w  w w . jav a  2s . c o m
private void loadDefaultModel() {
    InputStream in = null;
    selectedDefaultsMap = new HashMap<Class<?>, MGraphicElement>();
    defaultReport = null;
    try {
        File defaultFile = new File(actualDefault);
        if (defaultFile.exists()) {
            in = new ByteArrayInputStream(FileUtils.readFileToByteArray(defaultFile));
            JasperReportsConfiguration jConfig = getDefaultJRConfig();
            JasperDesign jd = new JRXmlLoader(jConfig, JRXmlDigesterFactory.createDigester(jConfig))
                    .loadXML(in);
            jConfig.setJasperDesign(jd);
            defaultReport = ReportFactory.createReport(jConfig);
            defaultReport.getChildren().get(0).setValue(jd);
            defaultConfig = jConfig;
            setElementsType();
        }
    } catch (Exception e) {
        actualDefault = null;
        defaultReport = null;
        e.printStackTrace();
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
            }
    }
}

From source file:com.ylink.ylpay.project.mp.workorder.service.WorkOrderManagerImpl.java

@Override
public void save(WorkOrder workOrder, List<UploadBean> listBean) throws Exception {
    logger.debug("?...");

    Assert.notNull(workOrder, "workOrderDTO?.");
    Assert.notNull(workOrder.getContactUserPhone(), "ContactUserPhone?.");
    Assert.notNull(workOrder.getAscendingNodeName(), "AscendingNodeName?.");
    Assert.notNull(workOrder.getIpAlready(), "IpAlready?.");
    Assert.notNull(workOrder.getNewIpDistribution(), "NewIpDistribution?.");
    Assert.notNull(workOrder.getDistributionSign(), "DistributionSign?.");
    Assert.notNull(workOrder.getDistributioDate(), "DistributioDate?.");
    Assert.notNull(workOrder.getLineTerminalDevice(), "LineTerminalDevice?.");
    Assert.notNull(workOrder.getOriginalDeviceModel(), "OriginalDeviceModel?.");
    Assert.notNull(workOrder.getOriginalDeviceAmount(), "OriginalDeviceAmount?.");

    workOrder.setOrderNo(this.sequenceManager.nextSequenceNumber(workOrder));
    // ?: ./* ww  w.j  ava  2  s .c  o  m*/
    workOrder.setStatus(EntityStatus.NEW);
    // ?: ?.
    workOrder.setWorkOrderAuditStatus(WorkOrderAuditStatus.WAIT_AUDIT);
    // 
    workOrder.setCreateTime(new Date());
    if (listBean != null && !listBean.isEmpty())
        for (int i = 0; i < listBean.size(); i++) {
            CustCert custCert = new CustCert();
            byte[] fileBytes = FileUtils.readFileToByteArray(listBean.get(i).getUpload());
            custCert.setCertFile(fileBytes);
            custCert.setAuditStatus(AuditStatus.WAIT_AUDIT);
            if (i == 0) {
                custCert.setCertType(CertificationType.C01);
                workOrder.setBusinessLicenseCertId((Long) custCertManager.saveEntity(custCert));
            } else {
                custCert.setCertType(CertificationType.P01);
                workOrder.setIdCardCertId((Long) custCertManager.saveEntity(custCert));
            }
        }
    this.dao.create(workOrder);
}