Example usage for org.springframework.data.util CloseableIterator CloseableIterator

List of usage examples for org.springframework.data.util CloseableIterator CloseableIterator

Introduction

In this page you can find the example usage for org.springframework.data.util CloseableIterator CloseableIterator.

Prototype

CloseableIterator

Source Link

Usage

From source file:com.ethlo.geodata.importer.GeonamesImporter.java

@Override
public CloseableIterator<Map<String, String>> iterator() throws IOException {
    final Map<Long, Long> childToParentMap = new HashMap<>();
    final Set<Long> inHierarchy = new TreeSet<>();
    new HierarchyImporter(hierarchyFile).processFile(h -> {
        childToParentMap.put(Long.parseLong(h.get("child_id")), Long.parseLong(h.get("parent_id")));
        inHierarchy.add(Long.parseLong(h.get("child_id")));
        inHierarchy.add(Long.parseLong(h.get("parent_id")));
    });//from  w  w  w  .j a  v  a 2  s .c  om

    // Load alternate names
    final Map<Long, String> preferredNames = loadPreferredNames("EN");

    final BufferedReader reader = IoUtils.getBufferedReader(allCountriesFile);

    final AbstractIterator<Map<String, String>> actual = new AbstractIterator<Map<String, String>>() {
        @Override
        protected Map<String, String> computeNext() {
            try {
                String line;
                while ((line = reader.readLine()) != null) {
                    final Map<String, String> map = lineToMap(line, preferredNames, childToParentMap,
                            inHierarchy);
                    if (map != null) {
                        return map;
                    }
                }
                return endOfData();
            } catch (IOException exc) {
                throw new DataAccessResourceFailureException("Cannot read line from file", exc);
            }
        }
    };

    return new CloseableIterator<Map<String, String>>() {
        @Override
        public boolean hasNext() {
            return actual.hasNext();
        }

        @Override
        public Map<String, String> next() {
            return actual.next();
        }

        @Override
        public void close() {
            IOUtils.closeQuietly(reader);
        }
    };
}