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.hortonworks.streamline.storage.tool.SQLScriptRunner.java

public void runScript(String path) throws Exception {
    String delimiter = storageProperties.getDelimiter();

    final File file = new File(path);
    if (!file.exists()) {
        throw new RuntimeException("File not found for given path " + path);
    }/*from  w  w w  .  j a v a2s .com*/

    String content = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())), StandardCharsets.UTF_8);

    try (Connection connection = connect()) {
        connection.setAutoCommit(true);

        String[] queries = content.split(delimiter);
        for (String query : queries) {
            query = query.trim();
            if (!query.isEmpty()) {
                System.out.println(String.format("######## SQL Query:  %s ", query));
                connection.createStatement().execute(query);
                System.out.println("######## Query executed");
            }
        }
    }
}

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

@Test
public void save() throws IOException {
    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);//www. j  a v a  2  s .  c om
    ResponseEntity<?> fileUploadResponse = mockDocController.saveAll(
            new MockMultipartFile[] { idDocMultipartFile }, new String[] { "front" }, Long.valueOf(1),
            Long.valueOf(1), request);

    Assert.assertNotNull(fileUploadResponse);
}

From source file:com.heliosdecompiler.helios.controller.files.OpenedFile.java

private void readQuick() {
    byte[] fileData;

    try {// ww  w .  j  a v  a  2s  . com
        fileData = Files.readAllBytes(this.target);
    } catch (IOException e) {
        this.messageHandler.handleException(Message.ERROR_IOEXCEPTION_OCCURRED.format(), e);
        return;
    }

    this.fileContents.clear();
    this.fileContents = new HashMap<>();

    try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(fileData))) {
        ZipEntry entry;
        while ((entry = zipInputStream.getNextEntry()) != null) {
            // todo warn about CRC
            if (!entry.isDirectory()) {
                this.fileContents.put(entry.getName(), IOUtils.toByteArray(zipInputStream));
            }
        }
    } catch (Exception ex) {
        this.messageHandler.handleException(Message.ERROR_UNKNOWN_ERROR.format(), ex);
        return;
    }

    // If files is still empty, then it's not a zip file (or something weird happened)
    if (this.fileContents.size() == 0) {
        this.fileContents.put(this.target.toString(), fileData);
    }
}

From source file:org.segator.plex.cloud.transcoding.scheduled.MachineImageBuilder.java

@Scheduled(fixedDelay = 5000)
public synchronized void imageChecking() throws UnsupportedEncodingException, DigitalOceanException,
        RequestUnsuccessfulException, IOException, RemoteException, InterruptedException {
    if (!existImage) {
        //Exist the required Image?
        Images images = applicationParameters.getDOClient().getAvailableImages(0, 1000);
        Image baseImage = null;/*from www . j av  a2 s  .  c om*/
        for (Image image : images.getImages()) {
            if (image.getRegions().contains(applicationParameters.getDORegion())) {
                if (TranscoderConstants.DROPLET_IMAGE_PLEX_REMOTE_TRANSCODING.equals(image.getName())) {
                    applicationParameters.setDOImageID(image.getId().toString());
                    existImage = true;
                    machineBuild = null;
                    return;
                } else if (TranscoderConstants.DROPLET_BASE_BUILD_SLUG.equals(image.getSlug())) {
                    baseImage = image;
                }
            }
        }
        if (machineBuild == null) {
            Droplet buildDroplet = applicationParameters
                    .getBasicDroplet(TranscoderConstants.DROPLET_IMAGE_PLEX_REMOTE_TRANSCODING + "Build");
            buildDroplet.setImage(baseImage);
            File provisioningDigitalOcean = new File(TranscoderConstants.DROPLET_PROVISION_FILE_NAME);
            String provisionTemplate = new String(
                    Files.readAllBytes(Paths.get(provisioningDigitalOcean.getAbsolutePath())), "UTF-8");
            String provisionFile = applicationParameters.parseScriptTemplate(provisionTemplate);
            buildDroplet.setUserData(provisionFile);
            Droplet builderDropletImage = applicationParameters.getDOClient().createDroplet(buildDroplet);
            machineBuild = new TranscoderMachine(builderDropletImage.getId(), builderDropletImage.getName());
            machineBuild.setDroplet(builderDropletImage);
            storerMachine.getTranscoderMachines().add(machineBuild);
        } else if (machineBuild.isReadyToSnapshot()) {
            //Power Of builder machine
            waitForActionComplete(
                    applicationParameters.getDOClient().powerOffDroplet(machineBuild.getMachineID()));
            //Take Snapshot
            waitForActionComplete(applicationParameters.getDOClient().takeDropletSnapshot(
                    machineBuild.getMachineID(), TranscoderConstants.DROPLET_IMAGE_PLEX_REMOTE_TRANSCODING));
            //Destroy machine
            Delete delete = applicationParameters.getDOClient().deleteDroplet(machineBuild.getMachineID());
        }

    }
}

From source file:com.netscape.cmstools.pkcs7.PKCS7CertExportCLI.java

public void execute(String[] args) throws Exception {

    CommandLine cmd = parser.parse(options, args, true);

    if (cmd.hasOption("help")) {
        printHelp();//  w w w.ja v  a  2 s  .  c o m
        return;
    }

    if (cmd.hasOption("verbose")) {
        PKILogger.setLevel(PKILogger.Level.INFO);

    } else if (cmd.hasOption("debug")) {
        PKILogger.setLevel(PKILogger.Level.DEBUG);
    }

    String filename = cmd.getOptionValue("pkcs7-file");

    if (filename == null) {
        throw new Exception("Missing PKCS #7 file.");
    }

    logger.info("Loading PKCS #7 data from " + filename);
    String str = new String(Files.readAllBytes(Paths.get(filename))).trim();
    PKCS7 pkcs7 = new PKCS7(str);

    X509Certificate[] certs = pkcs7.getCertificates();
    if (certs == null || certs.length == 0) {
        System.out.println("PKCS #7 data contains no certificates");
        return;
    }

    // sort certs from root to leaf
    certs = CryptoUtil.sortCertificateChain(certs);

    String prefix = cmd.getOptionValue("output-prefix", filename + "-");
    String suffix = cmd.getOptionValue("output-suffix", "");
    int i = 0;

    for (X509Certificate cert : certs) {

        logger.info("Exporting certificate #" + i + ": " + cert.getSubjectDN());

        String output = prefix + i + suffix;

        try (PrintWriter out = new PrintWriter(new FileWriter(output))) {
            out.println(Cert.HEADER);
            out.print(Utils.base64encode(cert.getEncoded(), true));
            out.println(Cert.FOOTER);
        }

        System.out.println(output + ": " + cert.getSubjectDN());

        i++;
    }
}

From source file:io.github.zlika.reproducible.ZipStripper.java

@Override
public void strip(File in, File out) throws IOException {
    try (final ZipFile zip = new ZipFile(in);
            final ZipArchiveOutputStream zout = new ZipArchiveOutputStream(out)) {
        final List<String> sortedNames = sortEntriesByName(zip.getEntries());
        for (String name : sortedNames) {
            final ZipArchiveEntry entry = zip.getEntry(name);
            // Strip Zip entry
            final ZipArchiveEntry strippedEntry = filterZipEntry(entry);
            // Strip file if required
            final Stripper stripper = getSubFilter(name);
            if (stripper != null) {
                // Unzip entry to temp file
                final File tmp = File.createTempFile("tmp", null);
                tmp.deleteOnExit();/*from w w  w.ja v  a2s . c  o  m*/
                Files.copy(zip.getInputStream(entry), tmp.toPath(), StandardCopyOption.REPLACE_EXISTING);
                final File tmp2 = File.createTempFile("tmp", null);
                tmp2.deleteOnExit();
                stripper.strip(tmp, tmp2);
                final byte[] fileContent = Files.readAllBytes(tmp2.toPath());
                strippedEntry.setSize(fileContent.length);
                zout.putArchiveEntry(strippedEntry);
                zout.write(fileContent);
                zout.closeArchiveEntry();
            } else {
                // Copy the Zip entry as-is
                zout.addRawArchiveEntry(strippedEntry, getRawInputStream(zip, entry));
            }
        }
    }
}

From source file:fi.vm.kapa.identification.adapter.service.AdapterPropertyMapper.java

@PostConstruct
public void initAdapterUtils() {
    try {//ww w  . ja v a 2  s  .  c o m
        /* The session attribute map has the following syntax:
         * [External-IdP-attribute-key];[SP-attribute-key]
         */
        this.sessionAttributeMap.putAll(getMapFromFromCsvFile(adapterMapFile,
                CSVFormat.DEFAULT.withDelimiter(';').withCommentMarker('#')));

        // Tupas properties contains each bank specific values and attributes
        this.tupasProperties.putAll(getMapFromFromCsvFile(tupasPropertiesFile,
                CSVFormat.DEFAULT.withDelimiter(';').withCommentMarker('#')));
        tupasFormTemplate = new String(Files.readAllBytes(Paths.get(tupasRequestFormTemplate)), "UTF-8");
    } catch (Exception e) {
        logger.error("Error initializing session parser", e);
    }
}

From source file:de.alpharogroup.crypto.key.reader.PrivateKeyReader.java

/**
 * Read private key./*from  w  w w .java 2 s. co  m*/
 *
 * @param file
 *            the file
 * @param provider
 *            the security provider
 * @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, final String provider)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final byte[] keyBytes = Files.readAllBytes(file.toPath());
    return readPrivateKey(keyBytes, provider);
}

From source file:org.lecture.unit.tutorial.controller.TutorialControllerUnitTest.java

@Test
public void patchShouldPatchADocumentWithNewContent() throws Exception {
    String original = new String(Files.readAllBytes(Paths.get(getClass().getResource("/original.md").toURI())));

    Tutorial instance = new Tutorial();
    instance.setId("1");
    instance.setContent(original);// www. j  a v  a 2s . c o  m
    instance.setFormat("MARKDOWN");
    TutorialResource testResource = new TutorialResource(instance);
    when(tutorialRepository.findOne("1")).thenReturn(instance);

    String modified = new String(Files.readAllBytes(Paths.get(getClass().getResource("/modified.md").toURI())));
    String patch = new DmpPatchService().createPatch(original, modified);
    ResponseEntity<?> response = testInstance.update("1", patch);

    assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());

    assertEquals(instance.getContent(), modified);

}

From source file:net.kemitix.checkstyle.ruleset.builder.CheckstyleWriter.java

private void writeCheckstyleFile(@NonNull final RuleLevel ruleLevel) {
    val xmlFile = outputProperties.getDirectory().resolve(outputProperties.getRulesetFiles().get(ruleLevel));
    val checkerRules = rulesProperties.getRules().stream().filter(Rule::isEnabled)
            .filter(rule -> RuleParent.CHECKER.equals(rule.getParent()))
            .filter(rule -> ruleLevel.compareTo(rule.getLevel()) >= 0).map(this::formatRuleAsModule)
            .collect(Collectors.joining(NEWLINE));
    val treeWalkerRules = rulesProperties.getRules().stream().filter(Rule::isEnabled)
            .filter(rule -> RuleParent.TREEWALKER.equals(rule.getParent()))
            .filter(rule -> ruleLevel.compareTo(rule.getLevel()) >= 0).map(this::formatRuleAsModule)
            .collect(Collectors.joining(NEWLINE));
    try {//from w w  w. j  ava  2s.c  om
        val checkstyleXmlTemplate = templateProperties.getCheckstyleXml();
        if (checkstyleXmlTemplate.toFile().exists()) {
            val bytes = Files.readAllBytes(checkstyleXmlTemplate);
            val template = new String(bytes, StandardCharsets.UTF_8);
            val output = Arrays.asList(String.format(template, checkerRules, treeWalkerRules).split(NEWLINE));
            log.info("Writing xmlFile: {}", xmlFile);
            Files.write(xmlFile, output, StandardCharsets.UTF_8);
        } else {
            throw new IOException("Missing template: " + checkstyleXmlTemplate.toString());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}