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:com.codename1.tools.javadoc.sourceembed.javadocsourceembed.Main.java

public static void processFile(File javaSourceFile, File javaDestFile) throws Exception {
    System.out.println("JavaSource Processing: " + javaSourceFile.getName());
    List<String> lines = Files.readAllLines(Paths.get(javaSourceFile.toURI()), CHARSET);
    for (int iter = 0; iter < lines.size(); iter++) {
        String l = lines.get(iter);
        int position = l.indexOf("<script src=\"https://gist.github.com/");
        if (position > -1) {
            String id = l.substring(position + 39);
            id = id.split("/")[1];
            id = id.substring(0, id.indexOf('.'));
            String fileContent = gistCache.get(id);
            if (fileContent != null) {
                lines.add(iter + 1, fileContent);
                iter++;//from w w w .j  a va  2s . c o m
                continue;
            }

            URL u = new URL("https://api.github.com/gists/" + id + "?client_id=" + CLIENT_ID + "&client_secret="
                    + CLIENT_SECRET);
            try (BufferedReader br = new BufferedReader(new InputStreamReader(u.openStream(), CHARSET))) {
                String jsonText = br.lines().collect(Collectors.joining("\n"));
                JSONObject json = new JSONObject(jsonText);
                JSONObject filesObj = json.getJSONObject("files");
                String str = "";
                for (String k : filesObj.keySet()) {
                    JSONObject jsonFileEntry = filesObj.getJSONObject(k);
                    // breaking line to fix the problem with a blank space on the first line
                    String current = "\n" + jsonFileEntry.getString("content");
                    str += current;
                }
                int commentStartPos = str.indexOf("/*");
                while (commentStartPos > -1) {
                    // we just remove the comment as its pretty hard to escape it properly
                    int commentEndPos = str.indexOf("*/");
                    str = str.substring(commentStartPos, commentEndPos + 1);
                    commentStartPos = str.indexOf("/*");
                }

                // allows things like the @Override annotation
                str = "<noscript><pre>{@code " + str.replace("@", "{@literal @}") + "}</pre></noscript>";
                gistCache.put(id, str);
                lines.add(iter + 1, str);
                iter++;
            }
        }
    }
    try (BufferedWriter fw = new BufferedWriter(new FileWriter(javaDestFile))) {
        for (String l : lines) {
            fw.write(l);
            fw.write('\n');
        }
    }
}

From source file:eu.arthepsy.sonar.plugins.elixir.language.ElixirMeasureSensor.java

private void processMainFile(InputFile inputFile, SensorContext context) {
    List<String> lines;
    try {// ww w . j a  va  2  s. c  om
        lines = Files.readAllLines(Paths.get(inputFile.absolutePath()), fileSystem.encoding());
    } catch (IOException e) {
        LOG.warn(LOG_PREFIX + "could not process file: " + inputFile.toString());
        return;
    }
    ElixirParser parser = new ElixirParser();
    parser.parse(lines);

    LOG.debug(LOG_PREFIX + "processing file: " + inputFile.toString());
    double linesOfCode = parser.getLineCount() - parser.getEmptyLineCount() - parser.getCommentLineCount();
    context.saveMeasure(inputFile, CoreMetrics.LINES, (double) parser.getLineCount());
    context.saveMeasure(inputFile, CoreMetrics.NCLOC, (double) linesOfCode);
    context.saveMeasure(inputFile, CoreMetrics.COMMENT_LINES, (double) parser.getCommentLineCount());

    double publicApi = parser.getPublicFunctionCount() + parser.getClassCount();
    double documentedApi = parser.getDocumentedPublicFunctionCount() + parser.getDocumentedClassCount();
    double undocumentedApi = publicApi - documentedApi;
    double documentedApiDensity = (publicApi == 0 ? 100.0
            : ParsingUtils.scaleValue(documentedApi / publicApi * 100, 2));
    context.saveMeasure(inputFile, CoreMetrics.PUBLIC_API, publicApi);
    context.saveMeasure(inputFile, CoreMetrics.PUBLIC_UNDOCUMENTED_API, undocumentedApi);
    context.saveMeasure(inputFile, CoreMetrics.PUBLIC_DOCUMENTED_API_DENSITY, documentedApiDensity);

    double functionCount = parser.getPublicFunctionCount() + parser.getPrivateFunctionCount();
    context.saveMeasure(inputFile, CoreMetrics.CLASSES, (double) parser.getClassCount());
    context.saveMeasure(inputFile, CoreMetrics.FUNCTIONS, (double) (functionCount));
}

From source file:org.wso2.appcloud.mgt.ManagementService.java

@GET
@Path("/createSource/{tenantDomain}/{appType}/{sourceDir}/{sample}")
public boolean createSource(@PathParam("tenantDomain") String tenantDomain,
        @PathParam("appType") String appType, @PathParam("sourceDir") String sourceDir,
        @PathParam("sample") String sample) throws IOException {

    String sourceLocation = System.getenv(Constants.SOURCE_LOCATION) + "/" + tenantDomain + "/" + appType + "/"
            + sourceDir;/*  ww  w  .ja v a  2  s.c o m*/
    File file = new File(sourceLocation);
    log.info("Source location : " + sourceLocation);

    try {
        boolean isFolderCreated = file.mkdirs();
        log.info("isFolderCreated : " + isFolderCreated);
        if (isFolderCreated) {
            log.info("Source location created: " + sourceDir);

            // copy source structure
            File source = new File(System.getenv(Constants.SAMPLE_LOCATION) + "/" + appType + "/" + sample);
            log.info("sample location : " + System.getenv(Constants.SAMPLE_LOCATION) + "/" + appType + "/"
                    + sample);
            File dest = new File(sourceLocation);
            FileUtils.copyDirectory(source, dest);
            log.info("Sample copied for: " + sourceDir);
        }

        //Adding package name for initial sample.
        if (file.exists()) {
            String dirPath = System.getenv(Constants.SOURCE_LOCATION) + "/" + tenantDomain + "/" + appType + "/"
                    + sourceDir;
            String pkgName = "org." + tenantDomain + "." + appType + "." + sourceDir;
            List<String> newLines = new ArrayList<>();
            for (String line : Files.readAllLines(Paths.get(dirPath + "/" + sample + ".bal"),
                    StandardCharsets.UTF_8)) {
                if (line.contains("_pkgName")) {
                    log.info("Adding package to the source file: " + pkgName);
                    newLines.add(line.replace("_pkgName", pkgName));
                } else {
                    newLines.add(line);
                }
            }
            Files.write(Paths.get(dirPath + "/" + sample + ".bal"), newLines, StandardCharsets.UTF_8);
        }
    } catch (IOException ex) {
        log.error(ex);
        return false;
    }
    return true;
}

From source file:org.optaplanner.core.impl.score.director.drools.testgen.TestGenTestWriterTest.java

private static void checkOutput(Path expected, String actual) throws IOException {
    // first detect different lines
    List<String> expectedLines = Files.readAllLines(expected, StandardCharsets.UTF_8);
    List<String> actualLines = new BufferedReader(new StringReader(actual)).lines()
            .collect(Collectors.toList());
    for (int i = 0; i < Math.min(expectedLines.size(), actualLines.size()); i++) {
        String expectedLine = StringUtils.replace(expectedLines.get(i), DRL_FILE_PLACEHOLDER,
                new File(DRL_FILE_PATH).getAbsolutePath());
        assertEquals("At line " + (i + 1), expectedLine, actualLines.get(i));
    }/*from ww w.  j  a v  a2 s .c  om*/

    // then check line counts are the same
    assertEquals(expectedLines.size(), actualLines.size());

    // finally check the whole string
    String expectedString = StringUtils.replace(
            new String(Files.readAllBytes(expected), StandardCharsets.UTF_8), DRL_FILE_PLACEHOLDER,
            new File(DRL_FILE_PATH).getAbsolutePath());
    assertEquals(expectedString, actual);
}

From source file:com.liferay.ide.gradle.core.parser.GradleDependencyUpdater.java

public FindDependenciesVisitor insertDependency(String dependency) throws IOException {
    FindDependenciesVisitor visitor = new FindDependenciesVisitor();

    walkScript(visitor);/*from  ww w  .j  a  v  a2s .  c o m*/

    _gradleFileContents = FileUtils.readLines(_file);

    if (!dependency.startsWith("\t")) {
        dependency = "\t" + dependency;
    }

    if (visitor.getDependenceLineNum() == -1) {
        _gradleFileContents.add("");
        _gradleFileContents.add("dependencies {");
        _gradleFileContents.add(dependency);
        _gradleFileContents.add("}");
    } else {
        if (visitor.getColumnNum() != -1) {
            _gradleFileContents = Files.readAllLines(Paths.get(_file.toURI()), StandardCharsets.UTF_8);

            StringBuilder builder = new StringBuilder(
                    _gradleFileContents.get(visitor.getDependenceLineNum() - 1));

            builder.insert(visitor.getColumnNum() - 2, "\n" + dependency + "\n");
            String dep = builder.toString();

            if (CoreUtil.isWindows()) {
                dep.replace("\n", "\r\n");
            } else if (CoreUtil.isMac()) {
                dep.replace("\n", "\r");
            }

            _gradleFileContents.remove(visitor.getDependenceLineNum() - 1);
            _gradleFileContents.add(visitor.getDependenceLineNum() - 1, dep);
        } else {
            _gradleFileContents.add(visitor.getDependenceLineNum() - 1, dependency);
        }
    }

    return visitor;
}

From source file:com.uisteps.utils.thucydides.Result.java

private void init(String charset, String projectKey) throws IOException, JSONException {

    List<String> lines = Files.readAllLines(file.toPath(), Charset.forName(charset));

    for (int i = 1; i < lines.size(); i++) {

        String line = lines.get(i);
        JSONObject item = new JSONObject();

        String[] attrs = line.replace("\"", "").split(",");
        String component = attrs[0];

        Pattern pattern = Pattern.compile("(.*)\\s(" + projectKey + "-\\d+)");
        Matcher matcher = pattern.matcher(attrs[1]);
        matcher.find();/*from  w  w w  .  j  a  va  2 s  .  co m*/

        String title = matcher.group(1);
        String issue = matcher.group(2);

        String status = attrs[2];

        item.put(COMPONENT, component).put(TITLE, title).put(ISSUE, issue).put(STATUS, status);

        result.put(item);

        tests.put(issue, new Test(component, title, issue, status));
    }

}

From source file:org.esupportail.publisher.config.FileUploadConfiguration.java

@Bean(name = "publicFileUploadHelper")
public FileUploadHelper publicFileUploadHelper() throws IOException, URISyntaxException {
    FileUploadHelper fuh = new FileUploadHelper();
    final String path = getDefinedUploadPath(ENV_UPLOAD_PATH);
    Assert.notNull(path, "You should define a protected file path");

    fuh.setUploadDirectoryPath(path);/* w  w w .  j a  v  a2s .c o  m*/
    fuh.setResourceLocation("file:///" + path);
    fuh.setUrlResourceMapping("files/");
    fuh.setUseDefaultPath(false);
    fuh.setFileMaxSize(env.getProperty(ENV_UPLOAD_IMAGESIZE, long.class, defaultImageMaxSize));
    fuh.setUnremovablePaths(
            Arrays.asList(env.getProperty(ENV_UNREMOVABLE_PATH, String[].class, new String[] {})));
    final String mimeTypesFilePath = env.getProperty(ENV_UPLOAD_FILE_AUTHORIZED_MIME_TYPE,
            defaultFileMimeTypes);
    try {
        List<String> list = Files.readAllLines(Paths.get(new ClassPathResource(mimeTypesFilePath).getURI()),
                Charsets.UTF_8);
        fuh.setAuthorizedMimeType(list);
    } catch (IOException e) {
        log.error("No file describing authorized MimeTypes is readable !", e);
        throw e;
    }
    log.debug("FileUploadConfiguration : " + fuh.toString());
    return fuh;
    /* Default way
    fuh.setUploadDirectoryPath(new ClassPathResource("classpath:static/").getPath());
    fuh.setResourceLocation("classpath:static/");
    fuh.setUrlResourceMapping("files/");
    fuh.setUseDefaultPath(true);
    fuh.setFileMaxSize(env.getProperty(ENV_UPLOAD_IMAGESIZE, long.class, DefaultImageMaxSize));
    log.debug("FileUploadConfiguration : " + fuh.toString());
    return fuh;*/
}

From source file:org.jboss.as.test.integration.logging.operations.CustomHandlerTestCase.java

private void searchLog(final String msg, final boolean expected) throws Exception {
    int statusCode = getResponse(msg);
    Assert.assertTrue("Invalid response statusCode: " + statusCode, statusCode == HttpStatus.SC_OK);
    boolean logFound = false;
    for (String s : Files.readAllLines(logFile, StandardCharsets.UTF_8)) {
        if (s.contains(msg)) {
            logFound = true;/*from  w ww .java2s  .c om*/
            break;
        }
    }
    Assert.assertTrue(msg + " not found in " + logFile, logFound == expected);
}

From source file:com.sliit.neuralnetwork.RecurrentNN.java

public static void main(String[] args) {

    RecurrentNN neural_network = new RecurrentNN();
    System.out.println("start=======================");
    try {//from w  w  w .  j  a  v a 2  s  .c  o m
        neural_network.inputs = 10;
        neural_network.numHiddenNodes = 5;
        neural_network.HIDDEN_LAYER_COUNT = 2;
        neural_network.outputNum = 2;
        neural_network.buildModel();
        String output = neural_network.trainModel("nn", "D:/Data/originalnormkddaddeddata.csv", 2, 10);
        System.out.println("output " + output);

        System.out.println("Testing........................");
        Charset charset = Charset.forName("ISO-8859-1");
        Path wiki_path = Paths.get("D:/SLIIT/deadlocks/data/", "normtrainadded.csv");

        List<String> lines = Files.readAllLines(wiki_path, charset);
        String[] testDataArr = lines.toArray(new String[lines.size()]);

        Map<Integer, String> map = new HashMap<Integer, String>();

        String testOutput = neural_network.testModel("nn", testDataArr, map, 10, 2, "D:/Data/Test", "");
        System.out.println("Test output " + testOutput);
    } catch (Exception e) {
        e.printStackTrace();
    }
}