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

The following examples show how to use java.nio.file.Files#readString() . 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 check out the related API usage on the sidebar.
Example 1
Source File: WindowsRunScriptGeneratorTest.java    From robozonky with Apache License 2.0 6 votes vote down vote up
@Test
void run() throws IOException {
    Path installFolder = Files.createTempDirectory("robozonky-install");
    Path robozonkyCli = Files.createTempFile(installFolder, "robozonky-", ".cli");
    Path distFolder = Files.createTempDirectory(installFolder, "dist");
    RunScriptGenerator generator = RunScriptGenerator.forWindows(distFolder.toFile(), robozonkyCli.toFile());
    assertThat(generator.getChildRunScript())
        .hasName("robozonky.bat");
    assertThat(generator.getRootFolder()
        .toPath())
            .isEqualTo(installFolder);
    File result = generator.apply(Arrays.asList("-a x", "-b"));
    String contents = Files.readString(result.toPath());
    String expected = "set \"JAVA_OPTS=%JAVA_OPTS% -a x -b\"\r\n" +
            distFolder + "\\robozonky.bat" + " @" + robozonkyCli;
    // toCharArray() is a hack to make this pass on Windows. The actual reason for failing is not know.
    assertThat(contents.toCharArray())
        .isEqualTo(expected.toCharArray());
}
 
Example 2
Source File: IllustRankService.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
public void deal() throws IOException, InterruptedException {
    //读取文件中所有未获取的画作id
    String s = Files.readString(Paths.get("/home/oysterqaq/文档/illustIdList.txt"));
    String[] split = s.split("\n");
    //遍历
    int length = split.length;
    for (int i = 1360; i < length; i++) {
        System.out.println(split[i]);
        Illustration illustration = illustrationService.pullIllustrationInfo(Integer.parseInt(split[i]));
        if (illustration != null) {
            System.out.println(split[i] + "存在");
            List<Illustration> illustrations = new ArrayList<>();
            illustrations.add(illustration);
            illustrationMapper.batchInsert(illustrations);
        }
        Thread.sleep(1000);
    }

    //下载
    //存入数据库
}
 
Example 3
Source File: TxValid.java    From nuls-v2 with MIT License 5 votes vote down vote up
/**
     * 合约与普通交易混发
     * @throws Exception
     */
    @Test
    public void transferAndContractPixelTest() throws Exception {
        String code = Files.readString(Path.of("E:\\ContractTest", "pixel.txt"));
        int size = 0;
        for (int i = 0; i < 1000; i++) {
            size++;
            String hash = createTransfer(address21, address29, new BigInteger("100000000"));
            //String hash = createCtxTransfer();
            System.out.println("transfer: " + hash);
            System.out.println("contract: " + createContract(address21, PASSWORD, code, new Object[]{size % 50 + 1}));
//            Thread.sleep(100L);
        }
    }
 
Example 4
Source File: ConfiguredSslContextFactoryProvider.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static String readToString(String filename) {
    try {
        return Files.readString(Paths.get(filename), StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 5
Source File: TestJyc.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Test
public void createContractPixelTest() throws Exception {
    String code = Files.readString(Path.of("C:\\Users\\alvin\\Desktop\\contract", "pixel.txt"));
    int size = 0;
    for (int i = 0; i < 10000000; i++) {
        size++;
        System.out.println(createContract("tNULSeBaMnrs6JKrCy6TQdzYJZkMZJDng7QAsD", PASSWORD, code, new Object[]{size % 50 + 1}));
        Thread.sleep(1000);
    }
}
 
Example 6
Source File: SDKTest.java    From shogun with Apache License 2.0 5 votes vote down vote up
@Test
void versionFirst() throws URISyntaxException, IOException {
    // test version description with broadcast message can be parsed.
    String parsedVersion = Files.readString(Paths.get(SDKTest.class.getResource("/shogun/version-first.txt").toURI()));
    String version = new SDK().parseSDKVersion(parsedVersion);
    assertEquals("SDKMAN 5.7.3+337", version);
}
 
Example 7
Source File: FacetDefinitionTest.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Verify that all non-excluded java files are represented by an entry 
 * in the applicationContext file. An exceptions list is used to track 
 * classes which are not facets.
 *   
 * @param sourceFolder The folder containing the source files.
 * @throws IOException 
 */
private void checkFacetsDefined(File sourceFolder) throws IOException
{
	Assertions.assertTrue(sourceFolder.isDirectory(), "Source folder " + sourceFolder.getAbsolutePath()
		+ " should be a directory");

	String packageName =
			sourceFolder.getPath().replace(File.separatorChar, '.')
				.replace("code.src.java.", "");

	String contextData = Files.readString(Path.of(APP_CONTEXT_FILE), StandardCharsets.UTF_8);


	Files.walk(sourceFolder.toPath()).iterator().forEachRemaining(srcFile ->
	{
		String testString = srcFile.toString();
		testString = testString.replaceAll(".java", "");
		if (!exceptions.contains(testString))
		{
			testString = "class=\"" + packageName + "." + testString + "\"";
			Assertions.assertTrue(
					contextData.contains(testString),
					"Unable to find Spring definition for " + srcFile
			);
		}
	});
}
 
Example 8
Source File: JobControllerApiHandlerHelperTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
private void assertResponse(HttpResponse response, String fileName) {
    try {
        Path path = Paths.get("src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/").resolve(fileName);
        String expected = Files.readString(path);
        compare(response, expected);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: OLMOperatorManager.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public void deployCatalogSource(String catalogSourceName, String catalogNamespace, String customRegistryImageToUse) throws IOException {
    Path catalogSourceFile = Files.createTempFile("catalogsource", ".yaml");
    String catalogSource = Files.readString(Paths.get(System.getProperty("user.dir"), "custom-operator-registry", "catalog-source.yaml"));
    Files.writeString(catalogSourceFile,
            catalogSource
                    .replaceAll("\\$\\{CATALOG_SOURCE_NAME}", catalogSourceName)
                    .replaceAll("\\$\\{OPERATOR_NAMESPACE}", catalogNamespace)
                    .replaceAll("\\$\\{REGISTRY_IMAGE}", customRegistryImageToUse));
    KubeCMDClient.applyFromFile(catalogNamespace, catalogSourceFile);
}
 
Example 10
Source File: AbstractIdeTest.java    From n4js with Eclipse Public License 1.0 5 votes vote down vote up
/** @return contents of the file with the given URI as a string. */
protected String getContentOfFileOnDisk(FileURI fileURI) {
	try {
		Path filePath = fileURI.toJavaIoFile().toPath();
		String content = Files.readString(filePath);
		return content;
	} catch (IOException e) {
		// wrap in AssertionError to avoid need for test code to declare IOExceptions
		throw new AssertionError("IOException while reading file contents from disk", e);
	}
}
 
Example 11
Source File: OLMOperatorManager.java    From enmasse with Apache License 2.0 5 votes vote down vote up
public void applySubscription(String installationNamespace, String catalogSourceName, String catalogNamespace, String csvName, String operatorName, String operatorChannel) throws IOException {
    Path subscriptionFile = Files.createTempFile("subscription", ".yaml");
    String subscription = Files.readString(Paths.get(System.getProperty("user.dir"), "custom-operator-registry", "subscription.yaml"));
    Files.writeString(subscriptionFile,
            subscription
                    .replaceAll("\\$\\{OPERATOR_NAME}", operatorName)
                    .replaceAll("\\$\\{OPERATOR_CHANNEL}", operatorChannel)
                    .replaceAll("\\$\\{OPERATOR_NAMESPACE}", installationNamespace)
                    .replaceAll("\\$\\{CATALOG_SOURCE_NAME}", catalogSourceName)
                    .replaceAll("\\$\\{CATALOG_NAMESPACE}", catalogNamespace)
                    .replaceAll("\\$\\{CSV}", csvName));
    KubeCMDClient.applyFromFile(installationNamespace, subscriptionFile);
}
 
Example 12
Source File: SDKTest.java    From shogun with Apache License 2.0 5 votes vote down vote up
@Test
void parseRequireUpdateJava() throws IOException, URISyntaxException {
    Path path = Paths.get(SDKTest.class.getResource("/shogun/list-java-require-update.txt").toURI());
    String javaVersions = Files.readString(path);
    SDK sdk = new SDK();
    List<Version> versions = sdk.parseVersions("java", javaVersions);
    assumeFalse(sdk.isOffline());
    assumeTrue(sdk.isUpdateAvailable());
    assertEquals(33, versions.size());
    assertEquals("12.0.1.j9-adpt", versions.get(0).getIdentifier());
}
 
Example 13
Source File: TestWebUi.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testJwtAuthenticator()
        throws Exception
{
    try (TestingPrestoServer server = TestingPrestoServer.builder()
            .setProperties(ImmutableMap.<String, String>builder()
                    .putAll(SECURE_PROPERTIES)
                    .put("http-server.authentication.type", "jwt")
                    .put("http-server.authentication.jwt.key-file", HMAC_KEY)
                    .build())
            .build()) {
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));
        String nodeId = server.getInstance(Key.get(NodeInfo.class)).getNodeId();

        testLogIn(httpServerInfo.getHttpUri(), false);

        testNeverAuthorized(httpServerInfo.getHttpsUri(), client);

        String hmac = Files.readString(Paths.get(HMAC_KEY));
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, hmac)
                .setSubject("test-user")
                .setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant()))
                .compact();

        OkHttpClient clientWithJwt = client.newBuilder()
                .authenticator((route, response) -> response.request().newBuilder()
                        .header(AUTHORIZATION, "Bearer " + token)
                        .build())
                .build();
        testAlwaysAuthorized(httpServerInfo.getHttpsUri(), clientWithJwt, nodeId);
    }
}
 
Example 14
Source File: TestResourceSecurity.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testJwtAuthenticator()
        throws Exception
{
    try (TestingPrestoServer server = TestingPrestoServer.builder()
            .setProperties(ImmutableMap.<String, String>builder()
                    .putAll(SECURE_PROPERTIES)
                    .put("http-server.authentication.type", "jwt")
                    .put("http-server.authentication.jwt.key-file", HMAC_KEY)
                    .build())
            .build()) {
        server.getInstance(Key.get(AccessControlManager.class)).addSystemAccessControl(new TestSystemAccessControl());
        HttpServerInfo httpServerInfo = server.getInstance(Key.get(HttpServerInfo.class));

        assertAuthenticationDisabled(httpServerInfo.getHttpUri());

        String hmac = Files.readString(Paths.get(HMAC_KEY));
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, hmac)
                .setSubject("test-user")
                .setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant()))
                .compact();

        OkHttpClient clientWithJwt = client.newBuilder()
                .authenticator((route, response) -> response.request().newBuilder()
                        .header(AUTHORIZATION, "Bearer " + token)
                        .build())
                .build();
        assertAuthenticationAutomatic(httpServerInfo.getHttpsUri(), clientWithJwt);
    }
}
 
Example 15
Source File: InstallationFeatureTest.java    From robozonky with Apache License 2.0 4 votes vote down vote up
@Test
void setupWindowsDry() throws IOException, SetupFailedException {
    // Setup stuff.
    InstallationFeature feature = new InstallationFeature();
    feature.windows = true;
    feature.dryRunEnabled = true;
    feature.jmxHostname = new URL("http://localhost");
    feature.distribution = Files.createTempDirectory("robozonky-distribution");
    feature.installation = Files.createTempDirectory("robozonky-install");
    feature.keystore = Files.createTempFile("robozonky-", ".keystore");
    feature.secret = UUID.randomUUID()
        .toString()
        .toCharArray();
    feature.strategyLocation = new URL("http://somewhere.props");
    feature.notificationLocation = new URL("http://somewhere.cfg");
    feature.username = "[email protected]";
    // Run the test.
    feature.setup();
    feature.test();
    // Check output.
    assertSoftly(softly -> {
        softly.assertThat(feature.installation.resolve("robozonky.properties"))
            .exists();
        softly.assertThat(feature.installation.resolve("management.properties"))
            .exists();
        softly.assertThat(feature.installation.resolve("robozonky.cli"))
            .exists();
        softly.assertThat(feature.installation.resolve("robozonky-exec.bat"))
            .exists();
        softly.assertThat(feature.installation.resolve("robozonky-exec.sh"))
            .doesNotExist();
        softly.assertThat(feature.installation.resolve("robozonky-systemd.service"))
            .doesNotExist();
        softly.assertThat(feature.installation.resolve("robozonky.keystore"))
            .exists();
    });
    // test CLI contents
    String cliContents = Files.readString(feature.installation.resolve("robozonky.cli"));
    assertThat(cliContents)
        .isEqualTo("-d\r\n"
                + "-g\r\n" +
                "\"" + feature.installation.resolve("robozonky.keystore") + "\"\r\n"
                + "-p\r\n" +
                "\"" + String.valueOf(feature.secret) + "\"\r\n"
                + "-s\r\n" +
                "\"" + feature.strategyLocation + "\"\r\n"
                + "-i\r\n" +
                "\"" + feature.notificationLocation + "\"");
    // test exec contents
    String execContents = Files.readString(feature.installation.resolve("robozonky-exec.bat"));
    assertThat(execContents)
        .contains(feature.distribution.toString())
        .contains("robozonky.bat")
        .contains("Xmx128m")
        .contains("XX:StartFlightRecording")
        .contains("-Dcom.sun.management.jmxremote=\"true\"");
}
 
Example 16
Source File: VersionedDatabaseFactoryTest.java    From teku with Apache License 2.0 4 votes vote down vote up
private void assertDbVersionSaved(final Path dataDirectory, final DatabaseVersion defaultVersion)
    throws IOException {
  final String versionValue =
      Files.readString(dataDirectory.resolve(VersionedDatabaseFactory.DB_VERSION_PATH));
  assertThat(versionValue).isEqualTo(defaultVersion.getValue());
}
 
Example 17
Source File: OLMOperatorManager.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public String getLatestManifestsImage() throws Exception {
    String exampleCatalogSource = Files.readString(Paths.get(Environment.getInstance().getTemplatesPath().toString(), "install", "components", "example-olm", "catalog-source.yaml"));
    var tree = new YAMLMapper().readTree(exampleCatalogSource);
    return tree.get("spec").get("image").asText();
}
 
Example 18
Source File: ClusterMetricsRetrieverTest.java    From vespa with Apache License 2.0 4 votes vote down vote up
private String containerMetrics() throws IOException {
    return Files.readString(Path.of("src/test/resources/metrics/container_metrics"));
}
 
Example 19
Source File: MainTest.java    From vespa with Apache License 2.0 4 votes vote down vote up
private static String readTestResource(String fileName) throws IOException {
    return Files.readString(Paths.get(MainTest.class.getResource('/' + fileName).getFile()));
}
 
Example 20
Source File: TestDataFileReader.java    From ods-provisioning-app with Apache License 2.0 4 votes vote down vote up
public String readFileContent(String name) throws IOException {
  File testFile = findTestFile(name);
  return Files.readString(testFile.toPath());
}