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

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

Introduction

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

Prototype

public LineReader(Readable readable) 

Source Link

Document

Creates a new instance that will read lines from the given Readable object.

Usage

From source file:com.lyndir.lhunath.masterpassword.CLI.java

public static void main(final String[] args) throws IOException {

    String userName, masterPassword, siteName = null;

    /* Environment. */
    userName = System.getenv().get(ENV_USERNAME);
    masterPassword = System.getenv().get(ENV_PASSWORD);

    /* Arguments. */
    int counter = 1;
    MPElementType type = MPElementType.GeneratedLong;
    boolean typeArg = false, counterArg = false, userNameArg = false;
    for (final String arg : Arrays.asList(args))
        if ("-t".equals(arg) || "--type".equals(arg))
            typeArg = true;/*from   w  ww.  j  av a2  s. c  o  m*/
        else if (typeArg) {
            if ("list".equalsIgnoreCase(arg)) {
                System.out.format("%30s | %s\n", "type", "description");
                for (final MPElementType aType : MPElementType.values())
                    System.out.format("%30s | %s\n", aType.getName(), aType.getDescription());
                System.exit(0);
            }

            type = MPElementType.forName(arg);
            typeArg = false;
        } else if ("-c".equals(arg) || "--counter".equals(arg))
            counterArg = true;
        else if (counterArg) {
            counter = ConversionUtils.toIntegerNN(arg);
            counterArg = false;
        } else if ("-u".equals(arg) || "--username".equals(arg))
            userNameArg = true;
        else if (userNameArg) {
            userName = arg;
            userNameArg = false;
        } else if ("-h".equals(arg) || "--help".equals(arg)) {
            System.out.println();
            System.out.println("\tMaster Password CLI");
            System.out.println("\t\tLyndir");

            System.out.println("[options] [site name]");
            System.out.println();
            System.out.println("Available options:");

            System.out.println("\t-t | --type [site password type]");
            System.out.format("\t\tDefault: %s.  The password type to use for this site.\n", type.getName());
            System.out.println("\t\tUse 'list' to see the available types.");

            System.out.println();
            System.out.println("\t-c | --counter [site counter]");
            System.out.format("\t\tDefault: %d.  The counter to use for this site.\n", counter);
            System.out.println("\t\tIncrement the counter if you need a new password.");

            System.out.println();
            System.out.println("\t-u | --username [user's name]");
            System.out.println("\t\tDefault: asked.  The name of the user.");

            System.out.println();
            System.out.println("Available environment variables:");

            System.out.format("\t%s\n", ENV_USERNAME);
            System.out.println("\t\tThe name of the user.");

            System.out.format("\t%s\n", ENV_PASSWORD);
            System.out.println("\t\tThe master password of the user.");

            System.out.println();
            return;
        } else
            siteName = arg;

    InputStreamReader inReader = new InputStreamReader(System.in);
    try {
        LineReader lineReader = new LineReader(inReader);
        if (siteName == null) {
            System.err.format("Site name: ");
            siteName = lineReader.readLine();
        }
        if (userName == null) {
            System.err.format("User's name: ");
            userName = lineReader.readLine();
        }
        if (masterPassword == null) {
            System.err.format("%s's master password: ", userName);
            masterPassword = lineReader.readLine();
        }

        byte[] masterKey = MasterPassword.keyForPassword(masterPassword, userName);
        String sitePassword = MasterPassword.generateContent(type, siteName, masterKey, counter);
        System.out.println(sitePassword);
    } finally {
        inReader.close();
    }
}

From source file:com.lyndir.masterpassword.CLI.java

public static void main(final String[] args) throws IOException {

    // Read information from the environment.
    char[] masterPassword;
    String siteName = null, context = null;
    String userName = System.getenv(MPConstant.env_userName);
    String siteTypeName = ifNotNullElse(System.getenv(MPConstant.env_siteType), "");
    MPSiteType siteType = siteTypeName.isEmpty() ? MPSiteType.GeneratedLong
            : MPSiteType.forOption(siteTypeName);
    MPSiteVariant variant = MPSiteVariant.Password;
    String siteCounterName = ifNotNullElse(System.getenv(MPConstant.env_siteCounter), "");
    UnsignedInteger siteCounter = siteCounterName.isEmpty() ? UnsignedInteger.valueOf(1)
            : UnsignedInteger.valueOf(siteCounterName);

    // Parse information from option arguments.
    boolean userNameArg = false, typeArg = false, counterArg = false, variantArg = false, contextArg = false;
    for (final String arg : Arrays.asList(args))
        // Full Name
        if ("-u".equals(arg) || "--username".equals(arg))
            userNameArg = true;// ww  w.ja va  2 s.c om
        else if (userNameArg) {
            userName = arg;
            userNameArg = false;
        }

        // Type
        else if ("-t".equals(arg) || "--type".equals(arg))
            typeArg = true;
        else if (typeArg) {
            siteType = MPSiteType.forOption(arg);
            typeArg = false;
        }

        // Counter
        else if ("-c".equals(arg) || "--counter".equals(arg))
            counterArg = true;
        else if (counterArg) {
            siteCounter = UnsignedInteger.valueOf(arg);
            counterArg = false;
        }

        // Variant
        else if ("-v".equals(arg) || "--variant".equals(arg))
            variantArg = true;
        else if (variantArg) {
            variant = MPSiteVariant.forOption(arg);
            variantArg = false;
        }

        // Context
        else if ("-C".equals(arg) || "--context".equals(arg))
            contextArg = true;
        else if (contextArg) {
            context = arg;
            contextArg = false;
        }

        // Help
        else if ("-h".equals(arg) || "--help".equals(arg)) {
            System.out.println();
            System.out.format("Usage: mpw [-u name] [-t type] [-c counter] site\n\n");
            System.out.format("    -u name      Specify the full name of the user.\n");
            System.out.format("                 Defaults to %s in env.\n\n", MPConstant.env_userName);
            System.out.format("    -t type      Specify the password's template.\n");
            System.out.format(
                    "                 Defaults to %s in env or 'long' for password, 'name' for login.\n",
                    MPConstant.env_siteType);

            int optionsLength = 0;
            Map<String, MPSiteType> typeMap = Maps.newLinkedHashMap();
            for (MPSiteType elementType : MPSiteType.values()) {
                String options = Joiner.on(", ").join(elementType.getOptions());
                typeMap.put(options, elementType);
                optionsLength = Math.max(optionsLength, options.length());
            }
            for (Map.Entry<String, MPSiteType> entry : typeMap.entrySet()) {
                String infoString = strf("                  -v %" + optionsLength + "s | ", entry.getKey());
                String infoNewline = "\n" + StringUtils.repeat(" ", infoString.length() - 3) + " | ";
                infoString += entry.getValue().getDescription().replaceAll("\n", infoNewline);
                System.out.println(infoString);
            }
            System.out.println();

            System.out.format("    -c counter   The value of the counter.\n");
            System.out.format("                 Defaults to %s in env or '1'.\n\n", MPConstant.env_siteCounter);
            System.out.format("    -v variant   The kind of content to generate.\n");
            System.out.format("                 Defaults to 'password'.\n");

            optionsLength = 0;
            Map<String, MPSiteVariant> variantMap = Maps.newLinkedHashMap();
            for (MPSiteVariant elementVariant : MPSiteVariant.values()) {
                String options = Joiner.on(", ").join(elementVariant.getOptions());
                variantMap.put(options, elementVariant);
                optionsLength = Math.max(optionsLength, options.length());
            }
            for (Map.Entry<String, MPSiteVariant> entry : variantMap.entrySet()) {
                String infoString = strf("                  -v %" + optionsLength + "s | ", entry.getKey());
                String infoNewline = "\n" + StringUtils.repeat(" ", infoString.length() - 3) + " | ";
                infoString += entry.getValue().getDescription().replaceAll("\n", infoNewline);
                System.out.println(infoString);
            }
            System.out.println();

            System.out.format("    -C context   A variant-specific context.\n");
            System.out.format("                 Defaults to empty.\n");
            for (Map.Entry<String, MPSiteVariant> entry : variantMap.entrySet()) {
                String infoString = strf("                  -v %" + optionsLength + "s | ", entry.getKey());
                String infoNewline = "\n" + StringUtils.repeat(" ", infoString.length() - 3) + " | ";
                infoString += entry.getValue().getContextDescription().replaceAll("\n", infoNewline);
                System.out.println(infoString);
            }
            System.out.println();

            System.out.format("    ENVIRONMENT\n\n");
            System.out.format("        MP_USERNAME    | The full name of the user.\n");
            System.out.format("        MP_SITETYPE    | The default password template.\n");
            System.out.format("        MP_SITECOUNTER | The default counter value.\n\n");
            return;
        } else
            siteName = arg;

    // Read missing information from the console.
    Console console = System.console();
    try (InputStreamReader inReader = new InputStreamReader(System.in)) {
        LineReader lineReader = new LineReader(inReader);

        if (siteName == null) {
            System.err.format("Site name: ");
            siteName = lineReader.readLine();
        }

        if (userName == null) {
            System.err.format("User's name: ");
            userName = lineReader.readLine();
        }

        if (console != null)
            masterPassword = console.readPassword("%s's master password: ", userName);

        else {
            System.err.format("%s's master password: ", userName);
            masterPassword = lineReader.readLine().toCharArray();
        }
    }

    // Encode and write out the site password.
    System.out.println(MasterKey.create(userName, masterPassword).encode(siteName, siteType, siteCounter,
            variant, context));
}

From source file:org.wikimedia.analytics.kraken.pig.LocalWebRequestTestFile.java

public static String[] load(final String fileName) throws IOException {
    InputStream inputStream = ComparePageviewDefinitionsTest.class.getResourceAsStream(fileName);
    InputStreamReader reader = new InputStreamReader(inputStream);
    LineReader lineReader = new LineReader(reader);

    ArrayList<String> logLines = new ArrayList<String>();

    while (true) {
        String logLine = lineReader.readLine();
        if (logLine != null) {
            logLines.add(logLine + "\\n");
        } else {//from ww  w .ja v a 2  s .c  o  m
            break;
        }
    }

    String[] input = new String[logLines.size()];
    return logLines.toArray(input);
}

From source file:net.oneandone.shared.artifactory.model.BomEntry.java

/**
 * Reads all sha1 sum entries from the given input stream.
 *
 * @param in to read from./*from  ww  w . ja  v  a2  s. c om*/
 * @return list of BomEntry.
 * @throws IOException when reading from in does not succeed.
 */
public static List<BomEntry> read(final InputStream in) throws IOException {
    final LineReader lineReader = new LineReader(new InputStreamReader(checkNotNull(in), Charsets.UTF_8));
    final ArrayList<BomEntry> bomEntries = new ArrayList<BomEntry>();
    String readLine = lineReader.readLine();
    while (readLine != null) {
        if (!readLine.startsWith("#")) {
            bomEntries.add(BomEntry.valueOf(readLine));
        }
        readLine = lineReader.readLine();
    }
    return bomEntries;
}

From source file:co.jirm.core.sql.SqlPlaceholderParser.java

private static ParsedSql _parseSql(String sql, SqlPlaceholderParserConfig config) throws IOException {

    StringBuilder sb = new StringBuilder(sql.length());
    LineReader lr = new LineReader(new StringReader(sql));
    String line;/*ww  w. j ava2  s. co  m*/
    ImmutableList.Builder<PlaceHolder> placeHolders = ImmutableList.builder();
    int nameIndex = 0;
    int positionalIndex = 0;
    int position = 0;
    boolean first = true;

    while ((line = lr.readLine()) != null) {
        if (first)
            first = false;
        else if (!config.isStripNewLines())
            sb.append("\n");
        Matcher m = tokenPattern.matcher(line);
        if (m.matches()) {
            String leftHand = m.group(1);
            int start = m.start(1);
            check.state(start == 0, "start should be 0");
            int[] ind = parseForReplacement(leftHand);
            check.state(ind != null, "Problem parsing {}", line);
            String before = leftHand.substring(0, ind[0]);
            String after = leftHand.substring(ind[1], leftHand.length());
            sb.append(before);
            sb.append("?");
            sb.append(after);

            String name = null;
            final PlaceHolder ph;
            if (m.groupCount() == 2 && !(name = nullToEmpty(m.group(2))).isEmpty()) {
                ph = new NamePlaceHolder(position, name, nameIndex);
                ++nameIndex;
            } else {
                ph = new PositionPlaceHolder(position, positionalIndex);
                ++positionalIndex;
            }
            placeHolders.add(ph);
            ++position;
        } else {
            sb.append(line);
        }
    }
    if (sql.endsWith("\r\n") || sql.endsWith("\n") || sql.endsWith("\r")) {
        if (!config.isStripNewLines())
            sb.append("\n");
    }
    return new ParsedSql(config, sql, sb.toString(), placeHolders.build());
}

From source file:rapture.kernel.plugin.SeriesInstaller.java

@Override
public void install(CallingContext ctx, RaptureURI uri, PluginTransportItem item) {
    SeriesApi api = Kernel.getSeries();
    try {//from w  w w .j  ava2s. c  o  m
        LineReader reader = new LineReader(new StringReader(new String(item.getContent(), Charsets.UTF_8)));
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            String part[] = line.split(",", 2);
            if (part.length != 2) {
                throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                        "Malformed Series Descption: " + uri);
            }
            String column = part[0];
            String val = part[1];
            // TODO MEL find a way to bypass the wrapper so we don't reparse
            // URI and entitle/audit each point
            if (val.startsWith("'")) {
                api.addStringToSeries(ctx, uri.toString(), column, val.substring(1));
            } else if (val.startsWith("{")) {
                api.addStructureToSeries(ctx, uri.toString(), column, val);
            } else if (val.contains(".")) {
                api.addDoubleToSeries(ctx, uri.toString(), column, Double.parseDouble(val));
            } else {
                api.addLongToSeries(ctx, uri.toString(), column, Long.parseLong(val));
            }
        }
    } catch (IOException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                "Error installing series at uri " + uri.toString(), e);
    }
}

From source file:com.sindicetech.siren.demo.ncpr.DatatypeConverter.java

public void process() throws IOException {
    final FileReader fileReader = new FileReader(new File(INPUT_FILE));
    final LineReader reader = new LineReader(fileReader);
    try {/*from w  w  w.  j a v  a 2  s.co  m*/
        JsonNode obj;
        String line;
        while ((line = reader.readLine()) != null) {
            obj = mapper.readTree(line);
            this.convertRatedOutputCurrent(obj);
            this.convertRatedOutputVoltage(obj);
            this.convertRatedOutputkW(obj);
            this.convertLatitude(obj);
            this.convertLongitude(obj);
            this.convertTetheredCable(obj);
            this.convertChargeMode(obj);
            this.convertDeviceControllerWebsite(obj);
            this.convertDeviceOwnerWebsite(obj);
            generator.writeTree(obj);
            generator.writeRaw('\n');
        }
    } finally {
        fileReader.close();
    }
}

From source file:com.palantir.stash.stashbot.outputhandler.CommandOutputHandlerFactory.java

public CommandOutputHandler<Object> getRevlistOutputHandler() {
    return new CommandOutputHandler<Object>() {

        private ArrayList<String> changesets;
        private LineReader lr;
        private boolean processed = false;

        @Override//from  ww w.  j  a v a 2 s. c o m
        public void complete() throws ProcessException {
        }

        @Override
        public void setWatchdog(Watchdog watchdog) {
        }

        @Override
        public Object getOutput() {
            if (processed == false) {
                throw new IllegalStateException("getOutput() called before process()");
            }
            return ImmutableList.copyOf(changesets).reverse();
        }

        @Override
        public void process(InputStream output) throws ProcessException {
            processed = true;
            if (changesets == null) {
                changesets = new ArrayList<String>();
                lr = new LineReader(new InputStreamReader(output));
            }

            String sha1 = "";
            while (sha1 != null) {
                try {
                    sha1 = lr.readLine();
                } catch (IOException e) {
                    // dear god, why is this happening?
                    throw new RuntimeException(e);
                }
                if (sha1 != null && sha1.matches("[0-9a-fA-F]{40}")) {
                    changesets.add(sha1);
                }
            }
        }
    };
}

From source file:org.sindice.siren.demo.ncpr.NCPRIndexer.java

/**
 * Reads and parses the input file line by line. Each line is expected to be a
 * serialised JSON object. It creates a {@link SolrInputDocument} for each
 * JSON object, add it to the index, and commit the documents at the end of
 * the process./*from w w  w.  j  ava  2s  . c o  m*/
 */
public void index(final File input) throws IOException, SolrServerException {
    logger.info("Loading JSON objects from {}", input);
    final LineReader reader = new LineReader(new FileReader(input));

    int counter = 0;
    String line;
    while ((line = reader.readLine()) != null) {
        server.add(this.parseObject(line));
        counter++;
    }
    server.commit();
    logger.info("Loaded {} JSON objects", counter);
}

From source file:com.compomics.colims.core.io.headers.ProteinGroupHeaders.java

/**
 * Parse a TSV file and create a map for each line that maps the keys found on the first line to the values found to
 * the values found on lines two and further until the end of the file.
 *
 * @param tsvFile tab separated values file
 * @throws IOException//  ww  w  .  jav a  2  s  . c om
 */
private void readFileHeaders(final File tsvFile) throws IOException {
    headersInProteinGroupFile = new ArrayList<>();
    fileReader = new FileReader(tsvFile);
    lineReader = new LineReader(fileReader);

    String firstLine = lineReader.readLine();

    if (firstLine == null || firstLine.isEmpty()) {
        throw new IOException("Input file " + tsvFile.getPath() + " is empty.");
    } else {
        String[] headers = firstLine.toLowerCase(Locale.US).split("" + DELIMITER);
        Arrays.stream(headers).forEach(e -> headersInProteinGroupFile.add(e));
    }
}