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

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

Introduction

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

Prototype

public String readLine() throws IOException 

Source Link

Document

Reads a line of text.

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;/*  w  w  w  .  j a v a 2  s .  com*/
        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;/*from w w w . j  a va2  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  a2  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./* ww w  . j a v  a 2s.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:com.thinkbiganalytics.util.ColumnSpec.java

/**
 * Method  for defining a column specification as a pipe-delimited format:  column|data type|comment (optional)|pk|created|modified. Each row separated by a newline
 *//*from   w  w  w. j  av  a  2  s.c  o m*/
public static ColumnSpec[] createFromString(String specString) {
    if (StringUtils.isEmpty(specString)) {
        return null;
    }
    List<ColumnSpec> specs = new Vector<>();
    try {
        LineReader lineReader = new LineReader(new StringReader(specString));

        String line;
        while ((line = lineReader.readLine()) != null) {
            String[] parts = line.split("\\|");
            int len = parts.length;
            if (len > 0) {
                String columnName = "";
                String comment = "";
                String dataType = "string";
                boolean pk = false;
                boolean modifiedDt = false;
                boolean createDt = false;
                String otherName = "";
                switch (len) {
                default:
                case 7:
                    otherName = parts[6];
                case 6:
                    modifiedDt = "1".equals(parts[5].trim());
                case 5:
                    createDt = "1".equals(parts[4].trim());
                case 4:
                    pk = "1".equals(parts[3].trim());
                case 3:
                    comment = parts[2];
                case 2:
                    dataType = parts[1];
                case 1:
                    columnName = parts[0];
                }
                specs.add(new ColumnSpec(columnName, dataType, comment, pk, createDt, modifiedDt, otherName));
            }
        }
        return specs.toArray(new ColumnSpec[0]);
    } catch (IOException e) {
        throw new RuntimeException("Failed to parse column specs[" + specString + "]", e);
    }

}

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;//  w w w. j a v a  2s.  c  o  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: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  ww  . j  av a 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: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 av a  2  s . 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.axelor.meta.loader.DataLoader.java

private boolean isConfig(File file, Pattern pattern) {
    try {/*from  w  w w. j ava2  s .  c o m*/
        Reader reader = new FileReader(file);
        LineReader lines = new LineReader(reader);
        String line = null;
        while ((line = lines.readLine()) != null) {
            if (pattern.matcher(line).find()) {
                return true;
            }
        }
        reader.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    return false;
}

From source file:org.apache.maven.plugins.shade.resource.ServicesResourceTransformer.java

public void processResource(String resource, InputStream is, final List<Relocator> relocators)
        throws IOException {
    ServiceStream out = serviceEntries.get(resource);
    if (out == null) {
        out = new ServiceStream();
        serviceEntries.put(resource, out);
    }// w  w w  .  j  ava2  s.  c o m

    final ServiceStream fout = out;

    final String content = IOUtils.toString(is);
    StringReader reader = new StringReader(content);
    LineReader lineReader = new LineReader(reader);
    String line;
    while ((line = lineReader.readLine()) != null) {
        String relContent = line;
        for (Relocator relocator : relocators) {
            if (relocator.canRelocateClass(relContent)) {
                relContent = relocator.applyToSourceContent(relContent);
            }
        }
        fout.append(relContent + "\n");
    }

    if (this.relocators == null) {
        this.relocators = relocators;
    }
}