Wednesday, 22 February 2017

Unit Test for Salesforce Rest API



  • Any test class should be annotated with @isTest annotation.
  • Test method will have an identifier as testmethod as part of the method declaration.
  • To test Rest api RestRequest and RestResponse object to be instantiated and added in RestContext instance
  • Invoke Rest Api class to get back the response.

Example shown below:


@isTest
private class RestApiSample_Test {

    static testMethod void testGetMethod() {
        RestRequest req = new RestRequest(); 
        RestResponse res = new RestResponse(); 
        
        req.requestURI = '/services/apexrest/RestApiSample'; 
        req.addParameter('userName', 'Raghav');
        req.httpMethod = 'GET';

        RestContext.request = req;
        RestContext.response = res;

        String msg = RestApiSample.getWelcomeMessage();
        system.assertEquals(msg, 'Welcome Raghav');
    }
}

Saturday, 28 January 2017

Salesforce Apex Class as REST api Get


Salesforce REST Api as Apex Class using Get Method

Salesforce enables the programmer to expose Apex class and methods through REST architecture.

To define an apex class as REST resource @RestResource annotation is used.

@RestResource(urlMapping='/RestApiSample/*')

urlMapping is used to provide url path through which the class can be accessed.

Rest api supports different methods like Get, Post

To define a method as Get, we can use @HttpGet annotation.

RestContext class contains the RestRequest and RestResponse objects.

We can get the parameter using RestContext.

Full code example is shared below:



Wednesday, 25 June 2014

Send email using Java Mail API


          Java Mail API (Application Programming Interface) can be used to send email through Java programs. Here, in this blog code examples are provided with explanation on how to send email using smtp protocol with gmail server.

Dependency Jar:

          java-mail-1.4.4.jar can be downloaded from any site. 1.4.4 is the java mail api version referred by below program for execution.

Email Code:

          Below steps are just the guidance for any programmer and it is not mandatory to follow same methodical approach.
  • Create SendEmail.java with main method and sendEmail method. sendEmail method accepts below parameters and implement logic.

                     # fromEmail - String
                     # toEmail - String array (For more than one recipient).
                     # subject - String (Contains email subject)
                     # messageContent - String (Contains email message body content)

  • Load all properties required for sending email.

              Properties properties = new Properties();
                properties.put("mail.smtp.host","smtp.gmail.com");
                properties.put("mail.smtp.port", 587);
                properties.put("mail.smtp.auth",true);
                properties.put("mail.smtp.starttls.enable",true);

  • Creates Javax mail Session object instance by passing required authentication information or default information as required by email server. Sending email through gmail smtp server, need to pass across an authentication email user and password.
session = Session.getDefaultInstance(properties, 
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(<Email User ID>, <Email Password>);
}
});                   

  • Create MimeMessage and add receipent, subject and message content. Using Transport class send email by passing MimeMessage instance as parameter.

     // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);
    
                    // Set From: header field of the header.
    message.setFrom(new InternetAddress(fromEmail));
   
                    // Set To: header field of the header.
    for(int index=0; index < to.length; index++) {
message.addRecipient(Message.RecipientType.TO,new InternetAddress(toEmail[index]));
    }

    // Set Subject: header field
    message.setSubject(subject);

    // Set Message Content
    message.setContent(messageContent, "text/html");

  // Send message
  Transport.send(message);
  • In main method, create instance of SendEmail class and call sendEmailMethod with parameters. 
// Sender's email ID needs to be mentioned
String from = "<Provide from Email id>";
// Recipient's email ID needs to be mentioned in an array
String[] to = {"<Receipent 1 Email ID", "Receipent 2 Email ID"};
// Email Subject
String subject = "This is the Subject Line!";
// Email Message Content
String messageContent = "<h1>This is the actual Message</h1>";

// Call Email send method.
SendEmail se = new SendEmail();
try {
se.sendEmailMessage(from, to, subject, messageContent);
} catch(Exception excep) {
excep.printStackTrace();
}

  • Include java-mail-1.4.4.jar in class path for compiling and executing the program in command line.