Optimal way to get Case.Id from Case.Thread_Id

Per the Spring '13, Release Notes this is being added to the standard library. A new Static method, getCaseIdFromEmailThreadId, has been added to the Cases class.

public class GetCaseIdController {

  public static void getCaseIdSample() {
    // Get email thread ID
    String emailThreadId = '_00Dxx1gEW._500xxYktg';
    // Call Apex method to retrieve case ID from email thread ID
    ID caseId = Cases.getCaseIdFromEmailThreadId(emailThreadId);
  }
}

The emailThreadId argument should have the following format: _00Dxx1gEW._500xxYktg. Other formats, such as ref:_00Dxx1gEW._500xxYktl:ref and [ref:_00Dxx1gEW._500xxYktl:ref], are invalid.


These are the helper functions I created to extract the Case Id from a Thread Id.

1) Break up the Thread Id to get the second part: (This can be done far better and neater but works for what I need)

  public static String ParseThreadId (String text){

      String[] result = text.split('ref\\:[0-9a-zA-Z]+\\.');

      if(result.size() >= 2){
        result = result[1].split('\\:ref');

        if(!result.isEmpty()){
          return result[0];
        }
      }  

      return '';  
  }

2) Pass the result of the previous function into this one to expand out the Case Id. When stored in a Thread Id all the '0' padding characters are removed. To get the Case Id you need to expand it back out:

  public static String ThreadToCaseId (String thread){

    if(thread.length() >= 5){ //If the string isnt at least 5 long it cant be a thread id
        String caseid = thread.substring(0,4);

        for(Integer  i = thread.length(); i < 15; i++){
          caseid += '0';
        }

        caseid += thread.substring(4);

      return caseid;
    }else{
      return '';
    }
  }

Tags:

Email

Soql

Apex