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:org.scigap.iucig.controller.ScienceDisciplineController.java

private String convertStreamToString(InputStream is) {
    Scanner s = new Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

From source file:com.planetmayo.debrief.satc.util.StraightLineCullingTestForm.java

private void loadFile(File file) throws IOException {
    Scanner scanner = new Scanner(file);
    scanner.useLocale(Locale.US);
    List<List<Coordinate>> coordinates = new ArrayList<List<Coordinate>>();
    while (true) {
        try {//w ww. j  ava 2 s  . c om
            int num = scanner.nextInt();
            scanner.next();
            double x = scanner.nextDouble();
            double y = scanner.nextDouble();

            if (num > 0) {
                num--;
                while (coordinates.size() <= num) {
                    coordinates.add(new ArrayList<Coordinate>());
                }
                Coordinate coordinate = new Coordinate(x, y);
                coordinates.get(num).add(coordinate);
            }
        } catch (NoSuchElementException ex) {
            break;
        }
    }
    for (int i = 0; i < coordinates.size(); i++) {
        Coordinate c = coordinates.get(i).get(0);
        coordinates.get(i).add(c);
    }
    culling(coordinates);
}

From source file:com.bt.heliniumstudentapp.UpdateClass.java

@Override
protected String doInBackground(Void... Void) {
    try {/*w w w. j ava2 s. co m*/
        URLConnection connection = new URL(HeliniumStudentApp.URL_UPDATE_CHANGELOG).openConnection();

        connection.setConnectTimeout(HeliniumStudentApp.TIMEOUT_CONNECT);
        connection.setReadTimeout(HeliniumStudentApp.TIMEOUT_READ);

        connection.setRequestProperty("Accept-Charset", HeliniumStudentApp.CHARSET);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded;charset=" + HeliniumStudentApp.CHARSET);

        connection.connect();

        final Scanner line = new Scanner(connection.getInputStream()).useDelimiter("\\A");
        final String html = line.hasNext() ? line.next() : "";

        ((HttpURLConnection) connection).disconnect();

        if (((HttpURLConnection) connection).getResponseCode() == 200)
            return html;
        else
            return null;
    } catch (IOException e) {
        return null;
    }
}

From source file:com.sonicle.webtop.core.versioning.SqlUpgradeScript.java

private void readFile(InputStreamReader readable, boolean flatNewLines) throws IOException {
    this.statements = new ArrayList<>();
    StringBuilder sb = null, sbsql = null;
    String lines[] = null;// w  w  w. j a va 2  s .  com

    Scanner s = new Scanner(readable);
    s.useDelimiter("(;( )?(\r)?\n)");
    //s.useDelimiter("(;( )?(\r)?\n)|(--\n)");
    while (s.hasNext()) {
        String block = s.next();
        block = StringUtils.replace(block, "\r", "");
        if (!StringUtils.isEmpty(block)) {
            // Remove remaining ; at the end of the block (only if this block is the last one)
            if (!s.hasNext() && StringUtils.endsWith(block, ";"))
                block = StringUtils.left(block, block.length() - 1);

            sb = new StringBuilder();
            sbsql = new StringBuilder();
            lines = StringUtils.split(block, "\n");
            for (String line : lines) {
                if (AnnotationLine.matches(line)) {
                    if (DataSourceAnnotationLine.matches(line)) {
                        statements.add(new DataSourceAnnotationLine(line));
                    } else if (IgnoreErrorsAnnotationLine.matches(line)) {
                        statements.add(new IgnoreErrorsAnnotationLine(line));
                    } else if (RequireAdminAnnotationLine.matches(line)) {
                        statements.add(new RequireAdminAnnotationLine(line));
                    } else {
                        throw new IOException("Bad line: " + line);
                    }
                } else if (CommentLine.matches(line)) {
                    sb.append(line);
                    sb.append("\n");
                } else {
                    sbsql.append(StringUtils.trim(line));
                    sbsql.append(" ");
                    if (!flatNewLines)
                        sbsql.append("\n");
                }
            }
            if (sb.length() > 0)
                statements.add(new CommentLine(StringUtils.removeEnd(sb.toString(), "\n")));
            if (sbsql.length() > 0)
                statements.add(new SqlLine(StringUtils.removeEnd(sbsql.toString(), "\n")));
        }
    }
}

From source file:org.seedstack.w20.internal.MasterPageBuilder.java

public String build(HttpServletRequest httpServletRequest) {
    URL masterpageURL = SeedReflectionUtils.findMostCompleteClassLoader().getResource(masterpagePath);
    if (masterpageURL == null) {
        throw new RuntimeException("Unable to generate W20 masterpage, template not found");
    }/*from  w w w  . j  a  va 2s . c om*/

    Scanner scanner;
    try {
        scanner = new Scanner(masterpageURL.openStream()).useDelimiter("\\A");
    } catch (IOException e) {
        throw SeedException.wrap(e, W20ErrorCode.UNABLE_TO_GENERATE_MASTERPAGE);
    }
    String template = scanner.next();
    scanner.close();

    Map<String, Object> variables = new HashMap<String, Object>();
    String contextPath = httpServletRequest.getContextPath();
    variables.put("applicationTitle",
            StringUtils.isBlank(applicationTitle) ? application.getName() : applicationTitle);
    variables.put("applicationSubtitle", applicationSubtitle);
    variables.put("applicationVersion",
            StringUtils.isBlank(applicationVersion) ? application.getVersion() : applicationVersion);
    variables.put("timeout", timeout);
    variables.put("corsWithCredentials", corsWithCredentials);
    variables.put("basePath", PathUtils.removeTrailingSlash(getBasePath(contextPath)));
    variables.put("basePathSlash", PathUtils.ensureTrailingSlash(getBasePath(contextPath)));
    variables.put("restPath", PathUtils.removeTrailingSlash(getRestPath(contextPath)));
    variables.put("restPathSlash", PathUtils.ensureTrailingSlash(getRestPath(contextPath)));
    variables.put("componentsPath", PathUtils.removeTrailingSlash(getComponentsPath(contextPath)));
    variables.put("componentsPathSlash", PathUtils.ensureTrailingSlash(getComponentsPath(contextPath)));

    return replaceTokens(template, variables);

}

From source file:org.openiot.ide.core.MenuFactory.java

/**
 * Groups the navigation properties in a Linked Hashmap where Key = the navigation group name
 * e.g. Request Presentation Values = a Hashmap with the group fields e.g. Url, Title, Active
 * Monitoring/*ww  w .j  a  v a  2 s . c o m*/
 * 
 * @return
 */
private HashMap<String, HashMap<String, String>> createPropertyMap() {
    HashMap<String, HashMap<String, String>> itemMap = null;

    HashMap<String, String> navigationMap = resources.getNavigationMap();
    MultiValueMap groupMap = new MultiValueMap();

    for (String key : navigationMap.keySet()) {

        String newKey = key.split(IDE_CORE_GROUP)[1];

        Scanner sc = new Scanner(newKey).useDelimiter("\\.");
        String group = sc.next();
        groupMap.put(group, sc.next());

        sc.close();
    }

    itemMap = new LinkedHashMap<>();

    for (Object parentKey : groupMap.keySet()) {

        HashMap<String, String> childMap = new HashMap<>();

        for (Object childKey : groupMap.getCollection(parentKey)) {
            String fullKey = IDE_CORE_GROUP + parentKey + "." + childKey;
            childMap.put((String) childKey, navigationMap.get(fullKey));
        }

        itemMap.put((String) parentKey, childMap);
    }

    System.out.println("ItemMap size: " + itemMap.size());

    return itemMap;
}

From source file:org.couch4j.http.DatabaseChangeNotificationService.java

private void receiveChangeNotifications() {
    if (receivingChangeNotifications) {
        return;//from ww  w.java  2 s.c om
    }
    logger.info("[" + Thread.currentThread().getName() + "] Start receiveChangeNotifications()...");

    receivingChangeNotifications = true;
    executor = Executors.newSingleThreadExecutor();
    Runnable r = new Runnable() {
        private void streamChanges(int updateSeq) {
            if (!receivingChangeNotifications) {
                return;
            }
            // Do we need the "heartbeat" param?
            HttpGet method = new HttpGet(urlResolver.urlForPath("_changes", map("feed", "continuous", "style",
                    "all_docs", "since", String.valueOf(updateSeq), "heartbeat", "5000")));

            HttpResponse response = null;
            HttpEntity entity = null;
            try {
                // int statusCode = client.executeMethod(method);
                response = client.execute(method);
                entity = response.getEntity();
                // Read the response body.
                Reader in = new InputStreamReader(entity.getContent(), EntityUtils.getContentCharSet(entity));

                Scanner s = new Scanner(in).useDelimiter("\n");
                String line;
                while (s.hasNext() && null != (line = s.next())) {
                    // dispatch change event
                    if (line.length() > 1 && JSONUtils.mayBeJSON(line)) {
                        JSONObject json = JSONObject.fromObject(line);
                        if (json.has("seq")) {
                            if (logger.isLoggable(Level.FINE)) {
                                logger.fine("Dispatch new change event: " + line);
                            }
                            dispatchEvent(new DatabaseChangeEvent(json));
                        } else if (json.has("last_seq")) {
                            if (logger.isLoggable(Level.FINE)) {
                                logger.fine("CouchDB server closed _changes connection. Reconnecting...");
                            }
                            streamChanges(json.getInt("last_seq"));
                        }
                    }
                }
                if (logger.isLoggable(Level.FINE)) {
                    logger.fine("[" + Thread.currentThread().getName() + "] Stop receiving changes...");
                }
            } catch (IOException e) {
                throw new Couch4JException(e);
            } finally {
                if (null != entity) {
                    try {
                        entity.consumeContent();
                    } catch (IOException e) {
                        // swallow
                    }
                }
            }
        }

        public void run() {
            if (logger.isLoggable(Level.FINE)) {
                logger.fine("[" + Thread.currentThread().getName() + "] Start receiving changes... ");
            }
            // Start with current udpate seq
            int updateSeq = database.getDatabaseInfo().getUpdateSeq();
            streamChanges(updateSeq);
        }
    };
    executor.submit(r);
}

From source file:MediaLibrary.java

public MediaLibrary(String jsonFilename) {
    this.mediaFiles = new HashMap<String, MediaDescription>();
    count = 0;//  w w w .j av  a2 s . c om

    Scanner ifstr = null;

    try {
        ifstr = new Scanner(new FileInputStream(jsonFilename));

        StringBuilder sb = new StringBuilder();

        while (ifstr.hasNext()) {
            sb.append(ifstr.next());
        }

        JSONObject obj = new JSONObject(sb.toString());

        for (String title : JSONObject.getNames(obj)) {
            JSONObject tobj = new JSONObject(obj.get(title).toString());

            MediaDescription md = new MediaDescription(tobj);

            mediaFiles.put(md.getTitle(), md);
        }

    } catch (FileNotFoundException fnfe) {
        System.out.println("File not found");
        fnfe.printStackTrace();
    } finally {
        ifstr.close();
    }

}

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

public void load(DataResource data) throws ResourceInitializationException {
    InputStream inputStream = null;
    try {//www . j  a  va 2 s  .  co  m
        inputStream = data.getInputStream();
        Scanner scanner = null;
        try {
            String fixedExpression, line;
            String[] str;
            scanner = new Scanner(inputStream, "UTF-8");
            scanner.useDelimiter(TermSuiteConstants.LINE_BREAK);
            while (scanner.hasNext()) {
                line = scanner.next().split(TermSuiteConstants.DIESE)[0].trim();
                str = line.split(TermSuiteConstants.TAB);
                fixedExpression = str[0];

                fixedExpressionLemmas.add(fixedExpression);
            }
        } catch (Exception e) {
            throw new ResourceInitializationException(e);
        } finally {
            IOUtils.closeQuietly(scanner);
        }
    } catch (IOException e) {
        LOGGER.error("Could not load file {}", data.getUrl());
        throw new ResourceInitializationException(e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:eu.scape_project.archiventory.identifiers.UnixFileIdentification.java

@Override
public HashMap<String, List<String>> identifyFileList(DualHashBidiMap fileRecidBidiMap) throws IOException {
    HashMap<String, List<String>> resultMap = new HashMap<String, List<String>>();
    String ufidRes = this.identify(fileRecidBidiMap.values());
    Scanner s = new Scanner(ufidRes);
    // one file identification result per line
    s.useDelimiter("\n");
    while (s.hasNext()) {
        // output syntax of the unix-tool 'file' is ${fileName} : ${mimeType}
        StringTokenizer st = new StringTokenizer(s.next(), ":");
        String fileName = st.nextToken().trim();
        // output key
        String key = (String) fileRecidBidiMap.getKey(fileName);
        if (key != null) {
            String containerFileName = key.substring(0, key.indexOf("/"));
            String containerIdentifier = key.substring(key.indexOf("/") + 1);
            String outputKey = String.format(outputKeyFormat, containerFileName, containerIdentifier);
            // output value
            String property = "mime";
            String value = st.nextToken().trim();
            String outputValue = String.format(outputValueFormat, tool, property, value);
            List<String> valueLineList = new ArrayList<String>();
            valueLineList.add(outputValue);
            resultMap.put(outputKey, valueLineList);
        } else {//from w  w w .j a  v a 2s  .c  om
        }
    }
    return resultMap;
}