Skip to content

Instantly share code, notes, and snippets.

@alan-morey
Created November 24, 2012 01:29
Show Gist options
  • Save alan-morey/4137976 to your computer and use it in GitHub Desktop.
Save alan-morey/4137976 to your computer and use it in GitHub Desktop.
Simple wrapper for querying Salesforce using PartnerConnection in Groovy. Dependencies are pulled in from maven repository via Grape.
@Grab(group='com.force.sdk', module='force-connector', version='22.0.9-BETA')
import com.force.sdk.connector.ForceConnectorConfig
import com.force.sdk.connector.ForceServiceConnector
import com.sforce.soap.partner.PartnerConnection
import com.sforce.soap.metadata.FileProperties
import com.sforce.soap.metadata.ListMetadataQuery
import java.net.URLEncoder
class ForceService {
def forceServiceConnector
ForceService(serverUrl, username, password) {
def config = new ForceConnectorConfig()
config.connectionUrl = buildConnectionUrl serverUrl, username, password
forceServiceConnector = new ForceServiceConnector(config)
}
def getConnection() {
forceServiceConnector.connection
}
def getMetadataConnection() {
forceServiceConnector.metadataConnection
}
def getSessionId() {
forceServiceConnector.connection.sessionId
}
def query(soql) {
def result = []
def queryResult = connection.query soql
if (queryResult.size > 0) {
for (;;) {
queryResult.records.each { result << it }
if (queryResult.isDone()) {
break;
}
queryResult = connection.queryMore queryResult.queryLocator
}
}
result
}
def listMetadata(String type) {
listMetadata(type, null)
}
def listMetadata(String type, String folder) {
def query = new ListMetadataQuery()
query.type = type
query.folder = folder
listMetadata([query])
}
def listMetadata(List<ListMetadataQuery> queries) {
final MAX_QUERIES_PER_REQUEST = 3
def numQueries = queries.size
def isLastQuery = false
def index = 0
def fileProperties = []
while (numQueries > 0 && !isLastQuery) {
def start = index * MAX_QUERIES_PER_REQUEST
def end = start + MAX_QUERIES_PER_REQUEST
if (end > numQueries) {
end = numQueries
}
def requestQueries = queries.subList(start, end) as ListMetadataQuery[]
def result = metadataConnection.listMetadata(requestQueries, 26.0)
if (result != null) {
fileProperties.addAll(result.toList())
}
isLastQuery = (numQueries - (++index * MAX_QUERIES_PER_REQUEST)) < 1
}
fileProperties
}
private buildConnectionUrl = { serverUrl, username, password ->
def encode = { URLEncoder.encode(it, 'UTF-8') }
def host = new URI(serverUrl).host;
def query = [
user: username,
password: password
].collect { k, v -> "${encode k}=${encode v}" }.join('&')
"force://$host?$query"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment