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.qubole.quark.fatjdbc.QuarkDriver.java

public Connection connect(String url, Properties info) throws SQLException {
    if (!acceptsURL(url)) {
        return null;
    }/*from  w w  w.ja v  a  2 s. co m*/

    final String prefix = getConnectStringPrefix();
    final String urlSuffix = url.substring(prefix.length());

    if (urlSuffix.startsWith(DB_PREFIX)) {
        info.setProperty("schemaFactory", DB_SCHEMA_FACTORY);
        final String path = urlSuffix.substring(DB_PREFIX.length());
        if (!path.isEmpty()) {
            try {
                byte[] encoded = Files.readAllBytes(Paths.get(path));
                ObjectMapper objectMapper = new ObjectMapper();
                CatalogDetail catalogDetail = objectMapper.readValue(encoded, CatalogDetail.class);
                info.setProperty("url", catalogDetail.dbCredentials.url);
                info.setProperty("user", catalogDetail.dbCredentials.username);
                info.setProperty("password", catalogDetail.dbCredentials.password);
                info.setProperty("encryptionKey", catalogDetail.dbCredentials.encryptionKey);
                info.setProperty("encrypt", catalogDetail.dbCredentials.encrypt);
            } catch (IOException e) {
                throw new SQLException(e);
            }
        }
    } else if (urlSuffix.startsWith(JSON_PREFIX)) {
        info.setProperty("schemaFactory", JSON_SCHEMA_FACTORY);
        final String path = urlSuffix.substring(JSON_PREFIX.length());
        if (!path.isEmpty()) {
            try {
                byte[] encoded = Files.readAllBytes(Paths.get(path));
                info.setProperty("model", new String(encoded, StandardCharsets.UTF_8));
            } catch (IOException e) {
                throw new SQLException(e);
            }
        }
    } else {
        throw new SQLException("URL is malformed. Specify catalog type with 'db:' or 'json:'");
    }

    return super.connect(url, info);
}

From source file:de.fatalix.bookery.bl.background.importer.CalibriImporter.java

private void processArchive(final Path zipFile, final int batchSize) throws IOException {
    try (FileSystem zipFileSystem = FileSystems.newFileSystem(zipFile, null)) {
        final List<BookEntry> bookEntries = new ArrayList<>();
        Path root = zipFileSystem.getPath("/");
        Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

            @Override/*from w w w  .  j a  v  a  2  s . c  o  m*/
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (dir.toString().contains("__MACOSX")) {
                    return FileVisitResult.SKIP_SUBTREE;
                }
                try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir)) {
                    BookEntry bookEntry = new BookEntry().setUploader("admin");
                    for (Path path : directoryStream) {
                        if (!Files.isDirectory(path)) {
                            if (path.toString().contains(".opf")) {
                                bookEntry = parseOPF(path, bookEntry);
                            }
                            if (path.toString().contains(".mobi")) {
                                bookEntry.setMobi(Files.readAllBytes(path)).setMimeType("MOBI");
                            }
                            if (path.toString().contains(".epub")) {
                                bookEntry.setEpub(Files.readAllBytes(path));
                            }
                            if (path.toString().contains(".jpg")) {
                                bookEntry.setCover(Files.readAllBytes(path));
                                ByteArrayOutputStream output = new ByteArrayOutputStream();
                                Thumbnails.of(new ByteArrayInputStream(bookEntry.getCover())).size(130, 200)
                                        .toOutputStream(output);
                                bookEntry.setThumbnail(output.toByteArray());
                                bookEntry.setThumbnailGenerated("done");
                            }
                        }
                    }
                    if (bookEntry.getMobi() != null || bookEntry.getEpub() != null) {
                        bookEntries.add(bookEntry);
                        if (bookEntries.size() > batchSize) {
                            logger.info("Adding " + bookEntries.size() + " Books...");
                            try {
                                solrHandler.addBeans(bookEntries);
                            } catch (SolrServerException ex) {
                                logger.error(ex, ex);
                            }
                            bookEntries.clear();
                        }
                    }
                } catch (IOException ex) {
                    logger.error(ex, ex);
                }
                return super.preVisitDirectory(dir, attrs);
            }
        });
        try {
            if (!bookEntries.isEmpty()) {
                logger.info("Adding " + bookEntries.size() + " Books...");
                solrHandler.addBeans(bookEntries);
            }
        } catch (SolrServerException ex) {
            logger.error(ex, ex);
        }
    } finally {
        Files.delete(zipFile);
    }
}

From source file:ddf.security.pdp.realm.xacml.processor.PollingPolicyFinderModule.java

public void onFileChange(File changedFile) {
    try {//from   w  w  w . jav  a2 s.  co m
        SecurityLogger.audit("File {} changed to:\n{}", changedFile.getCanonicalPath(), new String(
                Files.readAllBytes(Paths.get(changedFile.getCanonicalPath())), StandardCharsets.UTF_8));
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }

    reloadPolicies();
}

From source file:org.hawkular.apm.api.services.ConfigurationLoader.java

/**
 * This method loads the configuration from the supplied URI.
 *
 * @param uri The URI/*from   w  w w . j a v a  2 s  .co m*/
 * @param type The type, or null if default (jvm)
 * @return The configuration
 */
protected static CollectorConfiguration loadConfig(String uri, String type) {
    final CollectorConfiguration config = new CollectorConfiguration();

    if (type == null) {
        type = DEFAULT_TYPE;
    }

    uri += java.io.File.separator + type;

    File f = new File(uri);

    if (!f.isAbsolute()) {
        if (f.exists()) {
            uri = f.getAbsolutePath();
        } else if (System.getProperties().containsKey("jboss.server.config.dir")) {
            uri = System.getProperty("jboss.server.config.dir") + java.io.File.separatorChar + uri;
        } else {
            try {
                URL url = Thread.currentThread().getContextClassLoader().getResource(uri);
                if (url != null) {
                    uri = url.getPath();
                } else {
                    log.severe("Failed to get absolute path for uri '" + uri + "'");
                }
            } catch (Exception e) {
                log.log(Level.SEVERE, "Failed to get absolute path for uri '" + uri + "'", e);
                uri = null;
            }
        }
    }

    if (uri != null) {
        String[] uriParts = uri.split(Matcher.quoteReplacement(File.separator));
        int startIndex = 0;

        // Remove any file prefix
        if (uriParts[0].equals("file:")) {
            startIndex++;
        }

        try {
            Path path = getPath(startIndex, uriParts);

            Files.walkFileTree(path, new FileVisitor<Path>() {

                @Override
                public FileVisitResult postVisitDirectory(Path path, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs)
                        throws IOException {
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                    if (path.toString().endsWith(".json")) {
                        String json = new String(Files.readAllBytes(path));
                        CollectorConfiguration childConfig = mapper.readValue(json,
                                CollectorConfiguration.class);
                        if (childConfig != null) {
                            config.merge(childConfig, false);
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path path, IOException exc) throws IOException {
                    return FileVisitResult.CONTINUE;
                }

            });
        } catch (Throwable e) {
            log.log(Level.SEVERE, "Failed to load configuration", e);
        }
    }

    return config;
}

From source file:edu.illinois.cs.cogcomp.temporal.normalizer.main.TemporalNormalizerBenchmark.java

/**
 * Setting up TemporalChunkerAnnotator, prepare dataset
 * @param fullFolderName folder name of the dataset
 * @param useHeidelTime boolean whether use HeidelTime for normalization or not
 * @throws IOException/*  w w w .jav  a 2  s . c  om*/
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public void setUp(String fullFolderName, boolean useHeidelTime)
        throws IOException, ParserConfigurationException, SAXException {
    testText = new ArrayList<>();
    DCTs = new ArrayList<>();
    docIDs = new ArrayList<>();
    te3inputText = new ArrayList<>();

    Properties rmProps = new TemporalChunkerConfigurator().getDefaultConfig().getProperties();
    rmProps.setProperty("useHeidelTime", useHeidelTime ? "True" : "False");
    tca = new TemporalChunkerAnnotator(new ResourceManager(rmProps));

    File folder = new File(fullFolderName);
    File[] listOfFiles = folder.listFiles();
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    for (File file : listOfFiles) {
        if (file.isFile()) {
            String testFile = fullFolderName + "/" + file.getName();
            byte[] encoded = Files.readAllBytes(Paths.get(testFile));
            String fileContent = new String(encoded, StandardCharsets.UTF_8);
            te3inputText.add(fileContent);
            Document document = builder.parse(new InputSource(new StringReader(fileContent)));
            Element rootElement = document.getDocumentElement();
            NodeList nodeList = rootElement.getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node currentNode = nodeList.item(i);
                if (currentNode.getNodeName().equals("TEXT")) {
                    testText.add(currentNode.getTextContent());
                }
                if (currentNode.getNodeName().indexOf("DOCID") != -1) {
                    docIDs.add(currentNode.getTextContent());
                }
                if (currentNode.getNodeName().indexOf("DCT") != -1) {
                    Node dctNode = currentNode.getChildNodes().item(0);
                    NamedNodeMap dctAttrs = dctNode.getAttributes();
                    for (int j = 0; j < dctAttrs.getLength(); j++) {
                        if (dctAttrs.item(j).getNodeName().equals("value")) {
                            DCTs.add(dctAttrs.item(j).getNodeValue());
                        }
                    }
                }
            }
        }
    }
}

From source file:com.grillecube.common.utils.JSONHelper.java

/**
 * return a String which contains the full file bytes
 * //  ww w  . j  a  v a  2  s. c  o m
 * @throws IOException
 */
public static String readFile(File file) throws IOException {
    if (!file.exists()) {
        throw new IOException("Couldnt read file. (It doesnt exists: " + file.getPath() + ")");
    }
    if (file.isDirectory()) {
        throw new IOException("Couldnt read file. (It is a directory!!! " + file.getPath() + ")");
    }
    if (!file.canRead() && !file.setReadable(true)) {
        throw new IOException("Couldnt read model file. (Missing read permissions: " + file.getPath() + ")");
    }

    byte[] encoded = Files.readAllBytes(Paths.get(file.getPath()));
    return (new String(encoded, StandardCharsets.UTF_8));
}

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

@Test
public void modifySubmittedDocumentTest() throws IOException {
    // Arrange//from ww  w . j  a  va2s  .  c o  m
    long id = 1l;
    long docId = 1l;
    CreditCardApplicationDocumentDTO doc = new CreditCardApplicationDocumentDTO();
    doc.setId(docId);
    File ifile = new File("./src/main/resources/sample");
    Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf");
    byte[] idDocByteArray = Files.readAllBytes(idDocPath);
    MockMultipartFile idDocMultipartFile = new MockMultipartFile("IdDoc", "IdDoc.pdf", "application/pdf",
            idDocByteArray);

    Mockito.when(ccAppService.isSubmittedDocument(id)).thenReturn(true);
    Mockito.when(mockDocService.documentIsBelongToApp(id, docId)).thenReturn(true);

    // Act
    ResponseEntity<?> response = mockDocController.saveAll(new MockMultipartFile[] { idDocMultipartFile }, null,
            id, docId, request);

    // Assert
    Assert.assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode());
    Assert.assertEquals(Constants.MODIFYING_SUBMITTED_DOCUMENT, ((ErrorObject) response.getBody()).getId());
}

From source file:database.HashTablesTools.java

public static String getMD5hash(String pathToFile) throws NoSuchAlgorithmException, IOException {

    byte[] b = Files.readAllBytes(Paths.get(pathToFile));
    byte[] hash = MessageDigest.getInstance("MD5").digest(b);
    String actual = DatatypeConverter.printHexBinary(hash);
    return actual;
}

From source file:com.github.pierods.ramltoapidocconverter.RAMLToApidocConverter.java

public String getVersion(String uriString) throws IOException, URISyntaxException {

    String data;/*from w  w  w. j a  va2  s .  co m*/

    if (uriString.startsWith("http")) {

        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(uriString);
        CloseableHttpResponse response = client.execute(get);

        data = response.getEntity().toString();
    } else {
        URI uri = new URI(uriString);
        data = new String(Files.readAllBytes(Paths.get(uri.getRawPath())));
    }

    Yaml yaml = new Yaml();

    Map raml = (Map) yaml.load(new StringReader(data));

    return (String) raml.get("version");
}