/*
* Copyright 2004 Sun Microsystems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.sun.syndication.samples;
import com.sun.syndication.feed.synd.SyndFeedI;
import com.sun.syndication.io.SyndFeedInput;
import java.applet.Applet;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* It Reads and prints any RSS/Atom feed type.
* <p>
* @author Alejandro Abdelnur
*
*/
public class FeedReaderApplet extends Applet {
public void start() {
try {
URL feedUrl = new URL(this.getParameter("feed.url"));
SyndFeedInput input = new SyndFeedInput();
SyndFeedI feed = input.build(getFeedReader(feedUrl));
System.out.println(feed);
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("ERROR: "+ex.getMessage());
}
}
// To handle charset encoding of incoming feed properly
private static final Pattern CHARSET_PATTERN = Pattern.compile("charset=([.[^; ]]*)");
private static Reader getFeedReader(URL feedUrl) throws IOException {
Reader reader;
URLConnection conn = feedUrl.openConnection();
if (feedUrl.getProtocol().equals("http") || feedUrl.getProtocol().equals("https")) {
// Finds out server charset encoding based on HTTP spec
String contentTypeHeader = conn.getContentType();
String encoding = "ISO-8859-1";
if (contentTypeHeader!=null) {
Matcher matcher = CHARSET_PATTERN.matcher(contentTypeHeader);
if (matcher.find()) {
encoding = matcher.group(1);
}
}
reader = new InputStreamReader(conn.getInputStream(),encoding);
}
else {
// Goes with plartform's default charset encoding
reader = new InputStreamReader(conn.getInputStream());
}
return reader;
}
}