Example usage for java.util Scanner Scanner

List of usage examples for java.util Scanner Scanner

Introduction

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

Prototype

public Scanner(ReadableByteChannel source) 

Source Link

Document

Constructs a new Scanner that produces values scanned from the specified channel.

Usage

From source file:com.microsoft.azure.storage.util.KeyVaultUtility.java

/**
 * Creates a secret in Azure Key Vault and returns its ID.
 * /*from   w  ww  .  java  2 s.c  om*/
 * @param secretName
 *            The name of the secret to create
 * @return The ID of the created secret
 * @throws InterruptedException
 * @throws ExecutionException
 * @throws NoSuchAlgorithmException
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public static String SetUpKeyVaultSecret(String secretName) throws InterruptedException, ExecutionException,
        NoSuchAlgorithmException, URISyntaxException, MalformedURLException {
    KeyVaultClient cloudVault = GetKeyVaultClient();

    if (Utility.vaultURL == null || Utility.vaultURL.isEmpty()) {
        throw new IllegalArgumentException("No Keyvault URL specified.");
    }

    try {
        // Delete the secret if it exists.
        cloudVault.deleteSecretAsync(Utility.vaultURL, secretName).get();
    } catch (ExecutionException ex) {
        boolean keyNotFound = false;
        if (ex.getCause().getClass() == ServiceException.class) {
            ServiceException serviceException = (ServiceException) ex.getCause();
            if (serviceException.getHttpStatusCode() == 404) {
                keyNotFound = true;
            }
        }

        if (!keyNotFound) {
            System.out.println(
                    "Unable to access the specified vault. Please confirm the KVClientId, KVClientKey, and VaultUri are valid in the app.config file.");
            System.out.println(
                    "Also ensure that the client ID has previously been granted full permissions for Key Vault secrets using the Set-AzureKeyVaultAccessPolicy command with the -PermissionsToSecrets parameter.");
            System.out.println("Press any key to exit");
            Scanner input = new Scanner(System.in);
            input.nextLine();
            input.close();
            throw ex;
        }
    }

    // Create a 256bit symmetric key and convert it to Base64.
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(256); // Note that we cannot use SymmetricKey.KeySize256,
                      // because this resolves to '0x20'.
    SecretKey wrapKey = keyGen.generateKey();

    // Store the Base64 of the key in the key vault. Note that the
    // content-type of the secret must
    // be application/octet-stream or the KeyVaultKeyResolver will not load
    // it as a key.
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/octet-stream");
    Secret cloudSecret = cloudVault.setSecretAsync(Utility.vaultURL, secretName,
            Base64.encodeBase64String(wrapKey.getEncoded()), "application/octet-stream", null, null).get();

    // Return the base identifier of the secret. This will be resolved to
    // the current version of the secret.
    return cloudSecret.getSecretIdentifier().getBaseIdentifier();
}

From source file:mase.MaseManagerTerminal.java

public void run(File runnersFile, File jobsFile) {
    try {//from   www . java  2 s . com
        if (runnersFile != null) {
            mng.loadRunners(runnersFile);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    try {
        if (jobsFile != null) {
            mng.loadJobs(jobsFile);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    final Scanner lineSC = new Scanner(System.in);

    while (true) {
        System.out.print("> ");
        String option = lineSC.next();
        Scanner sc = new Scanner(lineSC.nextLine());
        try {
            switch (option) {
            case "addrunner":
                mng.addRunner(sc.nextLine());
                break;
            case "loadrunners":
                while (sc.hasNext()) {
                    mng.loadRunners(new File(sc.next()));
                }
                break;
            case "addjobs":
                mng.addJob(sc.nextLine());
                break;
            case "loadjobs":
                while (sc.hasNext()) {
                    mng.loadJobs(new File(sc.next()));
                }
                break;
            case "remove":
                while (sc.hasNext()) {
                    mng.removeFromWaiting(sc.next());
                }
                break;
            case "killrunner":
                while (sc.hasNextInt()) {
                    mng.killRunner(sc.nextInt());
                }
                break;
            case "kill":
                while (sc.hasNext()) {
                    mng.killJob(sc.next());
                }
                break;
            case "killall":
                mng.failed.addAll(mng.waitingList);
                mng.waitingList.clear();
                List<Job> running = new ArrayList<>(mng.running.values());
                for (Job j : running) {
                    mng.killJob(j.id);
                }
                break;
            case "output":
                int id = sc.nextInt();
                int l = sc.hasNextInt() ? sc.nextInt() : lines;
                System.out.println(mng.getOutput(id, l));
                break;
            case "jobs":
                while (sc.hasNext()) {
                    String jobid = sc.next();
                    List<Job> found = mng.findJobs(jobid);
                    for (Job j : found) {
                        System.out.println(j.detailedToString() + "\n-----------------");
                    }
                }
                break;
            case "status":
                int ls = sc.hasNextInt() ? sc.nextInt() : lines;
                System.out.println("Completed: " + mng.completed.size() + "\tWaiting: " + mng.waitingList.size()
                        + "\tFailed: " + mng.failed.size() + "\tRunning: " + mng.running.size() + "/"
                        + mng.runners.size() + " " + (mng.runningStatus() ? "(ACTIVE)" : "(PAUSED)"));
                for (Entry<JobRunner, Job> e : mng.running.entrySet()) {
                    System.out.println("== " + e.getValue() + " @ " + e.getKey() + " ========");
                    System.out.println(mng.getOutput(e.getKey().id, ls));
                }
                break;
            case "list":
                while (sc.hasNext()) {
                    String t = sc.next();
                    if (t.equals("failed")) {
                        for (int i = mng.failed.size() - 1; i >= 0; i--) {
                            Job j = mng.failed.get(i);
                            System.out.println(df.format(j.submitted) + " " + j);
                        }
                    } else if (t.equals("completed")) {
                        for (int i = mng.completed.size() - 1; i >= 0; i--) {
                            Job j = mng.completed.get(i);
                            System.out.println(df.format(j.submitted) + " " + j);
                        }
                    } else if (t.equals("waiting")) {
                        for (int i = mng.waitingList.size() - 1; i >= 0; i--) {
                            Job j = mng.waitingList.get(i);
                            System.out.println(df.format(j.submitted) + " " + j);
                        }
                    } else if (t.equals("runners")) {
                        for (JobRunner r : mng.runners.values()) {
                            if (mng.running.containsKey(r)) {
                                Job runningJob = mng.running.get(r);
                                System.out
                                        .println(df.format(runningJob.started) + " " + r + " @ " + runningJob);
                            } else {
                                System.out.println("Idle     " + r);
                            }
                        }
                    } else {
                        error("Unknown list: " + t);
                    }
                }
                break;
            case "retry":
                while (sc.hasNext()) {
                    mng.retryJob(sc.next());
                }
                break;
            case "retryfailed":
                mng.retryFailed();
                break;
            case "clear":
                while (sc.hasNext()) {
                    String t = sc.next();
                    if (t.equals("failed")) {
                        mng.failed.clear();
                    } else if (t.equals("completed")) {
                        mng.completed.clear();
                    } else if (t.equals("waiting")) {
                        mng.waitingList.clear();
                    } else if (t.equals("runners")) {
                        List<Integer> runners = new ArrayList<>(mng.runners.keySet());
                        for (Integer r : runners) {
                            mng.killRunner(r);
                        }
                    } else {
                        error("Unknown list: " + t);
                    }
                }
                break;
            case "priority":
                String type = sc.next();
                while (sc.hasNext()) {
                    String i = sc.next();
                    if (type.equals("top")) {
                        mng.topPriority(i);
                    } else if (type.equals("bottom")) {
                        mng.lowestPriority(i);
                    }
                }
                break;
            case "sort":
                String sort = sc.next();
                if (sort.equals("job")) {
                    mng.sortJobFirst();
                } else if (sort.equals("date")) {
                    mng.sortSubmissionDate();
                } else {
                    error("Unknown sorting method: " + sort);
                }
                break;
            case "pause":
                mng.pause(sc.hasNext() && sc.next().equals("force"));
                break;
            case "start":
                mng.resume();
                break;
            case "exit":
                System.exit(0);
                break;
            case "set":
                String par = sc.next();
                switch (par) {
                case "lines":
                    lines = sc.nextInt();
                    break;
                case "maxtries":
                    mng.setMaxTries(sc.nextInt());
                    break;
                }

                break;
            case "mute":
                this.mute = true;
                break;
            case "unmute":
                this.mute = false;
                break;
            case "help":
                System.out.println("Available commands:\n" + "-- addrunner      runner_type [config]\n"
                        + "-- loadrunners    [file]...\n" + "-- addjobs        job_params\n"
                        + "-- loadjobs       [file]...\n" + "-- killrunner     [runner_id]...\n"
                        + "-- remove         [job_id]...\n" + "-- kill           [job_id]...\n"
                        + "-- killall        \n" + "-- output         runner_id [lines]\n"
                        + "-- jobs           [job_id]...\n" + "-- status         [lines]\n"
                        + "-- list           [waiting|completed|failed|runners]...\n"
                        + "-- retry          [job_id]...\n" + "-- retryfailed    \n"
                        + "-- priority       top|bottom [job_id]...\n" + "-- sort           batch|job|date\n"
                        + "-- clear          [waiting|completed|failed|runners]...\n"
                        + "-- pause          [force]\n" + "-- start          \n" + "-- mute|unmute    \n"
                        + "-- exit           \n" + "-- set            lines|tries value");
                break;
            default:
                System.out.println("Unknown command. Try help.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:eu.crisis_economics.configuration.FromFileConfigurationContext.java

public FromFileConfigurationContext(String configurationFilename) {
    if (configurationFilename == null)
        throw new NullArgumentException();
    String fileContents = null;/*from w  w  w .j a va  2  s. c  o  m*/
    try {
        fileContents = new Scanner(new File(configurationFilename)).useDelimiter("\\Z").next();
    } catch (IOException e) {
        System.out.println("FromFileConfigurationContext: file not found: '" + configurationFilename + "'");
    }
    this.configFileParseIsComplete = false;
    this.knownNameDeclarations = new Hashtable<String, NameDeclarationExpression>();
    this.knownDefinitions = new Hashtable<String, DefinitionExpression>();
    this.knownIntegerPrimitiveDefinitions = new Hashtable<String, IntegerPrimitiveExpression>();
    this.knownDoublePrimitiveDefinitions = new Hashtable<String, DoublePrimitiveExpression>();
    this.userObjectCreationPending = new LinkedList<UserObjectCreationTask>();
    this.definitionExpressionRegistrationOrder = new ArrayList<DefinitionExpression>();
    this.arrayCreationCounters = new Hashtable<String, IntegerIndexOfMaximum>();
    this.compoundConfigurationExpressions = ConfParser.parse(fileContents, this); // Populates the above hashtables
    this.awaitingUserCreationRequest = false;
    this.configFileParseIsComplete = true;
}

From source file:flens.input.GraphiteInput.java

@Override
//metric_path value timestamp\n  
//http://graphite.wikidot.com/getting-your-data-into-graphite
public void readAndProcess(Pair<String, BufferedReader> inx) throws IOException {
    BufferedReader in = inx.getRight();
    String host = inx.getLeft();/*  ww  w  .  ja  v  a  2  s. c o m*/
    String line = in.readLine();
    if (line == null)
        throw new IOException("connection lost");

    Scanner st = new Scanner(line);

    try {

        String metricName = st.next();
        String metric = st.next();
        long time = st.nextLong();

        Map<String, Object> tags = new HashMap<String, Object>();

        tags.put(Constants.METRIC, metricName);
        tags.put(Constants.VALUE, metric);

        Record r = Record.createWithTimeHostAndValues(time * 1000, host, tags);
        dispatch(r);
    } catch (NoSuchElementException e) {
        warn("line too short", line);
    }

}