Example usage for java.util Scanner hasNextLine

List of usage examples for java.util Scanner hasNextLine

Introduction

In this page you can find the example usage for java.util Scanner hasNextLine.

Prototype

public boolean hasNextLine() 

Source Link

Document

Returns true if there is another line in the input of this scanner.

Usage

From source file:org.apache.asterix.experiment.builder.AbstractLSMBaseExperimentBuilder.java

protected Map<String, List<String>> readDatagenPairs(Path p) throws IOException {
    Map<String, List<String>> dgenPairs = new HashMap<>();
    Scanner s = new Scanner(p, StandardCharsets.UTF_8.name());
    try {/*from  w  w w . j a va 2 s.  co  m*/
        while (s.hasNextLine()) {
            String line = s.nextLine();
            String[] pair = line.split("\\s+");
            List<String> vals = dgenPairs.get(pair[0]);
            if (vals == null) {
                vals = new ArrayList<>();
                dgenPairs.put(pair[0], vals);
            }
            vals.add(pair[1]);
        }
    } finally {
        s.close();
    }
    return dgenPairs;
}

From source file:org.openinfinity.sso.common.ss.sp.SpringAuthenticationMessageConverter.java

@Override
protected Authentication readInternal(Class<? extends Authentication> clazz, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {
    String resultString = stringHttpMessageConverter.read(String.class, inputMessage);
    Scanner resultScanner = new Scanner(resultString);
    Map<String, String> properties = new HashMap<String, String>();
    Collection<GrantedAuthorityImpl> authorities = new HashSet<GrantedAuthorityImpl>();
    String name = null, attributeName = null;
    boolean collectingAttributeValues = false;
    while (resultScanner.hasNextLine()) {
        String resultLine = resultScanner.nextLine();
        if (collectingAttributeValues && !resultLine.startsWith("userdetails.attribute.value")) {
            collectingAttributeValues = false;
        }/*from  w ww  .j  a v a2 s.c o  m*/
        if (resultLine.startsWith("userdetails.token.id")) {
            properties.put(SSO_TOKEN_ID_KEY, valueFrom(resultLine));
        } else if (resultLine.startsWith("userdetails.attribute.name")) {
            attributeName = valueFrom(resultLine);
            collectingAttributeValues = true;
        } else if (collectingAttributeValues && resultLine.startsWith("userdetails.attribute.value")) {
            String value = valueFrom(resultLine);
            if (attributeName.equals("memberof")) {
                authorities.add(new GrantedAuthorityImpl(value));
            } else {
                if (attributeName.equals("screenname")) {
                    name = value;
                }
                properties.put(attributeName, value);
            }
        }
    }

    return new PreAuthenticatedAuthenticationToken(new User(name, properties), properties.get(SSO_TOKEN_ID_KEY),
            authorities);
}

From source file:com.alibaba.dubbo.qos.textui.TTree.java

@Override
public String rendering() {

    final StringBuilder treeSB = new StringBuilder();
    recursive(0, true, "", root, new Callback() {

        @Override/*from  w w w .j ava 2  s.  c o m*/
        public void callback(int deep, boolean isLast, String prefix, Node node) {

            final boolean hasChild = !node.children.isEmpty();
            final String stepString = isLast ? STEP_FIRST_CHAR : STEP_NORMAL_CHAR;
            final int stepStringLength = StringUtils.length(stepString);
            treeSB.append(prefix).append(stepString);

            int costPrefixLength = 0;
            if (hasChild) {
                treeSB.append("+");
            }
            if (isPrintCost && !node.isRoot()) {
                final String costPrefix = String.format("[%s,%sms]", (node.endTimestamp - root.beginTimestamp),
                        (node.endTimestamp - node.beginTimestamp));
                costPrefixLength = StringUtils.length(costPrefix);
                treeSB.append(costPrefix);
            }

            final Scanner scanner = new Scanner(new StringReader(node.data.toString()));
            try {
                boolean isFirst = true;
                while (scanner.hasNextLine()) {
                    if (isFirst) {
                        treeSB.append(scanner.nextLine()).append("\n");
                        isFirst = false;
                    } else {
                        treeSB.append(prefix).append(repeat(' ', stepStringLength))
                                .append(hasChild ? "|" : EMPTY).append(repeat(' ', costPrefixLength))
                                .append(scanner.nextLine()).append("\n");
                    }
                }
            } finally {
                scanner.close();
            }

        }

    });

    return treeSB.toString();
}

From source file:edu.harvard.med.iccbl.screensaver.io.users.UserAgreementExpirationUpdater.java

/**
 * Return the subject first and the message second.
 * Message://from ww w . j a  v a  2s .  c  om
 * {0} Expiration Date
 * 
 * @throws MessagingException
 */
private Pair<String, String> getExpireNotificationSubjectMessage() throws MessagingException {
    InputStream in = null;
    if (isCommandLineFlagSet(EXPIRATION_EMAIL_MESSAGE_LOCATION[SHORT_OPTION_INDEX])) {
        try {
            in = new FileInputStream(
                    new File(getCommandLineOptionValue(EXPIRATION_EMAIL_MESSAGE_LOCATION[SHORT_OPTION_INDEX])));
        } catch (FileNotFoundException e) {
            sendErrorMail(
                    "Operation not completed for UserAgreementExpirationUpdater, could not locate expiration message",
                    toString(), e);
            throw new DAOTransactionRollbackException(e);
        }
    } else {
        in = this.getClass().getResourceAsStream(EXPIRATION_MESSAGE_TXT_LOCATION);
    }
    Scanner scanner = new Scanner(in);
    try {
        StringBuilder builder = new StringBuilder();
        String subject = scanner.nextLine();
        while (scanner.hasNextLine()) {
            builder.append(scanner.nextLine()).append("\n");
        }
        return Pair.newPair(subject, builder.toString());
    } finally {
        scanner.close();
    }
}

From source file:org.apache.camel.dataformat.bindy.fixed.BindyFixedLengthDataFormat.java

public Object unmarshal(Exchange exchange, InputStream inputStream) throws Exception {
    BindyFixedLengthFactory factory = getFactory(exchange.getContext().getPackageScanClassResolver());
    ObjectHelper.notNull(factory, "not instantiated");

    // List of Pojos
    List<Map<String, Object>> models = new ArrayList<Map<String, Object>>();

    // Pojos of the model
    Map<String, Object> model;

    InputStreamReader in = new InputStreamReader(inputStream);

    // Scanner is used to read big file
    Scanner scanner = new Scanner(in);

    int count = 0;

    try {//from  ww w  . j  ava2s  .  c  om

        // TODO Test if we have a Header
        // TODO Test if we have a Footer (containing by example checksum)

        while (scanner.hasNextLine()) {
            String line;

            // Read the line (should not trim as its fixed length)
            line = scanner.nextLine();

            if (ObjectHelper.isEmpty(line)) {
                // skip if line is empty
                continue;
            }

            // Increment counter
            count++;

            // Check if the record length corresponds to the parameter
            // provided in the @FixedLengthRecord
            if ((line.length() < factory.recordLength()) || (line.length() > factory.recordLength())) {
                throw new java.lang.IllegalArgumentException("Size of the record : " + line.length()
                        + " is not equal to the value provided in the model : " + factory.recordLength()
                        + " !");
            }

            // Create POJO where Fixed data will be stored
            model = factory.factory();

            // Bind data from Fixed record with model classes
            factory.bind(line, model, count);

            // Link objects together
            factory.link(model);

            // Add objects graph to the list
            models.add(model);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Graph of objects created : " + model);
            }

        }

        // Test if models list is empty or not
        // If this is the case (correspond to an empty stream, ...)
        if (models.size() == 0) {
            throw new java.lang.IllegalArgumentException("No records have been defined in the message !");
        } else {
            return models;
        }

    } finally {
        scanner.close();
        IOHelper.close(in, "in", LOG);
    }

}

From source file:com.searchcode.app.util.Helpers.java

/**
 * Reads a certain amount of lines deep into a file to save on memory
 *//*from   www .jav  a  2  s .  co  m*/
public List<String> readFileLines(String filePath, int maxFileLineDepth) throws FileNotFoundException {
    List<String> lines = new ArrayList<>();
    Scanner scanner = null;
    int counter = 0;

    try {
        scanner = new Scanner(new File(filePath));

        while (scanner.hasNextLine() && counter < maxFileLineDepth) {
            lines.add(scanner.nextLine());
            counter++;
        }
    } finally {
        IOUtils.closeQuietly(scanner);
    }

    return lines;
}

From source file:org.elasticsearch.hadoop.integration.rest.AbstractRestSaveTest.java

@Test
public void testBulkWrite() throws Exception {
    TestSettings testSettings = new TestSettings("rest/savebulk");
    //testSettings.setPort(9200)
    testSettings.setProperty(ConfigurationOptions.ES_SERIALIZATION_WRITER_VALUE_CLASS,
            JdkValueWriter.class.getName());
    RestRepository client = new RestRepository(testSettings);

    Scanner in = new Scanner(getClass().getResourceAsStream("/artists.dat")).useDelimiter("\\n|\\t");

    Map<String, String> line = new LinkedHashMap<String, String>();

    for (; in.hasNextLine();) {
        // ignore number
        in.next();/* w  ww.  j  av a 2  s .co  m*/
        line.put("name", in.next());
        line.put("url", in.next());
        line.put("picture", in.next());
        client.writeToIndex(line);
        line.clear();
    }

    client.close();
}

From source file:com.gitblit.HtpasswdUserService.java

/**
 * Reads the realm file and rebuilds the in-memory lookup tables.
 *//*from w ww  . j av  a  2 s  .c  o m*/
protected synchronized void read() {

    // This is done in two steps in order to avoid calling GitBlit.getFileOrFolder(String, String) which will segfault for unit tests.
    String file = settings.getString(KEY_HTPASSWD_FILE, DEFAULT_HTPASSWD_FILE);
    if (!file.equals(htpasswdFilePath)) {
        // The htpasswd file setting changed. Rediscover the file.
        this.htpasswdFilePath = file;
        this.htpasswdFile = GitBlit.getFileOrFolder(file);
        this.htUsers.clear();
        this.forceReload = true;
    }

    if (htpasswdFile.exists() && (forceReload || (htpasswdFile.lastModified() != lastModified))) {
        forceReload = false;
        lastModified = htpasswdFile.lastModified();
        htUsers.clear();

        Pattern entry = Pattern.compile("^([^:]+):(.+)");

        Scanner scanner = null;
        try {
            scanner = new Scanner(new FileInputStream(htpasswdFile));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine().trim();
                if (!line.isEmpty() && !line.startsWith("#")) {
                    Matcher m = entry.matcher(line);
                    if (m.matches()) {
                        htUsers.put(m.group(1), m.group(2));
                    }
                }
            }
        } catch (Exception e) {
            logger.error(MessageFormat.format("Failed to read {0}", htpasswdFile), e);
        } finally {
            if (scanner != null)
                scanner.close();
        }
    }
}

From source file:com.medigy.persist.model.data.EntitySeedDataPopulator.java

/**
* Loads the reference data contained in separate data files
*/// w  w  w  .  j a v a2  s. c o m
protected void loadExternalReferenceData() {
    try {
        InputStream propertyFileStream = Environment.class.getResourceAsStream(EXTERNAL_DATA_PROPERTY_FILE);
        if (propertyFileStream == null)
            propertyFileStream = Thread.currentThread().getContextClassLoader()
                    .getResourceAsStream(EXTERNAL_DATA_PROPERTY_FILE);
        if (propertyFileStream == null) {
            log.warn("'" + EXTERNAL_DATA_PROPERTY_FILE
                    + "' property file not found for loading reference data contained " + "in external files.");
            return;
        }
        Properties props = new java.util.Properties();
        props.load(propertyFileStream);

        final Enumeration keys = props.keys();
        while (keys.hasMoreElements()) {
            final String className = (String) keys.nextElement();
            final String dataFileName = props.getProperty(className);
            InputStream stream = Environment.class.getResourceAsStream(dataFileName);
            if (stream == null)
                stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(dataFileName);
            Scanner sc = new Scanner(stream);
            int rowsAdded = 0;
            if (sc.hasNextLine()) {
                sc.findInLine(
                        "\\\"([ \\.0-9a-zA-Z]*)\\\"\\s*\\\"([ \\.0-9a-zA-Z]*)\\\"\\s*\\\"([ \\.0-9a-zA-Z]*)\\\"\\s*\\\"([ \\.0-9a-zA-Z]*)\\\"");
                try {
                    MatchResult result = sc.match();
                    final Class refClass = Class.forName(className);
                    final Object refObject = refClass.newInstance();
                    if (refObject instanceof AbstractReferenceEntity) {
                        final AbstractReferenceEntity refEntity = (AbstractReferenceEntity) refObject;
                        refEntity.setCode(result.group(0));
                        refEntity.setLabel(result.group(1));
                        refEntity.setDescription(result.group(2));
                        HibernateUtil.getSession().save(refEntity);
                        rowsAdded++;
                    }
                } catch (Exception e) {
                    log.error(className + ": Error at data row count = " + rowsAdded + " \n"
                            + ExceptionUtils.getStackTrace(e));
                }
            }
            sc.close();
            log.info(className + ", Rows Added = " + rowsAdded);
        }
        //InputStream stream = new FileInputStream("e:\\netspective\\medigy\\persistence\\database\\refdata\\icd9-codes.txt");
    } catch (Exception e) {
        log.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:me.mast3rplan.phantombot.HTTPResponse.java

HTTPResponse(String address, String request) throws IOException {

    Socket sock = new Socket(address, 80);
    Writer output = new StringWriter();
    IOUtils.write(request, sock.getOutputStream(), "utf-8");
    IOUtils.copy(sock.getInputStream(), output);
    com.gmt2001.Console.out.println(output.toString());
    Scanner scan = new Scanner(sock.getInputStream());
    String errorLine = scan.nextLine();
    for (String line = scan.nextLine(); !line.equals(""); line = scan.nextLine()) {
        String[] keyval = line.split(":", 2);
        if (keyval.length == 2) {
            values.put(keyval[0], keyval[1].trim());
        } else {//from  ww w  .j  av a  2  s . c o  m
            //?
        }
    }
    while (scan.hasNextLine()) {
        body += scan.nextLine();
    }
    sock.close();

}