Saturday, 27 May 2017

Abdera: Atom Source element

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.

Example
<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>


Following application get the source element from the feed generated by atom document ‘https://self-learning-java-tutorial.blogspot.com/atom.xml’.

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();
 }
}


ParseDemo.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();
  ;

 }
}





Previous                                                 Next                                                 Home

Abdera: Atom rights element

The rights element is a Text construct that conveys information about rights held in and over an entry or feed.

Example
<rights type="text">Copyrighted : Java Tutorial</rights>

Feed and Entry interfaces provide ‘setRights’ method to set right element.

Example
feed.setRights("Copyrighted : Java Tutorial");

Following is the complete working application.

HelloWorld.java
import java.io.IOException;
import java.util.Date;

import org.apache.abdera.Abdera;
import org.apache.abdera.model.Content;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.model.Text;
import org.apache.abdera.writer.Writer;

public class HelloWorld {

 private static void addMetaData(Feed feed) {
  feed.setId("tag:blogger.com,1999:blog-3062500619105519975");
  feed.setUpdated(new Date());
  feed.setTitle("java tutorial : Blog to learn java programming");
  feed.setSubtitle("Learners Blog");

  feed.addCategory("scheme", "Programming", "Java Tutorial for beginners");

  feed.addContributor("Krishna", "Krishna@Krishna.com", "https://self-learning-java-tutorial.blogspot.com");

  feed.setGenerator("http://www.blogger.com", "7.00", "Blogger");

  feed.setIcon("https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJHpypki-Y-JqQUorVvFkZkU0JWZKxkb138p8W-saAaVr4qaPKTgpkE7BV8sqq0elgI_pDejsHMxTEmY2KPLgwrkfyQXwWqkXYWRUJIKj_ci1JDFzVpKg1lddacb8SifWynpsWfmR_RH4j/s1600/1.bmp");

  addLinksToFeed(feed);
  addAuthorToFeed(feed);
  
  feed.setLogo("https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJHpypki-Y-JqQUorVvFkZkU0JWZKxkb138p8W-saAaVr4qaPKTgpkE7BV8sqq0elgI_pDejsHMxTEmY2KPLgwrkfyQXwWqkXYWRUJIKj_ci1JDFzVpKg1lddacb8SifWynpsWfmR_RH4j/s1600/1.bmp");
  
  feed.setRights("Copyrighted : Java Tutorial");
 }

 private static void addLinksToFeed(Feed feed) {
  /* Adding Links */
  String rel = "http://schemas.google.com/g/2005#feed";
  String type = "application/atom+xml";
  String href = "https://self-learning-java-tutorial.blogspot.com/feeds/posts/default";
  String title = "";
  String hreflang = "";
  long length = 0;

  feed.addLink(href, rel, type, title, hreflang, length);

  rel = "self";
  type = "application/atom+xml";
  href = "http://www.blogger.com/feeds/3062500619105519975/posts/default?alt=atom";

  feed.addLink(href, rel, type, title, hreflang, length);

 }

 private static void addAuthorToFeed(Feed feed) {
  String name = "hari krishna";
  String email = "noreply@blogger.com";
  String iri = "https://self-learning-java-tutorial.blogspot.com";

  feed.addAuthor(name, email, iri);
 }

 private static void addEntry(Feed feed) {

  Entry entry1 = feed.addEntry();
  entry1.setId("tag:blogger.com,1999:blog-3062500619105519975.post-918659526208416960");
  Date date = new Date();
  entry1.setPublished(date);
  entry1.setUpdated(date);
  entry1.setTitle("SWT: Slider Tutorial", Text.Type.TEXT);
  entry1.setContent("Slider class is used to define Slider widget", Content.Type.HTML);
  entry1.addAuthor("Hari Krishna Gurram", "noreply@blogger.com",
    "https://self-learning-java-tutorial.blogspot.com");
  entry1.addAuthor("Rama Krishna Gurram", "noreply@blogger.com",
    "https://self-learning-java-tutorial.blogspot.com");
  entry1.addContributor("Ritweek Mehenty", "noreply@blogger.com",
    "https://self-learning-java-tutorial.blogspot.com");
  entry1.addContributor("Sailaja Navakotla", "noreply@blogger.com",
    "https://self-learning-java-tutorial.blogspot.com");

  entry1.addCategory("scheme", "GUI", "SWT for beginners");
  entry1.setRights("Copyrighted : SWT Tutorial");

  feed.addEntry(entry1);
 }

 public static void main(String args[]) throws IOException {
  Abdera abdera = new Abdera();

  /* Create a new Feed instance. */
  Feed feed = abdera.newFeed();

  /* Populate feed */
  addMetaData(feed);
  addEntry(feed);

  /* Print the feed to console */
  Writer writer = abdera.getWriterFactory().getWriter("prettyxml");
  feed.writeTo(writer, System.out);
 }
}


Output
<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <id>tag:blogger.com,1999:blog-3062500619105519975</id>
  <updated>2016-12-17T18:33:54.228Z</updated>
  <title type="text">java tutorial : Blog to learn java programming</title>
  <subtitle type="text">Learners Blog</subtitle>
  <category term="Programming" scheme="scheme" label="Java Tutorial for beginners"/>
  <contributor>
    <name>Krishna</name>
    <email>Krishna@Krishna.com</email>
    <uri>https://self-learning-java-tutorial.blogspot.com</uri>
  </contributor>
  <generator uri="http://www.blogger.com" version="7.00">Blogger</generator>
  <icon>https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJHpypki-Y-JqQUorVvFkZkU0JWZKxkb138p8W-saAaVr4qaPKTgpkE7BV8sqq0elgI_pDejsHMxTEmY2KPLgwrkfyQXwWqkXYWRUJIKj_ci1JDFzVpKg1lddacb8SifWynpsWfmR_RH4j/s1600/1.bmp</icon>
  <link href="https://self-learning-java-tutorial.blogspot.com/feeds/posts/default" rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" title="" hreflang="" length="0"/>
  <link href="http://www.blogger.com/feeds/3062500619105519975/posts/default?alt=atom" rel="self" type="application/atom+xml" title="" hreflang="" length="0"/>
  <author>
    <name>hari krishna</name>
    <email>noreply@blogger.com</email>
    <uri>https://self-learning-java-tutorial.blogspot.com</uri>
  </author>
  <logo>https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJHpypki-Y-JqQUorVvFkZkU0JWZKxkb138p8W-saAaVr4qaPKTgpkE7BV8sqq0elgI_pDejsHMxTEmY2KPLgwrkfyQXwWqkXYWRUJIKj_ci1JDFzVpKg1lddacb8SifWynpsWfmR_RH4j/s1600/1.bmp</logo>
  <rights type="text">Copyrighted : Java Tutorial</rights>
  <entry>
    <id>tag:blogger.com,1999:blog-3062500619105519975.post-918659526208416960</id>
    <published>2016-12-17T18:33:54.252Z</published>
    <updated>2016-12-17T18:33:54.252Z</updated>
    <title type="text">SWT: Slider Tutorial</title>
    <content type="html">Slider class is used to define Slider widget</content>
    <author>
      <name>Hari Krishna Gurram</name>
      <email>noreply@blogger.com</email>
      <uri>https://self-learning-java-tutorial.blogspot.com</uri>
    </author>
    <author>
      <name>Rama Krishna Gurram</name>
      <email>noreply@blogger.com</email>
      <uri>https://self-learning-java-tutorial.blogspot.com</uri>
    </author>
    <contributor>
      <name>Ritweek Mehenty</name>
      <email>noreply@blogger.com</email>
      <uri>https://self-learning-java-tutorial.blogspot.com</uri>
    </contributor>
    <contributor>
      <name>Sailaja Navakotla</name>
      <email>noreply@blogger.com</email>
      <uri>https://self-learning-java-tutorial.blogspot.com</uri>
    </contributor>
    <category term="GUI" scheme="scheme" label="SWT for beginners"/>
    <rights type="text">Copyrighted : SWT Tutorial</rights>
  </entry>
</feed>




Previous                                                 Next                                                 Home

Friday, 26 May 2017

File.separator vs File.pathSeparator

File separator is used to construct file path. ‘/’ is the file separator in windows and ‘\’ is the file separator in Linux,

For Example
For the files f1, f2 and f3, the path looks like
f1/f2/f3 in Windows
f1\f2\f3 in Linux environment.

Following application is used to take list of file names as input and construct the path as output.

FileUtil.java
package com.sample.util;

import java.io.File;

public class FileUtil {

 private static final String EMPTY_STR = "";
 
 public static String constructPath(String[] fileNames){
  if(fileNames == null || fileNames.length == 0){
   return EMPTY_STR;
  }
  
  StringBuilder pathBuilder = new StringBuilder();
  
  for(String fileName : fileNames){
   pathBuilder.append(fileName).append(File.separator);
  }
  
  String path =  pathBuilder.toString();
  
  return path.substring(0, path.length()-1);
 }
 
}

FileUtilTest.java
package com.sample.util;

public class FileUtilTest {
 public static void main(String[] args) {
  String[] fileNames = { "f1", "f2", "f3" };

  String path = FileUtil.constructPath(fileNames);

  System.out.println(path);
 }
}

File path separator is used to combine list of file paths. ‘;’ is the file path separator in Windows, where as ‘:’ is the file path separator in Linux.

For example,

On Linux environment, paths can be combined using ‘:’ like below.

/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Java/JavaVirtualMachines/jdk1.8.0_77.jdk/Contents/Home/bin:

On Windows based systems, paths can be combined using ‘;’ like below.

C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Java\jdk1.8.0_102\bin;

Following application takes list of file paths as input and combine the paths using path separator.


FileUtil.java
package com.sample.util;

import java.io.File;

public class FileUtil {

 private static final String EMPTY_STR = "";

 public static String constructPath(String[] paths) {
  if (paths == null || paths.length == 0) {
   return EMPTY_STR;
  }

  StringBuilder pathBuilder = new StringBuilder();

  for (String path : paths) {
   pathBuilder.append(path).append(File.pathSeparator);
  }

  String path = pathBuilder.toString();

  return path.substring(0, path.length() - File.pathSeparator.length());
 }

}

FileUtilTest.java
package com.sample.util;

import java.io.File;

public class FileUtilTest {
 public static void main(String[] args) {
  String path1 = "f1" + File.separator + "f2";
  String path2 = "f1" + File.separator + "f2" + File.separator + "f3";
  String path3 = "folder1" + File.separator + "folder2";

  String[] paths = { path1, path2, path3 };

  String path = FileUtil.constructPath(paths);

  System.out.println(path);
 }
}




Split the string using file Path separator

In my previous post, I explained how to split a file path using file separator. Sometimes, you may want to split the string using file path separator.

What is path separator?
Path separator is used to combine list of paths. For example, In linux based systems ‘:’ is used as path separator, on Windows ‘;’ is used as path separator.

On Linux environment, paths can be combined using ‘:’ like below.

/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Java/JavaVirtualMachines/jdk1.8.0_77.jdk/Contents/Home/bin:

On Windows based systems, paths can be combined using ‘;’ like below.

C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Java\jdk1.8.0_102\bin;

Following program splits the file paths into list of file paths based on the file path separator.

For the following input
f1\f2\f3;folder1\folder2;users\Krishna

On Windows system, following application return output array like below.

{"f1\f2\f3", "folder1\folder2, "users\Krishna"}

FileUtil.java
package com.sample.util;

import java.io.File;

public class FileUtil {

 private static final String[] NO_PATHS = {};

 public static String[] filePaths(String str) {
  if (str == null || str.isEmpty()) {
   return NO_PATHS;
  }

  return str.split(File.pathSeparator);
 }

}

FileUtilTest.java
package com.sample.util;

import static org.junit.Assert.assertEquals;

import java.io.File;

import org.junit.Test;

public class FileUtilTest {

 @Test
 public void filePaths_empty_emptyArray() {
  String[] result = FileUtil.filePaths("");

  assertEquals(result.length, 0);
 }

 @Test
 public void filePaths_empty_nullArray() {
  String[] result = FileUtil.filePaths(null);

  assertEquals(result.length, 0);
 }

 @Test
 public void filePaths_filePaths_arrayWithfilePaths() {
  String fileName = "hello.txt";

  String[] result = FileUtil.filePaths(fileName);

  assertEquals(result[0], fileName);
 }

 @Test
 public void fileNames_filePaths_arrayWithFilePaths() {
  String path1 = "f1" + File.separator + "f2" + File.separator + "f3";
  String path2 = "folder1" + File.separator + "folder2";
  String path3 = "users" + File.separator + "Krishna";

  String paths = new StringBuilder(path1).append(File.pathSeparator).append(path2).append(File.pathSeparator)
    .append(path3).toString();

  String[] result = FileUtil.filePaths(paths);

  assertEquals(result[0], path1);
  assertEquals(result[1], path2);
  assertEquals(result[2], path3);
 }

}



Split file path using system file separator symbol

If you are working in files related application, you may come across the situation, where you want to split the file path using file separator. Following program takes file path as argument and return all the filenames in the path.

FileUtil.java
package com.sample.util;

import java.io.File;
import java.util.regex.Pattern;

public class FileUtil {

 private static final String[] NO_FILES_NAMES = {};

 public static String[] fileNames(String path) {
  if (path == null || path.isEmpty()) {
   return NO_FILES_NAMES;
  }

  String pattern = Pattern.quote(File.separator);
  String[] paths = path.split(pattern);
  return paths;
 }

}

FileUtilTest.java
package com.sample.util;

import static org.junit.Assert.assertEquals;

import java.io.File;

import org.junit.Test;

public class FileUtilTest {

 @Test
 public void fileNames_empty_emptyArray() {
  String[] result = FileUtil.fileNames("");

  assertEquals(result.length, 0);
 }

 @Test
 public void fileNames_empty_nullArray() {
  String[] result = FileUtil.fileNames(null);

  assertEquals(result.length, 0);
 }

 @Test
 public void fileNames_fileName_arrayWithFileName() {
  String fileName = "hello.txt";

  String[] result = FileUtil.fileNames(fileName);

  assertEquals(result[0], fileName);
 }

 @Test
 public void fileNames_fileNames_arrayWithFileNames() {
  String fileName = "f1" + File.separator + "f2" + File.separator + "f3";

  String[] result = FileUtil.fileNames(fileName);

  assertEquals(result[0], "f1");
  assertEquals(result[1], "f2");
  assertEquals(result[2], "f3");
 }

 @Test
 public void fileNames_fileNamesEndedWithSeparator_arrayWithFileNames() {
  String fileName = "f1" + File.separator + "f2" + File.separator + "f3" + File.separator;

  String[] result = FileUtil.fileNames(fileName);

  assertEquals(result[0], "f1");
  assertEquals(result[1], "f2");
  assertEquals(result[2], "f3");
 }

}