Example usage for com.google.common.io LineProcessor LineProcessor

List of usage examples for com.google.common.io LineProcessor LineProcessor

Introduction

In this page you can find the example usage for com.google.common.io LineProcessor LineProcessor.

Prototype

LineProcessor

Source Link

Usage

From source file:org.apache.s4.tools.CreateApp.java

public static void main(String[] args) {

    final CreateAppArgs appArgs = new CreateAppArgs();
    Tools.parseArgs(appArgs, args);//from w w w  . ja  v  a 2 s  .c  om

    if (new File(appArgs.getAppDir() + "/" + appArgs.appName.get(0)).exists()) {
        System.err.println("There is already a directory called " + appArgs.appName.get(0) + " in the "
                + appArgs.getAppDir()
                + " directory. Please specify another name for your project or specify another parent directory");
        System.exit(1);
    }
    // create project structure
    try {
        createDir(appArgs, "/src/main/java");
        createDir(appArgs, "/src/main/resources");
        createDir(appArgs, "/src/main/java/hello");

        // copy gradlew script (redirecting to s4 gradlew)
        File gradlewTempFile = File.createTempFile("gradlew", "tmp");
        gradlewTempFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/gradlew")),
                gradlewTempFile);
        String gradlewScriptContent = Files.readLines(gradlewTempFile, Charsets.UTF_8,
                new PathsReplacer(appArgs));
        Files.write(gradlewScriptContent, gradlewTempFile, Charsets.UTF_8);
        Files.copy(gradlewTempFile, new File(appArgs.getAppDir() + "/gradlew"));
        new File(appArgs.getAppDir() + "/gradlew").setExecutable(true);

        // copy build file contents
        String buildFileContents = Resources.toString(Resources.getResource("templates/build.gradle"),
                Charsets.UTF_8);
        buildFileContents = buildFileContents.replace("<s4_install_dir>",
                "'" + new File(appArgs.s4ScriptPath).getParent() + "'");
        Files.write(buildFileContents, new File(appArgs.getAppDir() + "/build.gradle"), Charsets.UTF_8);

        // copy lib
        FileUtils.copyDirectory(new File(new File(appArgs.s4ScriptPath).getParentFile(), "lib"),
                new File(appArgs.getAppDir() + "/lib"));

        // update app settings
        String settingsFileContents = Resources.toString(Resources.getResource("templates/settings.gradle"),
                Charsets.UTF_8);
        settingsFileContents = settingsFileContents.replaceFirst("rootProject.name=<project-name>",
                "rootProject.name=\"" + appArgs.appName.get(0) + "\"");
        Files.write(settingsFileContents, new File(appArgs.getAppDir() + "/settings.gradle"), Charsets.UTF_8);
        // copy hello app files
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/HelloPE.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloPE.java"));
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/HelloApp.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloApp.java"));
        // copy hello app adapter
        Files.copy(
                Resources.newInputStreamSupplier(Resources.getResource("templates/HelloInputAdapter.java.txt")),
                new File(appArgs.getAppDir() + "/src/main/java/hello/HelloInputAdapter.java"));

        File s4TmpFile = File.createTempFile("s4Script", "template");
        s4TmpFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/s4")), s4TmpFile);

        // create s4
        String preparedS4Script = Files.readLines(s4TmpFile, Charsets.UTF_8, new PathsReplacer(appArgs));

        File s4Script = new File(appArgs.getAppDir() + "/s4");
        Files.write(preparedS4Script, s4Script, Charsets.UTF_8);
        s4Script.setExecutable(true);

        File readmeTmpFile = File.createTempFile("newApp", "README");
        readmeTmpFile.deleteOnExit();
        Files.copy(Resources.newInputStreamSupplier(Resources.getResource("templates/newApp.README")),
                readmeTmpFile);
        // display contents from readme
        Files.readLines(readmeTmpFile, Charsets.UTF_8, new LineProcessor<Boolean>() {

            @Override
            public boolean processLine(String line) throws IOException {
                if (!line.startsWith("#")) {
                    System.out.println(line.replace("<appDir>", appArgs.getAppDir()));
                }
                return true;
            }

            @Override
            public Boolean getResult() {
                return true;
            }

        });
    } catch (Exception e) {
        logger.error("Could not create project due to [{}]. Please check your configuration.", e.getMessage());
    }
}

From source file:com.storezhang.android.flavor.FlavorUtils.java

public static String build() throws IOException {
    final List<Map<String, String>> flavors = new ArrayList<Map<String, String>>();

    File flavorsFile = new File("flavors.txt");
    Files.readLines(flavorsFile, Charset.forName("UTF-8"), new LineProcessor<Void>() {

        @Override// w  w  w  .  j  a v  a  2s  .c om
        public boolean processLine(String line) throws IOException {
            String[] flavorString = line.split("\t");
            Map<String, String> flavor = new HashMap<String, String>();
            flavor.put("name", "_" + (flavorString[0].substring(0, 1).toUpperCase()
                    + flavorString[0].substring(1).replaceFirst("\\w", "").replaceAll("/", "")).trim());
            flavor.put("umeng", flavorString[1].trim());
            flavor.put("youmi", flavorString[2].trim());
            flavors.add(flavor);

            return true;
        }

        @Override
        public Void getResult() {
            return null;
        }
    });

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("flavors", flavors);
    String flavorString = HttlUtils.render("flavor.httl", model);

    return flavorString;
}

From source file:org.eclipse.scada.protocol.utils.BufferLoader.java

public static List<IoBuffer> loadBuffersFromResource(final Class<?> clazz, final String resourceName)
        throws IOException {
    logger.debug("Loading buffer - {}", resourceName);

    final URL url = Resources.getResource(clazz, resourceName);

    return Resources.readLines(url, Charset.forName("UTF-8"), new LineProcessor<List<IoBuffer>>() {

        private final List<IoBuffer> result = new LinkedList<>();

        private IoBuffer buffer = null;

        protected void pushBuffer() {
            if (this.buffer == null) {
                return;
            }//from w ww  .j  a va2s. com

            this.buffer.flip();
            this.result.add(this.buffer);

            this.buffer = null;
        }

        @Override
        public boolean processLine(String line) throws IOException {
            line = line.replaceAll("#.*", ""); // clear comments

            if (line.isEmpty()) {
                pushBuffer();
                return true;
            }

            final String[] toks = line.split("\\s+");

            if (toks.length <= 0) {
                pushBuffer();
                return true;
            }

            if (this.buffer == null) {
                // start a new buffer
                this.buffer = IoBuffer.allocate(0);
                this.buffer.setAutoExpand(true);
            }

            for (final String tok : toks) {
                this.buffer.put(Byte.parseByte(tok, 16));
            }
            return true;
        }

        @Override
        public List<IoBuffer> getResult() {
            pushBuffer(); // last chance to add something
            return this.result;
        }
    });
}

From source file:us.eharning.atomun.mnemonic.spi.electrum.v2.CJKCleanupUtility.java

private static RangeSet<Integer> buildRanges() {
    LineProcessor<RangeSet<Integer>> lineProcess = new LineProcessor<RangeSet<Integer>>() {
        private final RangeSet<Integer> resultBuilder = TreeRangeSet.create();

        @Override/* w  w w .j ava2 s  . c om*/
        public boolean processLine(@Nonnull String line) throws IOException {
            /* Skip comments and empty lines */
            int commentIndex = line.indexOf('#');
            if (commentIndex >= 0) {
                line = line.substring(0, commentIndex);
            }
            line = CharMatcher.WHITESPACE.trimFrom(line);
            if (line.isEmpty()) {
                return true;
            }
            /* NOTE: Assuming 0xHEX-0xHEX notation */
            int splitMarker = line.indexOf('-');
            assert splitMarker >= 0;
            int start = Integer.parseInt(line.substring(2, splitMarker), 16);
            int stop = Integer.parseInt(line.substring(splitMarker + 3), 16);
            resultBuilder.add(Range.closed(start, stop));
            return true;
        }

        @Override
        public RangeSet<Integer> getResult() {
            return ImmutableRangeSet.copyOf(resultBuilder);
        }
    };
    try {
        return Resources.readLines(MnemonicUtility.class.getResource("cjk_ranges.dat"), Charsets.UTF_8,
                lineProcess);
    } catch (IOException e) {
        throw new Error(e);
    }
}

From source file:com.android.tools.idea.res.RDotTxtParser.java

@NotNull
static Collection<String> getIdNames(final File rFile) {
    try {/*from  ww w.  j av  a2s. c  o m*/
        return Files.readLines(rFile, Charsets.UTF_8, new LineProcessor<Collection<String>>() {
            Collection<String> idNames = new ArrayList<String>(32);

            @Override
            public boolean processLine(@NotNull String line) throws IOException {
                if (!line.startsWith(INT_ID)) {
                    return true;
                }
                int i = line.indexOf(' ', INT_ID_LEN);
                assert i != -1 : "File not in expected format: " + rFile.getPath() + "\n"
                        + "Expected the ids to be in the format int id <name> <number>";
                idNames.add(line.substring(INT_ID_LEN, i));
                return true;
            }

            @Override
            public Collection<String> getResult() {
                return idNames;
            }
        });
    } catch (IOException e) {
        getLog().warn("Unable to read file: " + rFile.getPath(), e);
        return Collections.emptyList();
    }
}

From source file:org.excalibur.core.io.utils.IOUtils2.java

/**
 * Reads all of the lines from an {@link InputStream} object. The lines include the line-termination characters, and also include other leading
 * and trailing whitespace.// w w w.j a  va2 s  .c  o  m
 * 
 * <p>
 * Does not close the {@code InputStream}.
 * 
 * @param is
 *            The stream to read from.
 * 
 * @throws IOException
 *             if an I/O error occurs.
 */
public static String readLines(InputStream is) throws IOException {
    InputStreamReader isr = new InputStreamReader(is);
    try {
        return CharStreams.readLines(isr, new LineProcessor<String>() {
            final StringBuilder lines = new StringBuilder();

            @Override
            public boolean processLine(String line) throws IOException {
                lines.append(line).append(Strings2.NEW_LINE);
                return true;
            }

            @Override
            public String getResult() {
                return lines.toString();
            }
        });
    } finally {
        closeQuietly(isr);
    }
}

From source file:org.icgc.dcc.generator.utils.Files.java

@SneakyThrows
public static long getLineCount(File file) {
    return com.google.common.io.Files.readLines(file, UTF_8, new LineProcessor<Long>() {

        long count = 0;

        @Override//from  w  ww.  j  a  v  a  2s.c  o m
        public Long getResult() {
            return count;
        }

        @Override
        public boolean processLine(String line) {
            count++;
            return true;
        }

    });
}

From source file:org.locationtech.geogig.osm.internal.log.ReadOSMLogEntries.java

@Override
protected List<OSMLogEntry> _call() {
    URL url = command(ResolveOSMLogfile.class).call();
    File file = new File(url.getFile());
    List<OSMLogEntry> entries;
    try {/*from w w  w.  j  a v  a  2 s.  c  o m*/
        synchronized (file.getCanonicalPath().intern()) {
            entries = Files.readLines(file, Charsets.UTF_8, new LineProcessor<List<OSMLogEntry>>() {
                List<OSMLogEntry> entries = Lists.newArrayList();

                @Override
                public List<OSMLogEntry> getResult() {
                    return entries;
                }

                @Override
                public boolean processLine(String s) throws IOException {
                    OSMLogEntry entry = OSMLogEntry.valueOf(s);
                    entries.add(entry);
                    return true;
                }
            });
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    return entries;
}

From source file:com.google.gapid.glviewer.ShaderSource.java

public static Shader loadShader(URL resource) {
    String version = isAtLeastVersion(3, 2) ? VERSION_150 : VERSION_130;
    try {/*  www.j  av  a  2s.  co  m*/
        Source source = Resources.readLines(resource, Charsets.US_ASCII, new LineProcessor<Source>() {
            private static final int MODE_COMMON = 0;
            private static final int MODE_VERTEX = 1;
            private static final int MODE_FRAGMENT = 2;
            private static final String VERTEX_PREAMBLE = "#define varying out\n";
            private static final String FRAGMENT_PREAMBLE = "#define varying in\n";

            private final StringBuilder vertexSource = new StringBuilder(version + VERTEX_PREAMBLE);
            private final StringBuilder fragmentSource = new StringBuilder(version + FRAGMENT_PREAMBLE);

            private int mode = MODE_COMMON;

            @Override
            public boolean processLine(String line) throws IOException {
                line = line.trim();
                if ("//! COMMON".equals(line)) {
                    mode = MODE_COMMON;
                } else if ("//! VERTEX".equals(line)) {
                    mode = MODE_VERTEX;
                } else if ("//! FRAGMENT".equals(line)) {
                    mode = MODE_FRAGMENT;
                } else if (!line.startsWith("//")) {
                    switch (mode) {
                    case MODE_COMMON:
                        vertexSource.append(line).append('\n');
                        fragmentSource.append(line).append('\n');
                        break;
                    case MODE_VERTEX:
                        vertexSource.append(line).append('\n');
                        break;
                    case MODE_FRAGMENT:
                        fragmentSource.append(line).append('\n');
                        break;
                    }
                }
                return true;
            }

            @Override
            public Source getResult() {
                return new Source(vertexSource.toString(), fragmentSource.toString());
            }
        });

        Shader shader = new Shader();
        if (!shader.link(source.vertex, source.fragment)) {
            shader.delete();
            shader = null;
        }
        return shader;
    } catch (IOException e) {
        LOG.log(WARNING, "Failed to load shader source", e);
        return null;
    }
}

From source file:org.geogit.osm.base.ReadOSMLogEntries.java

@Override
public List<OSMLogEntry> call() {
    URL url = command(ResolveOSMLogfile.class).call();
    File file = new File(url.getFile());
    List<OSMLogEntry> entries;
    try {/* w w  w  .ja v a  2s  .  c o  m*/
        synchronized (file.getCanonicalPath().intern()) {
            entries = Files.readLines(file, Charsets.UTF_8, new LineProcessor<List<OSMLogEntry>>() {
                List<OSMLogEntry> entries = Lists.newArrayList();

                @Override
                public List<OSMLogEntry> getResult() {
                    return entries;
                }

                @Override
                public boolean processLine(String s) throws IOException {
                    OSMLogEntry entry = OSMLogEntry.valueOf(s);
                    entries.add(entry);
                    return true;
                }
            });
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    return entries;
}