Example usage for java.util Scanner nextLine

List of usage examples for java.util Scanner nextLine

Introduction

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

Prototype

public String nextLine() 

Source Link

Document

Advances this scanner past the current line and returns the input that was skipped.

Usage

From source file:com.continuent.tungsten.common.security.KeystoreManagerCtrl.java

/**
 * Reads user input from stdin// w  ww.  j a  va2  s .c  om
 * 
 * @param listPrompts list of prompts to display, asking for user input
 * @return a list containing user inputs
 */
private List<String> getUserInputFromStdin(List<String> listPrompts) {
    List<String> listUserInput = new ArrayList<String>();

    Scanner console = new Scanner(System.in);
    Scanner lineTokenizer = null;

    for (String prompt : listPrompts) {
        System.out.println(prompt);

        try {
            lineTokenizer = new Scanner(console.nextLine());
        } catch (NoSuchElementException nse) {
            console.close();
            throw new NoSuchElementException(MessageFormat.format("Missing user input=  {0}", prompt));
        }

        if (lineTokenizer.hasNext()) {
            String userInput = lineTokenizer.next();
            listUserInput.add(userInput);
        }
    }

    console.close();
    return listUserInput;
}

From source file:de.betterform.agent.web.resources.ResourceServlet.java

private long getLastModifiedValue() {
    if (this.lastModified == 0) {
        long bfTimestamp;
        try {//from  w  w  w. jav a  2 s  .  co m
            String path = WebFactory.getRealPath("/WEB-INF/betterform-version.info", this.getServletContext());
            StringBuilder versionInfo = new StringBuilder();
            String NL = System.getProperty("line.separator");
            Scanner scanner = new Scanner(new FileInputStream(path), "UTF-8");
            try {
                while (scanner.hasNextLine()) {
                    versionInfo.append(scanner.nextLine() + NL);
                }
            } finally {
                scanner.close();
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("VersionInfo: " + versionInfo);
            }
            // String APP_NAME = APP_INFO.substring(0, APP_INFO.indexOf(" "));
            // String APP_VERSION = APP_INFO.substring(APP_INFO.indexOf(" ") + 1, APP_INFO.indexOf("-") - 1);
            String timestamp = versionInfo.substring(versionInfo.indexOf("Timestamp:") + 10,
                    versionInfo.length());
            String df = "yyyy-MM-dd HH:mm:ss";
            SimpleDateFormat sdf = new SimpleDateFormat(df);
            Date date = sdf.parse(timestamp);
            bfTimestamp = date.getTime();
        } catch (Exception e) {
            LOG.error("Error setting HTTP Header 'Last Modified', could not parse the given date.");
            bfTimestamp = 0;
        }
        this.lastModified = bfTimestamp;
    }
    return lastModified;
}

From source file:com.joliciel.jochre.search.JochreQueryImpl.java

public JochreQueryImpl(Map<String, String> argMap) {
    try {//ww w . j a  v a  2s. c om
        for (Entry<String, String> argEntry : argMap.entrySet()) {
            String argName = argEntry.getKey();
            String argValue = argEntry.getValue();
            if (argName.equalsIgnoreCase("query")) {
                this.setQueryString(argValue);
            } else if (argName.equalsIgnoreCase("queryFile")) {
                File queryFile = new File(argValue);
                Scanner scanner = new Scanner(
                        new BufferedReader(new InputStreamReader(new FileInputStream(queryFile), "UTF-8")));
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine();
                    this.setQueryString(line);
                    break;
                }
                scanner.close();
            } else if (argName.equalsIgnoreCase("maxDocs")) {
                int maxDocs = Integer.parseInt(argValue);
                this.setMaxDocs(maxDocs);
            } else if (argName.equalsIgnoreCase("decimalPlaces")) {
                int decimalPlaces = Integer.parseInt(argValue);
                this.setDecimalPlaces(decimalPlaces);
            } else if (argName.equalsIgnoreCase("lang")) {
                this.setLanguage(argValue);
            } else if (argName.equalsIgnoreCase("filter")) {
                if (argValue.length() > 0) {
                    String[] idArray = argValue.split(",");
                    this.setDocFilter(idArray);
                }
            } else if (argName.equalsIgnoreCase("filterField")) {
                if (argValue.length() > 0)
                    this.setFilterField(argValue);
            } else {
                LOG.trace("JochreQuery unknown option: " + argName);
            }
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.joliciel.talismane.machineLearning.AbstractMachineLearningModel.java

public boolean loadZipEntry(ZipInputStream zis, ZipEntry ze) throws IOException {
    boolean loaded = true;
    if (ze.getName().equals("model.bin")) {
        this.loadModelFromStream(zis);
    } else if (ze.getName().equals("externalResources.obj")) {
        ObjectInputStream in = new ObjectInputStream(zis);
        try {/* www  . j a  va 2 s  . c  o m*/
            @SuppressWarnings("unchecked")
            List<ExternalResource<?>> externalResources = (List<ExternalResource<?>>) in.readObject();
            this.setExternalResources(externalResources);
        } catch (ClassNotFoundException e) {
            LogUtils.logError(LOG, e);
            throw new RuntimeException(e);
        }
    } else if (ze.getName().endsWith("_descriptors.txt")) {
        String key = ze.getName().substring(0, ze.getName().length() - "_descriptors.txt".length());
        Scanner scanner = new Scanner(zis, "UTF-8");
        List<String> descriptorList = new ArrayList<String>();
        while (scanner.hasNextLine()) {
            String descriptor = scanner.nextLine();
            descriptorList.add(descriptor);
        }
        this.getDescriptors().put(key, descriptorList);
    } else if (ze.getName().endsWith("_dependency.obj")) {
        String key = ze.getName().substring(0, ze.getName().length() - "_dependency.obj".length());
        ObjectInputStream in = new ObjectInputStream(zis);
        try {
            Object dependency = in.readObject();
            this.dependencies.put(key, dependency);
        } catch (ClassNotFoundException e) {
            LogUtils.logError(LOG, e);
            throw new RuntimeException(e);
        }
    } else if (ze.getName().equals("attributes.txt")) {
        Scanner scanner = new Scanner(zis, "UTF-8");
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.length() > 0) {
                String[] parts = line.split("\t");
                String name = parts[0];
                String value = "";
                if (parts.length > 1)
                    value = parts[1];
                this.addModelAttribute(name, value);
            }
        }
    } else {
        loaded = this.loadDataFromStream(zis, ze);
    }
    return loaded;
}

From source file:carmen.demo.LocationResolverStatsDemo.java

private void run(String inputFile, String outputFile) throws FileNotFoundException, IOException {
    Writer output = null;/*from   w ww . j a v a  2 s. c o m*/
    if (outputFile != null)
        output = Utils.createWriter(outputFile);

    HashMap<ResolutionMethod, Integer> resolutionMethodCounts = new HashMap<ResolutionMethod, Integer>();

    int numCity = 0;
    int numCounty = 0;
    int numState = 0;
    int numCountry = 0;

    int hasPlace = 0;
    int hasCoordinate = 0;
    int hasCoordinate2 = 0;
    int hasGeo = 0;
    int hasUserProfile = 0;

    Scanner scanner = Utils.createScanner(inputFile);

    ObjectMapper mapper = new ObjectMapper();
    int numResolved = 0;
    int total = 0;
    int skipped = 0;
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();

        HashMap<String, Object> tweet = null;

        try {
            @SuppressWarnings("unchecked")
            HashMap<String, Object> readValue = (HashMap<String, Object>) mapper.readValue(line, Map.class);
            tweet = readValue;
        } catch (com.fasterxml.jackson.core.JsonParseException exception) {
            logger.warn("Skipping bad tweet: " + line);
            skipped++;
            continue;
        } catch (com.fasterxml.jackson.databind.JsonMappingException exception) {
            logger.warn("Skipping bad tweet: " + line);
            skipped++;
            continue;
        }
        Map<String, Object> place = Utils.getPlaceFromTweet(tweet);
        if (place != null && place.size() > 0)
            hasPlace++;
        LatLng latLng = Utils.getLatLngFromTweet(tweet);
        if (latLng != null)
            hasCoordinate++;
        if (tweet.get("coordinates") != null)
            hasCoordinate2++;
        if (tweet.get("geo") != null)
            hasGeo++;

        String tweet_location = Utils.getLocationFromTweet(tweet);
        if (tweet_location != null && tweet_location.length() != 0) {
            hasUserProfile++;
        }

        total++;

        if (total % 10000 == 0) {
            logger.info(total + "\r");
        }
        Location resolvedLocation = this._locationResolver.resolveLocationFromTweet(tweet);

        if (resolvedLocation != null && !resolvedLocation.isNone()) {
            tweet.put(Constants.TWEET_USER_LOCATION, Location.createJsonFromLocation(resolvedLocation));

            numResolved++;
            ResolutionMethod resolutionMethod = resolvedLocation.getResolutionMethod();
            if (!resolutionMethodCounts.containsKey(resolutionMethod))
                resolutionMethodCounts.put(resolutionMethod, 0);
            resolutionMethodCounts.put(resolutionMethod, resolutionMethodCounts.get(resolutionMethod) + 1);

            // What resolution is this location?
            if (resolvedLocation.getCity() != null) {
                numCity++;
            } else if (resolvedLocation.getCounty() != null) {
                numCounty++;
            } else if (resolvedLocation.getState() != null) {
                numState++;
            } else if (resolvedLocation.getCountry() != null) {
                numCountry++;
            }
        }
        if (output != null) {
            String outputString = mapper.writeValueAsString(tweet);
            output.write(outputString);
            output.write("\n");
        }

    }
    if (output != null)
        output.close();

    scanner.close();
    logger.info("Total: " + total);
    logger.info("Resolved: " + numResolved);
    logger.info("Skipped (not included in total): " + skipped);

    logger.info("Has Place:" + hasPlace);
    logger.info("Has Coordinate: " + hasCoordinate);
    logger.info("Has Coordinate2: " + hasCoordinate2);
    logger.info("Has UserProfile: " + hasUserProfile);
    logger.info("Has Geo: " + hasGeo);

    logger.info("Num city: " + numCity);
    logger.info("Num county: " + numCounty);
    logger.info("Num state: " + numState);
    logger.info("Num country: " + numCountry);

    for (ResolutionMethod method : resolutionMethodCounts.keySet()) {
        int count = resolutionMethodCounts.get(method);
        logger.info(method + "\t" + count);
    }

}

From source file:org.apache.streams.rss.test.SyndEntryActivitySerizlizerTest.java

@Test
public void testJsonData() throws Exception {
    Scanner scanner = new Scanner(this.getClass().getResourceAsStream("/TestSyndEntryJson.txt"));
    List<Activity> activities = Lists.newLinkedList();
    List<ObjectNode> objects = Lists.newLinkedList();

    SyndEntryActivitySerializer serializer = new SyndEntryActivitySerializer();

    while (scanner.hasNext()) {
        String line = scanner.nextLine();
        System.out.println(line);
        ObjectNode node = (ObjectNode) mapper.readTree(line);

        objects.add(node);/* www  .  j  a v a2 s  .c  o  m*/
        activities.add(serializer.deserialize(node));
    }

    assertEquals(11, activities.size());

    for (int x = 0; x < activities.size(); x++) {
        ObjectNode n = objects.get(x);
        Activity a = activities.get(x);

        testActor(n.get("author").asText(), a.getActor());
        testAuthor(n.get("author").asText(), a.getObject().getAuthor());
        testProvider("id:providers:rss", "RSS", a.getProvider());
        testProviderUrl(a.getProvider());
        testVerb("post", a.getVerb());
        testPublished(n.get("publishedDate").asText(), a.getPublished());
        testUrl(n.get("uri").asText(), n.get("link").asText(), a);
    }
}

From source file:eu.creatingfuture.propeller.blocklyprop.propellent.Propellent.java

public List<String> getPorts() {
    List<String> ports = new ArrayList<>();
    try {//  w  w w .  ja v  a2 s .  c  om
        CommandLine cmdLine = new CommandLine("propellent/Propellent.exe");
        cmdLine.addArgument("/id");
        cmdLine.addArgument("/gui").addArgument("OFF");
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValues(new int[] { 451, 301 });

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        try {
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            //   exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            return ports;
        }

        output = outputStream.toString();

        // 301 = None found
        // 451 = Chip found
        if (exitValue == 301) {
            return ports;
        }

        //            System.out.println("output: " + output);
        Scanner scanner = new Scanner(output);

        Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?");
        Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$");
        while (scanner.hasNextLine()) {
            String portLine = scanner.nextLine();
            if (chipFoundPattern.matcher(portLine).matches()) {
                Matcher portMatch = pattern.matcher(portLine);
                if (portMatch.find()) {
                    String port = portMatch.group("comport");
                    ports.add(port);
                }
            }
        }

        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        return ports;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        return null;
    }
}

From source file:eu.creatingfuture.propeller.webLoader.propellent.Propellent.java

public List<String> getPorts() {
    List<String> ports = new ArrayList<String>();
    try {/* w  w  w . j a va2 s. c  o m*/
        CommandLine cmdLine = new CommandLine("propellent/Propellent.exe");
        cmdLine.addArgument("/id");
        cmdLine.addArgument("/gui").addArgument("OFF");
        DefaultExecutor executor = new DefaultExecutor();
        executor.setExitValues(new int[] { 451, 301 });

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);

        try {
            exitValue = executor.execute(cmdLine);
        } catch (ExecuteException ee) {
            //   exitValue = ee.getExitValue();
            logger.log(Level.SEVERE, "Unexpected exit value: {0}", exitValue);
            return ports;
        }

        output = outputStream.toString();

        // 301 = None found
        // 451 = Chip found
        if (exitValue == 301) {
            return ports;
        }

        //            System.out.println("output: " + output);
        Scanner scanner = new Scanner(output);

        Pattern chipFoundPattern = Pattern.compile(".*?(EVT:505).*?");
        Pattern pattern = Pattern.compile(".*?found on (?<comport>[a-zA-Z0-9]*).$");
        while (scanner.hasNextLine()) {
            String portLine = scanner.nextLine();
            if (chipFoundPattern.matcher(portLine).matches()) {
                Matcher portMatch = pattern.matcher(portLine);
                if (portMatch.find()) {
                    String port = portMatch.group("comport");
                    ports.add(port);
                }
            }
        }

        //            System.out.println("output: " + output);
        //            System.out.println("exitValue: " + exitValue);
        return ports;
    } catch (IOException ioe) {
        logger.log(Level.SEVERE, null, ioe);
        return null;
    }
}

From source file:com.joliciel.talismane.extensions.standoff.ConllFileSplitter.java

/**
 * @param args/*w  w w  .  jav a  2s  .c  o m*/
 * @throws IOException 
 * @throws UnsupportedEncodingException 
 */
public void split(String filePath, int startIndex, int sentencesPerFile, String encoding) {
    try {
        String fileBase = filePath;
        if (filePath.indexOf('.') > 0)
            fileBase = filePath.substring(0, filePath.lastIndexOf('.'));
        File file = new File(filePath);
        Scanner scanner = new Scanner(
                new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding)));

        boolean hasSentence = false;
        int currentFileIndex = startIndex;

        int sentenceCount = 0;
        Writer writer = null;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.length() == 0 && !hasSentence) {
                continue;
            } else if (line.length() == 0) {
                writer.write("\n");
                writer.flush();
                hasSentence = false;
            } else {
                if (!hasSentence) {
                    hasSentence = true;
                    sentenceCount++;
                }
                if (writer == null || sentenceCount % sentencesPerFile == 0) {
                    if (writer != null) {
                        writer.flush();
                        writer.close();
                    }
                    File outFile = new File(fileBase + "_" + df.format(currentFileIndex) + ".tal");
                    outFile.delete();
                    outFile.createNewFile();
                    writer = new BufferedWriter(
                            new OutputStreamWriter(new FileOutputStream(outFile, false), encoding));
                    currentFileIndex++;
                    hasSentence = false;
                }

                writer.write(line + "\n");
                writer.flush();
            }
        }
        if (writer != null) {
            writer.flush();
            writer.close();
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:net.solarnetwork.node.control.ping.HttpRequesterJob.java

private void logInputStream(final InputStream src, final boolean errorStream) {
    new Thread(new Runnable() {

        @Override/*from  w ww.j  ava 2 s  .c  o  m*/
        public void run() {
            Scanner sc = new Scanner(src);
            while (sc.hasNextLine()) {
                if (errorStream) {
                    log.error(sc.nextLine());
                } else {
                    log.info(sc.nextLine());
                }
            }
        }
    }).start();
}