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:net.ftb.util.DownloadUtils.java

/**
 * Checks the file for corruption./*from  w  w  w .  j a va2s.c om*/
 * @param file - File to check
 * @param url - base url to grab md5 with old method
 * @return boolean representing if it is valid
 * @throws IOException 
 */
public static boolean backupIsValid(File file, String url) throws IOException {
    Logger.logInfo("Issue with new md5 method, attempting to use backup method.");
    String content = null;
    Scanner scanner = null;
    String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer()))
            ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer())
            : Locations.masterRepo;
    resolved += "/md5/FTB2/" + url;
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) new URL(resolved).openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        int response = connection.getResponseCode();
        if (response == 200) {
            scanner = new Scanner(connection.getInputStream());
            scanner.useDelimiter("\\Z");
            content = scanner.next();
        }
        if (response != 200 || (content == null || content.isEmpty())) {
            for (String server : backupServers.values()) {
                resolved = "http://" + server + "/md5/FTB2/" + url.replace("/", "%5E");
                connection = (HttpURLConnection) new URL(resolved).openConnection();
                connection.setRequestProperty("Cache-Control", "no-transform");
                response = connection.getResponseCode();
                if (response == 200) {
                    scanner = new Scanner(connection.getInputStream());
                    scanner.useDelimiter("\\Z");
                    content = scanner.next();
                    if (content != null && !content.isEmpty()) {
                        break;
                    }
                }
            }
        }
    } catch (IOException e) {
    } finally {
        connection.disconnect();
        if (scanner != null) {
            scanner.close();
        }
    }
    String result = fileMD5(file);
    Logger.logInfo("Local: " + result.toUpperCase());
    Logger.logInfo("Remote: " + content.toUpperCase());
    return content.equalsIgnoreCase(result);
}

From source file:eu.project.ttc.resources.CompostInflectionRules.java

public void load(DataResource data) throws ResourceInitializationException {
    InputStream inputStream;//from   w  w w.j a  v a 2  s .co  m
    this.inflectionRules = Lists.newArrayList();
    try {
        inputStream = data.getInputStream();
        Scanner scanner = null;
        try {
            scanner = new Scanner(inputStream, "UTF-8");
            scanner.useDelimiter(TermSuiteConstants.LINE_BREAK);
            while (scanner.hasNext()) {
                String rawLine = scanner.next();
                String line = rawLine.split(";")[0];
                String[] args = line.split(",");
                if (args.length != 2 && !line.trim().isEmpty()) {
                    LOGGER.warn("Bad inflection rules format: " + rawLine);
                } else {
                    this.inflectionRules.add(new InflectionRule(args[0].trim(), args[1].trim()));
                }
            }
            this.inflectionRules = ImmutableList.copyOf(this.inflectionRules);
        } catch (Exception e) {
            throw new ResourceInitializationException(e);
        } finally {
            IOUtils.closeQuietly(scanner);
            IOUtils.closeQuietly(inputStream);
        }
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }
}

From source file:com.frankdye.marvelgraphws2.MarvelGraphView.java

private void processLine(String nextLine, Map<String, List<String>> map1, Set<String> set1) {
    // TODO Auto-generated method stub

    // use a second Scanner to parse the content of each line
    Scanner scanner = new Scanner(nextLine);
    scanner.useDelimiter("\t");
    if (scanner.hasNext()) {
        // assumes the line has a certain structure
        String first = scanner.next();
        first = first.replaceAll("^\"|\"$", "");
        String last = scanner.next();
        last = last.replaceAll("^\"|\"$", "");

        // Query map to see if we have an entry for this comic issue
        List<String> l = map1.get(last);
        if (l == null) // No entry for this issue so create it.
        {/*w w w  .j ava  2  s  .  c  o m*/
            map1.put(last, l = new ArrayList<String>());
        }
        // Issue exists or is created so append the characters name to the
        // map entry for that issue
        l.add(first);
        // Add the characters name to our set to maintain a list of each
        // unique character
        set1.add(first);

    } else {
        log("Empty or invalid line. Unable to process.");
    }
    scanner.close();

}

From source file:com.intel.cosbench.driver.handler.TriggerHandler.java

private String getTrigger(Scanner scanner) {
    if (!scanner.hasNext())
        LOGGER.error("bad request exception");
    String trigger = scanner.next();
    if (trigger == null)
        LOGGER.error("no found exception");
    return trigger;
}

From source file:kuona.jenkins.analyser.JenkinsClient.java

/**
 * Perform a GET request and parse the response and return a simple string of the content
 *
 * @param path path to request, can be relative or absolute
 * @return the entity text//from   ww w  .j a v a2 s . co  m
 * @throws IOException, HttpResponseException
 */
public String get(String path) throws IOException {
    HttpGet getMethod = new HttpGet(api(path));
    HttpResponse response = client.execute(getMethod, localContext);
    try {
        httpResponseValidator.validateResponse(response);
        Scanner s = new Scanner(response.getEntity().getContent());
        s.useDelimiter("\\z");
        StringBuffer sb = new StringBuffer();
        while (s.hasNext()) {
            sb.append(s.next());
        }
        return sb.toString();
    } finally {
        releaseConnection(getMethod);
    }
}

From source file:kuona.client.JenkinsHttpClient.java

/**
 * Perform a GET request and parse the response and return a simple string of the content
 *
 * @param path path to request, can be relative or absolute
 * @return the entity text/* w  w w  .  j a  v a2  s  .  c o  m*/
 * @throws IOException, HttpResponseException
 */
public String get(String path, String contentType) throws IOException {
    HttpGet getMethod = new HttpGet(api(path));
    HttpResponse response = client.execute(getMethod, localContext);
    try {
        httpResponseValidator.validateResponse(response);
        Scanner s = new Scanner(response.getEntity().getContent());
        s.useDelimiter("\\z");
        StringBuffer sb = new StringBuffer();
        while (s.hasNext()) {
            sb.append(s.next());
        }
        return sb.toString();
    } finally {
        releaseConnection(getMethod);
    }
}

From source file:org.galicaster.dashboard.snapshot.GstreamerSnapshotTaker.java

@Override
public File call() {

    // Marks the file to be deleted on exist, if an error occurred
    boolean deleteOnExit = true;

    ProcessBuilder pb = new ProcessBuilder(splitCommandArguments(String.format(pipeStr, EXEC_NAME,
            agent.getUrl(), password, rfbVersion, destFile.getAbsolutePath())));

    Scanner s = null;
    try {/*  ww w.j a v  a2 s .c o  m*/
        p = pb.start();

        if (p.waitFor() != 0) {
            s = new Scanner(p.getErrorStream()).useDelimiter("\\A");
            String error = s.hasNext() ? s.next() : "";

            error = String.format("The subprocess returned error code %s: %s", p.exitValue(), error);
            logger.error(error);
            throw new RuntimeException(error);
        }

        if (!destFile.isFile())
            throw new RuntimeException("The subprocess did not create a file");

        deleteOnExit = false;

        return destFile;

    } catch (IOException e) {
        logger.error("Error when initiating the helper subprocess: {}", e.getMessage());
        throw new RuntimeException("Error when initiating the helper subprocess.", e);
    } catch (InterruptedException e) {
        logger.error("The subprocess was unexpectedly interrupted: {}", e.getMessage());
        throw new RuntimeException("The subprocess was unexpectedly interrupted.", e);
    } finally {
        if (s != null)
            s.close();
        if (deleteOnExit)
            FileUtils.deleteQuietly(destFile);
    }

}

From source file:org.broadleafcommerce.vendor.amazon.s3.S3FileServiceProviderTest.java

protected boolean checkTestFileExists(String filename) {
    boolean ok = false;
    try {/*  ww w . ja  v  a  2 s .c o  m*/
        File f = s3FileProvider.getResource(filename);
        if (f.exists()) {
            Scanner fileScanner = new Scanner(f);
            fileScanner.useDelimiter("\\Z");
            String content = fileScanner.next();
            int contentLength = content.length();
            if (contentLength > 10) {
                System.out.println("Returned file contents: " + content);
                ok = TEST_FILE_CONTENTS.equals(content);
            }
            fileScanner.close();
        }
    } catch (Exception e) {
        ok = false;
    }
    return ok;
}

From source file:phonegraph.PhoneGraph.java

public void CreatedphoneOnly(String filename) {
    try {/*from w ww  . j  av  a 2 s.co m*/
        phonemaps = new HashMap<String, Integer>(400000);
        FileReader fileReader = new FileReader(filename);
        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        String line;
        int count = 0;
        bufferedReader.readLine();
        while ((line = bufferedReader.readLine()) != null) {
            Scanner sc = new Scanner(line);
            sc.useDelimiter("\t");
            Integer id = sc.nextInt();
            String phone = sc.next();
            phonemaps.put(phone, id);
            count++;
            //                if(count%100==0){
            //                    System.out.println(count);
            //                }
        }
        bufferedReader.close();
    } catch (IOException ex) {
        Logger.getLogger(PhoneGraph.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.chromium.ChromeI18n.java

private JSONObject getAssetContents(String assetName) throws IOException, JSONException {
    Context context = this.cordova.getActivity();
    InputStream is = context.getAssets().open(assetName);
    //Small trick to get the scanner to pull the entire input stream in one go
    Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String contents = s.hasNext() ? s.next() : "";
    return new JSONObject(contents);
}