List of usage examples for org.apache.commons.io FileUtils readFileToByteArray
public static byte[] readFileToByteArray(File file) throws IOException
From source file:com.falkonry.TestAddFactsStream.java
/** * Should create datastream and add fact stream data in CSV format * @throws Exception/* w w w.j a v a2 s.c o m*/ */ @Test public void createDatastreamWithCsvFactsStream() throws Exception { Datastream ds = new Datastream(); ds.setName("Test-DS-" + Math.random()); TimeObject time = new TimeObject(); time.setIdentifier("time"); time.setFormat("iso_8601"); time.setZone("GMT"); Signal signal = new Signal(); signal.setTagIdentifier("tag"); signal.setValueIdentifier("value"); signal.setDelimiter("_"); signal.setIsSignalPrefix(false); Field field = new Field(); field.setSiganl(signal); field.setTime(time); ds.setField(field); Datasource dataSource = new Datasource(); dataSource.setType("STANDALONE"); ds.setDatasource(dataSource); Datastream datastream = falkonry.createDatastream(ds); datastreams.add(datastream); List<Assessment> assessments = new ArrayList<Assessment>(); AssessmentRequest assessmentRequest = new AssessmentRequest(); assessmentRequest.setName("Health"); assessmentRequest.setDatastream(datastream.getId()); assessmentRequest.setAssessmentRate("PT1S"); Assessment assessment = falkonry.createAssessment(assessmentRequest); assessments.add(assessment); Map<String, String> options = new HashMap<String, String>(); String data = "time, tag, value\n2016-03-01 01:01:01, entity1_signal1, 3.4"; falkonry.addInput(datastream.getId(), data, options); File file = new File("res/factsData.csv"); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file)); InputStatus response = falkonry.addFactsStream(assessment.getId(), byteArrayInputStream, null); Assert.assertEquals(response.getAction(), "ADD_FACT_DATA"); Assert.assertEquals(response.getStatus(), "PENDING"); }
From source file:com.screenslicer.common.CommonFile.java
public static byte[] readFileToByteArray(File file) { byte[] content = null; synchronized (lock(file.getAbsolutePath())) { try {//from w w w .ja v a 2s . co m content = FileUtils.readFileToByteArray(file); } catch (Throwable t) { Log.exception(t); } } unlock(file.getAbsolutePath()); return content; }
From source file:model.NotesImageFile.java
/** * This constructor is used to turn the image into an base64 image buffer so that it can be shown in the jsp * @param imgId/* ww w . ja v a 2s . c o m*/ * @param imgFullFilePath * @param contentType */ public NotesImageFile(int imgId, String imgFullFilePath, String contentType) { this.id = imgId; this.uniqueFileLocation = imgFullFilePath; this.contentType = contentType; this.fileName = splitTheFilePathOnLastSlashToGetTheName(imgFullFilePath); try { //this.base64Encoding = Base64.encodeBase64URLSafeString(FileUtils.readFileToByteArray(getImageFile(imgFullFilePath))); this.base64Encoding = Base64 .encodeBase64String(FileUtils.readFileToByteArray(getImageFile(imgFullFilePath))); } catch (IOException ex) { Logger.getLogger(NotesImageFile.class.getName()).log(Level.SEVERE, null, ex); System.err.println("File could not be found where specified"); ex.printStackTrace(); } }
From source file:de.topobyte.largescalefileio.TestClosingFileOutputStream.java
public void test(int n, boolean existingFiles) throws IOException { files = new File[n]; for (int i = 0; i < n; i++) { files[i] = File.createTempFile("closing-fos", ".dat"); }// w w w . ja va 2s . c o m allFiles.addAll(Arrays.asList(files)); ByteArrayGenerator generator = new ByteArrayGenerator(); byte[][] bytes = new byte[n][]; for (int i = 0; i < n; i++) { bytes[i] = generator.generateBytes(1024); } if (existingFiles) { for (int i = 0; i < n; i++) { writeSomeData(files[i], generator); } } ClosingFileOutputStreamFactory factory = new SimpleClosingFileOutputStreamFactory(); OutputStream[] outputs = new OutputStream[n]; for (int i = 0; i < n; i++) { outputs[i] = factory.create(files[i]); } WriterUtil.writeInterleaved(outputs, bytes); for (int i = 0; i < n; i++) { outputs[i].close(); } for (int i = 0; i < n; i++) { byte[] read = FileUtils.readFileToByteArray(files[i]); Assert.assertArrayEquals(bytes[i], read); } }
From source file:de.fabianonline.telegram_backup.ApiStorage.java
public AuthKey loadAuthKey() { if (this.auth_key != null) return this.auth_key; if (this.file_auth_key != null) { try {// w ww .jav a 2 s .co m return new AuthKey(FileUtils.readFileToByteArray(this.file_auth_key)); } catch (IOException e) { if (!(e instanceof FileNotFoundException)) e.printStackTrace(); } } return null; }
From source file:co.kuali.rice.kew.notes.service.impl.RiceAttachmentDataToS3ConversionImpl.java
@Override public void execute() { LOG.info("Starting attachment conversion job for file_data to S3"); if (!processRecords()) { return;/* w w w . j a v a 2 s . c o m*/ } final Collection<Attachment> attachments = dataObjectService.findMatching(Attachment.class, QueryByCriteria.Builder.fromPredicates(PredicateFactory.isNotNull("fileLoc"))).getResults(); attachments.forEach(attachment -> { try { final File file = new File(attachment.getFileLoc()); if (file.isFile() && file.exists()) { final byte[] fsBytes = FileUtils.readFileToByteArray(file); String fileDataId = attachment.getFileDataId(); final Object s3File; if (StringUtils.isBlank(fileDataId)) { fileDataId = UUID.randomUUID().toString(); s3File = null; } else { s3File = riceS3FileService.retrieveFile(fileDataId); } final byte[] s3Bytes; if (s3File == null) { final Class<?> s3FileClass = Class.forName(RiceAttachmentDataS3Constants.S3_FILE_CLASS); final Object newS3File = s3FileClass.newInstance(); final Method setId = s3FileClass.getMethod(RiceAttachmentDataS3Constants.SET_ID_METHOD, String.class); setId.invoke(newS3File, fileDataId); final Method setFileContents = s3FileClass.getMethod( RiceAttachmentDataS3Constants.SET_FILE_CONTENTS_METHOD, InputStream.class); try (InputStream stream = new BufferedInputStream(new ByteArrayInputStream(fsBytes))) { setFileContents.invoke(newS3File, stream); riceS3FileService.createFile(newS3File); } s3Bytes = getBytesFromS3File(riceS3FileService.retrieveFile(fileDataId)); } else { if (LOG.isDebugEnabled()) { final Method getFileMetaData = s3File.getClass() .getMethod(RiceAttachmentDataS3Constants.GET_FILE_META_DATA_METHOD); LOG.debug("data found in S3, existing id: " + fileDataId + " attachment id " + attachment.getAttachmentId() + " metadata: " + getFileMetaData.invoke(s3File)); } s3Bytes = getBytesFromS3File(s3File); } if (s3Bytes != null && fsBytes != null) { final String s3MD5 = DigestUtils.md5Hex(s3Bytes); final String dbMD5 = DigestUtils.md5Hex(fsBytes); if (!Objects.equals(s3MD5, dbMD5)) { LOG.error("S3 data MD5: " + s3MD5 + " does not equal DB data MD5: " + dbMD5 + " for id: " + fileDataId + " attachment id " + attachment.getAttachmentId()); } else { attachment.setFileDataId(fileDataId); if (isDeleteFromFileSystem()) { attachment.setFileLoc(null); } try { dataObjectService.save(attachment, PersistenceOption.FLUSH); } finally { if (isDeleteFromFileSystem()) { file.delete(); } } } } } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | IOException | ClassNotFoundException | InstantiationException e) { throw new RuntimeException(e); } }); LOG.info("Finishing attachment conversion job for file_data to S3"); }
From source file:com.talis.platform.testsupport.StubCallDefn.java
public StubCallDefn andReturn(final int status, final File entity) throws IOException { return andReturn(status, FileUtils.readFileToByteArray(entity)); }
From source file:co.kuali.rice.krad.service.impl.RiceAttachmentDataToS3ConversionImpl.java
@Override public void execute() { LOG.info("Starting attachment conversion job for file_data to S3"); if (!processRecords()) { return;/*from ww w .j a va 2 s . c o m*/ } final Collection<Attachment> attachments = dataObjectService.findAll(Attachment.class).getResults(); attachments.forEach(attachment -> { try { final File file = new File(getDocumentDirectory(attachment.getNote().getRemoteObjectIdentifier()) + File.separator + attachment.getAttachmentIdentifier()); if (file.isFile() && file.exists()) { final byte[] fsBytes = FileUtils.readFileToByteArray(file); String fileDataId = attachment.getAttachmentIdentifier(); final Object s3File = riceS3FileService.retrieveFile(fileDataId); final byte[] s3Bytes; if (s3File == null) { final Class<?> s3FileClass = Class.forName(RiceAttachmentDataS3Constants.S3_FILE_CLASS); final Object newS3File = s3FileClass.newInstance(); final Method setId = s3FileClass.getMethod(RiceAttachmentDataS3Constants.SET_ID_METHOD, String.class); setId.invoke(newS3File, fileDataId); final Method setFileContents = s3FileClass.getMethod( RiceAttachmentDataS3Constants.SET_FILE_CONTENTS_METHOD, InputStream.class); try (InputStream stream = new BufferedInputStream(new ByteArrayInputStream(fsBytes))) { setFileContents.invoke(newS3File, stream); riceS3FileService.createFile(newS3File); } s3Bytes = getBytesFromS3File(riceS3FileService.retrieveFile(fileDataId)); } else { if (LOG.isDebugEnabled()) { final Method getFileMetaData = s3File.getClass() .getMethod(RiceAttachmentDataS3Constants.GET_FILE_META_DATA_METHOD); LOG.debug("data found in S3, existing id: " + fileDataId + " note id " + attachment.getNoteIdentifier() + " metadata: " + getFileMetaData.invoke(s3File)); } s3Bytes = getBytesFromS3File(s3File); } if (s3Bytes != null && fsBytes != null) { final String s3MD5 = DigestUtils.md5Hex(s3Bytes); final String dbMD5 = DigestUtils.md5Hex(fsBytes); if (!Objects.equals(s3MD5, dbMD5)) { LOG.error("S3 data MD5: " + s3MD5 + " does not equal DB data MD5: " + dbMD5 + " for id: " + fileDataId + " note id " + attachment.getNoteIdentifier()); } else { if (isDeleteFromFileSystem()) { file.delete(); } } } } } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException | IOException | ClassNotFoundException | InstantiationException e) { throw new RuntimeException(e); } }); LOG.info("Finishing attachment conversion job for file_data to S3"); }
From source file:com.samczsun.helios.transformers.compilers.JavaCompiler.java
@Override public byte[] compile(String name, String contents) { File tmpdir = null;//from w w w. j a v a 2 s . c o m File javaFile = null; File classFile = null; File classpathFile = null; try { tmpdir = Files.createTempDirectory("javac").toFile(); javaFile = new File(tmpdir, name + ".java"); classFile = new File(tmpdir, name + ".class"); classpathFile = new File(tmpdir, "classpath.jar"); FileUtils.write(javaFile, contents, "UTF-8", false); Utils.save(classpathFile, Helios.getAllLoadedData()); StringWriter stringWriter = new StringWriter(); com.sun.tools.javac.main.Main compiler = new com.sun.tools.javac.main.Main("javac", new PrintWriter(stringWriter)); int responseCode = compiler.compile(new String[] { "-d", tmpdir.getAbsolutePath(), "-classpath", buildPath(classFile), javaFile.getAbsolutePath() }).exitCode; if (responseCode != Main.Result.OK.exitCode) { System.out.println(stringWriter.toString()); Shell shell = SWTUtil.generateLongMessage("Error", stringWriter.toString()); shell.getDisplay().syncExec(() -> { SWTUtil.center(shell); shell.open(); }); } else { return FileUtils.readFileToByteArray(classFile); } } catch (Exception e) { ExceptionHandler.handle(e); } finally { FileUtils.deleteQuietly(javaFile); FileUtils.deleteQuietly(classFile); FileUtils.deleteQuietly(classpathFile); FileUtils.deleteQuietly(tmpdir); } return null; }
From source file:gov.nih.nci.caintegrator.application.study.deployment.GenericUnparsedSupplementalFileSingleSampleHandlerTest.java
/** * Sets up the test.// ww w . jav a2 s . c om * @throws Exception on error */ @Before public void setUp() throws Exception { when(caArrayFacade.retrieveFile(any(GenomicDataSourceConfiguration.class), anyString())) .thenReturn(FileUtils.readFileToByteArray(TestDataFiles.TCGA_LEVEL_2_DATA_SINGLE_SAMPLE_FILE)); }