Example usage for java.util Scanner hasNext

List of usage examples for java.util Scanner hasNext

Introduction

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

Prototype

public boolean hasNext() 

Source Link

Document

Returns true if this scanner has another token in its input.

Usage

From source file:com.google.payments.InAppBillingV3.java

private JSONObject getManifestContents() {
    if (manifestObject != null)
        return manifestObject;

    Context context = this.cordova.getActivity();
    InputStream is;/*  www . ja  v  a2  s  .co  m*/
    try {
        is = context.getAssets().open("www/manifest.json");
        Scanner s = new Scanner(is).useDelimiter("\\A");
        String manifestString = s.hasNext() ? s.next() : "";
        manifestObject = new JSONObject(manifestString);
    } catch (IOException e) {
        Log.d(TAG, "Unable to read manifest file:" + e.toString());
        manifestObject = null;
    } catch (JSONException e) {
        Log.d(TAG, "Unable to parse manifest file:" + e.toString());
        manifestObject = null;
    }
    return manifestObject;
}

From source file:analyzer.code.FXMLAnalyzerController.java

@FXML
private void openProjectMenuItem() throws FileNotFoundException, IOException {
    source.clear();//from  w ww .  j ava  2s.c o m
    DirectoryChooser chooser = new DirectoryChooser();
    chooser.setTitle("C project");
    File selectedDirectory = chooser.showDialog(null);
    if (null != selectedDirectory) {
        File[] files = selectedDirectory.listFiles();
        for (File file : files) {
            if (FilenameUtils.getExtension(file.getAbsolutePath()).equals("java")) {
                analyzer = new AnalyzerC();
                curLang = C;
                countOperatorsEnable = true;
                levelNestEnable = true;
                middleLenIdentEnable = true;
                tableMetric.setVisible(true);
                tableDescript.setVisible(true);
                labelDesc.setVisible(true);
                labelMetrics.setVisible(true);
                button.setVisible(true);
                Scanner scanner = new Scanner(file);
                nameFile.add(FilenameUtils.getName(file.getAbsolutePath()));
                String tmpSource = new String();
                while (scanner.hasNext()) {
                    tmpSource += scanner.nextLine() + '\n';
                }
                source.add(tmpSource);
            }
        }
    }
}

From source file:org.fhaes.fhfilereader.FHCategoryReader.java

/**
 * Parses the input category file and stores its contents in the categoryEntries arrayList.
 * //from  w  w w.j a  v a2 s  . co m
 * @param categoryFile
 */
public FHCategoryReader(File categoryFile) {

    try {
        // Setup the scanner for reading and storing the category entries from the CSV file
        Scanner sc = new Scanner(categoryFile);
        sc.useDelimiter(",|\r\n");

        // Verify that the category file has the necessary header and version number
        for (int numValuesRead = 0; numValuesRead <= NUM_INITIAL_VALUES_TO_READ; numValuesRead++) {
            if (numValuesRead == INDEX_OF_HEADER && sc.hasNext()) {
                if (!sc.next().equals(FHAES_CATEGORY_FILE_HEADER)) {
                    sc.close();
                    throw new InvalidCategoryFileException();
                }
            } else if (numValuesRead == INDEX_OF_VERSION && sc.hasNext()) {
                if (!sc.next().equals(FHAES_CATEGORY_FILE_VERSION)) {
                    sc.close();
                    throw new InvalidCategoryFileException();
                }
            } else if (numValuesRead == INDEX_OF_FILENAME && sc.hasNext()) {
                nameOfCorrespondingFHXFile = sc.next();
            } else {
                sc.close();
                throw new InvalidCategoryFileException();
            }
        }

        // Read the contents of the category file into the categoryEntries array
        while (sc.hasNext()) {
            String seriesTitle = sc.next();
            String category = sc.next();
            String content = sc.next();

            if (!seriesTitle.equals("") && !category.equals("") && !content.equals("")) {
                categoryEntries.add(new FHCategoryEntry(seriesTitle, category, content));
            } else {
                sc.close();
                throw new InvalidCategoryFileException();
            }
        }

        sc.close();
    } catch (FileNotFoundException ex) {
        log.info("The category file " + FilenameUtils.getBaseName(categoryFile.getAbsolutePath())
                + " does not exist.");
    } catch (InvalidCategoryFileException ex) {
        log.error("Could not parse category file. File is in an invalid format or has missing entries.");
    }
}

From source file:com.alexdisler.inapppurchases.InAppBillingV3.java

private JSONObject getManifestContents() {
    if (manifestObject != null)
        return manifestObject;

    Context context = this.cordova.getActivity();
    InputStream is;//from  w  w w .j  a  v  a 2  s.  c om
    try {
        is = context.getAssets().open("www/manifest.json");
        Scanner s = new Scanner(is).useDelimiter("\\A");
        String manifestString = s.hasNext() ? s.next() : "";
        Log.d(TAG, "manifest:" + manifestString);
        manifestObject = new JSONObject(manifestString);
    } catch (IOException e) {
        Log.d(TAG, "Unable to read manifest file:" + e.toString());
        manifestObject = null;
    } catch (JSONException e) {
        Log.d(TAG, "Unable to parse manifest file:" + e.toString());
        manifestObject = null;
    }
    return manifestObject;
}

From source file:org.apache.eagle.alert.metric.MetricSystemTest.java

@Test
public void testSlf4jSink() throws IOException {
    PrintStream console = System.out;
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    System.setOut(new PrintStream(bytes));

    Slf4jSink sink = new Slf4jSink();
    MetricRegistry registry = new MetricRegistry();
    JvmAttributeGaugeSet jvm = Mockito.mock(JvmAttributeGaugeSet.class);
    Map<String, Metric> metrics = new HashMap<>();
    metrics.put("name", (Gauge) () -> "testname");
    metrics.put("uptime", (Gauge) () -> "testuptime");
    metrics.put("vendor", (Gauge) () -> "testvendor");
    Mockito.when(jvm.getMetrics()).thenReturn(metrics);
    registry.registerAll(jvm);//from ww  w .  j  a va 2s.c o  m
    File file = genSlf4jSinkConfig();
    Config config = ConfigFactory.parseFile(file);
    sink.prepare(config, registry);
    sink.report();
    sink.stop();
    String result = bytes.toString();
    String finalResult = "";
    Scanner scanner = new Scanner(result);
    while (scanner.hasNext()) {
        finalResult += scanner.nextLine().substring(DATA_BEGIN_INDEX) + END_LINE;
    }
    Assert.assertEquals("type=GAUGE, name=name, value=testname" + END_LINE + ""
            + "type=GAUGE, name=uptime, value=testuptime" + END_LINE + ""
            + "type=GAUGE, name=vendor, value=testvendor" + END_LINE + "", finalResult);
    System.setOut(console);
}

From source file:com.santhoshknn.sudoku.GridExtractor.java

/**
 * <p>//w  w w.  j  a  va2s  . c o  m
 * Parses the supplied file to extract a 9x9 grid of integers substituting
 * the supplied x with a 0
 * </p>
 * <b>Note:</b>Used internally for testing with various data. REST API uses
 * the operation above
 *
 * @param input
 * @return extracted grid if valid input, null otherwise
 */
public GridResponse parseFromFile(final String fileName) {
    int[][] grid = new int[9][9]; // default 0 vals
    GridResponse response = new GridResponse();
    Scanner scanner = null;
    String error = null;
    try {
        URL url = getClass().getResource(fileName);
        log.info("Reading input file [{}]", url.getFile());
        scanner = new Scanner(new File(url.getPath()));
        int row = 0;
        while (scanner.hasNext()) {
            int col = 0;
            String line = scanner.nextLine();
            // delete whitespaces added for cosmetic purpose
            line = StringUtils.deleteWhitespace(line);
            if (line.isEmpty())
                continue; // Sanitize input. Remove line added for
                          // readability
                          // fail if line's length!=9
            if (line.length() != 9) {
                error = INVALID_CHARS_IN_FILE + ":" + (row + 1);
                break;
            }

            for (int i = 0; i < line.length(); i++) {
                //log.info("Row [{}] Char is [{}]",row,line.charAt(i));
                if (Character.isDigit(line.charAt(i))) {
                    int number = Character.getNumericValue(line.charAt(i));
                    grid[row][col] = number;
                } else {
                    grid[row][col] = 0;
                }
                col++;
            }
            if (row == 9)
                break;
            row++;
        }
    } catch (FileNotFoundException e) {
        log.error("Error reading file [{}]", fileName, e);
    } finally {
        if (scanner != null)
            scanner.close();
    }
    if (null == error) {
        response.setGrid(grid);
    } else {
        response.setError(error);
        log.error(error);
    }
    return response;
}

From source file:cz.cuni.mff.ksi.jinfer.autoeditor.BububuEditor.java

/**
 * Draws automaton and waits until user picks two states and clicks
 * 'continue' button.// www  .j  a v a  2 s.  com
 *
 * @param automaton automaton to be drawn
 * @return if user picks exactly two states returns Pair of them otherwise null
 */
@Override
public List<State<T>> drawAutomatonToPickStates(final Automaton<T> automaton) {

    final DirectedSparseMultigraph<State<T>, Step<T>> graph = new DirectedSparseMultigraph<State<T>, Step<T>>();
    final Map<State<T>, Set<Step<T>>> automatonDelta = automaton.getDelta();

    // Get vertices = states of automaton
    for (Entry<State<T>, Set<Step<T>>> entry : automatonDelta.entrySet()) {
        graph.addVertex(entry.getKey());
    }

    // Get edges of automaton
    for (Entry<State<T>, Set<Step<T>>> entry : automatonDelta.entrySet()) {
        for (Step<T> step : entry.getValue()) {
            graph.addEdge(step, step.getSource(), step.getDestination());
        }
    }

    Map<State<T>, Point2D> positions = new HashMap<State<T>, Point2D>();

    ProcessBuilder p = new ProcessBuilder(Arrays.asList("/usr/bin/dot", "-Tplain"));
    try {
        Process k = p.start();
        k.getOutputStream().write((new AutomatonToDot<T>()).convertToDot(automaton, symbolToString).getBytes());
        k.getOutputStream().flush();
        BufferedReader b = new BufferedReader(new InputStreamReader(k.getInputStream()));
        k.getOutputStream().close();

        Scanner s = new Scanner(b);
        s.next();
        s.next();
        double width = s.nextDouble();
        double height = s.nextDouble();
        double windowW = 500;
        double windowH = 300;

        while (s.hasNext()) {
            if (s.next().equals("node")) {
                int nodeName = s.nextInt();
                double x = s.nextDouble();
                double y = s.nextDouble();
                for (State<T> state : automatonDelta.keySet()) {
                    if (state.getName() == nodeName) {
                        positions.put(state,
                                new Point((int) (windowW * x / width), (int) (windowH * y / height)));
                        break;
                    }
                }
            }
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
    Transformer<State<T>, Point2D> trans = TransformerUtils.mapTransformer(positions);

    // TODO rio find suitable layout
    final Layout<State<T>, Step<T>> layout = new StaticLayout<State<T>, Step<T>>(graph, trans);

    //layout.setSize(new Dimension(300,300)); // sets the initial size of the space

    visualizationViewer = new VisualizationViewer<State<T>, Step<T>>(layout);
    //visualizationViewer.setPreferredSize(new Dimension(350,350)); //Sets the viewing area size

    visualizationViewer.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<State<T>>());
    visualizationViewer.getRenderContext().setEdgeLabelTransformer(new Transformer<Step<T>, String>() {
        @Override
        public String transform(Step<T> i) {
            return BububuEditor.this.symbolToString.toString(i.getAcceptSymbol());
        }
    });

    final PluggableGraphMouse gm = new PluggableGraphMouse();
    gm.add(new PickingUnlimitedGraphMousePlugin<State<T>, Step<T>>());
    visualizationViewer.setGraphMouse(gm);

    // Call GUI in a special thread. Required by NB.
    synchronized (this) {
        WindowManager.getDefault().invokeWhenUIReady(new Runnable() {

            @Override
            public void run() {
                // Pass this as argument so the thread will be able to wake us up.
                AutoEditorTopComponent.findInstance().drawAutomatonBasicVisualizationServer(BububuEditor.this,
                        visualizationViewer, "Please select two states to be merged together.");
            }
        });

        try {
            // Sleep on this.
            this.wait();
        } catch (InterruptedException e) {
            return null;
        }
    }

    /* AutoEditorTopComponent wakes us up. Get the result and return it.
     * VisualizationViewer should give us the information about picked vertices.
     */
    final Set<State<T>> pickedSet = visualizationViewer.getPickedVertexState().getPicked();
    List<State<T>> lst = new ArrayList<State<T>>(pickedSet);
    return lst;
}

From source file:com.surevine.alfresco.esl.impl.GroupDetails.java

/**
 * Constructor. Create a GroupDetails within the given constraint according to the given specification
 * /*from w w w  .  j  av a  2s  . c o m*/
 * @param specification
 *            See the comments at the top of this class, and the unit tests, for more details
 * @param parentConstraint
 */
public GroupDetails(String specification, EnhancedSecurityConstraint parentConstraint) {
    // Check params look OK
    if (specification == null || parentConstraint == null) {
        throw new EnhancedSecurityException(
                "Both the specification and the parent constraint must be non-null to create a GroupDetails");
    }

    // Parse out key=value,key=value pairs and use setKVPair to set relevant properties
    try {
        _constraint = parentConstraint;
        Scanner keyValuePair = new Scanner(specification.trim());
        keyValuePair.useDelimiter("\n+");
        while (keyValuePair.hasNext()) {
            String keyOrValueStr = keyValuePair.next().trim();
            if (keyOrValueStr.equals("")) {
                continue;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found Key/Value Pair: " + keyOrValueStr);
            }
            Scanner keyOrValue = new Scanner(keyOrValueStr);
            keyOrValue.useDelimiter("=");
            String key = keyOrValue.next();
            LOG.debug("  Found Key: " + key);
            String value = keyOrValue.next();
            LOG.debug("  Found Value: " + value);
            if (keyOrValue.hasNext()) {
                throw new EnhancedSecurityException("Was expecting a single '=' in [" + keyValuePair + "]");
            }
            setKVPair(key, value);
        }
    } catch (NoSuchElementException e) {
        throw new EnhancedSecurityException(
                "The group details specification was incorrectly formatted.  It should be key=value [lineBreak] key=value with no '=' charecters in the keys or values",
                e);
    }

}

From source file:hmp.HMPClassiferSummary.java

private ResultContainer getRawRdpResults(String fileName, ReadContainer reads)
        throws FileNotFoundException, SQLException {
    System.out.println("Getting RDP Results");
    ResultContainer results = new ResultContainer((float) cutoff);
    Scanner scan = new Scanner(new File(fileName));
    while (scan.hasNext()) {
        results.addResult(new Result(scan.nextLine(), (float) cutoff, readDelimiter, readIdIndex));
    }//from   w  w w .  ja  v  a  2s .com

    /*
     * Add read object to each rdp result
     * Used for stats calculation later on
     */
    for (Result r : results.getResults()) {
        r.addRead(reads.getRead(r.getId()));
    }
    //
    //        /*
    //         * Add rank to reach result entry
    //         */
    //        System.out.println("Adding ranks for each taxa entry");
    //        for (Result r : results.getResults()) {
    //            for (ResultEntry e : r.getEntries()) {
    //                e.setLevel(getTaxaLevelFromDB(e.getTaxa(), e.getIndex()));
    //            }
    //
    //            /*
    //             * get level for processed data, using taxa information from
    //             * pre processed array.  this ensures that unclassified entries
    //             * are at the proper level
    //             */
    //
    //            for (ResultEntry e : r.getProcessedEntries()) {
    //                e.setLevel(getTaxaLevelFromDB(r.getEntries()[e.getIndex()].getTaxa(), e.getIndex()));
    //            }
    //        }

    return results;
}

From source file:com.networknt.light.server.LoadPageMojo.java

public void parsePageFile(final String filePath) {
    System.out.println("Process file = " + filePath);
    StringBuilder content = new StringBuilder();
    try {//  w w  w .j av a  2s . c  o m
        File file = new File(filePath);
        String id = getFileName(file);
        if (".html".equals(getExtension(file))) {
            final Scanner scan = new Scanner(file, encoding);
            String line = scan.nextLine();
            while (scan.hasNext()) {
                content.append(line);
                content.append("\n");
                line = scan.nextLine();
            }
            content.append(line);
            content.append("\n");

            // only import if content has been changed after comparing with server
            if (!content.toString().equals(pageMap.get(id))) {
                impPage(id, content.toString());
                // generate SQL insert statements

                String sql = "INSERT INTO PAGE(id, content) VALUES ('" + id + "', '"
                        + content.toString().replaceAll("'", "''") + "');\n";
                sqlString += sql;
            }

        }
    } catch (final IOException e) {
        getLog().error(e.getMessage());
    }
}