Apex download images from RSS feed as attachments

Update Blog Post Job calling from RSS

  @future(callout=true)
    static global void upsertContentMapping() {
        List<Dom.XMLNode> recentPosts = getRSSFeed('https://www.yoursite.com/resources/rss.xml');
        List<BP_Content_Mapping__c> blogEntries = new List<BP_Content_Mapping__c>();
        List<String> titles = new List<String>();
        List<BP_Content_Mapping__c> entriesToAdd = new List<BP_Content_Mapping__c>();

        String listOfBlogs = '';
        System.Debug('# OF POSTS FOUND:' +recentPosts.size());

        for(Dom.XMLNode post : recentPosts) {
           blogEntries.add(convertFeedToBlogPost(post));
        }

        System.Debug('# OF ENTRIES FOUND:' +blogEntries.size());

        for(BP_Content_Mapping__c bp : blogEntries) {
            titles.add(bp.Content_URL__c);
        }

        List<Attachment> blogAttachments = new List<Attachment>();
        List<BP_Content_Mapping__c> blogs = [SELECT Id, GUID__c from BP_Content_Mapping__c WHERE Content_URL__c IN :titles];
        Integer counter = 0 ;
        for(BP_Content_Mapping__c blogEntry : blogEntries) {
            if (counter < 10){
              Boolean added = false;
              for(BP_Content_Mapping__c blog : blogs) {
                  if(blog.GUID__c == blogEntry.GUID__c) { added = true; }
              }
              if(!added) {
                entriesToAdd.add(blogEntry);
                counter++;
              }
            }
        }

        Map<String, Attachment> attachments =  createAttachments(entriesToAdd);

        System.Debug('# OF ENTRIES TO IMPORT:' + entriesToAdd.size() + ' ' + entriesToAdd);
        insert entriesToAdd;

        for (BP_Content_Mapping__c entry : entriesToAdd){
          Attachment attachment = attachments.get(entry.GUID__c);
          attachment.ParentId = entry.Id;
          attachments.put(entry.GUID__c, attachment);
        }

        System.Debug('# OF ATTACHMENTS TO IMPORT:' + attachments.size() + ' ' + attachments);
        insert attachments.values();
   }

Get RSS feed and return XMLNode

static global List<Dom.XMLNode> getRSSFeed(string URL) {
      Http h = new Http();
      HttpRequest req = new HttpRequest();
      // url that returns the XML in the response body

      req.setEndpoint(url);
      req.setMethod('GET');
      HttpResponse res = h.send(req);
      Dom.Document doc = res.getBodyDocument();

      Dom.XMLNode rss = doc.getRootElement();
      System.debug('@@' + rss.getName());

      List<Dom.XMLNode> rssList = new List<Dom.XMLNode>();
      for(Dom.XMLNode child : rss.getChildren()) {
         System.debug('@@@' + child.getName());
         for(Dom.XMLNode channel : child.getChildren()) {
             System.debug('@@@@' + channel.getName());

             if(channel.getName() == 'item') {
                  rssList.add(channel);
             }
         }
      }
      return rssList;
  }

Convert XMLNode to Blog Posts

static global BP_Content_Mapping__c convertFeedToBlogPost(Dom.XMLNode post) {
      BP_Content_Mapping__c bp = new BP_Content_Mapping__c();
      Integer tagIndex = 0;

      for(Dom.XMLNode child : post.getChildren()) {
          if(child.getName() == 'title') { bp.Title__c = child.getText(); }
                    if(child.getName() == 'guid') { bp.GUID__c = child.getText(); }
          if(child.getName() == 'pubDate') { bp.Effective_Date__c = convertRSSDateStringToDate(child.getText()); }
          if(child.getName() == 'link') { bp.Content_URL__c = child.getText(); }
          if(child.getName() == 'description') {
            String[] descriptionPipeSlit = child.getText().split('\\|',-1);
            if (descriptionPipeSlit.size() > 0){
              bp.Summary__c = descriptionPipeSlit[0];
              bp.Author__c = descriptionPipeSlit[1].remove('Author:');
              bp.Blog_Category__c = descriptionPipeSlit[2].remove('Category:');
              bp.Category_Color__c = descriptionPipeSlit[3].remove('Color:');
            }
          }
          if ('content'.equals(child.getName())){
              bp.Image_URL__c = child.getAttributeValue('url', null);
          }
      }
      return bp;
  }

Download blog images to attachment

static Map<String, Attachment> createAttachments(List<BP_Content_Mapping__c> contentMappings){
    Map<String, Attachment> attachments = new Map<String, Attachment>();
    for (BP_Content_Mapping__c contentMapping : contentMappings){
      Attachment attachment = new Attachment();
      attachment.Name = contentMapping.Title__c + '.jpg';
      attachment.ContentType= 'image/jpg';
      attachment.Body = downloadImagesToBlob(contentMapping.Image_URL__c);
      attachments.put(contentMapping.GUID__c, attachment);
    }
    return attachments;
  }

  static Blob downloadImagesToBlob(String imageUrl){
      Http h = new Http();
      HttpRequest req = new HttpRequest();
      req.setEndpoint(imageUrl);
      req.setMethod('GET');
      req.setHeader('Content-Type', 'image/jpg');
      req.setCompressed(true);
      req.setTimeout(60000);
      HttpResponse res = null;
      res = h.send(req);
      Blob image = res.getBodyAsBlob();
      return image;
  }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: