Getting Started with the Metadata API

To get started with the Metadata API, follow these steps:

1. In the App Setup area, click Develop, API.

2. Right-click the Download Metadata WSDL link and save it on your local file system. You’ll need this plus the Enterprise WSDL in order to call the Metadata API.

3. Generate stub code from the WSDL (for example, by using WSC as described in Chapter 10) and add it to your project.

Listing 11.18 demonstrates usage of the Metadata API in Java by creating a new database object given a name and its plural name. The code assumes the existence of a member variable called sessionId, previously populated from the login call’s LoginResult. It prepares the minimum set of metadata required to call the create service, which is a custom object name, full name, label, deployment status, sharing model, and name field. After invoking the asynchronous create service, it loops to check the status using the checkStatus service until the invocation is complete.

Listing 11.18 Java Fragment for Creating Object


public void createObject(String name, String pluralName) {
  try {
    ConnectorConfig config = new ConnectorConfig();
    config.setUsername(user);
    config.setPassword(pass);
    com.sforce.soap.enterprise.Connector.newConnection(config);
    config.setServiceEndpoint(Connector.END_POINT);
    MetadataConnection connection = new MetadataConnection(config);
    CustomObject obj = new CustomObject();
    obj.setFullName(name + "__c");
    obj.setLabel(name);
    obj.setPluralLabel(pluralName);
    obj.setDeploymentStatus(DeploymentStatus.Deployed);
    obj.setSharingModel(SharingModel.ReadWrite);
    CustomField nameField = new CustomField();
    nameField.setType(FieldType.AutoNumber);
    nameField.setLabel("Name");
    obj.setNameField(nameField);
    AsyncResult[] result = connection.create(
      new Metadata[] { obj });
    if (result == null) {
      System.out.println("create failed");
      return;
    }
    boolean done = false;
    AsyncResult[] status = null;
    long waitTime = 1000;
    while (!done) {
      status = connection.checkStatus(
        new String[] { result[0].getId() });
      if (status != null) {
        done = status[0].isDone();
        if (status[0].getStatusCode() != null) {
          System.out.println("Error: " +
            status[0].getStatusCode() + ": " +
            status[0].getMessage());
        }
        Thread.sleep(waitTime);
        waitTime *= 2;
        System.out.println("Current state: " +
          status[0].getState());
      }
    }
    System.out.println("Created object: " +
      status[0].getId());
  } catch (Throwable t) {
    t.printStackTrace();
  }
}


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.73.142