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:core.MusicStreaming.java

public void play() throws JavaLayerException, IOException {

    ftpClient = new FTPClient();
    ftpClient.connect(server, port);/*www  .jav a 2s. co  m*/
    ftpClient.login(user, pass);
    ftpClient.enterLocalPassiveMode();
    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    System.out.println(ftpClient.getListHiddenFiles());
    engine = ftpClient.initiateListParsing();

    files = engine.getFiles();

    for (int i = 0; i < files.length; i++) {
        System.out.println(i + "  " + files[i].getName());
    }

    Scanner scanner = new Scanner(System.in);
    while (scanner.hasNext()) {

        int i = scanner.nextInt();
        song = "/" + files[i].getName();
        System.out.println("curently playing " + i);
        //        song = "/Bondhu Tomar Chokher Majhe.mp3";

        if (!isFirst) {
            System.out.println("trying to stop");
            mp3player.close();
            mp3player.getPosition();
            in.close();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    isFirst = false;
                    in = new BufferedInputStream(ftpClient.retrieveFileStream(song));
                    mp3player = new Player(in);
                    mp3player.play();
                } catch (Exception ex) {
                    Logger.getLogger(MusicStreaming.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        }).start();

    }

}

From source file:com.android.idtt.http.client.util.URLEncodedUtils.java

/**
 * Returns a list of {@link org.apache.http.NameValuePair NameValuePairs} as built from the
 * URI's query portion. For example, a URI of
 * http://example.org/path/to/file?a=1&b=2&c=3 would return a list of three
 * NameValuePairs, one for a=1, one for b=2, and one for c=3.
 * <p/>//ww w .ja  va2s. c  om
 * This is typically useful while parsing an HTTP PUT.
 *
 * @param uri      uri to parse
 * @param encoding encoding to use while parsing the query
 */
public static List<NameValuePair> parse(final URI uri, final String encoding) {
    final String query = uri.getRawQuery();
    if (!TextUtils.isEmpty(query)) {
        List<NameValuePair> result = new ArrayList<NameValuePair>();
        Scanner scanner = new Scanner(query);
        parse(result, scanner, encoding);
        return result;
    } else {
        return Collections.emptyList();
    }
}

From source file:com.l2jfree.gameserver.datatables.ExtractableItemsData.java

private ExtractableItemsData() {
    _items.clear();/* ww  w .ja  va  2  s  . c  o  m*/

    Scanner s;

    try {
        s = new Scanner(new File(Config.DATAPACK_ROOT, "data/extractable_items.csv"));
    } catch (Exception e) {
        _log.warn("Extractable items data: Can not find '" + Config.DATAPACK_ROOT
                + "data/extractable_items.csv'");
        return;
    }

    int lineCount = 0;

    while (s.hasNextLine()) {
        lineCount++;

        String line = s.nextLine().trim();

        if (line.startsWith("#"))
            continue;
        else if (line.isEmpty())
            continue;

        String[] lineSplit = line.split(";");
        boolean ok = true;
        int itemID = 0;

        try {
            itemID = Integer.parseInt(lineSplit[0]);
        } catch (Exception e) {
            _log.warn("Extractable items data: Error in line " + lineCount
                    + " -> invalid item id or wrong seperator after item id!");
            _log.warn("      " + line);
            ok = false;
        }

        if (!ok)
            continue;

        FastList<L2ExtractableProductItem> product_temp = new FastList<L2ExtractableProductItem>();

        for (int i = 0; i < lineSplit.length - 1; i++) {
            ok = true;

            String[] lineSplit2 = lineSplit[i + 1].split(",");

            if (lineSplit2.length < 3) {
                _log.warn("Extractable items data: Error in line " + lineCount + " -> wrong seperator!");
                _log.warn("      " + line);
                ok = false;
            }

            if (!ok)
                continue;

            int[] production = null;
            int[] amount = null;
            int chance = 0;

            try {
                int k = 0;
                production = new int[(lineSplit2.length - 1) / 2];
                amount = new int[(lineSplit2.length - 1) / 2];
                for (int j = 0; j < lineSplit2.length - 1; j++) {
                    production[k] = Integer.parseInt(lineSplit2[j]);
                    amount[k] = Integer.parseInt(lineSplit2[j += 1]);
                    k++;
                }

                chance = Integer.parseInt(lineSplit2[lineSplit2.length - 1]);
            } catch (Exception e) {
                _log.warn("Extractable items data: Error in line " + lineCount
                        + " -> incomplete/invalid production data or wrong seperator!");
                _log.warn("      " + line);
                ok = false;
            }

            if (!ok)
                continue;

            L2ExtractableProductItem product = new L2ExtractableProductItem(production, amount, chance);
            product_temp.add(product);
        }

        int fullChances = 0;

        for (L2ExtractableProductItem Pi : product_temp)
            fullChances += Pi.getChance();

        if (fullChances > 100) {
            _log.warn("Extractable items data: Error in line " + lineCount
                    + " -> all chances together are more then 100!");
            _log.warn("      " + line);
            continue;
        }
        L2ExtractableItem product = new L2ExtractableItem(itemID, product_temp);
        _items.put(itemID, product);
    }

    s.close();
    _log.info("Extractable items data: Loaded " + _items.size() + " extractable items!");
}

From source file:wordGame.Util.WebUtil.java

public static Board GetBoardFromServer(String boardID) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet getMethod = new HttpGet(WEBGETBOARD + boardID);
    Scanner fileScanner = null;/*w  w  w  .j ava 2 s  .c o m*/
    String boardString = null;
    try {
        HttpResponse response = httpclient.execute(getMethod);
        HttpEntity responseEntity = response.getEntity();

        if (responseEntity != null) {
            fileScanner = new Scanner(new BufferedReader(new InputStreamReader(responseEntity.getContent())));
            while (fileScanner.hasNext()) {
                boardString = fileScanner.next();
                return BoardGenerator.generateCubesFromWebString(boardString);
            }
        }
    } catch (IOException e) {
        return null;
    }
    return null;

}

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

/**
 * Loads the credential profiles from the given input stream.
 *
 * @param is input stream from where the profile details are read.
 * @throws IOException/*from   w w  w  .j av  a 2 s.  com*/
 */
private static Map<String, Profile> loadProfiles(InputStream is) throws IOException {
    ProfilesConfigFileLoaderHelper helper = new ProfilesConfigFileLoaderHelper();
    Map<String, Map<String, String>> allProfileProperties = helper.parseProfileProperties(new Scanner(is));

    // Convert the loaded property map to credential objects
    Map<String, Profile> profilesByName = new LinkedHashMap<String, Profile>();

    for (Entry<String, Map<String, String>> entry : allProfileProperties.entrySet()) {
        String profileName = entry.getKey();
        Map<String, String> properties = entry.getValue();

        if (profileName.startsWith("profile ")) {
            LOG.warn("The legacy profile format requires the 'profile ' prefix before the profile name. "
                    + "The latest code does not require such prefix, and will consider it as part of the profile name. "
                    + "Please remove the prefix if you are seeing this warning.");
        }

        String accessKey = properties.get(Profile.AWS_ACCESS_KEY_ID);
        String secretKey = properties.get(Profile.AWS_SECRET_ACCESS_KEY);
        String sessionToken = properties.get(Profile.AWS_SESSION_TOKEN);

        assertParameterNotEmpty(profileName, "Unable to load credentials into profile: ProfileName is empty.");
        if (accessKey == null) {
            throw new AmazonClientException(String.format(
                    "Unable to load credentials into profile [%s]: AWS Access Key ID is not specified.",
                    profileName));
        }
        if (secretKey == null) {
            throw new AmazonClientException(String.format(
                    "Unable to load credentials into profile [%s]: AWS Secret Access Key is not specified.",
                    profileName));
        }

        if (sessionToken == null) {
            profilesByName.put(profileName,
                    new Profile(profileName, new BasicAWSCredentials(accessKey, secretKey)));
        } else {
            if (sessionToken.isEmpty()) {
                throw new AmazonClientException(String.format(
                        "Unable to load credentials into profile [%s]: AWS Session Token is empty.",
                        profileName));
            }

            profilesByName.put(profileName,
                    new Profile(profileName, new BasicSessionCredentials(accessKey, secretKey, sessionToken)));
        }
    }

    return profilesByName;
}

From source file:com.github.mavogel.ilias.utils.IOUtils.java

/**
 * Reads and parses a multiple choices from the user.<br>
 * Handles wrong inputs and ensures the choices are meaningful (lo <= up) and in
 * the range of the possible choices./* w  ww.  ja va2 s . c  om*/
 *
 * @param choices the possible choices
 * @return the choice of the user.
 */
public static List<Integer> readAndParseChoicesFromUser(final List<?> choices) {
    boolean isCorrectDigits = false, isCorrectRanges = false;
    String line = null;
    List<Integer> digits = null;
    List<String[]> ranges = null;

    Scanner scanner = new Scanner(System.in);
    while (!(isCorrectDigits && isCorrectRanges)) {
        try {
            LOG.info(
                    "Your choice: \n - Comma separated choices and/or ranges (e.g.: 1, 2, 4-6, 8, 10-15 -> or a combination) \n - The Wildcard 'A' for selecting all choices");
            line = scanner.nextLine();

            if (containsWildcard(line)) {
                return IntStream.range(0, choices.size()).mapToObj(Integer::valueOf)
                        .collect(Collectors.toList());
            }
            // == 1
            List<String> trimmedSplit = splitAndTrim(line);
            checkForInvalidCharacters(trimmedSplit);

            // == 2
            digits = parseDigits(trimmedSplit);
            isCorrectDigits = checkInputDigits(choices, digits);

            // == 3
            ranges = parseRanges(trimmedSplit);
            isCorrectRanges = checkRanges(choices, ranges);
        } catch (NumberFormatException nfe) {
            if (!isCorrectDigits) {
                LOG.error("'" + line + "' contains incorrect indexes! Try again");
            }
            if (!isCorrectRanges) {
                LOG.error("'" + line + "' contains incorrect ranges! Try again");
            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }
    }

    return concatDigitsAndRanges(digits, ranges);
}

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

private ExpenseItemDao(Context context) {
    itemList = new ArrayList<ExpenseItem>();
    File file = new File(context.getFilesDir(), FILENAME);
    Scanner scanner = null;/*from  w  ww  .j  a  v a  2 s.  c om*/
    try {
        scanner = new Scanner(file);
        while (scanner.hasNextLine()) {
            JSONObject jo = new JSONObject(scanner.nextLine());
            ExpenseItem item = new ExpenseItem();
            item.setId(jo.getInt("id"));
            item.setClaimId(jo.getInt("claimId"));
            item.setCategory(jo.getString("category"));
            item.setDescription(jo.getString("description"));
            item.setDate(new Date(jo.getLong("date")));
            item.setAmount(jo.getDouble("amount"));
            item.setUnit(jo.getString("unit"));
            if (maxId < item.getId()) {
                maxId = item.getId();
            }
            itemList.add(item);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    maxId++;
}

From source file:net.sf.jaceko.mock.resource.BasicSetupResource.java

static Map<String, String> parseHeadersToPrime(String headersToPrime) {
    Map<String, String> headersMap = new HashMap<String, String>();

    if (headersToPrime != null) {
        Scanner headersScanner = new Scanner(headersToPrime).useDelimiter(HEADERS_DELIMITER);
        while (headersScanner.hasNext()) {
            String header = headersScanner.next();
            String[] headerPart = header.split(HEADER_DELIMITER);
            String headerName = headerPart[HEADER_KEY_INDEX];
            String headerValue = headerPart[HEADER_VALUE_INDEX];
            headersMap.put(headerName, headerValue);
        }//from   w  w  w.ja  v  a2 s. c  om
    }

    return headersMap;
}

From source file:AwsConsoleApp.java

public static void main(String[] args) throws Exception {

    System.out.println("===========================================");
    System.out.println("Welcome to the AWS VPN connection creator");
    System.out.println("===========================================");

    init();//w ww. j  av a 2 s. co m
    List<String> CIDRblocks = new ArrayList<String>();
    String vpnType = null;
    String vpnGatewayId = null;
    String customerGatewayId = null;
    String customerGatewayInfoPath = null;
    String routes = null;

    options.addOption("h", "help", false, "show help.");
    options.addOption("vt", "vpntype", true, "Set vpn tunnel type e.g. (ipec.1)");
    options.addOption("vgw", "vpnGatewayId", true, "Set AWS VPN Gateway ID e.g. (vgw-eca54d85)");
    options.addOption("cgw", "customerGatewayId", true, "Set AWS Customer Gateway ID e.g. (cgw-c16e87a8)");
    options.addOption("r", "staticroutes", true, "Set static routes e.g. cutomer subnet 10.77.77.0/24");
    options.addOption("vi", "vpninfo", true, "path to vpn info file c:\\temp\\customerGatewayInfo.xml");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    // Parse command line options
    try {
        cmd = parser.parse(options, args);

        if (cmd.hasOption("h"))
            help();

        if (cmd.hasOption("vt")) {
            log.log(Level.INFO, "Using cli argument -vt=" + cmd.getOptionValue("vt"));

            vpnType = cmd.getOptionValue("vt");

            // Whatever you want to do with the setting goes here
        } else {
            log.log(Level.SEVERE, "Missing vt option");
            help();
        }

        if (cmd.hasOption("vgw")) {
            log.log(Level.INFO, "Using cli argument -vgw=" + cmd.getOptionValue("vgw"));
            vpnGatewayId = cmd.getOptionValue("vgw");
        } else {
            log.log(Level.SEVERE, "Missing vgw option");
            help();
        }

        if (cmd.hasOption("cgw")) {
            log.log(Level.INFO, "Using cli argument -cgw=" + cmd.getOptionValue("cgw"));
            customerGatewayId = cmd.getOptionValue("cgw");

        } else {
            log.log(Level.SEVERE, "Missing cgw option");
            help();
        }

        if (cmd.hasOption("r")) {
            log.log(Level.INFO, "Using cli argument -r=" + cmd.getOptionValue("r"));
            routes = cmd.getOptionValue("r");

            String[] routeItems = routes.split(",");
            CIDRblocks = Arrays.asList(routeItems);

        } else {
            log.log(Level.SEVERE, "Missing r option");
            help();
        }

        if (cmd.hasOption("vi")) {
            log.log(Level.INFO, "Using cli argument -vi=" + cmd.getOptionValue("vi"));
            customerGatewayInfoPath = cmd.getOptionValue("vi");

        } else {
            log.log(Level.SEVERE, "Missing vi option");
            help();
        }

    } catch (ParseException e) {
        log.log(Level.SEVERE, "Failed to parse comand line properties", e);
        help();
    }

    /*
     * Amazon VPC
     * Create and delete VPN tunnel to customer VPN hardware
     */
    try {

        //String vpnType = "ipsec.1";
        //String vpnGatewayId = "vgw-eca54d85";
        //String customerGatewayId = "cgw-c16e87a8";
        //List<String> CIDRblocks = new ArrayList<String>();
        //CIDRblocks.add("10.77.77.0/24");
        //CIDRblocks.add("172.16.1.0/24");
        //CIDRblocks.add("172.18.1.0/24");
        //CIDRblocks.add("10.66.66.0/24");
        //CIDRblocks.add("10.8.1.0/24");

        //String customerGatewayInfoPath = "c:\\temp\\customerGatewayInfo.xml";

        Boolean staticRoutesOnly = true;

        List<String> connectionIds = new ArrayList<String>();
        List<String> connectionIdList = new ArrayList<String>();

        connectionIdList = vpnExists(connectionIds);

        if (connectionIdList.size() == 0) {
            CreateVpnConnectionRequest vpnReq = new CreateVpnConnectionRequest(vpnType, customerGatewayId,
                    vpnGatewayId);
            CreateVpnConnectionResult vpnRes = new CreateVpnConnectionResult();

            VpnConnectionOptionsSpecification vpnspec = new VpnConnectionOptionsSpecification();
            vpnspec.setStaticRoutesOnly(staticRoutesOnly);
            vpnReq.setOptions(vpnspec);

            System.out.println("Creating VPN connection");
            vpnRes = ec2.createVpnConnection(vpnReq);
            String vpnConnId = vpnRes.getVpnConnection().getVpnConnectionId();
            String customerGatewayInfo = vpnRes.getVpnConnection().getCustomerGatewayConfiguration();

            //System.out.println("Customer Gateway Info:" + customerGatewayInfo);

            // Write Customer Gateway Info to file
            System.out.println("Writing Customer Gateway Info to file:" + customerGatewayInfoPath);
            try (PrintStream out = new PrintStream(new FileOutputStream(customerGatewayInfoPath))) {
                out.print(customerGatewayInfo);
            }

            System.out.println("Creating VPN routes");
            for (String destCIDR : CIDRblocks) {
                CreateVpnConnectionRouteRequest routeReq = new CreateVpnConnectionRouteRequest();
                CreateVpnConnectionRouteResult routeRes = new CreateVpnConnectionRouteResult();

                routeReq.setDestinationCidrBlock(destCIDR);
                routeReq.setVpnConnectionId(vpnConnId);

                routeRes = ec2.createVpnConnectionRoute(routeReq);
            }

            // Parse XML file
            File file = new File(customerGatewayInfoPath);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(customerGatewayInfoPath);

            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression exprGetipAddress = xpath
                    .compile("/vpn_connection/ipsec_tunnel/vpn_gateway/tunnel_outside_address/ip_address");
            NodeList vpnGateway = (NodeList) exprGetipAddress.evaluate(document, XPathConstants.NODESET);
            if (vpnGateway != null) {
                for (int i = 0; i < vpnGateway.getLength(); i++) {
                    String vpnGatewayIP = vpnGateway.item(i).getTextContent();
                    System.out
                            .println("AWS vpnGatewayIP for tunnel " + Integer.toString(i) + " " + vpnGatewayIP);
                }
            }

            System.out.println("==============================================");

            XPathExpression exprGetKey = xpath.compile("/vpn_connection/ipsec_tunnel/ike/pre_shared_key");
            NodeList presharedKeyList = (NodeList) exprGetKey.evaluate(document, XPathConstants.NODESET);
            if (presharedKeyList != null) {
                for (int i = 0; i < presharedKeyList.getLength(); i++) {
                    String pre_shared_key = presharedKeyList.item(i).getTextContent();
                    System.out.println(
                            "AWS pre_shared_key for tunnel " + Integer.toString(i) + " " + pre_shared_key);
                }
            }

            System.out.println("Creating VPN creation completed!");

        } else {
            boolean yn;
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter yes or no to delete VPN connection: ");
            String input = scan.next();
            String answer = input.trim().toLowerCase();
            while (true) {
                if (answer.equals("yes")) {
                    yn = true;
                    break;
                } else if (answer.equals("no")) {
                    yn = false;
                    System.exit(0);
                } else {
                    System.out.println("Sorry, I didn't catch that. Please answer yes/no");
                }
            }

            // Delete all existing VPN connections
            System.out.println("Deleting AWS VPN connection(s)");

            for (String vpnConID : connectionIdList) {
                DeleteVpnConnectionResult delVPNres = new DeleteVpnConnectionResult();
                DeleteVpnConnectionRequest delVPNreq = new DeleteVpnConnectionRequest();
                delVPNreq.setVpnConnectionId(vpnConID);

                delVPNres = ec2.deleteVpnConnection(delVPNreq);
                System.out.println("Successfully deleted AWS VPN conntion: " + vpnConID);

            }

        }

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}

From source file:org.apache.streams.rss.test.SyndEntryActivitySerizlizerTest.java

@Test
public void testJsonData() throws Exception {
    Scanner scanner = new Scanner(this.getClass().getResourceAsStream("/TestSyndEntryJson.txt"));
    List<Activity> activities = Lists.newLinkedList();
    List<ObjectNode> objects = Lists.newLinkedList();

    SyndEntryActivitySerializer serializer = new SyndEntryActivitySerializer();

    while (scanner.hasNext()) {
        String line = scanner.nextLine();
        System.out.println(line);
        ObjectNode node = (ObjectNode) mapper.readTree(line);

        objects.add(node);/*from   w ww  .j a  va  2s . co  m*/
        activities.add(serializer.deserialize(node));
    }

    assertEquals(11, activities.size());

    for (int x = 0; x < activities.size(); x++) {
        ObjectNode n = objects.get(x);
        Activity a = activities.get(x);

        testActor(n.get("author").asText(), a.getActor());
        testAuthor(n.get("author").asText(), a.getObject().getAuthor());
        testProvider("id:providers:rss", "RSS", a.getProvider());
        testProviderUrl(a.getProvider());
        testVerb("post", a.getVerb());
        testPublished(n.get("publishedDate").asText(), a.getPublished());
        testUrl(n.get("uri").asText(), n.get("link").asText(), a);
    }
}