Example usage for java.util Scanner useDelimiter

List of usage examples for java.util Scanner useDelimiter

Introduction

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

Prototype

public Scanner useDelimiter(String pattern) 

Source Link

Document

Sets this scanner's delimiting pattern to a pattern constructed from the specified String .

Usage

From source file:reittienEtsinta.tiedostonKasittely.GeoJsonLukija.java

/**
 * Lukee GeoJson tiedoston ja muodostaa sen pohjalta polygoni taulukon
 * Polygonit on tallennettu joukkona koordinaattipisteita
 *
 * @param polku/*from www.  j  a va 2  s . c om*/
 * @return
 */
private JSONObject lataaJsonObject(File tiedosto) {

    Scanner lukija = null;
    try {
        lukija = new Scanner(tiedosto);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GeoJsonLukija.class.getName()).log(Level.SEVERE, null, ex);
    }
    lukija.useDelimiter("\\Z");
    String data = lukija.next();

    return new JSONObject(data);
}

From source file:org.callimachusproject.auth.FacebookAuthReader.java

private AccessToken verify(String parameters, String[] via) {
    String code = getValueAfter(parameters, "code=");
    String error_description = getValueAfter(parameters, "error_description=");
    String state = getValueAfter(parameters, "state=");
    boolean verified = verifyState(state, via);
    if (error_description != null && error_description.length() > 0) {
        logger.warn("Facebook says: {}", error_description);
        return null;
    } else if (!verified) {
        logger.error("Invalid facebook manager state");
        return null;
    } else if (code == null) {
        logger.error("Could not login facebook user");
        return null;
    }/*from w w  w  .j  a  va 2 s. c  o  m*/
    long now = System.currentTimeMillis();
    synchronized (tokens) {
        Iterator<AccessToken> iter = tokens.values().iterator();
        while (iter.hasNext()) {
            AccessToken token = iter.next();
            if (token.isExpired(now)) {
                iter.remove();
            }
        }
        if (tokens.containsKey(parameters))
            return tokens.get(parameters);
    }
    String redirect_uri = getValueAfter(parameters, "redirect_uri=");
    String url = ACCESS_URL + "?client_id=" + encode(getFacebookAppId()) + "&redirect_uri="
            + encode(redirect_uri) + "&client_secret=" + encode(getFacebookSecret()) + "&code=" + encode(code);
    try {
        HttpEntity entity = client.getEntity(url, "application/x-www-form-urlencoded");
        try {
            Scanner scanner = new Scanner(entity.getContent(), "UTF-8");
            String content = scanner.useDelimiter("\\A").next();
            AccessToken token = new AccessToken(now, content);
            synchronized (tokens) {
                tokens.put(parameters, token);
                return token;
            }
        } finally {
            EntityUtils.consume(entity);
        }
    } catch (Exception e) {
        logger.error(url, e);
        return null;
    }
}

From source file:org.bibsonomy.webapp.controller.MySearchController.java

/**
 * extract the last names of the authors
 * // w w w .  j  av  a2s  .c o  m
 * @param authors
 * @return string list of the last names of the authors
 */
private List<String> extractAuthorsLastNames(String authors) {
    List<String> authorsList = new LinkedList<String>();
    List<String> names = new LinkedList<String>();
    Pattern pattern = Pattern.compile("[0-9]+"); // only numbers

    Scanner s = new Scanner(authors);
    s.useDelimiter(" and ");
    while (s.hasNext())
        names.add(s.next());

    for (String person : names) {
        /*
         * extract all parts of a name
         */
        List<String> nameList = new LinkedList<String>();
        StringTokenizer token = new StringTokenizer(person);
        while (token.hasMoreTokens()) {
            /*
             * ignore numbers (from DBLP author names)
             */
            final String part = token.nextToken();
            if (!pattern.matcher(part).matches()) {
                nameList.add(part);
            }
        }

        /*
         * detect lastname
         */
        int i = 0;
        while (i < nameList.size() - 1) { // iterate up to the last but one
            // part
            final String part = nameList.get(i++);
            /*
             * stop, if this is the last abbreviated forename
             */
            if (part.contains(".") && !nameList.get(i).contains(".")) {
                break;
            }
        }

        StringBuilder lastName = new StringBuilder();
        while (i < nameList.size()) {
            lastName.append(nameList.get(i++) + " ");
        }

        // add name to list
        authorsList.add(lastName.toString().trim());
    }
    return authorsList;
}

From source file:org.pepstock.jem.ant.tasks.utilities.sort.DefaultComparator.java

/**
 * Reads a input stream putting all in a string buffer for further parsing.
 * Removes <code>/n</code> chars. 
 * /*from  w w  w.  j av a 2 s  .  co  m*/
 * @param is
 *            input stream with all commands
 * @return string buffer with all commands
 * @throws IOException
 *             if IO error occurs
 */
private StringBuilder read(InputStream is) throws IOException {
    StringBuilder sb = new StringBuilder();
    Scanner sc = new Scanner(is, CharSet.DEFAULT_CHARSET_NAME);
    sc.useDelimiter("\n");
    while (sc.hasNext()) {
        String record = sc.next().toString();
        sb.append(record.trim()).append(' ');
    }
    sc.close();
    return sb;
}

From source file:org.apache.camel.processor.idempotent.FileIdempotentRepository.java

/**
 * Loads the given file store into the 1st level cache
 *//* w w  w.  ja v  a  2s.  co m*/
protected void loadStore() {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Loading to 1st level cache from idempotent filestore: " + fileStore);
    }

    if (!fileStore.exists()) {
        return;
    }

    cache.clear();
    Scanner scanner = null;
    try {
        scanner = new Scanner(fileStore);
        scanner.useDelimiter(STORE_DELIMITER);
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            cache.put(line, line);
        }
    } catch (IOException e) {
        throw ObjectHelper.wrapRuntimeCamelException(e);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Loaded " + cache.size() + " to the 1st level cache from idempotent filestore: " + fileStore);
    }
}

From source file:org.trafodion.rest.RESTServlet.java

public synchronized List<RunningServer> getDcsServersList() {
    ArrayList<RunningServer> serverList = new ArrayList<RunningServer>();
    Stat stat = null;//from  ww  w . j av  a  2  s.  c o  m
    byte[] data = null;

    //int totalAvailable = 0;
    //int totalConnecting = 0;
    //int totalConnected = 0;

    if (LOG.isDebugEnabled())
        LOG.debug("Begin getServersList()");

    if (!runningServers.isEmpty()) {
        for (String aRunningServer : runningServers) {
            RunningServer runningServer = new RunningServer();
            Scanner scn = new Scanner(aRunningServer);
            scn.useDelimiter(":");
            runningServer.setHostname(scn.next());
            runningServer.setInstance(scn.next());
            runningServer.setInfoPort(Integer.parseInt(scn.next()));
            runningServer.setStartTime(Long.parseLong(scn.next()));
            scn.close();

            if (!registeredServers.isEmpty()) {
                for (String aRegisteredServer : registeredServers) {
                    if (aRegisteredServer
                            .contains(runningServer.getHostname() + ":" + runningServer.getInstance() + ":")) {
                        try {
                            RegisteredServer registeredServer = new RegisteredServer();
                            stat = zkc.exists(parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_REGISTERED
                                    + "/" + aRegisteredServer, false);
                            if (stat != null) {
                                data = zkc.getData(
                                        parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_REGISTERED + "/"
                                                + aRegisteredServer,
                                        false, stat);
                                scn = new Scanner(new String(data));
                                scn.useDelimiter(":");
                                if (LOG.isDebugEnabled())
                                    LOG.debug("getDataRegistered [" + new String(data) + "]");
                                registeredServer.setState(scn.next());
                                String state = registeredServer.getState();
                                //if(state.equals("AVAILABLE"))
                                //    totalAvailable += 1;
                                //else if(state.equals("CONNECTING"))
                                //    totalConnecting += 1;
                                //else if(state.equals("CONNECTED"))
                                //    totalConnected += 1;
                                registeredServer.setTimestamp(Long.parseLong(scn.next()));
                                registeredServer.setDialogueId(scn.next());
                                registeredServer.setNid(scn.next());
                                registeredServer.setPid(scn.next());
                                registeredServer.setProcessName(scn.next());
                                registeredServer.setIpAddress(scn.next());
                                registeredServer.setPort(scn.next());
                                registeredServer.setClientName(scn.next());
                                registeredServer.setClientIpAddress(scn.next());
                                registeredServer.setClientPort(scn.next());
                                registeredServer.setClientAppl(scn.next());
                                registeredServer.setIsRegistered();
                                scn.close();
                                runningServer.getRegistered().add(registeredServer);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            if (LOG.isErrorEnabled())
                                LOG.error("Exception: " + e.getMessage());
                        }
                    }
                }
            }

            serverList.add(runningServer);
        }
    }

    // metrics.setTotalAvailable(totalAvailable);
    // metrics.setTotalConnecting(totalConnecting);
    // metrics.setTotalConnected(totalConnected);

    Collections.sort(serverList, new Comparator<RunningServer>() {
        public int compare(RunningServer s1, RunningServer s2) {
            if (s1.getInstanceIntValue() == s2.getInstanceIntValue())
                return 0;
            return s1.getInstanceIntValue() < s2.getInstanceIntValue() ? -1 : 1;
        }
    });

    if (LOG.isDebugEnabled())
        LOG.debug("End getServersList()");

    return serverList;
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static Long[] subsetLongVector(InputStream in, int column, int numCases) {
    Long[] retVector = new Long[numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);
            try {
                retVector[caseIndex] = new Long(line[column]);
            } catch (NumberFormatException ex) {
                retVector[caseIndex] = null; // assume missing value
            }/*from w  w  w.  j  a  v  a  2  s .  c  o m*/
        } else {
            scanner.close();
            throw new RuntimeException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new RuntimeException(
                    "Column " + column + ": tab file has more nonempty rows than the stored number of cases ("
                            + numCases + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}

From source file:org.apache.camel.util.ObjectHelper.java

/**
 * Creates an iterator over the value if the value is a collection, an
 * Object[] or a primitive type array; otherwise to simplify the caller's
 * code, we just create a singleton collection iterator over a single value
 *
 * @param value  the value/*from w ww. j  a  v  a2 s .  c o  m*/
 * @param  delimiter  delimiter for separating String values
 * @return the iterator
 */
@SuppressWarnings("unchecked")
public static Iterator<Object> createIterator(Object value, String delimiter) {
    // if its a message than we want to iterate its body
    if (value instanceof Message) {
        value = ((Message) value).getBody();
    }

    if (value == null) {
        return Collections.emptyList().iterator();
    } else if (value instanceof Iterator) {
        return (Iterator) value;
    } else if (value instanceof Iterable) {
        return ((Iterable) value).iterator();
    } else if (value.getClass().isArray()) {
        // TODO we should handle primitive array types?
        List<Object> list = Arrays.asList((Object[]) value);
        return list.iterator();
    } else if (value instanceof NodeList) {
        // lets iterate through DOM results after performing XPaths
        final NodeList nodeList = (NodeList) value;
        return CastUtils.cast(new Iterator<Node>() {
            int idx = -1;

            public boolean hasNext() {
                return (idx + 1) < nodeList.getLength();
            }

            public Node next() {
                idx++;
                return nodeList.item(idx);
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        });
    } else if (value instanceof String) {
        final String s = (String) value;

        // this code is optimized to only use a Scanner if needed, eg there is a delimiter

        if (s.contains(delimiter)) {
            // use a scanner if it contains the delimiter
            Scanner scanner = new Scanner((String) value);
            scanner.useDelimiter(delimiter);
            return CastUtils.cast(scanner);
        } else {
            // use a plain iterator that returns the value as is as there are only a single value
            return CastUtils.cast(new Iterator<String>() {
                int idx = -1;

                public boolean hasNext() {
                    // empty string should not be regarded as having next
                    return idx + 1 == 0 && ObjectHelper.isNotEmpty(s);
                }

                public String next() {
                    idx++;
                    return s;
                }

                public void remove() {
                    throw new UnsupportedOperationException();
                }
            });
        }
    } else {
        return Collections.singletonList(value).iterator();
    }
}

From source file:edu.harvard.iq.dataverse.dataaccess.TabularSubsetGenerator.java

public static Double[][] subsetDoubleVectors(InputStream in, Set<Integer> columns, int numCases)
        throws IOException {
    Double[][] retVector = new Double[columns.size()][numCases];
    Scanner scanner = new Scanner(in);
    scanner.useDelimiter("\\n");

    for (int caseIndex = 0; caseIndex < numCases; caseIndex++) {
        if (scanner.hasNext()) {
            String[] line = (scanner.next()).split("\t", -1);
            int j = 0;
            for (Integer i : columns) {
                try {
                    // TODO: verify that NaN and +-Inf are going to be
                    // handled correctly here! -- L.A. 
                    // NO, "+-Inf" is not handled correctly; see the 
                    // comment further down below. 
                    retVector[j][caseIndex] = new Double(line[i]);
                } catch (NumberFormatException ex) {
                    retVector[j][caseIndex] = null; // missing value
                }//w  w  w. jav  a 2 s.  c  o m
                j++;
            }
        } else {
            scanner.close();
            throw new IOException("Tab file has fewer rows than the stored number of cases!");
        }
    }

    int tailIndex = numCases;
    while (scanner.hasNext()) {
        String nextLine = scanner.next();
        if (!"".equals(nextLine)) {
            scanner.close();
            throw new IOException("Tab file has more nonempty rows than the stored number of cases (" + numCases
                    + ")! current index: " + tailIndex + ", line: " + nextLine);
        }
        tailIndex++;
    }

    scanner.close();
    return retVector;

}

From source file:net.devietti.ArchConfMapServlet.java

/** Parse a URL (presumed to be pointing at an HTML page) into a Jsoup Document */
private Document getURL(String url) {
    Scanner s = null;
    try {//from  w  ww  . j a  va 2  s  . c  o m

        s = new Scanner(new URL(url).openStream(), "UTF-8");
        return Jsoup.parse(s.useDelimiter("\\A").next());

    } catch (MalformedURLException e) {
        error(e.getMessage());
    } catch (IOException e) {
        error(e.getMessage());
    } finally {
        if (s != null)
            s.close();
    }
    throw new IllegalStateException("error parsing URL " + url);
}