(Return to main article: Samples for Java (REST) v1)
1. Specify Service URL:
private static final String serviceURL = "http://server[:port]/services/v1/reportservice/tables/";
2. Provide login and account information:
private static final String login = "INSERT_LOGIN_HERE"; private static final String password = "INSERT_PASSWORD_HERE"; private static final int profileId = INSERT_PROFILE_ID_HERE;
3. Compose REST URL:
String url = serviceURL + "tables/?" +
"login=" + login + "&" +
"password=" + password + "&" +
"profileId=" + profileId;
URL service = new URL(url);
4. Create the buffering character-input stream for retrieving 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 request:
XPathFactory fact = XPathFactory.newInstance();
XPath xp = fact.newXPath();
InputSource is = new InputSource(in);
// set namespace context
xp.setNamespaceContext(new UrchinNamespaceContext());
// retrieve list of tables
NodeList tables = (NodeList)xp.evaluate("/tns:getTableListResponse/table", is, XPathConstants.NODESET);
7. Parse and display response:
System.out.println("reportservice/tables/");
System.out.println("url:" + url);
for(int i = 0; i < tables.getLength(); i++){
System.out.println("\ttable id: " + xp.evaluate("tableId/text()", tables.item(i)));
// retrieve dimensions
NodeList dimensions = (NodeList)xp.evaluate("dimensions/dimension/text()", tables.item(i), XPathConstants.NODESET);
for(int j = 0; j < dimensions.getLength(); j++){
System.out.println("\tdimension: " + dimensions.item(j).getNodeValue());
}
// retrieve list of metrics
NodeList metrics = (NodeList)xp.evaluate("metrics/metric/text()", tables.item(i), XPathConstants.NODESET);
for(int j = 0; j < metrics.getLength(); j++){
System.out.println("\tmetric: " + metrics.item(j).getNodeValue());
}
}
in.close();
Complete sample code for this example can be found in the ReportService.java file.
(Return to main article: Samples for Java (REST) v1)