5

I need to analyze the login ip ranges for profiles across multiple orgs on a frequent basis. Previously I've been accomplishing this with an Ant retrieve call to get all the profiles and parsing the XML results in python.

I'm trying to determine if there's a more efficient way to accomplish this, either in Python directly (beatbox and the python salesforce toolkit do not support the metadata API, but the Force AppEngine toolkit might), or, as a last resort, in Java if necessary. Since it's just a retrieve, the process of using Ant seems like overkill.

Alternatively, if you know of a scriptable way (without screen scraping) to grab the setup audit log data, that could work for this too.

4 Answers 4

3

I haven't done this in Python, but I have in Java - here's some sample code:

// Set up MetadataConnection from an EnterpriseConnection as in
// http://www.salesforce.com/us/developer/docs/api_meta/Content/meta_quickstart_java_sample.htm
// Ranges should be like this
// String[][] ranges = { 
//     { "1.0.0.0", "1.255.255.255" }, 
//     { "3.0.0.0", "3.255.255.255" } 
// };
public static void setLoginIpRanges(MetadataConnection metadataConnection, 
        String profileName, String[][] ranges) throws ConnectionException {
    private static long longestWaitMilliSecs = 16000; // Read from config, whatever
    try {
        ProfileLoginIpRange[] loginIpRanges = new ProfileLoginIpRange[ranges.length];

        for (int i = 0; i < ranges.length; i++) {
            loginIpRanges[i] = new ProfileLoginIpRange();
            loginIpRanges[i].setStartAddress(ranges[i][0]);
            loginIpRanges[i].setEndAddress(ranges[i][1]);
        }

        Profile profile = new Profile();
        profile.setLoginIpRanges(loginIpRanges);
        profile.setFullName(profileName);

        UpdateMetadata updateMetadata = new UpdateMetadata();
        updateMetadata.setMetadata(profile);
        updateMetadata.setCurrentName(profileName);

        AsyncResult[] ars = metadataConnection
                .update(new UpdateMetadata[] { updateMetadata });
        AsyncResult asyncResult = ars[0];

        long waitTimeMilliSecs = 1000;
        while (!asyncResult.isDone() && waitTimeMilliSecs <= longestWaitMilliSecs) {
            Thread.sleep(waitTimeMilliSecs);

            waitTimeMilliSecs *= 2;
            asyncResult = metadataConnection
                    .checkStatus(new String[] { asyncResult.getId() })[0];
            System.out.println("Status is: " + asyncResult.getState());
        }

        if (asyncResult.getState() != AsyncRequestState.Completed) {
            System.out.println(asyncResult.getStatusCode() + " msg: "
                    + asyncResult.getMessage());
        }
    } catch (InterruptedException ie) {
        ie.printStackTrace();
    } catch (ConnectionException ce) {
        ce.printStackTrace();
    }
}
2
  • a retrieve would be similar to the update you have here then?
    – cji
    Commented Aug 21, 2013 at 20:53
  • Ah - no - unfortunately, you're stuck with the file-based retrieve. There is a Java code sample at that link, and another one (that looks a bit better) here.
    – metadaddy
    Commented Aug 22, 2013 at 19:18
3

I have recently automated whitelisting the Login Ip range in profiles through metadata API, here is my code:

import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.metadata.FileProperties;
import com.sforce.soap.metadata.ListMetadataQuery;
import com.sforce.soap.metadata.Metadata;
import com.sforce.soap.metadata.MetadataConnection;
import com.sforce.soap.metadata.Profile;
import com.sforce.soap.metadata.ProfileLoginIpRange;
import com.sforce.ws.ConnectionException;


public class MetadataSample {

    private MetadataConnection metadataconnection;

    private void run() throws ConnectionException, Exception
    {
        login();
        String[][]ranges = {{"1.2.3.0","1.2.3.255"}, { "2.3.4.0", "2.3.4.255" } };

         ListMetadataQuery query = new ListMetadataQuery();
         query.setType("Profile");
         double asOfVersion = 39.;
         FileProperties[] lmr = metadataconnection.listMetadata(new ListMetadataQuery[] {query}, asOfVersion);
         if (lmr != null)
         {
             for (FileProperties n : lmr) {

             System.out.println("Component fullName: " + n.getFullName());

             setLoginIpRanges(n.getFullName(),ranges);
         }}
    //  setLoginIpRanges("Standard",ranges);

    }

    public static void main(String[] args) throws Exception
    {
        MetadataSample samples1 = new MetadataSample();
        samples1.run();
    }


    private void login() throws ConnectionException
    {
         String username = System.getenv("");
         String password = System.getenv("");
         ConnectorConfig config = new ConnectorConfig();   
         config.setUsername(username);
         config.setPassword(password);

         EnterpriseConnection connection;
         connection = Connector.newConnection(config);
         ConnectorConfig metadataConfig = new ConnectorConfig();
         metadataConfig.setSessionId(connection.getSessionHeader().getSessionId());
         metadataconnection = com.sforce.soap.metadata.Connector.newConnection(metadataConfig);

    }

    private void setLoginIpRanges(String string,String[][] ranges) throws ConnectionException, InterruptedException
    {
        ProfileLoginIpRange[] loginIpRanges = new ProfileLoginIpRange[ranges.length];

        for (int i =0;i<ranges.length; i++)
        {
            loginIpRanges[i] = new ProfileLoginIpRange();
            loginIpRanges[i].setStartAddress(ranges[i][0]);
            loginIpRanges[i].setEndAddress(ranges[i][1]);

        }


        Profile profile = new Profile();
        profile.setLoginIpRanges(loginIpRanges);

        profile.setFullName(string);



com.sforce.soap.metadata.SaveResult[] results = metadataconnection.updateMetadata( new Metadata[] {profile}); 

for (com.sforce.soap.metadata.SaveResult r : results)
{
    if (r.isSuccess())
    {
        System.out.println("Updated profile: " + r.getFullName());
    } else 
    {
        System.out.println("Errors were encountered while creating " + r.getFullName());
        for (com.sforce.soap.metadata.Error e : r.getErrors())
        {
            System.out.println("Error message: " + e.getMessage());
            System.out.println("Status code: " + e.getStatusCode());
        }
    }
}


    }


}
0

Please find this git hub project which is python module. This one simplifies all your login and metadata retrieval from salesforce: https://github.com/sun30nil/python-SalesforceMetadataAPISupport

1
  • 2
    Welcome to SFSE. On this site we typically don't allow link-only answers. It would help to expand on how this answers the question.
    – martin
    Commented Oct 31, 2015 at 14:55
0

This code retrieves existing IP ranges and inserts new set of IP ranges to a profile.


public class UpdateIPRangeInProfile {
    public static void main(String[] args) throws ConnectionException {

        String[][] ranges = { { "7.0.0.0", "7.255.255.255" }, { "8.0.0.0", "8.255.255.255" } };
        String profileName = "TestIPRangeUpdates";
        MetadataConnection metadataConnection = MetadataLoginUtility.login();
        ProfileLoginIpRange[] existingIPRanges = new ProfileLoginIpRange[40];

        try {
            ReadResult readResult = metadataConnection
                    .readMetadata("Profile", new String[] {
                            "TestIPRangeUpdates" });
            Metadata[] metadataRecords = readResult.getRecords();
            System.out.println("Number of component info returned: "
                    + metadataRecords.length);
            for (Metadata eachRecord : metadataRecords) {
                if (eachRecord != null) {
                    Profile obj = (Profile) eachRecord;
                    System.out.println("Custom object full name: "
                            + obj.getFullName() + obj.getLoginIpRanges());
                    existingIPRanges = obj.getLoginIpRanges();

                } else {
                    System.out.println("Empty metadata.");
                }
            }
        } catch (ConnectionException ce) {
            ce.printStackTrace();
        }

        try {
            List<ProfileLoginIpRange> rangeList = new ArrayList<ProfileLoginIpRange>();


            for (int i = 0; i < ranges.length; i++) {
                ProfileLoginIpRange newRange = new ProfileLoginIpRange();
                newRange.setStartAddress(ranges[i][0]);
                newRange.setEndAddress(ranges[i][1]);
                rangeList.add(newRange);
            }
            for(ProfileLoginIpRange eachIPRange : existingIPRanges) {
                rangeList.add(eachIPRange);
            }
            ProfileLoginIpRange[] loginIpRanges = new ProfileLoginIpRange[rangeList.size()];
            loginIpRanges = (rangeList.toArray(loginIpRanges));

            Profile profile = new Profile();
            profile.setLoginIpRanges(loginIpRanges);
            profile.setFullName(profileName);

            UpsertResult[] saveResults = metadataConnection
                    .upsertMetadata(new Metadata[] { profile });


            for (com.sforce.soap.metadata.UpsertResult result : saveResults) {
                if (result.isSuccess()) {
                    System.out.println("Updated profile: " + result.getFullName());
                } else {
                    System.out.println("Errors encountered while updating profile " + result.getFullName());
                    for (com.sforce.soap.metadata.Error eachError : result.getErrors()) {
                        System.out.println("Error message: " + eachError.getMessage());
                        System.out.println("Status code: " + eachError.getStatusCode());
                    }
                }

            }
        } catch (ConnectionException ce) {
            ce.printStackTrace();
        }
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .