CreateApplicationAndPackageKeysForDeveloper
The below sample uses the Jackson JSON parser from FasterXML, LLC. The required jar files can be found at:
- jackson-core-2.0.4.jar
- jackson-annotations-2.0.4.jar
- jackson-databind-2.0.4.jar
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class CreateApplicationAndPackageKeysForDeveloper {
/**
* @param args
*/
public static void main(String[] args) {
// TODO: Need to enter a developer's username.
String developerUsername = "<enter a developer's username here>";
try {
// First create the application; you'll need the generated application id in order to add package keys to the application.
// Also note the "is_packaged" attribute, set to true. If set to false, then it is considered to be a "legacy" application, i.e.
// utilizing Service Keys as opposed to Package Keys.
String jsonString = "{\"method\":\"application.create\",\"id\":1,\"params\":[{\"name\":\"Application for "+ developerUsername +"\",\"is_packaged\":true,\"member\":{\"username\":\""+developerUsername+"\"}}]}";
String jsonResponse = callMasheryAPI(jsonString);
String applicationId = getApplicationIdFromJson(jsonResponse);
// This is just a query to get at package and plan data. The key is to get the package id and plan ids, both of which are required for the package_key.create method.
jsonString = "{\"method\":\"object.query\",\"id\":1,\"params\":[\"SELECT id, plans.id FROM packages\"]}";
jsonResponse = callMasheryAPI(jsonString);
HashMap<String, String> packages = getPackagesFromJson(jsonResponse); // This is where I'll go and get the package and plan ids from the returned JSON response.
for (Map.Entry<String,String> entry : packages.entrySet()) {
String packageId = entry.getKey();
String planId = entry.getValue();
// Create the package key for the specified application, package an plan.
jsonString = "{\"method\":\"package_key.create\",\"id\":1,\"params\":[{\"application\":{\"id\":"+applicationId+"},\"package\":{\"id\":"+packageId+"},\"plan\":{\"id\":"+planId+"}}]}";
jsonResponse = callMasheryAPI(jsonString);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static HashMap<String, String> getPackagesFromJson(String jsonResponse) throws Exception {
HashMap<String, String> packages = new HashMap<String, String> ();
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jsonResponse, JsonNode.class);
JsonNode itemsNodes = rootNode.path("result").path("items");
for (JsonNode node : itemsNodes) {
String packageId = node.path("id").toString();
JsonNode planNode = node.path("plans").get(0);
String planId = planNode.path("id").toString();
packages.put(packageId, planId);
}
return packages;
}
private static String getApplicationIdFromJson(String jsonResponse) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jsonResponse, JsonNode.class);
return rootNode.path("result").path("id").toString();
}
private static int getResultTotalPages(String jsonResponse) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jsonResponse, JsonNode.class);
JsonNode totalNode = rootNode.path("result").path("total_pages");
return Integer.parseInt(totalNode.toString());
}
private static String callMasheryAPI(String jsonString) throws Exception
{
long epoch = System.currentTimeMillis()/1000;
String timestamp = Long.toString(epoch);
String sig = MD5(masheryV2ApiKey + masheryV2ApiSecret + timestamp);
String urlStr = "http://api.mashery.com/v2/json-rpc";
String urlParams ="apikey=" + masheryV2ApiKey + "&sig=" + sig;
urlStr = urlStr + "/" + siteIdFromDashboard +"?" + urlParams;
URL url = new URL(urlStr);
URLConnection connection = url.openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setDoInput(true);
connection.setReadTimeout(0);
connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
connection.setRequestProperty("Content-Type", "application/json");
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(jsonString);
wr.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer buf = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
buf.append(inputLine);
}
wr.close();
in.close();
return buf.toString();
}
private static String callMasheryReportingAPI(String reportingMethod, String reportingParams) throws Exception
{
long epoch = System.currentTimeMillis()/1000;
String timestamp = Long.toString(epoch);
String sig = MD5(masheryV2ApiKey + masheryV2ApiSecret + timestamp);
String urlStr = "http://api.mashery.com/v2/rest";
String urlParams ="apikey=" + masheryV2ApiKey + "&sig=" + sig;
urlStr = urlStr + "/" + siteIdFromDashboard + "/" + reportingMethod +"?" + reportingParams + "&" + urlParams;
URL url = new URL(urlStr);
URLConnection connection = url.openConnection();
connection.setDoInput(true);
connection.setReadTimeout(0);
connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
connection.setRequestProperty("Content-Type", "application/json");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer buf = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
buf.append(inputLine);
buf.append("\n");
}
in.close();
return buf.toString();
}
private static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while(two_halfs++ < 1);
}
return buf.toString();
}
private static String MD5(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md;
md = MessageDigest.getInstance("MD5");
byte[] md5hash = new byte[32];
md.update(text.getBytes("iso-8859-1"), 0, text.length());
md5hash = md.digest();
return convertToHex(md5hash);
}
}
Docs Navigation
- API Documentation Portal
- IO Docs Definition
- Mashery API Documentation
- Mashery 3.0 API Guide
- Mashery 2.0 API Guide
- OAuth Supporting Methods
- Examples
- JSON RPC
- Authentication
- API Objects
- Fetching Objects
- Query Language
- Creating Objects
- Updating Objects
- Validating Fields
- Deleting Objects
- Applications
- General Object Methods
- Members
- Packages
- Plans
- Package Keys
- Keys
- Developer Classes
- Services
- Roles
- Mashery 2.0 Reporting API Guide
- Event Trigger API
- Differences between Roles and Portal Access Groups
- Managing a Portal Access Group Using Mashery V2 or V3 API
- Mashery Reporting Event Post API Guide
- Tips and Tricks
- Your Portal
- API Traffic Manager
- I/O Docs WSDL requirements