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.trafodion.rest.RESTServlet.java

public synchronized List<RunningServer> getDcsServersList() {
    ArrayList<RunningServer> serverList = new ArrayList<RunningServer>();
    Stat stat = null;/*from www  .ja  v  a 2 s  . c om*/
    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:ch.cyberduck.core.importer.WinScpBookmarkCollection.java

@Override
protected void parse(final ProtocolFactory protocols, final Local file) throws AccessDeniedException {
    try {//from   ww  w . j a  va 2 s. c om
        final BufferedReader in = new BufferedReader(
                new InputStreamReader(file.getInputStream(), Charset.forName("UTF-8")));
        try {
            Host current = null;
            String line;
            while ((line = in.readLine()) != null) {
                if (line.startsWith("[Sessions\\")) {
                    current = new Host(protocols.forScheme(Scheme.sftp));
                    current.getCredentials()
                            .setUsername(PreferencesFactory.get().getProperty("connection.login.anon.name"));
                    Pattern pattern = Pattern.compile("\\[Session\\\\(.*)\\]");
                    Matcher matcher = pattern.matcher(line);
                    if (matcher.matches()) {
                        current.setNickname(matcher.group(1));
                    }
                } else if (StringUtils.isBlank(line)) {
                    this.add(current);
                    current = null;
                } else {
                    if (null == current) {
                        log.warn("Failed to detect start of bookmark");
                        continue;
                    }
                    Scanner scanner = new Scanner(line);
                    scanner.useDelimiter("=");
                    if (!scanner.hasNext()) {
                        log.warn("Missing key in line:" + line);
                        continue;
                    }
                    String name = scanner.next().toLowerCase(Locale.ROOT);
                    if (!scanner.hasNext()) {
                        log.warn("Missing value in line:" + line);
                        continue;
                    }
                    String value = scanner.next();
                    if ("hostname".equals(name)) {
                        current.setHostname(value);
                    } else if ("username".equals(name)) {
                        current.getCredentials().setUsername(value);
                    } else if ("portnumber".equals(name)) {
                        try {
                            current.setPort(Integer.parseInt(value));
                        } catch (NumberFormatException e) {
                            log.warn("Invalid Port:" + e.getMessage());
                        }
                    } else if ("fsprotocol".equals(name)) {
                        try {
                            switch (Integer.parseInt(value)) {
                            case 0:
                            case 1:
                            case 2:
                                current.setProtocol(protocols.forScheme(Scheme.sftp));
                                break;
                            case 5:
                                current.setProtocol(protocols.forScheme(Scheme.ftp));
                                break;
                            }
                            // Reset port to default
                            current.setPort(-1);
                        } catch (NumberFormatException e) {
                            log.warn("Unknown Protocol:" + e.getMessage());
                        }
                    }
                }
            }
        } finally {
            IOUtils.closeQuietly(in);
        }
    } catch (IOException e) {
        throw new AccessDeniedException(e.getMessage(), e);
    }
}

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

/**
 * extract the last names of the authors
 * /*w ww.  j a v  a2 s .co 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:com.haulmont.cuba.core.sys.utils.DbUpdaterUtil.java

@SuppressWarnings("AccessStaticViaInstance")
public void execute(String[] args) {
    Options cliOptions = new Options();

    Option dbConnectionOption = OptionBuilder.withArgName("connectionString").hasArgs()
            .withDescription("JDBC Database URL").isRequired().create("dbUrl");

    Option dbUserOption = OptionBuilder.withArgName("userName").hasArgs().withDescription("Database user")
            .isRequired().create("dbUser");

    Option dbPasswordOption = OptionBuilder.withArgName("password").hasArgs()
            .withDescription("Database password").isRequired().create("dbPassword");

    Option dbDriverClassOption = OptionBuilder.withArgName("driverClassName").hasArgs()
            .withDescription("JDBC driver class name").create("dbDriver");

    Option dbDirOption = OptionBuilder.withArgName("filePath").hasArgs()
            .withDescription("Database scripts directory").isRequired().create("scriptsDir");

    Option dbTypeOption = OptionBuilder.withArgName("dbType").hasArgs()
            .withDescription("DBMS type: postgres|mssql|oracle|etc").isRequired().create("dbType");

    Option dbVersionOption = OptionBuilder.withArgName("dbVersion").hasArgs()
            .withDescription("DBMS version: 2012|etc").create("dbVersion");

    Option dbExecuteGroovyOption = OptionBuilder.withArgName("executeGroovy").hasArgs()
            .withDescription("Ignoring Groovy scripts").create("executeGroovy");

    Option showUpdatesOption = OptionBuilder.withDescription("Print update scripts").create("check");

    Option applyUpdatesOption = OptionBuilder.withDescription("Update database").create("update");

    Option createDbOption = OptionBuilder.withDescription("Create database").create("create");

    cliOptions.addOption("help", false, "Print help");
    cliOptions.addOption(dbConnectionOption);
    cliOptions.addOption(dbUserOption);/*from   w  w w. j  a  v  a  2s  . co m*/
    cliOptions.addOption(dbPasswordOption);
    cliOptions.addOption(dbDirOption);
    cliOptions.addOption(dbTypeOption);
    cliOptions.addOption(dbVersionOption);
    cliOptions.addOption(dbExecuteGroovyOption);
    cliOptions.addOption(showUpdatesOption);
    cliOptions.addOption(applyUpdatesOption);
    cliOptions.addOption(createDbOption);

    CommandLineParser parser = new PosixParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;
    try {
        cmd = parser.parse(cliOptions, args);
    } catch (ParseException exp) {
        formatter.printHelp("dbupdate", cliOptions);
        return;
    }

    if (cmd.hasOption("help") || (!cmd.hasOption(showUpdatesOption.getOpt()))
            && !cmd.hasOption(applyUpdatesOption.getOpt()) && !cmd.hasOption(createDbOption.getOpt()))
        formatter.printHelp("dbupdate", cliOptions);
    else {
        this.dbScriptsDirectory = cmd.getOptionValue(dbDirOption.getOpt());
        File directory = new File(dbScriptsDirectory);
        if (!directory.exists()) {
            log.error("Not found db update directory");
            return;
        }

        dbmsType = cmd.getOptionValue(dbTypeOption.getOpt());
        dbmsVersion = StringUtils.trimToEmpty(cmd.getOptionValue(dbVersionOption.getOpt()));

        AppContext.Internals.setAppComponents(new AppComponents("core"));

        AppContext.setProperty("cuba.dbmsType", dbmsType);
        AppContext.setProperty("cuba.dbmsVersion", dbmsVersion);

        String dbDriver;
        if (!cmd.hasOption(dbDriverClassOption.getOpt())) {
            switch (dbmsType) {
            case "postgres":
                dbDriver = "org.postgresql.Driver";
                break;
            case "mssql":
                if (MS_SQL_2005.equals(dbmsVersion)) {
                    dbDriver = "net.sourceforge.jtds.jdbc.Driver";
                } else {
                    dbDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
                }
                break;
            case "oracle":
                dbDriver = "oracle.jdbc.OracleDriver";
                break;
            default:
                log.error(
                        "Unable to determine driver class name by DBMS type. Please provide driverClassName option");
                return;
            }
        } else {
            dbDriver = cmd.getOptionValue(dbDriverClassOption.getOpt());
        }

        try {
            Class.forName(dbDriver);
        } catch (ClassNotFoundException e) {
            log.error("Unable to load driver class " + dbDriver);
            return;
        }

        String connectionStringParam = cmd.getOptionValue(dbConnectionOption.getOpt());
        try {
            this.dataSource = new SingleConnectionDataSource(connectionStringParam,
                    cmd.getOptionValue(dbUserOption.getOpt()), cmd.getOptionValue(dbPasswordOption.getOpt()));
        } catch (SQLException e) {
            log.error("Unable to connect to db: " + connectionStringParam);
            return;
        }

        if (cmd.hasOption(createDbOption.getOpt())) {
            // create database from init scripts
            StringBuilder availableScripts = new StringBuilder();
            for (ScriptResource initScript : getInitScripts()) {
                availableScripts.append("\t").append(getScriptName(initScript)).append("\n");
            }
            log.info("Available create scripts: \n" + availableScripts);
            log.info(String.format("Do you want to create database %s ? [y/n]", connectionStringParam));
            Scanner scanner = new Scanner(new InputStreamReader(System.in, StandardCharsets.UTF_8));
            if ("y".equals(scanner.next())) {
                doInit();
            }
        } else {
            boolean updatesAvailable = false;
            try {
                List<String> scripts;

                executeGroovy = !(cmd.hasOption(dbExecuteGroovyOption.getOpt())
                        && cmd.getOptionValue(dbExecuteGroovyOption.getOpt()).equals("false"));

                scripts = findUpdateDatabaseScripts();

                if (!scripts.isEmpty()) {
                    StringBuilder availableScripts = new StringBuilder();
                    for (String script : scripts) {
                        availableScripts.append("\t").append(script).append("\n");
                    }
                    log.info("Available updates:\n" + availableScripts);
                    updatesAvailable = true;
                } else
                    log.info("No available updates found for database");
            } catch (DbInitializationException e) {
                log.warn("Database not initialized");
                return;
            }

            if (updatesAvailable && cmd.hasOption(applyUpdatesOption.getOpt())) {
                log.info(String.format("Do you want to apply updates to %s ? [y/n]", connectionStringParam));
                Scanner scanner = new Scanner(new InputStreamReader(System.in, StandardCharsets.UTF_8));
                if ("y".equals(scanner.next())) {
                    doUpdate();
                }
            }
        }
    }
}

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

@Override
public void load(DataResource data) throws ResourceInitializationException {
    InputStream inputStream = null;
    try {/*from ww w .  ja v  a 2  s.co  m*/
        this.path = data.getUri().toString();
        LOGGER.debug("Loading reference term list at {}", this.path);
        inputStream = data.getInputStream();
        Scanner scanner = null;
        try {
            scanner = new Scanner(inputStream);
            scanner.useDelimiter(TermSuiteConstants.LINE_BREAK);
            while (scanner.hasNext()) {
                lineNb++;
                String line = scanner.next().split(TermSuiteConstants.DIESE)[0].trim();
                List<String> els = Splitter.on(TermSuiteConstants.TAB).splitToList(line.trim().toLowerCase());
                if (!els.isEmpty()) {
                    if (els.size() != 3)
                        LOGGER.warn("Ignoring line {} : should have exactly 3 elements ({})", lineNb, line);
                    else {
                        int id = Integer.parseInt(els.get(0));
                        RTLTerm refTerm = new RTLTerm(lineNb, id, els.get(2),
                                els.get(1).toLowerCase().equals("v"));
                        if (refTerm.isVariant()) {
                            if (!bases.containsKey(id)) {
                                LOGGER.warn("No such base term id {} for variant term {}", id, refTerm);
                                continue;
                            } else
                                bases.get(id).addVariant(refTerm);
                        } else {
                            bases.put(id, refTerm);
                        }
                    }
                }
            }
            this.bases = ImmutableMap.copyOf(this.bases);
            int total = 0;
            for (RTLTerm ref : bases.values())
                total += 1 + ref.getVariants().size();
            LOGGER.debug("Reference term list loaded (nb terms: {}, nb terms and variants: {})",
                    this.bases.keySet().size(), total);
        } 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:it.isti.cnr.hpc.europeana.hackthon.domain.GoogleQuery2Entity.java

/**
 * @param string//from w w  w . ja  va2 s . c o  m
 * @return
 */
private List<Result> parseResults(String string) {
    Scanner scanner = new Scanner(string).useDelimiter("<h3");
    List<Result> results = new ArrayList<Result>(10);
    while (scanner.hasNext()) {
        Result r = getResult(scanner.next());
        if (r != null)
            results.add(r);
    }
    return results;
}

From source file:org.sead.repositories.reference.RefRepository.java

private static String handleRepub(C3PRPubRequestFacade RO, BagGenerator bg, String localSource) {

    JSONObject request = RO.getPublicationRequest();
    JSONObject prefs = request.getJSONObject("Preferences");
    Scanner input = new Scanner(System.in);
    if (prefs.has("External Identifier")) {
        String extIdPref = prefs.getString("External Identifier");
        System.out.println("This publication is intended to replace " + extIdPref);
        if (!((String) getProps().get("repo.allowupdates")).equalsIgnoreCase("true")) {
            System.out.println("NOTE: Since updates are not allowed, a new DOI will be generated.");
        }/*from  w w w.  j  a va  2  s . c om*/
        System.out.println("Proceed (Y/N)?: ");

        if (!input.next().equalsIgnoreCase("y")) {
            input.close();
            RO.sendStatus(PubRequestFacade.FAILURE_STAGE,
                    "This request has been denied as a replacement for the existing publication: " + extIdPref
                            + ". Please contact the repository for further information.");
            System.exit(0);
        }
    }
    if (localSource == null && prefs.has("alternateOf")) {
        // Add a LocalContent class
        localSource = prefs.getString("alternateOf");
        System.out.println("Setting local content source to alternateOf value: " + localSource);
    }
    if (localSource != null) {
        System.out.println("Looking at: " + localSource + " for local content.");
        log.info("Looking at: " + localSource + " for local content.");
        RefLocalContentProvider ref = new RefLocalContentProvider(localSource, Repository.getProps());
        if (ref.getHashType() != null) {
            bg.setLocalContentProvider(ref);
            System.out.println("Proceeding with : " + localSource + " for local content.");
        } else {

            System.out
                    .println("Original RO not found/has no usable hash entries: " + getDataPathTo(localSource));
            System.out.println("Proceed (using remote content)? {Y/N}: ");
            if (!input.next().equalsIgnoreCase("y")) {
                input.close();
                RO.sendStatus(PubRequestFacade.FAILURE_STAGE,
                        "This request won't be processed due to a problem in finding local data copies: "
                                + localSource + ". Please contact the repository for further information.");
                System.exit(0);
            }
            localSource = null;
        }
    }

    input.close();
    return localSource;
}

From source file:com.alexdisler.inapppurchases.InAppBillingV3.java

private JSONObject getManifestContents() {
    if (manifestObject != null)
        return manifestObject;

    Context context = this.cordova.getActivity();
    InputStream is;/*  ww  w.  j  a va  2  s .c om*/
    try {
        is = context.getAssets().open("www/manifest.json");
        Scanner s = new Scanner(is).useDelimiter("\\A");
        String manifestString = s.hasNext() ? s.next() : "";
        Log.d(TAG, "manifest:" + manifestString);
        manifestObject = new JSONObject(manifestString);
    } catch (IOException e) {
        Log.d(TAG, "Unable to read manifest file:" + e.toString());
        manifestObject = null;
    } catch (JSONException e) {
        Log.d(TAG, "Unable to parse manifest file:" + e.toString());
        manifestObject = null;
    }
    return manifestObject;
}

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. 
 * /*  www. ja  v a 2s  .  c  o 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.elasticsearch.hadoop.integration.rest.AbstractRestSaveTest.java

@Test
public void testBulkWrite() throws Exception {
    TestSettings testSettings = new TestSettings("rest/savebulk");
    //testSettings.setPort(9200)
    testSettings.setProperty(ConfigurationOptions.ES_SERIALIZATION_WRITER_VALUE_CLASS,
            JdkValueWriter.class.getName());
    RestRepository client = new RestRepository(testSettings);

    Scanner in = new Scanner(getClass().getResourceAsStream("/artists.dat")).useDelimiter("\\n|\\t");

    Map<String, String> line = new LinkedHashMap<String, String>();

    for (; in.hasNextLine();) {
        // ignore number
        in.next();
        line.put("name", in.next());
        line.put("url", in.next());
        line.put("picture", in.next());
        client.writeToIndex(line);//from   www.  j  a va2s.  c  o  m
        line.clear();
    }

    client.close();
}