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:csns.importer.parser.csula.RosterParserImpl.java

/**
 * This parser handles the format under CSULA Baseline -> CSULA Student
 * Records -> Class Roster on GET. A sample record is as follows:
 * "1 123456789 Doe,John M 3.00 ETG CS MS G1". Note that some fields like
 * middle name and units may not be present, and some people's last name has
 * space in it.//  ww w.  ja v a2  s  .  c o  m
 */
private List<ImportedUser> parse1(String text) {
    List<ImportedUser> students = new ArrayList<ImportedUser>();

    Scanner scanner = new Scanner(text);
    scanner.useDelimiter("\\s+|\\r\\n|\\r|\\n");
    while (scanner.hasNext()) {
        String cin = scanner.next();
        if (!isCin(cin))
            continue;

        String name = "";
        boolean nameFound = false;
        while (scanner.hasNext()) {
            String token = scanner.next();
            name += token + " ";
            if (token.matches(".+,.*")) {
                if (token.endsWith(",") && scanner.hasNext())
                    name += scanner.next();
                nameFound = true;
                break;
            }
        }

        String grade = null;
        boolean gradeFound = false;
        boolean unitsFound = false;
        while (nameFound && scanner.hasNext()) {
            String token = scanner.next();
            if (isUnits(token)) {
                unitsFound = true;
                continue;
            }
            if (isGrade(token)) {
                if (unitsFound) // this must be a grade
                {
                    grade = token;
                    gradeFound = true;
                    break;
                } else
                // this could be a grade or a middle name
                {
                    grade = token;
                    continue;
                }
            }
            if (isProgram(token)) {
                if (grade != null)
                    gradeFound = true;
                break;
            }

            name += token + " ";
        }

        if (nameFound) {
            ImportedUser student = new ImportedUser();
            student.setCin(cin);
            student.setName(name);
            if (gradeFound)
                student.setGrade(grade);
            students.add(student);
        }
    }
    scanner.close();

    return students;
}

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

private boolean parse(final ProtocolFactory protocols, final Host current, final String line) {
    final Scanner scanner = new Scanner(line);
    scanner.useDelimiter("=");
    if (!scanner.hasNext()) {
        log.warn("Missing key in line:" + line);
        return false;
    }/*from  w ww  . j  a  v a2 s. c o  m*/
    String name = scanner.next().toLowerCase(Locale.ROOT);
    if (!scanner.hasNext()) {
        log.warn("Missing value in line:" + line);
        return false;
    }
    String value = scanner.next().replaceAll("\"", StringUtils.EMPTY);
    if ("conntype".equals(name)) {
        try {
            switch (Integer.parseInt(value)) {
            case 4:
                current.setProtocol(protocols.forScheme(Scheme.sftp));
                break;
            case 5:
                current.setProtocol(protocols.forScheme(Scheme.ftps));
                break;
            }
            // Reset port to default
            current.setPort(-1);
        } catch (NumberFormatException e) {
            log.warn("Unknown Protocol:" + e.getMessage());
        }
    } else 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 ("dir".equals(name)) {
        current.setDefaultPath(value);
    } else if ("comment".equals(name)) {
        current.setComment(value);
    } else if ("uid".equals(name)) {
        current.getCredentials().setUsername(value);
    }
    return true;
}

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

private synchronized void getZkRunning() throws Exception {
    if (LOG.isDebugEnabled())
        LOG.debug("Reading " + parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_RUNNING);
    List<String> children = getChildren(parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_RUNNING,
            new RunningWatcher());

    if (!children.isEmpty()) {
        for (String child : children) {
            //If stop-dcs.sh is executed and DCS_MANAGES_ZK then zookeeper is stopped abruptly.
            //Second scenario is when ZooKeeper fails for some reason regardless of whether DCS
            //manages it. When either happens the DcsServer running znodes still exist in ZooKeeper
            //and we see them at next startup. When they eventually timeout
            //we get node deleted events for a server that no longer exists. So, only recognize
            //DcsServer running znodes that have timestamps after last DcsMaster startup.
            Scanner scn = new Scanner(child);
            scn.useDelimiter(":");
            String hostName = scn.next();
            String instance = scn.next();
            int infoPort = Integer.parseInt(scn.next());
            long serverStartTimestamp = Long.parseLong(scn.next());
            scn.close();/*from   w  w w.  j av  a  2s  . co  m*/

            //if(serverStartTimestamp < startupTimestamp) 
            //    continue;

            if (!runningServers.contains(child)) {
                if (LOG.isDebugEnabled())
                    LOG.debug("Watching running [" + child + "]");
                zkc.exists(parentZnode + Constants.DEFAULT_ZOOKEEPER_ZNODE_SERVERS_RUNNING + "/" + child,
                        new RunningWatcher());
                runningServers.add(child);
            }
        }
        //metrics.setTotalRunning(runningServers.size());
    } //else {
      //  metrics.setTotalRunning(0);
      //}
}

From source file:com.pushinginertia.commons.net.client.AbstractHttpPostClient.java

/**
 * Retrieves the response message from the remote host.
 *
 * @param con instantiated connection/* w ww . j av  a2 s. co  m*/
 * @param encoding encoding to use in the response
 * @return response message from the remote host or null if none exists
 * @throws HttpConnectException if there is a problem retrieving the message
 */
protected String getResponseMessage(final HttpURLConnection con, final String encoding)
        throws HttpConnectException {
    try {
        final InputStream is = con.getInputStream();
        final Scanner s = new Scanner(is, encoding);
        s.useDelimiter("\\A"); // \A is the beginning of input
        if (s.hasNext())
            return s.next();
        return null;
    } catch (NoSuchElementException e) {
        // no input
        return null;
    } catch (Exception e) {
        final String msg = "An unexpected error occurred while trying to retrieve the response message from ["
                + getUrl() + "]: " + e.getMessage();
        LOG.error(getClass().getSimpleName(), msg, e);
        throw new HttpConnectException(msg, e);
    }
}

From source file:replicatedstackjgroups.ReplStack.java

private void eventLoop() {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    Scanner input = new Scanner(System.in);
    JSONObject json_obj = new JSONObject();
    while (true) {
        try {// w w  w  . ja va2s  . com
            System.out.print("> ");
            System.out.flush();
            //                String line = in.readLine().toLowerCase();
            String line = input.next().toLowerCase();

            if (line.startsWith("quit") || line.startsWith("exit"))
                break;
            else if (line.startsWith("stack_push")) {
                T object = (T) input.nextLine();
                json_obj.put("mode", "stack_push");
                json_obj.put("body", object);
            } else if (line.startsWith("stack_pop")) {
                json_obj.put("mode", "stack_pop");
                json_obj.put("body", "");
            } else if (line.startsWith("stack_top")) {
                json_obj.put("mode", "stack_top");
                json_obj.put("body", "");
            }

            Message msg = new Message(null, null, json_obj);
            channel.send(msg);
            json_obj.clear();
        } catch (Exception e) {
        }
    }
}

From source file:com.hubrick.raml.codegen.springweb.RestControllerClassGenerator.java

private void annotateActionMethod(JMethod actionMethod, ActionMetaInfo actionMetaInfo) {
    final JAnnotationUse requestMapping = actionMethod
            .annotate(codeModel.ref("org.springframework.web.bind.annotation.RequestMapping"));
    requestMapping.param("method", codeModel.ref("org.springframework.web.bind.annotation.RequestMethod")
            .staticRef(actionMetaInfo.getAction().getType().name()));

    final List<String> stringBuffer = new LinkedList<>();

    final Map<String, UriParameterDefinition> uriParameterIndex = actionMetaInfo.getUriParameterDefinitions()
            .stream().collect(toMap(p -> p.getName(), p -> p));

    JExpression uriExpression = null;/*from   w ww  .  jav a  2s  .c o  m*/
    final String uri = actionMetaInfo.getAction().getResource().getUri();
    final Scanner scanner = new Scanner(uri).useDelimiter("/");
    while (scanner.hasNext()) {
        final String token = scanner.next();
        final Matcher m = URI_PARAMETER_PATTERN.matcher(token);
        if (m.find()) {
            final String param = m.group("param");

            final UriParameterDefinition p = uriParameterIndex.get(param);

            checkState(p != null, "Parameter [%s] definition not found", param);

            final PatternDefinition patternDefinition = p.getPattern();
            if (patternDefinition instanceof InlinePatternDefinition) {
                stringBuffer.add(
                        "/{" + param + ":" + ((InlinePatternDefinition) patternDefinition).getPattern() + "}");
            } else if (patternDefinition instanceof ReferencedPatternDefinition) {
                final String reference = ((ReferencedPatternDefinition) patternDefinition).getReference();
                stringBuffer.add("/{" + p.getName() + ":");

                final String[] components = reference.split("\\.(?=[^\\.]+$)");
                uriExpression = concat(uriExpression, concat(flushBuffer(stringBuffer),
                        codeModel.ref(components[0]).staticRef(components[1])));
                stringBuffer.add("}");
            } else if (patternDefinition == null) {
                stringBuffer.add("/{" + param + "}");
            } else {
                throw new IllegalStateException(
                        "Unknown pattern definition type: " + patternDefinition.getClass().getName());
            }

        } else {
            stringBuffer.add("/" + token);
        }
    }

    uriExpression = concat(uriExpression, flushBuffer(stringBuffer));

    requestMapping.param("value", uriExpression);
}

From source file:org.unitedinternet.cosmo.db.DbInitializer.java

private List<String> readStatements(String resource) {
    List<String> statements = new ArrayList<>();
    Scanner scanner = null;
    try {//from w ww . j  av  a 2  s.co  m
        scanner = new Scanner(this.getClass().getResourceAsStream(resource), StandardCharsets.UTF_8.name());
        scanner.useDelimiter(";");
        while (scanner.hasNext()) {
            String statement = scanner.next().replace("\n", " ").trim();
            if (!statement.isEmpty()) {
                statements.add(statement);
            }
        }
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    return statements;
}

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

private String readProcess(Process p) {
    try {//from w  w  w  .  j a  v a2  s.com
        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.
 *//*from   www. ja  va2  s .  c o  m*/
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.wso2.charon.core.config.SCIMUserSchemaExtensionBuilder.java

/**
 * This method reads configuration file and stores in the memory as an
 * configuration map/*from  w w w . j  ava  2s  . 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);
    }
}