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:demo.admin.controller.UserController.java

@RequestMapping(value = "/user/downloadData")
@VerifyAuthentication(Trader = true, Admin = true, Operation = true)
public HttpEntity<byte[]> downloadUserData(String status, String securephone,
        @RequestParam(value = "startDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
        @RequestParam(value = "endDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate)
        throws IOException, DocumentException {
    if (securephone != null && securephone != "") {
        securephone = Where.$like$(securephone);
    }//from ww  w  .  j av a 2s. c o  m
    List<Map<String, Object>> users = userMapper.userExport(status, securephone, startDate, endDate);
    String type = status + "?";
    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet(type);
    HSSFRow row = sheet.createRow(0);
    CellStyle cellStyle = wb.createCellStyle();
    cellStyle.setAlignment(CellStyle.ALIGN_CENTER);
    cellStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

    sheet.setVerticallyCenter(true);
    sheet.setHorizontallyCenter(true);
    String[] excelHeader = { "??", "???", "??", "", "??" };
    for (int i = 0; i < excelHeader.length; i++) {
        HSSFCell cell = row.createCell(i);
        cell.setCellValue(excelHeader[i]);
        cell.setCellStyle(cellStyle);
        sheet.autoSizeColumn(i, true);
    }
    for (int i = 0; i < users.size(); i++) {
        Map<String, Object> resultSet = users.get(i);
        sheet.autoSizeColumn(i, true);
        row = sheet.createRow(i + 1);
        row.setRowStyle(cellStyle);
        row.createCell(0).setCellValue(i + 1);
        row.createCell(1).setCellValue(String.valueOf(resultSet.get("name")));
        row.createCell(2).setCellValue(String.valueOf(resultSet.get("address")));
        row.createCell(3).setCellValue(String.valueOf(resultSet.get("registertime")));
        row.createCell(4).setCellValue(String.valueOf(resultSet.get("securephone")));

    }
    File file = File.createTempFile(".xls", ".xls");
    OutputStream out = new FileOutputStream(file);
    wb.write(out);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment",
            URLEncoder.encode(type, "UTF-8") + LocalDate.now() + ".xls");
    return new HttpEntity<byte[]>(FileUtils.readFileToByteArray(file), headers);
}

From source file:net.doubledoordev.backend.server.FileManager.java

public String getFileContents() throws IOException {
    switch (getExtension()) {
    case "json":
        return FileUtils.readFileToString(file);
    case "dat":
    case "dat_old":

        Tag tag = Helper.readRawNBT(file, true);
        if (tag == null)
            tag = Helper.readRawNBT(file, false);
        if (tag != null) {
            return JsonNBTHelper.parseNBT(tag).toString();
        } else {//  w ww  . j a v a2  s  .  co m
            return FileUtils.readFileToString(file);
        }
    case "jpg":
    case "png":
        return String.format("data:%s;base64,%s", MimeType.get(getExtension()),
                Base64.encodeBase64String(FileUtils.readFileToByteArray(file)));
    case "jar":
    case "zip":
    case "disabled":
    case "mca":
    case "mcr":
        return null;
    default:
        return StringEscapeUtils.escapeHtml4(FileUtils.readFileToString(file));
    }
}

From source file:com.ikanow.infinit.e.api.social.sharing.ShareHandler.java

/**
 * getShare//from   w w  w  . ja va  2 s .  co m
 * Retrieve an individual share by id
 * @param shareIdStr
 * @return
 */
public ResponsePojo getShare(String userIdStr, String shareIdStr, boolean returnContent) {
    ResponsePojo rp = new ResponsePojo();

    BasicDBObject query = new BasicDBObject("_id", new ObjectId(shareIdStr));
    HashSet<ObjectId> memberOf = null;

    if (!RESTTools.adminLookup(userIdStr)) { // (admins can see all shares)         
        memberOf = SocialUtils.getUserCommunities(userIdStr);
        if (null != memberOf) {
            query.put("communities._id", new BasicDBObject("$in", memberOf));
        } else { // (some error but we'll let this go if the share has no security)
            query.put("communities", new BasicDBObject("$exists", false));
        }
    }

    try {
        BasicDBObject dbo = (BasicDBObject) DbManager.getSocial().getShare().findOne(query);
        if (null != dbo) {
            byte[] bytes = (byte[]) dbo.remove("binaryData");

            SharePojo share = SharePojo.fromDb(dbo, SharePojo.class);
            share.setBinaryData(bytes);

            //new way of handling bytes, if has a binaryid, get bytes from there and set

            if (returnContent) {
                if (null != share.getBinaryId()) {
                    share.setBinaryData(getGridFile(share.getBinaryId()));
                } //TESTED
                else if (null != share.getDocumentLocation()) {
                    try {
                        if ((null != share.getType()) && share.getType().equalsIgnoreCase("binary")) {
                            File x = new File(share.getDocumentLocation().getCollection());
                            share.setBinaryData(FileUtils.readFileToByteArray(x));
                        } //TESTED
                        else { // text
                            share.setShare(getReferenceString(share));
                        } //TESTED
                    } catch (Exception e) {
                        rp.setResponse(new ResponseObject("Get Share", false,
                                "Unable to get share reference: " + e.getMessage()));
                        return rp;
                    } //TESTED
                }
                // (else share.share already set)
            } else { // don't return content
                share.setShare(null);
            } //TESTED

            rp.setData(share, new SharePojoApiMap(memberOf));
            rp.setResponse(new ResponseObject("Share", true, "Share returned successfully"));
        } else {
            rp.setResponse(new ResponseObject("Get Share", false,
                    "Unable to get share, not found or no access permission"));
        }
    } catch (Exception e) {
        logger.error("Exception Message: " + e.getMessage(), e);
        rp.setResponse(new ResponseObject("Get Share", false, "Unable to get share: " + e.getMessage()));
    }
    return rp;
}

From source file:be.fedict.eid.dss.admin.portal.control.bean.RPBean.java

@Override
@Begin(join = true)//from  ww  w  . j  a va2s  .  co m
public void uploadListenerLogo(UploadEvent event) throws IOException {

    UploadItem item = event.getUploadItem();
    this.log.debug(item.getContentType());
    this.log.debug(item.getFileSize());
    this.log.debug(item.getFileName());

    byte[] logoBytes;
    if (null == item.getData()) {
        // meaning createTempFiles is set to true in the SeamFilter
        logoBytes = FileUtils.readFileToByteArray(item.getFile());
    } else {
        logoBytes = item.getData();
    }

    this.selectedRP.setLogo(logoBytes);
}

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

public String update(LoginAccount user, WorkOrder workOrder, List<UploadBean> listBean) throws Exception {
    if (workOrder == null)
        throw new ApplicationException("??");

    WorkOrder dbWorkOrder = this.getDao().getWorkOrder(workOrder.getId());
    // /*from  www. j  ava2 s .c  om*/
    WorkOrder originalWorkOrder = dbWorkOrder, newWorkOrder = workOrder;
    // .
    newWorkOrder.setCreateTime(dbWorkOrder.getCreateTime());
    if (workOrder.getStatus() != null) {
        newWorkOrder.setStatus(workOrder.getStatus());
    } else {
        newWorkOrder.setStatus(dbWorkOrder.getStatus());
    }
    //?
    newWorkOrder.setWorkOrderAuditStatus(dbWorkOrder.getWorkOrderAuditStatus());
    newWorkOrder.setCreator(dbWorkOrder.getCreator());
    if (listBean != null && !listBean.isEmpty()) {
        int size = listBean.size();
        int i = 0;
        while (i < size) {
            CustCert custCert = new CustCert();
            byte[] fileBytes = null;
            if (listBean.get(i) != null) {
                fileBytes = FileUtils.readFileToByteArray(listBean.get(i).getUpload());
                custCert.setCertFile(fileBytes);
            }
            custCert.setAuditStatus(AuditStatus.WAIT_AUDIT);
            switch (i) {
            case 0:
                custCert.setCertType(CertificationType.P01);
            case 1:
                custCert.setCertType(CertificationType.P01);
            default:
                break;
            }
            custCert = null;
            i++;
        }
    }
    // ?
    String remark = "?????";
    if (workOrder.getRemark() != null) {
        remark = workOrder.getRemark();
    }
    WorkOrderChange.Type type = WorkOrderChange.Type.UPDATE;
    if (newWorkOrder.getStatus() != null && EntityStatus.DISABLED.equals(newWorkOrder.getStatus())) {
        type = WorkOrderChange.Type.DELETE;
    }
    workOrderChangeManager.save(user, type, originalWorkOrder, newWorkOrder, remark);
    return "??";
}

From source file:com.buddycloud.mediaserver.MediaServerTest.java

protected Form createWebForm(String name, String title, String description, String filePath,
        String contentType) {//  w  w  w. j a va2 s.c o m
    Form form = new Form();

    if (name != null) {
        form.set(Constants.NAME_FIELD, name);
    }

    if (title != null) {
        form.set(Constants.TITLE_FIELD, title);
    }

    if (description != null) {
        form.set(Constants.DESC_FIELD, description);
    }

    if (contentType != null) {
        form.set(Constants.TYPE_FIELD, contentType);
    }

    if (filePath != null) {
        try {
            File file = new File(filePath);
            byte[] byteArray = FileUtils.readFileToByteArray(file);

            form.set(Constants.DATA_FIELD, Base64.encode(byteArray, false));
        } catch (IOException e) {
        }
    }

    return form;
}

From source file:com.zacwolf.commons.crypto.Crypter_Blowfish.java

/**
 * @param keyfile//from ww w. j  a v  a  2 s  .c  o m
 * @param cipher
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public Crypter_Blowfish(final File keyfile, final String cipher) throws NoSuchAlgorithmException, IOException {
    this(FileUtils.readFileToByteArray(keyfile), cipher);
}

From source file:com.servicelibre.jxsl.scenario.XslScenario.java

public Map<String, String> apply(File xmlFile) {
    try {//from w w w . j  av  a  2 s. com
        return apply(FileUtils.readFileToByteArray(xmlFile), xmlFile.getAbsolutePath());
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

    return new HashMap<String, String>();
}

From source file:com.zacwolf.commons.crypto.Crypter_AES.java

/**
 * @param keyfile// w w w .  j  ava2 s  .c  o  m
 * @param cipher
 * @throws NoSuchAlgorithmException
 * @throws IOException
 */
public Crypter_AES(final File keyfile, final String cipher) throws NoSuchAlgorithmException, IOException {
    this(FileUtils.readFileToByteArray(keyfile), cipher);
}

From source file:net.ripe.rpki.validator.fetchers.RsyncRpkiRepositoryObjectFetcher.java

private byte[] readFile(File destinationFile, ValidationResult validationResult) {
    byte[] result;
    try {/*from w ww . j a va2s.  c o  m*/
        result = FileUtils.readFileToByteArray(destinationFile);
    } catch (IOException e) {
        result = null;
    }
    validationResult.rejectIfNull(result, VALIDATOR_READ_FILE, destinationFile.getAbsolutePath());
    return result;
}