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:jenkins.plugins.jclouds.compute.MigrationTest.java

private void checkTags(final File f) throws Exception {
    // Verify that the obsoleted tags are gone
    String content = new Scanner(f).useDelimiter("\\Z").next();
    assertFalse("Tag <identity> still in file", content.contains("<identity>"));
    assertFalse("Tag <credential> still in file", content.contains("<credential>"));
    assertFalse("Tag <privateKey> still in file", content.contains("<privateKey>"));
    assertFalse("Tag <publicKey> still in file", content.contains("<publicKey>"));
    assertFalse("Tag <initScript> still in file", content.contains("<initScript>"));
    assertFalse("Tag <userData> still in file", content.contains("<userData>"));
    assertFalse("Tag <vmUser> still in file", content.contains("<vmUser>"));
    assertFalse("Tag <vmPassword> still in file", content.contains("<vmPassword>"));
    assertFalse("Tag <preInstalledJava> still in file", content.contains("<preInstalledJava>"));
    assertFalse("Tag <preInstalledJava> still in file", content.contains("<preInstalledJava>"));
    assertFalse("Tag <assignFloatingIp> still in file", content.contains("<assignFloatingIp>"));
    assertFalse("Tag <isWindows> still in file", content.contains("<isWindows>"));
    // Verify, that new tags are there
    assertTrue("Tag <cloudCredentialsId> in file", content.contains("<cloudCredentialsId>"));
    assertTrue("Tag <cloudGlobalKeyId> in file", content.contains("<cloudGlobalKeyId>"));
    assertTrue("Tag <credentialsId> in file", content.contains("<credentialsId>"));
    assertTrue("Tag <initScriptId> in file", content.contains("<initScriptId>"));
    assertTrue("Tag <userDataEntries> in file", content.contains("<userDataEntries>"));
    assertTrue("Tag <adminCredentialsId> in file", content.contains("<adminCredentialsId>"));
    assertTrue("Tag <useConfigDrive> in file", content.contains("<useConfigDrive>"));
    assertTrue("Tag <waitPhoneHome> in file", content.contains("<waitPhoneHome>"));
    assertTrue("Tag <waitPhoneHomeTimeout> in file", content.contains("<waitPhoneHomeTimeout>"));
}

From source file:org.sasabus.export2Freegis.network.DataRequestManager.java

public String datarequest() throws IOException {
    Scanner sc = new Scanner(new File(DATAREQUEST));
    String subscriptionstring = "";
    while (sc.hasNextLine()) {
        subscriptionstring += sc.nextLine();
    }//w ww  .j  a v  a  2  s  . c o m
    sc.close();
    SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ");

    Date d = new Date();
    String timestamp = date_date.format(d) + "T" + date_time.format(d);
    timestamp = timestamp.substring(0, timestamp.length() - 2) + ":"
            + timestamp.substring(timestamp.length() - 2);

    subscriptionstring = subscriptionstring.replaceAll(":timestamp", timestamp);

    String requestString = "http://" + this.address + ":" + this.portnumber_sender
            + "/TmEvNotificationService/gms/polldata.xml";

    HttpPost subrequest = new HttpPost(requestString);

    StringEntity requestEntity = new StringEntity(subscriptionstring,
            ContentType.create("text/xml", "ISO-8859-1"));

    CloseableHttpClient httpClient = HttpClients.createDefault();

    subrequest.setEntity(requestEntity);

    CloseableHttpResponse response = httpClient.execute(subrequest);
    //System.out.println("Stauts Response: " + response.getStatusLine().getStatusCode());
    //System.out.println("Status Phrase: " + response.getStatusLine().getReasonPhrase());
    HttpEntity responseEntity = response.getEntity();
    String responsebody = "";
    if (responseEntity != null) {
        responsebody = EntityUtils.toString(responseEntity);
    }
    return responsebody;
}

From source file:org.mifos.tools.service.ConsoleReaderService.java

@Override
public void run(String... args) throws Exception {
    final Scanner console = new Scanner(System.in);

    while (true) {
        System.out.print("ppiul> ");
        final String command = console.nextLine();
        if (command.equals("quit")) {
            System.out.println("Bye!");
            break;
        } else if (command.startsWith("show")) {
            if (command.contains("config")) {
                this.printProperties();
            } else if (command.contains("countries")) {
                this.printCountries();
            } else {
                this.unknownCommand();
            }/*from  ww w . j  a  v  a2s  .  com*/
        } else if (command.startsWith("set")) {
            this.setProperty(command);
        } else if (command.startsWith("upload")) {
            final String[] message = command.split(" ");
            this.ppiUploaderService.upload(this.properties, message[1]);
        } else if (command.startsWith("help")) {
            this.printHelp();
        } else {
            this.unknownCommand();
        }
    }
}

From source file:ReversePolishNotation.java

/**
 * This method will calculate the answer of the given Reverse Polar Notation
 * equation. All exceptions are thrown to the parent for handling.
 * /*from w w w.  j a  va2s.  c o m*/
 * @param input
 *            is the equation entered by the user
 * @throws EmptyRPNException
 *             when there is no RPN equation to be evaluated.
 * @throws RPNDivideByZeroException
 *             when the RPN equation attempts to divide by zero.
 * @throws RPNUnderflowException
 *             when the RPN equation has a mathematical operator before
 *             there are enough numerical values for it to evaluate.
 * @throws InvalidRPNException
 *             when the RPN equation is a String which is unable to be
 *             manipulated.
 * @throws RPNOverflowException
 *             when the RPN equation has too many numerical values and not
 *             enough mathematical operators with which to evaluate them.
 * @return the top item of the stack; the calculated answer of the Reverse
 *         Polish Notation equation
 */
public static double calcRPN(String input) {
    // eliminate any leading or trailing whitespace from input
    input = input.trim();
    // scanner to manipulate input and stack to store double values
    String next;
    Stack<Double> stack = new Stack<Double>();
    Scanner scan = new Scanner(input);

    // loop while there are tokens left in scan
    while (scan.hasNext()) {
        // retrieve the next token from the input
        next = scan.next();

        // see if token is mathematical operator
        if (nextIsOperator(next)) {
            // ensure there are enough numbers on stack
            if (stack.size() > 1) {
                if (next.equals("+")) {
                    stack.push((Double) stack.pop() + (Double) stack.pop());
                } else if (next.equals("-")) {
                    stack.push(-(Double) stack.pop() + (Double) stack.pop());
                } else if (next.equals("*")) {
                    stack.push((Double) stack.pop() * (Double) stack.pop());
                } else if (next.equals("/")) {
                    double first = stack.pop();
                    double second = stack.pop();

                    if (first == 0) {
                        System.out.println("The RPN equation attempted to divide by zero.");
                    } else {
                        stack.push(second / first);
                    }
                }
            } else {
                System.out.println(
                        "A mathematical operator occured before there were enough numerical values for it to evaluate.");
            }
        } else {
            try {
                stack.push(Double.parseDouble(next));
            } catch (NumberFormatException c) {
                System.out.println("The string is not a valid RPN equation.");
            }
        }
    }

    if (stack.size() > 1) {
        System.out.println(
                "There too many numbers and not enough mathematical operators with which to evaluate them.");
    }

    return (Double) stack.pop();
}

From source file:ca.ualberta.cs.expenseclaim.dao.ExpenseClaimDao.java

private ExpenseClaimDao(Context context) {
    claimList = new ArrayList<ExpenseClaim>();
    File file = new File(context.getFilesDir(), FILENAME);
    Scanner scanner = null;/*from w w w.ja va  2s. co m*/
    try {
        scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            JSONObject jo = new JSONObject(scanner.nextLine());
            ExpenseClaim claim = new ExpenseClaim();
            claim.setId(jo.getInt("id"));
            claim.setName(jo.getString("name"));
            claim.setDescription(jo.getString("description"));
            claim.setStartDate(new Date(jo.getLong("startDate")));
            claim.setEndDate(new Date(jo.getLong("endDate")));
            claim.setStatus(jo.getString("status"));
            if (maxId < claim.getId()) {
                maxId = claim.getId();
            }
            claimList.add(claim);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    maxId++;
}

From source file:de.cgarbs.lib.json.JSONDataModel.java

/**
 * Reads JSON data from the specified file and writes all attribute
 * values from the JSON data to the appropriate attributes in the
 * given DataModel.//from  w ww .j  ava 2s .  c  o m
 *
 * @param model the DataModel to be written to
 * @param file the File containing the JSON data to be read
 * @throws DataException either IO errors or errors during the JSON conversion
 */
public static void readFromFile(final DataModel model, final File file) throws DataException {
    StringBuilder json = new StringBuilder();
    try {
        for (final Scanner sc = new Scanner(file); sc.hasNext();) {
            json.append(sc.nextLine());
        }
    } catch (FileNotFoundException e) {
        throw wrappedAsDataException(DataException.ERROR.IO_ERROR, e);
    }

    try {
        readFromJSON(model, getJSONParser().parse(json.toString(), getOrderedContainerFactory()));
    } catch (ParseException e) {
        throw wrappedAsDataException(DataException.ERROR.JSON_CONVERSION_ERROR, e);
    } catch (JSONException e) {
        throw wrappedAsDataException(DataException.ERROR.JSON_CONVERSION_ERROR, e);
    }
}

From source file:com.intel.cosbench.driver.handler.TriggerHandler.java

@Override
protected Response process(HttpServletRequest req, HttpServletResponse res) throws Exception {
    scriptLog = "";
    Scanner scanner = new Scanner(req.getInputStream());
    String trigger = getTrigger(scanner);
    runTrigger(trigger);/* ww  w.ja v a2  s  .c om*/

    return createResponse();
}

From source file:com.joliciel.lefff.LefffPosTagMapperImpl.java

public LefffPosTagMapperImpl(File file, PosTagSet posTagSet) {
    this.posTagSet = posTagSet;
    Scanner scanner = null;//  w  ww  .  j  a  va  2 s  . c o m
    try {
        scanner = new Scanner(file);
        List<String> descriptors = new ArrayList<String>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            descriptors.add(line);
        }
        this.load(descriptors);
    } catch (FileNotFoundException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.jaxio.celerio.template.VelocityGeneratorTest.java

@Test
public void testExtraction() {
    String message = "Object 'com.jaxio.celerio.convention.WellKnownFolder' does not contain property 'resource' at src/main/resources/spring/springmvc-parent.p.vm.xml[line "
            + "28, column 47]";
    Scanner s = new Scanner(message);
    String u = s.findInLine("\\[line (\\d+), column (\\d+)\\]");
    assertThat(u).isNotEmpty();//from  ww  w.  j a  v  a2 s.co m
    MatchResult result = s.match();
    assertThat(result.groupCount()).isEqualTo(2);
    assertThat(result.group(1)).isEqualTo("28");
    assertThat(result.group(2)).isEqualTo("47");
}

From source file:Vdisk.java

public void get_access_token() {
    Scanner in = new Scanner(System.in);
    this.access_token = in.next();
}