com.sforce.ws.ConnectionException Java Examples

The following examples show how to use com.sforce.ws.ConnectionException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SalesforceRuntimeTestUtil.java    From components with Apache License 2.0 6 votes vote down vote up
private void login(String endpoint) throws ConnectionException {
    ConnectorConfig config = new ConnectorConfig();

    config.setAuthEndpoint(endpoint);
    config.setUsername(username);
    config.setPassword(password + securityKey);
    config.setConnectionTimeout(60000);
    config.setUseChunkedPost(true);

    partnerConnection = new PartnerConnection(config);
}
 
Example #2
Source File: SalesforceRuntimeTestUtil.java    From components with Apache License 2.0 6 votes vote down vote up
public void deleteTestData(List<String> ids) throws ConnectionException {
    this.login(SalesforceConnectionProperties.URL);

    try {
        DeleteResult[] results = partnerConnection.delete(ids.toArray(new String[0]));

        for (DeleteResult result : results) {
            if (result.isSuccess()) {

            } else {
                for (int i = 0; i < result.getErrors().length; i++) {
                    com.sforce.soap.partner.Error err = result.getErrors()[i];
                    Assert.fail(err.getMessage());
                }
            }
        }
    } catch (ConnectionException ce) {
        Assert.fail(ce.getMessage());
    }
}
 
Example #3
Source File: SalesforceGetDeletedUpdatedReaderTestIT.java    From components with Apache License 2.0 6 votes vote down vote up
/**
 * For tSalesforceGetDeleted generate SOQL
 */
@Test
public void testGetQueryStringList() throws Throwable {
    SalesforceGetDeletedReader deletedReader =
            new SalesforceGetDeletedReader(null, null, createSalesforceGetDeletedUpdatedProperties(false)) {

                @Override
                protected GetDeletedResult getResult() throws IOException, ConnectionException {
                    GetDeletedResult result = new GetDeletedResult();
                    List<DeletedRecord> records = new ArrayList<>();
                    for (int i = 1000; i < 1999; i++) {
                        DeletedRecord record = new DeletedRecord();
                        record.setId("0019000001fvZV" + i);
                        records.add(record);
                    }
                    result.setDeletedRecords(records.toArray(new DeletedRecord[records.size()]));
                    return result;
                }
            };
    List<String> queryStrings = deletedReader.getQueryStringList(deletedReader.getResult());
    for (String query : queryStrings) {
        assertTrue(query.length() > 0);
        assertTrue(query.length() < deletedReader.soqlCharacterLimit);
    }
    assertEquals(3, queryStrings.size());
}
 
Example #4
Source File: SalesforceSourceOrSinkTestIT.java    From components with Apache License 2.0 6 votes vote down vote up
@Test(expected = ConnectionException.class)
public void testSalesForcePasswordExpired() throws ConnectionException {
    SalesforceSourceOrSink salesforceSourceOrSink = new SalesforceSourceOrSink();
    TSalesforceInputProperties properties = (TSalesforceInputProperties) new TSalesforceInputProperties(null).init();
    salesforceSourceOrSink.initialize(null, properties);

    ConnectorConfig config = new ConnectorConfig();
    config.setUsername(StringUtils.strip(USER_ID_EXPIRED, "\""));
    String password = StringUtils.strip(PASSWORD_EXPIRED, "\"");
    String securityKey = StringUtils.strip(SECURITY_KEY_EXPIRED, "\"");
    if (StringUtils.isNotEmpty(securityKey)) {
        password = password + securityKey;
    }
    config.setPassword(password);

    PartnerConnection connection = null;
    try {
        connection = salesforceSourceOrSink.doConnection(config, true);
    } catch (LoginFault ex) {
        Assert.fail("Must be an exception related to expired password, not the Login Fault.");
    } finally {
        if (null != connection) {
            connection.logout();
        }
    }
}
 
Example #5
Source File: SalesforceGetDeletedReader.java    From components with Apache License 2.0 6 votes vote down vote up
@Override
public boolean start() throws IOException {
    try {
        result = getResult();
        queryStringList = getQueryStringList(result);
        if (queryStringList.size() == 0) {
            return false;
        }
        inputResult = getConnection().queryAll(queryStringList.get(queryIndex++));
        inputRecords = inputResult.getRecords();
        while (!inputResult.isDone()) {
            inputResult = getConnection().queryMore(inputResult.getQueryLocator());
            inputRecords = ArrayUtils.addAll(inputRecords, inputResult.getRecords());
        }
        inputRecordsIndex = 0;
    } catch (ConnectionException e) {
        throw new IOException(e);
    }
    boolean startable = inputRecords.length > 0;
    if (startable) {
        dataCount++;
    }
    return startable;
}
 
Example #6
Source File: SalesforceConnectionImpl.java    From teiid-spring-boot with Apache License 2.0 6 votes vote down vote up
@Override
protected SalesforceConnectorConfig createConnectorConfig(SalesforceConfiguration sfc)
        throws ConnectionException {
    SalesforceConnectorConfig config = new SalesforceConnectorConfig();
    config.setCompression(true);
    config.setTraceMessage(false);
    config.setUsername(sfc.getUsername());
    config.setPassword(sfc.getPassword());
    config.setAuthEndpoint(sfc.getUrl());
    config.setRestTemplate(sfc.getRestTemplate());
    config.setOAuth2Template(sfc.getOAuth2Template());
    config.setRefreshToken(sfc.getRefreshToken());

    if (sfc.getConnectTimeout() != null) {
        config.setConnectionTimeout((int)Math.min(Integer.MAX_VALUE, sfc.getConnectTimeout()));
    }

    if (sfc.getRequestTimeout() != null) {
        config.setReadTimeout((int)Math.min(Integer.MAX_VALUE, sfc.getRequestTimeout()));
    }
    return config;
}
 
Example #7
Source File: SalesforceBulkQueryInputReader.java    From components with Apache License 2.0 6 votes vote down vote up
@Override
public boolean start() throws IOException {
    if (bulkRuntime == null) {
        bulkRuntime = new SalesforceBulkRuntime(((SalesforceSource) getCurrentSource()).connect(container).bulkConnection);
        if (((TSalesforceInputProperties) properties).pkChunking.getValue()) {
            bulkRuntime.setChunkProperties((TSalesforceInputProperties) properties);
        }
        bulkRuntime.setSafetySwitch(((TSalesforceInputProperties) properties).safetySwitch.getValue());
        bulkRuntime.setJobTimeout((TSalesforceInputProperties) properties);
    }
    try {
        executeSalesforceBulkQuery();
    } catch (ConnectionException e) {
        // Wrap the exception in an IOException.
        throw new IOException(e);
    }

    return retrieveNextResultSet();
}
 
Example #8
Source File: SalesforceBulkExecRuntime.java    From components with Apache License 2.0 6 votes vote down vote up
public void bulkExecute(RuntimeContainer container) {
    TSalesforceBulkExecProperties sprops = (TSalesforceBulkExecProperties) properties;
    try {
        SalesforceBulkRuntime bulkRuntime = new SalesforceBulkRuntime(connect(container).bulkConnection);
        bulkRuntime.setConcurrencyMode(sprops.bulkProperties.concurrencyMode.getValue());
        bulkRuntime.setAwaitTime(sprops.bulkProperties.waitTimeCheckBatchState.getValue());
        // We only support CSV file for bulk output
        bulkRuntime.executeBulk(sprops.module.moduleName.getStringValue(), sprops.outputAction.getValue(), sprops.hardDelete.getValue(),
                sprops.upsertKeyColumn.getStringValue(), "csv", sprops.bulkFilePath.getStringValue(),
                sprops.bulkProperties.bytesToCommit.getValue(), sprops.bulkProperties.rowsToCommit.getValue());
        // count results
        for (int i = 0; i < bulkRuntime.getBatchCount(); i++) {
            for (BulkResult result : bulkRuntime.getBatchLog(i)) {
                dataCount++;
                if ("true".equalsIgnoreCase(String.valueOf(result.getValue("Success")))) {
                    successCount++;
                } else {
                    rejectCount++;
                }
            }
        }
        bulkRuntime.close();
    } catch (IOException | AsyncApiException | ConnectionException e) {
        throw new ComponentException(e);
    }
}
 
Example #9
Source File: ForceSoapWriter.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void delete(
    SObject[] recordArray,
    Map<SObject, Record> recordMap,
    List<OnRecordErrorException> errorRecords
) throws ConnectionException {
  LOG.info("Deleting {} records in Salesforce", recordArray.length);

  DeleteResult[] deleteResults = partnerConnection.delete(sObjectsToIds(recordArray));

  LOG.info("{} records deleted from Salesforce", deleteResults.length);

  // check the returned results for any errors
  for (int i = 0; i < deleteResults.length; i++) {
    if (!deleteResults[i].isSuccess()) {
      handleErrorRecord(recordArray[i], deleteResults[i].getErrors(), recordMap, errorRecords);
    }
  }
}
 
Example #10
Source File: ForceService.java    From salesforce-jdbc with MIT License 6 votes vote down vote up
private static PartnerConnection createConnectionByUserCredential(ForceConnectionInfo info)
        throws ConnectionException {
    ConnectorConfig partnerConfig = new ConnectorConfig();
    partnerConfig.setUsername(info.getUserName());
    partnerConfig.setPassword(info.getPassword());
    if (info.getSandbox() != null) {
        partnerConfig.setAuthEndpoint(buildAuthEndpoint(info.getSandbox()));
        return Connector.newConnection(partnerConfig);
    }

    try {
        partnerConfig.setAuthEndpoint(buildAuthEndpoint(false));
        return Connector.newConnection(partnerConfig);
    } catch (ConnectionException ce) {
        partnerConfig.setAuthEndpoint(buildAuthEndpoint(true));
        return Connector.newConnection(partnerConfig);
    }
}
 
Example #11
Source File: ForceService.java    From salesforce-jdbc with MIT License 6 votes vote down vote up
private static PartnerConnection createConnectionBySessionId(ForceConnectionInfo info) throws ConnectionException {
    ConnectorConfig partnerConfig = new ConnectorConfig();
    partnerConfig.setSessionId(info.getSessionId());

    if (info.getSandbox() != null) {
        partnerConfig.setServiceEndpoint(ForceService.getPartnerUrl(info.getSessionId(), info.getSandbox()));
        return Connector.newConnection(partnerConfig);
    }

    try {
        partnerConfig.setServiceEndpoint(ForceService.getPartnerUrl(info.getSessionId(), false));
        return Connector.newConnection(partnerConfig);
    } catch (RuntimeException re) {
        try {
            partnerConfig.setServiceEndpoint(ForceService.getPartnerUrl(info.getSessionId(), true));
            return Connector.newConnection(partnerConfig);
        } catch (RuntimeException r) {
            throw new ConnectionException(r.getMessage());
        }
    }
}
 
Example #12
Source File: SalesforceBulkQueryInputReader.java    From components with Apache License 2.0 6 votes vote down vote up
private boolean retrieveNextResultSet() throws IOException {
    while (bulkRuntime.hasNextResultId()) {
        String resultId = bulkRuntime.nextResultId();
        if (null != resultId) {
            try {
                // Get a new result set
                bulkResultSet = bulkRuntime.getQueryResultSet(resultId);
            } catch (AsyncApiException | ConnectionException e) {
                throw new IOException(e);
            }

            currentRecord = bulkResultSet.next();
            // If currentRecord is null, we need to check if resultId set has more entries.
            if (null != currentRecord) {
                // New result set available to retrieve
                dataCount++;
                return true;
            }
        }
    }
    return false;
}
 
Example #13
Source File: ForceSoapWriter.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void update(
    SObject[] recordArray,
    Map<SObject, Record> recordMap,
    List<OnRecordErrorException> errorRecords
) throws ConnectionException {
  LOG.info("Updating {} records in Salesforce", recordArray.length);

  SaveResult[] saveResults = partnerConnection.update(recordArray);

  LOG.info("{} records updated in Salesforce", saveResults.length);

  // check the returned results for any errors
  for (int i = 0; i < saveResults.length; i++) {
    if (!saveResults[i].isSuccess()) {
      handleErrorRecord(recordArray[i], saveResults[i].getErrors(), recordMap, errorRecords);
    }
  }
}
 
Example #14
Source File: SalesforceSourceOrSink.java    From components with Apache License 2.0 6 votes vote down vote up
/**
 * Get the session properties instance
 *
 * @return session properties
 * @throws ConnectionException connection disable during get user information
 */
protected Properties getSessionProperties() throws ConnectionException {
    File sessionFile = new File(sessionFilePath);
    try {
        if (sessionFile.exists()) {
            FileInputStream sessionInput = new FileInputStream(sessionFile);
            try {
                Properties sessionProp = new Properties();
                sessionProp.load(sessionInput);
                int maxValidSeconds = Integer.valueOf(sessionProp.getProperty(SalesforceConstant.MAX_VALID_SECONDS));
                // Check whether the session is timeout
                if (maxValidSeconds > ((System.currentTimeMillis() - sessionFile.lastModified()) / 1000)) {
                    return sessionProp;
                }
            } finally {
                sessionInput.close();
            }
        }
    } catch (IOException e) {
        throw new ConnectionException("Reuse session fails!", e);
    }
    return null;
}
 
Example #15
Source File: SalesforceServerTimeStampReader.java    From components with Apache License 2.0 6 votes vote down vote up
@Override
public boolean start() throws IOException {
    ConnectionHolder ch = ((SalesforceSource) getCurrentSource()).connect(container);
    PartnerConnection connection = ch.connection;
    if (ch.bulkConnection != null) {
        LOGGER.info(MESSAGES.getMessage("info.bulkConnectionUsage"));
    }
    try {
        Calendar serverTimestamp = connection.getServerTimestamp().getTimestamp();
        if (serverTimestamp != null) {
            long timestamp = serverTimestamp.getTimeInMillis();
            result = new GenericData.Record(properties.schema.schema.getValue());
            result.put(0, timestamp);
        }
        if (result != null) {
            dataCount++;
            return true;
        } else {
            return false;
        }
    } catch (ConnectionException e) {
        throw new IOException(e);
    }
}
 
Example #16
Source File: PartnerService.java    From salesforce-jdbc with MIT License 6 votes vote down vote up
private Column convertToColumn(Field field) {
    try {
        Column column = new Column(field.getName(), getType(field));
        column.setNillable(false);
        column.setCalculated(field.isCalculated() || field.isAutoNumber());
        String[] referenceTos = field.getReferenceTo();
        if (referenceTos != null) {
            for (String referenceTo : referenceTos) {
                if (getSObjectTypes().contains(referenceTo)) {
                    column.setReferencedTable(referenceTo);
                    column.setReferencedColumn("Id");
                }
            }
        }
        return column;
    } catch (ConnectionException e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: WaveAnalyticsTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void write(Batch batch) throws StageException {
  if (batch.getRecords().hasNext()) {
    if (datasetID == null) {
      LOG.info("Opening dataset");
      try {
        openDataset();
      } catch (ConnectionException ce) {
        throw new StageException(Errors.WAVE_01, ce);
      }
    }

    LOG.info("Writing batch to dataset");
    writeToDataset(batch);
    try {
      commitDataset();
    } catch (ConnectionException | IOException e) {
      throw new StageException(Errors.WAVE_01, e);
    }
  }
}
 
Example #18
Source File: SalesforceGetUpdatedReader.java    From components with Apache License 2.0 6 votes vote down vote up
@Override
public boolean advance() throws IOException {
    inputRecordsIndex++;
    // Fast return conditions.
    if (inputRecordsIndex < inputRecords.length) {
        dataCount++;
        return true;
    }
    if (queryIndex < idsList.size()) {
        try {
            inputRecords = getConnection().retrieve(getFieldNamesStr(), properties.module.moduleName.getValue(),
                    idsList.get(queryIndex++));
            inputRecordsIndex = 0;
            boolean isAdvanced = inputRecords.length > 0;
            if (isAdvanced) {
                dataCount++;
            }
            return isAdvanced;
        } catch (ConnectionException e) {
            throw new IOException(e);
        }
    }
    return false;
}
 
Example #19
Source File: SfdcApiServiceImpl.java    From Data-Migration-Tool with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Counts number of records
 *
 * @param PartnerConnection connection: connection to Salesforce org
 * @param String sObjectAPIName: Object to be queried (API name)
 *
 */
public Integer queryValidate(PartnerConnection connection, SforceObject sforceObject) {

    int records = 0;
    try {

        String query = "SELECT COUNT()  FROM " + sforceObject.getsObjectName();
        QueryResult qr = connection.query(query);
        records = qr.getSize();

    } catch (ConnectionException ce) {
        log.error("ConnectionException...", ce);
        ce.printStackTrace();
    }

    return records;
}
 
Example #20
Source File: SalesforceBulkRuntime.java    From components with Apache License 2.0 6 votes vote down vote up
protected JobInfo createJob(JobInfo job) throws AsyncApiException, ConnectionException {
    try {
        if (0 != chunkSize) {
            // Enabling PK chunking by setting header and chunk size.
            bulkConnection.addHeader(PK_CHUNKING_HEADER_NAME, CHUNK_SIZE_PROPERTY_NAME + chunkSize);
        }
        return bulkConnection.createJob(job);
    } catch (AsyncApiException sfException) {
        if (AsyncExceptionCode.InvalidSessionId.equals(sfException.getExceptionCode())) {
            SalesforceRuntimeCommon.renewSession(bulkConnection.getConfig());
            return createJob(job);
        }
        throw sfException;
    } finally {
        if (0 != chunkSize) {
            // Need to disable PK chunking after job was created.
            bulkConnection.addHeader(PK_CHUNKING_HEADER_NAME, Boolean.FALSE.toString());
        }
    }
}
 
Example #21
Source File: ForceWriter.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs and sets field mappings for the writer.
 * @param customMappings Mappings of SDC field names to Salesforce field names
 */
public ForceWriter(PartnerConnection partnerConnection, String sObject, Map<String, String> customMappings) throws
    ConnectionException {
  this.partnerConnection = partnerConnection;
  this.sObject = sObject;

  // Get default field mappings and add them to the configured mappings
  this.fieldMappings = new HashMap<String, String>(customMappings);
  DescribeSObjectResult result = partnerConnection.describeSObject(sObject);
  for (Field field : result.getFields()) {
    String fieldName = field.getName();
    if (!customMappings.containsKey(fieldName)) {
      fieldMappings.put(fieldName, "/" + fieldName);
    }
  }
}
 
Example #22
Source File: SfdcConnection.java    From Data-Migration-Tool with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void printUserInfo(ConnectorConfig config) {
    try {
        GetUserInfoResult userInfo = connectionSource.getUserInfo();

        System.out.println("\nSource Logging in ...\n");
        System.out.println("Source UserID: " + userInfo.getUserId());
        System.out.println("Source User Name: " + userInfo.getUserName());
        System.out.println("Source User Email: " + userInfo.getUserEmail());
        System.out.println();

        System.out.println("Source Auth End Point: " + config.getAuthEndpoint());
        System.out.println("Source Service End Point: " + config.getServiceEndpoint());
        System.out.println();
    } catch (ConnectionException ce) {
        ce.printStackTrace();
    }
}
 
Example #23
Source File: SalesForceBaseFunction.java    From openbd-core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Ges the Connection to SalesForce using the WSC wrapper
 * 
 * @param _session
 * @param argStruct
 * @return
 * @throws cfmRunTimeException
 * @throws ConnectionException
 */
protected PartnerConnection getConnection(cfSession _session, cfArgStructData argStruct) throws cfmRunTimeException, ConnectionException {
	String	email	= getNamedStringParam(argStruct, "email", null );
	if ( email == null )
		throwException( _session, "email was not properly defined" );

	String	passwordtoken	= getNamedStringParam(argStruct, "passwordtoken", null );
	if ( passwordtoken == null )
		throwException( _session, "passwordtoken was not properly defined" );

	// Make the connection to SalesForce
	ConnectorConfig config = new ConnectorConfig();
   config.setUsername(email);
   config.setPassword(passwordtoken);
   
   int timeout =	getNamedIntParam(argStruct, "timeout", -1 );
   if ( timeout > 0 )
     config.setReadTimeout(timeout);

   return Connector.newConnection(config);
}
 
Example #24
Source File: SalesforceInputReader.java    From components with Apache License 2.0 5 votes vote down vote up
protected QueryResult executeSalesforceQuery() throws IOException, ConnectionException {
    TSalesforceInputProperties inProperties = (TSalesforceInputProperties) properties;
    getConnection().setQueryOptions(inProperties.batchSize.getValue());
    if (inProperties.includeDeleted.getValue()) {
        return getConnection().queryAll(getQueryString(inProperties));
    } else {
        return getConnection().query(getQueryString(inProperties));
    }
}
 
Example #25
Source File: SalesforceBulkRuntime.java    From components with Apache License 2.0 5 votes vote down vote up
protected BatchInfo createBatchFromStream(JobInfo job, InputStream input) throws AsyncApiException, ConnectionException {
    try {
        return bulkConnection.createBatchFromStream(job, input);
    } catch (AsyncApiException sfException) {
        if (AsyncExceptionCode.InvalidSessionId.equals(sfException.getExceptionCode())) {
            SalesforceRuntimeCommon.renewSession(bulkConnection.getConfig());
            return createBatchFromStream(job, input);
        }
        throw sfException;
    }
}
 
Example #26
Source File: SalesforceWriter.java    From components with Apache License 2.0 5 votes vote down vote up
private SaveResult[] doInsert() throws IOException {
    if (insertItems.size() > 0) {
        // Clean the feedback records at each batch write.
        cleanWrites();
        SObject[] accs = new SObject[insertItems.size()];
        for (int i = 0; i < insertItems.size(); i++) {
            accs[i] = createSObject(insertItems.get(i));
        }

        String[] changedItemKeys = new String[accs.length];
        SaveResult[] saveResults;
        try {
            saveResults = connection.create(accs);
            if (saveResults != null && saveResults.length != 0) {
                int batch_idx = -1;
                for (int i = 0; i < saveResults.length; i++) {
                    ++batch_idx;
                    if (saveResults[i].getSuccess()) {
                        handleSuccess(insertItems.get(i), saveResults[i].getId(), null);
                    } else {
                        handleReject(insertItems.get(i), saveResults[i].getErrors(), changedItemKeys, batch_idx);
                    }
                }
            }
            insertItems.clear();
            return saveResults;
        } catch (ConnectionException e) {
            throw new IOException(e);
        }
    }
    return null;
}
 
Example #27
Source File: SalesforceRuntimeCommonTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Test(expected = ComponentException.class)
public void testGetSchemaNamesError() throws Exception {

    PartnerConnection conn = mock(PartnerConnection.class);
    doThrow(new ConnectionException("CONNECTION ERROR")).when(conn).describeGlobal();

    SalesforceRuntimeCommon.getSchemaNames(conn);
}
 
Example #28
Source File: SalesforceRuntimeCommon.java    From components with Apache License 2.0 5 votes vote down vote up
public static List<NamedThing> getSchemaNames(PartnerConnection connection) throws IOException {
    List<NamedThing> returnList = new ArrayList<>();
    DescribeGlobalResult result = null;
    try {
        result = connection.describeGlobal();
    } catch (ConnectionException e) {
        throw new ComponentException(e);
    }
    DescribeGlobalSObjectResult[] objects = result.getSobjects();
    for (DescribeGlobalSObjectResult obj : objects) {
        LOG.debug("module label: " + obj.getLabel() + " name: " + obj.getName());
        returnList.add(new SimpleNamedThing(obj.getName(), obj.getLabel()));
    }
    return returnList;
}
 
Example #29
Source File: SalesforceBulkRuntime.java    From components with Apache License 2.0 5 votes vote down vote up
protected InputStream getQueryResultStream(String jobID, String batchID, String resultID)
        throws AsyncApiException, ConnectionException {
    try {
        return bulkConnection.getQueryResultStream(jobID, batchID, resultID);
    } catch (AsyncApiException sfException) {
        if (AsyncExceptionCode.InvalidSessionId.equals(sfException.getExceptionCode())) {
            SalesforceRuntimeCommon.renewSession(bulkConnection.getConfig());
            return getQueryResultStream(jobID, batchID, resultID);
        }
        throw sfException;
    }
}
 
Example #30
Source File: ForceLookupSoapLoader.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private Optional<List<Map<String, Field>>> lookupValuesForRecord(String preparedQuery) throws StageException {
  List<Map<String, Field>> lookupItems = new ArrayList<>();
  SobjectRecordCreator recordCreator = (SobjectRecordCreator)processor.getRecordCreator();

  try {
    if (!recordCreator.metadataCacheExists()) {
      recordCreator.buildMetadataCacheFromQuery(processor.partnerConnection, preparedQuery);
    }

    QueryResult queryResult = processor.getConfig().queryAll
        ? processor.partnerConnection.queryAll(preparedQuery)
        : processor.partnerConnection.query(preparedQuery);
    addResult(lookupItems, queryResult);

    while (!queryResult.isDone()) {
      queryResult = processor.partnerConnection.queryMore(queryResult.getQueryLocator());
      addResult(lookupItems, queryResult);
    }

  } catch (ConnectionException e) {
    String message = (e instanceof ApiFault) ? ((ApiFault)e).getExceptionMessage() : e.getMessage();
    LOG.error(Errors.FORCE_17.getMessage(), preparedQuery, message, e);
    throw new OnRecordErrorException(Errors.FORCE_17, preparedQuery, message, e);
  }

  // If no lookup items were found, use defaults
  return lookupItems.isEmpty() ? Optional.empty() : Optional.of(lookupItems);
}