Example usage for java.nio.file Files readAllLines

List of usage examples for java.nio.file Files readAllLines

Introduction

In this page you can find the example usage for java.nio.file Files readAllLines.

Prototype

public static List<String> readAllLines(Path path, Charset cs) throws IOException 

Source Link

Document

Read all lines from a file.

Usage

From source file:org.jboss.as.test.integration.logging.formatters.JsonFormatterTestCase.java

@Test
public void testStructuredException() throws Exception {
    configure(Collections.emptyMap(), Collections.emptyMap(), false);

    // Change the exception-output-type
    executeOperation(/* w  w  w. j av  a2 s  .c o  m*/
            Operations.createWriteAttributeOperation(FORMATTER_ADDRESS, "exception-output-type", "detailed"));

    final String msg = "Logging test: JsonFormatterTestCase.testNoExceptions";
    int statusCode = getResponse(msg,
            Collections.singletonMap(LoggingServiceActivator.LOG_EXCEPTION_KEY, "true"));
    Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);

    final List<String> expectedKeys = createDefaultKeys();
    expectedKeys.add("exception");

    for (String s : Files.readAllLines(logFile, StandardCharsets.UTF_8)) {
        if (s.trim().isEmpty())
            continue;
        try (JsonReader reader = Json.createReader(new StringReader(s))) {
            final JsonObject json = reader.readObject();

            validateDefault(json, expectedKeys, msg);
            validateStackTrace(json, false, true);
        }
    }
}

From source file:org.jboss.as.test.integration.domain.events.JmxControlledStateNotificationsTestCase.java

private void readAndCheckFile(File file, Consumer<List<String>> consumer) throws IOException {
    Assert.assertTrue("File not found " + file.getAbsolutePath(), file.exists());
    consumer.accept(Files.readAllLines(file.toPath(), StandardCharsets.UTF_8));
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.TestDockerContainerRuntime.java

@Test
public void testDockerContainerLaunch()
        throws ContainerExecutionException, PrivilegedOperationException, IOException {
    DockerLinuxContainerRuntime runtime = new DockerLinuxContainerRuntime(mockExecutor);
    runtime.initialize(conf);// www  .  ja  v  a  2  s. co  m

    String[] testCapabilities = { "NET_BIND_SERVICE", "SYS_CHROOT" };

    conf.setStrings(YarnConfiguration.NM_DOCKER_CONTAINER_CAPABILITIES, testCapabilities);
    runtime.launchContainer(builder.build());

    PrivilegedOperation op = capturePrivilegedOperationAndVerifyArgs();
    List<String> args = op.getArguments();
    String dockerCommandFile = args.get(11);

    /* Ordering of capabilities depends on HashSet ordering. */
    Set<String> capabilitySet = new HashSet<>(Arrays.asList(testCapabilities));
    StringBuilder expectedCapabilitiesString = new StringBuilder("--cap-drop=ALL ");

    for (String capability : capabilitySet) {
        expectedCapabilitiesString.append("--cap-add=").append(capability).append(" ");
    }

    //This is the expected docker invocation for this case
    StringBuffer expectedCommandTemplate = new StringBuffer("run --name=%1$s ").append("--user=%2$s -d ")
            .append("--workdir=%3$s ").append("--net=host ").append(expectedCapabilitiesString)
            .append("-v /etc/passwd:/etc/password:ro ").append("-v %4$s:%4$s ").append("-v %5$s:%5$s ")
            .append("-v %6$s:%6$s ").append("%7$s ").append("bash %8$s/launch_container.sh");

    String expectedCommand = String.format(expectedCommandTemplate.toString(), containerId, runAsUser,
            containerWorkDir, localDirs.get(0), containerWorkDir, logDirs.get(0), image, containerWorkDir);

    List<String> dockerCommands = Files.readAllLines(Paths.get(dockerCommandFile), Charset.forName("UTF-8"));

    Assert.assertEquals(1, dockerCommands.size());
    Assert.assertEquals(expectedCommand, dockerCommands.get(0));
}

From source file:edu.usu.sdl.openstorefront.usecase.AttributeImport.java

private AttributeTypeView loadJCAArch() {
    AttributeTypeView attributeTypeView = new AttributeTypeView();

    CSVParser parser = new CSVParser();
    Path path = Paths.get(FileSystemManager.getDir(FileSystemManager.IMPORT_DIR) + "/jca.csv");
    try {// w w  w  .  j  a  v a 2  s.  c o  m
        List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
        //read type
        try {
            String data[] = parser.parseLine(lines.get(1));

            attributeTypeView.setAttributeType(data[0].trim());
            attributeTypeView.setDescription(data[1].trim());
            attributeTypeView.setArchitectureFlg(Convert.toBoolean(data[2].trim()));
            attributeTypeView.setVisibleFlg(Convert.toBoolean(data[3].trim()));
            attributeTypeView.setImportantFlg(Convert.toBoolean(data[4].trim()));
            attributeTypeView.setRequiredFlg(Convert.toBoolean(data[5].trim()));
            attributeTypeView.setAllowMultipleFlg(Convert.toBoolean(data[6].trim()));

            for (int i = 2; i < lines.size(); i++) {
                if (StringUtils.isNotBlank(lines.get(i))) {
                    data = parser.parseLine(lines.get(i));
                    AttributeCodeView attributeCodeView = new AttributeCodeView();
                    if (StringUtils.isNotBlank(data[0].trim())) {
                        attributeCodeView.setCode(data[0].toUpperCase().trim());

                        StringBuilder label = new StringBuilder();
                        for (int j = 1; j < data.length; j++) {
                            label.append(data[j]);
                        }

                        attributeCodeView
                                .setLabel(data[0].toUpperCase().trim() + " " + label.toString().trim());
                        attributeTypeView.getCodes().add(attributeCodeView);
                    }
                }
            }

        } catch (IOException ex) {
            log.log(Level.SEVERE, null, ex);
        }

    } catch (IOException ex) {

        log.log(Level.SEVERE, null, ex);
    }

    return attributeTypeView;
}

From source file:de.fatalix.book.importer.BookMigrator.java

private static BookEntry parseOPF(File pathToOPF, BookEntry bmd) throws IOException {
    List<String> lines = Files.readAllLines(pathToOPF.toPath(), Charset.forName("UTF-8"));
    boolean multiLineDescription = false;
    String description = "";
    for (String line : lines) {
        if (multiLineDescription) {
            multiLineDescription = false;
            if (line.split("<").length == 1) {
                multiLineDescription = true;
                description = description + line;
            } else {
                description = description + line.split("<")[0];
                description = StringEscapeUtils.unescapeXml(description);
                bmd.setDescription(description);
            }/*  ww  w. ja  v a 2s.  c o  m*/
        } else if (line.contains("dc:title")) {
            String title = line.split(">")[1].split("<")[0];
            bmd.setTitle(title);
        } else if (line.contains("dc:creator")) {
            String creator = line.split(">")[1].split("<")[0];
            bmd.setAuthor(creator);
        } else if (line.contains("dc:description")) {
            String value = line.split(">")[1];
            if (value.split("<").length == 1) {
                multiLineDescription = true;
                description = value;
            } else {
                value = value.split("<")[0];
                value = StringEscapeUtils.unescapeXml(value);
                bmd.setDescription(value);
            }
        } else if (line.contains("dc:publisher")) {
            String value = line.split(">")[1].split("<")[0];
            bmd.setPublisher(value);
        } else if (line.contains("dc:date")) {
            String value = line.split(">")[1].split("<")[0];
            DateTime dtReleaseDate = new DateTime(value, DateTimeZone.UTC);
            if (dtReleaseDate.getYear() != 101) {
                bmd.setReleaseDate(dtReleaseDate.toDate());
            }
        } else if (line.contains("dc:language")) {
            String value = line.split(">")[1].split("<")[0];
            bmd.setLanguage(value);
        } else if (line.contains("opf:scheme=\"ISBN\"")) {
            String value = line.split(">")[1].split("<")[0];
            bmd.setIsbn(value);
        }
    }
    return bmd;
}

From source file:org.omegat.core.spellchecker.SpellChecker.java

private void loadWordLists() {
    // find out the internal project directory
    String projectDir = Core.getProject().getProjectProperties().getProjectInternal();

    // load the ignore list
    ignoreFilePath = Paths.get(projectDir, OConsts.IGNORED_WORD_LIST_FILE_NAME);

    ignoreList.clear();/*from  ww w.j a va  2  s.c  om*/
    if (ignoreFilePath.toFile().isFile()) {
        try {
            ignoreList.addAll(Files.readAllLines(ignoreFilePath, StandardCharsets.UTF_8));
        } catch (Exception ex) {
            Log.log(ex);
        }
    }

    // now the correct words
    learnedFilePath = Paths.get(projectDir, OConsts.LEARNED_WORD_LIST_FILE_NAME);

    learnedList.clear();
    if (learnedFilePath.toFile().isFile()) {
        try {
            learnedList.addAll(Files.readAllLines(learnedFilePath, StandardCharsets.UTF_8));
            learnedList.stream().forEach(word -> checker.learnWord(word));
        } catch (Exception ex) {
            Log.log(ex);
        }
    }
}

From source file:com.spotify.docker.BuildMojoTest.java

public void testBuildWithProfile() throws Exception {
    final File pom = getTestFile("src/test/resources/pom-build-with-profile.xml");
    assertNotNull("Null pom.xml", pom);
    assertTrue("pom.xml does not exist", pom.exists());

    final BuildMojo mojo = setupMojo(pom);
    final DockerClient docker = mock(DockerClient.class);
    mojo.execute(docker);/*from w  w w. j a v  a  2 s  .com*/

    verify(docker).build(eq(Paths.get("target/docker")), eq("docker-maven-plugin-test"),
            any(AnsiProgressHandler.class));
    assertFileExists("target/docker/xml/pom-build-with-profile.xml");
    assertFileExists("target/docker/Dockerfile");
    assertEquals("wrong dockerfile contents", PROFILE_GENERATED_DOCKERFILE,
            Files.readAllLines(Paths.get("target/docker/Dockerfile"), UTF_8));
}

From source file:it.tidalwave.northernwind.util.test.TestHelper.java

/*******************************************************************************************************************
 *
 * Reads the content from the resource file as a single string. See {@link #resourceFileFor(java.lang.String)} for
 * further info.//from  ww  w  .java 2s . co  m
 *
 * @param   resourceName    the resource name
 * @return                  the string
 * @throws  IOException     in case of error
 *
 ******************************************************************************************************************/
@Nonnull
public String readStringFromResource(final @Nonnull String resourceName) throws IOException {
    final Path file = resourceFileFor(resourceName);
    final StringBuilder buffer = new StringBuilder();
    String separator = "";

    for (final String string : Files.readAllLines(file, UTF_8)) {
        buffer.append(separator).append(string);
        separator = "\n";
    }

    return buffer.toString();
    //            return String.join("\n", Files.readAllLines(path, UTF_8)); TODO JDK 8
}

From source file:org.neo4j.io.fs.FileUtils.java

public static String readTextFile(File file, Charset charset) throws IOException {
    StringBuilder out = new StringBuilder();
    for (String s : Files.readAllLines(file.toPath(), charset)) {
        out.append(s).append("\n");
    }//from  w  ww  . j a  v  a  2  s .c  om
    return out.toString();
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.linux.runtime.TestDockerContainerRuntime.java

@Test
public void testLaunchPrivilegedContainersInvalidEnvVar()
        throws ContainerExecutionException, PrivilegedOperationException, IOException {
    DockerLinuxContainerRuntime runtime = new DockerLinuxContainerRuntime(mockExecutor);
    runtime.initialize(conf);/*from  w ww  . j a v  a 2 s.co m*/

    env.put("YARN_CONTAINER_RUNTIME_DOCKER_RUN_PRIVILEGED_CONTAINER", "invalid-value");
    runtime.launchContainer(builder.build());

    PrivilegedOperation op = capturePrivilegedOperationAndVerifyArgs();
    List<String> args = op.getArguments();
    String dockerCommandFile = args.get(11);

    List<String> dockerCommands = Files.readAllLines(Paths.get(dockerCommandFile), Charset.forName("UTF-8"));

    Assert.assertEquals(1, dockerCommands.size());

    String command = dockerCommands.get(0);

    //ensure --privileged isn't in the invocation
    Assert.assertTrue("Unexpected --privileged in docker run args : " + command,
            !command.contains("--privileged"));
}