@Test(expected = ConnectionException.class)
  public void testCreateBulkWithTimeOutException() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    SaveResult saveResult = Mockito.mock(SaveResult.class);
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    when(partnerConnection.create(Mockito.argThat(new SObjectArrayMatcher())))
        .thenReturn(new SaveResult[] {saveResult});
    connector.setConnection(partnerConnection);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);
    JobInfo jobInfo = Mockito.mock(JobInfo.class);
    BatchRequest batchRequest = Mockito.mock(BatchRequest.class);
    AsyncApiException exception = Mockito.mock(AsyncApiException.class);
    doReturn(AsyncExceptionCode.InvalidSessionId).when(exception).getExceptionCode();
    doReturn(jobInfo).when(bulkConnection).createJob(any(JobInfo.class));
    doReturn(batchRequest).when(bulkConnection).createBatch(any(JobInfo.class));
    doThrow(exception).when(batchRequest).completeRequest();

    Map<String, Object> sObject = new HashMap<String, Object>();
    sObject.put(FIRST_NAME_FIELD, FIRST_NAME);
    sObject.put(LAST_NAME_FIELD, LAST_NAME);
    List<Map<String, Object>> sObjectList = new ArrayList<Map<String, Object>>();
    sObjectList.add(sObject);
    connector.createBulk(MOCK_OBJET_TYPE, sObjectList);
  }
  @Test
  public void testGetUpdatedObjects() throws Exception {
    SalesforceConnector connector = Mockito.spy(new SalesforceConnector());
    connector.setConnection(connection);
    when(connection.getConfig()).thenReturn(createConnectorConfig("userX"));
    connector.setObjectStoreHelper(objectStoreHelper);
    Calendar lastUpdateTime = createCalendar(4, 15);
    when(objectStoreHelper.getTimestamp("Account")).thenReturn(lastUpdateTime);
    setServerTime(connection, 5, 15);

    when(connection.getUpdated(anyString(), any(Calendar.class), any(Calendar.class)))
        .thenReturn(getUpdatedResult);
    Calendar latestDateCovered = createCalendar(5, 10);
    when(getUpdatedResult.getLatestDateCovered()).thenReturn(latestDateCovered);
    when(getUpdatedResult.getIds()).thenReturn(new String[] {"1", "3"});

    List<Map<String, Object>> updatedObjects = new ArrayList<Map<String, Object>>();
    doReturn(updatedObjects)
        .when(connector)
        .retrieve("Account", Arrays.asList("1", "3"), Arrays.asList("Id", "Name"));

    assertSame(
        updatedObjects, connector.getUpdatedObjects("Account", 60, Arrays.asList("Id", "Name")));

    verify(connection)
        .getUpdated(eq("Account"), startTimeCaptor.capture(), endTimeCaptor.capture());
    assertStartTime(4, 15);
    assertEndTime(5, 15);
    verify(objectStoreHelper).updateTimestamp(getUpdatedResult, "Account");
  }
  @Test
  public void testQuery() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    final SObject sObject1 = Mockito.mock(SObject.class);
    final SObject sObject2 = Mockito.mock(SObject.class);
    final SObject sObject3 = Mockito.mock(SObject.class);
    when(sObject1.getId()).thenReturn("1");
    when(sObject2.getId()).thenReturn("2");
    when(sObject3.getId()).thenReturn("3");
    QueryResult queryResult = Mockito.mock(QueryResult.class);
    when(queryResult.getRecords())
        .thenAnswer(
            new Answer<Object>() {
              int counter = 0;

              @Override
              public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
                SObject[] result = null;
                switch (counter) {
                  case 0:
                    result = new SObject[] {sObject1};
                    break;
                  case 1:
                    result = new SObject[] {sObject2, sObject3};
                    break;
                  case 2:
                    result = new SObject[] {};
                    break;
                }
                counter++;
                return result;
              }
            });
    when(queryResult.isDone()).thenReturn(false).thenReturn(true);
    when(queryResult.getQueryLocator()).thenReturn("001").thenReturn(null);

    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);
    connector.setConnection(partnerConnection);

    when(partnerConnection.query(eq(MOCK_QUERY))).thenReturn(queryResult);
    when(partnerConnection.queryMore("001")).thenReturn(queryResult);

    PagingDelegate<Map<String, Object>> delegate =
        connector.query(MOCK_QUERY, new PagingConfiguration(1));
    List<Map<String, Object>> result = delegate.getPage();
    assertEquals(1, result.size());

    result = delegate.getPage();
    assertEquals(2, result.size());

    assertNull(delegate.getPage());
  }
  @Test
  public void testGetUserInfo() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    connector.setConnection(partnerConnection);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);
    GetUserInfoResult getUserInfoResult = Mockito.mock(GetUserInfoResult.class);
    when(partnerConnection.getUserInfo()).thenReturn(getUserInfoResult);

    assertEquals(getUserInfoResult, connector.getUserInfo());
  }
  @Test
  public void testDescribeSObject() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    DescribeSObjectResult describeSObjectResult = Mockito.mock(DescribeSObjectResult.class);
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    connector.setConnection(partnerConnection);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);

    when(partnerConnection.describeSObject(eq(MOCK_OBJET_TYPE))).thenReturn(describeSObjectResult);

    connector.describeSObject(MOCK_OBJET_TYPE);
  }
 private SalesforceBayeuxClient mockBayeuxClient() throws MalformedURLException {
   PartnerConnection connection = Mockito.mock(PartnerConnection.class);
   LoginResult loginResult = Mockito.mock(LoginResult.class);
   ConnectorConfig connectorConfig = Mockito.mock(ConnectorConfig.class);
   SalesforceConnector connector = Mockito.mock(SalesforceConnector.class);
   when(connector.getConnection()).thenReturn(connection);
   when(connector.getLoginResult()).thenReturn(loginResult);
   when(connector.getSessionId()).thenReturn("001");
   when(connection.getConfig()).thenReturn(connectorConfig);
   when(connectorConfig.getServiceEndpoint()).thenReturn("http://xxx.salesforce.com");
   when(connectorConfig.getUsername()).thenReturn("mulesoft");
   return new SalesforceBayeuxClient(connector);
 }
  @Test
  public void testQuerySingle() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    QueryResult queryResult = Mockito.mock(QueryResult.class);
    when(queryResult.getRecords()).thenReturn(new SObject[] {});
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);
    connector.setConnection(partnerConnection);

    when(partnerConnection.query(eq(MOCK_QUERY))).thenReturn(queryResult);

    connector.querySingle(MOCK_QUERY);
  }
  @Test
  public void testDescribeGlobal() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    DescribeGlobalResult describeGlobalResult = Mockito.mock(DescribeGlobalResult.class);
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);
    connector.setConnection(partnerConnection);

    when(partnerConnection.describeGlobal()).thenReturn(describeGlobalResult);

    connector.describeGlobal();

    verify(partnerConnection).describeGlobal();
  }
  @Test
  public void testGetDeletedRange() throws Exception {
    SalesforceConnector connector = spy(new SalesforceConnector());
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    connector.setConnection(partnerConnection);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);
    GetServerTimestampResult getServerTimestampResult =
        Mockito.mock(GetServerTimestampResult.class);
    when(partnerConnection.getServerTimestamp()).thenReturn(getServerTimestampResult);

    connector.getDeletedRange("Account", Calendar.getInstance(), Calendar.getInstance());

    verify(partnerConnection, atLeastOnce())
        .getDeleted(eq("Account"), any(Calendar.class), any(Calendar.class));
  }
  @Test
  public void testDelete() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    DeleteResult deleteResult = Mockito.mock(DeleteResult.class);
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    connector.setConnection(partnerConnection);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);

    when(partnerConnection.delete(argThat(new StringArrayMatcher())))
        .thenReturn(new DeleteResult[] {deleteResult});

    List<String> ids = new ArrayList<String>();
    ids.add(MOCKED_ID);

    connector.delete(ids);
  }
  @Test
  public void testEmptyRecycleBin() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    EmptyRecycleBinResult emptyRecycleBinResult = Mockito.mock(EmptyRecycleBinResult.class);
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    connector.setConnection(partnerConnection);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);

    when(partnerConnection.emptyRecycleBin(argThat(new StringArrayMatcher())))
        .thenReturn(new EmptyRecycleBinResult[] {emptyRecycleBinResult});

    List<String> ids = new ArrayList<String>();
    ids.add(MOCKED_ID);

    connector.emptyRecycleBin(ids);
  }
예제 #12
0
 @Override
 protected void executeFunction(final PartnerConnection connection) throws Exception {
   if (logger.isDebugEnabled()) {
     logger.debug("query = " + query);
   }
   queryResult = connection.query(query);
   sObjects = Arrays.asList(queryResult.getRecords());
 }
예제 #13
0
 private QueryResult executeSoqlQuery(String query) {
   logger.info("Executing SOQL query: {}", query);
   try {
     QueryResult queryResult = _connection.query(query);
     return queryResult;
   } catch (ConnectionException e) {
     throw SalesforceUtils.wrapException(e, "Failed to invoke query service");
   }
 }
  @Test
  public void testCreateSingleWithNoSaveResults() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    when(partnerConnection.create(Mockito.argThat(new SObjectArrayMatcher())))
        .thenReturn(new SaveResult[] {});
    connector.setConnection(partnerConnection);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);

    Map<String, Object> sObject = new HashMap<String, Object>();
    sObject.put(FIRST_NAME_FIELD, FIRST_NAME);
    sObject.put(LAST_NAME_FIELD, LAST_NAME);

    SaveResult returnedSaveResult = connector.createSingle(MOCK_OBJET_TYPE, sObject);

    assertNull(returnedSaveResult);
  }
  @Test
  public void testRetrieve() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);
    connector.setConnection(partnerConnection);

    SObject sObject1 = Mockito.mock(SObject.class);
    SObject sObject2 = Mockito.mock(SObject.class);

    when(partnerConnection.retrieve(eq("Id,Name"), eq("Account"), eq(new String[] {"id1", "id2"})))
        .thenReturn(new SObject[] {sObject1, sObject2});

    List<Map<String, Object>> result =
        connector.retrieve("Account", Arrays.asList("id1", "id2"), Arrays.asList("Id", "Name"));

    assertEquals(2, result.size());
  }
  @Test
  public void testPublishTopic() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    connector.setConnection(partnerConnection);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);
    SaveResult saveResult = Mockito.mock(SaveResult.class);
    when(saveResult.isSuccess()).thenReturn(true);
    when(partnerConnection.create(Mockito.argThat(new SObjectArrayMatcher())))
        .thenReturn(new SaveResult[] {saveResult});
    QueryResult queryResult = Mockito.mock(QueryResult.class);
    when(partnerConnection.query(eq("SELECT Id FROM PushTopic WHERE Name = 'TopicName'")))
        .thenReturn(queryResult);
    when(queryResult.getSize()).thenReturn(0);

    connector.publishTopic("TopicName", "SELECT * FROM Account", "Description");

    verify(partnerConnection, atLeastOnce()).create(Mockito.argThat(new SObjectArrayMatcher()));
  }
  @Test
  public void testUpdate() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    SaveResult saveResult = Mockito.mock(SaveResult.class);
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    when(partnerConnection.update(Mockito.argThat(new SObjectArrayMatcher())))
        .thenReturn(new SaveResult[] {saveResult});
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);
    connector.setConnection(partnerConnection);

    Map<String, Object> sObject = new HashMap<String, Object>();
    sObject.put(FIRST_NAME_FIELD, FIRST_NAME);
    sObject.put(LAST_NAME_FIELD, LAST_NAME);
    List<Map<String, Object>> sObjectList = new ArrayList<Map<String, Object>>();
    sObjectList.add(sObject);

    List<SaveResult> saveResults = connector.update(MOCK_OBJET_TYPE, sObjectList);

    assertEquals(saveResults.get(0), saveResult);
  }
예제 #18
0
  public void querySample() {
    try {
      // Set query batch size
      partnerConnection.setQueryOptions(250);

      // SOQL query to use
      String soqlQuery = "SELECT FirstName, LastName FROM Contact";
      // Make the query call and get the query results
      QueryResult qr = partnerConnection.query(soqlQuery);

      boolean done = false;
      int loopCount = 0;
      // Loop through the batches of returned results
      while (!done) {
        System.out.println("Records in results set " + loopCount++ + " - ");
        SObject[] records = qr.getRecords();
        // Process the query results
        for (int i = 0; i < records.length; i++) {
          SObject contact = records[i];
          Object firstName = contact.getField("FirstName");
          Object lastName = contact.getField("LastName");
          if (firstName == null) {
            System.out.println("Contact " + (i + 1) + ": " + lastName);
          } else {
            System.out.println("Contact " + (i + 1) + ": " + firstName + " " + lastName);
          }
        }
        if (qr.isDone()) {
          done = true;
        } else {
          qr = partnerConnection.queryMore(qr.getQueryLocator());
        }
      }
    } catch (ConnectionException ce) {
      ce.printStackTrace();
    }
    System.out.println("\nQuery execution completed.");
  }
예제 #19
0
  public void updateSample(String id) {
    try {
      // Create an sObject of type contact
      SObject updateContact = new SObject();
      updateContact.setType("Contact");

      // Set the ID of the contact to update
      updateContact.setId(id);
      // Set the Phone field with a new value
      updateContact.setField("Phone", "(415) 555-1212");

      // Create another contact that will cause an error
      // because it has an invalid ID.
      SObject errorContact = new SObject();
      errorContact.setType("Contact");
      // Set an invalid ID on purpose
      errorContact.setId("SLFKJLFKJ");
      // Set the value of LastName to null
      errorContact.setFieldsToNull(new String[] {"LastName"});

      // Make the update call by passing an array containing
      // the two objects.
      SaveResult[] saveResults =
          partnerConnection.update(new SObject[] {updateContact, errorContact});
      // Iterate through the results and write the ID of
      // the updated contacts to the console, in this case one contact.
      // If the result is not successful, write the errors
      // to the console. In this case, one item failed to update.
      for (int j = 0; j < saveResults.length; j++) {
        System.out.println("\nItem: " + j);
        if (saveResults[j].isSuccess()) {
          System.out.println("Contact with an ID of " + saveResults[j].getId() + " was updated.");
        } else {
          // There were errors during the update call,
          // go through the errors array and write
          // them to the console.
          for (int i = 0; i < saveResults[j].getErrors().length; i++) {
            Error err = saveResults[j].getErrors()[i];
            System.out.println("Errors were found on item " + j);
            System.out.println("Error code: " + err.getStatusCode().toString());
            System.out.println("Error message: " + err.getMessage());
          }
        }
      }
    } catch (ConnectionException ce) {
      ce.printStackTrace();
    }
  }
예제 #20
0
  public String createSample() {
    String result = null;
    try {
      // Create a new sObject of type Contact
      // and fill out its fields.
      SObject contact = new SObject();
      contact.setType("Contact");
      contact.setField("FirstName", "Otto");
      contact.setField("LastName", "Jespersen");
      contact.setField("Salutation", "Professor");
      contact.setField("Phone", "(999) 555-1234");
      contact.setField("Title", "Philologist");

      // Add this sObject to an array
      SObject[] contacts = new SObject[1];
      contacts[0] = contact;
      // Make a create call and pass it the array of sObjects
      SaveResult[] results = partnerConnection.create(contacts);

      // Iterate through the results list
      // and write the ID of the new sObject
      // or the errors if the object creation failed.
      // In this case, we only have one result
      // since we created one contact.
      for (int j = 0; j < results.length; j++) {
        if (results[j].isSuccess()) {
          result = results[j].getId();
          System.out.println("\nA contact was created with an ID of: " + result);
        } else {
          // There were errors during the create call,
          // go through the errors array and write
          // them to the console
          for (int i = 0; i < results[j].getErrors().length; i++) {
            Error err = results[j].getErrors()[i];
            System.out.println("Errors were found on item " + j);
            System.out.println("Error code: " + err.getStatusCode().toString());
            System.out.println("Error message: " + err.getMessage());
          }
        }
      }
    } catch (ConnectionException ce) {
      ce.printStackTrace();
    }
    return result;
  }
예제 #21
0
  public void searchSample(String phoneNumber) {
    try {
      // Example of phoneNumber format: 4155551212
      String soslQuery =
          "FIND {"
              + phoneNumber
              + "} IN Phone FIELDS "
              + "RETURNING "
              + "Contact(Id, Phone, FirstName, LastName), "
              + "Lead(Id, Phone, FirstName, LastName),"
              + "Account(Id, Phone, Name)";
      // Perform SOSL query
      SearchResult sResult = partnerConnection.search(soslQuery);
      // Get the records returned by the search result
      SearchRecord[] records = sResult.getSearchRecords();
      // Create lists of objects to hold search result records
      List<SObject> contacts = new ArrayList<SObject>();
      List<SObject> leads = new ArrayList<SObject>();
      List<SObject> accounts = new ArrayList<SObject>();

      // Iterate through the search result records
      // and store the records in their corresponding lists
      // based on record type.
      if (records != null && records.length > 0) {
        for (int i = 0; i < records.length; i++) {
          SObject record = records[i].getRecord();
          if (record.getType().toLowerCase().equals("contact")) {
            contacts.add(record);
          } else if (record.getType().toLowerCase().equals("lead")) {
            leads.add(record);
          } else if (record.getType().toLowerCase().equals("account")) {
            accounts.add(record);
          }
        }
        // Display the contacts that the search returned
        if (contacts.size() > 0) {
          System.out.println("Found " + contacts.size() + " contact(s):");
          for (SObject contact : contacts) {
            System.out.println(
                contact.getId()
                    + " - "
                    + contact.getField("FirstName")
                    + " "
                    + contact.getField("LastName")
                    + " - "
                    + contact.getField("Phone"));
          }
        }
        // Display the leads that the search returned
        if (leads.size() > 0) {
          System.out.println("Found " + leads.size() + " lead(s):");
          for (SObject lead : leads) {
            System.out.println(
                lead.getId()
                    + " - "
                    + lead.getField("FirstName")
                    + " "
                    + lead.getField("LastName")
                    + " - "
                    + lead.getField("Phone"));
          }
        }
        // Display the accounts that the search returned
        if (accounts.size() > 0) {
          System.out.println("Found " + accounts.size() + " account(s):");
          for (SObject account : accounts) {
            System.out.println(
                account.getId()
                    + " - "
                    + account.getField("Name")
                    + " - "
                    + account.getField("Phone"));
          }
        }
      } else {
        // The search returned no records
        System.out.println("No records were found for the search.");
      }
    } catch (ConnectionException ce) {
      ce.printStackTrace();
    }
  }
  @Test
  public void testConvertLead() throws Exception {
    SalesforceConnector connector = new SalesforceConnector();
    PartnerConnection partnerConnection = Mockito.mock(PartnerConnection.class);
    BulkConnection bulkConnection = Mockito.mock(BulkConnection.class);
    connector.setBulkConnection(bulkConnection);
    connector.setConnection(partnerConnection);
    LeadConvertResult result = Mockito.mock(LeadConvertResult.class);

    when(partnerConnection.convertLead(
            argThat(
                new Matcher<LeadConvert[]>() {
                  @Override
                  public boolean matches(Object o) {
                    if (!o.getClass().isArray()) {
                      return false;
                    }

                    Object[] oArray = (Object[]) o;
                    if (oArray.length != 1) {
                      return false;
                    }

                    if (!(oArray[0] instanceof LeadConvert)) {
                      return false;
                    }

                    LeadConvert leadConvert = (LeadConvert) oArray[0];

                    if (!leadConvert.getAccountId().equals(ACCOUNT_ID)) {
                      return false;
                    }

                    if (!leadConvert.getContactId().equals(CONTACT_ID)) {
                      return false;
                    }

                    if (!leadConvert.getLeadId().equals(LEAD_ID)) {
                      return false;
                    }

                    if (!leadConvert.getOpportunityName().equals(OPPORTUNITY_NAME)) {
                      return false;
                    }

                    if (!leadConvert.getOverwriteLeadSource()) {
                      return false;
                    }

                    if (!leadConvert.getDoNotCreateOpportunity()) {
                      return false;
                    }

                    if (!leadConvert.getSendNotificationEmail()) {
                      return false;
                    }

                    return true;
                  }

                  @Override
                  public void _dont_implement_Matcher___instead_extend_BaseMatcher_() {}

                  @Override
                  public void describeTo(Description description) {}
                })))
        .thenReturn(new LeadConvertResult[] {result});

    connector.convertLead(
        LEAD_ID, CONTACT_ID, ACCOUNT_ID, true, true, OPPORTUNITY_NAME, CONVERTED_STATUS, true);
  }
 private void setServerTime(PartnerConnection connection, int hourOfDay, int minute)
     throws com.sforce.ws.ConnectionException {
   GetServerTimestampResult getServerTimetampResult = Mockito.mock(GetServerTimestampResult.class);
   when(connection.getServerTimestamp()).thenReturn(getServerTimetampResult);
   when(getServerTimetampResult.getTimestamp()).thenReturn(createCalendar(hourOfDay, minute));
 }