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.ccserver.digital.controller.CreditCardApplicationDocumentControllerTest.java

@Test
public void downloadDocumentByIdDocMockTest() throws IOException, URISyntaxException {
    File ifile = new File("./src/main/resources/sample");
    Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf");
    byte[] idDocByteArray = Files.readAllBytes(idDocPath);

    CreditCardApplicationDocumentThumbNailDTO CCAppDocThumbNailDTO = new CreditCardApplicationDocumentThumbNailDTO();
    CCAppDocThumbNailDTO.setId(1L);/* ww  w .j a v  a2 s.  c  o  m*/
    CCAppDocThumbNailDTO.setDocument(idDocByteArray);
    CCAppDocThumbNailDTO.setThumbNail(idDocByteArray);
    CCAppDocThumbNailDTO.setFileName("name");

    Mockito.when(mockDocService.findByCreditCardApplicationDocumentId(1L)).thenReturn(CCAppDocThumbNailDTO);
    Mockito.when(mockDocService.documentIsBelongToApp(1L, 1L)).thenReturn(true);

    ResponseEntity<?> response = mockDocController.downloadDocumentByDocId(1L, 1L);
    CreditCardApplicationDocumentThumbNailDTO result = (CreditCardApplicationDocumentThumbNailDTO) response
            .getBody();

    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

    Assert.assertTrue(result.getId() > 0);
}

From source file:org.wso2.identity.integration.test.saml.SAMLQueryProfileTestCase.java

@BeforeTest
public void initiateTenant() throws Exception {
    // Since all the requests sign with default wso2 key, upload that public key to tenants
    super.init(TestUserMode.TENANT_ADMIN);
    KeyStoreAdminClient keyStoreAdminClient = new KeyStoreAdminClient(backendURL, sessionCookie);
    String filePath = FrameworkPathUtil.getSystemResourceLocation() + "keystores" + File.separator + "products"
            + File.separator + "wso2.pem";
    byte[] crt = Files.readAllBytes(Paths.get(filePath));
    keyStoreAdminClient.importCertToStore("wso2local.pem", crt, "wso2-com.jks");
}

From source file:io.druid.segment.loading.HdfsDataSegmentPullerTest.java

@Test
public void testDir() throws IOException, SegmentLoadingException {

    final Path zipPath = new Path(perTestPath, "test.txt");

    final File outTmpDir = com.google.common.io.Files.createTempDir();
    final File outFile = new File(outTmpDir, "test.txt");
    outFile.delete();/*from www  .j  ava  2s  .c  om*/

    final URI uri = URI.create(uriBase.toString() + perTestPath.toString());

    try (final OutputStream outputStream = miniCluster.getFileSystem().create(zipPath);
            final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) {
        ByteStreams.copy(inputStream, outputStream);
    }
    try {
        Assert.assertFalse(outFile.exists());
        puller.getSegmentFiles(uri, outTmpDir);
        Assert.assertTrue(outFile.exists());

        Assert.assertArrayEquals(pathByteContents, Files.readAllBytes(outFile.toPath()));
    } finally {
        if (outFile.exists()) {
            outFile.delete();
        }
        if (outTmpDir.exists()) {
            outTmpDir.delete();
        }
    }
}

From source file:de.upb.wdqa.wdvd.test.JsonNormalizerTest.java

static String readFile(String path, Charset encoding) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(path));
    return new String(encoded, encoding);
}

From source file:io.druid.storage.hdfs.HdfsDataSegmentPullerTest.java

@Test
public void testDir() throws IOException, SegmentLoadingException {

    final Path zipPath = new Path(perTestPath, "test.txt");

    final File outTmpDir = com.google.common.io.Files.createTempDir();
    final File outFile = new File(outTmpDir, "test.txt");
    outFile.delete();/*from w w w. j av a 2 s .com*/

    final URI uri = URI.create(uriBase.toString() + perTestPath.toString());

    try (final OutputStream outputStream = miniCluster.getFileSystem().create(zipPath);
            final InputStream inputStream = new ByteArrayInputStream(pathByteContents)) {
        ByteStreams.copy(inputStream, outputStream);
    }
    try {
        Assert.assertFalse(outFile.exists());
        puller.getSegmentFiles(new Path(uri), outTmpDir);
        Assert.assertTrue(outFile.exists());

        Assert.assertArrayEquals(pathByteContents, Files.readAllBytes(outFile.toPath()));
    } finally {
        if (outFile.exists()) {
            outFile.delete();
        }
        if (outTmpDir.exists()) {
            outTmpDir.delete();
        }
    }
}

From source file:de.fenvariel.mavenfreemarker.FreemarkerPlugin.java

private String readFile(File file) throws IOException {
    byte[] bytes = Files.readAllBytes(Paths.get(file.toURI()));
    return new String(bytes);
}

From source file:com.lagrange.LabelApp.java

/**
 * Gets up to {@code maxResults} labels for an image stored at {@code path}.
 *///from w  ww  .  java 2  s .  com
public List<EntityAnnotation> labelImage(Path path, int maxResults) throws IOException {
    // [START construct_request]
    byte[] data = Files.readAllBytes(path);

    AnnotateImageRequest request = new AnnotateImageRequest().setImage(new Image().encodeContent(data))
            .setFeatures(ImmutableList.of(new Feature().setType("LABEL_DETECTION").setMaxResults(maxResults)));
    Vision.Images.Annotate annotate = vision.images()
            .annotate(new BatchAnnotateImagesRequest().setRequests(ImmutableList.of(request)));
    // Due to a bug: requests to Vision API containing large images fail when GZipped.
    annotate.setDisableGZipContent(true);
    // [END construct_request]

    // [START parse_response]
    BatchAnnotateImagesResponse batchResponse = annotate.execute();
    assert batchResponse.getResponses().size() == 1;
    AnnotateImageResponse response = batchResponse.getResponses().get(0);
    if (response.getLabelAnnotations() == null) {
        throw new IOException(response.getError() != null ? response.getError().getMessage()
                : "Unknown error getting image annotations");
    }
    return response.getLabelAnnotations();
    // [END parse_response]
}

From source file:de.tuberlin.uebb.jbop.access.ClassAccessor.java

/**
 * Return the bytes of the corresponding class.
 * // w w w  .  ja v a  2 s .c  o m
 * @param input
 *          the input Object (may be a class-Object)
 * @return the byte[] of the class
 * @throws JBOPClassException
 *           if the Classfile for the given Object cannot be accessed
 *           (e.g. if the class is synthetic)
 */
public static byte[] toBytes(final Object input) throws JBOPClassException {
    if (input == null) {
        throw new JBOPClassException("Nullvalue for input is not allowed.", null);
    }
    Path file;
    Class<?> clazz;
    if (input instanceof Class) {
        clazz = (Class<?>) input;
    } else {
        clazz = input.getClass();
    }
    file = toPath(clazz);
    final String filename = file.toString();
    if (StringUtils.contains(filename, "!")) {
        file = getPathInJar(filename);
    }
    try {
        return Files.readAllBytes(file);
    } catch (final IOException e) {
        throw new JBOPClassException("The content of the Classfile (" + filename + ") couldn't be read.", e);
    }
}

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

@Override
public ServiceResponse<byte[]> retrievePatientPhotoData(int patientId) {
    ServiceResponse<byte[]> response = new ServiceResponse<>();
    try {//from  w  w w. j av a  2 s .com
        IPatient patient = patientRepository.retrievePatientById(patientId);
        if (patient.getPhoto() == null) {
            response.setResponseObject(null);
        } else {
            if (_bUseDbPhotoStorage) {
                //BLOB Mode
                response.setResponseObject(patient.getPhoto().getPhotoBlob());
            } else {
                //File system mode
                byte[] photoData = Files
                        .readAllBytes(Paths.get(_profilePhotoPath + patient.getPhoto().getFilePath()));
                response.setResponseObject(photoData);
            }

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

From source file:com.fizzed.rocker.compiler.RockerUtil.java

static public String md5(File f) throws IOException {
    try {/*from   www  .  ja va2  s  . co  m*/
        byte[] b = Files.readAllBytes(f.toPath());
        byte[] hash = MessageDigest.getInstance("MD5").digest(b);
        return byteArrayToHex(hash);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e.getMessage(), e);
    }
}