package com.corejava.structureddata;

import java.util.HashMap;
import java.util.Map.Entry;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class WikipediaContributorsSAXParser {
	static HashMap<String, Integer> map = new HashMap<String, Integer>();

	public static void main(String argv[]) {

		try {

			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser saxParser = factory.newSAXParser();

			DefaultHandler handler = new DefaultHandler() {
				boolean username = false;

				public void startElement(String uri, String localName,
						String qName, Attributes attributes)
						throws SAXException {
					if (qName.equalsIgnoreCase("username")) {
						username = true;
					}
				}

				public void characters(char ch[], int start, int length)
						throws SAXException {

					if (username) {
						String name = new String(ch, start, length);
						if (map.keySet().contains(name)) {
							map.put(name, (Integer) map.get(name) + 1);
						} else {
							map.put(name, 1);
						}
						username = false;
					}
				}
			};

			saxParser.parse(
					"metawiki-latest-stub-articles.xml",
					handler);
			Entry<String, Integer> maxEntry = null;

			for (Entry<String, Integer> entry : map.entrySet()) {
				if (maxEntry == null || entry.getValue() > maxEntry.getValue()) {
					maxEntry = entry;
				}
			}
			System.out.println(maxEntry.toString()); // FuzzyBot=52422
			System.out.println(maxEntry.getValue().toString()); // 52422

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}