Skip to content

Instantly share code, notes, and snippets.

@dradtke
Created November 22, 2013 16:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dradtke/7602458 to your computer and use it in GitHub Desktop.
Save dradtke/7602458 to your computer and use it in GitHub Desktop.
import com.sforce.ws.ConnectorConfig;
import com.sforce.ws.ConnectionException;
import com.sforce.soap.tooling.SoapConnection;
import com.sforce.soap.tooling.ExecuteAnonymousResult;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.LoginResult;
import com.sforce.soap.tooling.LogInfo;
import com.sforce.soap.tooling.LogCategoryLevel;
import com.sforce.soap.tooling.LogCategory;
import com.sforce.soap.tooling.LogType;
public class ExecuteAnonymous {
final static String API_VERSION = "29.0";
final static String API_URL = "https://login.salesforce.com/services/Soap/c/" + API_VERSION;
public static void main(String[] args) throws ConnectionException {
SoapConnection conn = toolingLogin("<username>", "<password>");
LogInfo infoAll = new LogInfo();
infoAll.setCategory(LogCategory.Apex_code);
infoAll.setLevel(LogCategoryLevel.Finest);
conn.setDebuggingHeader(new LogInfo[] { infoAll }, LogType.Detail);
ExecuteAnonymousResult result = conn.executeAnonymous("System.debug('hello world');");
if (!result.getCompiled()) {
System.err.println("Anonymous block failed to compile: " + result.getCompileProblem());
System.err.println("At line " + result.getLine() + ", column " + result.getColumn() + ".");
System.exit(1);
}
else if (!result.getSuccess()) {
System.err.println(result.getExceptionMessage());
System.err.println(result.getExceptionStackTrace());
System.exit(1);
}
else {
System.out.println(conn.getDebuggingInfo());
}
}
private static ConnectorConfig newConfig() {
final ConnectorConfig config = new ConnectorConfig();
config.setAuthEndpoint(API_URL);
config.setServiceEndpoint(API_URL);
config.setManualLogin(true);
return config;
}
public static SoapConnection toolingLogin(String username, String password) throws ConnectionException {
ConnectorConfig config = newConfig();
EnterpriseConnection enterprise = new EnterpriseConnection(config);
LoginResult lr = enterprise.login(username, password);
config.setServiceEndpoint(lr.getServerUrl().replace("/c/", "/T/"));
config.setSessionId(lr.getSessionId());
SoapConnection conn = new SoapConnection(config);
return new SoapConnection(config);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment