Example usage for java.nio.file Files readAllBytes

List of usage examples for java.nio.file Files readAllBytes

Introduction

In this page you can find the example usage for java.nio.file Files readAllBytes.

Prototype

public static byte[] readAllBytes(Path path) throws IOException 

Source Link

Document

Reads all the bytes from a file.

Usage

From source file:com.samsung.sjs.SJSTest.java

protected String readFileIntoString(Path path) throws IOException {
    return new String(Files.readAllBytes(path));
}

From source file:femr.business.services.system.PhotoService.java

@Override
public ServiceResponse<byte[]> retrievePhotoData(int photoId) {
    ServiceResponse<byte[]> response = new ServiceResponse<>();
    try {/*ww  w.j  a  va2 s .com*/
        IPhoto photo = photoRepository.retrievePhotoById(photoId);
        if (photo != null) {
            if (!_bUseDbPhotoStorage) {
                //Read data from file and return:
                File encPhoto = new File(_encounterPhotoPath + photo.getFilePath());
                if (encPhoto.canRead()) {
                    byte[] photoData = Files.readAllBytes(Paths.get(_encounterPhotoPath + photo.getFilePath()));
                    response.setResponseObject(photoData);
                }
            } else {
                //Data is already loaded in Photo record, let's return it!
                response.setResponseObject(photo.getPhotoBlob());
            }
        }

    } catch (Exception ex) {
        response.addError("", ex.getMessage());
        return response;
    }

    return response;
}

From source file:com.ccserver.digital.controller.AdminControllerTest.java

@Test
public void downloadApplicationNullDocument() throws IOException {
    CreditCardApplicationDTO ccApp = getCreditCardApplicationDTOMock(1L);
    ccApp.setApplicationLOS(null);//from w w  w.j  ava 2  s  .c  om
    Mockito.when(ccAppService.getApplication(1L)).thenReturn(ccApp);

    File ifile = new File("./src/main/resources/sample");
    Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf");
    byte[] idDocByteArray = Files.readAllBytes(idDocPath);

    Map<String, byte[]> docs = new HashMap<String, byte[]>();
    docs.put("abc", idDocByteArray);

    Map<String, byte[]> doc = new HashMap<String, byte[]>();

    Mockito.when(docsService.getFullDocumentsByApplicationId(1L)).thenReturn(doc);

    Mockito.when(response.getOutputStream()).thenReturn(servletOutputStream);

    Mockito.when(zipFileService.zipIt(docs)).thenReturn(idDocByteArray);

    // when
    ResponseEntity<?> application = controller.downloadApplication(1L, response);

    // then
    Assert.assertEquals(HttpStatus.BAD_REQUEST, application.getStatusCode());
    Assert.assertEquals(Constants.APPLICATION_DETAIL_OBJECT_REQUIRED,
            ((ErrorObject) application.getBody()).getId());
}

From source file:org.wte4j.ui.server.services.TemplateServiceIntegrationTest.java

@Test
public void saveTemplateData() throws URISyntaxException, IOException {
    Template<TemplateDto> template = createAndPersistTestTemplate();

    TemplateDto dto = new TemplateDto();
    dto.setDocumentName(template.getDocumentName());
    dto.setLanguage(template.getLanguage());

    MappingDto mappingDto = new MappingDto();
    mappingDto.setModelKey("documentName");
    mappingDto.setContentControlKey("template");
    dto.getMapping().add(mappingDto);//www.  j  ava 2  s. c o m

    Path filePath = Paths.get(getClass().getResource("template.docx").toURI());
    templateService.saveTemplateData(dto, filePath.toString());

    Template<TemplateDto> updatedTemplate = engine.getTemplateRepository().getTemplate("test", "en",
            TemplateDto.class);
    File updatedTemplateFile = File.createTempFile("updated-template", "docx");
    updatedTemplateFile.deleteOnExit();

    updatedTemplate.write(updatedTemplateFile);
    assertTrue(Arrays.equals(Files.readAllBytes(filePath), Files.readAllBytes(updatedTemplateFile.toPath())));
}

From source file:de.alpharogroup.crypto.key.KeyExtensions.java

/**
 * Read private key./*from  w  w w .  ja  va2 s .com*/
 *
 * @param file
 *            the file
 * @return the private key
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws NoSuchAlgorithmException
 *             is thrown if instantiation of the cypher object fails.
 * @throws InvalidKeySpecException
 *             is thrown if generation of the SecretKey object fails.
 * @throws NoSuchProviderException
 *             is thrown if the specified provider is not registered in the security provider
 *             list.
 */
public static PrivateKey readPrivateKey(final File file)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final byte[] keyBytes = Files.readAllBytes(file.toPath());
    return readPrivateKey(keyBytes, "BC");
}

From source file:de.fatalix.book.importer.BookMigrator.java

private static BookEntry importBatchWise(File bookFolder, Gson gson) throws IOException {
    BookEntry bookEntry = new BookEntry();

    for (File file : bookFolder.listFiles()) {
        if (file.getName().contains(".mobi")) {
            byte[] bookData = Files.readAllBytes(file.toPath());
            bookEntry.setMobi(bookData);
        } else if (file.getName().contains(".jpg")) {
            byte[] coverData = Files.readAllBytes(file.toPath());
            bookEntry.setCover(coverData);
        } else if (file.getName().contains(".epub")) {
            byte[] bookData = Files.readAllBytes(file.toPath());
            bookEntry.setEpub(bookData);
        } else if (file.getName().contains(".json")) {
            BookMetaData bmd = gson.fromJson(
                    IOUtils.toString(new FileInputStream(file), Charset.defaultCharset()), BookMetaData.class);
            bookEntry.setAuthor(bmd.getAuthor()).setTitle(bmd.getTitle()).setIsbn(bmd.getIsbn())
                    .setPublisher(bmd.getPublisher()).setDescription(bmd.getDescription())
                    .setLanguage(bmd.getLanguage()).setMimeType(bmd.getMimeType())
                    .setUploadDate(bmd.getUploadDate()).setReleaseDate(bmd.getReleaseDate());
        } else if (file.getName().contains(".opf")) {
            bookEntry = parseOPF(file, bookEntry);

            bookEntry.setMimeType("mobi").setUploadDate(new DateTime(DateTimeZone.UTC).toDate());
        }/*from w w w .ja va 2 s  .com*/
    }

    return bookEntry;
}

From source file:com.jkoolcloud.tnt4j.streams.configure.zookeeper.ZKConfigInit.java

/**
 * Loads all bytes from provided file.//from   w w  w.j  a  va 2  s  .c  o m
 * 
 * @param cfgFileName
 *            path string of file to read data
 * @return a byte array containing the bytes read from the file, or {@code null} if path is {@code null}/empty or
 *         {@link java.io.IOException} occurs
 */
public static byte[] loadDataFromFile(String cfgFileName) {
    LOGGER.log(OpLevel.INFO,
            StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME, "ZKConfigInit.loading.cfg.data"),
            cfgFileName);

    if (StringUtils.isEmpty(cfgFileName)) {
        return null;
    }

    try {
        return Files.readAllBytes(Paths.get(cfgFileName));
    } catch (IOException exc) {
        LOGGER.log(OpLevel.ERROR, StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ZKConfigInit.loading.cfg.failed"), exc.getLocalizedMessage(), exc);
        return null;
    }
}

From source file:com.sastix.cms.server.services.content.HashedDirectoryServiceTest.java

@Test
public void testGetDataByUID() throws IOException, URISyntaxException {
    final String UURI = UUID.randomUUID().toString() + "-" + TENANT_ID + "/demo.txt";
    final String path = hashedDirectoryService.storeFile(UURI, TENANT_ID, "HELLO Data".getBytes());

    final Path content = hashedDirectoryService.getDataByUID(hashedDirectoryService.hashText(UURI), TENANT_ID);

    Assert.assertEquals(new String(Files.readAllBytes(content)), "HELLO Data");
}

From source file:org.exist.xquery.RestBinariesTest.java

/**
 * {@see https://github.com/eXist-db/exist/issues/790#error-case-5}
 *
 * response:stream-binary is used to return raw binary.
 *///from  w  w w.ja va  2 s .  com
@Test
public void readAndStreamBinaryRaw() throws IOException, JAXBException {
    final byte[] data = randomData(1024 * 1024); // 1MB
    final Path tmpInFile = createTemporaryFile(data);

    final String query = "import module namespace file = \"http://exist-db.org/xquery/file\";\n"
            + "import module namespace response = \"http://exist-db.org/xquery/response\";\n"
            + "let $bin := file:read-binary('" + tmpInFile.toAbsolutePath().toString() + "')\n"
            + "return response:stream-binary($bin, 'media-type=application/octet-stream', ())";

    final HttpResponse response = postXquery(query);

    final HttpEntity entity = response.getEntity();
    try (final FastByteArrayOutputStream baos = new FastByteArrayOutputStream()) {
        entity.writeTo(baos);

        assertArrayEquals(Files.readAllBytes(tmpInFile), baos.toByteArray());
    }
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

private static void validateEclipseCsMetaXmlFile(File file, String pkg, Set<Class<?>> pkgModules)
        throws Exception {
    Assert.assertTrue("'checkstyle-metadata.xml' must exist in eclipsecs in inside " + pkg, file.exists());

    final String input = new String(Files.readAllBytes(file.toPath()), UTF_8);
    final Document document = XmlUtil.getRawXml(file.getAbsolutePath(), input, input);

    final NodeList ruleGroups = document.getElementsByTagName("rule-group-metadata");

    Assert.assertTrue(pkg + " checkstyle-metadata.xml must contain only one rule group",
            ruleGroups.getLength() == 1);

    for (int position = 0; position < ruleGroups.getLength(); position++) {
        final Node ruleGroup = ruleGroups.item(position);
        final Set<Node> children = XmlUtil.getChildrenElements(ruleGroup);

        validateEclipseCsMetaXmlFileRules(pkg, pkgModules, children);
    }/*from  ww w. j a  v  a2s  . c o m*/

    for (Class<?> module : pkgModules) {
        Assert.fail("Module not found in " + pkg + " checkstyle-metadata.xml: " + module.getCanonicalName());
    }
}