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:com.std.Index.java

public void find_historical_data(int month, int day, int year) {
    try {/*  w  ww. jav a 2 s .  com*/
        String url = "http://real-chart.finance.yahoo.com/table.csv?s=" + this.ticker + "&d=" + month + "&e="
                + day + "&f=" + year + "&g=d&a=0&b=1&c=1970&ignore=.csv";
        InputStream input;
        input = new URL(url).openStream();
        Scanner s = new Scanner(input);
        s.useDelimiter("\\A");
        String csv = s.hasNext() ? s.next() : "";
        s.close();
        input.close();
        csv = csv.replace("\"", "");
        historical_data = new ArrayList<String>(Arrays.asList(csv.split("\n")));
    } catch (Exception ex) {
        System.out.println("Could not retrieve historical data");
        System.out.println("Error with connection");

    }
}

From source file:se.anyro.nfc_reader.TagViewer.java

public void processReadTag(NdefMessage ndef) {

    final String tag_content = new String(ndef.getRecords()[0].getPayload());

    //setContentView(R.layout.tag_viewer); //?
    EditText twitterHandleEditText = (EditText) findViewById(R.id.txtTwitterHandle);
    final String twitter_handle = twitterHandleEditText.getText().toString();

    Log.i(">>> NDEF:", tag_content);
    Log.i(">>> TWITTER:", twitter_handle); // THIS DOESN'T GET PRINTED?!

    // this doesn't seem like the proper way to do this #yolo
    Thread thread = new Thread(new Runnable() {
        @Override/*from ww w .  j  ava  2 s.  co  m*/
        public void run() {
            try {
                // build request
                URL url = new URL("http://10.2.2.147:8666/");
                //URL url = new URL("http://httpbin.org/post");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-type", "application/json");
                conn.setDoInput(true);
                conn.setDoOutput(true);

                /*
                // create POST body and send it over
                Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("ndef", tag_content)
                    .appendQueryParameter("twitter_handle", "omerk");
                String query = builder.build().getEncodedQuery();
                */
                OutputStream os = conn.getOutputStream();

                //BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
                JSONObject json = new JSONObject();
                json.put("ndef", tag_content);
                json.put("twitter", twitter_handle);

                os.write(json.toString().getBytes("UTF-8"));
                os.flush();
                os.close();

                conn.connect();

                // read the response
                Log.i(">>> ResponseCode: ", "" + conn.getResponseCode());
                InputStream in = new BufferedInputStream(conn.getInputStream());
                java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");
                String r = s.hasNext() ? s.next() : "";
                Log.i(">>> ResponseBody: ", r);
            } catch (Exception e) {
                Log.i(">>> OOPS: ", e.toString());
            }
        }
    });

    thread.start();

}

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

/**
 * Get Command List JSON File From Server
 * /*from   ww  w. j  a  va  2s.  c om*/
 * @throws IOException
 * @throws MalformedURLException
 * @throws JSONException
 */
public void getCommandsList() throws IOException, MalformedURLException, JSONException {
    // Connect to Intel Galileo get Commands List
    HttpURLConnection httpCon = (HttpURLConnection) commandsJSONUrl.openConnection();
    httpCon.setReadTimeout(10000);
    httpCon.setConnectTimeout(15000);
    httpCon.setRequestMethod("GET");
    httpCon.setDoInput(true);
    httpCon.connect();
    // Read JSON File as InputStream
    InputStream readCommand = httpCon.getInputStream();
    Scanner scanCommand = new Scanner(readCommand).useDelimiter("\\A");
    // Set stream to String
    String commandFile = scanCommand.hasNext() ? scanCommand.next() : "";
    // Initialize serveFile as read string
    JSONObject commandsList = new JSONObject(commandFile);
    JSONObject temp = (JSONObject) commandsList.get("commands");
    JSONArray comArray = (JSONArray) temp.getJSONArray("command");
    int numberOfCommands = comArray.length();
    commands = new String[numberOfCommands];
    // Fill the Array
    for (int i = 0; i < numberOfCommands; i++) {
        JSONObject commandObject = (JSONObject) comArray.get(i);
        commands[i] = commandObject.getString("text");
    }
    Log.d("JSON", "Loaded " + commands[2]);
    httpCon.disconnect();
}

From source file:mase.MaseManagerTerminal.java

public void run(File runnersFile, File jobsFile) {
    try {/*from   ww  w. j  a v  a 2s .  c  o  m*/
        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:edgeserver.Descoberta.java

@Override
public void run() {
    try {/*from  ww w. j a v a 2  s. c  o  m*/

        UpnpService upnpService = new UpnpServiceImpl();

        // Adiciona um verificador de novos registros de dispositivos UPNP / Add a listener for device registration events
        upnpService.getRegistry().addListener(createRegistryListener(upnpService));

        // Envia a mensagem de busca de novos dispositivos UPNP para todos os dispositivos da rede / Broadcast a search message for all devices
        // Acontece s uma vez
        upnpService.getControlPoint().search(new STAllHeader());

        Scanner scanner = new Scanner(System.in);
        String command = "";

        while (!"quit".equals(command)) {
            command = scanner.next();

            // leitor de comandos do servidor de borda

            if ("getDevices".equals(command)) {
                Collection<Device> devices = upnpService.getRegistry().getDevices();
                int devicessize = devices.size();

                System.out.printf("Esses so os dispositivos locais ( %d )\n", devicessize);

                System.out.println(Arrays.toString(upnpService.getRegistry().getDevices().toArray()));

                RemoteDevice newdevice;

                for (int i = 0; i < devices.size(); i++) {
                    newdevice = (RemoteDevice) devices.toArray()[i];
                    System.out.println(newdevice.getDetails().getFriendlyName());
                }

            } else if ("exec".equals(command)) {
                /*Collection<Device> devices = upnpService.getRegistry().getDevices();
                ServiceId serviceId = new UDAServiceId("NodoTemp");
                RemoteDevice newdevice;
                        
                for(int i = 0 ; i < devices.size() ; i++){
                newdevice = (RemoteDevice) devices.toArray()[i];
                        
                Service edgeServer;
                if ((edgeServer = newdevice.findService(serviceId)) != null) {
                        
                    //AO A SER EXECUTADA QUANDO ENCONTRADO DISPOSITIVO
                        
                    //ADICIONAR O DISPOSITIVO EM ALGUM LUGAR PRA MONITORAMENTO
                    executeAction(upnpService, edgeServer);
                        
                }
                }*/
            } else if ("countCadGateways".equals(command)) {
                synchronized (gatewaysCadastrados) {
                    System.out.println(gatewaysCadastrados.size());
                }
            }
        }

        System.exit(0);

    } catch (Exception ex) {
        System.err.println("Exception occured: " + ex);
        System.exit(1);
    }
}

From source file:com.surevine.alfresco.esl.impl.GroupDetails.java

/**
 * Constructor. Create a GroupDetails within the given constraint according to the given specification
 * //  w w w .  j a v a 2 s. c  o  m
 * @param specification
 *            See the comments at the top of this class, and the unit tests, for more details
 * @param parentConstraint
 */
public GroupDetails(String specification, EnhancedSecurityConstraint parentConstraint) {
    // Check params look OK
    if (specification == null || parentConstraint == null) {
        throw new EnhancedSecurityException(
                "Both the specification and the parent constraint must be non-null to create a GroupDetails");
    }

    // Parse out key=value,key=value pairs and use setKVPair to set relevant properties
    try {
        _constraint = parentConstraint;
        Scanner keyValuePair = new Scanner(specification.trim());
        keyValuePair.useDelimiter("\n+");
        while (keyValuePair.hasNext()) {
            String keyOrValueStr = keyValuePair.next().trim();
            if (keyOrValueStr.equals("")) {
                continue;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("Found Key/Value Pair: " + keyOrValueStr);
            }
            Scanner keyOrValue = new Scanner(keyOrValueStr);
            keyOrValue.useDelimiter("=");
            String key = keyOrValue.next();
            LOG.debug("  Found Key: " + key);
            String value = keyOrValue.next();
            LOG.debug("  Found Value: " + value);
            if (keyOrValue.hasNext()) {
                throw new EnhancedSecurityException("Was expecting a single '=' in [" + keyValuePair + "]");
            }
            setKVPair(key, value);
        }
    } catch (NoSuchElementException e) {
        throw new EnhancedSecurityException(
                "The group details specification was incorrectly formatted.  It should be key=value [lineBreak] key=value with no '=' charecters in the keys or values",
                e);
    }

}

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

public static int loadControls(ServletContext servletContext) throws Exception {

    // assume no controls
    int controlCount = 0;

    // create a list for our controls
    List<JSONObject> jsonControls = new ArrayList<JSONObject>();

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

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

    // create a schema object for the xsd
    Schema schema = _schemaFactory
            .newSchema(new File(servletContext.getRealPath("/WEB-INF/schemas/") + "/control.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"))));

        // convert the string into JSON
        JSONObject jsonControlCollection = org.json.XML.toJSONObject(xml).getJSONObject("controls");

        JSONObject jsonControl;
        int index = 0;
        int count = 0;

        if (jsonControlCollection.optJSONArray("control") == null) {
            jsonControl = jsonControlCollection.getJSONObject("control");
        } else {
            jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index);
            count = jsonControlCollection.getJSONArray("control").length();
        }

        do {

            // check this type does not already exist
            for (int i = 0; i < jsonControls.size(); i++) {
                if (jsonControl.getString("type").equals(jsonControls.get(i).getString("type")))
                    throw new Exception(" control type is loaded already. Type names must be unique");
            }

            // add the jsonControl to our array
            jsonControls.add(jsonControl);

            // inc the control count
            controlCount++;
            // inc the count of controls in this file
            index++;

            // get the next one
            if (index < count)
                jsonControl = jsonControlCollection.getJSONArray("control").getJSONObject(index);

        } while (index < count);

    }

    // sort the list of controls by name
    Collections.sort(jsonControls, new Comparator<JSONObject>() {
        @Override
        public int compare(JSONObject c1, JSONObject c2) {
            try {
                return Comparators.AsciiCompare(c1.getString("name"), c2.getString("name"), false);
            } catch (JSONException e) {
                return 0;
            }
        }

    });

    // create a JSON Array object which will hold json for all of the available controls
    JSONArray jsonArrayControls = new JSONArray(jsonControls);

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

    _logger.info(controlCount + " controls loaded in .control.xml files");

    return controlCount;

}

From source file:uk.ac.ebi.bioinvindex.services.browse.BrowseStudyBeanImpl.java

private AssayInfoBean createAssayInfoBean(AssayInfoBean assayInfoBean, String assayRepresentation) {

    assayRepresentation = assayRepresentation.replace("assay(", "").replace(")", "");

    Scanner scanner = new Scanner(assayRepresentation);
    scanner.useDelimiter("\\|");

    if (scanner.hasNext()) {
        assayInfoBean.setEndPoint(scanner.next());
    } else {/* w ww .j av  a2s .  com*/
        assayInfoBean.setEndPoint("");
    }

    if (scanner.hasNext()) {
        String token = scanner.next();
        try {
            // check to see if the String can be made into a number.
            Integer.valueOf(token);
            assayInfoBean.setCount(token);
            assayInfoBean.setTechnology("");
        } catch (NumberFormatException nfe) {
            assayInfoBean.setTechnology(token);
            if (scanner.hasNext()) {
                assayInfoBean.setCount(scanner.next());
            } else {
                assayInfoBean.setCount("0");
            }
        }
    }

    return assayInfoBean;
}

From source file:com.twitter.hraven.rest.client.HRavenRestClient.java

public String getCluster(String hostname) throws IOException {
    String urlString = String.format("http://%s/api/v1/getCluster?hostname=%s", apiHostname,
            StringUtil.cleanseToken(hostname));

    if (LOG.isInfoEnabled()) {
        LOG.info("Requesting cluster for " + hostname);
    }/*from w ww . ja va  2  s.co m*/
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(this.connectTimeout);
    connection.setReadTimeout(this.readTimeout);
    InputStream input = connection.getInputStream();
    java.util.Scanner s = new java.util.Scanner(input).useDelimiter("\\A");
    String cluster = s.hasNext() ? s.next() : "";
    try {
        input.close();
    } catch (IOException ioe) {
        LOG.error("IOException in closing input stream, returning no error " + ioe.getMessage());
    }
    return cluster;
}

From source file:tajo.worker.TestWorker.java

public final void testRequestSubQuery() throws Exception {
    Fragment[] frags = sm.split("employee", 40000);

    int splitIdx = (int) Math.ceil(frags.length / 2.f);
    QueryIdFactory.reset();// w ww  .  jav  a 2s .  co  m

    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);

    sm.initTableBase(frags[0].getMeta(), "testLeafServer");
    QueryUnitRequest req1 = new QueryUnitRequestImpl(QueryIdFactory.newQueryUnitAttemptId(qid1, 0),
            Lists.newArrayList(Arrays.copyOfRange(frags, 0, splitIdx)), "", false, plan.toJSON());

    QueryUnitRequest req2 = new QueryUnitRequestImpl(QueryIdFactory.newQueryUnitAttemptId(qid2, 0),
            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
    TajoMaster master = util.getMiniTajoCluster().getMaster();
    Set<QueryUnitAttemptId> submitted = Sets.newHashSet();
    submitted.add(req1.getId());
    submitted.add(req2.getId());

    assertSubmittedAndReported(master, submitted);

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

    assertEquals(tupleNum, j);
}