Search in sources :

Example 1 with SObject

use of com.salesforce.soap.partner.sobject.SObject in project tdi-studio-se by Talend.

the class PartnerSamples method upsertSample.

private void upsertSample() {
    // call the login function to do so
    if (!loggedIn) {
        if (!login()) {
            return;
        }
    }
    try {
        DescribeSObjectResult dsr = binding.describeSObject("Account");
        HashMap fieldMap = makeFieldMap(dsr.getFields());
        if (!fieldMap.containsKey("External_Id__c")) {
            System.out.println("\n\nATTENTION: To run this sample you need to \ncreate a custom text field on the Account object \nnamed External_Id with a length of 8 characters \nand with the 'external id' checkbox checked.");
        } else {
            // First, we need to make sure the test accounts do not exist.
            QueryResult qr = binding.query("Select Id From Account Where External_Id__c = '11111111' or External_Id__c = '22222222'");
            if (qr.getSize() > 0) {
                SObject[] accounts = qr.getRecords();
                // Get the ids
                String[] ids = new String[accounts.length];
                for (int i = 0; i < ids.length; i++) {
                    ids[i] = accounts[i].getId();
                }
                // Delete the accounts
                binding.delete(ids);
            }
            // Create a new account using create, we wil use this to update via upsert
            // We will set the external id to be ones so that we can use that value for the upsert
            SObject newAccount = new SObject();
            newAccount.setType("Account");
            MessageElement acctName = newMessageElement("Name", "Account to update");
            MessageElement extId = newMessageElement("External_Id__c", "11111111");
            newAccount.set_any(new MessageElement[] { acctName, extId });
            binding.create(new SObject[] { newAccount });
            // Now we will create an account that should be updated on insert based
            // on the external id field.
            SObject updateAccount = new SObject();
            updateAccount.setType("Account");
            MessageElement webSite = newMessageElement("Website", "http://www.website.com");
            MessageElement extId1 = newMessageElement("External_Id__c", "11111111");
            updateAccount.set_any(new MessageElement[] { webSite, extId1 });
            // This account is meant to be new
            SObject createAccount = new SObject();
            createAccount.setType("Account");
            MessageElement cacctName = newMessageElement("Name", "My Company, Inc");
            MessageElement extId3 = newMessageElement("External_Id__c", "22222222");
            createAccount.set_any(new MessageElement[] { cacctName, extId3 });
            // We have our two accounts, one should be new, the other should be updated.
            try {
                // Invoke the upsert call and save the results.
                // Use External_Id custom field for matching records
                UpsertResult[] upsertResults = binding.upsert("External_Id__c", new SObject[] { createAccount, updateAccount });
                for (UpsertResult result : upsertResults) {
                    if (result.isSuccess()) {
                        System.out.println("\nUpsert succeeded.");
                        System.out.println((result.isCreated() ? "Inserted" : "Updated") + " account, id is " + result.getId().toString());
                    } else {
                        System.out.println("The Upsert failed because: " + result.getErrors(0).getMessage());
                    }
                }
            } catch (RemoteException ex) {
                System.out.println("An unexpected error has occurred." + ex.getMessage());
            }
        }
        getUserInput("\nPress the RETURN key to continue...");
    } catch (ApiFault e) {
        System.out.println("Error merging account: " + e.getExceptionMessage());
        getUserInput("\nHit return to continue...");
    } catch (RemoteException e) {
        System.out.println("Error from the server on the merge sample: " + e.getMessage());
        getUserInput("\nHit return to continue...");
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : HashMap(java.util.HashMap) DescribeSObjectResult(com.salesforce.soap.partner.DescribeSObjectResult) MessageElement(org.apache.axis.message.MessageElement) RemoteException(java.rmi.RemoteException) ServiceException(javax.xml.rpc.ServiceException) IOException(java.io.IOException) QueryResult(com.salesforce.soap.partner.QueryResult) ApiFault(com.salesforce.soap.partner.fault.ApiFault) SObject(com.salesforce.soap.partner.sobject.SObject) RemoteException(java.rmi.RemoteException) UpsertResult(com.salesforce.soap.partner.UpsertResult)

Example 2 with SObject

use of com.salesforce.soap.partner.sobject.SObject in project tdi-studio-se by Talend.

the class PartnerSamples method createTaskSample.

private void createTaskSample() {
    // call the login function to do so
    if (!loggedIn) {
        if (!login()) {
            return;
        }
    }
    try {
        // create an array to create 4 items in one call
        SObject[] taskarray = new SObject[4];
        for (int x = 0; x < 4; x++) {
            // Declare a new task object to hold our values
            final java.text.SimpleDateFormat ISO8601UTC = new java.text.SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss+SSSS");
            // Set the appropriate values on the task
            SObject task = new SObject();
            task.setType("Task");
            Date activityDate = new Date();
            int taskUbound = 5;
            int index = 0;
            if (contacts != null)
                taskUbound++;
            if (accounts != null)
                taskUbound++;
            if (x > 1)
                taskUbound++;
            MessageElement[] fields = new MessageElement[taskUbound];
            fields[index++] = newMessageElement("ActivityDate", ISO8601UTC.format(activityDate));
            fields[index++] = newMessageElement("Description", "Get in touch with this person");
            fields[index++] = newMessageElement("Priority", "Normal");
            fields[index++] = newMessageElement("Status", "Not Started");
            fields[index++] = newMessageElement("Subject", "Setup Call");
            // make sure we get some errors on records 3 and 4
            if (x > 1) {
                fields[index++] = newMessageElement("OwnerId", "DSF:LJKSDFLKJ");
            // The two lines below illustrate associating an object with
            // another object. If
            // we have created an account and/or a contact prior to
            // creating the task, we will
            // just grab the first account and/or contact id and place
            // it in the appropriate
            // reference field. WhoId can be a reference to a contact or
            // a lead or a user.
            // WhatId can be a reference to an account, campaign, case,
            // contract or opportunity
            }
            if (contacts != null) {
                fields[index++] = newMessageElement("WhoId", contacts[0]);
            }
            if (accounts != null) {
                fields[index++] = newMessageElement("WhatId", accounts[0]);
            }
            taskarray[x] = task;
        }
        // call the create method passing the array of tasks as sobjects
        SaveResult[] sr = binding.create(taskarray);
        for (int j = 0; j < sr.length; j++) {
            if (sr[j].isSuccess()) {
                System.out.println("A task was create with an id of: " + sr[j].getId());
                if (accounts != null) {
                    System.out.println(" - the task was associated with the account you created with an id of " + accounts[0] + ".");
                }
                if (tasks == null) {
                    tasks = new String[] { sr[j].getId() };
                } else {
                    String[] tempTasks = null;
                    tempTasks = new String[tasks.length + 1];
                    for (int i = 0; i < tasks.length; i++) {
                        tempTasks[i] = tasks[i];
                    }
                    tempTasks[tasks.length] = sr[j].getId();
                    tasks = tempTasks;
                }
            } else {
                // array and write them to the screen
                for (int i = 0; i < sr[j].getErrors().length; i++) {
                    // get the next error
                    com.salesforce.soap.partner.Error err = sr[j].getErrors()[i];
                    System.out.println("Errors were found on item " + new Integer(j).toString());
                    System.out.println("Error code is: " + err.getStatusCode().toString());
                    System.out.println("Error message: " + err.getMessage());
                }
            }
        }
        getUserInput("\nHit return to continue...");
    } catch (ApiFault af) {
        System.out.println("\nFailed to succesfully create a task, error message was: \n" + af.getExceptionMessage());
        getUserInput("\nHit return to continue...");
    } catch (Exception ex) {
        System.out.println("\nFailed to succesfully create a task, error message was: \n" + ex.getMessage());
        getUserInput("\nHit return to continue...");
    }
}
Also used : MessageElement(org.apache.axis.message.MessageElement) SaveResult(com.salesforce.soap.partner.SaveResult) Date(java.util.Date) RemoteException(java.rmi.RemoteException) ServiceException(javax.xml.rpc.ServiceException) IOException(java.io.IOException) ApiFault(com.salesforce.soap.partner.fault.ApiFault) SObject(com.salesforce.soap.partner.sobject.SObject)

Example 3 with SObject

use of com.salesforce.soap.partner.sobject.SObject in project tdi-studio-se by Talend.

the class TopQueryResult method processTopQueryResult.

public void processTopQueryResult(QueryResult qr) throws Exception {
    if (qr == null || qr.getRecords() == null) {
        return;
    }
    for (int i = 0; i < qr.getRecords().length; i++) {
        SObject record = qr.getRecords()[i];
        // transmit the rootType to each TopRecord
        TopRecord topRecord = new TopRecord(record.getType());
        topRecord.processSObject(record, record.getType());
        addNewColumns(this.returnColumns, topRecord.getColumnNameList());
        addNewColumns(this.returnLocalColumns, topRecord.getColumnLocalNameList());
        // buffer all the TopRecord in a List
        allTopRecords.add(topRecord);
    }
}
Also used : SObject(com.salesforce.soap.partner.sobject.SObject)

Example 4 with SObject

use of com.salesforce.soap.partner.sobject.SObject in project tdi-studio-se by Talend.

the class PartnerSamples method convertLeadSample.

private void convertLeadSample() {
    // call the login function to do so
    if (!loggedIn) {
        if (!login())
            return;
    }
    try {
        // This is the structure we need to fill in to effect a conversion
        LeadConvert lc = new LeadConvert();
        String summary = "Converting lead to contact.\n";
        // When converting a lead you have the option of creating a new
        // contact, or
        // merging the lead with an existing contact. This sample will show
        // both
        // cases. So the first thing to do, is get the lead to convert.
        // Step 1 - Determine the String of the lead to conver
        SObject lead;
        lead = this.getUnconvertedLead();
        // Set the lead id on the structure.
        String lid = new String();
        lid = lead.getId().substring(0, 15);
        lc.setLeadId(lid);
        // Step2 - determine if the user wants to merge the lead to an
        // existing contact,
        // or have a new contact created.
        String merge = getUserInput("\nDo you want to merge this lead into an existing contact (Y/N)? ");
        SObject contact = null;
        if (merge != null && merge.toLowerCase().equals("y")) {
            contact = getContact();
            if (contact == null) {
                summary += "  Create new contact.\n";
            } else {
                summary += "  Merge with " + getFieldValue(contact.get_any(), "FirstName") + " " + getFieldValue(contact.get_any(), "LastName") + "\n";
                String cid = new String();
                cid = contact.getId().substring(0, 15);
                lc.setContactId(cid);
                // We have the option of resetting the contact status to
                // that of the lead,
                // so we will query the user for that information.
                String overWrite = getUserInput("Do you want to overwrite the contact status with the lead status (Y/N)? ");
                if (overWrite != null && overWrite.toLowerCase().equals("y"))
                    lc.setOverwriteLeadSource(true);
                else
                    lc.setOverwriteLeadSource(false);
            }
        } else
            summary += "  Create new contact.\n";
        // Step 3 - Determine account id, if a contact is chosen, we will
        // use the accountid of the contact, this must
        // be specified. If the contact is not chosen, then the user needs
        // to select
        // an account to place the new contact in.
        String accountId = null;
        if (contact != null) {
            accountId = getFieldValue(contact.get_any(), "AccountId");
            String aid = new String();
            aid = accountId.substring(0, 15);
            lc.setAccountId(aid);
        } else // get an account chosen by the user
        {
            String newAccount = getUserInput("Do you want to create a new account for this lead (Y/N)? ");
            if (newAccount == null || !newAccount.toLowerCase().equals("y"))
                accountId = this.getAccount().getId().substring(0, 15);
            if (accountId != null) {
                String aid = new String();
                aid = accountId;
                lc.setAccountId(aid);
                String accountName;
                accountName = getAccountName(accountId);
                if (accountName != null)
                    summary += "  New contact will be in account '" + accountName + "'.\n";
                else
                    summary += "  New contact will be in account with an String of '" + accountId + "'.\n";
            } else {
                summary += "  A new account will be created.";
            }
        }
        // Step 4 - Determine if opportunity is to be created.
        // We will now ask the user if they would like to create a new
        // opportunity
        // based on the information on this lead
        String opp = getUserInput("Do you want to create an opportunity for this conversion (Y/N)? ");
        lc.setDoNotCreateOpportunity(true);
        if (opp != null && opp.toLowerCase().equals("y")) {
            lc.setDoNotCreateOpportunity(false);
            String oppName = getUserInput("Enter the name of the opportunity to create.. ");
            if (oppName == null) {
                System.out.println("No opportunity name given, NO opportunity will be created.");
                lc.setDoNotCreateOpportunity(true);
                summary += "  No opportunity will be created.\n";
            } else {
                lc.setOpportunityName(oppName);
                summary += "  An opportunity named: " + oppName + " will be created.\n";
            }
        }
        // Step 5 - Obtain the proper lead status to place on the converted
        // lead
        // The lead needs to have it's status updated to reflect the
        // conversion operation,
        // so we will ask the user to select the status to use
        System.out.println("Select the lead status to use to update the converted lead. ");
        lc.setConvertedStatus(getLeadStatus());
        summary += "  The converted lead will be assigned a status of " + lc.getConvertedStatus() + ".\n";
        // Step 6 - Finally, we have the option of notifying the owner of
        // the lead that it
        // has been converted.
        String sendMail = getUserInput("Would you like to have an email sent to the owner of the lead after the conversion (Y/N)?");
        if (sendMail != null && sendMail.toLowerCase().equals("y")) {
            lc.setSendNotificationEmail(true);
            summary += "  Email notification will be sent.\n";
        } else {
            lc.setSendNotificationEmail(false);
            summary += "  Email notificatino will NOT be sent.\n";
        }
        String cont;
        System.out.println("\n\nDEBUG VALUES\n");
        System.out.println("account id: " + (lc.getAccountId() == null ? "(create new)" : lc.getAccountId()));
        System.out.println("contact id: " + (lc.getContactId() == null ? "(create new)" : lc.getContactId()));
        System.out.println("converted status: " + lc.getConvertedStatus());
        System.out.println("do not create opp: " + new Boolean(lc.isDoNotCreateOpportunity()).toString());
        System.out.println("lead id: " + lc.getLeadId());
        System.out.println("opp name: " + (lc.getOpportunityName() == null ? "(no opp)" : lc.getOpportunityName()));
        System.out.println("overwrite lead source: " + new Boolean(lc.isOverwriteLeadSource()).toString());
        System.out.println("send email: " + new Boolean(lc.isSendNotificationEmail()).toString());
        // Get a final verification of lead conversion from the user.
        cont = getUserInput(summary + "\n Enter 'Y' to convert the lead.");
        if (cont != null && cont.toLowerCase().equals("y")) {
            LeadConvertResult[] lcr = null;
            lcr = binding.convertLead(new LeadConvert[] { lc });
            // LeadConvertResults
            for (int i = 0; i < lcr.length; i++) {
                if (lcr[i].isSuccess()) {
                    try {
                        System.out.println("Conversion of lead " + getFieldValue(lead.get_any(), "FirstName") + " " + getFieldValue(lead.get_any(), "LastName") + " was successful.");
                        if (contact != null && contact.getId().equals(lcr[i].getContactId()))
                            System.out.println("  Contact with String of '" + lcr[i].getContactId() + "' was merged.");
                        else
                            System.out.println("  Contact with String of '" + lcr[i].getContactId() + "' was created.");
                        if (lcr[i].getOpportunityId() != null)
                            System.out.println("  An opportunity with an String of '" + lcr[i].getOpportunityId() + "' was created.");
                        else
                            System.out.println("  No opportunity was created.");
                        System.out.println("  The contact was created in the account with an String of '" + lcr[i].getAccountId() + "'.");
                    } catch (Exception e) {
                        getUserInput("Although the lead was converted, some error prevented the reporting of results.");
                    }
                } else {
                    System.out.println("One or more errors where encountered during the lead conversion process...\n");
                    for (int j = 0; j < lcr[i].getErrors().length; j++) {
                        System.out.println((j + 1) + ". " + lcr[0].getErrors(j).getMessage());
                    }
                }
            }
        } else {
            System.out.println("Lead conversion was aborted.");
        }
    } catch (ApiFault af) {
        System.out.println("Errors occurred during conversion preventing any conversion to take place.\n\n" + af.getExceptionMessage());
        getUserInput("\nHit return to continue...");
    } catch (Exception e) {
        System.out.println("Errors occurred during conversion preventing any conversion to take place.\n\n" + e.getMessage());
    }
}
Also used : ApiFault(com.salesforce.soap.partner.fault.ApiFault) LeadConvert(com.salesforce.soap.partner.LeadConvert) SObject(com.salesforce.soap.partner.sobject.SObject) LeadConvertResult(com.salesforce.soap.partner.LeadConvertResult) RemoteException(java.rmi.RemoteException) ServiceException(javax.xml.rpc.ServiceException) IOException(java.io.IOException)

Example 5 with SObject

use of com.salesforce.soap.partner.sobject.SObject in project tdi-studio-se by Talend.

the class PartnerSamples method querySample.

private void querySample() {
    // call the login function to do so
    if (!loggedIn) {
        if (!login()) {
            return;
        }
    }
    QueryResult qr = null;
    QueryOptions qo = new QueryOptions();
    qo.setBatchSize(new Integer(3));
    binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(), "QueryOptions", qo);
    try {
        qr = binding.query("select id, Website, Name from Account where Name = 'Golden Straw'");
        ArrayList records = this.loadQueryResults(qr);
        if (records.size() != 0) {
            HashMap record = (HashMap) records.get(0);
            System.out.println("Retrieved " + new Integer(records.size()).toString() + " account(s) using Name = 'Golden Straw', String = " + (record.containsKey("id") ? record.get("id").toString() : " ").toString() + ", website = " + (record.containsKey("website") ? record.get("website").toString() : " ").toString());
        }
        // if (qr.getSize() != 0) {
        // SObject account = qr.getRecords()[0];
        //
        // System.out.println("Retrieved "
        // + new Integer(qr.getSize()).toString()
        // + " account(s) using Name = 'Golden Straw', String = "
        // + account.getId() + ", website = "
        // + account.get_any()[1]);
        // }
        qr = binding.query("select FirstName, LastName from Contact");
        int loopCount = 0;
        boolean continueLoop = true;
        while (continueLoop) {
            System.out.println("Results set " + new Integer(loopCount++).toString() + " - ");
            // process the query results
            for (int i = 0; i < qr.getRecords().length; i++) {
                SObject con = qr.getRecords()[i];
                String fName = "";
                String lName = "";
                if (con.get_any()[0].getName().toLowerCase().equals("firstname")) {
                    fName = con.get_any()[0].getValue();
                    lName = con.get_any()[1].getValue();
                } else
                    lName = con.get_any()[0].getValue();
                if (fName == null) {
                    System.out.println("Contact " + (i + 1) + ": " + lName);
                } else {
                    System.out.println("Contact " + (i + 1) + ": " + fName + " " + lName);
                }
            }
            // recent queryResult
            if (qr.isDone())
                continueLoop = false;
            else
                qr = binding.queryMore(qr.getQueryLocator());
        }
        System.out.println("\nQuery succesfully executed.");
        getUserInput("\nHit return to continue...");
    } catch (ApiFault af) {
        System.out.println("\nFailed to execute query succesfully, error message was: \n" + af.getExceptionMessage());
        getUserInput("\nHit return to continue...");
    } catch (Exception ex) {
        System.out.println("\nFailed to execute query succesfully, error message was: \n" + ex.getMessage());
        getUserInput("\nHit return to continue...");
    }
}
Also used : QueryResult(com.salesforce.soap.partner.QueryResult) ApiFault(com.salesforce.soap.partner.fault.ApiFault) SforceServiceLocator(com.salesforce.soap.partner.SforceServiceLocator) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SObject(com.salesforce.soap.partner.sobject.SObject) QueryOptions(com.salesforce.soap.partner.QueryOptions) RemoteException(java.rmi.RemoteException) ServiceException(javax.xml.rpc.ServiceException) IOException(java.io.IOException)

Aggregations

SObject (com.salesforce.soap.partner.sobject.SObject)25 RemoteException (java.rmi.RemoteException)17 IOException (java.io.IOException)15 ServiceException (javax.xml.rpc.ServiceException)15 ApiFault (com.salesforce.soap.partner.fault.ApiFault)14 QueryResult (com.salesforce.soap.partner.QueryResult)10 SaveResult (com.salesforce.soap.partner.SaveResult)9 MessageElement (org.apache.axis.message.MessageElement)7 DescribeSObject (com.salesforce.soap.partner.DescribeSObject)5 UpsertResult (com.salesforce.soap.partner.UpsertResult)3 OMElement (org.apache.axiom.om.OMElement)3 Create (com.salesforce.soap.partner.Create)2 DeleteResult (com.salesforce.soap.partner.DeleteResult)2 ID (com.salesforce.soap.partner.ID)2 Update (com.salesforce.soap.partner.Update)2 Upsert (com.salesforce.soap.partner.Upsert)2 HashMap (java.util.HashMap)2 Delete (com.salesforce.soap.partner.Delete)1 DeleteResponse (com.salesforce.soap.partner.DeleteResponse)1 DescribeSObjectResult (com.salesforce.soap.partner.DescribeSObjectResult)1