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.netsteadfast.greenstep.util.UploadSupportUtils.java

public static String create(String system, String type, boolean isFile, File file, String showName)
        throws ServiceException, IOException, Exception {
    if (StringUtils.isBlank(type) || null == file || StringUtils.isBlank(showName)) {
        throw new Exception("parameter is blank!");
    }/*from w  w  w.j a v a  2  s .  c om*/
    if (!file.exists()) {
        throw new Exception("file no exists!");
    }
    SysUploadVO upload = new SysUploadVO();
    upload.setIsFile((isFile ? YesNo.YES : YesNo.NO));
    upload.setShowName(showName);
    upload.setSystem(system);
    upload.setType(type);
    upload.setSubDir(getSubDir());
    if (isFile) {
        String uploadDir = getUploadFileDir(system, type);
        String uploadFileName = generateRealFileName(file);
        mkdirUploadFileDir(system, type);
        FSUtils.cp(file.getPath(), uploadDir + "/" + uploadFileName);
        upload.setFileName(uploadFileName);
    } else {
        upload.setContent(FileUtils.readFileToByteArray(file));
        upload.setFileName(" ");
    }
    DefaultResult<SysUploadVO> result = sysUploadService.saveObject(upload);
    if (result.getValue() == null) {
        throw new ServiceException(result.getSystemMessage().getValue());
    }
    return result.getValue().getOid();
}

From source file:com.cloudant.sync.indexing.IndexManagerIndexTest.java

@Test
public void indexString_documentWithInvalidField_indexRowShouldNotBeAdded()
        throws IndexExistsException, IOException, SQLException {
    Index index = createAndGetIndex("StringIndex", "stringIndex", IndexType.STRING);
    byte[] data = FileUtils.readFileToByteArray(new File("fixture/string_index_invalid_field.json"));
    DocumentRevision obj = datastore.createDocument(DocumentBodyFactory.create(data));
    IndexTestUtils.assertDBObjectNotInIndex(database, index, obj);
}

From source file:com.xpn.xwiki.plugin.graphviz.GraphVizPlugin.java

/**
 * Get the contents of a previously generated temporary file.
 * //  w w w.ja v  a2 s  .  com
 * @param ofile the file to read
 * @return the content found inside the file, if any
 * @throws IOException when reading the file fails
 */
private byte[] readDotImage(File ofile) throws IOException {
    return FileUtils.readFileToByteArray(ofile);
}

From source file:gov.nih.nci.nbia.wadosupport.WADOSupportDAOImpl.java

@Transactional(propagation = Propagation.REQUIRED)
public WADOSupportDTO getOviyamWADOSupportDTO(String image, String contentType, String user,
        WADOParameters params) {/* w w w .j  a  va 2  s  . c om*/
    WADOSupportDTO returnValue = new WADOSupportDTO();
    log.info("Oviyam wado image-" + image);
    try {
        List<Object[]> images = this.getHibernateTemplate().getSessionFactory().getCurrentSession()
                .createSQLQuery(WADO_OVIYAM_QUERY).setParameter("image", image).list();
        if (images.size() == 0) {
            log.info("image not found");
            return null; //nothing to do
        }
        List<SiteData> authorizedSites;
        UserObject uo = userTable.get(user);
        if (uo != null) {
            authorizedSites = uo.getAuthorizedSites();
            if (authorizedSites == null) {
                AuthorizationManager manager = new AuthorizationManager(user);
                authorizedSites = manager.getAuthorizedSites();
                uo.setAuthorizedSites(authorizedSites);
            }
        } else {
            AuthorizationManager manager = new AuthorizationManager(user);
            authorizedSites = manager.getAuthorizedSites();
            uo = new UserObject();
            uo.setAuthorizedSites(authorizedSites);
            userTable.put(user, uo);
        }
        returnValue.setCollection((String) images.get(0)[0]);
        returnValue.setSite((String) images.get(0)[1]);
        boolean isAuthorized = false;
        for (SiteData siteData : authorizedSites) {
            if (siteData.getCollection().equals(returnValue.getCollection())) {
                if (siteData.getSiteName().equals(returnValue.getSite())) {
                    isAuthorized = true;
                    break;
                }
            }
        }
        if (!isAuthorized) {
            System.out.println("User: " + user + " not authorized");
            return null; //not authorized
        }
        String filePath = (String) images.get(0)[2];
        File imageFile = new File(filePath);
        if (!imageFile.exists()) {
            log.error("File " + filePath + " does not exist");
            return null;
        }
        if (contentType.equals(("application/dicom"))) {
            returnValue.setImage(FileUtils.readFileToByteArray(imageFile));
        } else {
            JPEGResult result = DCMUtils.getJPGFromFile(imageFile, params);
            if (result.getErrors() != null) {
                returnValue.setErrors(result.getErrors());
                return returnValue;
            }
            returnValue.setImage(result.getImages());
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
    return returnValue;
}

From source file:com.sat.vcse.automation.utils.shell.SSHClient.java

/**
 * SCPs a passed in class resource (file) to the specified filename
 * and file directory and sets the mode of the file on the SSH server
 * /*from w  w w. ja va2 s  .com*/
 * @param inputFile : local file which needs to be SCP'ed
 *            
 * @param remoteFileName
 *            The name that will be given to the SCP'ed file on the SSH
 *            server
 * @param remoteTargetDirectory
 *            The directory where the file will be placed on the SSH server
 * @param mode
 *            The file mode that will be assigned to the SCP'ed file, e.g.
 *            0744
 */
public void scpFile(final File inputFile, String remoteFileName, final String remoteTargetDirectory,
        final String mode) {

    final String METHOD_NAME = "scpFile(File,String,String,String): ";
    if (!this.isLogInDone) {
        logIn();
    }

    if (remoteFileName == null) {
        remoteFileName = inputFile.getName();
    }

    if (!inputFile.exists()) {
        //This means the file might be present in subclass path.
        //So try that now
        scpFile(readFromClassPath(inputFile.getPath()), remoteFileName, remoteTargetDirectory, mode);
        return;
    }
    final SCPClient scpClient = new SCPClient(sshConn);
    try (OutputStream scpOutStream = scpClient.put(remoteFileName, inputFile.length(), remoteTargetDirectory,
            mode);) {
        scpOutStream.write(FileUtils.readFileToByteArray(inputFile));
        scpOutStream.flush();
    } catch (IOException exp) {
        LogHandler.error(CLASS_NAME + METHOD_NAME + "Exception: scping" + exp.getMessage());
        throw new CoreRuntimeException(exp, CLASS_NAME + METHOD_NAME + "Exception: scping" + exp.getMessage());
    } finally {
        tryLogOut();
    }

}

From source file:com.turn.ttorrent.common.Torrent.java

/**
 * Load a torrent from the given torrent file.
 *
 * @param torrent The abstract {@link File} object representing the
 * <tt>.torrent</tt> file to load.
 * @param seeder Whether we are a seeder for this torrent or not (disables
 * local data validation).//w  ww.  j  a v  a 2  s  .co  m
 * @throws IOException When the torrent file cannot be read.
 */
public static Torrent load(File torrent, boolean seeder) throws IOException, NoSuchAlgorithmException {
    byte[] data = FileUtils.readFileToByteArray(torrent);
    return new Torrent(data, seeder);
}

From source file:com.bittorrent.mpetazzoni.common.Torrent.java

/**
 * Load a torrent from the given torrent file.
 *
 * @param torrent The abstract {@link File} object representing the
 * <tt>.torrent</tt> file to load.
 * @param seeder Whether we are a seeder for this torrent or not (disables
 * local data validation).//w w  w . j  a  v a2s.co  m
 * @throws IOException When the torrent file cannot be read.
 */
public static Torrent load(File torrent, boolean seeder) throws IOException {
    byte[] data = FileUtils.readFileToByteArray(torrent);
    return new Torrent(data, seeder);
}

From source file:$.DeviceTypeServiceImpl.java

@Path("/device/download")
    @GET/* w  w  w. ja  v a  2 s  .  c om*/
    @Produces("application/zip")
    public Response downloadSketch(@QueryParam("deviceName") String deviceName,
            @QueryParam("sketchType") String sketchType) {
        try {
            ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
            Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
            response.status(Response.Status.OK);
            response.type("application/zip");
            response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
            Response resp = response.build();
            zipFile.getZipFile().delete();
            return resp;
        } catch (IllegalArgumentException ex) {
            return Response.status(400).entity(ex.getMessage()).build();//bad request
        } catch (DeviceManagementException ex) {
            log.error(ex.getMessage(), ex);
            return Response.status(500).entity(ex.getMessage()).build();
        } catch (JWTClientException ex) {
            log.error(ex.getMessage(), ex);
            return Response.status(500).entity(ex.getMessage()).build();
        } catch (APIManagerException ex) {
            log.error(ex.getMessage(), ex);
            return Response.status(500).entity(ex.getMessage()).build();
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
            return Response.status(500).entity(ex.getMessage()).build();
        } catch (UserStoreException ex) {
            log.error(ex.getMessage(), ex);
            return Response.status(500).entity(ex.getMessage()).build();
        }
    }

From source file:controllers.admin.AuditableController.java

/**
 * Creates an archive of all the audit logs files and set it into the
 * personal space of the current user./*from w w  w  .j  av a2  s  .c o m*/
 */
public Promise<Result> exportAuditLogs() {
    return Promise.promise(new Function0<Result>() {
        @Override
        public Result apply() throws Throwable {
            try {
                final String currentUserId = getUserSessionManagerPlugin().getUserSessionId(ctx());
                final String errorMessage = Msg.get("admin.auditable.export.notification.error.message");
                final String successTitle = Msg.get("admin.auditable.export.notification.success.title");
                final String successMessage = Msg.get("admin.auditable.export.notification.success.message");
                final String notFoundMessage = Msg.get("admin.auditable.export.notification.not_found.message");
                final String errorTitle = Msg.get("admin.auditable.export.notification.error.title");

                // Audit log export requested
                if (log.isDebugEnabled()) {
                    log.debug("Audit log export : Audit log export requested by " + currentUserId);
                }

                // Execute asynchronously
                getSysAdminUtils().scheduleOnce(false, "AUDITABLE", Duration.create(0, TimeUnit.MILLISECONDS),
                        new Runnable() {
                            @Override
                            public void run() {
                                // Find the files to be archived
                                String logFilesPathAsString = getConfiguration()
                                        .getString("maf.audit.log.location");
                                File logFilesPath = new File(logFilesPathAsString);
                                File logDirectory = logFilesPath.getParentFile();

                                if (!logDirectory.exists()) {
                                    log.error("Log directory " + logDirectory.getAbsolutePath()
                                            + " is not found, please check the configuration");
                                    return;
                                }

                                final String logFilePrefix = (logFilesPath.getName().indexOf('.') != -1
                                        ? logFilesPath.getName().substring(0,
                                                logFilesPath.getName().indexOf('.'))
                                        : logFilesPath.getName());

                                if (log.isDebugEnabled()) {
                                    log.debug("Audit log export : Selecting files to archive");
                                }

                                File[] filesToArchive = logDirectory.listFiles(new FilenameFilter() {
                                    @Override
                                    public boolean accept(File dir, String name) {
                                        return name.startsWith(logFilePrefix);
                                    }
                                });

                                if (filesToArchive.length != 0) {
                                    if (log.isDebugEnabled()) {
                                        log.debug("Audit log export : zipping the " + filesToArchive.length
                                                + " archive files");
                                    }

                                    // Write to the user personal space
                                    final String fileName = String.format(
                                            "auditExport_%1$td_%1$tm_%1$ty_%1$tH-%1$tM-%1$tS.zip", new Date());
                                    ZipOutputStream out = null;
                                    try {
                                        OutputStream personalOut = getPersonalStoragePlugin()
                                                .createNewFile(currentUserId, fileName);
                                        out = new ZipOutputStream(personalOut);
                                        for (File fileToArchive : filesToArchive) {
                                            ZipEntry e = new ZipEntry(fileToArchive.getName());
                                            out.putNextEntry(e);
                                            byte[] data = FileUtils.readFileToByteArray(fileToArchive);
                                            out.write(data, 0, data.length);
                                            out.closeEntry();
                                        }
                                        getNotificationManagerPlugin().sendNotification(currentUserId,
                                                NotificationCategory.getByCode(Code.AUDIT), successTitle,
                                                successMessage,
                                                controllers.my.routes.MyPersonalStorage.index().url());

                                    } catch (Exception e) {
                                        log.error("Fail to export the audit archives", e);
                                        getNotificationManagerPlugin().sendNotification(currentUserId,
                                                NotificationCategory.getByCode(Code.ISSUE), errorTitle,
                                                errorMessage, controllers.admin.routes.AuditableController
                                                        .listAuditable().url());
                                    } finally {
                                        IOUtils.closeQuietly(out);
                                    }
                                } else {
                                    log.error("No audit archive found in the folder");
                                    getNotificationManagerPlugin().sendNotification(currentUserId,
                                            NotificationCategory.getByCode(Code.ISSUE), errorTitle,
                                            notFoundMessage,
                                            controllers.admin.routes.AuditableController.listAuditable().url());
                                }
                            }
                        });

                return ok(Json.newObject());
            } catch (Exception e) {
                return ControllersUtils.logAndReturnUnexpectedError(e, log, getConfiguration(),
                        getMessagesPlugin());
            }
        }
    });
}

From source file:com.esri.arcgisruntime.sample.editfeatureattachments.EditAttachmentActivity.java

/**
 * Upload the selected image from the gallery as an attachment to the selected feature
 *
 * @param requestCode RESULT_LOAD_IMAGE request code to identify the requesting activity
 * @param resultCode  activity result code
 * @param data        Uri of the selected image
 *//*  w w w  . j  av  a  2 s  .co  m*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            // covert file to bytes to pass to ArcGISFeature
            byte[] imageByte = new byte[0];
            try {
                File imageFile = new File(picturePath);
                imageByte = FileUtils.readFileToByteArray(imageFile);
            } catch (IOException e) {
                e.printStackTrace();
            }

            final String attachmentName = getApplication().getString(R.string.attachment) + "_"
                    + System.currentTimeMillis() + ".png";

            progressDialog.setTitle(getApplication().getString(R.string.apply_edit_message));
            progressDialog.setMessage(getApplication().getString(R.string.wait));

            progressDialog.show();

            ListenableFuture<Attachment> addResult = mSelectedArcGISFeature.addAttachmentAsync(imageByte,
                    "image/png", attachmentName);

            addResult.addDoneListener(new Runnable() {
                @Override
                public void run() {
                    final ListenableFuture<Void> tableResult = mServiceFeatureTable
                            .updateFeatureAsync(mSelectedArcGISFeature);
                    tableResult.addDoneListener(new Runnable() {
                        @Override
                        public void run() {
                            applyServerEdits();
                        }
                    });
                }
            });
        }
    }

}