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.fhaes.fhfilereader.FHCategoryReader.java

/**
 * Parses the input category file and stores its contents in the categoryEntries arrayList.
 * //from w  ww  .  j  av a2 s .com
 * @param categoryFile
 */
public FHCategoryReader(File categoryFile) {

    try {
        // Setup the scanner for reading and storing the category entries from the CSV file
        Scanner sc = new Scanner(categoryFile);
        sc.useDelimiter(",|\r\n");

        // Verify that the category file has the necessary header and version number
        for (int numValuesRead = 0; numValuesRead <= NUM_INITIAL_VALUES_TO_READ; numValuesRead++) {
            if (numValuesRead == INDEX_OF_HEADER && sc.hasNext()) {
                if (!sc.next().equals(FHAES_CATEGORY_FILE_HEADER)) {
                    sc.close();
                    throw new InvalidCategoryFileException();
                }
            } else if (numValuesRead == INDEX_OF_VERSION && sc.hasNext()) {
                if (!sc.next().equals(FHAES_CATEGORY_FILE_VERSION)) {
                    sc.close();
                    throw new InvalidCategoryFileException();
                }
            } else if (numValuesRead == INDEX_OF_FILENAME && sc.hasNext()) {
                nameOfCorrespondingFHXFile = sc.next();
            } else {
                sc.close();
                throw new InvalidCategoryFileException();
            }
        }

        // Read the contents of the category file into the categoryEntries array
        while (sc.hasNext()) {
            String seriesTitle = sc.next();
            String category = sc.next();
            String content = sc.next();

            if (!seriesTitle.equals("") && !category.equals("") && !content.equals("")) {
                categoryEntries.add(new FHCategoryEntry(seriesTitle, category, content));
            } else {
                sc.close();
                throw new InvalidCategoryFileException();
            }
        }

        sc.close();
    } catch (FileNotFoundException ex) {
        log.info("The category file " + FilenameUtils.getBaseName(categoryFile.getAbsolutePath())
                + " does not exist.");
    } catch (InvalidCategoryFileException ex) {
        log.error("Could not parse category file. File is in an invalid format or has missing entries.");
    }
}

From source file:com.okta.tools.awscli.java

private static String oktaAuthntication() throws ClientProtocolException, JSONException, IOException {
    CloseableHttpResponse responseAuthenticate = null;
    int requestStatus = 0;

    //Redo sequence if response from AWS doesn't return 200 Status
    while (requestStatus != 200) {

        // Prompt for user credentials
        System.out.print("Username: ");
        Scanner scanner = new Scanner(System.in);

        String oktaUsername = scanner.next();

        Console console = System.console();
        String oktaPassword = null;
        if (console != null) {
            oktaPassword = new String(console.readPassword("Password: "));
        } else { // hack to be able to debug in an IDE
            System.out.print("Password: ");
            oktaPassword = scanner.next();
        }/*  w ww .j a v  a2  s.c  o  m*/

        responseAuthenticate = authnticateCredentials(oktaUsername, oktaPassword);
        requestStatus = responseAuthenticate.getStatusLine().getStatusCode();
        authnFailHandler(requestStatus, responseAuthenticate);
    }

    //Retrieve and parse the Okta response for session token
    BufferedReader br = new BufferedReader(
            new InputStreamReader((responseAuthenticate.getEntity().getContent())));

    String outputAuthenticate = br.readLine();
    JSONObject jsonObjResponse = new JSONObject(outputAuthenticate);

    responseAuthenticate.close();

    if (jsonObjResponse.getString("status").equals("MFA_REQUIRED")) {
        return mfa(jsonObjResponse);
    } else {
        return jsonObjResponse.getString("sessionToken");
    }
}

From source file:com.galileha.smarthome.SmartHome.java

/**
 * Read home.json from Server/*www. j  av a2 s.com*/
 * 
 * @param URL
 * @return
 * @throws IOException
 *             , MalformedURLException, JSONException
 */
public void getHomeStatus() throws IOException, MalformedURLException, JSONException {
    // Set URL
    // Connect to Intel Galileo get Device Status
    HttpURLConnection httpCon = (HttpURLConnection) homeJSONUrl.openConnection();
    httpCon.setReadTimeout(10000);
    httpCon.setConnectTimeout(15000);
    httpCon.setRequestMethod("GET");
    httpCon.setDoInput(true);
    httpCon.connect();
    // Read JSON File as InputStream
    InputStream readStream = httpCon.getInputStream();
    Scanner scan = new Scanner(readStream).useDelimiter("\\A");
    // Set stream to String
    String jsonFile = scan.hasNext() ? scan.next() : "";
    // Initialize serveFile as read string
    homeInfo = new JSONObject(jsonFile);
    httpCon.disconnect();
}

From source file:com.rapid.server.RapidServletContextListener.java

public static int loadThemes(ServletContext servletContext) throws Exception {

    // assume no themes
    int themeCount = 0;

    // create a list for our themes
    List<Theme> themes = new ArrayList<Theme>();

    // get the directory in which the control xml files are stored
    File dir = new File(servletContext.getRealPath("/WEB-INF/themes/"));

    // create a filter for finding .control.xml files
    FilenameFilter xmlFilenameFilter = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".theme.xml");
        }/*  w ww .  j av  a  2  s  .  c  o  m*/
    };

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/theme.xsd"));
    // create a validator
    Validator validator = schema.newValidator();

    // loop the xml files in the folder
    for (File xmlFile : dir.listFiles(xmlFilenameFilter)) {

        // get a scanner to read the file
        Scanner fileScanner = new Scanner(xmlFile).useDelimiter("\\A");

        // read the xml into a string
        String xml = fileScanner.next();

        // close the scanner (and file)
        fileScanner.close();

        // validate the control xml file against the schema
        validator.validate(new StreamSource(new ByteArrayInputStream(xml.getBytes("UTF-8"))));

        // create a theme object from the xml
        Theme theme = new Theme(xml);

        // add it to our collection
        themes.add(theme);

        // inc the template count
        themeCount++;

    }

    // sort the list of templates by name
    Collections.sort(themes, new Comparator<Theme>() {
        @Override
        public int compare(Theme t1, Theme t2) {
            return Comparators.AsciiCompare(t1.getName(), t2.getName(), false);
        }

    });

    // put the jsonControls in a context attribute (this is available via the getJsonControls method in RapidHttpServlet)
    servletContext.setAttribute("themes", themes);

    _logger.info(themeCount + " templates loaded in .template.xml files");

    return themeCount;

}

From source file:no.sintef.jarfter.PostgresqlInteractor.java

private String fileToString(String fileName) throws FileNotFoundException {
    FileInputStream fileStream = new FileInputStream(new File(fileName));
    java.util.Scanner scanner = new java.util.Scanner(fileStream).useDelimiter("\\A");
    String inputAsString = scanner.hasNext() ? scanner.next() : "";
    return inputAsString.replaceAll("[\uFEFF-\uFFFF]", "");
}

From source file:org.colombbus.tangara.core.Version.java

private void doExtractFieldsFromText(String textVersion) throws Exception {
    Scanner scanner = new Scanner(textVersion);
    scanner.useDelimiter("\\."); //$NON-NLS-1$
    major = scanner.nextInt();//  ww w .j a  v a  2 s  .com
    if (scanner.hasNext())
        minor = scanner.nextInt();
    if (scanner.hasNext())
        fix = scanner.nextInt();
    if (scanner.hasNext())
        qualifier = scanner.next();
    if (scanner.hasNext()) {
        throw new Exception("Too many fields"); //$NON-NLS-1$
    }
    scanner.close();
}

From source file:tajo.worker.TestWorker.java

@Test
public final void testCommand() throws Exception {
    Fragment[] frags = sm.split("employee", 40000);
    for (Fragment f : frags) {
        f.setDistCached();//from  w  w  w  .  ja v  a2 s  .c  o  m
    }

    for (Fragment f : frags) {
        System.out.println(f);
    }

    int splitIdx = (int) Math.ceil(frags.length / 2.f);
    QueryIdFactory.reset();

    Worker worker1 = util.getMiniTajoCluster().getWorker(0);
    Worker worker2 = util.getMiniTajoCluster().getWorker(1);

    SubQueryId sid = QueryIdFactory.newSubQueryId(QueryIdFactory.newQueryId());
    QueryUnitId qid1 = QueryIdFactory.newQueryUnitId(sid);
    QueryUnitId qid2 = QueryIdFactory.newQueryUnitId(sid);

    PlanningContext context = analyzer.parse("testLeafServer := select name, empId, deptName from employee");
    LogicalNode plan = planner.createPlan(context);
    plan = LogicalOptimizer.optimize(context, plan);

    TajoMaster master = util.getMiniTajoCluster().getMaster();
    QueryManager qm = master.getQueryManager();
    Query q = new Query(qid1.getQueryId(), "testLeafServer := select name, empId, deptName from employee");
    qm.addQuery(q);
    SubQuery su = new SubQuery(qid1.getSubQueryId());
    qm.addSubQuery(su);
    sm.initTableBase(frags[0].getMeta(), "testLeafServer");
    QueryUnit[] qu = new QueryUnit[2];
    qu[0] = new QueryUnit(qid1);
    qu[1] = new QueryUnit(qid2);
    su.setQueryUnits(qu);
    qu[0].setStatus(QueryStatus.QUERY_INITED);
    qu[1].setStatus(QueryStatus.QUERY_INITED);
    QueryUnitAttempt attempt0 = qu[0].newAttempt();
    QueryUnitAttempt attempt1 = qu[1].newAttempt();
    QueryUnitRequest req1 = new QueryUnitRequestImpl(attempt0.getId(),
            Lists.newArrayList(Arrays.copyOfRange(frags, 0, splitIdx)), "", false, plan.toJSON());

    QueryUnitRequest req2 = new QueryUnitRequestImpl(attempt1.getId(),
            Lists.newArrayList(Arrays.copyOfRange(frags, splitIdx, frags.length)), "", false, plan.toJSON());

    assertNotNull(worker1.requestQueryUnit(req1.getProto()));
    Thread.sleep(1000);
    assertNotNull(worker2.requestQueryUnit(req2.getProto()));
    Thread.sleep(1000);

    // for the report sending test
    Set<QueryUnitAttemptId> submitted = Sets.newHashSet();
    submitted.add(req1.getId());
    submitted.add(req2.getId());

    QueryStatus s1, s2;
    do {
        s1 = worker1.getTask(req1.getId()).getStatus();
        s2 = worker2.getTask(req2.getId()).getStatus();
    } while (s1 != QueryStatus.QUERY_FINISHED && s2 != QueryStatus.QUERY_FINISHED);

    Command.Builder cmd = Command.newBuilder();
    cmd.setId(req1.getId().getProto()).setType(CommandType.FINALIZE);
    worker1.requestCommand(CommandRequestProto.newBuilder().addCommand(cmd.build()).build());
    cmd = Command.newBuilder();
    cmd.setId(req2.getId().getProto()).setType(CommandType.FINALIZE);
    worker2.requestCommand(CommandRequestProto.newBuilder().addCommand(cmd.build()).build());

    assertNull(worker1.getTask(req1.getId()));
    assertNull(worker2.getTask(req2.getId()));

    Scanner scanner = sm.getTableScanner("testLeafServer");
    int j = 0;
    while (scanner.next() != null) {
        j++;
    }

    assertEquals(tupleNum, j);
}

From source file:org.apache.zookeeper.server.persistence.TxnLogToolkit.java

private boolean askForFix(Scanner scanner) throws TxnLogToolkitException {
    while (true) {
        System.out.print("Would you like to fix it (Yes/No/Abort) ? ");
        char answer = Character.toUpperCase(scanner.next().charAt(0));
        switch (answer) {
        case 'Y':
            return true;
        case 'N':
            return false;
        case 'A':
            throw new TxnLogToolkitException(ExitCode.EXECUTION_FINISHED.getValue(), "Recovery aborted.");
        }/*from   ww w.jav  a 2 s .c o  m*/
    }
}

From source file:com.inaetics.demonstrator.MainActivity.java

/**
 * Method called when QR-code scanner has been triggered and finished.
 * If a qr-code is scanned it will process the content.
 *//*from  w w  w  . jav  a2 s.c o m*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
    if (result != null) {
        if (result.getContents() == null) {
            Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
        } else {
            String content = result.getContents();
            try {
                new URL(content);
                // Is a url!
                download(content);
            } catch (MalformedURLException e) {
                //Not an url
                Scanner sc = new Scanner(content);
                boolean autostart = false;
                while (sc.hasNextLine()) {
                    String[] keyValue = sc.nextLine().split("=");
                    switch (keyValue[0]) {
                    case "cosgi.auto.start.1":
                        autostart = true;
                        String startBundles = "";
                        Scanner bscan = new Scanner(keyValue[1]);
                        while (bscan.hasNext()) {
                            startBundles += model.getBundleLocation() + "/" + bscan.next() + " ";
                        }
                        bscan.close();
                        config.putProperty(keyValue[0], startBundles);
                        break;
                    case "deployment_admin_identification":
                        config.putProperty(keyValue[0], keyValue[1] + "_" + model.getCpu_abi());
                        break;
                    default:
                        try {
                            config.putProperty(keyValue[0], keyValue[1]);
                        } catch (ArrayIndexOutOfBoundsException ex) {
                            //Ignore property there is no key/value combination
                            Log.e("Scanner", "couldn't scan: " + Arrays.toString(keyValue));
                        }
                    }
                }
                sc.close();
                if (autostart && !Celix.getInstance().isCelixRunning()) {
                    Celix.getInstance().startFramework(config.getConfigPath());
                }
                Toast.makeText(this, "Scanned QR", Toast.LENGTH_SHORT).show();
            }

        }
    }
}

From source file:au.org.ala.layers.web.IntersectService.java

@RequestMapping(value = WS_INTERSECT_BATCH, method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody//  w ww.ja v  a2s .c o m
public Map batch(@RequestParam(value = "fids", required = false, defaultValue = "") String fids,
        @RequestParam(value = "points", required = false, defaultValue = "") String pointsString,
        @RequestParam(value = "gridcache", required = false, defaultValue = "0") String gridcache,
        HttpServletRequest request, HttpServletResponse response) {

    BatchConsumer.start(layerIntersectDao, userProperties.getProperty("batch_path"));

    //help get params when they don't pick up automatically from a POST
    try {
        if ("POST".equalsIgnoreCase(request.getMethod()) && fids.isEmpty() && pointsString.isEmpty()) {
            Scanner s = new Scanner(request.getInputStream(), "UTF-8").useDelimiter("\\A");
            String body = s.hasNext() ? s.next() : "";

            for (String param : body.split("&")) {
                if (param.startsWith("fids=")) {
                    fids = param.substring(5);
                } else if (param.startsWith("points=")) {
                    pointsString = param.substring(7);
                }
            }
        }
    } catch (Exception e) {
        logger.error("failed to read POST body for: " + WS_INTERSECT_BATCH, e);
    }

    if (pointsString == null || pointsString.isEmpty()) {
        return null;
    }

    Map map = new HashMap();
    String batchId = null;
    try {

        // get limits
        int pointsLimit, fieldsLimit;

        String[] passwords = userProperties.getProperty("batch_sampling_passwords").split(",");
        pointsLimit = Integer.parseInt(userProperties.getProperty("batch_sampling_points_limit"));
        fieldsLimit = Integer.parseInt(userProperties.getProperty("batch_sampling_fields_limit"));

        String password = request.getParameter("pw");
        for (int i = 0; password != null && i < passwords.length; i++) {
            if (passwords[i].equals(password)) {
                pointsLimit = Integer.MAX_VALUE;
                fieldsLimit = Integer.MAX_VALUE;
            }
        }

        // count fields
        int countFields = 1;
        int p = 0;
        while ((p = fids.indexOf(',', p + 1)) > 0)
            countFields++;

        // count points
        int countPoints = 1;
        p = 0;
        while ((p = pointsString.indexOf(',', p + 1)) > 0)
            countPoints++;

        if (countPoints / 2 > pointsLimit) {
            map.put("error", "Too many points.  Maximum is " + pointsLimit);
        } else if (countFields > fieldsLimit) {
            map.put("error", "Too many fields.  Maximum is " + fieldsLimit);
        } else {
            batchId = BatchProducer.produceBatch(userProperties.getProperty("batch_path"),
                    "request address:" + request.getRemoteAddr(), fids, pointsString, gridcache);

            map.put("batchId", batchId);
            BatchProducer.addInfoToMap(userProperties.getProperty("batch_path"), batchId, map);
            map.put("statusUrl", userProperties.getProperty("layers_service_url")
                    + WS_INTERSECT_BATCH_STATUS.replace("{id}", batchId));
        }

        return map;
    } catch (Exception e) {
        e.printStackTrace();
    }

    map.put("error", "failed to create new batch");
    return map;
}