Java Code Examples for java.nio.file.Files#readAllBytes()

The following examples show how to use java.nio.file.Files#readAllBytes() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Test
public void testCamelCdiEarContextInjection() throws Exception {
    Set<CamelContext> camelContexts = contextRegistry.getCamelContexts();
    Assert.assertEquals("Expected 1 CamelContext to be present in CamelContextRegistry", camelContexts.size(), 1);

    // Verify the CamelContext ApplicationContextClassLoader is as expected
    CamelContext camelctx = camelContexts.iterator().next();
    String moduleName = TestUtils.getClassLoaderModuleName(camelctx.getApplicationContextClassLoader());
    Assert.assertEquals("deployment.context-inject.ear", moduleName);

    // Verify that each WAR sub deployment each had the same CamelContext injected
    Path dataDir = Paths.get(System.getProperty("jboss.server.data.dir"));

    String moduleNameA = new String(Files.readAllBytes(dataDir.resolve("injected-context-a.txt")), StandardCharsets.UTF_8);
    Assert.assertEquals("deployment.context-inject.ear", moduleNameA);

    String moduleNameB = new String(Files.readAllBytes(dataDir.resolve("injected-context-b.txt")), StandardCharsets.UTF_8);
    Assert.assertEquals("deployment.context-inject.ear", moduleNameB);
}
 
Example 2
Source Project: JavaSteam   File: KeyValueTest.java    License: MIT License 6 votes vote down vote up
@Test
public void keyValuesSavesTextToFile() throws IOException {
    String expected = "\"RootNode\"\n{\n\t\"key1\"\t\t\"value1\"\n\t\"key2\"\n\t{\n\t\t\"ChildKey\"\t\t\"ChildValue\"\n\t}\n}\n";

    KeyValue kv = new KeyValue("RootNode");
    KeyValue kv2 = new KeyValue("key2");
    kv2.getChildren().add(new KeyValue("ChildKey", "ChildValue"));

    kv.getChildren().add(new KeyValue("key1", "value1"));
    kv.getChildren().add(kv2);

    String text;
    File temporaryFile = folder.newFile();
    kv.saveToFile(temporaryFile, false );
    text = new String(Files.readAllBytes(Paths.get(temporaryFile.getPath())));

    assertEquals(expected, text);
}
 
Example 3
Source Project: AVM   File: InterfaceFieldIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Test
public void FIELDSAsInnerInterfaceName() throws IOException {
    byte[] jar = JarBuilder.buildJarForMainClassAndExplicitClassNamesAndBytecode(ClassWithFIELDSAsInterfaceName.class, Collections.emptyMap(), InnerFIELDSInterface.class, ABIEncoder.class, ABIException.class, InnerFIELDSImplementation.class);
    byte[] txData = new CodeAndArguments(jar, new byte[0]).encodeToBytes();
    AionAddress dappAddress = deploy(deployer, kernel, txData);

    byte[] objectGraph = Files.readAllBytes(Paths.get("test/resources/ClassWithFIELDSAsInterfaceNameObjectGraph"));
    kernel.putObjectGraph(dappAddress, objectGraph);
    //re-transform the code
    kernel.setTransformedCode(dappAddress, null);

    TransactionResult result = callDapp(kernel, deployer, dappAddress, "",
            ExecutionType.ASSUME_MAINCHAIN, kernel.getBlockNumber() - 1);
    // number of processed classes will be different
    Assert.assertTrue(result.transactionStatus.isFailed());
}
 
Example 4
Source Project: nifi   File: TestJoltTransformJSON.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTransformInputWithRemovr() throws IOException {
    final TestRunner runner = TestRunners.newTestRunner(new JoltTransformJSON());
    final String spec = new String(Files.readAllBytes(Paths.get("src/test/resources/TestJoltTransformJson/removrSpec.json")));
    runner.setProperty(JoltTransformJSON.JOLT_SPEC, spec);
    runner.setProperty(JoltTransformJSON.JOLT_TRANSFORM, JoltTransformJSON.REMOVR);
    runner.enqueue(JSON_INPUT);
    runner.run();
    runner.assertAllFlowFilesTransferred(JoltTransformJSON.REL_SUCCESS);
    final MockFlowFile transformed = runner.getFlowFilesForRelationship(JoltTransformJSON.REL_SUCCESS).get(0);
    Object transformedJson = JsonUtils.jsonToObject(new ByteArrayInputStream(transformed.toByteArray()));
    Object compareJson = JsonUtils.jsonToObject(Files.newInputStream(Paths.get("src/test/resources/TestJoltTransformJson/removrOutput.json")));
    assertTrue(DIFFY.diff(compareJson, transformedJson).isEmpty());
}
 
Example 5
Source Project: athenz   File: CryptoTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractX509CSRFieldsURIDouble() throws IOException {

    Path path = Paths.get("src/test/resources/valid_multiple_uri.csr");
    String csr = new String(Files.readAllBytes(path));
    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(csr);
    assertNotNull(certReq);

    List<String> uris = Crypto.extractX509CSRURIs(certReq);
    assertEquals(2, uris.size());
    assertEquals(uris.get(0), "spiffe://athenz/domain1/service1");
    assertEquals(uris.get(1), "spiffe://athenz/domain1/service2");
}
 
Example 6
Source Project: json-snapshot.github.io   File: SnapshotFile.java    License: MIT License 5 votes vote down vote up
private void loadSnapshotFile() throws IOException {

    Path path = Paths.get(this.pathAndfileName);

    String lines = new String(Files.readAllBytes(path), UTF_8);
    String[] rawSnapshotItems = split(lines);

    Stream.of(rawSnapshotItems)
        .filter(StringUtils::isNotBlank)
        .map(SnapshotDataItem::new)
        .forEach(storedSnapshots::add);
  }
 
Example 7
Source Project: nifi   File: TestUpdateRecord.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFieldValuesInEL() throws InitializationException, IOException {
    final JsonTreeReader jsonReader = new JsonTreeReader();
    runner.addControllerService("reader", jsonReader);

    final String inputSchemaText = new String(Files.readAllBytes(Paths.get("src/test/resources/TestUpdateRecord/schema/person-with-name-record.avsc")));
    final String outputSchemaText = new String(Files.readAllBytes(Paths.get("src/test/resources/TestUpdateRecord/schema/person-with-name-record.avsc")));

    runner.setProperty(jsonReader, SchemaAccessUtils.SCHEMA_ACCESS_STRATEGY, SchemaAccessUtils.SCHEMA_TEXT_PROPERTY);
    runner.setProperty(jsonReader, SchemaAccessUtils.SCHEMA_TEXT, inputSchemaText);
    runner.enableControllerService(jsonReader);

    final JsonRecordSetWriter jsonWriter = new JsonRecordSetWriter();
    runner.addControllerService("writer", jsonWriter);
    runner.setProperty(jsonWriter, SchemaAccessUtils.SCHEMA_ACCESS_STRATEGY, SchemaAccessUtils.SCHEMA_TEXT_PROPERTY);
    runner.setProperty(jsonWriter, SchemaAccessUtils.SCHEMA_TEXT, outputSchemaText);
    runner.setProperty(jsonWriter, "Pretty Print JSON", "true");
    runner.setProperty(jsonWriter, "Schema Write Strategy", "full-schema-attribute");
    runner.enableControllerService(jsonWriter);

    runner.enqueue(Paths.get("src/test/resources/TestUpdateRecord/input/person.json"));
    runner.setProperty("/name/last", "${field.value:toUpper()}");
    runner.setProperty(UpdateRecord.REPLACEMENT_VALUE_STRATEGY, UpdateRecord.LITERAL_VALUES);

    runner.run();
    runner.assertAllFlowFilesTransferred(UpdateRecord.REL_SUCCESS, 1);
    final String expectedOutput = new String(Files.readAllBytes(Paths.get("src/test/resources/TestUpdateRecord/output/person-with-capital-lastname.json")));
    runner.getFlowFilesForRelationship(UpdateRecord.REL_SUCCESS).get(0).assertContentEquals(expectedOutput);
}
 
Example 8
@Override
public String getFileContents() throws Exception {
   if (AuditLogger.isEnabled()) {
      AuditLogger.getFileContents(this.getBroadcastGroup());
   }
   URL resource = this.getClass().getClassLoader().getResource(this.getFile());
   File file = new File(resource.getFile());
   return new String(Files.readAllBytes(Paths.get(file.getPath())));
}
 
Example 9
Source Project: dcos-commons   File: CosmosRenderer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the content of the specified file, or throws an {@link IllegalArgumentException} if the file couldn't be
 * accessed.
 */
private static String readFile(String path) {
  try {
    return new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);
  } catch (IOException e) {
    throw new IllegalArgumentException(String.format(
        "Failed to access file at %s (relative to pwd=%s)", path, System.getProperty("user.dir")), e);
  }
}
 
Example 10
/**
 * Linux specific test to exercise Files.readAllBytes on /proc. This is
 * special because file sizes are reported as 0 even though the file
 * has content.
 */
public void testReadAllBytesOnProcFS() throws IOException {
    // read from procfs
    if (System.getProperty("os.name").equals("Linux")) {
        Path statFile = Paths.get("/proc/self/stat");
        byte[] data = Files.readAllBytes(statFile);
        assertTrue(data.length > 0, "Files.readAllBytes('" + statFile + "') failed to read");
    }
}
 
Example 11
Source Project: nifi   File: TestJoltTransformJSON.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testTransformInputWithDefaultrExpressionLanguage() throws IOException {
    final TestRunner runner = TestRunners.newTestRunner(new JoltTransformJSON());
    final String spec = new String(Files.readAllBytes(Paths.get("src/test/resources/TestJoltTransformJson/defaultrELSpec.json")));
    runner.setProperty(JoltTransformJSON.JOLT_SPEC, spec);
    runner.setProperty(JoltTransformJSON.JOLT_TRANSFORM, JoltTransformJSON.DEFAULTR);
    runner.setVariable("quota","5");
    runner.enqueue(JSON_INPUT);
    runner.run();
    runner.assertAllFlowFilesTransferred(JoltTransformJSON.REL_SUCCESS);
    final MockFlowFile transformed = runner.getFlowFilesForRelationship(JoltTransformJSON.REL_SUCCESS).get(0);
    Object transformedJson = JsonUtils.jsonToObject(new ByteArrayInputStream(transformed.toByteArray()));
    Object compareJson = JsonUtils.jsonToObject(Files.newInputStream(Paths.get("src/test/resources/TestJoltTransformJson/defaultrELOutput.json")));
    assertTrue(DIFFY.diff(compareJson, transformedJson).isEmpty());
}
 
Example 12
private static void checkInvalidTsaCertKeyUsage() throws Exception {

        // Hack: Rewrite the TSA cert inside normal.jar into ts2.jar.

        // Both the cert and the serial number must be rewritten.
        byte[] tsCert = Files.readAllBytes(Paths.get("ts.cert"));
        byte[] ts2Cert = Files.readAllBytes(Paths.get("ts2.cert"));
        byte[] tsSerial = getCert(tsCert)
                .getSerialNumber().toByteArray();
        byte[] ts2Serial = getCert(ts2Cert)
                .getSerialNumber().toByteArray();

        byte[] oldBlock;
        try (JarFile normal = new JarFile("normal.jar")) {
            oldBlock = Utils.readAllBytes(normal.getInputStream(
                    normal.getJarEntry("META-INF/SIGNER.RSA")));
        }

        JarUtils.updateJar("normal.jar", "ts2.jar",
                mapOf("META-INF/SIGNER.RSA",
                        updateBytes(updateBytes(oldBlock, tsCert, ts2Cert),
                                tsSerial, ts2Serial)));

        verify("ts2.jar", "-verbose", "-certs")
                .shouldHaveExitValue(64)
                .shouldContain("jar verified")
                .shouldContain("Invalid TSA certificate chain: Extended key usage does not permit use for TSA server");
    }
 
Example 13
Source Project: flink   File: FlinkStandaloneHiveRunner.java    License: Apache License 2.0 5 votes vote down vote up
private static String readAll(Path path) {
	try {
		return new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
	} catch (IOException e) {
		throw new IllegalStateException("Unable to read " + path + ": " + e.getMessage(), e);
	}
}
 
Example 14
Source Project: netty-cookbook   File: FileUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static String readFileAsString(String uri) throws java.io.IOException {
	String fullpath = FileUtils.getRuntimeFolderPath() + uri.replace("/", File.separator);
	if(!uri.startsWith("/")){
		fullpath = FileUtils.getRuntimeFolderPath() + File.separator + uri.replace("/", File.separator);
	}		
	//System.out.println(fullpath);
	byte[] data = Files.readAllBytes(Paths.get(fullpath));
	return new String(data);
}
 
Example 15
protected String getTextFromFile(String resourcePath) throws Exception {
	URI uri = getUri(resourcePath);
	return new String(Files.readAllBytes(Paths.get(uri)), StandardCharsets.UTF_8);
}
 
Example 16
public static String readText(final Path path) throws IOException {
  return new String(Files.readAllBytes(path), UTF8);
}
 
Example 17
Source Project: conjure   File: ReadmeTest.java    License: Apache License 2.0 4 votes vote down vote up
private static String extractSnippetFromReadme() throws IOException {
    String markdown = new String(Files.readAllBytes(Paths.get("..", "readme.md")), StandardCharsets.UTF_8);
    Matcher matcher = Pattern.compile("```yaml([^`]+)```", Pattern.DOTALL).matcher(markdown);
    assertThat(matcher.find()).isTrue();
    return matcher.group(1);
}
 
Example 18
Source Project: bookish   File: Tex2SVG.java    License: MIT License 4 votes vote down vote up
public Triple<String,Float,Float> tex2svg(String latex, LatexType type, int fontsize) {
		try {
			latex = latex.trim();
			String outputDir = new File(tool.outputDir).getAbsolutePath();
			String buildDir = tool.getBuildDir();

			if ( !Files.exists(Paths.get(outputDir)) ) {
				Files.createDirectories(Paths.get(outputDir));
			}
			if ( !Files.exists(Paths.get(buildDir)) ) {
				Files.createDirectories(Paths.get(buildDir));
			}
			if ( !Files.exists(Paths.get(outputDir+"/images")) ) {
				Files.createSymbolicLink(Paths.get(outputDir+"/images"), Paths.get(tool.outputDir+"/images"));
			}

			String texfilename = buildDir+"/temp.tex";
			ST template = null;
			switch ( type ) {
				case EQN:
					template = templates.getInstanceOf("eqntex");
					break;
				case BLOCKEQN:
					template = templates.getInstanceOf("blockeqntex");
					break;
				case LATEX:
					template = templates.getInstanceOf("blocktex");
					break;
			}
			template.add("text", latex);
			template.add("fontsize", fontsize);
			Files.write(Paths.get(texfilename), template.render().getBytes());

//			System.out.println("wrote "+texfilename);

			String[] results = execInDir(buildDir, "xelatex", "-shell-escape", "-interaction=nonstopmode", "temp.tex");
//    println(results.a)

			float height=0, depth=0;

			for (String line : results[0].split("\n")) {
				String prefix = "// bookish metrics: ";
				if ( line.startsWith(prefix) ) {
					int first = prefix.length();
					int comma = line.indexOf(',');
					String heightS = line.substring(first,comma-"pt".length());
					String depthS = line.substring(comma+1,line.indexOf('p',comma));
					height = Float.parseFloat(heightS);
					depth = Float.parseFloat(depthS);
				}
				if ( line.startsWith("!") || line.startsWith("l.") ) {
					System.err.println(line);
					System.err.println(latex);
				}
			}
			if ( results[1].length()>0 ) {
				System.err.println(results[1]);
			}

			results = execInDir(buildDir, "pdfcrop", "temp.pdf");
			if ( results[1].length()>0 ) {
				System.err.println(results[1]);
			}

			results = execInDir(buildDir, "pdf2svg", "temp-crop.pdf", "temp.svg");
			if ( results[1].length()>0 ) {
				System.err.println(results[1]);
			}

			String svgfilename = buildDir+"/temp.svg";
			return new Triple<>(new String(Files.readAllBytes(Paths.get(svgfilename))),height,depth);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
 
Example 19
private String content(File file) throws IOException {
	return new String(Files.readAllBytes(file.toPath()));
}
 
Example 20
/**
 * Gets a {@link SecretKey} from a {@link File}.
 * 
 * @param file
 * 		The file that is encoded as a key.
 * 
 * @throws IOException
 * 		The exception thrown if the file could not be read as a {@link SecretKey}.
 * 
 * @return The key.
 */
public static SecretKey getSecretKey(File file) throws IOException {
	return new SecretKeySpec(Files.readAllBytes(file.toPath()), algorithm);
}