import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.io.InputStream;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.xpath.*;

public class SpockApiExample {
   public static void main(String[] args) throws MalformedURLException, ParserConfigurationException, SAXException, IOException, XPathExpressionException
   {
      // change the key and parameters following our documentation - http://www.spock.com/api
      URL url = new URL("http://www.spock.com/api/2/search.xml?api_key=115c5ab1fb7dec3a8ce457fee8e6f0eb&query=spock-team&show_blurb=1&sig=3462c6f4692d6977bd8f734c6584b42b");
      HttpURLConnection connection = (HttpURLConnection)url.openConnection();
      connection.setRequestProperty("User-Agent", "Spock API Java Sample Client");
      InputStream inputStream = connection.getInputStream();

      DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
      domFactory.setNamespaceAware(true);
      DocumentBuilder docBuilder = domFactory.newDocumentBuilder();
      Document doc = docBuilder.parse(inputStream);

      XPathFactory factory = XPathFactory.newInstance();
      XPath xpathIds = factory.newXPath();
      XPathExpression expression = xpathIds.compile("//response/search_results/person");
      NodeList nodeList = (NodeList) expression.evaluate(doc, XPathConstants.NODESET);

      for (int i = 0; i < nodeList.getLength(); ++i) {
         Node node = nodeList.item(i);
	 String blurb = "";
	 for (int j = 0; j < node.getChildNodes().getLength(); ++j) {
            Node childNode = node.getChildNodes().item(j);
	    if (childNode.getNodeName() == "blurb") {
	       Node blurbTextNode = childNode.getFirstChild();
	       blurb = blurbTextNode == null ? "" : blurbTextNode.getNodeValue();
	       break;
	    }
	 }
         System.out.println(node.getAttributes().getNamedItem("id").getNodeValue() + ": " + blurb); 
      }
   }
}
