Thursday, December 27, 2012

Future Annotation:

Future Annotation:

Use the future annotation to identify methods that are executed asynchronously. When you specify future, the method executes when Salesforce has available resources.
For example, you can use the future annotation when making an asynchronous Web service callout to an external service. Without the annotation, the Web service callout is made from the same thread that is executing the Apex code, and no additional processing can occur until the callout is complete (synchronous processing).
Methods with the future annotation must be static methods, and can only return a void type.
public with sharing class DF12FutureController {

    public Contact customer {
        get {
            return [
                SELECT Id, FirstName, LastName, Email
                FROM Contact
                WHERE Id = :ApexPages.currentPage().getParameters().get('id')
                LIMIT 1
            ];
        }
        private set;
    }

    public PageReference createSampleContactIfNecessary() {
        if (ApexPages.currentPage().getParameters().get('id') == null) {
            Contact c = new Contact();
            User currentUser = [
                SELECT Id, FirstName, LastName, Email
                FROM User
                WHERE Id = :UserInfo.getUserId()
            ];
            List<Contact> cList = [
                SELECT Id, FirstName, LastName, Email
                FROM Contact
                WHERE Email = :currentUser.Email
            ];
            if (cList != null && cList.size() > 0) {
                c = cList[0];
            } else {
                c.FirstName = currentUser.FirstName;
                c.LastName = currentUser.LastName;
                c.Email = currentUser.Email;
                insert c;
            }
            PageReference pr = ApexPages.currentPage().setRedirect(true);
            pr.getParameters().put('id', c.id);
            return pr;
        }
        return null;
    }

    @RemoteAction
    public static String requestAllInvoices(String customerId) {
        sendAllInvoices(customerId);
        return 'All invoices have been requested.';
    }

    @future
    private static void sendAllInvoices(String customerId) {
        EmailHelper.emailCustomerInvoices(customerId);
    }

    @isTest
    private static void testCreateSampleContactIfNecessary() {
        DF12FutureController con = new DF12FutureController();
        PageReference pr = Page.DF12Future;
        Test.setCurrentPageReference(pr);
        con.createSampleContactIfNecessary();
        System.assertEquals(1, ApexPages.currentPage().getParameters().size(), 'Page should have the id param.');
    }

    @isTest
    private static void testRequestAllInvoices() {
        Contact c = new Contact(LastName = 'Smith', FirstName = 'Joe', Email = 'test@test.test.test.test');
        insert c;
        String response = DF12FutureController.requestAllInvoices(c.id);
        System.assertEquals('All invoices have been requested.', response, 'The wrong response was returned.');
    }

    @isTest
    private static void testGetCustomer() {
        DF12FutureController con = new DF12FutureController();
        PageReference pr = Page.DF12Future;
        Test.setCurrentPageReference(pr);
        con.createSampleContactIfNecessary();
        System.assertEquals(con.customer.Id, ApexPages.currentPage().getParameters().get('id'), 'Customer retrieved was not correct.');
    }

}
<apex:page docType="html-5.0" controller="DF12FutureController" action="{!createSampleContactIfNecessary}" showHeader="false" standardStylesheets="false">
<apex:composition template="DF12Template">

    <apex:define name="pageTitle">DF '12: @future Example</apex:define>

    <apex:define name="header">
        <h1 class="pageTitle">@future Example</h1>
    </apex:define>

    <apex:define name="body">
        <p>A sample contact has been created with the following information:</p>
        <dl>
            <dt>Contact Id:</dt>
            <dd>{!customer.Id}</dd>
            <dt>Contact First Name:</dt>
            <dd>{!customer.FirstName}</dd>
            <dt>Contact Last Name:</dt>
            <dd>{!customer.LastName}</dd>
            <dt>Contact Email:</dt>
            <dd>{!customer.Email}</dd>
        </dl>
        <p>To see the @future method in action, click the button below. (This will send a sample email to the contact above.)</p>
        <button type="button" onclick="DF12Examples.requestInvoices('{!customer.Id}');">Request Invoices</button>
        <div class="pageMask" id="pageMask"></div>
        <div class="pageWait" id="pageWait">working...</div>
    </apex:define>

    <apex:define name="pageScripts">
        <script>

            // startTime and endTime are only being created for logging purposes, but
            // note that I am initializing their values to Date objects. this is so
            // JavaScript doesn't have to guess what kind of variables they are
            // (and therefore, doesn't have to change their datatype mid-execution).
            // this is a best practice for all JS variable declarations to help with
            // performance.
            DF12Examples.startTime = new Date();
            DF12Examples.endTime = new Date();

            // this is the function that gets called when the button is clicked.
            DF12Examples.requestInvoices = function(customerId) {
                document.getElementById("pageMask").style.display = "block";
                document.getElementById("pageWait").style.display = "block";
                DF12Examples.startTime = Date.now();
                DF12FutureController.requestAllInvoices(customerId, DF12Examples.handleResponse);
            };

            // this is the function that gets called when the apex method tagged
            // with the @RemoteAction annotation is completed.
            DF12Examples.handleResponse = function(results, event) {
                document.getElementById("pageMask").style.display = "none";
                document.getElementById("pageWait").style.display = "none";
                if (event.status) {
                    alert("Congratulations! Everything worked! The response from the server is:\n\n" + results);
                }
                DF12Examples.endTime = Date.now();
                if (console) {
                    console.log("elapsed time: " + (DF12Examples.endTime - DF12Examples.startTime) + "ms");
                }
            }

        </script>
    </apex:define>

</apex:composition>
</apex:page>


No comments:

Post a Comment