Advertisement
Guest User

ArticlesDataSource.java

a guest
Jul 20th, 2012
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 17.63 KB | None | 0 0
  1. package com.mysite.datasources;
  2.  
  3. import java.io.IOException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6.  
  7. import javax.xml.parsers.SAXParser;
  8. import javax.xml.parsers.SAXParserFactory;
  9.  
  10. import org.apache.commons.lang3.StringEscapeUtils;
  11. import org.xml.sax.SAXParseException;
  12.  
  13. import android.content.ContentValues;
  14. import android.content.Context;
  15. import android.database.Cursor;
  16. import android.database.DatabaseUtils;
  17. import android.database.SQLException;
  18. import android.database.sqlite.SQLiteDatabase;
  19. import android.util.Log;
  20. import android.widget.Toast;
  21.  
  22. import com.mysite.models.Article;
  23. import com.mysite.models.Photo;
  24. import com.mysite.models.Section;
  25. import com.mysite.utilities.DateHelper;
  26. import com.mysite.utilities.DbHelper;
  27. import com.mysite.utilities.RSSHandler;
  28. import com.mysite.utilities.RSSHandler.NewsItem;
  29. import com.mysite.utilities.RSSHandler.PhotoItem;
  30.  
  31. public class ArticlesDataSource
  32. {
  33.  
  34.     private final Context mContext;
  35.    
  36.     // Database fields
  37.     private SQLiteDatabase database;
  38.     private DbHelper dbHelper;
  39.     private PhotosDataSource photosdatasource;
  40.     private SectionsDataSource sectionsdatasource;
  41.    
  42.     private final String[] allColumns = {
  43.         Article.TABLE + "." + Article.COLUMN_ID,
  44.         Article.TABLE + "." + Article.COLUMN_TITLE,
  45.         Article.TABLE + "." + Article.COLUMN_SUBTITLE,
  46.         Article.TABLE + "." + Article.COLUMN_LINK,
  47.         Article.TABLE + "." + Article.COLUMN_BYLINE,
  48.         Article.TABLE + "." + Article.COLUMN_DESCRIPTION,
  49.         Article.TABLE + "." + Article.COLUMN_STORYTEXT,
  50.         Article.TABLE + "." + Article.COLUMN_TRIBID,
  51.         Article.TABLE + "." + Article.COLUMN_PUBDATE,
  52.         Article.TABLE + "." + Article.COLUMN_KEYWORDS,
  53.         Article.TABLE + "." + Article.COLUMN_CATEGORY,
  54.         Article.TABLE + "." + Article.COLUMN_SUBCATEGORY,
  55.         Article.TABLE + "." + Article.COLUMN_WEIGHT,
  56.         Article.TABLE + "." + Article.COLUMN_MODIFIED,
  57.         Article.TABLE + "." + Article.COLUMN_S_TOP,
  58.         Article.TABLE + "." + Article.COLUMN_S_UTAH,
  59.         Article.TABLE + "." + Article.COLUMN_S_SPORTS,
  60.         Article.TABLE + "." + Article.COLUMN_S_MONEY,
  61.         Article.TABLE + "." + Article.COLUMN_S_OPINION,
  62.         Article.TABLE + "." + Article.COLUMN_S_MIX,
  63.         Article.TABLE + "." + Article.COLUMN_S_POPULAR,
  64.         Article.TABLE + "." + Article.COLUMN_S_BAGLEY,
  65.         Article.TABLE + "." + Article.COLUMN_S_OBITS,
  66.     };
  67.    
  68.     private final String[] listColumns = {
  69.         Article.TABLE + "." + Article.COLUMN_ID,
  70.         Article.TABLE + "." + Article.COLUMN_TITLE,
  71.         Article.TABLE + "." + Article.COLUMN_SUBTITLE,
  72.         Article.TABLE + "." + Article.COLUMN_BYLINE,
  73.         Article.TABLE + "." + Article.COLUMN_DESCRIPTION,
  74.         Article.TABLE + "." + Article.COLUMN_PUBDATE,
  75.         Photo.TABLE + "." + Photo.COLUMN_FILEPATH + " AS filepath"
  76.     };
  77.    
  78.     public ArticlesDataSource(Context context)
  79.     {
  80.         mContext = context;
  81.         dbHelper = new DbHelper(mContext);
  82.         photosdatasource = new PhotosDataSource(context);
  83.         sectionsdatasource = new SectionsDataSource(context);
  84.     }
  85.    
  86.     public void open() throws SQLException
  87.     {
  88.         database = dbHelper.getWritableDatabase();
  89.     }
  90.    
  91.     public void close()
  92.     {
  93.         dbHelper.close();
  94.     }
  95.    
  96.    
  97.     public void importArticles(String[] section, Boolean forceImport)
  98.     {
  99.         try
  100.         {
  101.             this.open();
  102.             //photosdatasource.open();
  103.            
  104.             Boolean shouldImport = true;
  105.            
  106.             if(!forceImport)
  107.             {
  108.                 //check if it's been at least an hour since last update
  109.                 String lastUpdated = sectionsdatasource.last_updated(section[Section.INDEX_SLUG]);
  110.                 int minutesSinceLastUpdate = 0;
  111.                 try
  112.                 {
  113.                     minutesSinceLastUpdate = DateHelper.minutesAgo(lastUpdated);
  114.                 }
  115.                 catch (Exception e)
  116.                 {
  117.                     minutesSinceLastUpdate = 9999;
  118.                 }
  119.                
  120.                
  121.                 if(minutesSinceLastUpdate < 60)
  122.                 {
  123.                     shouldImport = false;
  124.                 }
  125.             }
  126.            
  127.             if(shouldImport)
  128.             {
  129.                    
  130.                 //Parse the response data using SAX
  131.                 SAXParserFactory factory = SAXParserFactory.newInstance();
  132.                 SAXParser p = factory.newSAXParser();
  133.                 RSSHandler parser = new RSSHandler();
  134.                
  135.                 //Run the parsing operation
  136.                 try
  137.                 {
  138.                     p.parse(section[1], parser);
  139.                 }
  140.                 catch (SAXParseException e)
  141.                 {
  142.                     e.printStackTrace();
  143.                 }
  144.                 catch (IOException e)
  145.                 {
  146.                     e.printStackTrace();
  147.                 }
  148.                
  149.                 //Add all items from the parsed XML
  150.                 for(NewsItem item : parser.getParsedItems())
  151.                 {
  152.                     Article a1 = new Article();
  153.                     if(item.title != null) { a1.title = item.title.trim(); } else { a1.title = ""; }
  154.                     if(item.subhead != null) { a1.subtitle = item.subhead.trim(); } else { a1.subtitle = ""; }
  155.                     if(item.link != null) { a1.link = item.link.trim(); } else { a1.link = ""; }
  156.                     if(item.byline != null) { a1.byline = item.byline.trim(); } else { a1.byline = ""; }
  157.                     if(item.description != null) { a1.description = item.description.trim(); } else { a1.description = ""; }
  158.                     if(item.storytext != null) { a1.storytext = item.storytext.trim(); } else { a1.storytext = ""; }
  159.                     if(item.cmsstoryid != null) { a1.tribid = item.cmsstoryid.trim(); } else { a1.tribid = ""; }
  160.                     if(item.pubDate != null) { a1.pubdate = item.pubDate.trim(); } else { a1.pubdate = ""; }
  161.                     if(item.keyword != null) { a1.keywords = item.keyword.trim(); } else { a1.keywords = ""; }
  162.                     if(item.category != null) { a1.category = item.category.trim(); } else { a1.category = ""; }
  163.                     if(item.subcategory != null) { a1.subcategory = item.subcategory.trim(); } else { a1.subcategory = ""; }
  164.                     if(item.slotreference != null && item.slotreference.length() > 0) { a1.weight = Integer.parseInt(item.slotreference.trim()); } else { a1.weight = 0; }
  165.                     if(item.lastModTime != null) { a1.modified = item.lastModTime.trim(); } else { a1.modified = ""; }
  166.                    
  167.                     if(section[Section.INDEX_SLUG].equals(Section.TOP[Section.INDEX_SLUG])) { a1.s_top = 1; } //else { a1.s_top = 0; }
  168.                     if(section[Section.INDEX_SLUG].equals(Section.UTAH[Section.INDEX_SLUG])) { a1.s_utah = 1; } //else { a1.s_utah = 0; }
  169.                     if(section[Section.INDEX_SLUG].equals(Section.SPORTS[Section.INDEX_SLUG])) { a1.s_sports = 1; } //else { a1.s_sports = 0; }
  170.                     if(section[Section.INDEX_SLUG].equals(Section.MONEY[Section.INDEX_SLUG])) { a1.s_money = 1; } //else { a1.s_money = 0; }
  171.                     if(section[Section.INDEX_SLUG].equals(Section.OPINION[Section.INDEX_SLUG])) { a1.s_opinion = 1; } //else { a1.s_opinion = 0; }
  172.                     if(section[Section.INDEX_SLUG].equals(Section.MIX[Section.INDEX_SLUG])) { a1.s_mix = 1; } //else { a1.s_mix = 0; }
  173.                     if(section[Section.INDEX_SLUG].equals(Section.POPULAR[Section.INDEX_SLUG])) { a1.s_popular = 1; } //else { a1.s_popular = 0; }
  174.                     if(section[Section.INDEX_SLUG].equals(Section.BAGLEY[Section.INDEX_SLUG])) { a1.s_bagley = 1; } //else { a1.s_bagley = 0; }
  175.                     if(section[Section.INDEX_SLUG].equals(Section.OBITS[Section.INDEX_SLUG])) { a1.s_obits = 1; } //else { a1.s_obits = 0; }
  176.                    
  177.                     //add or update (check if it already exists)
  178.                     if(this.exists(a1.tribid))
  179.                     {
  180.                         if(this.needsUpdating(a1.tribid, a1.modified))
  181.                         {
  182.                             this.updateArticle(a1);
  183.                         }
  184.                         else
  185.                         {
  186.                             Log.d("MYSITE", "[/] Article doesn't need updating.");
  187.                         }
  188.                     }
  189.                     else
  190.                     {
  191.                         Log.d("MYSITE", "[+] Article: " + a1.title);
  192.                         this.createArticle(a1);
  193.                     }
  194.                    
  195.                    
  196.                     //repeats through any images and adds them to the database (with related article_id field populated)
  197.  
  198.                     for(PhotoItem photo : item.photos)
  199.                     {
  200.                         Photo p1 = new Photo();
  201.                         if(photo.photoid != null) { p1.tribid = photo.photoid.trim(); } else { p1.tribid = ""; }
  202.                         if(photo.caption != null) { p1.caption = photo.caption.trim(); } else { p1.caption = ""; }
  203.                         if(photo.height != null && photo.height.length() > 0) { p1.height = Math.round(Float.parseFloat(photo.height.trim())); } else { p1.height = 0; }
  204.                         if(photo.width != null && photo.width.length() > 0) { p1.width =  Math.round(Float.parseFloat(photo.width.trim())); } else { p1.width = 0; }
  205.                         if(photo.photo != null) { p1.filepath = photo.photo.trim(); } else { p1.filepath = ""; }
  206.                         if(a1.tribid != null) { p1.articletribid = a1.tribid; } else { p1.articletribid = ""; }
  207.                         if(photo.photolastmodified != null) { p1.modified = photo.photolastmodified.trim(); } else { p1.modified = ""; }
  208.                        
  209.                         //either add or update the photo
  210.                         if(photosdatasource.exists(p1.filepath))
  211.                         {
  212.                             photosdatasource.updatePhoto(p1);
  213.                         }
  214.                         else
  215.                         {
  216.                             photosdatasource.createPhoto(p1);
  217.                         }
  218.                        
  219.                     }
  220.                    
  221.                 }
  222.                
  223.                 //Updates section's last_updated field
  224.                 sectionsdatasource.updated(section[Section.INDEX_SLUG]);
  225.             } //end "should import
  226.         }
  227.         catch (Exception e)
  228.         {
  229.             e.printStackTrace();
  230.         }
  231.         finally
  232.         {
  233.             //photosdatasource.close();
  234.             this.close();
  235.         }
  236.        
  237.     }
  238.    
  239.     public long createArticle(Article article)
  240.     {
  241.         return database.insert(Article.TABLE, null, this.buildContentValues(article));
  242.     }
  243.    
  244.     public Article getArticleData(String id, Boolean showToast)
  245.     {  
  246.         Article a1 = new Article();
  247.         try
  248.         {
  249.             this.open();
  250.             Cursor cursor = database.query(Article.TABLE,
  251.                 allColumns,
  252.                 Article.COLUMN_ID + "=?",
  253.                 new String[] {id},
  254.                 null, null, null, null); //WHY CAN'T I USE "LIMIT 1" ?????
  255.             cursor.moveToFirst();
  256.             a1 = cursorToArticle(cursor);
  257.             cursor.close();
  258.         }
  259.         catch (Exception e)
  260.         {
  261.             e.printStackTrace();
  262.             if(showToast)
  263.             {
  264.                 //show "couldn't load" message
  265.                 Toast toast = Toast.makeText(
  266.                     this.mContext.getApplicationContext(),
  267.                     "NOTICE: Could not load selected article.",
  268.                     Toast.LENGTH_LONG);
  269.                 toast.show();
  270.             }
  271.         }
  272.         finally
  273.         {
  274.             this.close();
  275.         }
  276.         return a1;
  277.     }
  278.    
  279.     public int updateArticle(Article article)
  280.     {
  281.         return database.update(Article.TABLE, buildContentValues(article), Article.COLUMN_ID + " = ?", new String[] { String.valueOf(article.id) });
  282.     }
  283.    
  284.     private ContentValues buildContentValues(Article article)
  285.     {
  286.         ContentValues values = new ContentValues();
  287.         values.put(Article.COLUMN_TITLE, article.title);
  288.         values.put(Article.COLUMN_SUBTITLE, article.subtitle);
  289.         values.put(Article.COLUMN_LINK, article.link);
  290.         values.put(Article.COLUMN_BYLINE, article.byline);
  291.         values.put(Article.COLUMN_DESCRIPTION, article.description);
  292.         values.put(Article.COLUMN_STORYTEXT, article.storytext);
  293.         values.put(Article.COLUMN_TRIBID, article.tribid);
  294.         values.put(Article.COLUMN_PUBDATE, article.pubdate);
  295.         values.put(Article.COLUMN_KEYWORDS, article.keywords);
  296.         values.put(Article.COLUMN_CATEGORY, article.category);
  297.         values.put(Article.COLUMN_SUBCATEGORY, article.subcategory);
  298.         values.put(Article.COLUMN_WEIGHT, article.weight);
  299.         values.put(Article.COLUMN_MODIFIED, article.modified);
  300.         values.put(Article.COLUMN_S_TOP, article.s_top);
  301.         values.put(Article.COLUMN_S_UTAH, article.s_utah);
  302.         values.put(Article.COLUMN_S_SPORTS, article.s_sports);
  303.         values.put(Article.COLUMN_S_MONEY, article.s_money);
  304.         values.put(Article.COLUMN_S_OPINION, article.s_opinion);
  305.         values.put(Article.COLUMN_S_MIX, article.s_mix);
  306.         values.put(Article.COLUMN_S_POPULAR, article.s_popular);
  307.         values.put(Article.COLUMN_S_BAGLEY, article.s_bagley);
  308.         values.put(Article.COLUMN_S_OBITS, article.s_obits);
  309.         return values;
  310.     }
  311.    
  312.     public void deleteArticle(Article article)
  313.     {
  314.         System.out.println("Article deleted with id: " + article.id);
  315.         database.delete(Article.TABLE, Article.COLUMN_ID + " = " + article.id, null);
  316.     }
  317.    
  318.     public long getArticleCount()
  319.     {
  320.         return DatabaseUtils.queryNumEntries(database, Article.TABLE);
  321.     }
  322.    
  323.     public boolean exists(String tribid)
  324.     {
  325.         String countQuery = "SELECT count(" + Article.COLUMN_ID + ") FROM " + Article.TABLE + " WHERE " + Article.COLUMN_TRIBID + " = '" + tribid + "' LIMIT 1";
  326.         if(DatabaseUtils.longForQuery(database, countQuery, null) > 0)
  327.         {
  328.             return true;
  329.         }
  330.         else
  331.         {
  332.             return false;
  333.         }
  334.     }
  335.    
  336.     public boolean needsUpdating(String tribid, String modified)
  337.     {
  338.         String countQuery = "SELECT count(" + Article.COLUMN_ID + ") FROM " + Article.TABLE + " WHERE " + Article.COLUMN_TRIBID + " = '" + tribid + "' AND " + Article.COLUMN_MODIFIED + " < '" + modified + "' LIMIT 1";
  339.         if(DatabaseUtils.longForQuery(database, countQuery, null) > 0)
  340.         {
  341.             return true;
  342.         }
  343.         else
  344.         {
  345.             return false;
  346.         }
  347.     }
  348.    
  349.     public List<Article> getArticles(String[] section)
  350.     {
  351.         this.open();
  352.         List<Article> articles = new ArrayList<Article>();
  353.        
  354.         //queries the database
  355.         Log.d("MYSITE", "ArticlesDataSource: getArticles(): field: s_" + Section.currentSection[Section.INDEX_SLUG]);
  356.         Cursor cursor = database.query(
  357.                 Article.TABLE + " LEFT JOIN " + Photo.TABLE +
  358.                     " ON (" + Article.TABLE + "." + Article.COLUMN_TRIBID + " = " + Photo.TABLE + "." + Photo.COLUMN_ARTICLETRIBID + ")",
  359.                 listColumns,
  360.                 "s_" + section[Section.INDEX_SLUG] + "=1", //KLUDGE: builds the field name dynamically instead of referencing the model
  361.                 null, //
  362.                 Article.TABLE + "." + Article.COLUMN_ID, //group by
  363.                 null, //having
  364.                 Article.COLUMN_WEIGHT+" DESC ", //order
  365.                 null);
  366.        
  367.        
  368.         //sets the cursor to the first article
  369.         cursor.moveToFirst();
  370.         //repeat through and adds each article (via cursor) to the arciesl array
  371.         while(!cursor.isAfterLast())
  372.         {
  373.             Article article = cursorToArticleSummary(cursor);
  374.             articles.add(article);
  375.             cursor.moveToNext();
  376.         }
  377.         // Make sure to close the cursor
  378.         cursor.close();
  379.         this.close();
  380.         return articles;
  381.     }
  382.    
  383.     private Article cursorToArticle(Cursor cursor)
  384.     {
  385.         Article article = new Article();
  386.         article.id = cursor.getLong(cursor.getColumnIndex(Article.COLUMN_ID));
  387.         article.title = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_TITLE)));
  388.         article.subtitle = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_SUBTITLE)));
  389.         article.link = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_LINK)));
  390.         article.byline = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_BYLINE)));
  391.         article.description = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_DESCRIPTION)));
  392.         article.storytext = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_STORYTEXT)));
  393.         article.tribid = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_TRIBID)));
  394.         article.pubdate = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_PUBDATE)));
  395.         article.keywords = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_KEYWORDS)));
  396.         article.category = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_CATEGORY)));
  397.         article.subcategory = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_SUBCATEGORY)));
  398.         article.weight = cursor.getInt(cursor.getColumnIndex(Article.COLUMN_WEIGHT));
  399.         article.modified = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_MODIFIED)));
  400.        
  401.         //capitalize byline
  402.         article.byline = article.byline.toUpperCase();
  403.        
  404.         //clean up
  405.         if(article.storytext != null && article.storytext.length() != 0) {
  406.             article.storytext = article.storytext.replace("\r", "\n");
  407.             article.storytext = article.storytext.replace("\n\n", "\n");
  408.             article.storytext = article.storytext.replace("\n\n", "\n");
  409.             article.storytext = article.storytext.replace("\n\n", "\n");
  410.             article.storytext = article.storytext.replace("\n", "\n\n");
  411.         }
  412.         return article;
  413.     }
  414.    
  415.     private Article cursorToArticleSummary(Cursor cursor)
  416.     {
  417.         Article article = new Article();
  418.         //sets data for the list item's object
  419.         article.id = cursor.getLong(cursor.getColumnIndex(Article.COLUMN_ID));
  420.         article.title = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_TITLE)));
  421.         article.subtitle = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_SUBTITLE)));
  422.         article.description = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_DESCRIPTION)));
  423.         article.pubdate = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_PUBDATE)));
  424.         article.filepath = StringEscapeUtils.unescapeXml(cursor.getString(cursor.getColumnIndex(Article.COLUMN_THUMBPATH)));
  425.        
  426.         //cleans up (or replaces with "" if empty)
  427.         if(article.title != null && article.title.length() != 0) { article.title = article.title.replace("\n", ""); } else { article.title = ""; }
  428.         if(article.subtitle != null && article.subtitle.length() != 0) { article.subtitle = article.subtitle.replace("\n", ""); } else { article.subtitle = ""; }
  429.         if(article.description != null && article.description.length() != 0) { article.description = article.description.replace("\n", ""); } else { article.description = ""; }
  430.        
  431.         //truncates texts
  432.         if(article.subtitle != null && article.subtitle.length() != 0 && article.subtitle.length() > 90) { article.subtitle = article.subtitle.substring(0,90) + "..."; }
  433.         if(article.description != null && article.description.length() != 0 && article.description.length() > 90) { article.description = article.description.substring(0,90) + "..."; }
  434.                
  435.         return article;
  436.     }
  437.    
  438. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement