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:org.openmrs.module.eidinterface.web.controller.PatientStatusController.java

@ResponseBody
@RequestMapping(value = "module/eidinterface/getPatientStatus", method = RequestMethod.POST)
public String getPatientStatus(HttpServletResponse response, @RequestBody String identifiers)
        throws IOException {

    StringWriter sw = new StringWriter();
    CSVWriter csv = new CSVWriter(sw);

    String[] header = { "Identifier", "Status", "CCC Number" };
    csv.writeNext(header);//from  ww  w  .  ja  v  a 2 s . c om

    StringReader sr = new StringReader(identifiers);
    Scanner s = new Scanner(sr);

    // iterate through identifiers
    while (s.hasNext()) {

        String identifier = s.next().trim();

        String status;
        String ccc = "";

        String[] parts = identifier.split("-");
        String validIdentifier = new LuhnIdentifierValidator().getValidIdentifier(parts[0]);

        if (!OpenmrsUtil.nullSafeEquals(identifier, validIdentifier)) {
            status = "INVALID IDENTIFIER";
        } else {
            List<Patient> patients = Context.getPatientService().getPatients(null, identifier, null, true);
            if (patients != null && patients.size() == 1) {
                Patient p = patients.get(0);
                PatientIdentifier pi = p.getPatientIdentifier(CCC_NUMBER_PATIENT_IDENTIFIER_ID);
                if (pi != null) {
                    status = "ENROLLED";
                    ccc = pi.getIdentifier();
                } else {
                    status = "NOT ENROLLED";
                }
            } else if (patients != null && patients.size() > 1) {
                status = "MULTIPLE FOUND";
            } else {
                status = "NOT FOUND";
            }
        }

        csv.writeNext(new String[] { identifier, status, ccc });
    }

    // flush the string writer
    sw.flush();

    // set the information
    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    // respond with it
    return sw.toString();
}

From source file:com.amazonaws.auth.profile.internal.ProfilesConfigFileParser.java

/**
 * Loads the credentials from the given input stream.
 *
 * @param is input stream from where the profile details are read.
 * @throws IOException//from   w w w .ja va  2s  .  com
 */
private static Map<String, Profile> loadProfiles(InputStream is) throws IOException {
    Scanner scanner = new Scanner(is);
    AWSCredentials credentials = null;
    String profileName = null;
    String accessKey = null;
    String secretKey = null;
    String line = null;
    boolean accessKeyRead = false;
    boolean secretKeyRead = false;
    ProfileCredentialScannerState scannerState = ProfileCredentialScannerState.READ_CONFIG_NAME;
    HashMap<String, Profile> profilesByName = new HashMap<String, Profile>();

    try {
        while (scanner.hasNextLine()) {
            line = scanner.nextLine();
            line = line.trim();

            if (line.isEmpty())
                continue;

            if (!line.startsWith("[") && !line.startsWith(AWS_ACCESS_KEY_ID)
                    && !line.startsWith(AWS_SECRET_ACCESS_KEY)) {
                LOG.info("Unsupported configuration setting: " + line);
                continue;
            }

            switch (scannerState) {
            case READ_CONFIG_NAME:
                profileName = parseProfileName(line);
                scannerState = ProfileCredentialScannerState.READ_KEY;
                break;
            case READ_KEY:
                if (line.startsWith(AWS_ACCESS_KEY_ID) && !accessKeyRead) {
                    accessKey = parseAccessKey(line);
                    accessKeyRead = true;
                } else if (!secretKeyRead) {
                    secretKey = parseSecretKey(line);
                    secretKeyRead = true;
                } else {
                    throw new AmazonClientException(
                            "Unable to load Amazon AWS Credentials. File not in proper format.");
                }
                break;
            }

            if (accessKeyRead && secretKeyRead) {

                assertParameterNotEmpty(profileName,
                        "Unable to load credentials into profile. ProfileName is empty. " + line);
                assertParameterNotEmpty(accessKey,
                        "Unable to load credentials into profile. AWS Access Key ID is empty. " + line);
                assertParameterNotEmpty(secretKey,
                        "Unable to load credentials into profile. AWS Secret Access Key is empty. " + line);

                credentials = new BasicAWSCredentials(accessKey, secretKey);
                profilesByName.put(profileName, new Profile(credentials));
                scannerState = ProfileCredentialScannerState.READ_CONFIG_NAME;
                accessKeyRead = false;
                secretKeyRead = false;
            }
        }
        if (scannerState != ProfileCredentialScannerState.READ_CONFIG_NAME || accessKeyRead || secretKeyRead) {
            throw new AmazonClientException(
                    "Unable to load credentials into profile. Profile Name or AWS Access Key ID or AWS Secret Access Key missing for a profile.");
        }

    } finally {
        scanner.close();
    }

    return profilesByName;
}

From source file:com.microsoft.intellij.util.WAHelper.java

/**
 * This API compares if two files content is identical. It ignores extra
 * spaces and new lines while comparing//from  ww w.j ava  2s  .  com
 *
 * @param sourceFile
 * @param destFile
 * @return
 * @throws Exception
 */
public static boolean isFilesIdentical(URL sourceFile, File destFile) throws Exception {
    try {
        Scanner sourceFileScanner = new Scanner(sourceFile.openStream());
        Scanner destFileScanner = new Scanner(destFile);

        while (sourceFileScanner.hasNext()) {
            /*
             * If source file is having next token then destination file
            * also should have next token, else they are not identical.
            */
            if (!destFileScanner.hasNext()) {
                destFileScanner.close();
                sourceFileScanner.close();
                return false;
            }
            if (!sourceFileScanner.next().equals(destFileScanner.next())) {
                sourceFileScanner.close();
                destFileScanner.close();
                return false;
            }
        }
        /*
        * Handling the case where source file is empty and destination file
        * is having text
        */
        if (destFileScanner.hasNext()) {
            destFileScanner.close();
            sourceFileScanner.close();
            return false;
        } else {
            destFileScanner.close();
            sourceFileScanner.close();
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } /*finally {
      sourceFile.close();
      }*/
}

From source file:com.joliciel.talismane.posTagger.PosTagSetImpl.java

public PosTagSetImpl(File file) {
    Scanner scanner = null;/*from ww w  .  j  a  v  a  2s  . c  om*/
    try {
        scanner = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")));
        this.load(scanner);
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.github.rnewson.couchdb.lucene.Index.java

public static void main(String[] args) throws Exception {
    Utils.LOG.info("indexer started.");
    final Indexer indexer = new Indexer(FSDirectory.getDirectory(Config.INDEX_DIR));
    final Thread thread = new Thread(indexer, "index");
    thread.setDaemon(true);/*  ww w  . j a v  a2  s  .com*/
    thread.start();

    final Scanner scanner = new Scanner(System.in);
    while (scanner.hasNextLine()) {
        final String line = scanner.nextLine();
        final JSONObject obj = JSONObject.fromObject(line);
        if (obj.has("type") && obj.has("db")) {
            indexer.setStale(true);
        }
    }
    Utils.LOG.info("indexer stopped.");
}

From source file:de.vandermeer.skb.commons.utils.Json2Collections.java

/**
 * Reads the given JSON file and logs errors.
 * @param file JSON file//from   w  w  w.  j  a va2s  .co  m
 * @return a map with information from the JSON file or null in case of errors 
 */
public Object read(File file) {
    if (file != null && file.canRead()) {
        try {
            return this.read(new Scanner(file));
        } catch (Exception ignore) {
        }
    }
    return null;
}

From source file:at.beris.virtualfile.shell.Shell.java

public Shell() throws IOException {
    fileContext = new FileContext();
    localFile = fileContext.newLocalFile(System.getProperty("user.dir"));
    scanner = new Scanner(System.in);
    scanner.useDelimiter("\n");
}

From source file:msuresh.raftdistdb.RaftClient.java

public static void GetValue(String name, String key) throws FileNotFoundException {
    if (key == null || key.isEmpty()) {
        return;//from w ww .ja va 2s.  c  om
    }
    File configFile = new File(Constants.STATE_LOCATION + name + ".info");
    if (!configFile.exists() || configFile.isDirectory()) {
        FileNotFoundException ex = new FileNotFoundException();
        throw ex;
    }
    try {
        System.out.println("Getting key .. Hold on.");
        String content = new Scanner(configFile).useDelimiter("\\Z").next();
        JSONObject config = (JSONObject) (new JSONParser()).parse(content);
        Long numPart = (Long) config.get("countPartitions");
        Integer shardId = key.hashCode() % numPart.intValue();
        JSONArray memberJson = (JSONArray) config.get(shardId.toString());
        List<Address> members = new ArrayList<>();
        for (int i = 0; i < memberJson.size(); i++) {
            JSONObject obj = (JSONObject) memberJson.get(i);
            Long port = (Long) obj.get("port");
            String address = (String) obj.get("address");
            members.add(new Address(address, port.intValue()));
        }
        CopycatClient client = CopycatClient.builder(members).withTransport(new NettyTransport()).build();
        client.open().join();
        Object str = client.submit(new GetQuery(key)).get();
        System.out.println("For the key : " + key + ", the database returned the value : " + (String) str);
        client.close().join();
        while (client.isOpen()) {
            Thread.sleep(1000);
        }
    } catch (Exception ex) {
        System.out.println(ex.toString());
    }
}

From source file:com.btobits.automator.fix.utils.FileMessageFactory.java

public void load() throws Exception {
    try {/*  w ww.j a  v  a  2s  . c  o m*/
        Scanner scanner = new Scanner(new FileInputStream(file));

        while (scanner.hasNextLine()) {
            final String line = scanner.nextLine();

            if (StringUtils.isBlank(line)) {
                continue;
            }

            int i = line.indexOf("8=FIX");
            if (i != -1) {
                String s = line.substring(i);
                final String type = MessageUtils.getStringField(s, FixUtils.MSGTYPE);
                if (!isSkip(type)) {
                    messages.add(s);
                }
            }
        }
    } catch (Exception ex) {
        throw new Exception("Error load from file", ex);
    }
}

From source file:com.openbravo.webservicesimplementation.OpenbravoSystemClient.java

public void run() {
    StringBuilder menuString = new StringBuilder();
    in = new Scanner(System.in);
    menuString.append("OPENBRAVO SYSTEM SEND MENU\n");
    menuString.append("     1.- Get Product Category JSON\n");
    menuString.append("     2.- Send Order Entity JSON\n");
    menuString.append("     3.- Exit\n");
    while (!exit) {
        System.out.println(menuString.toString());
        userOption = in.nextLine();//from w w w  . j  a  v a  2 s  .  c o m
        switch (userOption) {
        case "1":
            this.getProductCategoryJSON();
            break;
        case "2":
            this.sendOrderEntityJSON();
            break;
        case "3":
            System.out.println("Bye !");
            exit = true;
            break;
        default:
            System.out.println("Incorrect option..try again\n");
        }
    }
}