(Return to main article: Samples for Java (REST) v1)
1. Specify service URL:
private static final String serviceURL = "http://URCHINHOST:URCHINPORT/services/v1/adminservice/";
2. Provide login information:
private static final String login = "URCHIN_LOGIN"; private static final String password = "URCHIN_PASSWORD";
3. Compose the REST URL:
URL service = new URL(serviceURL + "profiles/" + "?login=" + login + "&password=" + password);
4. Create the buffering character-input stream for retrieving the account list:
BufferedReader in = new BufferedReader(new InputStreamReader(service.openStream()));
5. Define namespace context implementation for data parsing:
class UrchinNamespaceContext implements NamespaceContext { public String getNamespaceURI(String prefix) { if (prefix == null) throw new NullPointerException("Null prefix"); if (prefix.equals("tns")) return "https://urchin.com/api/urchin/v1/"; else if ("xml".equals(prefix)) return XMLConstants.XML_NS_URI; return XMLConstants.NULL_NS_URI; } public String getPrefix(String namespaceURI) { throw new UnsupportedOperationException(); } public Iterator getPrefixes(String namespaceURI) { throw new UnsupportedOperationException(); } }
6. Execute the request:
XPathFactory fact = XPathFactory.newInstance(); XPath xp = fact.newXPath(); InputSource is = new InputSource(in); // set namespace context xp.setNamespaceContext(new UrchinNamespaceContext()); // retrieve list of accounts NodeList profiles = (NodeList)xp.evaluate("/tns:getProfileListResponse/profile", is, XPathConstants.NODESET);
7. Display the response:
System.out.println("adminservice/profiles/"); for(int i = 0; i < profiles.getLength(); i++){ System.out.print("profile id: \"" + xp.evaluate("profileId/text()", profiles.item(i)) + "\", "); System.out.print("profile name: \"" + xp.evaluate("profileName/text()", profiles.item(i)) + "\", "); System.out.print("account id: \"" + xp.evaluate("accountId/text()", profiles.item(i)) + "\", "); System.out.println("account name: \"" + xp.evaluate("accountName/text()", profiles.item(i)) + "\""); } in.close(); }
Complete sample code for this example can be found in the AdminService.java file.
(Return to main article: Samples for Java (REST) v1)