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:io.undertow.server.handlers.accesslog.ExtendedAccessLogFileTestCase.java

private void verifySingleLogMessageToFile(Path logFileName, DefaultAccessLogReceiver logReceiver)
        throws IOException, InterruptedException {

    CompletionLatchHandler latchHandler;
    DefaultServer.setRootHandler(latchHandler = new CompletionLatchHandler(new AccessLogHandler(HELLO_HANDLER,
            logReceiver, PATTERN,/*from  w  w  w .  j a v  a2  s.c  o m*/
            new ExtendedAccessLogParser(ExtendedAccessLogFileTestCase.class.getClassLoader()).parse(PATTERN))));
    TestHttpClient client = new TestHttpClient();
    try {
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path");
        get.addHeader("test-header", "single-val");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("Hello", HttpClientUtils.readResponse(result));
        latchHandler.await();
        logReceiver.awaitWrittenForTest();
        String data = new String(Files.readAllBytes(logFileName));
        String[] lines = data.split("\n");
        Assert.assertEquals("#Fields: " + PATTERN, lines[0]);
        Assert.assertEquals("#Version: 2.0", lines[1]);
        Assert.assertEquals("#Software: " + Version.getFullVersionString(), lines[2]);
        Assert.assertEquals("", lines[3]);
        Assert.assertEquals("/path 'single-val'", lines[4]);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:io.bitgrillr.gocddockerexecplugin.DockerExecPluginTest.java

@Test
public void handleView() throws Exception {
    GoPluginApiResponse response = new DockerExecPlugin()
            .handle(new DefaultGoPluginApiRequest(null, null, "view"));

    assertEquals("Expected successful response", DefaultGoPluginApiResponse.SUCCESS_RESPONSE_CODE,
            response.responseCode());//from   w w  w .  j a  va  2 s. c o  m
    String expected = new String(
            Files.readAllBytes(Paths.get(getClass().getResource("/templates/task.template.html").toURI())));
    String actual = Json.createReader(new StringReader(response.responseBody())).readObject()
            .getString("template");
    assertEquals("HTML content doesn't match", expected, actual);
}

From source file:com.bmwcarit.barefoot.matcher.ServerTest.java

@Test
public void testServer() throws IOException, JSONException, InterruptedException, ParseException {
    Server server = new Server();
    InetAddress host = InetAddress.getLocalHost();
    Properties properties = new Properties();
    properties.load(new FileInputStream("config/server.properties"));
    int port = Integer.parseInt(properties.getProperty("server.port"));

    server.start();/*from   w ww .j  a  v  a 2  s.  c  o  m*/
    {
        String json = new String(
                Files.readAllBytes(Paths.get(ServerTest.class.getResource("x0001-015.json").getPath())),
                Charset.defaultCharset());
        sendRequest(host, port, new JSONArray(json));
    }
    server.stop();
}

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

/**
 * Read public key./*w w  w  .  j  a  va 2  s .co  m*/
 *
 * @param file
 *            the file
 * @return the public 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 PublicKey readPublicKey(final File file)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchProviderException {
    final byte[] keyBytes = Files.readAllBytes(file.toPath());
    return readPublicKey(keyBytes, "BC");
}

From source file:com.spotify.helios.cli.CliConfig.java

/**
 * Returns a CliConfig instance with values parsed from the specified file.
 *
 * If the file is not found, a CliConfig with pre-defined values will be returned.
 *
 * @param defaultsFile        The file to parse from
 * @throws IOException        If the file exists but could not be read
 * @throws URISyntaxException If a HELIOS_MASTER env var is present and doesn't parse as a URI
 *///from w  w  w  .jav a2s.c  o m
public static CliConfig fromFile(File defaultsFile) throws IOException, URISyntaxException {
    final Map<String, Object> config;
    // TODO: use typesafe config for config file parsing
    if (defaultsFile.exists() && defaultsFile.canRead()) {
        config = Json.read(Files.readAllBytes(defaultsFile.toPath()), OBJECT_TYPE);
    } else {
        config = ImmutableMap.of();
    }
    return fromEnvVar(config);
}

From source file:com.mycompany.FacebookManager.java

@Override
public void postMessageOnFacebook(String token, String fileName) throws FileNotFoundException, IOException {

    byte[] image;
    FacebookClient facebookClient = new DefaultFacebookClient(token, APP_SECRET);
    Path path = Paths.get(fileName);
    image = Files.readAllBytes(path);
    facebookClient.publish("me/photos", FacebookType.class, BinaryAttachment.with("composite.png", image),
            Parameter.with("message", blameMessage));
}

From source file:net.sourceforge.cobertura.test.ParentChildStaticFieldTest.java

@Test
public void parentChildStaticFieldShouldWorkWithoutInstrumentalizationTest() throws Exception {
    /*//from w w  w . ja  v  a2s  .c om
     * Use a temporary directory and create a few sources files.
     */
    File tempDir = TestUtils.getTempDir();
    File srcDir = new File(tempDir, "src");
    File instrumentDir = new File(tempDir, "instrument");

    File mainSourceFile = new File(srcDir, "mypackage/ParentChildStaticField.java");
    File datafile = new File(srcDir, "cobertura.ser");
    mainSourceFile.getParentFile().mkdirs();

    byte[] encoded = Files.readAllBytes(Paths.get(
            "src/test/resources/examples/basic/src/com/example/simple/ParentChildStaticFieldExample.java"));

    FileUtils.write(mainSourceFile, new String(encoded, "utf8"));

    TestUtils.compileSource(ant, srcDir);

    /*
     * Kick off the Main (instrumented) class.
     */
    Java java = new Java();
    java.setProject(TestUtils.project);
    java.setClassname("mypackage.ParentChildStaticField");
    java.setDir(srcDir);
    java.setFork(true);
    java.setFailonerror(true);
    java.setClasspath(TestUtils.getCoberturaDefaultClasspath());
    java.execute();

}

From source file:duthientan.mmanm.com.CipherRSA.java

@Override
public void decrypt(String filePath) {
    try {// w w w .j  av  a  2  s .c  o  m
        Cipher decipher = Cipher.getInstance("RSA");
        decipher.init(Cipher.DECRYPT_MODE, privateKey);
        Path path = Paths.get(filePath);
        String decryptFilePath = filePath.replace("RSA" + "_", "");
        byte[] data = Files.readAllBytes(path);
        byte[] textDncrypted = null;
        int chunkSize = 256;
        if (data.length < 256) {
            textDncrypted = decipher.doFinal(data);
        } else {
            for (int i = 0; i < data.length; i += chunkSize) {
                byte[] segment = Arrays.copyOfRange(data, i,
                        i + chunkSize > data.length ? data.length : i + chunkSize);
                byte[] segmentEncrypted = decipher.doFinal(segment);
                textDncrypted = ArrayUtils.addAll(textDncrypted, segmentEncrypted);
            }
        }
        FileOutputStream fos = new FileOutputStream(decryptFilePath);
        fos.write(textDncrypted);
        fos.close();
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:edu.ucuenca.authorsdisambiguation.Distance.java

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