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:gtu._work.ui.RegexTestUI.java

private void jText1OrJArea1Change(DocumentEvent doc) {
    try {/*from  w w  w .j av  a2 s  .co  m*/
        String complie1 = regexText.getText();
        String complie2 = regexText0.getText();
        String complie = complie1;
        if (StringUtils.isBlank(complie1)) {
            complie = complie2;
        }

        String matcherStr = srcArea.getText();

        if (StringUtils.isBlank(complie)) {
            setTitle("Regex");
            return;
        }
        if (StringUtils.isBlank(matcherStr)) {
            setTitle("content");
            return;
        }

        Pattern pattern = Pattern.compile(complie);
        Matcher matcher = pattern.matcher(matcherStr);

        DefaultComboBoxModel model1 = new DefaultComboBoxModel();
        groupList.setModel(model1);
        while (matcher.find()) {
            model1.addElement("---------------------");
            for (int ii = 0; ii <= matcher.groupCount(); ii++) {
                model1.addElement(ii + " : [" + matcher.group(ii) + "]");
            }
        }

        DefaultComboBoxModel model2 = new DefaultComboBoxModel();
        scannerList.setModel(model2);
        Scanner scanner = new Scanner(matcherStr);
        scanner.useDelimiter(pattern);
        while (scanner.hasNext()) {
            model2.addElement("[" + scanner.next() + "]");
        }
        scanner.close();
        this.setTitle("?");
    } catch (Exception ex) {
        this.setTitle(ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:com.laex.cg2d.screeneditor.handlers.RenderHandler.java

/**
 * the command has been executed, so extract extract the needed information
 * from the application context./*from   ww  w  .j  a  va  2  s.c o m*/
 * 
 * @param event
 *          the event
 * @return the object
 * @throws ExecutionException
 *           the execution exception
 */
public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    final IEditorPart editorPart = window.getActivePage().getActiveEditor();

    editorPart.doSave(new NullProgressMonitor());

    validate(window.getShell());

    // Eclipse Jobs API
    final Job job = new Job("Render Game") {
        @Override
        protected IStatus run(IProgressMonitor monitor) {

            if (monitor.isCanceled()) {
                return Status.CANCEL_STATUS;
            }

            try {
                IFile file = ((IFileEditorInput) editorPart.getEditorInput()).getFile();

                monitor.beginTask("Building rendering command", 5);
                ILog log = Activator.getDefault().getLog();

                String mapFile = file.getLocation().makeAbsolute().toOSString();
                String controllerFile = file.getLocation().removeFileExtension().addFileExtension("lua")
                        .makeAbsolute().toOSString();

                String[] command = buildRunnerCommandFromProperties(mapFile, controllerFile);
                monitor.worked(5);

                monitor.beginTask("Rendering external", 5);

                ProcessBuilder pb = new ProcessBuilder(command);
                Process p = pb.start();

                monitor.worked(4);
                Scanner scn = new Scanner(p.getErrorStream());
                while (scn.hasNext() && !monitor.isCanceled()) {

                    if (monitor.isCanceled()) {
                        throw new InterruptedException("Cancelled");
                    }

                    log.log(new Status(IStatus.INFO, Activator.PLUGIN_ID, scn.nextLine()));
                }
                monitor.worked(5);

                monitor.done();
                this.done(Status.OK_STATUS);
                return Status.OK_STATUS;

            } catch (RuntimeException e) {
                return handleException(e);
            } catch (IOException e) {
                return handleException(e);
            } catch (CoreException e) {
                return handleException(e);
            } catch (InterruptedException e) {
                return handleException(e);
            }
        }

        private IStatus handleException(Exception e) {
            Activator.log(e);
            return Status.CANCEL_STATUS;
        }
    };

    job.setUser(true);
    job.setPriority(Job.INTERACTIVE);
    job.schedule();

    return null;
}

From source file:eu.project.ttc.resources.CompostInflectionRules.java

public void load(DataResource data) throws ResourceInitializationException {
    InputStream inputStream;//  ww w .  ja  v a  2s  .c  om
    this.inflectionRules = Lists.newArrayList();
    try {
        inputStream = data.getInputStream();
        Scanner scanner = null;
        try {
            scanner = new Scanner(inputStream, "UTF-8");
            scanner.useDelimiter(TermSuiteConstants.LINE_BREAK);
            while (scanner.hasNext()) {
                String rawLine = scanner.next();
                String line = rawLine.split(";")[0];
                String[] args = line.split(",");
                if (args.length != 2 && !line.trim().isEmpty()) {
                    LOGGER.warn("Bad inflection rules format: " + rawLine);
                } else {
                    this.inflectionRules.add(new InflectionRule(args[0].trim(), args[1].trim()));
                }
            }
            this.inflectionRules = ImmutableList.copyOf(this.inflectionRules);
        } catch (Exception e) {
            throw new ResourceInitializationException(e);
        } finally {
            IOUtils.closeQuietly(scanner);
            IOUtils.closeQuietly(inputStream);
        }
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:it.acubelab.batframework.systemPlugins.TagmeAnnotator.java

@Override
public HashSet<ScoredAnnotation> solveSa2W(String text) throws AnnotationException {
    // System.out.println(text.length()+ " "+text.substring(0,
    // Math.min(text.length(), 15)));
    // TODO: workaround for a bug in tagme. should be deleted afterwards.
    String newText = "";
    for (int i = 0; i < text.length(); i++)
        newText += (text.charAt(i) > 127 ? ' ' : text.charAt(i));
    text = newText;//w w w .ja v a  2  s  .c om

    // avoid crashes for empty documents
    int j = 0;
    while (j < text.length() && text.charAt(j) == ' ')
        j++;
    if (j == text.length())
        return new HashSet<ScoredAnnotation>();

    HashSet<ScoredAnnotation> res;
    String params = null;
    try {
        res = new HashSet<ScoredAnnotation>();

        params = "key=" + this.key;
        params += "&lang=en";
        if (epsilon >= 0)
            params += "&epsilon=" + epsilon;
        if (minComm >= 0)
            params += "&min_comm=" + minComm;
        if (minLink >= 0)
            params += "&min_link=" + minLink;
        params += "&text=" + URLEncoder.encode(text, "UTF-8");
        URL wikiApi = new URL(url);

        HttpURLConnection slConnection = (HttpURLConnection) wikiApi.openConnection();
        slConnection.setRequestProperty("accept", "text/xml");
        slConnection.setDoOutput(true);
        slConnection.setDoInput(true);
        slConnection.setRequestMethod("POST");
        slConnection.setRequestProperty("charset", "utf-8");
        slConnection.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
        slConnection.setUseCaches(false);
        slConnection.setReadTimeout(0);

        DataOutputStream wr = new DataOutputStream(slConnection.getOutputStream());
        wr.writeBytes(params);
        wr.flush();
        wr.close();

        Scanner s = new Scanner(slConnection.getInputStream());
        Scanner s2 = s.useDelimiter("\\A");
        String resultStr = s2.hasNext() ? s2.next() : "";
        s.close();

        JSONObject obj = (JSONObject) JSONValue.parse(resultStr);
        lastTime = (Long) obj.get("time");

        JSONArray jsAnnotations = (JSONArray) obj.get("annotations");
        for (Object js_ann_obj : jsAnnotations) {
            JSONObject js_ann = (JSONObject) js_ann_obj;
            System.out.println(js_ann);
            int start = ((Long) js_ann.get("start")).intValue();
            int end = ((Long) js_ann.get("end")).intValue();
            int id = ((Long) js_ann.get("id")).intValue();
            float rho = Float.parseFloat((String) js_ann.get("rho"));
            System.out.println(text.substring(start, end) + "->" + id + " (" + rho + ")");
            res.add(new ScoredAnnotation(start, end - start, id, (float) rho));
        }

    } catch (Exception e) {
        e.printStackTrace();
        throw new AnnotationException("An error occurred while querying TagMe API. Message: " + e.getMessage()
                + " Parameters:" + params);
    }
    return res;

}

From source file:ch.sdi.core.impl.parser.CsvParser.java

/**
 * Parses the given input stream./*ww  w  . j  a va 2 s  .co m*/
 * <p>
 *
 * @param aInputStream
 *        must not be null
 * @param aDelimiter
 *        must not be null
 * @param aEncoding
 *        The encoding to be used. If null or empty, the systems default encoding is used.
 * @return a list which contains a list for each found person. The inner list contains the found
 *         values for this person. The number and the order must correspond to the configured field
 *         name list (see
 *         in each line.
 * @throws SdiException
 */
public List<List<String>> parse(InputStream aInputStream, String aDelimiter, String aEncoding,
        List<RawDataFilterString> aFilters) throws SdiException {
    if (!StringUtils.hasLength(aDelimiter)) {
        throw new SdiException("Delimiter not set", SdiException.EXIT_CODE_CONFIG_ERROR);
    } // if myDelimiter == null

    try {
        myLog.debug("Using encoding " + aEncoding);

        BufferedReader br = new BufferedReader(
                !StringUtils.hasText(aEncoding) ? new InputStreamReader(aInputStream)
                        : new InputStreamReader(aInputStream, aEncoding));
        List<List<String>> result = new ArrayList<>();
        Collection<String> myLinesFiltered = new ArrayList<>();

        int lineNo = 0;
        String line;
        LineLoop: while ((line = br.readLine()) != null) {
            lineNo++;

            if (aFilters != null) {
                for (RawDataFilterString filter : aFilters) {
                    if (filter.isFiltered(line)) {
                        myLog.debug("Skipping commented line: " + line);
                        myLinesFiltered.add(line);
                        continue LineLoop;
                    }
                }
            }

            myLog.debug("Parsing line " + lineNo + ": " + line);

            List<String> list = new ArrayList<String>();
            Scanner sc = new Scanner(line);
            try {
                sc.useDelimiter(aDelimiter);
                while (sc.hasNext()) {
                    list.add(sc.next());
                }

                // Note: if the line is terminated by the delimiter (last entry not present, the last entry
                // will not appear in the scanned enumeration. Check for this special case:
                if (line.endsWith(aDelimiter)) {
                    list.add("");
                } // if line.endsWith( aDelimiter )
            } finally {
                sc.close();
            }

            result.add(list);
        }

        myLog.info(new ReportMsg(ReportMsg.ReportType.PREPARSE_FILTER, "Filtered lines", myLinesFiltered));

        return result;
    } catch (Throwable t) {
        throw new SdiException("Problems while parsing CSV file", t, SdiException.EXIT_CODE_PARSE_ERROR);
    }
}

From source file:org.wso2.extension.siddhi.execution.var.backtest.Backtest.java

public ArrayList<Event> readBacktestData() throws FileNotFoundException {
    ClassLoader classLoader = getClass().getClassLoader();
    Scanner scan = new Scanner(new File(classLoader.getResource("BackTestDataNew.csv").getFile()));
    ArrayList<Event> list = new ArrayList();
    Event event;/*  www  . j a  va 2s  . c om*/
    String[] split;
    while (scan.hasNext()) {
        event = new Event();
        split = scan.nextLine().split(",");
        if (split.length == 2) {
            event.setSymbol(split[0]);
            event.setPrice(Double.parseDouble(split[1]));
        } else {
            event.setPortfolioID(split[0]); //portfolio id
            event.setQuantity(Integer.parseInt(split[1])); //shares
            event.setSymbol(split[2]); //symbol
            event.setPrice(Double.parseDouble(split[3])); //price
        }
        list.add(event);
    }
    return list;
}

From source file:org.wso2.extension.siddhi.execution.var.backtest.BacktestDaily.java

public ArrayList<Event> readBacktestData() throws FileNotFoundException {
    ClassLoader classLoader = getClass().getClassLoader();
    Scanner scan = new Scanner(new File(classLoader.getResource("BackTestDataReal.csv").getFile()));
    ArrayList<Event> list = new ArrayList();
    Event event;//ww w.  j  a  va2  s. co  m
    String[] split;

    while (scan.hasNext()) {
        event = new Event();
        split = scan.nextLine().split(",");
        if (split.length == 2) {
            event.setSymbol(split[0]);
            event.setPrice(Double.parseDouble(split[1]));
        } else {
            event.setPortfolioID(split[0]);
            event.setQuantity(Integer.parseInt(split[1]));
            event.setSymbol(split[2]);
            event.setPrice(Double.parseDouble(split[3]));
        }
        list.add(event);
    }
    return list;
}

From source file:com.addthis.hydra.data.util.JSONFetcher.java

/**
 * loads a json-formatted array from an url and adds enclosing
 * square brackets if missing/*from  w w  w.  j ava 2  s . co m*/
 *
 * @param mapURL
 * @return string set
 */
public HashSet<String> loadCSVSet(String mapURL, HashSet<String> set) {
    try {
        byte[] raw = retrieveBytes(mapURL);
        String list = LessBytes.toString(raw);

        if (set == null) {
            set = new HashSet<>();
        }

        Scanner in = new Scanner(list);

        while (in.hasNext()) {
            set.add(in.nextLine().replaceAll("^\"|\"$", ""));
        }

        return set;
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.wso2.extension.siddhi.execution.var.backtest.BacktestRealTime.java

public ArrayList<Event> readBacktestData() throws FileNotFoundException {
    ClassLoader classLoader = getClass().getClassLoader();
    Scanner scan = new Scanner(new File(classLoader.getResource("BackTestDataNew.csv").getFile()));
    ArrayList<Event> list = new ArrayList();
    Event event;/*from w w w . j a  v a2s.c om*/
    String[] split;

    while (scan.hasNext()) {
        event = new Event();
        split = scan.nextLine().split(",");
        if (split.length == 2) {
            event.setSymbol(split[0]);
            event.setPrice(Double.parseDouble(split[1]));
        } else {
            event.setPortfolioID(split[0]); //portfolio id
            event.setQuantity(Integer.parseInt(split[1])); //shares
            event.setSymbol(split[2]); //symbol
            event.setPrice(Double.parseDouble(split[3])); //price
        }
        list.add(event);
    }
    return list;
}

From source file:ch.cyberduck.core.importer.FireFtpBookmarkCollection.java

private void read(final ProtocolFactory protocols, final String entry) {
    final Host current = new Host(protocols.forScheme(Scheme.ftp));
    current.getCredentials().setUsername(PreferencesFactory.get().getProperty("connection.login.anon.name"));
    for (String attribute : entry.split(", ")) {
        Scanner scanner = new Scanner(attribute);
        scanner.useDelimiter(":");
        if (!scanner.hasNext()) {
            log.warn("Missing key in line:" + attribute);
            continue;
        }/*from   ww w.  j av  a  2  s. c  om*/
        String name = scanner.next().toLowerCase(Locale.ROOT);
        if (!scanner.hasNext()) {
            log.warn("Missing value in line:" + attribute);
            continue;
        }
        String value = scanner.next().replaceAll("\"", StringUtils.EMPTY);
        if ("host".equals(name)) {
            current.setHostname(value);
        } else if ("port".equals(name)) {
            try {
                current.setPort(Integer.parseInt(value));
            } catch (NumberFormatException e) {
                log.warn("Invalid Port:" + e.getMessage());
            }
        } else if ("remotedir".equals(name)) {
            current.setDefaultPath(value);
        } else if ("webhost".equals(name)) {
            current.setWebURL(value);
        } else if ("encoding".equals(name)) {
            current.setEncoding(value);
        } else if ("notes".equals(name)) {
            current.setComment(value);
        } else if ("account".equals(name)) {
            current.setNickname(value);
        } else if ("privatekey".equals(name)) {
            current.getCredentials().setIdentity(LocalFactory.get(value));
        } else if ("pasvmode".equals(name)) {
            if (Boolean.TRUE.toString().equals(value)) {
                current.setFTPConnectMode(FTPConnectMode.passive);
            }
            if (Boolean.FALSE.toString().equals(value)) {
                current.setFTPConnectMode(FTPConnectMode.active);
            }
        } else if ("login".equals(name)) {
            current.getCredentials().setUsername(value);
        } else if ("password".equals(name)) {
            current.getCredentials().setPassword(value);
        } else if ("anonymous".equals(name)) {
            if (Boolean.TRUE.toString().equals(value)) {
                current.getCredentials()
                        .setUsername(PreferencesFactory.get().getProperty("connection.login.anon.name"));
            }
        } else if ("security".equals(name)) {
            if ("authtls".equals(value)) {
                current.setProtocol(protocols.forScheme(Scheme.ftps));
                // Reset port to default
                current.setPort(-1);
            }
            if ("sftp".equals(value)) {
                current.setProtocol(protocols.forScheme(Scheme.sftp));
                // Reset port to default
                current.setPort(-1);
            }
        }
    }
    this.add(current);
}