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:cc.arduino.utils.network.FileDownloader.java

private void saveLocalFile() {
    try {//from www .j  av  a2  s  . c o  m
        Files.write(outputFile.toPath(), Files.readAllBytes(Paths.get(downloadUrl.getPath())));
        setStatus(Status.COMPLETE);
    } catch (Exception e) {
        setStatus(Status.ERROR);
        setError(e);
    }
}

From source file:com.mweagle.tereus.commands.CreateCommand.java

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "DM_EXIT", "OBL_UNSATISFIED_OBLIGATION" })
@SuppressWarnings("unchecked")
@Override//from   w  w w  .  j ava2  s . c  o  m
public void run() {
    int exitCode = 0;
    try {
        final String argumentJSON = (null != this.jsonParamAndTagsPath)
                ? new String(Files.readAllBytes(Paths.get(this.jsonParamAndTagsPath)), Charsets.UTF_8)
                : null;

        Map<String, Object> jsonJavaRootObject = (null != argumentJSON)
                ? new Gson().fromJson(argumentJSON, Map.class)
                : Collections.emptyMap();
        Map<String, Object> parameters = (Map<String, Object>) jsonJavaRootObject
                .getOrDefault(CONSTANTS.ARGUMENT_JSON_KEYNAMES.PARAMETERS, new HashMap<>());
        final String jsonS3BucketName = ((String) parameters
                .getOrDefault(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME, "")).trim();
        final String cliS3BucketName = (null == this.s3BucketName) ? "" : this.s3BucketName.trim();

        if (!jsonS3BucketName.isEmpty() && !cliS3BucketName.isEmpty()) {
            final String msg = String.format("S3 bucketname defined in both %s and via command line argument",
                    this.jsonParamAndTagsPath);
            throw new IllegalArgumentException(msg);
        } else if (!cliS3BucketName.isEmpty()) {
            parameters.put(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME, cliS3BucketName);
        }

        Map<String, Object> tags = (Map<String, Object>) jsonJavaRootObject
                .getOrDefault(CONSTANTS.ARGUMENT_JSON_KEYNAMES.TAGS, Collections.emptyMap());

        TereusInput tereusInput = new TereusInput(this.stackTemplatePath, this.region, parameters, tags,
                this.dryRun);

        Optional<OutputStream> osSink = Optional.empty();
        try {
            if (null != this.outputFilePath) {
                final Path outputPath = Paths.get(this.outputFilePath);
                osSink = Optional.of(new FileOutputStream(outputPath.toFile()));
            }
            this.create(tereusInput, osSink);
        } catch (Exception ex) {
            LogManager.getLogger().error(ex.getCause());
            exitCode = 2;
        } finally {
            if (osSink.isPresent()) {
                try {
                    osSink.get().close();
                } catch (Exception e) {
                    // NOP
                }
            }
        }
    } catch (Exception ex) {
        LogManager.getLogger().error(ex);
        Help.help(this.helpOption.commandMetadata);
        exitCode = 1;
    }
    System.exit(exitCode);
}

From source file:com.smartsheet.api.internal.ReportResourcesImplTest.java

@Test
public void testGetReportAsExcel() throws SmartsheetException, IOException {
    File file = new File("src/test/resources/getExcel.xls");
    server.setResponseBody(file);/*from   www. j  a v  a2s  .  c  o  m*/
    server.setContentType("application/vnd.ms-excel");

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    reportResources.getReportAsExcel(4583173393803140L, output);
    assertNotNull(output);

    assertTrue(output.toByteArray().length > 0);

    byte[] data = Files.readAllBytes(Paths.get(file.getPath()));
    assertEquals(data.length, output.toByteArray().length);
}

From source file:com.ibm.liberty.starter.unit.GitHubWriterTest.java

private void assertFileExistsWithContent(String pathToFile, byte[] expectedContents, File localGitRepo)
        throws IOException {
    File rootFile = new File(localGitRepo, pathToFile);
    assertThat(rootFile, is(anExistingFile()));
    assertThat(Files.readAllBytes(rootFile.toPath()), is(expectedContents));
}

From source file:com.yahoo.yqlplus.engine.tools.YQLPlusRun.java

@SuppressWarnings("unchecked")
public int run(CommandLine command) throws Exception {
    String script = null;/*from w  w  w .j  av a  2s . co  m*/
    String filename = null;
    if (command.hasOption("command")) {
        script = command.getOptionValue("command");
        filename = "<command line>";
    }
    List<String> scriptAndArgs = (List<String>) command.getArgList();
    if (filename == null && scriptAndArgs.size() < 1) {
        System.err.println("No script specified.");
        return -1;
    } else if (script == null) {
        filename = scriptAndArgs.get(0);
        Path scriptPath = Paths.get(filename);
        if (!Files.isRegularFile(scriptPath)) {
            System.err.println(scriptPath + " is not a file.");
            return -1;
        }
        script = Charsets.UTF_8.decode(ByteBuffer.wrap(Files.readAllBytes(scriptPath))).toString();
    }
    List<String> paths = Lists.newArrayList();
    if (command.hasOption("path")) {
        paths.addAll(Arrays.asList(command.getOptionValues("path")));
    }
    // TODO: this isn't going to be very interesting without some sources
    Injector injector = Guice.createInjector(new JavaEngineModule());
    YQLPlusCompiler compiler = injector.getInstance(YQLPlusCompiler.class);
    CompiledProgram program = compiler.compile(script);
    if (command.hasOption("source")) {
        program.dump(System.out);
        return 0;
    }
    // TODO: read command line arguments to pass to program
    ExecutorService outputThreads = Executors.newSingleThreadExecutor();
    ProgramResult result = program.run(Maps.<String, Object>newHashMap(), true);
    for (String name : result.getResultNames()) {
        final ListenableFuture<YQLResultSet> future = result.getResult(name);
        future.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    YQLResultSet resultSet = future.get();
                    System.out.println(new String((byte[]) resultSet.getResult()));
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }

            }
        }, outputThreads);
    }
    Future<TraceRequest> done = result.getEnd();
    try {
        done.get(10000L, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    } catch (ExecutionException | TimeoutException e) {
        e.printStackTrace();
    }
    outputThreads.awaitTermination(1L, TimeUnit.SECONDS);
    return 0;
}

From source file:SdkUnitTests.java

@Test
public void RequestASignatureTest() {

    byte[] fileBytes = null;
    try {//from ww  w.  j  a  v  a 2 s  . c  om
        //  String currentDir = new java.io.File(".").getCononicalPath();

        String currentDir = System.getProperty("user.dir");

        Path path = Paths.get(currentDir + SignTest1File);
        fileBytes = Files.readAllBytes(path);
    } catch (IOException ioExcp) {
        Assert.assertEquals(null, ioExcp);
    }

    // create an envelope to be signed
    EnvelopeDefinition envDef = new EnvelopeDefinition();
    envDef.setEmailSubject("Please Sign my Java SDK Envelope");
    envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");

    // add a document to the envelope
    Document doc = new Document();
    String base64Doc = Base64.getEncoder().encodeToString(fileBytes);
    doc.setDocumentBase64(base64Doc);
    doc.setName("TestFile.pdf");
    doc.setDocumentId("1");

    List<Document> docs = new ArrayList<Document>();
    docs.add(doc);
    envDef.setDocuments(docs);

    // Add a recipient to sign the document
    Signer signer = new Signer();
    signer.setEmail(UserName);
    signer.setName("Pat Developer");
    signer.setRecipientId("1");

    // Create a SignHere tab somewhere on the document for the signer to sign
    SignHere signHere = new SignHere();
    signHere.setDocumentId("1");
    signHere.setPageNumber("1");
    signHere.setRecipientId("1");
    signHere.setXPosition("100");
    signHere.setYPosition("100");

    List<SignHere> signHereTabs = new ArrayList<SignHere>();
    signHereTabs.add(signHere);
    Tabs tabs = new Tabs();
    tabs.setSignHereTabs(signHereTabs);
    signer.setTabs(tabs);

    // Above causes issue
    envDef.setRecipients(new Recipients());
    envDef.getRecipients().setSigners(new ArrayList<Signer>());
    envDef.getRecipients().getSigners().add(signer);

    // send the envelope (otherwise it will be "created" in the Draft folder
    envDef.setStatus("sent");

    try {

        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath(BaseUrl);

        String creds = createAuthHeaderCreds(UserName, Password, IntegratorKey);
        apiClient.addDefaultHeader("X-DocuSign-Authentication", creds);
        Configuration.setDefaultApiClient(apiClient);

        AuthenticationApi authApi = new AuthenticationApi();

        AuthenticationApi.LoginOptions loginOptions = authApi.new LoginOptions();
        loginOptions.setApiPassword("true");
        loginOptions.setIncludeAccountIdGuid("true");
        LoginInformation loginInfo = authApi.login(loginOptions);

        Assert.assertNotNull(loginInfo);
        Assert.assertNotNull(loginInfo.getLoginAccounts());
        Assert.assertTrue(loginInfo.getLoginAccounts().size() > 0);
        List<LoginAccount> loginAccounts = loginInfo.getLoginAccounts();
        Assert.assertNotNull(loginAccounts.get(0).getAccountId());

        String accountId = loginInfo.getLoginAccounts().get(0).getAccountId();

        EnvelopesApi envelopesApi = new EnvelopesApi();

        EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);

        Assert.assertNotNull(envelopeSummary);
        Assert.assertNotNull(envelopeSummary.getEnvelopeId());
        Assert.assertEquals("sent", envelopeSummary.getStatus());

        System.out.println("EnvelopeSummary: " + envelopeSummary);

    } catch (ApiException ex) {
        System.out.println("Exception: " + ex);
        Assert.assertEquals(null, ex);
    }
}

From source file:io.github.swagger2markup.extensions.DynamicDocumentExtensionTest.java

@Test
public void testSwagger2MarkdownExtensions() throws IOException, URISyntaxException {
    //Given/*from   w ww  . j a  v  a 2 s. c om*/
    Path file = Paths
            .get(DynamicDocumentExtensionTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/markdown/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Properties properties = new Properties();
    properties
            .load(DynamicDocumentExtensionTest.class.getResourceAsStream("/config/markdown/config.properties"));
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder(properties)
            .withMarkupLanguage(MarkupLanguage.MARKDOWN).build();
    Swagger2MarkupExtensionRegistry registry = new Swagger2MarkupExtensionRegistryBuilder()
            //.withDefinitionsDocumentExtension(new DynamicDefinitionsDocumentExtension(Paths.get("src/test/resources/docs/markdown/extensions")))
            //.withPathsDocumentExtension(new DynamicPathsDocumentExtension(Paths.get("src/test/resources/docs/markdown/extensions")))
            .build();
    Swagger2MarkupConverter.from(file).withConfig(config).withExtensionRegistry(registry).build()
            .toFolder(outputDirectory);

    //Then
    assertThat(new String(Files.readAllBytes(outputDirectory.resolve("paths.md"))))
            .contains("Pet update request extension");
    assertThat(new String(Files.readAllBytes(outputDirectory.resolve("definitions.md"))))
            .contains("Pet extension");

}

From source file:com.spectralogic.ds3client.helpers.FileObjectGetter_Test.java

@Test
public void testThatSymbolicLinksAreResolved() {
    Assume.assumeFalse(Platform.isWindows());
    final String message = "Hello World";
    final String file = "file.txt";
    try {//from   w  ww  .jav a  2 s.  co m
        final Path tempDirectory = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")),
                "ds3");
        final Path realDirectory = Files.createDirectory(Paths.get(tempDirectory.toString(), "dir"));
        final Path symbolicDirectory = Paths.get(tempDirectory.toString(), "symbolic");
        Files.createSymbolicLink(symbolicDirectory, realDirectory);
        Files.createFile(Paths.get(realDirectory.toString(), file));
        final ByteBuffer bb = ByteBuffer.wrap(message.getBytes());

        final SeekableByteChannel getterChannel = new FileObjectGetter(symbolicDirectory).buildChannel(file);
        getterChannel.write(bb);
        getterChannel.close();
        final String content = new String(Files.readAllBytes(Paths.get(realDirectory.toString(), file)));
        assertTrue(message.equals(content));
    } catch (final IOException e) {
        fail("Symbolic links are not handled correctly");
    }
}

From source file:com.diffplug.gradle.pde.CopyJarsUsingProductFile.java

@TaskAction
public void action() throws IOException {
    Objects.requireNonNull(explicitVersionPolicy, "Set explicitVersionPolicy");
    Objects.requireNonNull(destination, "Set destination");
    Preconditions.checkArgument(!inputFolders.isEmpty(), "Input folders should not be empty");

    FileMisc.cleanDir(destination);/* w w w  .  j a  va 2s . com*/

    PluginCatalog catalog = new PluginCatalog(explicitVersionPolicy.getResult(), SwtPlatform.getAll(),
            inputFolders);
    String inputStr = new String(Files.readAllBytes(productFile.toPath()), StandardCharsets.UTF_8);
    String[] lines = FileMisc.toUnixNewline(inputStr).split("\n");
    for (String line : lines) {
        ProductFileUtil.parsePlugin(line).ifPresent(plugin -> copyVersionsOfPlugin(catalog, plugin));
    }
    extras.forEach(plugin -> copyVersionsOfPlugin(catalog, plugin));
}

From source file:com.eriwen.gradle.Digest.java

private String digest(final File file, final DigestAlgorithm algorithm) throws IOException {
    final byte[] contentBytes = Files.readAllBytes(file.toPath());
    final String checksum;
    switch (algorithm) {
    case MD5:/*from   w  ww.  ja  va  2 s . c om*/
        checksum = DigestUtils.md5Hex(contentBytes);
        break;
    case SHA1:
        checksum = DigestUtils.sha1Hex(contentBytes);
        break;
    case SHA256:
        checksum = DigestUtils.sha256Hex(contentBytes);
        break;
    case SHA512:
        checksum = DigestUtils.sha512Hex(contentBytes);
        break;
    default:
        throw new IllegalArgumentException("Cannot use unknown digest algorithm " + algorithm.toString());
    }
    return checksum;
}