Rename samples subdirectories

This commit is contained in:
Joshua Peek
2012-07-23 15:52:49 -05:00
parent 314f0e4852
commit 7b6caa0f6c
273 changed files with 2952 additions and 2955 deletions

458
samples/Apex/ArrayUtils.cls Normal file
View File

@@ -0,0 +1,458 @@
/* ============================================================
* This code is part of the "apex-lang" open source project avaiable at:
*
* http://code.google.com/p/apex-lang/
*
* This code is licensed under the Apache License, Version 2.0. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
* ============================================================
*/
global class ArrayUtils {
global static String[] EMPTY_STRING_ARRAY = new String[]{};
global static Integer MAX_NUMBER_OF_ELEMENTS_IN_LIST {get{return 1000;}}
global static List<String> objectToString(List<Object> objects){
List<String> strings = null;
if(objects != null){
strings = new List<String>();
if(objects.size() > 0){
for(Object obj : objects){
if(obj instanceof String){
strings.add((String)obj);
}
}
}
}
return strings;
}
global static Object[] reverse(Object[] anArray) {
if (anArray == null) {
return null;
}
Integer i = 0;
Integer j = anArray.size() - 1;
Object tmp;
while (j > i) {
tmp = anArray[j];
anArray[j] = anArray[i];
anArray[i] = tmp;
j--;
i++;
}
return anArray;
}
global static SObject[] reverse(SObject[] anArray) {
if (anArray == null) {
return null;
}
Integer i = 0;
Integer j = anArray.size() - 1;
SObject tmp;
while (j > i) {
tmp = anArray[j];
anArray[j] = anArray[i];
anArray[i] = tmp;
j--;
i++;
}
return anArray;
}
global static List<String> lowerCase(List<String> strs){
List<String> returnValue = null;
if(strs != null){
returnValue = new List<String>();
if(strs.size() > 0){
for(String str : strs){
returnValue.add(str == null ? null : str.toLowerCase());
}
}
}
return returnValue;
}
global static List<String> upperCase(List<String> strs){
List<String> returnValue = null;
if(strs != null){
returnValue = new List<String>();
if(strs.size() > 0){
for(String str : strs){
returnValue.add(str == null ? null : str.toUpperCase());
}
}
}
return returnValue;
}
global static List<String> trim(List<String> strs){
List<String> returnValue = null;
if(strs != null){
returnValue = new List<String>();
if(strs.size() > 0){
for(String str : strs){
returnValue.add(str == null ? null : str.trim());
}
}
}
return returnValue;
}
global static Object[] mergex(Object[] array1, Object[] array2){
if(array1 == null){ return array2; }
if(array2 == null){ return array1; }
Object[] merged = new Object[array1.size() + array2.size()];
for(Integer i = 0; i < array1.size(); i++){
merged[i] = array1[i];
}
for(Integer i = 0; i < array2.size(); i++){
merged[i+array1.size()] = array2[i];
}
return merged;
}
global static SObject[] mergex(SObject[] array1, SObject[] array2){
if(array1 == null){ return array2; }
if(array2 == null){ return array1; }
if(array1.size() <= 0){ return array2; }
List<SObject> merged = new List<SObject>();
for(SObject sObj : array1){ merged.add(sObj); }
for(SObject sObj : array2){ merged.add(sObj); }
return merged;
}
global static Boolean isEmpty(Object[] objectArray){
if(objectArray == null){
return true;
}
return objectArray.size() == 0;
}
global static Boolean isEmpty(SObject[] objectArray){
if(objectArray == null){
return true;
}
return objectArray.size() == 0;
}
global static Boolean isNotEmpty(Object[] objectArray){
return !isEmpty(objectArray);
}
global static Boolean isNotEmpty(SObject[] objectArray){
return !isEmpty(objectArray);
}
global static Object[] pluck(SObject[] objectArray, String fieldName){
if(isEmpty(objectArray) || fieldName == null || fieldName.trim() == null || fieldName.trim().length() == 0){
return new Object[]{};
}
Object[] plucked = new Object[objectArray.size()];
for(Integer i = 0; i < objectArray.size(); i++){
plucked[i] = objectArray[i].get(fieldName);
}
return plucked;
}
global static String toString(Object[] objectArray){
if(objectArray == null){
return 'null';
}
String returnValue = '{';
for(Integer i = 0; i < objectArray.size(); i++){
if(i!=0){ returnValue += ','; }
returnValue += '\'' + objectArray[i] + '\'';
}
returnValue += '}';
return returnValue;
}
global static String toString(SObject[] objectArray){
if(objectArray == null){
return 'null';
}
String returnValue = '{';
for(Integer i = 0; i < objectArray.size(); i++){
if(i!=0){ returnValue += ','; }
returnValue += '\'' + objectArray[i] + '\'';
}
returnValue += '}';
return returnValue;
}
global static void assertArraysAreEqual(Object[] expected, Object[] actual){
//check to see if one param is null but the other is not
System.assert((expected == null && actual == null)|| (expected != null && actual != null),
'Assertion failed, the following two arrays are not equal. Expected: '
+ ArrayUtils.toString(expected) + ', Actual: ' + ArrayUtils.toString(actual));
if(expected != null && actual != null){
System.assert(expected.size() == actual.size(), 'Assertion failed, the following two arrays are not equal. Expected: '
+ ArrayUtils.toString(expected) + ', Actual: ' + ArrayUtils.toString(actual));
for(Integer i = 0; i < expected.size(); i++){
System.assert(expected[i] == actual[i], 'Assertion failed, the following two arrays are not equal. Expected: '
+ ArrayUtils.toString(expected) + ', Actual: ' + ArrayUtils.toString(actual));
}
}
}
global static void assertArraysAreEqual(SObject[] expected, SObject[] actual){
//check to see if one param is null but the other is not
System.assert((expected == null && actual == null)|| (expected != null && actual != null),
'Assertion failed, the following two arrays are not equal. Expected: '
+ ArrayUtils.toString(expected) + ', Actual: ' + ArrayUtils.toString(actual));
if(expected != null && actual != null){
System.assert(expected.size() == actual.size(), 'Assertion failed, the following two arrays are not equal. Expected: '
+ ArrayUtils.toString(expected) + ', Actual: ' + ArrayUtils.toString(actual));
for(Integer i = 0; i < expected.size(); i++){
System.assert(expected[i] == actual[i], 'Assertion failed, the following two arrays are not equal. Expected: '
+ ArrayUtils.toString(expected) + ', Actual: ' + ArrayUtils.toString(actual));
}
}
}
global static List<Object> merg(List<Object> list1, List<Object> list2) {
List<Object> returnList = new List<Object>();
if(list1 != null && list2 != null && (list1.size()+list2.size()) > MAX_NUMBER_OF_ELEMENTS_IN_LIST){
throw new IllegalArgumentException('Lists cannot be merged because new list would be greater than maximum number of elements in a list: ' + MAX_NUMBER_OF_ELEMENTS_IN_LIST);
}
if(isNotEmpty(list1)){
for(Object elmt : list1){
returnList.add(elmt);
}
}
if(isNotEmpty(list2)){
for(Object elmt : list2){
returnList.add(elmt);
}
}
return returnList;
}
global static List<SObject> merg(List<SObject> list1, List<SObject> list2) {
if(list1 != null && list2 != null && (list1.size()+list2.size()) > MAX_NUMBER_OF_ELEMENTS_IN_LIST){
throw new IllegalArgumentException('Lists cannot be merged because new list would be greater than maximum number of elements in a list: ' + MAX_NUMBER_OF_ELEMENTS_IN_LIST);
}
if(isEmpty(list1) && isEmpty(list2)){
return null;
}
List<SObject> returnList = new List<SObject>();
if(list1 != null){
for(SObject elmt : list1){
returnList.add(elmt);
}
}
if(list2 != null){
for(SObject elmt : list2){
returnList.add(elmt);
}
}
return returnList;
}
global static List<Object> subset(List<Object> aList, Integer count) {
return subset(aList,0,count);
}
global static List<Object> subset(List<Object> list1, Integer startIndex, Integer count) {
List<Object> returnList = new List<Object>();
if(list1 != null && list1.size() > 0 && startIndex >= 0 && startIndex <= list1.size()-1 && count > 0){
for(Integer i = startIndex; i < list1.size() && i - startIndex < count; i++){
returnList.add(list1.get(i));
}
}
return returnList;
}
global static List<SObject> subset(List<SObject> aList, Integer count) {
return subset(aList,0,count);
}
global static List<SObject> subset(List<SObject> list1, Integer startIndex, Integer count) {
List<SObject> returnList = null;
if(list1 != null && list1.size() > 0 && startIndex <= list1.size()-1 && count > 0){
returnList = new List<SObject>();
for(Integer i = startIndex; i < list1.size() && i - startIndex < count; i++){
returnList.add(list1.get(i));
}
}
return returnList;
}
//===============================================
//LIST/ARRAY SORTING
//===============================================
//FOR FORCE.COM PRIMITIVES (Double,Integer,ID,etc.):
global static List<Object> qsort(List<Object> theList) {
return qsort(theList,new PrimitiveComparator());
}
global static List<Object> qsort(List<Object> theList, Boolean sortAsc) {
return qsort(theList,new PrimitiveComparator(),sortAsc);
}
global static List<Object> qsort(List<Object> theList, ObjectComparator comparator) {
return qsort(theList,comparator,true);
}
global static List<Object> qsort(List<Object> theList, ObjectComparator comparator, Boolean sortAsc) {
return qsort(theList, 0, (theList == null ? 0 : theList.size()-1),comparator,sortAsc);
}
//FOR SALESFORCE OBJECTS (sObjects):
global static List<SObject> qsort(List<SObject> theList, ISObjectComparator comparator) {
return qsort(theList,comparator,true);
}
global static List<SObject> qsort(List<SObject> theList, ISObjectComparator comparator,Boolean sortAsc ) {
return qsort(theList, 0, (theList == null ? 0 : theList.size()-1),comparator,sortAsc);
}
private static List<Object> qsort(List<Object> theList,
Integer lo0,
Integer hi0,
ObjectComparator comparator,
Boolean sortAsc){
Integer lo = lo0;
Integer hi = hi0;
if (lo >= hi) {
return theList;
} else if( lo == hi - 1 ) {
if (( comparator.compare(theList[lo],theList[hi])>0 && sortAsc) ||
(comparator.compare(theList[lo],theList[hi])<0 && !sortAsc)
) {
Object prs = theList[lo];
theList[lo] = theList[hi];
theList[hi] = prs;
}
return theList;
}
Object pivot = theList[(lo + hi) / 2];
theList[(lo + hi) / 2] = theList[hi];
theList[hi] = pivot;
while( lo < hi ) {
while ((comparator.compare(theList[lo], pivot)<=0 && lo < hi && sortAsc) ||
(comparator.compare(theList[lo], pivot)>=0 && lo < hi && !sortAsc)
) { lo++; }
while (( comparator.compare(pivot,theList[hi])<=0 && lo < hi && sortAsc) ||
( comparator.compare(pivot,theList[hi])>=0 && lo < hi && !sortAsc)
) { hi--; }
if( lo < hi ){
Object prs = theList[lo];
theList[lo] = theList[hi];
theList[hi] = prs;
}
}
theList[hi0] = theList[hi];
theList[hi] = pivot;
qsort(theList, lo0, lo-1,comparator,sortAsc);
qsort(theList, hi+1, hi0,comparator,sortAsc);
return theList;
}
private static List<SObject> qsort(List<SObject> theList,
Integer lo0,
Integer hi0,
ISObjectComparator comparator,
Boolean sortAsc){
Integer lo = lo0;
Integer hi = hi0;
if (lo >= hi) {
return theList;
} else if( lo == hi - 1 ) {
if (( comparator.compare(theList[lo],theList[hi])>0 && sortAsc) ||
(comparator.compare(theList[lo],theList[hi])<0 && !sortAsc)
) {
SObject prs = theList[lo];
theList[lo] = theList[hi];
theList[hi] = prs;
}
return theList;
}
SObject pivot = theList[(lo + hi) / 2];
theList[(lo + hi) / 2] = theList[hi];
theList[hi] = pivot;
while( lo < hi ) {
while ((comparator.compare(theList[lo], pivot)<=0 && lo < hi && sortAsc) ||
(comparator.compare(theList[lo], pivot)>=0 && lo < hi && !sortAsc)
) { lo++; }
while (( comparator.compare(pivot,theList[hi])<=0 && lo < hi && sortAsc) ||
( comparator.compare(pivot,theList[hi])>=0 && lo < hi && !sortAsc)
) { hi--; }
if( lo < hi ){
SObject prs = theList[lo];
theList[lo] = theList[hi];
theList[hi] = prs;
}
}
theList[hi0] = theList[hi];
theList[hi] = pivot;
qsort(theList, lo0, lo-1,comparator,sortAsc);
qsort(theList, hi+1, hi0,comparator,sortAsc);
return theList;
}
/*
global static List<Object> unique(List<Object> theList) {
List<Object> uniques = new List<Object>();
Set<Object> keys = new Set<Object>();
if(theList != null && theList.size() > 0){
for(Object obj : theList){
if(keys.contains(obj)){
continue;
} else {
keys.add(obj);
uniques.add(obj);
}
}
}
return uniques;
}
global static List<SObject> unique(List<SObject> theList) {
if(theList == null){
return null;
}
List<SObject> uniques = createEmptySObjectList(theList.get(0));
Set<String> keys = new Set<String>();
if(theList != null && theList.size() > 0){
String key = null;
for(SObject obj : theList){
key = obj == null ? null : ''+obj;
if(keys.contains(key)){
continue;
} else {
keys.add(key);
uniques.add(obj);
}
}
}
return uniques;
}
*/
}

View File

@@ -0,0 +1,185 @@
/* ============================================================
* This code is part of the "apex-lang" open source project avaiable at:
*
* http://code.google.com/p/apex-lang/
*
* This code is licensed under the Apache License, Version 2.0. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
* ============================================================
*/
global class BooleanUtils {
global static Boolean isFalse(Boolean bool)
{
if(bool==null)
return false;
else
return !bool;
}
global static Boolean isNotFalse(Boolean bool)
{
if(bool==null)
return true;
else
return bool;
}
global static Boolean isNotTrue(Boolean bool)
{
if(bool==null)
return true;
else
return !bool;
}
global static Boolean isTrue(Boolean bool)
{
if(bool==null)
return false;
else
return bool;
}
global static Boolean negate(Boolean bool)
{
if(bool==null)
return null;
else
return !bool;
}
global static Boolean toBooleanDefaultIfNull(Boolean bool, Boolean defaultVal)
{
if(bool==null)
return defaultVal;
else
return bool;
}
global static Boolean toBoolean(Integer value)
{
if(value==null)
return false;
else
{
if(value==0)
return false;
else
return true;
}
}
global static Boolean strToBoolean(String value)
{
if(value==null)
return false;
else
{
if(StringUtils.equalsIgnoreCase(value,'true'))
return true;
else
return false;
}
}
/************************************/
//Converts an int to a boolean specifying
//the conversion values.
// Parameters:
// value - the Integer to convert, may be null
// trueValue - the value to match for true, may be null
// falseValue - the value to match for false, may be null
//Returns:
// true or false
//Throws:
// java.lang.IllegalArgumentException - if no match
/************************************/
global static Boolean toBoolean(Integer value,
Integer trueValue,
Integer falseValue)
{
if(value==trueValue)
return true;
else if(value==falseValue)
return false;
else
throw new IllegalArgumentException();
}
global static Integer toInteger(Boolean bool)
{
if(bool==null)
throw new IllegalArgumentException();
else
{
if(bool)
return 1;
else
return 0;
}
}
global static String toStringYesNo(Boolean bool)
{
if(bool==null)
return null;
else
{
if(bool)
return 'yes';
else
return 'no';
}
}
global static String toStringYN(Boolean bool)
{
if(bool==null)
return null;
else
{
if(bool)
return 'Y';
else
return 'N';
}
}
global static String toString(Boolean bool,
String trueString,
String falseString)
{
if(bool==null)
return null;
else
{
if(bool)
return trueString;
else
return falseString;
}
}
global static Boolean xor(Boolean[] boolArray)
{
if(boolArray==null || boolArray.size()==0)
throw new IllegalArgumentException();
else
{
Boolean firstItem=boolArray[0];
for(Boolean bool:boolArray)
{
if(bool!=firstItem)
return false;
}
return true;
}
}
}

View File

@@ -0,0 +1,98 @@
/* ============================================================
* Contributor: Caleb Sidel
*
* This code is part of the "apex-lang" open source project avaiable at:
*
* http://code.google.com/p/apex-lang/
*
* This code is licensed under the Apache License, Version 2.0. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
* ============================================================
*/
global class EmailUtils {
global static void sendEmailWithStandardAttachments(List<String> recipients,String emailSubject,String body,Boolean useHTML,List<Id> attachmentIDs) {
List<Attachment> stdAttachments = [SELECT id, name, body FROM Attachment WHERE Id IN:attachmentIDs];
sendEmailWithStandardAttachments(recipients, emailSubject, body, useHTML, stdAttachments);
}
global static void sendEmailWithStandardAttachments(List<String> recipients,String emailSubject,String body,Boolean useHTML,List<Attachment> stdAttachments) {
List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.EmailFileAttachment>();
for(Attachment attachment : stdAttachments) {
Messaging.EmailFileAttachment fileAttachment = new Messaging.EmailFileAttachment();
fileAttachment.setFileName(attachment.Name);
fileAttachment.setBody(attachment.Body);
fileAttachments.add(fileAttachment);
}
sendEmail(recipients, emailSubject, body, useHTML, fileAttachments);
}
global static void sendTextEmail(List<String> recipients,String emailSubject,String textBody) {
sendEmail(recipients, emailSubject, textBody, false, null);
}
global static void sendHTMLEmail(List<String> recipients,String emailSubject,String htmlBody) {
sendEmail(recipients, emailSubject, htmlBody, true, null);
}
global static void sendEmail(List<String> recipients,String emailSubject,String body,Boolean useHTML,List<Messaging.EmailFileAttachment> fileAttachments) {
if(recipients == null) return;
if(recipients.size() == 0) return;
// Create a new single email message object
// that will send out a single email to the addresses in the To, CC & BCC list.
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
//the email is not saved as an activity.
mail.setSaveAsActivity(false);
// Assign the addresses for the To lists to the mail object.
mail.setToAddresses(recipients);
// Specify the subject line for your email address.
mail.setSubject(emailSubject);
// Set to True if you want to BCC yourself on the email.
mail.setBccSender(false);
// The email address of the user executing the Apex Code will be used.
mail.setUseSignature(false);
if (useHTML) {
// Specify the html content of the email.
mail.setHtmlBody(body);
} else {
// Specify the text content of the email.
mail.setPlainTextBody(body);
}
// Specify FileAttachments
if(fileAttachments != null && fileAttachments.size() > 0) {
mail.setFileAttachments(fileAttachments);
}
// Send the email you have created.
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
/**
* null => false
* '' => false
* ' ' => false
* 'x' => false
* 'x@' => false
* 'x@x' => false
* 'x@x.x' => true
*/
global static Boolean isValidEmailAddress(String str){
if(str != null && str.trim() != null && str.trim().length() > 0){
String[] split = str.split('@');
if(split != null && split.size() == 2){
split = split[1].split('\\.');
if(split != null && split.size() >= 2){
return true;
}
}
}
return false;
}
global static Boolean isNotValidEmailAddress(String str){
return !isValidEmailAddress(str);
}
}

55
samples/Apex/GeoUtils.cls Normal file
View File

@@ -0,0 +1,55 @@
public class GeoUtils {
// generate a KML string given a page reference, call getContent()
// then cleanup the output.
public static string generateFromContent(PageReference pr) {
string ret = '';
try {
ret = (string) pr.getContent().toString();
ret = ret.replaceAll('"','\'' ); // get content produces quote chars \"
ret = ret.replaceAll( '&','&amp;');// we need to escape these in the node value
} catch (exception e ) {
system.debug( 'ERROR '+e);
}
ret = ret.replaceAll('\n',' '); // must use ALL since many new line may get
ret = ret.replaceAll('\r',' '); // get these also!
// system.debug( ret); // dump the KML
return ret ;
}
public static Map<String, String> geo_response = new Map<String, String>{'200'=>'G_GEO_SUCCESS',
'400'=>'G_GEO_BAD_REQUEST',
'500'=>'G_GEO_SERVER_ERROR',
'601'=>'G_GEO_MISSING_ADDRESS',
'602'=>'G_GEO_UNKNOWN_ADDRESS',
'603'=>'G_GEO_UNAVAILABLE_ADDRESS',
'604'=>'G_GEO_UNKNOWN_DIRECTIONS',
'610'=>'G_GEO_BAD_KEY',
'620'=>'G_GEO_TOO_MANY_QUERIES'
};
public static string accountAddressString ( account acct ) {
// form an address string given an account object
string adr = acct.billingstreet + ',' + acct.billingcity + ',' + acct.billingstate;
if ( acct.billingpostalcode != null ) adr += ',' + acct.billingpostalcode;
if ( acct.billingcountry != null ) adr += ',' + acct.billingcountry;
adr = adr.replaceAll('\"', '' );
adr = adr.replaceAll('\'', '' );
adr = adr.replaceAll( '\n', ' ' );
adr = adr.replaceAll( '\r', ' ' );
system.debug( adr );
return adr;
}
public static testmethod void t1() {
PageReference pageRef = Page.kmlPreviewTemplate;
Test.setCurrentPage(pageRef);
system.assert ( GeoUtils.generateFromContent( pageRef ) != null );
Account a = new Account( name='foo', billingstreet='main', billingcity='springfield',billingstate='il',
billingpostalcode='9',billingcountry='us');
insert a;
system.assertEquals( 'main,springfield,il,9,us',accountAddressString( a) );
}
}

View File

@@ -0,0 +1,740 @@
/* ============================================================
* This code is part of the "apex-lang" open source project avaiable at:
*
* http://code.google.com/p/apex-lang/
*
* This code is licensed under the Apache License, Version 2.0. You may obtain a
* copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
* ============================================================
*/
global class LanguageUtils {
global static final String HTTP_LANGUAGE_CODE_PARAMETER_KEY = 'l';
global static final String DEFAULT_LANGUAGE_CODE = 'en_us';
global static Set<String> SUPPORTED_LANGUAGE_CODES = new Set<String>{
'zh-cn' //Chinese (Simplified)
,'zh-tw' //Chinese (Traditional)
,'nl-nl' //Dutch
,'en-us' //English
,'fi' //Finnish
,'fr' //French
,'de' //German
,'it' //Italian
,'ja' //Japanese
,'ko' //Korean
,'pl' //Polish
,'pt-br' //Portuguese (Brazilian)
,'ru' //Russian
,'es' //Spanish
,'sv' //Swedish
,'th' //Thai
,'cs' //Czech
,'da' //Danish
,'hu' //Hungarian
,'in' //Indonesian
,'tr' //Turkish
};
private static Map<String,String> DEFAULTS = new Map<String,String>{
'en'=>'en-us'
,'zh'=>'zh-cn'
,'nl'=>'nl-nl'
,'pt'=>'pt-br'
};
global static String getLangCodeByHttpParam(){
String returnValue = null;
final Set<String> LANGUAGE_CODE_SET = getSuppLangCodeSet();
if(ApexPages.currentPage() != null && ApexPages.currentPage().getParameters() != null){
String LANGUAGE_HTTP_PARAMETER =
StringUtils.lowerCase(
StringUtils.replaceChars(
ApexPages.currentPage().getParameters().get(HTTP_LANGUAGE_CODE_PARAMETER_KEY)
, '_' //underscore
, '-' //dash
)
);
if(DEFAULTS.containsKey(LANGUAGE_HTTP_PARAMETER)){
LANGUAGE_HTTP_PARAMETER = DEFAULTS.get(LANGUAGE_HTTP_PARAMETER);
}
if(StringUtils.isNotBlank(LANGUAGE_HTTP_PARAMETER)
&& SUPPORTED_LANGUAGE_CODES.contains(LANGUAGE_HTTP_PARAMETER)){
returnValue = LANGUAGE_HTTP_PARAMETER;
}
}
return returnValue;
}
global static String getLangCodeByBrowser(){
final String LANGUAGES_FROM_BROWSER_AS_STRING = ApexPages.currentPage().getHeaders().get('Accept-Language');
final List<String> LANGUAGES_FROM_BROWSER_AS_LIST = splitAndFilterAcceptLanguageHeader(LANGUAGES_FROM_BROWSER_AS_STRING);
if(LANGUAGES_FROM_BROWSER_AS_LIST != null && LANGUAGES_FROM_BROWSER_AS_LIST.size() > 0){
for(String languageFromBrowser : LANGUAGES_FROM_BROWSER_AS_LIST){
if(DEFAULTS.containsKey(languageFromBrowser)){
languageFromBrowser = DEFAULTS.get(languageFromBrowser);
}
if(SUPPORTED_LANGUAGE_CODES.contains(languageFromBrowser)){
return languageFromBrowser;
}
}
}
return null;
}
global static String getLangCodeByUser(){
return UserInfo.getLanguage();
}
global static String getLangCodeByHttpParamOrIfNullThenBrowser(){
return StringUtils.defaultString(getLangCodeByHttpParam(),getLangCodeByBrowser());
}
global static String getLangCodeByHttpParamOrIfNullThenUser(){
return StringUtils.defaultString(getLangCodeByHttpParam(),getLangCodeByUser());
}
global static String getLangCodeByBrowserOrIfNullThenHttpParam(){
return StringUtils.defaultString(getLangCodeByBrowser(),getLangCodeByHttpParam());
}
global static String getLangCodeByBrowserOrIfNullThenUser(){
return StringUtils.defaultString(getLangCodeByBrowser(),getLangCodeByUser());
}
private static List<String> splitAndFilterAcceptLanguageHeader(String header){
List<String> returnList = new List<String>();
String[] tokens = StringUtils.split(header,',');
if(tokens != null){
for(String token : tokens){
if(token != null ){
if(token.contains(';')){
token = token.substring(0,token.indexOf(';',0));
}
returnList.add(token);
if(StringUtils.length(token) > 2){
returnList.add(StringUtils.substring(token,0,2));
}
}
}
}
return returnList;
}
private static Set<String> getSuppLangCodeSet(){
Set<String> langCodes = new Set<String>();
for(String langCode : SUPPORTED_LANGUAGE_CODES){
if(langCode != null){
langCodes.add(StringUtils.lowerCase(langCode));
}
}
return langCodes;
}
global static String getLanguageName(String displayLanguageCode, String languageCode){
return translatedLanguageNames.get(filterLanguageCode(displayLanguageCode)).get(filterLanguageCode(languageCode));
}
global static Map<String,String> getAllLanguages(){
return getAllLanguages(DEFAULT_LANGUAGE_CODE);
}
global static Map<String,String> getAllLanguages(String displayLanguageCode){
return translatedLanguageNames.get(filterLanguageCode(displayLanguageCode));
}
private static String filterLanguageCode(String displayLanguageCode){
displayLanguageCode = StringUtils.lowerCase(displayLanguageCode);
if(DEFAULTS.containsKey(displayLanguageCode)){
displayLanguageCode = StringUtils.replaceChars(DEFAULTS.get(displayLanguageCode),'-','_');
}
if(!translatedLanguageNames.containsKey(displayLanguageCode)){
displayLanguageCode = DEFAULT_LANGUAGE_CODE;
}
return displayLanguageCode;
}
private static final Map<String,Map<String,String>> translatedLanguageNames = new Map<String,Map<String,String>>{
'cs'=> new Map<String,String>{
'cs'=>'Čeština'
,'da'=>'Dánština'
,'de'=>'Němčina'
,'en_us'=>'Angličtina (Spojené státy)'
,'es'=>'Španělština'
,'es_mx'=>'Mexická španělština'
,'fi'=>'Finština'
,'fr'=>'Francouzština'
,'hu'=>'Maďarština'
,'in'=>'Indonéština'
,'it'=>'Italština'
,'ja'=>'Japonština'
,'ko'=>'Korejština'
,'nl_nl'=>'Nizozemština'
,'pl'=>'Polština'
,'pt_br'=>'Portugalština (Brazílie)'
,'ro'=>'Rumunština'
,'ru'=>'Ruština'
,'sv'=>'Švédština'
,'th'=>'Thajská'
,'tr'=>'Turečtina'
,'zh_cn'=>'Čínština (zjednodušená)'
,'zh_tw'=>'Čínština (tradiční)'
}
,'da'=> new Map<String,String>{
'cs'=>'Tjekkisk'
,'da'=>'Dansk'
,'de'=>'Tysk'
,'en_us'=>'Engelsk (USA)'
,'es'=>'Spansk'
,'es_mx'=>'Mexicansk spansk'
,'fi'=>'Finsk'
,'fr'=>'Fransk'
,'hu'=>'Ungarsk'
,'in'=>'Indonesisk'
,'it'=>'Italiensk'
,'ja'=>'Japansk'
,'ko'=>'Koreansk'
,'nl_nl'=>'Hollandsk'
,'pl'=>'Polsk'
,'pt_br'=>'Portugisisk (Brasilien)'
,'ro'=>'Rumænsk'
,'ru'=>'Russisk'
,'sv'=>'Svensk'
,'th'=>'Thai'
,'tr'=>'Tyrkisk'
,'zh_cn'=>'Kinesisk (forenklet)'
,'zh_tw'=>'Kinesisk (traditionelt)'
}
,'de'=> new Map<String,String>{
'cs'=>'Tschechisch'
,'da'=>'Dänisch'
,'de'=>'Deutsch'
,'en_us'=>'Englisch (Vereinigte Staaten)'
,'es'=>'Spanisch'
,'es_mx'=>'Mexican Spanish'
,'fi'=>'Finnisch'
,'fr'=>'Französisch'
,'hu'=>'Ungarisch'
,'in'=>'Indonesisch'
,'it'=>'Italienisch'
,'ja'=>'Japanisch'
,'ko'=>'Koreanisch'
,'nl_nl'=>'Niederländisch'
,'pl'=>'Polnisch'
,'pt_br'=>'Portugiesisch (Brasilien)'
,'ro'=>'Rumänisch'
,'ru'=>'Russisch'
,'sv'=>'Schwedisch'
,'th'=>'Thai'
,'tr'=>'Türkisch'
,'zh_cn'=>'Chinesisch (Taiwan)'
,'zh_tw'=>'Chinesisch (traditionell)'
}
,'en_us'=> new Map<String,String>{
'cs'=>'Czech'
,'da'=>'Danish'
,'de'=>'German'
,'en_us'=>'English (United States)'
,'es'=>'Spanish'
,'es_mx'=>'Mexican Spanish'
,'fi'=>'Finnish'
,'fr'=>'French'
,'hu'=>'Hungarian'
,'in'=>'Indonesian'
,'it'=>'Italian'
,'ja'=>'Japanese'
,'ko'=>'Korean'
,'nl_nl'=>'Dutch'
,'pl'=>'Polish'
,'pt_br'=>'Portuguese (Brazilian)'
,'ro'=>'Romanian'
,'ru'=>'Russian'
,'sv'=>'Swedish'
,'th'=>'Thai'
,'tr'=>'Turkish'
,'zh_cn'=>'Chinese (Simplified)'
,'zh_tw'=>'Chinese (Traditional)'
}
,'es'=> new Map<String,String>{
'cs'=>'Checa'
,'da'=>'Danés'
,'de'=>'Alemán'
,'en_us'=>'Inglés (Estados Unidos)'
,'es'=>'Español'
,'es_mx'=>'El español de México'
,'fi'=>'Finlandés'
,'fr'=>'Francés'
,'hu'=>'Húngaro'
,'in'=>'Indonesia'
,'it'=>'Italiano'
,'ja'=>'Japonés'
,'ko'=>'Corea'
,'nl_nl'=>'Neerlandés'
,'pl'=>'Polaco'
,'pt_br'=>'Portugués (brasileño)'
,'ro'=>'Rumano'
,'ru'=>'Rusia'
,'sv'=>'Sueco'
,'th'=>'Tailandia'
,'tr'=>'Turquía'
,'zh_cn'=>'Chino (simplificado)'
,'zh_tw'=>'Chino (tradicional)'
}
,'es_mx'=> new Map<String,String>{
'cs'=>'Checa'
,'da'=>'Danés'
,'de'=>'Alemán'
,'en_us'=>'Inglés (Estados Unidos)'
,'es'=>'Español'
,'es_mx'=>'El español de México'
,'fi'=>'Finlandés'
,'fr'=>'Francés'
,'hu'=>'Húngaro'
,'in'=>'Indonesia'
,'it'=>'Italiano'
,'ja'=>'Japonés'
,'ko'=>'Corea'
,'nl_nl'=>'Neerlandés'
,'pl'=>'Polaco'
,'pt_br'=>'Portugués (brasileño)'
,'ro'=>'Rumano'
,'ru'=>'Rusia'
,'sv'=>'Sueco'
,'th'=>'Tailandia'
,'tr'=>'Turquía'
,'zh_cn'=>'Chino (simplificado)'
,'zh_tw'=>'Chino (tradicional)'
}
,'fi'=> new Map<String,String>{
'cs'=>'Tšekki'
,'da'=>'Tanska'
,'de'=>'Saksa'
,'en_us'=>'Englanti (Yhdysvallat)'
,'es'=>'Espanja'
,'es_mx'=>'Meksikon espanja'
,'fi'=>'Suomen'
,'fr'=>'Ranska'
,'hu'=>'Unkari'
,'in'=>'Indonesia'
,'it'=>'Italia'
,'ja'=>'Japani'
,'ko'=>'Korea'
,'nl_nl'=>'Hollanti'
,'pl'=>'Puola'
,'pt_br'=>'Portugali (Brasilia)'
,'ro'=>'Romania'
,'ru'=>'Venäjä'
,'sv'=>'Ruotsi'
,'th'=>'Thaimaalaisen'
,'tr'=>'Turkki'
,'zh_cn'=>'Kiina (yksinkertaistettu)'
,'zh_tw'=>'Kiina (perinteinen)'
}
,'fr'=> new Map<String,String>{
'cs'=>'Tchèque'
,'da'=>'Danois'
,'de'=>'Allemand'
,'en_us'=>'Anglais (Etats Unis)'
,'es'=>'Espagnol'
,'es_mx'=>'Espagnol mexicain'
,'fi'=>'Finnois'
,'fr'=>'Français'
,'hu'=>'Hongrois'
,'in'=>'Indonésien'
,'it'=>'Italien'
,'ja'=>'Japonais'
,'ko'=>'Coréen'
,'nl_nl'=>'Néerlandais'
,'pl'=>'Polonais'
,'pt_br'=>'Portugais (brésilien)'
,'ro'=>'Roumain'
,'ru'=>'Russe'
,'sv'=>'Suédois'
,'th'=>'Thai'
,'tr'=>'Turc'
,'zh_cn'=>'Chinois (simplifié)'
,'zh_tw'=>'Chinois (Traditionnel)'
}
,'hu'=> new Map<String,String>{
'cs'=>'Cseh'
,'da'=>'Dán'
,'de'=>'Német'
,'en_us'=>'Angol (Egyesült Államok)'
,'es'=>'Spanyol'
,'es_mx'=>'Mexikói spanyol'
,'fi'=>'Finn'
,'fr'=>'Francia'
,'hu'=>'Magyar'
,'in'=>'Indonéz'
,'it'=>'Olasz'
,'ja'=>'Japán'
,'ko'=>'Koreai'
,'nl_nl'=>'Holland'
,'pl'=>'Lengyel'
,'pt_br'=>'Portugál (brazíliai)'
,'ro'=>'Román'
,'ru'=>'Orosz'
,'sv'=>'Svéd'
,'th'=>'Thaiföldi'
,'tr'=>'Török'
,'zh_cn'=>'Kínai (egyszerűsített)'
,'zh_tw'=>'Kínai (hagyományos)'
}
,'in'=> new Map<String,String>{
'cs'=>'Ceko'
,'da'=>'Denmark'
,'de'=>'Jerman'
,'en_us'=>'Inggris (Amerika Serikat)'
,'es'=>'Spanyol'
,'es_mx'=>'Meksiko Spanyol'
,'fi'=>'Finlandia'
,'fr'=>'Prancis'
,'hu'=>'Hungaria'
,'in'=>'Indonesia'
,'it'=>'Italia'
,'ja'=>'Jepang'
,'ko'=>'Korea'
,'nl_nl'=>'Belanda'
,'pl'=>'Polish'
,'pt_br'=>'Portugis (Brasil)'
,'ro'=>'Romanian'
,'ru'=>'Russian'
,'sv'=>'Swedia'
,'th'=>'Thai'
,'tr'=>'Turkish'
,'zh_cn'=>'Cina (Sederhana)'
,'zh_tw'=>'Cina (Tradisional)'
}
,'it'=> new Map<String,String>{
'cs'=>'Ceco'
,'da'=>'Danese'
,'de'=>'Tedesco'
,'en_us'=>'Inglese (Stati Uniti)'
,'es'=>'Spagnolo'
,'es_mx'=>'Spagnolo messicano'
,'fi'=>'Finlandese'
,'fr'=>'Francese'
,'hu'=>'Ungherese'
,'in'=>'Indonesiano'
,'it'=>'Italiano'
,'ja'=>'Giapponese'
,'ko'=>'Coreano'
,'nl_nl'=>'Olandese'
,'pl'=>'Polacco'
,'pt_br'=>'Portoghese (brasiliano)'
,'ro'=>'Rumeno'
,'ru'=>'Russo'
,'sv'=>'Svedese'
,'th'=>'Thai'
,'tr'=>'Turco'
,'zh_cn'=>'Cinese (semplificato)'
,'zh_tw'=>'Cinese (tradizionale)'
}
,'ja'=> new Map<String,String>{
'cs'=>''
,'da'=>''
,'de'=>''
,'en_us'=>''
,'es'=>''
,'es_mx'=>''
,'fi'=>''
,'fr'=>''
,'hu'=>''
,'in'=>''
,'it'=>''
,'ja'=>''
,'ko'=>''
,'nl_nl'=>''
,'pl'=>''
,'pt_br'=>''
,'ro'=>''
,'ru'=>''
,'sv'=>''
,'th'=>''
,'tr'=>''
,'zh_cn'=>''
,'zh_tw'=>''
}
,'ko'=> new Map<String,String>{
'cs'=>''
,'da'=>''
,'de'=>''
,'en_us'=>' ()'
,'es'=>''
,'es_mx'=>' '
,'fi'=>''
,'fr'=>''
,'hu'=>''
,'in'=>' '
,'it'=>''
,'ja'=>''
,'ko'=>''
,'nl_nl'=>''
,'pl'=>''
,'pt_br'=>' ()'
,'ro'=>''
,'ru'=>''
,'sv'=>''
,'th'=>''
,'tr'=>''
,'zh_cn'=>' ()'
,'zh_tw'=>' ()'
}
,'nl_nl'=> new Map<String,String>{
'cs'=>'Tsjechisch'
,'da'=>'Deens'
,'de'=>'Duits'
,'en_us'=>'Engels (Verenigde Staten)'
,'es'=>'Spaans'
,'es_mx'=>'Mexicaans Spaans'
,'fi'=>'Fins'
,'fr'=>'Frans'
,'hu'=>'Hongaars'
,'in'=>'Indonesisch'
,'it'=>'Italiaans'
,'ja'=>'Japans'
,'ko'=>'Koreaans'
,'nl_nl'=>'Nederlandse'
,'pl'=>'Pools'
,'pt_br'=>'Portugees (Braziliaans)'
,'ro'=>'Roemeens'
,'ru'=>'Russisch'
,'sv'=>'Zweeds'
,'th'=>'Thais'
,'tr'=>'Turks'
,'zh_cn'=>'Chinese (Simplified)'
,'zh_tw'=>'Chinees (traditioneel)'
}
,'pl'=> new Map<String,String>{
'cs'=>'Czeski'
,'da'=>'Duński'
,'de'=>'Niemiecki'
,'en_us'=>'Angielski (Stany Zjednoczone)'
,'es'=>'Hiszpański'
,'es_mx'=>'Mexican hiszpański'
,'fi'=>'Fiński'
,'fr'=>'Francuski'
,'hu'=>'Węgierski'
,'in'=>'Indonezyjski'
,'it'=>'Włoski'
,'ja'=>'Japoński'
,'ko'=>'Koreański'
,'nl_nl'=>'Niderlandzki'
,'pl'=>'Polska'
,'pt_br'=>'Portugalski (Brazylia)'
,'ro'=>'Rumuński'
,'ru'=>'Rosyjski'
,'sv'=>'Szwedzki'
,'th'=>'Taj'
,'tr'=>'Turecki'
,'zh_cn'=>'Chiński (uproszczony)'
,'zh_tw'=>'Chiński (tradycyjny)'
}
,'pt_br'=> new Map<String,String>{
'cs'=>'Tcheco'
,'da'=>'Dinamarquês'
,'de'=>'Alemão'
,'en_us'=>'Inglês (Estados Unidos)'
,'es'=>'Espanhol'
,'es_mx'=>'Espanhol mexicano'
,'fi'=>'Finlandês'
,'fr'=>'Francês'
,'hu'=>'Húngaro'
,'in'=>'Indonésio'
,'it'=>'Italiano'
,'ja'=>'Japonês'
,'ko'=>'Coreano'
,'nl_nl'=>'Holandês'
,'pl'=>'Polonês'
,'pt_br'=>'Português (Brasil)'
,'ro'=>'Romeno'
,'ru'=>'Russo'
,'sv'=>'Sueco'
,'th'=>'Tailandês'
,'tr'=>'Turco'
,'zh_cn'=>'Chinês (simplificado)'
,'zh_tw'=>'Chinês (Tradicional)'
}
,'ro'=> new Map<String,String>{
'cs'=>'Cehă'
,'da'=>'Daneză'
,'de'=>'Germană'
,'en_us'=>'În limba engleză (Statele Unite)'
,'es'=>'Spaniolă'
,'es_mx'=>'Mexicane Spanish'
,'fi'=>'Finlandeză'
,'fr'=>'Franţuzesc'
,'hu'=>'Maghiară'
,'in'=>'Indoneziană'
,'it'=>'Italiană'
,'ja'=>'Japoneză'
,'ko'=>'Coreeană'
,'nl_nl'=>'Olandeză'
,'pl'=>'Poloneză'
,'pt_br'=>'Portuguese (Brazilian)'
,'ro'=>'Român'
,'ru'=>'Rus'
,'sv'=>'Suedez'
,'th'=>'Thai'
,'tr'=>'Turcă'
,'zh_cn'=>'Chineză (simplificată)'
,'zh_tw'=>'Chineză (Tradiţională)'
}
,'ru'=> new Map<String,String>{
'cs'=>'Чешский'
,'da'=>'Датский'
,'de'=>'Немецкий'
,'en_us'=>'Английский (США)'
,'es'=>'Испанский'
,'es_mx'=>'Мексиканские Испанский'
,'fi'=>'Финский'
,'fr'=>'Французский'
,'hu'=>'Венгерский'
,'in'=>'Индонезийский'
,'it'=>'Итальянский'
,'ja'=>'Японский'
,'ko'=>'Корейский'
,'nl_nl'=>'Голландский'
,'pl'=>'Польский'
,'pt_br'=>'Португальский (бразильский)'
,'ro'=>'Румынский'
,'ru'=>'Русский'
,'sv'=>'Шведский'
,'th'=>'Тайский'
,'tr'=>'Турецкий'
,'zh_cn'=>'Китайский (упрощенный)'
,'zh_tw'=>'Китайский (традиционный)'
}
,'sv'=> new Map<String,String>{
'cs'=>'Tjeckiska'
,'da'=>'Danska'
,'de'=>'Tyska'
,'en_us'=>'Engelska (USA)'
,'es'=>'Spanska'
,'es_mx'=>'Mexikansk spanska'
,'fi'=>'Finska'
,'fr'=>'Franska'
,'hu'=>'Ungerska'
,'in'=>'Indonesiska'
,'it'=>'Italienska'
,'ja'=>'Japanska'
,'ko'=>'Koreanska'
,'nl_nl'=>'Nederländska'
,'pl'=>'Polska'
,'pt_br'=>'Portugisiska (Brasilien)'
,'ro'=>'Rumänska'
,'ru'=>'Ryska'
,'sv'=>'Svenska'
,'th'=>'Thai'
,'tr'=>'Turkiska'
,'zh_cn'=>'Kinesiska (förenklad)'
,'zh_tw'=>'Kinesiska (traditionell)'
}
,'th'=> new Map<String,String>{
'cs'=>' '
,'da'=>''
,'de'=>''
,'en_us'=>' States (United)'
,'es'=>''
,'es_mx'=>' '
,'fi'=>''
,'fr'=>''
,'hu'=>''
,'in'=>''
,'it'=>''
,'ja'=>''
,'ko'=>''
,'nl_nl'=>''
,'pl'=>''
,'pt_br'=>' ()'
,'ro'=>''
,'ru'=>' '
,'sv'=>''
,'th'=>''
,'tr'=>' '
,'zh_cn'=>' ()'
,'zh_tw'=>' ()'
}
,'tr'=> new Map<String,String>{
'cs'=>'Çekçe'
,'da'=>'Danca'
,'de'=>'Almanca'
,'en_us'=>'İngilizce (ABD)'
,'es'=>'İspanyolca'
,'es_mx'=>'Mexican İspanyolca'
,'fi'=>'Fince'
,'fr'=>'Fransızca'
,'hu'=>'Macarca'
,'in'=>'Endonezya Dili'
,'it'=>'İtalyanca'
,'ja'=>'Japonca'
,'ko'=>'Korece'
,'nl_nl'=>'Hollanda Dili'
,'pl'=>'Lehçe'
,'pt_br'=>'Portekizce (Brezilya)'
,'ro'=>'Romence'
,'ru'=>'Rusça'
,'sv'=>'İsveççe'
,'th'=>'Tay'
,'tr'=>'Türkçe'
,'zh_cn'=>'Çince (Basitleştirilmiş)'
,'zh_tw'=>'Çince (Geleneksel)'
}
,'zh_cn'=> new Map<String,String>{
'cs'=>''
,'da'=>''
,'de'=>''
,'en_us'=>''
,'es'=>'西'
,'es_mx'=>'西西'
,'fi'=>''
,'fr'=>''
,'hu'=>''
,'in'=>'西'
,'it'=>''
,'ja'=>''
,'ko'=>''
,'nl_nl'=>''
,'pl'=>''
,'pt_br'=>'西'
,'ro'=>''
,'ru'=>''
,'sv'=>''
,'th'=>''
,'tr'=>''
,'zh_cn'=>''
,'zh_tw'=>''
}
,'zh_tw'=> new Map<String,String>{
'cs'=>''
,'da'=>''
,'de'=>''
,'en_us'=>''
,'es'=>'西'
,'es_mx'=>'西西'
,'fi'=>''
,'fr'=>''
,'hu'=>''
,'in'=>'西'
,'it'=>''
,'ja'=>''
,'ko'=>''
,'nl_nl'=>''
,'pl'=>''
,'pt_br'=>'西'
,'ro'=>''
,'ru'=>''
,'sv'=>''
,'th'=>''
,'tr'=>''
,'zh_cn'=>''
,'zh_tw'=>''
}
};
}

114
samples/Apex/TwilioAPI.cls Normal file
View File

@@ -0,0 +1,114 @@
/*
Copyright (c) 2012 Twilio, Inc.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* Entry point for accessing Twilio resources that are pre-configured
* with credentials from the Twilio Config custom setting (TwilioConfig__c).
*
* To set up your Twilio credentials:
* 1. Get a Twilio account at http://www.twilio.com/try-twilio
* 2. Find your Twilio Account Sid and Auth Token at https://www.twilio.com/user/account
* 3. Log into Salesforce and go to: Setup | Develop | Custom Settings | Manage Twilio Config
* 4. Create a new Twilo Config instance
* 5. Copy and paste your Account Sid and Auth Token and click Save
*
* NOTE: The Application Sid field is for use with the Twilio Client softphone
* SDK for Javascript. It is not required for the rest of the Twilio API.
*
* Now you can get easy access to Twilio from your Apex code by calling:
*
* TwilioRestClient restClient = TwilioAPI.getDefaultClient();
* restClient.getAccount().getCalls();
* // etc.
*/
global class TwilioAPI {
private class MissingTwilioConfigCustomSettingsException extends Exception {}
private static TwilioRestClient client;
private TwilioAPI() {}
/**
* Get a TwilioRestClient pre-populated with your TwilioConfig credentials
*/
public static TwilioRestClient getDefaultClient() {
if (client==null) {
TwilioConfig__c twilioCfg = getTwilioConfig();
TwilioAPI.client = new TwilioRestClient(twilioCfg.AccountSid__c, twilioCfg.AuthToken__c);
}
return TwilioAPI.client;
}
/**
* Get your primary account using your TwilioConfig credentials
*/
public static TwilioAccount getDefaultAccount() {
return getDefaultClient().getAccount();
}
/**
* Get a new Twilio Client capability token generator pre-populated
* with your TwilioConfig credentials
*/
public static TwilioCapability createCapability() {
TwilioConfig__c twilioCfg = getTwilioConfig();
return new TwilioCapability(twilioCfg.AccountSid__c, twilioCfg.AuthToken__c);
}
/**
* Get a new TwilioRestClient authorized with the credentials provided
*/
public static TwilioRestClient createClient(String accountSid, String authToken) {
return new TwilioRestClient(accountSid, authToken);
}
/**
* Load the org default TwilioConfig record
*/
public static TwilioConfig__c getTwilioConfig() {
TwilioConfig__c twilioCfg;
if (Test.isRunningTest()) {
twilioCfg = new TwilioConfig__c();
twilioCfg.AccountSid__c = 'ACba8bc05eacf94afdae398e642c9cc32d'; // dummy sid
twilioCfg.AuthToken__c = '12345678901234567890123456789012'; // dummy token
} else {
twilioCfg = TwilioConfig__c.getOrgDefaults();
if (twilioCfg==null)
throw new MissingTwilioConfigCustomSettingsException('Please enter your Twilio account credentials under Twilio Config custom settings (go to Setup | Develop | Custom Settings | Manage Twilio Config)');
}
return twilioCfg;
}
@isTest
static void test_TwilioAPI() {
System.assertEquals('ACba8bc05eacf94afdae398e642c9cc32d', TwilioAPI.getTwilioConfig().AccountSid__c);
System.assertEquals('12345678901234567890123456789012', TwilioAPI.getTwilioConfig().AuthToken__c);
System.assertEquals('ACba8bc05eacf94afdae398e642c9cc32d', TwilioAPI.getDefaultClient().getAccountSid());
System.assertEquals('ACba8bc05eacf94afdae398e642c9cc32d', TwilioAPI.getDefaultClient().getAccount().getSid());
System.assertEquals('ACba8bc05eacf94afdae398e642c9cc32d', TwilioAPI.getDefaultAccount().getSid());
}
}