Example usage for java.util Scanner next

List of usage examples for java.util Scanner next

Introduction

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

Prototype

public String next() 

Source Link

Document

Finds and returns the next complete token from this scanner.

Usage

From source file:org.ff4j.store.RemoteHttpFeatureStore.java

/**
 * Invole GET webServices to feature./*from w  w w .  ja  va2  s .  co  m*/
 * 
 * @param path
 *            target path
 * @param featureId
 *            current feature id
 * @return JSON output response
 */
private String makeGetCall(String path, String featureId) {
    try {
        // Create request
        HttpGet getRequest = new HttpGet(url + path + "/" + featureId);
        getRequest.addHeader("accept", JSON);
        HttpResponse response = httpClient.execute(getRequest);

        java.util.Scanner s = new java.util.Scanner(response.getEntity().getContent()).useDelimiter("\\A");
        String output = s.hasNext() ? s.next() : "";
        httpClient.getConnectionManager().shutdown();

        // Handle Error
        if (response.getStatusLine().getStatusCode() == 404) {
            throw new FeatureNotFoundException(output);
        }
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new FeatureAccessException(
                    "ErrorHTTP(" + response.getStatusLine().getStatusCode() + ") - " + output);
        }

        return output;

    } catch (ClientProtocolException cpe) {
        throw new FeatureAccessException("Cannot access remote HTTP Feature Store", cpe);
    } catch (IOException ioe) {
        throw new FeatureAccessException("Cannot read response from  HTTP Feature Store", ioe);
    }
}

From source file:me.figo.FigoConnection.java

/***
 * Handle the response of a request by decoding its JSON payload
 * @param stream Stream containing the JSON data
 * @param typeOfT Type of the data to be expected
 * @return Decoded data//from   w  w  w .  ja va  2 s  .c  o m
 */
private <T> T handleResponse(InputStream stream, Type typeOfT) {
    // check whether decoding is actual requested
    if (typeOfT == null)
        return null;

    // read stream body
    Scanner s = new Scanner(stream, "UTF-8");
    s.useDelimiter("\\A");
    String body = s.hasNext() ? s.next() : "";
    s.close();

    // decode JSON payload
    Gson gson = GsonAdapter.createGson();
    return gson.fromJson(body, typeOfT);
}

From source file:org.sipfoundry.sipxconfig.conference.FreeswitchApiResultParserImpl.java

private ActiveConferenceMember parseConferenceMember(String line, String conferenceName) {
    ActiveConferenceMember member = new ActiveConferenceMember();

    Scanner scan = new Scanner(line);
    scan.useDelimiter(COMMAND_LIST_DELIM);

    member.setId(scan.nextInt());//from ww w .j av a  2  s. co m

    String sipAddress = scan.next().split("/")[2];

    member.setUuid(scan.next());

    String callerIdName = scan.next();
    if (callerIdName.equals(conferenceName)) {
        callerIdName = "";
    }

    scan.next(); // skip caller ID number

    String permissions = scan.next();
    member.setCanHear(permissions.contains("hear"));
    member.setCanSpeak(permissions.contains("speak"));

    member.setName(callerIdName + " (" + sipAddress + ")");

    member.setVolumeIn(scan.nextInt());
    member.setVolumeOut(scan.nextInt());
    member.setEnergyLevel(scan.nextInt());
    return member;
}

From source file:com.marklogic.client.functionaltest.TestBulkWriteWithTransformations.java

@Test
public void testBulkLoadWithXSLTClientSideTransform() throws Exception {
    String docId[] = { "/transform/emp.xml", "/transform/food1.xml", "/transform/food2.xml" };
    Source s[] = new Source[3];
    s[0] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/employee.xml");
    s[1] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/xml-original.xml");
    s[2] = new StreamSource("src/test/java/com/marklogic/client/functionaltest/data/xml-original-test.xml");
    // get the xslt
    Source xsl = new StreamSource(
            "src/test/java/com/marklogic/client/functionaltest/data/employee-stylesheet.xsl");

    // create transformer
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer(xsl);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    XMLDocumentManager docMgr = client.newXMLDocumentManager();
    DocumentWriteSet writeset = docMgr.newWriteSet();
    for (int i = 0; i < 3; i++) {
        SourceHandle handle = new SourceHandle();
        handle.set(s[i]);//w ww.  j a va 2 s. c om
        // set the transformer
        handle.setTransformer(transformer);
        writeset.add(docId[i], handle);
        //Close handle.
        handle.close();
    }
    docMgr.write(writeset);
    FileHandle dh = new FileHandle();
    //       DOMHandle dh = new DOMHandle();
    docMgr.read(docId[0], dh);
    Scanner scanner = new Scanner(dh.get()).useDelimiter("\\Z");
    String readContent = scanner.next();
    assertTrue("xml document contains firstname", readContent.contains("firstname"));
    docMgr.read(docId[1], dh);
    Scanner sc1 = new Scanner(dh.get()).useDelimiter("\\Z");
    readContent = sc1.next();
    assertTrue("xml document contains firstname", readContent.contains("firstname"));
    docMgr.read(docId[2], dh);
    Scanner sc2 = new Scanner(dh.get()).useDelimiter("\\Z");
    readContent = sc2.next();
    assertTrue("xml document contains firstname", readContent.contains("firstname"));

}

From source file:org.sipfoundry.sipxconfig.freeswitch.api.FreeswitchApiResultParserImpl.java

private ActiveConferenceMember parseConferenceMember(String line, String conferenceName) {
    ActiveConferenceMember member = new ActiveConferenceMember();

    Scanner scan = new Scanner(line);
    scan.useDelimiter(COMMAND_LIST_DELIM);

    member.setId(scan.nextInt());// w  ww. j a  v  a2 s.  co m

    String sipAddress = scan.next().split("/")[2];

    member.setUuid(scan.next());

    String callerIdName = scan.next();
    if (callerIdName.equals(conferenceName)) {
        callerIdName = "";
    }

    String number = scan.next();

    String permissions = scan.next();
    member.setCanHear(permissions.contains("hear"));
    member.setCanSpeak(permissions.contains("speak"));

    member.setNumber(number);

    member.setName(callerIdName + " (" + sipAddress + ")");

    member.setVolumeIn(scan.nextInt());
    member.setVolumeOut(scan.nextInt());
    member.setEnergyLevel(scan.nextInt());
    return member;
}

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

/**
 * Parses the given input stream./*from w  ww .  j av a2  s  .c  o  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:com.git.ifly6.javatelegram.util.JInfoFetcher.java

/** Queries the NationStates API for a listing of all World Assembly delegates.
 *
 * @return <code>String[]</code> with the recipients inside
 * @throws IOException in case there is a problem with connecting to the NS API */
public List<String> getDelegates() throws JTelegramException {

    // If necessary, fetch the Delegates list.
    if (delegates == null) {

        try {//from  ww  w.jav a 2 s.com
            List<String> delegates = new ArrayList<String>(0);
            URL website = new URL("http://www.nationstates.net/cgi-bin/api.cgi?wa=1&q=delegates");

            String xml_raw = "";

            // Read the list of Delegates from the file we just got.
            @SuppressWarnings("resource")
            Scanner xml_scan = new Scanner(website.openConnection().getInputStream()).useDelimiter("\\A");
            xml_raw = xml_scan.next();
            xml_scan.close();

            // Remove the XML tags from that list of Delegates.
            xml_raw = xml_raw.replaceFirst("<WA council=\"1\"><DELEGATES>", "");
            xml_raw = xml_raw.replaceFirst("</DELEGATES></WA>", "");

            // Split that list into a String[] and remove all new lines.
            for (String each : xml_raw.split(",")) {
                if (!StringUtils.isEmpty(each)) {
                    delegates.add(each);
                }
            }

            this.delegates = delegates;

        } catch (IOException e) {
            throw new JTelegramException("Failed to get list of delegates.");
        }
    }

    // Return the new or saved Delegates list.
    return delegates;
}

From source file:csns.importer.parser.MFTScoreParser.java

public void parse(MFTScoreImporter importer) {
    Department department = importer.getDepartment();
    Date date = importer.getDate();

    Scanner scanner = new Scanner(importer.getText());
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    while (scanner.hasNext()) {
        // last name
        String lastName = scanner.next();
        while (!lastName.endsWith(","))
            lastName += " " + scanner.next();
        lastName = lastName.substring(0, lastName.length() - 1);

        // first name
        String firstName = scanner.next();

        // score//from  w w  w  .j  av  a  2  s.  c om
        Stack<String> stack = new Stack<String>();
        String s = scanner.next();
        while (!isScore(s)) {
            stack.push(s);
            s = scanner.next();
        }
        int value = Integer.parseInt(s);

        // authorization code
        stack.pop();

        // cin
        String cin = null;
        if (!stack.empty() && isCin(stack.peek()))
            cin = stack.pop();

        // user
        User user = null;
        if (cin != null)
            user = userDao.getUserByCin(cin);
        else {
            List<User> users = userDao.getUsers(lastName, firstName);
            if (users.size() == 1)
                user = users.get(0);
        }

        if (user != null) {
            MFTScore score = mftScoreDao.getScore(department, date, user);
            if (score == null) {
                score = new MFTScore();
                score.setDepartment(department);
                score.setDate(date);
                score.setUser(user);
            } else {
                logger.info(user.getId() + ": " + score.getValue() + " => " + value);
            }
            score.setValue(value);
            importer.getScores().add(score);
        } else {
            User failedUser = new User();
            failedUser.setLastName(lastName);
            failedUser.setFirstName(firstName);
            failedUser.setCin(cin);
            importer.getFailedUsers().add(failedUser);
        }

        logger.debug(lastName + "," + firstName + "," + cin + "," + value);
    }

    scanner.close();
}

From source file:by.bsu.zmiecer.PieChartDemo1.java

/**
 * Creates a sample dataset.//from   w ww .  jav a 2s .c  o  m
 * 
 * Source: http://www.bbc.co.uk/news/business-15489523
 *
 * @return A sample dataset.
 */
private PieDataset createDataset() {
    DefaultPieDataset dataset = new DefaultPieDataset();
    try {

        File file = new File(
                "C:\\Users\\\\\\GitHub\\BSU\\2 course\\Practical Training\\Week 5\\Task53\\input.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext()) {
            String name;
            if (sc.hasNext())
                name = sc.next();
            else
                throw new InputMismatchException();
            Double val;
            if (sc.hasNext()) {
                val = Double.valueOf(sc.next());
                if (val < 0)
                    throw new NumberFormatException();
            } else
                throw new InputMismatchException();
            dataset.setValue(name, val);
        }
    } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(getParent(), "File not found!");
    } catch (InputMismatchException e) {
        JOptionPane.showMessageDialog(getParent(), "Enter corret data!");
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(getParent(), "Enter corret data!");
    }
    return dataset;
}

From source file:gtu._work.ui.RegexTestUI.java

private void jText1OrJArea1Change(DocumentEvent doc) {
    try {// ww w  .  j  a v a 2 s .c  o 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();
    }
}