Thursday, 8 June 2017

Abdera: Sort feed entries by comparator

Feed interface provides 'sortEntries' method, it takes a comparator and sort the entries by using comparator.

Example
feed.sortEntries(new Comparator<Entry>(){

         @Override
         public int compare(Entry e1, Entry e2) {
                  return e1.getTitle().compareTo(e2.getTitle());
         }
                         
});
                
Above snippet sort the entries by using the title of the entry.

Following is the complete working application.

FeedUtil.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Optional;
import java.util.zip.GZIPInputStream;

import org.apache.abdera.Abdera;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.Parser;

/**
 * Utility class to parse Atom feed.
 * 
 * Usage :
 * <ul>
 * <li>Instantiate FeedUtil with atom document url. Call the getFeed method</li>
 * <li>to get the feed document associated with url.</li>
 * </ul>
 * 
 * @author Hari Krishna Gurram
 *
 */
public class FeedUtil {
 private String url;
 private InputStream in = null;
 private Feed feed = null;
 HttpURLConnection conn = null;

 public FeedUtil(String url) {
  this.url = url;
 }

 /**
  * 
  * @param url
  * @return Optional.empty if url is null (or) unable to parse the url, else
  *         return the Document object.
  */
 private Optional<Document<Feed>> getDocument() {
  if (url == null) {
   return Optional.empty();
  }

  try {
   URL urlTemp = new URL(url);

   conn = (HttpURLConnection) urlTemp.openConnection();
   conn.setRequestProperty("Accept-Encoding", "gzip");
   conn.connect();

   String contentEncoding = conn.getContentEncoding();
   boolean isGzip = contentEncoding != null && contentEncoding.contains("gzip");

   in = !isGzip ? conn.getInputStream() : new GZIPInputStream(conn.getInputStream());
   Abdera abdera = Abdera.getInstance();
   Parser parser = abdera.getParser();
   Document<Feed> document = parser.parse(in, url.toString());
   return Optional.of(document);

  } catch (Exception e) {
   e.printStackTrace();
  }

  return Optional.empty();
 }

 /**
  * 
  * @return the Feed object associated with given {@link url}. In any case if
  *         the feed creation is failed, then it return Optional.empty().
  */

 public synchronized Optional<Feed> getFeed() {
  if (feed != null) {
   return Optional.of(feed);
  }

  Optional<Document<Feed>> documentOpt = getDocument();

  if (!documentOpt.isPresent()) {
   return Optional.empty();
  }

  Document<Feed> document = documentOpt.get();

  feed = document.getRoot();
  return Optional.of(feed);
 }

 public void closeStreamAndConnection() {
  if (in != null) {
   try {
    in.close();
    //System.out.println("\nInput Stream is closed");
   } catch (IOException e1) {
    e1.printStackTrace();
   }
  }

  if (conn != null) {
   conn.disconnect();
   //System.out.println("Connection is disconnected");
  }
 }

 /**
  * This is just a safety check, if user forget to close the stram, it will
  * be closed once object is out of scope.
  */
 @Override
 public void finalize() {
  closeStreamAndConnection();
 }
}

ParserDemo.java
import java.io.IOException;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.ParseException;

public class ParserDemo {
 private static String url = "https://self-learning-java-tutorial.blogspot.com/atom.xml";

 public static void main(String args[]) throws ParseException, IOException {
  FeedUtil util = new FeedUtil(url);

  Optional<Feed> feedOpt = util.getFeed();

  if (!feedOpt.isPresent()) {
   System.out.println("No feed present");
   return;
  }

  Feed feed = feedOpt.get();

  feed.sortEntries(new Comparator<Entry>(){

   @Override
   public int compare(Entry e1, Entry e2) {
    return e1.getTitle().compareTo(e2.getTitle());
   }
   
  });

  List<Entry> entries = feed.getEntries();
  for (Entry entry : entries) {
   String title = entry.getTitle();
   Date editedDate = entry.getUpdated();

   System.out.println("title : " + title + " editedDate : " + editedDate);

  }
  
  
  util.closeStreamAndConnection();

 }
}


Sample Output
title : Apache Commons CLI Tutorial editedDate : Fri Dec 16 22:00:00 IST 2016
title : C#:  Socket Programming editedDate : Sat Dec 10 13:02:13 IST 2016
title : C#: Get the version of zeroMQ used in the application editedDate : Wed Dec 14 21:08:34 IST 2016
title : C#: zeroMQ: Publish-subscribe model sockets editedDate : Wed Dec 14 21:07:09 IST 2016
title : Client in C# and Server in Java  editedDate : Sat Dec 10 14:41:59 IST 2016
title : Commons CLI : Options class editedDate : Fri Dec 16 21:03:47 IST 2016
title : Commons CLI: Add multiple arguments to an option editedDate : Fri Dec 16 21:10:33 IST 2016
title : Commons CLI: Boolean options editedDate : Fri Dec 16 21:07:02 IST 2016
title : Commons CLI: Option: Specify single command line option editedDate : Fri Dec 16 19:48:44 IST 2016
title : Commons CLI: OptionGroup: group mutually Exclusive options editedDate : Fri Dec 16 21:23:39 IST 2016
title : Commons CLI: Parsing command line options editedDate : Fri Dec 16 21:24:04 IST 2016
title : Commons CLI: Print command line argument in the order you inserted editedDate : Fri Dec 16 21:21:35 IST 2016
title : Commons-CLI Define options using builder editedDate : Fri Dec 16 20:59:50 IST 2016
title : Commons-CLI: Set the display name for the argument editedDate : Fri Dec 16 20:56:15 IST 2016
title : Commons-CLI: Setting the compulsory options editedDate : Fri Dec 16 21:13:59 IST 2016
title : SWT: Focus listeners editedDate : Mon Dec 12 19:54:58 IST 2016
title : SWT: Mouse listeners editedDate : Fri Dec 09 08:36:39 IST 2016
title : SWT: Scale widget editedDate : Sat Dec 17 08:38:55 IST 2016
title : SWT: Slider editedDate : Sat Dec 17 08:39:42 IST 2016
title : SWT: TabFolder widget editedDate : Thu Dec 15 10:47:20 IST 2016
title : SWT: Table widget editedDate : Tue Dec 13 17:49:43 IST 2016
title : SWT: Text listeners editedDate : Fri Dec 09 20:21:59 IST 2016
title : Two way communication in C# client and socket editedDate : Sat Dec 10 13:06:51 IST 2016
title : zeroMQ C# Tutorial editedDate : Wed Dec 14 21:12:01 IST 2016
title : zeroMQ: Hello World Application editedDate : Wed Dec 14 20:56:36 IST 2016






Previous                                                 Next                                                 Home

Wednesday, 7 June 2017

Abdera: Sort the entries by edited date

Feed interface provides ‘sortEntriesByEdited’ method to sort the entries by edited date.

Feed sortEntriesByEdited(boolean new_first)
If new_first is set to true, then the latest edited entries comes first, if new_first is set to false, then the latest edited entries comes last.

Following is the complete working application.

FeedUtil.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Optional;
import java.util.zip.GZIPInputStream;

import org.apache.abdera.Abdera;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.Parser;

/**
 * Utility class to parse Atom feed.
 * 
 * Usage :
 * <ul>
 * <li>Instantiate FeedUtil with atom document url. Call the getFeed method</li>
 * <li>to get the feed document associated with url.</li>
 * </ul>
 * 
 * @author Hari Krishna Gurram
 *
 */
public class FeedUtil {
 private String url;
 private InputStream in = null;
 private Feed feed = null;
 HttpURLConnection conn = null;

 public FeedUtil(String url) {
  this.url = url;
 }

 /**
  * 
  * @param url
  * @return Optional.empty if url is null (or) unable to parse the url, else
  *         return the Document object.
  */
 private Optional<Document<Feed>> getDocument() {
  if (url == null) {
   return Optional.empty();
  }

  try {
   URL urlTemp = new URL(url);

   conn = (HttpURLConnection) urlTemp.openConnection();
   conn.setRequestProperty("Accept-Encoding", "gzip");
   conn.connect();

   String contentEncoding = conn.getContentEncoding();
   boolean isGzip = contentEncoding != null && contentEncoding.contains("gzip");

   in = !isGzip ? conn.getInputStream() : new GZIPInputStream(conn.getInputStream());
   Abdera abdera = Abdera.getInstance();
   Parser parser = abdera.getParser();
   Document<Feed> document = parser.parse(in, url.toString());
   return Optional.of(document);

  } catch (Exception e) {
   e.printStackTrace();
  }

  return Optional.empty();
 }

 /**
  * 
  * @return the Feed object associated with given {@link url}. In any case if
  *         the feed creation is failed, then it return Optional.empty().
  */

 public synchronized Optional<Feed> getFeed() {
  if (feed != null) {
   return Optional.of(feed);
  }

  Optional<Document<Feed>> documentOpt = getDocument();

  if (!documentOpt.isPresent()) {
   return Optional.empty();
  }

  Document<Feed> document = documentOpt.get();

  feed = document.getRoot();
  return Optional.of(feed);
 }

 public void closeStreamAndConnection() {
  if (in != null) {
   try {
    in.close();
    //System.out.println("\nInput Stream is closed");
   } catch (IOException e1) {
    e1.printStackTrace();
   }
  }

  if (conn != null) {
   conn.disconnect();
   //System.out.println("Connection is disconnected");
  }
 }

 /**
  * This is just a safety check, if user forget to close the stram, it will
  * be closed once object is out of scope.
  */
 @Override
 public void finalize() {
  closeStreamAndConnection();
 }
}

ParserDemo.java
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.ParseException;

public class ParserDemo {
 private static String url = "https://self-learning-java-tutorial.blogspot.com/atom.xml";

 public static void main(String args[]) throws ParseException, IOException {
  FeedUtil util = new FeedUtil(url);

  Optional<Feed> feedOpt = util.getFeed();

  if (!feedOpt.isPresent()) {
   System.out.println("No feed present");
   return;
  }

  Feed feed = feedOpt.get();

  feed.sortEntriesByEdited(true);

  List<Entry> entries = feed.getEntries();
  for (Entry entry : entries) {
   String title = entry.getTitle();
   Date editedDate = entry.getUpdated();

   System.out.println("title : " + title + " editedDate : " + editedDate);

  }
  
  System.out.println("\n\n\n");

  feed.sortEntriesByEdited(false);

  entries = feed.getEntries();
  for (Entry entry : entries) {
   String title = entry.getTitle();
   Date editedDate = entry.getUpdated();

   System.out.println("title : " + title + " editedDate : " + editedDate);

  }
  
  util.closeStreamAndConnection();

 }
}


Sample Output
title : SWT: Slider editedDate : Sat Dec 17 08:39:42 IST 2016
title : SWT: Scale widget editedDate : Sat Dec 17 08:38:55 IST 2016
title : Apache Commons CLI Tutorial editedDate : Fri Dec 16 22:00:00 IST 2016
title : Commons CLI: Parsing command line options editedDate : Fri Dec 16 21:24:04 IST 2016
title : Commons CLI: OptionGroup: group mutually Exclusive options editedDate : Fri Dec 16 21:23:39 IST 2016
title : Commons CLI: Print command line argument in the order you inserted editedDate : Fri Dec 16 21:21:35 IST 2016
title : Commons-CLI: Setting the compulsory options editedDate : Fri Dec 16 21:13:59 IST 2016
title : Commons CLI: Add multiple arguments to an option editedDate : Fri Dec 16 21:10:33 IST 2016
title : Commons CLI: Boolean options editedDate : Fri Dec 16 21:07:02 IST 2016
title : Commons CLI : Options class editedDate : Fri Dec 16 21:03:47 IST 2016
title : Commons-CLI Define options using builder editedDate : Fri Dec 16 20:59:50 IST 2016
title : Commons-CLI: Set the display name for the argument editedDate : Fri Dec 16 20:56:15 IST 2016
title : Commons CLI: Option: Specify single command line option editedDate : Fri Dec 16 19:48:44 IST 2016
title : SWT: TabFolder widget editedDate : Thu Dec 15 10:47:20 IST 2016
title : zeroMQ C# Tutorial editedDate : Wed Dec 14 21:12:01 IST 2016
title : C#: Get the version of zeroMQ used in the application editedDate : Wed Dec 14 21:08:34 IST 2016
title : C#: zeroMQ: Publish-subscribe model sockets editedDate : Wed Dec 14 21:07:09 IST 2016
title : zeroMQ: Hello World Application editedDate : Wed Dec 14 20:56:36 IST 2016
title : SWT: Table widget editedDate : Tue Dec 13 17:49:43 IST 2016
title : SWT: Focus listeners editedDate : Mon Dec 12 19:54:58 IST 2016
title : Client in C# and Server in Java  editedDate : Sat Dec 10 14:41:59 IST 2016
title : Two way communication in C# client and socket editedDate : Sat Dec 10 13:06:51 IST 2016
title : C#:  Socket Programming editedDate : Sat Dec 10 13:02:13 IST 2016
title : SWT: Text listeners editedDate : Fri Dec 09 20:21:59 IST 2016
title : SWT: Mouse listeners editedDate : Fri Dec 09 08:36:39 IST 2016




title : SWT: Mouse listeners editedDate : Fri Dec 09 08:36:39 IST 2016
title : SWT: Text listeners editedDate : Fri Dec 09 20:21:59 IST 2016
title : C#:  Socket Programming editedDate : Sat Dec 10 13:02:13 IST 2016
title : Two way communication in C# client and socket editedDate : Sat Dec 10 13:06:51 IST 2016
title : Client in C# and Server in Java  editedDate : Sat Dec 10 14:41:59 IST 2016
title : SWT: Focus listeners editedDate : Mon Dec 12 19:54:58 IST 2016
title : SWT: Table widget editedDate : Tue Dec 13 17:49:43 IST 2016
title : zeroMQ: Hello World Application editedDate : Wed Dec 14 20:56:36 IST 2016
title : C#: zeroMQ: Publish-subscribe model sockets editedDate : Wed Dec 14 21:07:09 IST 2016
title : C#: Get the version of zeroMQ used in the application editedDate : Wed Dec 14 21:08:34 IST 2016
title : zeroMQ C# Tutorial editedDate : Wed Dec 14 21:12:01 IST 2016
title : SWT: TabFolder widget editedDate : Thu Dec 15 10:47:20 IST 2016
title : Commons CLI: Option: Specify single command line option editedDate : Fri Dec 16 19:48:44 IST 2016
title : Commons-CLI: Set the display name for the argument editedDate : Fri Dec 16 20:56:15 IST 2016
title : Commons-CLI Define options using builder editedDate : Fri Dec 16 20:59:50 IST 2016
title : Commons CLI : Options class editedDate : Fri Dec 16 21:03:47 IST 2016
title : Commons CLI: Boolean options editedDate : Fri Dec 16 21:07:02 IST 2016
title : Commons CLI: Add multiple arguments to an option editedDate : Fri Dec 16 21:10:33 IST 2016
title : Commons-CLI: Setting the compulsory options editedDate : Fri Dec 16 21:13:59 IST 2016
title : Commons CLI: Print command line argument in the order you inserted editedDate : Fri Dec 16 21:21:35 IST 2016
title : Commons CLI: OptionGroup: group mutually Exclusive options editedDate : Fri Dec 16 21:23:39 IST 2016
title : Commons CLI: Parsing command line options editedDate : Fri Dec 16 21:24:04 IST 2016
title : Apache Commons CLI Tutorial editedDate : Fri Dec 16 22:00:00 IST 2016
title : SWT: Scale widget editedDate : Sat Dec 17 08:38:55 IST 2016
title : SWT: Slider editedDate : Sat Dec 17 08:39:42 IST 2016



Previous                                                 Next                                                 Home

Tuesday, 6 June 2017

Abdera: Sort the entries by updated date

Feed interface provides sortEntriesByUpdated method, by calling this function you can sort the entries in their updated date.

Feed sortEntriesByUpdated(boolean new_first);
If the flag new_first is set to true, then all the entries are sorted from newly updated date to old updated date. if the new_first flag is set to false, then the entries are sorted from old to new.

FeedUtil.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Optional;
import java.util.zip.GZIPInputStream;

import org.apache.abdera.Abdera;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.Parser;

/**
 * Utility class to parse Atom feed.
 * 
 * Usage :
 * <ul>
 * <li>Instantiate FeedUtil with atom document url. Call the getFeed method</li>
 * <li>to get the feed document associated with url.</li>
 * </ul>
 * 
 * @author Hari Krishna Gurram
 *
 */
public class FeedUtil {
 private String url;
 private InputStream in = null;
 private Feed feed = null;
 HttpURLConnection conn = null;

 public FeedUtil(String url) {
  this.url = url;
 }

 /**
  * 
  * @param url
  * @return Optional.empty if url is null (or) unable to parse the url, else
  *         return the Document object.
  */
 private Optional<Document<Feed>> getDocument() {
  if (url == null) {
   return Optional.empty();
  }

  try {
   URL urlTemp = new URL(url);

   conn = (HttpURLConnection) urlTemp.openConnection();
   conn.setRequestProperty("Accept-Encoding", "gzip");
   conn.connect();

   String contentEncoding = conn.getContentEncoding();
   boolean isGzip = contentEncoding != null && contentEncoding.contains("gzip");

   in = !isGzip ? conn.getInputStream() : new GZIPInputStream(conn.getInputStream());
   Abdera abdera = Abdera.getInstance();
   Parser parser = abdera.getParser();
   Document<Feed> document = parser.parse(in, url.toString());
   return Optional.of(document);

  } catch (Exception e) {
   e.printStackTrace();
  }

  return Optional.empty();
 }

 /**
  * 
  * @return the Feed object associated with given {@link url}. In any case if
  *         the feed creation is failed, then it return Optional.empty().
  */

 public synchronized Optional<Feed> getFeed() {
  if (feed != null) {
   return Optional.of(feed);
  }

  Optional<Document<Feed>> documentOpt = getDocument();

  if (!documentOpt.isPresent()) {
   return Optional.empty();
  }

  Document<Feed> document = documentOpt.get();

  feed = document.getRoot();
  return Optional.of(feed);
 }

 public void closeStreamAndConnection() {
  if (in != null) {
   try {
    in.close();
    //System.out.println("\nInput Stream is closed");
   } catch (IOException e1) {
    e1.printStackTrace();
   }
  }

  if (conn != null) {
   conn.disconnect();
   //System.out.println("Connection is disconnected");
  }
 }

 /**
  * This is just a safety check, if user forget to close the stram, it will
  * be closed once object is out of scope.
  */
 @Override
 public void finalize() {
  closeStreamAndConnection();
 }
}

ParserDemo.java
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.ParseException;

public class ParserDemo {
 private static String url = "https://self-learning-java-tutorial.blogspot.com/atom.xml";

 public static void main(String args[]) throws ParseException, IOException {
  FeedUtil util = new FeedUtil(url);

  Optional<Feed> feedOpt = util.getFeed();

  if (!feedOpt.isPresent()) {
   System.out.println("No feed present");
   return;
  }

  Feed feed = feedOpt.get();

  feed.sortEntriesByUpdated(true);

  List<Entry> entries = feed.getEntries();
  for (Entry entry : entries) {
   String title = entry.getTitle();
   Date updatedDate = entry.getUpdated();

   System.out.println("title : " + title + " updatedDate : " + updatedDate);

  }
  
  System.out.println("\n\n\n");

  feed.sortEntriesByUpdated(false);

  entries = feed.getEntries();
  for (Entry entry : entries) {
   String title = entry.getTitle();
   Date updatedDate = entry.getUpdated();

   System.out.println("title : " + title + " updatedDate : " + updatedDate);

  }
  
  util.closeStreamAndConnection();

 }
}


Sample Output
title : SWT: Slider updatedDate : Sat Dec 17 08:39:42 IST 2016
title : SWT: Scale widget updatedDate : Sat Dec 17 08:38:55 IST 2016
title : Apache Commons CLI Tutorial updatedDate : Fri Dec 16 22:00:00 IST 2016
title : Commons CLI: Parsing command line options updatedDate : Fri Dec 16 21:24:04 IST 2016
title : Commons CLI: OptionGroup: group mutually Exclusive options updatedDate : Fri Dec 16 21:23:39 IST 2016
title : Commons CLI: Print command line argument in the order you inserted updatedDate : Fri Dec 16 21:21:35 IST 2016
title : Commons-CLI: Setting the compulsory options updatedDate : Fri Dec 16 21:13:59 IST 2016
title : Commons CLI: Add multiple arguments to an option updatedDate : Fri Dec 16 21:10:33 IST 2016
title : Commons CLI: Boolean options updatedDate : Fri Dec 16 21:07:02 IST 2016
title : Commons CLI : Options class updatedDate : Fri Dec 16 21:03:47 IST 2016
title : Commons-CLI Define options using builder updatedDate : Fri Dec 16 20:59:50 IST 2016
title : Commons-CLI: Set the display name for the argument updatedDate : Fri Dec 16 20:56:15 IST 2016
title : Commons CLI: Option: Specify single command line option updatedDate : Fri Dec 16 19:48:44 IST 2016
title : SWT: TabFolder widget updatedDate : Thu Dec 15 10:47:20 IST 2016
title : zeroMQ C# Tutorial updatedDate : Wed Dec 14 21:12:01 IST 2016
title : C#: Get the version of zeroMQ used in the application updatedDate : Wed Dec 14 21:08:34 IST 2016
title : C#: zeroMQ: Publish-subscribe model sockets updatedDate : Wed Dec 14 21:07:09 IST 2016
title : zeroMQ: Hello World Application updatedDate : Wed Dec 14 20:56:36 IST 2016
title : SWT: Table widget updatedDate : Tue Dec 13 17:49:43 IST 2016
title : SWT: Focus listeners updatedDate : Mon Dec 12 19:54:58 IST 2016
title : Client in C# and Server in Java  updatedDate : Sat Dec 10 14:41:59 IST 2016
title : Two way communication in C# client and socket updatedDate : Sat Dec 10 13:06:51 IST 2016
title : C#:  Socket Programming updatedDate : Sat Dec 10 13:02:13 IST 2016
title : SWT: Text listeners updatedDate : Fri Dec 09 20:21:59 IST 2016
title : SWT: Mouse listeners updatedDate : Fri Dec 09 08:36:39 IST 2016




title : SWT: Mouse listeners updatedDate : Fri Dec 09 08:36:39 IST 2016
title : SWT: Text listeners updatedDate : Fri Dec 09 20:21:59 IST 2016
title : C#:  Socket Programming updatedDate : Sat Dec 10 13:02:13 IST 2016
title : Two way communication in C# client and socket updatedDate : Sat Dec 10 13:06:51 IST 2016
title : Client in C# and Server in Java  updatedDate : Sat Dec 10 14:41:59 IST 2016
title : SWT: Focus listeners updatedDate : Mon Dec 12 19:54:58 IST 2016
title : SWT: Table widget updatedDate : Tue Dec 13 17:49:43 IST 2016
title : zeroMQ: Hello World Application updatedDate : Wed Dec 14 20:56:36 IST 2016
title : C#: zeroMQ: Publish-subscribe model sockets updatedDate : Wed Dec 14 21:07:09 IST 2016
title : C#: Get the version of zeroMQ used in the application updatedDate : Wed Dec 14 21:08:34 IST 2016
title : zeroMQ C# Tutorial updatedDate : Wed Dec 14 21:12:01 IST 2016
title : SWT: TabFolder widget updatedDate : Thu Dec 15 10:47:20 IST 2016
title : Commons CLI: Option: Specify single command line option updatedDate : Fri Dec 16 19:48:44 IST 2016
title : Commons-CLI: Set the display name for the argument updatedDate : Fri Dec 16 20:56:15 IST 2016
title : Commons-CLI Define options using builder updatedDate : Fri Dec 16 20:59:50 IST 2016
title : Commons CLI : Options class updatedDate : Fri Dec 16 21:03:47 IST 2016
title : Commons CLI: Boolean options updatedDate : Fri Dec 16 21:07:02 IST 2016
title : Commons CLI: Add multiple arguments to an option updatedDate : Fri Dec 16 21:10:33 IST 2016
title : Commons-CLI: Setting the compulsory options updatedDate : Fri Dec 16 21:13:59 IST 2016
title : Commons CLI: Print command line argument in the order you inserted updatedDate : Fri Dec 16 21:21:35 IST 2016
title : Commons CLI: OptionGroup: group mutually Exclusive options updatedDate : Fri Dec 16 21:23:39 IST 2016
title : Commons CLI: Parsing command line options updatedDate : Fri Dec 16 21:24:04 IST 2016
title : Apache Commons CLI Tutorial updatedDate : Fri Dec 16 22:00:00 IST 2016
title : SWT: Scale widget updatedDate : Sat Dec 17 08:38:55 IST 2016
title : SWT: Slider updatedDate : Sat Dec 17 08:39:42 IST 2016





Previous                                                 Next                                                 Home

Monday, 5 June 2017

Can I pass null to append method of StringBuilder?

No, you can’t pass null as an argument to append method of StringBuilder. Let’s try to pass null argument and see what will happen.

Test.java
public class Test {
 public static void main(String args[]){
  StringBuilder builder = new StringBuilder();
  
  builder.append("First Name").append(null);
  
 }
}

Try to compile Test.java, you will end up in following error.
$javac Test.java
Test.java:5: error: reference to append is ambiguous
                builder.append("First Name").append(null);
                                            ^
  both method append(CharSequence) in StringBuilder and method append(char[]) in StringBuilder match
1 error

As you observe the error message, Java compiler is unable to get the proper append method that takes null argument, it is because append is overloaded in many forms, when you call the method append with null argument, it don’t know which one to call. One way to solve this problem is type cast the null to specific type.

builder.append("First Name").append((String)null);


Test.java
public class Test {
 public static void main(String args[]){
  StringBuilder builder = new StringBuilder();
  
  builder.append("First Name").append((String)null);
  
 }
}


Abdera: Create source element from Feed

If an atom entry copied from one feed to another, then source element is used to preserve original entry metadata.

If you got the feed instance, then you can call ‘getAsSource’ method to get the Source instance from feed.

Following is the complete working application.

FeedUtil.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Optional;
import java.util.zip.GZIPInputStream;

import org.apache.abdera.Abdera;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.Parser;

/**
 * Utility class to parse Atom feed.
 * 
 * Usage :
 * <ul>
 * <li>Instantiate FeedUtil with atom document url. Call the getFeed method</li>
 * <li>to get the feed document associated with url.</li>
 * </ul>
 * 
 * @author Hari Krishna Gurram
 *
 */
public class FeedUtil {
 private String url;
 private InputStream in = null;
 private Feed feed = null;
 HttpURLConnection conn = null;

 public FeedUtil(String url) {
  this.url = url;
 }

 /**
  * 
  * @param url
  * @return Optional.empty if url is null (or) unable to parse the url, else
  *         return the Document object.
  */
 private Optional<Document<Feed>> getDocument() {
  if (url == null) {
   return Optional.empty();
  }

  try {
   URL urlTemp = new URL(url);

   conn = (HttpURLConnection) urlTemp.openConnection();
   conn.setRequestProperty("Accept-Encoding", "gzip");
   conn.connect();

   String contentEncoding = conn.getContentEncoding();
   boolean isGzip = contentEncoding != null && contentEncoding.contains("gzip");

   in = !isGzip ? conn.getInputStream() : new GZIPInputStream(conn.getInputStream());
   Abdera abdera = Abdera.getInstance();
   Parser parser = abdera.getParser();
   Document<Feed> document = parser.parse(in, url.toString());
   return Optional.of(document);

  } catch (Exception e) {
   e.printStackTrace();
  }

  return Optional.empty();
 }

 /**
  * 
  * @return the Feed object associated with given {@link url}. In any case if
  *         the feed creation is failed, then it return Optional.empty().
  */

 public synchronized Optional<Feed> getFeed() {
  if (feed != null) {
   return Optional.of(feed);
  }

  Optional<Document<Feed>> documentOpt = getDocument();

  if (!documentOpt.isPresent()) {
   return Optional.empty();
  }

  Document<Feed> document = documentOpt.get();

  feed = document.getRoot();
  return Optional.of(feed);
 }

 public void closeStreamAndConnection() {
  if (in != null) {
   try {
    in.close();
    //System.out.println("\nInput Stream is closed");
   } catch (IOException e1) {
    e1.printStackTrace();
   }
  }

  if (conn != null) {
   conn.disconnect();
   //System.out.println("Connection is disconnected");
  }
 }

 /**
  * This is just a safety check, if user forget to close the stram, it will
  * be closed once object is out of scope.
  */
 @Override
 public void finalize() {
  closeStreamAndConnection();
 }
}

ParserDemo.java
import java.io.IOException;
import java.util.Optional;

import org.apache.abdera.Abdera;
import org.apache.abdera.model.Feed;
import org.apache.abdera.model.Source;
import org.apache.abdera.parser.ParseException;
import org.apache.abdera.writer.Writer;

public class ParserDemo {
 private static String url = "https://self-learning-java-tutorial.blogspot.com/atom.xml";

 public static void main(String args[]) throws ParseException, IOException {
  FeedUtil util = new FeedUtil(url);

  Optional<Feed> feedOpt = util.getFeed();

  if (!feedOpt.isPresent()) {
   System.out.println("No feed present");
   return;
  }

  Feed feed = feedOpt.get();

  Source source = feed.getAsSource();

  Writer writer = Abdera.getInstance().getWriterFactory().getWriter("prettyxml");
  source.writeTo(writer, System.out);

  util.closeStreamAndConnection();
  ;

 }
}


Sample Output
<source xmlns="http://www.w3.org/2005/Atom" xml:base="https://self-learning-java-tutorial.blogspot.com/atom.xml">
  <id>tag:blogger.com,1999:blog-3062500619105519975</id>
  <updated>2016-12-17T03:22:05.420-08:00</updated>
  <title type="text">java tutorial : Blog to learn java programming</title>
  <subtitle type="html"/>
  <link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="https://self-learning-java-tutorial.blogspot.com/feeds/posts/default"/>
  <link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3062500619105519975/posts/default?alt=atom"/>
  <link rel="alternate" type="text/html" href="https://self-learning-java-tutorial.blogspot.com/"/>
  <link rel="hub" href="http://pubsubhubbub.appspot.com/"/>
  <link rel="next" type="application/atom+xml" href="http://www.blogger.com/feeds/3062500619105519975/posts/default?alt=atom&amp;start-index=26&amp;max-results=25"/>
  <author>
    <name>hari krishna</name>
    <email>noreply@blogger.com</email>
    <gd:image xmlns:gd="http://schemas.google.com/g/2005" rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh5.googleusercontent.com/-6kwxUAiFEDA/AAAAAAAAAAI/AAAAAAAADTE/LmWjnEaeU5c/s512-c/photo.jpg"/>
  </author>
  <generator version="7.00" uri="http://www.blogger.com">Blogger</generator>
  <openSearch:totalResults xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">3834</openSearch:totalResults>
  <openSearch:startIndex xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">1</openSearch:startIndex>
  <openSearch:itemsPerPage xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">25</openSearch:itemsPerPage>
</source>




Previous                                                 Next                                                 Home