Deprecated: Assigning the return value of new by reference is deprecated in /home/warped/public_html/sfdc-heretic/wp-content/plugins/codesnippet/codesnippet.php on line 248

Strict Standards: Non-static method GoogleSitemapGenerator::Enable() should not be called statically in /home/warped/public_html/sfdc-heretic/wp-content/plugins/sitemap.php on line 2452
Salesforce Heretic » Salesforce.com Mail Merge - Part IV:

April 25, 2006

Salesforce.com Mail Merge - Part IV:

Filed under: Code, Salesforce.com, Mail Merge — heretic @ 10:55 am

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/warped/public_html/sfdc-heretic/wp-content/plugins/codesnippet/codesnippet.php on line 260

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/warped/public_html/sfdc-heretic/wp-content/plugins/codesnippet/codesnippet.php on line 261

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/warped/public_html/sfdc-heretic/wp-content/plugins/codesnippet/codesnippet.php on line 262

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/warped/public_html/sfdc-heretic/wp-content/plugins/codesnippet/codesnippet.php on line 263

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in /home/warped/public_html/sfdc-heretic/wp-includes/functions-formatting.php on line 76

If you haven’t read them, parts I, II, and III get into how were going to do the merge, as well as how we’re going to get the data. At this point we’ve settled on using the XML merge feed from the Salesforce.com UI, and we’re going to generate CSV data to get fed into Word.

Now it it’s to talk code. I’m going to make some assumptions here. First is that you know what object Id you want to merge the data from, second we’re going to not worry about getting the merge template file yet, and lastly we’ve already got the sessionID and information we’ll need.

I’ll be using the Apache Commons HTTPClient - it’s nicer to work with, handles keepalives and compression, and you’ll find it all over the place.

So we have the beginnings of our code that look something like this:

public class MergeUtil {

  private void doMerge(String id, String sessionId) {

    HttpState clientState = new HttpState();
    clientState.addCookie(
      new Cookie("na1.salesforce.com", "sid", sessionId, "/", null, false)
    );
    HttpClient httpClient = new HttpClient(connectionManager);
    httpClient.setState(clientState);

    GetMethod httpget = new GetMethod(
      "https://na1.salesforce.com/servlet/servlet.SForceMailMerge?id=" + id);
    int httpgetResult = httpClient.executeMethod(httpget);
  }

}

Basically we have a function that now creates an HTTP connection to the Salesforce.com UI, setting the correct cookie, and gets the XML merge document. At this point we’re ready to check the return value (httpgetResult comatins an HTTP status code, 200 = success) and parse the resulting XML. I’ll use the org.w3c.dom.* package to parse the XML file like so:

if (httpgetResult == 200) {
  InputStream xmlMergeDocStream = httpget.getResponseBodyAsStream();

  // XML Parsing Time...
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document mergeDoc = builder.parse(xmlMergeDocStream);

  httpget.releaseConnection();

  NodeList nodes_i = mergeDoc.getDocumentElement().getChildNodes();
  for (int i = 0; i < nodes_i.getLength(); i++) {
    if (nodes_i.item(i).getNodeType() == Node.ELEMENT_NODE
     && nodes_i.item(i).getNodeName() == "data") {
      Element element_i = (Element) nodes_i.item(i);
      addMerge(element_i.getAttribute("fieldName"), element_i.getTextContent());
    }
  }
}

So, to annotate, checking the return result we take the InputStream provided by the HTTP Request and feed it into the XML parser to build an XML Document object in Java. At this point we release the HTTP connection (no need to tie up the socket connection) and start the parsing.

If you remember all the data and field names were direct children of the top tag in the merge XML document. So all we need to do is iterate through the children of the document root. nodes_i will be that list of children and we’ll walk that. For each node we make sure it’s the right type and name (”data” - you’ll notice an extra tag at the bottom of the XML doc — I don’t use it, but you could if you wanted) and then take it and parse the field name and data out to an addMerge() function call.

Our addMerge() function takes the data and appends it to 2 global String variables, mergedCSVData and mergedFieldList.

private void addMerge(String fieldName, String fieldData) {
  if (fieldData == null)
    fieldData = "";
  if (mergedCSVData.length() > 0)
    mergedCSVData = mergedCSVData.concat(",");
  if (mergedFieldList.length() > 0)
    mergedFieldList = mergedFieldList.concat(",");

  mergedCSVData = mergedCSVData.concat("\"" + fieldData + "\"");
  mergedFieldList = mergedFieldList.concat("\"" + fieldName.trim() + "\"");
}

At this point we have parsed the XML document into CSV notation* and have 2 variables ready to be written to disk. To create the CSV file we create a file, and write the mergedFieldList first, and the CSVData on the next line. Vola!

(* This is a bit of a simplification of the CSV notation. Care must be taken to escape your data if it contains a quotation mark. In most cases data won’t have a “,” pattern and Word/Excel will just figure it out and be fine. But be wary.)

In part V I’ll show you how to get your Mail Merge Template file, and actually use Java to have Word do the merge.

License

This work is published under a Creative Commons Attribution-ShareAlike 2.5 License.


Strict Standards: Only variables should be assigned by reference in /home/warped/public_html/sfdc-heretic/wp-includes/functions.php on line 590
« What is a “Best Practice”?  
Strict Standards: Only variables should be assigned by reference in /home/warped/public_html/sfdc-heretic/wp-includes/functions.php on line 590
“Inside The Force” - No, really, it’s not me. »

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.