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:HackathonSupporter.java

@Override
/**/*from   w w w  .  j ava 2 s .  c  om*/
 * Returns the banner after searching in the file.
 * @param advId The forced advertisement id you get from GET request
 * @param width the requested width
 * @param height the request height
 * @param segmentId the segment ID you get by reading the cookie
 * @context object of ServletContext which is needed to read the config.properties file
 */
public String readFromFile(String advId, int width, int height, int segmentId, ServletContext context,
        int callingFlag) {
    File file = null;
    Scanner fis = null;
    String banner = null;
    try {
        //read the filename and mappingFilename form the config.properties file
        Properties prop = new Properties();
        if (callingFlag == 0) {
            prop.load(new InputStreamReader(context.getResourceAsStream("/WEB-INF/config.properties")));
        } else if (callingFlag == 1) {
            prop.load(new FileReader(
                    "/home/sankalpkulshrestha/NetBeansProjects/AdServer/web/WEB-INF/config.properties"));
        } else {
            return DEFAULT_BANNER;
        }
        //filename contains the list of advId, width, height, banner,segmentID. The filename is input.txt
        String filename = prop.getProperty("filename");
        //mappingFilename contains the mapping of the advId and the default banner address
        String mappingFilename = prop.getProperty("mappingFilename");

        file = new File(filename);
        fis = new Scanner(file);
        String line = null;
        //read the each line of input.txt, split it by comma and store it in param String array
        String[] param = new String[5];
        //w and h hold the width and height respectively.
        //flag keeps track of whether a corresponding advId is found for a segnment ID, in case the advId is null
        int w = -1, h = -1, flag = 0;
        while (fis.hasNextLine()) {
            //read each line and split by comma
            line = fis.nextLine();
            param = line.split(",");
            //read the width and height from the input.txt
            w = Integer.parseInt(param[1]);
            h = Integer.parseInt(param[2]);
            //in case we are not getting and forced advertisement ID, we keep searching for the corresponding advId is found for a segnment ID
            if ((advId == null || advId.length() == 0) && flag == 0
                    && segmentId == Integer.parseInt(param[4])) {
                flag = 1;
                advId = param[0];
            }
            //in case segment ID is not 0 and segmentId is same as the segment ID found from the file of same width
            //and height as the requested width and height, we set the corresponding banner from the file and break away
            if (segmentId != 0 && segmentId == Integer.parseInt(param[4]) && w == width && h == height) {
                banner = param[3];
                break;
            }
        }
        //close the input.txt file
        if (fis != null) {
            fis.close();
        }

        //if till now the banner is still null and the advId is not null
        //then we check the mapping.txt file for finding the default banner of the campaign 
        //the advId points to
        if (banner == null && advId != null) {
            File file2 = new File(mappingFilename);
            Scanner fis2 = null;
            fis2 = new Scanner(file2);
            param = new String[2];
            while (fis2.hasNextLine()) {
                line = fis2.nextLine();
                param = line.split(",");
                if (param[0].equals(advId)) {
                    banner = param[1];
                    break;
                }
            }
            //close the mapping.txt file
            if (fis2 != null) {
                fis2.close();
            }
        } else if (banner == null && advId == null) {
            //in case the banner is null and the advId is null, we return the default banner
            return DEFAULT_BANNER;
        }
    } catch (IOException e) {
        //in case of any exception, we return the default banner
        return DEFAULT_BANNER;
    } finally {
        //close the file
        if (fis != null) {
            fis.close();
        }
    }
    return banner;
}

From source file:com.joliciel.talismane.machineLearning.TextFileResource.java

public TextFileResource(File file) {
    try {//  ww w .j a v  a 2s.  c  o m
        this.name = file.getName();

        Scanner scanner = new Scanner(file);
        int numParts = -1;
        int i = 1;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.length() > 0 && !line.startsWith("#")) {
                StringBuilder sb = new StringBuilder();
                String[] parts = line.split("\t");
                if (parts.length == 1 && line.startsWith("Name: ")) {
                    this.name = line.substring("Name: ".length());
                    i++;
                    continue;
                }
                if (parts.length == 1 && line.startsWith("Multivalued: ")) {
                    boolean multivalued = line.substring("Multivalued: ".length()).equalsIgnoreCase("true");
                    if (multivalued)
                        throw new JolicielException("Did not expect multivalued resource");
                    i++;
                    continue;
                }
                if (numParts < 0)
                    numParts = parts.length;
                if (parts.length != numParts)
                    throw new JolicielException(
                            "Wrong number of elements on line " + i + " in file: " + file.getName());

                for (int j = 0; j < numParts - 1; j++) {
                    sb.append(parts[j]);
                    sb.append("|");
                }
                String key = sb.toString();
                String value = parts[numParts - 1];
                resultMap.put(key, value);

            }
            i++;
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

public static int cargarParadasLinea(Context context, int numeroLinea) {
    if (!isConnectionEnabled(context)) {
        return SIN_CONEXION;
    }/*from   ww  w  .j  a v a 2s.c  o  m*/
    try {
        if (cookie == null) {
            if (loadCookie() == MANTENIMIENTO) {
                return MANTENIMIENTO;
            }
        }
        URL url = new URL(QUERY_ADDRESS_PARADAS_LINEA + numeroLinea);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setRequestProperty("Cookie", "ASP.NET_SessionId=" + cookie);
        connection.setRequestProperty("REFERER", "http://m.surbus.com/tiempo-espera");
        connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        connection.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        connection.connect();
        Scanner scan = new Scanner(connection.getInputStream());
        StringBuilder strBuilder = new StringBuilder();
        while (scan.hasNextLine()) {
            strBuilder.append(scan.nextLine());
        }
        scan.close();
        JSONObject json = new JSONObject(strBuilder.toString());
        Log.d("Almeribus", strBuilder.toString());
        boolean isSuccessful = json.getBoolean("success");
        if (isSuccessful) {
            DataStorage.DBHelper.eliminarParadasLinea(numeroLinea);
            Linea l = new Linea(numeroLinea);
            JSONArray list = json.getJSONArray("list");
            Parada primeraParada = null;
            Parada paradaAnterior = null;
            for (int i = 0; i < list.length(); i++) {
                JSONObject paradaJSON = list.getJSONObject(i);
                int numeroParada = paradaJSON.getInt("IdBusStop");
                String nombreParada = paradaJSON.getString("Name");
                Parada p = null;
                if (DataStorage.paradas.containsKey(numeroParada)) {
                    p = DataStorage.paradas.get(numeroParada);
                    p.setNombre(nombreParada);
                } else {
                    p = new Parada(numeroParada, nombreParada);
                }
                synchronized (DataStorage.DBHelper) {
                    DataStorage.DBHelper.addInfoParada(numeroParada, nombreParada);
                }
                p.addLinea(l.getNumero());
                if (paradaAnterior != null) {
                    p.setAnterior(paradaAnterior.getId(), numeroLinea);
                }

                if (i == 0) {
                    primeraParada = p;
                } else if (i == list.length() - 1) {
                    primeraParada.setAnterior(p.getId(), numeroLinea);
                    p.setSiguiente(primeraParada.getId(), numeroLinea);
                }

                if (paradaAnterior != null) {
                    paradaAnterior.setSiguiente(p.getId(), numeroLinea);
                }

                paradaAnterior = p;
                synchronized (DataStorage.paradas) {
                    if (DataStorage.paradas.containsKey(numeroParada)) {
                        DataStorage.paradas.remove(numeroParada);
                    }
                    DataStorage.paradas.put(numeroParada, p);
                }

                l.addParada(p);
            }
            DataStorage.lineas.put(numeroLinea, l);
            for (Parada parada : l.getParadas()) {
                synchronized (DataStorage.DBHelper) {
                    try {
                        DataStorage.DBHelper.addParadaLinea(parada.getId(), numeroLinea,
                                parada.getSiguiente(numeroLinea));
                    } catch (ParadaNotFoundException e) {
                        DataStorage.DBHelper.addParadaLinea(parada.getId(), numeroLinea, 0);
                    }
                }
            }
            return TODO_OK;
        } else {
            return ERROR_IO;
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        return ERROR_IO;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return ERROR_IO;
}

From source file:eu.seaclouds.platform.planner.core.HttpHelper.java

/**
 *
 * @param restPath//w  ww.ja v a 2 s .co m
 * @param params
 * @return
 */
public String getRequest(String restPath, List<NameValuePair> params) {

    HttpGet httpGet = new HttpGet(prepareRequestURL(restPath, params));

    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        String content = new Scanner(entity.getContent()).useDelimiter("\\Z").next();
        EntityUtils.consume(entity);
        return content;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            response.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

From source file:net.phillm.javaconsole.ConsoleApp.java

/**
 * @param args the command line arguments
 *///from   ww  w  .  j  a  va  2 s . co  m
public void main(String[] args) {
    // TODO code application logic here

    //Initialize main loop
    boolean runLoop;
    runLoop = true;

    String knownhostsFile;
    knownhostsFile = System.getProperty("user.home") + File.separator + ".ssh" + File.separator + "known_hosts";
    jsch = new JSch();
    try {
        jsch.setKnownHosts(knownhostsFile);
    } catch (JSchException ex) {
        System.out.println("Error while trying to import kown hosts: " + ex.getMessage());
    }

    remoteCmds.put("cd", "cd");
    remoteCmds.put("ls", "ls");
    remoteCmds.put("ping", "ping");

    Scanner scanner = new Scanner(System.in);
    String currentCommand;

    System.out.println("Info: Type /info to get the build version!");
    System.out.println("Info: Type /help to get a list of availble commands!");

    while (runLoop) { //loop untill /stop command
        currentCommand = scanner.nextLine().toLowerCase();

        if (currentCommand.contains("/info")) {
            System.out.println("Build Version: " + version);
            System.out.println("Website: " + website);
            System.out.println("View on Github: " + github);

        } else if (currentCommand.contains("/website") || currentCommand.contains("/site")) {
            System.out.println("Website: " + website);

        } else if (currentCommand.contains("/help")) {
            System.out.println("/Info: Gives Info Such as Build Version, Website, and Github Link");
            System.out.println("/Website: Gives The Developers Website");
            System.out.println("/Help: Gives All Commands");
            System.out.println("/Connect [Host]: Open a connection to Host");
            System.out.println("/Id: get a block id number from its name");
            System.out.println("/Stop: Close the console");

        } else if (currentCommand.contains("/stop") || currentCommand.contains("/quit")
                || currentCommand.contains("/exit") || currentCommand.contains("/close")) {
            System.out.println("Stopping");
            runLoop = false;

        } else if (currentCommand.contains("/connect")) {
            String host = "";
            String username = "";
            String password = "";
            List<Integer> ports = new ArrayList<>();
            int timeout = 5000;

            ports.add(22);
            ports.add(35681);

            String[] ssh_Parameters = currentCommand.split(" ");
            if (ssh_Parameters.length > 1) {
                host = ssh_Parameters[1];
            }

            if (ssh_Parameters.length > 2) {
                username = ssh_Parameters[2];
            }

            if (ssh_Parameters.length > 3) {
                password = ssh_Parameters[3];
            }

            if (host.equals("")) {
                System.out.println("Enter host to connect to.");
                host = scanner.nextLine();
            }
            if (username.equals("")) {
                System.out.println("Enter username.");
                username = scanner.nextLine();
            }
            if (password.equals("")) {
                System.out.println("Enter password.");
                password = scanner.nextLine();
            }
            System.out.println("Connecting to " + host + "...");

            int portTryCount = 0;
            Boolean sessionIsConnected = false;
            Boolean continueTrying = true;
            while ((!sessionIsConnected) && continueTrying && (portTryCount < ports.size())) {
                try {
                    sshSession = jsch.getSession(username, host, ports.get(portTryCount));
                    sshSession.setPassword(password);
                    sshSession.connect(timeout);
                    sessionIsConnected = sshSession.isConnected();
                } catch (JSchException ex) {
                    if (ex.getMessage().contains("timeout: socket is not established")) {
                        portTryCount++;
                    } else if (ex.getMessage().contains("Connection refused: connect")) {
                        portTryCount++;
                    } else if (ex.getMessage().contains("UnknownHostKey")) {
                        String response;

                        System.out.println(ex.getMessage());
                        System.out.println("Continue anyway? (y/n)");
                        response = scanner.nextLine();
                        switch (response.toLowerCase()) {
                        case "n":
                            continueTrying = false;
                            System.out.println("Aborting...");
                            break;
                        case "y":
                            break;
                        default:
                            System.out.println("Please type either y or n");
                            break;
                        }

                    } else if (ex.getMessage().contains("Auth fail")) {
                        System.out.println("Could not Authenticate. Check the username and password.");
                        continueTrying = false;
                    } else {
                        System.out.println("Could not connect: " + ex.getMessage());
                    }
                }
            }

            if (sessionIsConnected & sshSession != null) {

                try {
                    sshShell = sshSession.openChannel("shell");

                } catch (JSchException ex) {
                    System.out.println("Error while obtaining shell: " + ex.getMessage());
                }
                if (sshShell != null) {
                    try {
                        sshShell.connect();
                    } catch (JSchException ex) {
                        System.out.println("Error while connecting shell: " + ex.getMessage());
                    }
                    if (sshShell.isConnected()) {
                        System.out.println("Connected!");
                        OutputStream sshCommandOutStream;
                        sshCommandOutStream = null;
                        InputStream sshResponseStream;
                        sshResponseStream = null;
                        try {
                            sshCommandOutStream = sshShell.getOutputStream();
                            sshResponseStream = sshShell.getInputStream();
                        } catch (IOException ex) {
                            System.out.println("Error while seting up shell io streams: " + ex.getMessage());
                        }
                        if (sshCommandOutStream != null) {
                            sshCommandStream = new PrintStream(sshCommandOutStream, true);
                        }
                        if (sshResponseStream != null) {
                            sshResponseBuffer = new BufferedReader(new InputStreamReader(sshResponseStream));

                        }
                    }
                }
            }

        } else if (currentCommand.contains("/id")) {
            String blockName = "";
            String[] idParams = currentCommand.split(" ");
            if (idParams.length > 1) {
                blockName = idParams[1];
            } else {
                while (blockName.equals("")) {
                    System.out.println("please type a block");
                    blockName = scanner.nextLine();
                }
            }
            System.out.println(
                    "ID for block " + blockName + " is " + idManager.blockInfo.get(blockName.toLowerCase()));

        } else {
            System.out.println("Commands Available: [/Info, /Website, /Help, /Connect, /Stop, /Id]");
        }
    }
    if (sshShell != null) {
        if (sshShell.isConnected()) {
            sshShell.disconnect();
        }
    }
    if (sshSession != null) {
        if (sshSession.isConnected()) {
            sshSession.disconnect();
        }
    }
}

From source file:org.apache.streams.console.ConsolePersistReader.java

@Override
public StreamsResultSet readCurrent() {

    LOGGER.info("{} readCurrent", STREAMS_ID);

    Scanner sc = new Scanner(inputStream);

    while (sc.hasNextLine()) {

        persistQueue.offer(new StreamsDatum(sc.nextLine()));

    }//from  w  ww  .  ja  va2s .  co  m

    LOGGER.info("Providing {} docs", persistQueue.size());

    StreamsResultSet result = new StreamsResultSet(persistQueue);

    LOGGER.info("{} Exiting", STREAMS_ID);

    return result;

}

From source file:com.networknt.exception.ExceptionHandlerTest.java

static RoutingHandler getTestHandler() {
    RoutingHandler handler = Handlers.routing().add(Methods.GET, "/normal", new HttpHandler() {
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            exchange.getResponseSender().send("normal");
        }/*from  w ww.j av  a 2s .  c om*/
    }).add(Methods.GET, "/runtime", new HttpHandler() {
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            int i = 1 / 0;
        }
    }).add(Methods.GET, "/api", new HttpHandler() {
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            Status error = new Status("ERR10001");
            throw new ApiException(error);
        }
    }).add(Methods.GET, "/uncaught", new HttpHandler() {
        public void handleRequest(HttpServerExchange exchange) throws Exception {
            String content = new Scanner(new File("djfkjoiwejjhh9032d")).useDelimiter("\\Z").next();
        }
    });
    return handler;
}

From source file:com.a544jh.kanamemory.io.JsonFileReader.java

protected static JSONObject readFileToJsonObject(File file) throws FileNotFoundException, JSONException {
    JSONObject jo;/*  w w  w  .  j a  va2 s .  c  om*/
    StringBuilder sb = new StringBuilder((int) file.length());
    try (Scanner scanner = new Scanner(file)) {
        while (scanner.hasNextLine()) {
            sb.append(scanner.nextLine());
        }
    }
    jo = new JSONObject(sb.toString());

    return jo;
}

From source file:io.stallion.users.UserAdder.java

public void execute(CommandOptionsBase options, String action) throws Exception {

    Log.info("Settings: siteName {0} email password {1}", Settings.instance().getSiteName(),
            Settings.instance().getEmail().getPassword());

    Scanner scanner = new Scanner(System.in);
    Console console = System.console();

    if (empty(action)) {
        //System.out.print("Create new user or edit existing? (new/edit): ");

        //String newEdit = scanner.next();

        System.out.print("Create new user or edit existing? (new/edit): ");
        //String newEdit = console.readLine("Create new user or edit existing? (new/edit): ");
        action = scanner.nextLine();//from w ww  .  j  av  a2  s . c o m
    }
    User user = null;
    if ("new".equals(action)) {
        user = new User();
        user.setPredefined(true);
    } else if ("edit".equals(action)) {
        System.out.print("Enter the email, username, or ID of the user you wish to edit:");
        String idMaybe = scanner.next();
        if (StringUtils.isNumeric(idMaybe)) {
            user = (User) UserController.instance().forId(Long.parseLong(idMaybe));
        }
        if (user == null) {
            user = (User) UserController.instance().forUniqueKey("email", idMaybe);
        }
        if (user == null) {
            user = (User) UserController.instance().forUniqueKey("username", idMaybe);
        }
        if (user == null) {
            System.out.print("Could not find user for key: " + idMaybe);
            System.exit(1);
        }
    } else {
        System.out.print("Invalid choice. Choose either 'new' or 'edit'");
        System.exit(1);
    }

    System.out.print("User's given name: ");
    String givenName = scanner.nextLine();
    if (!empty(givenName)) {
        user.setGivenName(givenName);
    }

    System.out.print("User's family name: ");
    String familyName = scanner.nextLine();
    if (!empty(familyName)) {
        user.setFamilyName(familyName);
        user.setDisplayName(user.getGivenName() + " " + user.getFamilyName());
    }

    System.out.print("User's email: ");
    String email = scanner.nextLine();
    if (!empty(email)) {
        user.setEmail(email);
        user.setUsername(user.getEmail());
    }

    System.out.print("Enter password: ");
    String password = "";
    if (console != null) {
        password = new String(console.readPassword());
    } else {
        password = new String(scanner.nextLine());
    }
    //System.out.printf("password: \"%s\"\n", password);
    if (empty(password) && empty(user.getBcryptedPassword())) {
        throw new UsageException("You must set a password!");
    } else if (!empty(password)) {
        String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
        user.setBcryptedPassword(hashed);
    }

    if (empty(user.getSecret())) {
        user.setSecret(RandomStringUtils.randomAlphanumeric(18));
    }
    if (empty(user.getEncryptionSecret())) {
        user.setEncryptionSecret(RandomStringUtils.randomAlphanumeric(36));
    }

    user.setPredefined(true);
    user.setRole(Role.ADMIN);
    user.setId(Context.dal().getTickets().nextId());
    user.setFilePath(GeneralUtils.slugify(user.getEmail() + "---" + user.getId().toString()) + ".json");
    UserController.instance().save(user);

    System.out.print("User saved with email " + user.getEmail() + " and id " + user.getId());

}

From source file:cpd3314.project.CPD3314ProjectTest.java

private void assertFilesEqual(File a, File b) throws IOException {
    Scanner aIn = new Scanner(a);
    Scanner bIn = new Scanner(b);
    while (aIn.hasNext() && bIn.hasNext()) {
        assertEquals(aIn.nextLine().trim(), bIn.nextLine().trim());
    }/*from w  ww  .j  av  a 2  s .  c om*/
    assertTrue("Files Not Equal Length", !aIn.hasNext() && !bIn.hasNext());
}