How to write an RSS feed with Java?
I recommend using Rome:
// Feed header
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType("rss_2.0");
feed.setTitle("Sample Feed");
feed.setLink("http://example.com/");
// Feed entries
List entries = new ArrayList();
feed.setEntries(entries);
SyndEntry entry = new SyndEntryImpl();
entry.setTitle("Entry #1");
entry.setLink("http://example.com/post/1");
SyndContent description = new SyndContentImpl();
description.setType("text/plain");
description.setValue("There is text in here.");
entry.setDescription(description);
entries.add(entry);
// Write the feed to XML
StringWriter writer = new StringWriter();
new SyndFeedOutput().output(feed, writer);
System.out.println(writer.toString());
How to overwrite the default functionality of RSS feed in the AEM?
Since you are overlaying in /apps/<project>/
instead of /apps/
which is the default search path for the Sling.
Typically, Sling first searches in the /apps/
and then /libs/
and your changes are in /apps/<project>
this is why the default code is being picked up from the /libs/
.
You can resolve this in two ways -
- Move your changes from
/apps/<project>/
to/apps/
(easy but not recommended, as your changes are not in your project folder but outside of it) - Keep your changes in
/apps/<project>/
. To change the default search path of Sling, navigate to ./system/console/configMgr and change Resource Search Path field in Apache Sling Resource Resolver Factory configuration.
Get all RSS feed entries with Rome Library
When you call feed.getEntries()
, Rome library returns all entries that are available in http://example.com/rss
. It is not possible to get more than there are in the xml document (unless the entries have been cached in some service like Feedly).
See
- How to get all the posts from rss feed rather than the latest posts?
- How to get more feeds from RSS url?
- How Do I Fetch All Old Items on an RSS Feed?
java library for reading RSS and ATOM feeds
Have you had a look into the following list?
http://java-source.net/open-source/rss-rdf-tools
Even though it has been mentioned several times, I would suggest using Rome as well.
RSS feed using Spring boot
You wouldn't know if the URL is valid unless you make the http request. So in this case, it would be ideal to surround the code with a try-catch
and handle the exception accordingly. In case the URL isn't valid or returning no data, it can be handled by catching IOException
. In case the feed returned cannot be parsed or generated, it can be handled by catching FeedException
.
SyndFeedInput input = new SyndFeedInput();
int pageNumber = 1;
try{
do {
URL feedSource = new URL("https://altaonline.com/feed?paged=" + pageNumber);
SyndFeed feed = input.build(new XmlReader(feedSource));
pageNumber++;
}
while (pageNumber <= 27);
} catch (IOException ex){
System.out.println("IO exception occurred due to: "+ ex);
//Handle this exception accordingly
} catch (FeedException ex) {
System.out.println("Feed exception occurred due to: "+ ex);
//Handle this exception accordingly
}
You may even catch Exception
at the bottom for handling any other unknown exceptions that may occur. Please note that System.out.println
is only given as an example and ideally should be replaced by using a logging library.
get image url of rss with rome library
I for that get image tag , build new rss parser on the following:
public class NewRssParser extends RSS094Parser implements WireFeedParser {
public NewRssParser() {
this("rss_2.0");
}
protected NewRssParser(String type) {
super(type);
}
protected String getRSSVersion() {
return "2.0";
}
protected boolean isHourFormat24(Element rssRoot) {
return false;
}
protected Description parseItemDescription(Element rssRoot, Element eDesc) {
Description desc = super.parseItemDescription(rssRoot, eDesc);
desc.setType("text/html"); // change as per
// https://rome.dev.java.net/issues/show_bug.cgi?id=26
return desc;
}
public boolean isMyType(Document document) {
boolean ok;
Element rssRoot = document.getRootElement();
ok = rssRoot.getName().equals("rss");
if (ok) {
ok = false;
Attribute version = rssRoot.getAttribute("version");
if (version != null) {
// At this point, as far ROME is concerned RSS 2.0, 2.00 and
// 2.0.X are all the same, so let's use startsWith for leniency.
ok = version.getValue().startsWith(getRSSVersion());
}
}
return ok;
}
@Override
public Item parseItem(Element arg0, Element arg1) {
Item item = super.parseItem(arg0, arg1);
Element imageElement = arg1.getChild("image", getRSSNamespace());
if (imageElement != null) {
String imageUrl = imageElement.getText();
Element urlElement = imageElement.getChild("url");
imageUrl = urlElement != null ? urlElement.getText() : imageUrl;
Enclosure enc = new Enclosure();
enc.setType("image");
enc.setUrl(imageUrl);
item.getEnclosures().add(enc);
}
return item;
}
}
in the class override parseItem method and add code for get image element and add image's url to Enclosures.
then add following line to rome.properties file :
WireFeedParser.classes=[packge name].NewRssParser
Example :
WireFeedParser.classes=ir.armansoft.newscommunity.newsgathering.parser.impl.NewRssParser
Convert RSS Feed XML to JSON using Java Displays only Last Entry
Got it working like this:
@RequestMapping(value = "/v2/convertIntoJson",
method = RequestMethod.GET,
produces = "application/json")
public String getRssFeedAsJson() throws IOException {
InputStream xml = getInputStreamForURLData("http://www.samplefeed.com/feed/");
byte[] byteArray = IOUtils.toByteArray(xml);
String xmlString = new String(byteArray);
JSONObject xmlToJsonObject = XML.toJSONObject(xmlString);
String jsonString = xmlToJsonObject.toString();
byte[] jsonStringAsByteArray = jsonString.getBytes("UTF-8");
String retValue = new String(jsonStringAsByteArray, "UTF-8");
return retValue;
}
public static InputStream getInputStreamForURLData(String Url) {
URL url = null;
HttpURLConnection httpConnection = null;
InputStream content = null;
try {
url = new URL(Url);
System.out.println("URL::" + Url);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
httpConnection = (HttpURLConnection) conn;
int responseCode = httpConnection.getResponseCode();
System.out.println("Response Code : " + responseCode);
content = (InputStream) httpConnection.getInputStream();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return content;
}
RSS Feed parser library in Java
Take a look at:
- How to write an RSS feed with Java?
- java library for reading RSS and ATOM feeds
Related Topics
Java Null Check Why Use == Instead of .Equals()
Spring MVC - How to Get All Request Params in a Map in Spring Controller
How to Use Java.String.Format in Scala
Confusion: @Notnull VS. @Column(Nullable = False) with JPA and Hibernate
How Is an Instance Initializer Different from a Constructor
How to Create and Run Apache Jmeter Test Scripts from a Java Program
How to Format Decimals in a Currency Format
Program Freezes During Thread.Sleep() and with Timer
How to Convert a Java 8 Stream to an Array
Java Synchronized Method Lock on Object, or Method
Why Can't We Use 'This' Keyword in a Static Method
Swingutilities.Invokelater() Why Is It Needed
Booleans, Conditional Operators and Autoboxing