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:example.xmlbeam.XmlBeamExampleTests.java

private static MockHttpServletRequestBuilder buildXmlPostRequestFor(String filename) throws Exception {

    Path path = Paths.get(new ClassPathResource(filename, XmlBeamExampleTests.class).getURI());

    return post("/customers").//
            content(Files.readAllBytes(path)).//
            contentType(MediaType.APPLICATION_XML);
}

From source file:io.undertow.server.handlers.form.MultipartFormDataParserTestCase.java

private static HttpHandler createHandler() {
    return new HttpHandler() {
        @Override//w  w  w .  ja  v a2  s  . c o  m
        public void handleRequest(final HttpServerExchange exchange) throws Exception {
            System.out.println("In handler");
            final FormDataParser parser = FormParserFactory.builder().build().createParser(exchange);
            System.out.println("Created parser");
            try {
                FormData data = parser.parseBlocking();
                System.out.println("done parsing");
                exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
                if (data.getFirst("formValue").getValue().equals("myValue")) {
                    FormData.FormValue file = data.getFirst("file");
                    if (file.isFile()) {
                        if (file.getPath() != null) {
                            if (new String(Files.readAllBytes(file.getPath())).startsWith("file contents")) {
                                exchange.setStatusCode(StatusCodes.OK);
                            }
                        }
                    }
                }
                exchange.endExchange();
            } catch (Throwable e) {
                e.printStackTrace();
                exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
                exchange.endExchange();
            } finally {
                IoUtils.safeClose(parser);
            }
        }
    };
}

From source file:com.shadwelldacunha.byteswipe.core.Utilities.java

public static String readFileAsString(File file) throws IOException {
    byte[] encoded = Files.readAllBytes(Paths.get(file.toURI()));
    return new String(encoded, guessEncoding(encoded));
}

From source file:com.vsct.dt.strowgr.admin.nsq.payload.PayloadTest.java

private void assertSerialization(Object message, String file) throws IOException, URISyntaxException {
    String result = mapper/*  w w  w . j a v  a  2s  .co  m*/
            .writer(new DefaultPrettyPrinter().withArrayIndenter(new DefaultPrettyPrinter.FixedSpaceIndenter()))
            .writeValueAsString(message);

    URL resource = getClass().getClassLoader().getResource(file);
    String expected = new String(Files.readAllBytes(Paths.get(resource.toURI())));
    assertEquals(expected.replaceAll("\r\n", "\n"), result.replaceAll("\r\n", "\n"));
}

From source file:iplantappssplitter.IPlantAppsSplitter.java

/**
 * ReadFile reads the file specified by filename and then returns a string
 *  with the entire contents of the file.
 * @param filename//from   w  w w. j  a  va2 s. c om
 * @return 
 */
public static String ReadFile(String filename) {
    String Json = null;
    try {
        byte[] encoded = Files.readAllBytes(Paths.get(filename));
        Json = new String(encoded);
    } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    }
    return Json;
}

From source file:ch.digitalfondue.jfiveparse.TreeConstructionTest.java

@Parameters(name = "{0}:{index}:{2}")
public static List<Object[]> data() throws IOException {
    List<Object[]> data = new ArrayList<>();
    try (DirectoryStream<Path> ds = Files
            .newDirectoryStream(Paths.get("src/test/resources/html5lib-tests/tree-construction"), "*.dat")) {
        for (Path p : ds) {
            String file = new String(Files.readAllBytes(p), StandardCharsets.UTF_8);
            String[] testsAsString = file.split("\n\n#data\n");
            for (String t : testsAsString) {
                TreeConstruction treeTest = parse(t);
                if (treeTest.scriptingFlag == null) {
                    data.add(new Object[] { p.getFileName().toString(), treeTest, false });
                    data.add(new Object[] { p.getFileName().toString(), treeTest, true });
                } else if (treeTest.scriptingFlag) {
                    data.add(new Object[] { p.getFileName().toString(), treeTest, true });
                } else {
                    data.add(new Object[] { p.getFileName().toString(), treeTest, false });
                }/*  ww w .j  a v a  2 s .  com*/
            }
        }
    }
    data.sort(new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new CompareToBuilder().append((String) o1[0], (String) o2[0])
                    .append((boolean) o1[2], (boolean) o2[2]).toComparison();
        }
    });
    return data;
}

From source file:com.mobius.software.mqtt.parser.test.StaticData.java

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

From source file:com.github.ffremont.microservices.springboot.node.tasks.InstallPropertiesTaskTest.java

@Test
public void testRun() throws Exception {
    MicroServiceTask msTask = this.create();
    MicroServiceRest ms = msTask.getMs();

    Path propSrc = Paths//w  w  w.jav  a2  s .com
            .get(Thread.currentThread().getContextClassLoader().getResource("samples.ms.properties").toURI());
    byte[] propContent = Files.readAllBytes(propSrc);
    when(msService.getContentOfProperties(eq(ms.getName()))).thenReturn(propContent);

    Path msVersionFolder = Paths.get(this.nodeBase, ms.getName(), ms.getVersion());
    ;
    Files.createDirectories(msVersionFolder);

    task.run(msTask);

    Path appProp = Paths.get(msVersionFolder.toString(), "application.properties");
    assertTrue(Files.exists(appProp));
    assertArrayEquals(propContent, Files.readAllBytes(appProp));
}

From source file:com.microsoft.azure.management.TestVirtualMachineCustomData.java

@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    final String publicIpDnsLabel = SdkContext.randomResourceName("abc", 16);

    // Prepare the custom data
    ///* w  w  w .  j  av  a 2s .c om*/
    String cloudInitFilePath = getClass().getClassLoader().getResource("cloud-init").getPath();
    cloudInitFilePath = cloudInitFilePath.replaceFirst("^/(.:/)", "$1"); // In Windows remove leading slash
    byte[] cloudInitAsBytes = Files.readAllBytes(Paths.get(cloudInitFilePath));
    byte[] cloudInitEncoded = Base64.encodeBase64(cloudInitAsBytes);
    String cloudInitEncodedString = new String(cloudInitEncoded);

    PublicIPAddress pip = pips.define(publicIpDnsLabel).withRegion(Region.US_EAST).withNewResourceGroup()
            .withLeafDomainLabel(publicIpDnsLabel).create();

    VirtualMachine vm = virtualMachines.define(vmName).withRegion(pip.regionName())
            .withExistingResourceGroup(pip.resourceGroupName()).withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic().withExistingPrimaryPublicIPAddress(pip)
            .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
            .withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!")
            .withCustomData(cloudInitEncodedString).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();

    pip.refresh();
    Assert.assertTrue(pip.hasAssignedNetworkInterface());

    if (!MockIntegrationTestBase.IS_MOCKED) {
        JSch jsch = new JSch();
        Session session = null;
        ChannelExec channel = null;
        try {
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session = jsch.getSession("testuser", publicIpDnsLabel + "." + "eastus.cloudapp.azure.com", 22);
            session.setPassword("12NewPA$$w0rd!");
            session.setConfig(config);
            session.connect();

            // Try running the package installed via init script
            //
            channel = (ChannelExec) session.openChannel("exec");
            BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            channel.setCommand("pwgen;");
            channel.connect();

            String msg;
            while ((msg = in.readLine()) != null) {
                Assert.assertFalse(msg.startsWith("The program 'pwgen' is currently not installed"));
            }
        } catch (Exception e) {
            Assert.fail("SSH connection failed" + e.getMessage());
        } finally {
            if (channel != null) {
                channel.disconnect();
            }

            if (session != null) {
                session.disconnect();
            }
        }
    }
    return vm;
}

From source file:com.enremmeta.onenow.Utils.java

public static String readFile(File f) throws IOException {
    byte[] encoded;
    encoded = Files.readAllBytes(f.toPath());
    return new String(encoded);
}