All pastes #450111 Raw Edit

Miscellany

public java v1 · immutable
·published 2007-04-20 16:38 UTC
rendered paste body
/* * Created on Dec 6, 2005 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */package sftest;import java.io.BufferedReader;import java.io.IOException;import com.sforce.soap.enterprise.sobject.*;import com.sforce.soap.enterprise.*;import com.sforce.soap.enterprise.Error;import javax.xml.rpc.*;import org.apache.log4j.Level;import org.apache.log4j.Logger;import java.rmi.*;import com.sforce.soap.enterprise.fault.*;/** * @author dcarroll * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */public class quickstart {    // create a class scope reference to the service object    private SoapBindingStub binding = null;    private LoginResult lr = null; // maintain the login results    private Account[] _accounts = null;    static BufferedReader rdr = new BufferedReader(            new java.io.InputStreamReader(System.in));    public static void main(String[] args) {        Logger.getLogger("org.apache.axis").setLevel(Level.OFF);        new quickstart();    }    public quickstart() {        try {                        Order order = new Order();                        order.setAddress1("--------");            order.setAddress2("---");            order.setCity("New York");            order.setState("NY");            order.setAmount(19.99d);            order.setComplete(true);            order.setCountry("USA");            order.setEmail("gharding2@gmail.com");            order.setFirstname("Grant");            order.setLastname("Harding");            order.setOrderTimestamp(new java.util.Date());            order.setZip("10021");                                                                        //mainLoop();            doLogin();            //getOpps();            //getCmp();            Lead lead = addOrFetchLead(order);            System.out.println("lead created or fetched");                                                            if (lead.getIsConverted() == null || !lead.getIsConverted()) {                // convert, but don't create opp                convertLead(lead);            }            System.out.println("Lead converted or something");                                                Product2 pr = findProductByCode(Integer.toString(order.getSchedule().getProduct().getClassId()));            System.out.println("Found product");                                    // create new opp            String oppName = order.getFirstname();            if (order.getLastname() != null) {                oppName += " "+order.getLastname();            }            oppName += " - "+order.getSchedule().getProduct().getTitle();                            Opportunity opp = new Opportunity();            opp.setAccountId(lead.getConvertedAccountId());            opp.setName(oppName);            opp.setStageName("Pending");            opp.setCloseDate(new java.util.Date());            opp.setCurrencyIsoCode("USD");                        // save it            SaveResult[] sr = binding.create(new SObject[] {opp});            if (sr.length > 0 && sr[0].isSuccess()) {                SObject[] so = binding.retrieve("Id, Pricebook2Id", "Opportunity", new String[] {sr[0].getId()});                if (so.length > 0) {                    opp = (Opportunity) so[0];                }            }            addProductToOpp(opp, pr, order);                        //bindLeadToCampaign("00Q6000000DykeI","701300000003HWBAA2");        } catch (Exception e) {            System.out.println(e.getMessage());        }    }        private void addProductToOpp(Opportunity opp, Product2 pr, Order o) {        if (lr == null) {            System.out.println("not logged in?");            return;        }                String pbId = opp.getPricebook2Id();        String pbEntryId = getPricebookEntryIdFromPricebook(pr, pbId);        OpportunityLineItem oli = new OpportunityLineItem();        oli.setOpportunityId(opp.getId());        oli.setQuantity(1d);        oli.setPricebookEntryId(pbEntryId);        oli.setServiceDate(o.getSchedule().getDate());        oli.setTotalPrice(o.getSchedule().getProduct().getPrice());        //oli.setCurrencyIsoCode("USD");        try {            SaveResult[] sr = binding.create(new SObject[] {oli});            if (sr.length > 0) { }        } catch (Exception e) {            e.printStackTrace();        }                    }        private String getPricebookEntryIdFromPricebook(Product2 pr, String pricebookId) {        if (lr == null) {            System.out.println("not logged in?");            return null;        }        // create a variable to hold the query result        QueryResult qr = null;        // call the query saving the results in qr        try {            qr = binding                    .query("select Id,UseStandardPrice from PricebookEntry where Product2Id = '"+pr.getId()+"'");        } catch (UnexpectedErrorFault uef) {            System.out.println(uef.getExceptionMessage() + "\n\n");            return null;        } catch (Exception e) {            e.printStackTrace();            System.out.println("\n\n");            return null;        }        // always a good idea        if (qr != null) {            SObject[] records = qr.getRecords();                        if (records.length > 1) {                System.out.println("Got more than one PricebookEntry");            } else {                return ((PricebookEntry)records[0]).getId();            }        }                        return null;    }        private Product2 findProductByCode(String code) {        if (lr == null) {            System.out.println("not logged in?");            System.exit(0);        }        // create a variable to hold the query result        QueryResult qr = null;        // call the query saving the results in qr        try {            qr = binding                    .query("select Id from Product2 where ProductCode = '"+code+"'");        } catch (UnexpectedErrorFault uef) {            System.out.println(uef.getExceptionMessage() + "\n\n");            return null;        } catch (Exception e) {            e.printStackTrace();            System.out.println("\n\n");            return null;        }        // always a good idea        if (qr != null) {            SObject[] records = qr.getRecords();                        if (records.length > 0) {                return (Product2)records[0];            }        }        return null;    }        private Lead addOrFetchLead(Order o) {        Lead lead = null;                if (lr == null) {            System.out.println("not logged in?");            System.exit(0);        }                QueryResult qr = null;        try {            qr = binding.query("Select Id,IsConverted,ConvertedAccountId,ConvertedContactId,IsDeleted from Lead WHERE email = '"+o.getEmail()+"' AND IsDeleted = false");                    } catch (UnexpectedErrorFault uef) {            System.out.println("I think wer're tying here");            System.out.println(uef.getExceptionMessage() + "\n\n");            return null;        } catch (Exception e) {            e.printStackTrace();            System.out.println("\n\n");            return null;        }        System.out.println("made it here okay");        // always a good idea        if (qr != null && qr.getSize() > 0) {            SObject[] records = qr.getRecords();            System.out.println("here 4?");            if (records.length > 1) {                System.out.println("More than one lead for this email address??");            }                        Lead[] leads = new Lead[records.length];            // we can loop through the returned records            for (int i = 0; i < records.length; i++) {                // Because we asked for accounts we will convert                // the SObject for each record into an Account object                Lead t = (Lead) records[i];                leads[i] = t;                // Now we can access any of the fields we had in the query                // select clause directly from the account variable                System.out.println("here 3?");            }                        if (leads.length > 0) {                lead = leads[0];            }                        System.out.println("");        }                if (lead == null) {            lead = new Lead();        }                // update information in lead        if (lead.getFirstName() == null) {            lead.setFirstName(o.getFirstname());        }                if (lead.getLastName() == null) {            lead.setLastName(o.getLastname());        }                if (lead.getEmail() == null) {            lead.setEmail(o.getEmail());        }                if (lead.getPhone() == null) {            // fuck        }                if (lead.getStreet() == null) {            lead.setStreet(o.getAddress1() + (o.getAddress2() != null ? ", " + o.getAddress2() : ""));        }                if (lead.getState() == null) {            lead.setState(o.getState());        }                if (lead.getCountry() == null) {            lead.setCountry(o.getCountry());        }                if (lead.getPostalCode() == null) {            lead.setPostalCode(o.getZip());        }                lead.setCompany(o.getFirstname() + " " + o.getLastname());                System.out.println("here 2?");                SaveResult[] sr = null;        // save or update        try {            if (lead.getId() == null) {                sr = binding.create(new SObject[] {lead});            } else {                sr = binding.update(new SObject[] {lead});            }        } catch (Exception e) {            e.printStackTrace();        }        if (sr != null && sr.length == 1 && sr[0].isSuccess()) {            lead.setId(sr[0].getId());        }                System.out.println("here?");                return lead;    }                    private String[] getConvertedStatuses() {                String q = "Select Id, MasterLabel from LeadStatus where IsConverted=true";        if (lr == null) return null;                        QueryResult qr = null;        try {            qr = binding.query(q);                    } catch (UnexpectedErrorFault uef) {            System.out.println(uef.getExceptionMessage() + "\n\n");            return null;        } catch (Exception e) {            e.printStackTrace();            System.out.println("\n\n");            return null;        }                if (qr != null && qr.getSize() > 0) {            SObject[] records = qr.getRecords();            String[] str = new String[records.length];            //LeadStatus[] leads = new LeadStatus[records.length];            // we can loop through the returned records            for (int i = 0; i < records.length; i++) {                // Because we asked for accounts we will convert                // the SObject for each record into an Account object                LeadStatus t = (LeadStatus) records[i];                str[i] = t.getMasterLabel();                // Now we can access any of the fields we had in the query                // select clause directly from the account variable            }            return str;                    }        return null;    }        private Boolean convertLead (Lead lead) {        return convertLead(lead, null, null, false, true, null, null, false);    }        private Boolean convertLead (Lead lead, String contactId, String accountId, boolean overWriteLeadSource, boolean doNotCreateOpportunity, String opportunityName, String convertedStatus, boolean sendEmailToOwner){        String leadId = lead.getId();        getConvertedStatuses();  LeadConvert leadConvert = new LeadConvert();  leadConvert.setLeadId(leadId);  leadConvert.setContactId(contactId);  leadConvert.setAccountId(accountId);  leadConvert.setOverwriteLeadSource(overWriteLeadSource);  leadConvert.setDoNotCreateOpportunity(doNotCreateOpportunity);  leadConvert.setOpportunityName(opportunityName);  leadConvert.setConvertedStatus("Converted Lead");  leadConvert.setSendNotificationEmail(sendEmailToOwner);  LeadConvertResult[] lcr = null;  try {    lcr = binding.convertLead(new LeadConvert[] {leadConvert});    for (int i=0; i<lcr.length; i++) {      if (lcr[i].isSuccess()) {        System.out.println("Conversion succeeded.\n");        LeadConvertResult result = lcr[i];                lead.setConvertedAccountId(result.getAccountId());        lead.setConvertedContactId(result.getContactId());                System.out.println("The new contact id is: " + result.getContactId());      } else {        System.out.println("The conversion failed because: " + lcr[i].getErrors(0).getMessage());      }    }  } catch (UnexpectedErrorFault e) {    System.out.println("Unexpected error encountered:\n\n" + e.getExceptionMessage());    return Boolean.FALSE;  } catch (RemoteException e) {    System.out.println("Remote exception encountered:\n\n" + e.getMessage());    return Boolean.FALSE;  }  return Boolean.TRUE;}        private void bindLeadToCampaign(String leadId, String cmpId) {        if (lr == null) {            System.out.println("not logged in?");            System.exit(0);        }        // create campaign member        CampaignMember member = new CampaignMember();        member.setCampaignId(cmpId);        member.setLeadId(leadId);        // create a variable to hold the query result        QueryResult qr = null;        // call the query saving the results in qr        try {            binding.create(new SObject[] {member});        } catch (UnexpectedErrorFault uef) {            System.out.println(uef.getExceptionMessage() + "\n\n");            return;        } catch (Exception e) {            e.printStackTrace();            System.out.println("\n\n");            return;        }        System.out.println("Campaign added to lead!");    }    private void doGetAccounts() {        // check to see if we are already logged in        if (lr == null) {            System.out.println("Run the login sample before the others.\n");            return;        }        // create a variable to hold the query result        QueryResult qr = null;        // call the query saving the results in qr        try {            qr = binding                    .query("select Name, numberOfEmployees, Id, Industry from Account");        } catch (UnexpectedErrorFault uef) {            System.out.println(uef.getExceptionMessage() + "\n\n");            return;        } catch (Exception e) {            e.printStackTrace();            System.out.println("\n\n");            return;        }        // always a good idea        if (qr != null) {            SObject[] records = qr.getRecords();            _accounts = new Account[records.length];            // we can loop through the returned records            for (int i = 0; i < records.length; i++) {                // Because we asked for accounts we will convert                // the SObject for each record into an Account object                Account account = (Account) records[i];                _accounts[i] = account;                // Now we can access any of the fields we had in the query                // select clause directly from the account variable                System.out.print(new Integer(i).toString() + ". ");                System.out.print(account.getName() + " - ");                System.out.println(account.getId());            }            System.out.println("");        }    }        private void getOpps() {        if (lr == null) {            System.out.println("not logged in?");            System.exit(0);        }        // create a variable to hold the query result        QueryResult qr = null;        // call the query saving the results in qr        try {            qr = binding                    .query("select Name, Id, Type, StageName from Opportunity");        } catch (UnexpectedErrorFault uef) {            System.out.println(uef.getExceptionMessage() + "\n\n");            return;        } catch (Exception e) {            e.printStackTrace();            System.out.println("\n\n");            return;        }        // always a good idea        if (qr != null) {            SObject[] records = qr.getRecords();            Opportunity[] opps = new Opportunity[records.length];            // we can loop through the returned records            for (int i = 0; i < records.length; i++) {                // Because we asked for accounts we will convert                // the SObject for each record into an Account object                Opportunity opp = (Opportunity) records[i];                opps[i] = opp;                // Now we can access any of the fields we had in the query                // select clause directly from the account variable                System.out.print(new Integer(i).toString() + ". ");                System.out.print(opp.getName() + " - ");                System.out.println(opp.getId());            }            System.out.println("");        }            }        private void getCmp() {        String cmpId = "701300000003HWBAA2";        if (lr == null) {            System.out.println("not logged in?");            System.exit(0);        }        // create a variable to hold the query result        QueryResult qr = null;        // call the query saving the results in qr        try {            qr = binding                    .query("select Name, Id, Type, StageName from Opportunity");        } catch (UnexpectedErrorFault uef) {            System.out.println(uef.getExceptionMessage() + "\n\n");            return;        } catch (Exception e) {            e.printStackTrace();            System.out.println("\n\n");            return;        }        // always a good idea        if (qr != null) {            SObject[] records = qr.getRecords();            Opportunity[] opps = new Opportunity[records.length];            // we can loop through the returned records            for (int i = 0; i < records.length; i++) {                // Because we asked for accounts we will convert                // the SObject for each record into an Account object                Opportunity opp = (Opportunity) records[i];                opps[i] = opp;                // Now we can access any of the fields we had in the query                // select clause directly from the account variable                System.out.print(new Integer(i).toString() + ". ");                System.out.print(opp.getName() + " - ");                System.out.println(opp.getId());            }            System.out.println("");        }            }    private void updateAccount(String accountID, String newAccountName) {        // First we will create an account object array, all calls are batch        // ours is a single element batch        SObject[] accounts = new Account[1];        // instantiate the new account object        Account account = new Account();        Account oldAccount = _accounts[new Integer(accountID).intValue()];        // set the id, the id must always be set for an update        account.setId(oldAccount.getId());        // set the new name of the account        account.setName(newAccountName);        // add the account to the array of objects        accounts[0] = account;        // we are now ready to update the record        // create an array for the results        SaveResult[] saveResults = null;        try {            saveResults = binding.update(accounts);        } catch (UnexpectedErrorFault uef) {            System.out.println(uef.getExceptionMessage() + "\n\n");            return;        } catch (Exception e) {            e.printStackTrace();            System.out.println("\n\n");            return;        }        if (saveResults == null)            return;        for (int i = 0; i < saveResults.length; i++) {            // we will create a separate save result object for clarity            SaveResult saveResult = saveResults[i];            // check to see if the first update was a success            if (saveResult.isSuccess()) {                // the id that we passed should be the one we get back.                System.out.println("Update account with id: "                        + saveResult.getId());            } else {                // an error occurred on this record                Error error = saveResult.getErrors()[0];                System.out.println(error.getMessage());            }        }    }    private void doLogin() {        String userName = "----";        String pwd = "----";        try {            SforceServiceLocator sf = new SforceServiceLocator();            sf.setSoapEndpointAddress("https://www.salesforce.com/services/Soap/c/9.0");            binding = (SoapBindingStub) sf.getSoap();        } catch (ServiceException ex1) {            System.out.println(ex1.getMessage());            return;        }        try {            lr = binding.login(userName, pwd);        } catch (UnexpectedErrorFault ex2) {            System.out.println(ex2.getExceptionMessage() + "\n\n");            return;        } catch (LoginFault ex2) {            System.out.println(ex2.getExceptionMessage() + "\n\n");            return;        } catch (RemoteException ex2) {            System.out.println(ex2.getMessage() + "\n\n");            return;        }        System.out.println("Login was successfull.");        System.out.print("The returned session id is: ");        System.out.println(lr.getSessionId());        System.out.print("Your logged in user id is: ");        System.out.println(lr.getUserId() + " \n\n");        // on a successful login, you should always set up your session id        // and the url for subsequent calls        // reset the url endpoint property, this will cause subsequent calls        // to made to the serverURL from the login result        binding._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY, lr                .getServerUrl());        // create a session head object        SessionHeader sh = new SessionHeader();        // set the sessionId property on the header object using        // the value from the login result        sh.setSessionId(lr.getSessionId());        // add the header to the binding stub        String sforceURI = new SforceServiceLocator().getServiceName()                .getNamespaceURI();        binding.setHeader(sforceURI, "SessionHeader", sh);        return;    }}