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:eu.project.ttc.resources.SimpleWordSet.java

public void load(DataResource data) throws ResourceInitializationException {
    InputStream inputStream = null;
    this.elements = Sets.newHashSet();
    try {/*from   w  ww . j av a 2  s  .com*/
        inputStream = data.getInputStream();
        Scanner scanner = null;
        try {
            String word, line;
            String[] str, wordTranslations;
            scanner = new Scanner(inputStream, "UTF-8");
            scanner.useDelimiter(TermSuiteConstants.LINE_BREAK);
            while (scanner.hasNext()) {
                line = scanner.next().split(TermSuiteConstants.DIESE)[0].trim();
                str = line.split(TermSuiteConstants.TAB);
                word = str[0];
                if (str.length > 0)
                    this.elements.add(word);
                if (str.length > 1) {
                    // Set the second line as the translation
                    wordTranslations = str[1].split(TermSuiteConstants.COMMA);
                    for (String translation : wordTranslations) {
                        translations.put(word, translation);
                    }
                }

            }
            this.elements = ImmutableSet.copyOf(this.elements);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ResourceInitializationException(e);
        } finally {
            IOUtils.closeQuietly(scanner);
        }
    } catch (IOException e) {
        LOGGER.error("Could not load file {}", data.getUrl());
        throw new ResourceInitializationException(e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.wso2.charon.core.config.SCIMUserSchemaExtensionBuilder.java

/**
 * This method reads configuration file and stores in the memory as an
 * configuration map/*from   ww w.j  av a  2  s.c o  m*/
 * 
 * @param configFilePath
 * @throws CharonException
 */
private void readConfiguration(String configFilePath) throws CharonException {
    File provisioningConfig = new File(configFilePath);
    try {
        InputStream inputStream = new FileInputStream(provisioningConfig);
        java.util.Scanner scaner = new java.util.Scanner(inputStream).useDelimiter("\\A");
        String jsonString = scaner.hasNext() ? scaner.next() : "";

        JSONArray attributeConfigArray = new JSONArray(jsonString);

        for (int index = 0; index < attributeConfigArray.length(); ++index) {
            JSONObject attributeConfig = attributeConfigArray.getJSONObject(index);
            ExtensionAttributeSchemaConfig attrubteConfig = new ExtensionAttributeSchemaConfig(attributeConfig);
            extensionConfig.put(attrubteConfig.getAttributeName(), attrubteConfig);

            /**
             * NOTE: Assume last config is the root config
             */
            if (index == attributeConfigArray.length() - 1) {
                extensionRootAttributeName = attrubteConfig.getAttributeName();
            }
        }
        inputStream.close();
    } catch (FileNotFoundException e) {
        throw new CharonException(SCIMConfigConstants.SCIM_SCHEMA_EXTENSION_CONFIG + " file not found!", e);
    } catch (JSONException e) {
        throw new CharonException(
                "Error while parsing " + SCIMConfigConstants.SCIM_SCHEMA_EXTENSION_CONFIG + " file!", e);
    } catch (IOException e) {
        throw new CharonException(
                "Error while closing " + SCIMConfigConstants.SCIM_SCHEMA_EXTENSION_CONFIG + " file!", e);
    }
}

From source file:org.jboss.tools.openshift.internal.common.core.util.CommandLocationLookupStrategy.java

private String readProcess(Process p) {
    try {//w w w.jav a 2 s .c  om
        p.waitFor();
    } catch (InterruptedException ie) {
        // Ignore, expected
    }
    InputStream is = null;
    if (p.exitValue() == 0) {
        is = p.getInputStream();
    } else {
        // For debugging only
        //is = p.getErrorStream();
    }
    if (is != null) {
        try {
            java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
            String cmdOutput = s.hasNext() ? s.next() : "";
            if (!cmdOutput.isEmpty()) {
                cmdOutput = StringUtils.trim(cmdOutput);
                return cmdOutput;
            }
        } finally {
            try {
                if (p != null) {
                    p.destroy();
                }
                is.close();
            } catch (IOException ioe) {
                // ignore
            }
        }
    }
    return null;
}

From source file:am.roadpolice.roadpolice.downloaders.Submitter.java

/**
 * This function process URL and collect needed information about
 * violation and add it to Violation List (mViolationInfoList).
 *
 * @param url URL from which data will be processed.
 * @return null if no error occurs; otherwise ERROR1/ERROR2 if something
 * was changed in server behaviour,  ERROR3 if error occurs while trying
 * to get JSOUP document, or server error text.
 *//*ww w.  jav  a 2s  .  com*/
private String processUrl(final String url) {
    Logger.debugLine();
    Logger.debug(TAG, "Processing URL: " + url);

    HttpGet httpGet = new HttpGet(url);
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECT_TIMEOUT);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

    try {

        HttpResponse response = httpClient.execute(httpGet);
        java.util.Scanner s = new java.util.Scanner(response.getEntity().getContent()).useDelimiter("\\A");

        Document document = Jsoup.parse(s.hasNext() ? s.next() : null);
        // In the case if  some data  was provided not correct in
        // the url server generates page with red text, we handle
        // this situation and return text in the red block.
        Elements errorElement = document.getElementsByClass("red");
        if (errorElement != null && errorElement.first() != null) {
            final String errorText = errorElement.first().text();
            Logger.debug(TAG, "Found Error Element (RED): " + errorText);
            return errorText;
        }

        Elements tableElements = document.getElementsByClass("dahk_yes");
        tableElements.addAll(document.getElementsByClass("dahk_no"));
        for (Element element : tableElements) {
            Elements tdElements = element.getElementsByTag("td");

            int tdElementsCount = ViolationInfo.COL_OWNER_FULL_NAME;
            ViolationInfo violationInfo = null;
            for (Element tdElement : tdElements) {
                final String text = tdElement.text().trim();

                // We found vehicle registration number.
                if (text.equalsIgnoreCase(mRegNum)) {
                    // Create new class object to store data.
                    violationInfo = new ViolationInfo(mRegNum);
                    violationInfo.setCertificateNumber(mCerNum);
                    continue;
                }

                // Violation Info object was not created, reason can be
                // that something is changed on the server side.
                if (violationInfo == null) {
                    return ERROR_ON_SERVER_SIDE;
                }

                switch (tdElementsCount) {
                case ViolationInfo.COL_OWNER_FULL_NAME:
                    violationInfo.setOwnerFullName(text);
                    break;

                case ViolationInfo.COL_OWNER_ADDRESS:
                    violationInfo.setOwnerAddress(text);
                    break;

                case ViolationInfo.COL_TO_PAY:
                    violationInfo.setToPay(text);
                    break;

                case ViolationInfo.COL_PAYED:
                    violationInfo.setPayed(text);
                    break;

                case ViolationInfo.COL_CAR_MODEL:
                    violationInfo.setCarModel(text);
                    break;

                case ViolationInfo.COL_THE_DECISION:
                    // Do Nothing ...
                    break;

                case ViolationInfo.COL_DATE:
                    violationInfo.setDate(text);
                    break;

                case ViolationInfo.COL_PIN:
                    violationInfo.setPin(text);
                    break;

                default:
                    return ERROR_WHILE_PARSING_DATA;
                }

                tdElementsCount++;
            }

            // Add items to the list.
            mViolationInfoList.add(violationInfo);
        }
    } catch (IOException e) {
        Logger.error(TAG, "----> Exception occurs while trying to get JSOUP document.");
        Logger.error(TAG, "----> Message: " + e.getMessage());
        return ERROR_WHILE_CREATING_JSOUP;
    }

    return null;
}

From source file:org.isatools.isacreator.wizard.AddAssayPane.java

private String[] retrieveArrayDesigns() {
    String[] arrayDesignList = new String[] { "no designs available" };
    StringBuilder data = new StringBuilder();

    File arrayDesignsFile = new File(ARRAY_DESIGN_FILE);

    if (arrayDesignsFile.exists()) {

        try {/* w  w  w  . j a  v a  2  s  .  com*/
            Scanner sc = new Scanner(arrayDesignsFile);
            Pattern p = Pattern.compile("[a-zA-Z]+-[a-zA-Z]+-[0-9]+");
            while (sc.hasNext()) {
                String nextLine = sc.nextLine();

                String[] nextLineArray = nextLine.split("\t");

                String candidateEntry = nextLineArray[1].trim();
                String candidateDescription = null;
                if (nextLineArray.length > 2) {
                    candidateDescription = nextLine.split("\t")[2].trim();
                }

                Matcher m = p.matcher(candidateEntry);
                if (m.matches()) {
                    data.append(candidateEntry);

                    if (candidateDescription != null) {
                        data.append(" - ").append(candidateDescription);
                    }
                    data.append(":");
                }
            }

            if (!(data.length() == 0)) {
                String dataStr = data.toString();
                dataStr = dataStr.substring(0, data.length() - 1);
                arrayDesignList = dataStr.split(":");
            }

        } catch (FileNotFoundException e) {
            log.error("File not found: " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("Precautionary catch thrown if file contents are incorrect!!");
        }
    }
    return arrayDesignList;
}

From source file:eu.skillpro.ams.pscm.connector.amsservice.ui.AutomaticOrdersProcessingHandler.java

protected String loadFile(String filename) {
    InputStream inputStream = this.getClass().getResourceAsStream("/resources/" + filename);
    if (inputStream != null) {
        Scanner s = new Scanner(inputStream).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    } else {//from w  w  w . ja  v a2 s  .  c  om
        return "";
    }
}

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

public ArrayList<Event> readBacktestData() throws FileNotFoundException {
    ClassLoader classLoader = getClass().getClassLoader();
    Scanner scan = new Scanner(
            new File(classLoader.getResource("backtest-data-aio-" + DATA_SET + ".csv").getFile()));
    ArrayList<Event> list = new ArrayList();
    Event event;//from  www.  j  av a 2 s  . co m
    String[] split;
    while (scan.hasNext()) {
        event = new Event();
        split = scan.nextLine().split(",");

        event.setSymbol(split[2]);
        event.setPrice(Double.parseDouble(split[1]));

        list.add(event);
    }
    return list;
}

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);/* w  ww  .  jav a  2  s  .  co 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:org.springframework.web.servlet.resource.AppCacheManifestTransformer.java

@Override
public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain chain)
        throws IOException {

    resource = chain.transform(request, resource);
    if (!this.fileExtension.equals(StringUtils.getFilenameExtension(resource.getFilename()))) {
        return resource;
    }/*from w  w  w  .j ava 2 s .c  o  m*/

    byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
    String content = new String(bytes, DEFAULT_CHARSET);

    if (!content.startsWith(MANIFEST_HEADER)) {
        if (logger.isTraceEnabled()) {
            logger.trace("Manifest should start with 'CACHE MANIFEST', skip: " + resource);
        }
        return resource;
    }

    if (logger.isTraceEnabled()) {
        logger.trace("Transforming resource: " + resource);
    }

    Scanner scanner = new Scanner(content);
    LineInfo previous = null;
    LineAggregator aggregator = new LineAggregator(resource, content);

    while (scanner.hasNext()) {
        String line = scanner.nextLine();
        LineInfo current = new LineInfo(line, previous);
        LineOutput lineOutput = processLine(current, request, resource, chain);
        aggregator.add(lineOutput);
        previous = current;
    }

    return aggregator.createResource();
}

From source file:org.molasdin.wbase.xml.parser.light.basic.BasicParser.java

private Pair<String, List<Pair<String, String>>> extractTag(String value) {
    Scanner scanner = new Scanner(value);
    scanner.useDelimiter("\\s+");
    String tag = null;/*  w ww .ja v  a2  s. co m*/
    if (scanner.hasNext()) {
        tag = scanner.next();
        if (!isValidTag(tag)) {
            return null;
        }
    } else {
        return null;
    }

    if (tag.contains("/")) {
        return null;
    }

    List<Pair<String, String>> attributes = new ArrayList<Pair<String, String>>();

    while (scanner.hasNext()) {
        String part = scanner.next().trim();
        Matcher matcher = attributePattern.matcher(part);
        if (!matcher.matches()) {
            return null;
        }
        Pair<String, String> attribute = Pair.of(matcher.group(1), matcher.group(2));
        attributes.add(attribute);
    }

    return Pair.of(tag, attributes);
}