Using MetadataContainer with ApexClassMember, ApexTrigger Member etc.

I come to know that to update Apex component it is required to use Metdatacontainer object with ApexClassMember/ApexTrigger member. In Force.com Tooling API Dev guide given all examples to use Metadatacontainer and updating ApexClassMember and other members, but there all given examples uses SOAP API. In REST API only syntax and hints are provided for creating, deleting, describe but no implementation. I am able create a Metadatcontainer object and receive its id as response and by same way ApexClassMember, but don’t know how to use it with Metadatacontainer.

My Question is how to include and work with ApexClassMember with Metadatcontainer or associating ApexClassMember/ApexTriggerMember with a Metadacontainer object using REST API?

Answer

If your using Java, there are two blogs you can refer to and reference code which creates an ApexClassMember and set its MetadataContainerId property via the REST API.

Here is a code sample from first…

//First, the MetadataContainer
JSONObject metadataContainerRequest = new JSONObject();
metadataContainerRequest.put("Name", "SaveClass" + id); // Any unique name
JSONObject metadataContainerResponse = ToolingApi.post(
        "sobjects/MetadataContainer", metadataContainerRequest);
System.out.println("MetadataContainer id: "
        + metadataContainerResponse.get("id"));

// Then an ApexClassMember with our updated code
JSONObject apexClassMemberRequest = new JSONObject();
apexClassMemberRequest.put("MetadataContainerId",
        metadataContainerResponse.get("id"));
apexClassMemberRequest.put("ContentEntityId", id);
apexClassMemberRequest.put("Body", body);
JSONObject apexClassMemberResponse = ToolingApi.post(
        "sobjects/ApexClassMember", apexClassMemberRequest);
System.out.println("ApexClassMember id: "
        + apexClassMemberResponse.get("id"));

Or using POJO’s (serialised to JSON) instead of the JSONObject class from the second…

MetadataContainer container = new MetadataContainer();
container.setName("UnusedApexMethods");
List saveResults = port.create(new ArrayList(Arrays.asList(container)), sessionHeader);
String containerId = saveResults.get(0).getId();

ApexClassMember apexClassMember = new ApexClassMember();
apexClassMember.setBody(apexClass.getBody());
apexClassMember.setContentEntityId(apexClass.getId());
apexClassMember.setMetadataContainerId(containerId);
apexClassMembers.add(apexClassMember);

Attribution
Source : Link , Question Author : Ashwani , Answer Author : Andrew Fawcett

Leave a Comment