protected ProgrammeCache cache;
protected Stats stats = new Stats();
static Logger logger = Logger.getLogger(AbstractEPGSource.class);
-
- public static final int MAX_FETCH_TRIES=5;
+
+ public static final int MAX_FETCH_TRIES = 5;
public AbstractEPGSource(int sourceId, Config config) {
this.config = config;
}
public int getId() {
- return sourceId;
- }
-
+ return sourceId;
+ }
+
public void setId(int id) {
sourceId = id;
}
public List<Programme> getProgrammes(Channel channel, int day)
throws Exception {
- ArrayList<Channel> list = new ArrayList<Channel>(2);
- list.add(channel);
- return getProgrammes(list, day);
- }
+ ArrayList<Channel> list = new ArrayList<Channel>(2);
+ list.add(channel);
+ return getProgrammes(list, day);
+ }
@Override
public Stats getStats() {
Thread.sleep(config.niceMilliseconds);
StringBuffer buf = new StringBuffer();
boolean done = false;
- for(int count = 0; !done; count++) {
+ for (int count = 0; !done; count++) {
try {
- BufferedReader reader = new BufferedReader( new InputStreamReader( url.openStream()));
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(url.openStream()));
String s;
- while ((s = reader.readLine()) != null) buf.append(s);
+ while ((s = reader.readLine()) != null)
+ buf.append(s);
done = true;
} catch (IOException e) {
if (!config.quiet) {
- logger.warn("Error fetching from url " + url + ", count="+count);
+ logger.warn("Error fetching from url " + url + ", count="
+ + count);
}
- if (count>=MAX_FETCH_TRIES) {
+ if (count >= MAX_FETCH_TRIES) {
stats.fetchErrors++;
logger.debug("Error getting progrm data from url", e);
- throw new Exception("Error getting program data from url " + url, e);
+ throw new Exception("Error getting program data from url "
+ + url, e);
}
}
}
- return buf.toString();
+ return buf.toString();
}
-
+
public void clearCache() {
cache.clear(sourceId);
}
List<String> parseKijkwijzer(String s) {
List<String> result = new ArrayList<String>();
- for (int i=0; i<s.length(); i++) {
+ for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
- switch(c) {
- case 'a':result.add("Angst"); break;
- case 'd':result.add("Discriminatie"); break;
- case 's':result.add("Seks"); break;
- case 'h':result.add("Drugs/Alcohol"); break;
- case 'g':result.add("Geweld"); break;
- case 't':result.add("Grof taalgebruik"); break;
- case '1':result.add("Voor alle leeftijden"); break;
- case '2':result.add("Afgeraden voor kinderen jonger dan 6 jaar"); break;
- case '9':result.add("Afgeraden voor kinderen jonger dan 9 jaar"); break;
- case '3':result.add("Afgeraden voor kinderen jonger dan 12 jaar"); break;
- case '4':result.add("Afgeraden voor kinderen jonger dan 16 jaar"); break;
- case '5': break; // Lijkt op een foutje van RTL, bedoeld wordt wrsch "12 jaar en ouder". Wordt op RTL tvgids niet weegegeven.
- default: if (!config.quiet) {
- logger.warn("Unknown kijkwijzer character: " + c + " in string " + s);
+ switch (c) {
+ case 'a':
+ result.add("Angst");
+ break;
+ case 'd':
+ result.add("Discriminatie");
+ break;
+ case 's':
+ result.add("Seks");
+ break;
+ case 'h':
+ result.add("Drugs/Alcohol");
+ break;
+ case 'g':
+ result.add("Geweld");
+ break;
+ case 't':
+ result.add("Grof taalgebruik");
+ break;
+ case '1':
+ result.add("Voor alle leeftijden");
+ break;
+ case '2':
+ result.add("Afgeraden voor kinderen jonger dan 6 jaar");
+ break;
+ case '9':
+ result.add("Afgeraden voor kinderen jonger dan 9 jaar");
+ break;
+ case '3':
+ result.add("Afgeraden voor kinderen jonger dan 12 jaar");
+ break;
+ case '4':
+ result.add("Afgeraden voor kinderen jonger dan 16 jaar");
+ break;
+ case '5':
+ break; // Lijkt op een foutje van RTL, bedoeld wordt wrsch
+ // "12 jaar en ouder". Wordt op RTL tvgids niet
+ // weegegeven.
+ default:
+ if (!config.quiet) {
+ logger.warn("Unknown kijkwijzer character: " + c
+ + " in string " + s);
}
}
}
List<String> urls;\r
protected boolean enabled = true;\r
int source;\r
- \r
+\r
protected Channel(int source, String id) {\r
this.id = id;\r
this.source = source;\r
icons = new ArrayList<Icon>();\r
urls = new ArrayList<String>();\r
}\r
- \r
+\r
public String defaultName() {\r
return names.get(0);\r
}\r
- \r
+\r
static Channel getChannel(int source, String id, String name) {\r
Channel c = new Channel(source, id);\r
c.names.add(name);\r
c.icons.add(new Icon(iconUrl));\r
return c;\r
}\r
- \r
+\r
public String getXmltvChannelId() {\r
- return id+"."+getSourceName();\r
+ return id + "." + getSourceName();\r
}\r
- \r
+\r
public String getSourceName() {\r
return EPGSourceFactory.newInstance().getChannelSourceName(source);\r
}\r
- \r
+\r
public void serialize(XMLStreamWriter writer) throws XMLStreamException {\r
writer.writeStartElement("channel");\r
writer.writeAttribute("id", getXmltvChannelId());\r
- for(String name: names) {\r
+ for (String name : names) {\r
writer.writeStartElement("display-name");\r
writer.writeAttribute("lang", "nl");\r
writer.writeCharacters(name);\r
writer.writeEndElement();\r
}\r
- for(Icon i: icons) {\r
+ for (Icon i : icons) {\r
i.serialize(writer);\r
}\r
- for(String url: urls) {\r
+ for (String url : urls) {\r
writer.writeStartElement("url");\r
writer.writeCharacters(url);\r
writer.writeEndElement();\r
public void setEnabled(boolean b) {\r
this.enabled = b;\r
}\r
- \r
- public String toString() {\r
- return "Channel " + source + "::" + id + " (" + defaultName() + ")";\r
- }\r
+\r
+ public String toString() {\r
+ return "Channel " + source + "::" + id + " (" + defaultName() + ")";\r
+ }\r
}
\ No newline at end of file
package org.vanbest.xmltv;
/*
- Copyright (c) 2012 Jan-Pascal van Best <janpascal@vanbest.org>
+ Copyright (c) 2012 Jan-Pascal van Best <janpascal@vanbest.org>
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
- The full license text can be found in the LICENSE file.
-*/
+ The full license text can be found in the LICENSE file.
+ */
import java.io.BufferedReader;
import java.io.File;
import org.apache.log4j.Logger;
public class Config {
- //constants
- private final static int CURRENT_FILE_FORMAT=4;
+ // constants
+ private final static int CURRENT_FILE_FORMAT = 4;
// in config file
public int niceMilliseconds;
public String cacheDbHandle;
public String cacheDbUser;
public String cacheDbPassword;
-
+
// not stored (yet)
public boolean joinKijkwijzerRatings = true;
boolean fetchDetails = true;
-
+
// command-line options
boolean quiet = false;
-
+
String project_version;
String build_time;
static Logger logger = Logger.getLogger(Config.class);
-
+
private Config() {
Properties configProp = new Properties();
- InputStream in = ClassLoader.getSystemResourceAsStream("tv_grab_nl_java.properties");
- try {
- configProp.load(in);
- } catch (IOException e) {
- logger.warn("Error reading application properties from tv_grab_nl_java.properties resource");
- logger.debug("stack trace: ", e);
- }
- project_version=configProp.getProperty("project.version");
- build_time=configProp.getProperty("build.time");
+ InputStream in = ClassLoader
+ .getSystemResourceAsStream("tv_grab_nl_java.properties");
+ try {
+ configProp.load(in);
+ } catch (IOException e) {
+ logger.warn("Error reading application properties from tv_grab_nl_java.properties resource");
+ logger.debug("stack trace: ", e);
+ }
+ project_version = configProp.getProperty("project.version");
+ build_time = configProp.getProperty("build.time");
}
-
+
public static Config getDefaultConfig() {
Config result = new Config();
result.channels = new ArrayList<Channel>();
result.cattrans = getDefaultCattrans();
result.niceMilliseconds = 500;
- String cachefile = FileUtils.getFile(FileUtils.getUserDirectory(), ".xmltv", "tv_grab_nl_java.cache").getPath();
+ String cachefile = FileUtils.getFile(FileUtils.getUserDirectory(),
+ ".xmltv", "tv_grab_nl_java.cache").getPath();
result.setCacheFile(cachefile);
result.cacheDbUser = "SA";
result.cacheDbPassword = "";
return result;
}
-
- public Map<String,String> getCategories() {
+
+ public Map<String, String> getCategories() {
return cattrans;
}
}
public static File defaultCacheFile() {
- return FileUtils.getFile(FileUtils.getUserDirectory(), ".xmltv", "tv_grab_nl_java.cache");
+ return FileUtils.getFile(FileUtils.getUserDirectory(), ".xmltv",
+ "tv_grab_nl_java.cache");
}
public String translateCategory(String category) {
- if(!cattrans.containsKey(category.toLowerCase())) {
+ if (!cattrans.containsKey(category.toLowerCase())) {
return category;
}
return cattrans.get(category.toLowerCase());
}
- static private Map<String,String> getDefaultCattrans() {
- Map<String,String> result = new HashMap<String,String>();
+ static private Map<String, String> getDefaultCattrans() {
+ Map<String, String> result = new HashMap<String, String>();
result.put("amusement", "Animated");
result.put("comedy", "Comedy");
result.put("documentaire", "Documentary");
result.put("informatief", "Educational");
result.put("jeugd", "Children");
result.put("kunst/cultuur", "Arts/Culture");
- result.put("misdaad", "Crime/Mystery");
+ result.put("misdaad", "Crime/Mystery");
result.put("muziek", "Music");
result.put("natuur", "Science/Nature");
result.put("nieuws/actualiteiten", "News");
public void writeConfig(File configFile) throws IOException {
FileUtils.forceMkdir(configFile.getParentFile());
- PrintWriter out = new PrintWriter(new OutputStreamWriter( new FileOutputStream( configFile )));
+ PrintWriter out = new PrintWriter(new OutputStreamWriter(
+ new FileOutputStream(configFile)));
out.println("config-file-format: " + CURRENT_FILE_FORMAT);
out.println("cache-db-handle: " + escape(cacheDbHandle));
out.println("cache-db-user: " + escape(cacheDbUser));
out.println("cache-db-password: " + escape(cacheDbPassword));
out.println("nice-time-milliseconds: " + niceMilliseconds);
- for(Channel c: channels) {
+ for (Channel c : channels) {
// FIXME: handle multiple channels names, icons and urls
- out.print("channel: " + c.getSourceName() +
- ": " + c.id +
- ": " + (c.enabled?"enabled":"disabled") +
- ": " + escape(c.defaultName()));
+ out.print("channel: " + c.getSourceName() + ": " + c.id + ": "
+ + (c.enabled ? "enabled" : "disabled") + ": "
+ + escape(c.defaultName()));
if (!c.icons.isEmpty()) {
out.print(" : " + escape(c.icons.get(0).url));
}
out.println();
}
- for(Map.Entry<String,String> entry: cattrans.entrySet()) {
- out.println("category: " + escape(entry.getKey()) + ": " + escape(entry.getValue()));
+ for (Map.Entry<String, String> entry : cattrans.entrySet()) {
+ out.println("category: " + escape(entry.getKey()) + ": "
+ + escape(entry.getValue()));
}
out.close();
}
-
+
public static String escape(String s) {
- return "\"" + s.replace("\\", "\\\\").replaceAll("\\\"", "\\\\\"") + "\"";
+ return "\"" + s.replace("\\", "\\\\").replaceAll("\\\"", "\\\\\"")
+ + "\"";
}
public static List<String> splitLine(String s) {
List<String> parts = new ArrayList<String>(5);
- int pos=0;
+ int pos = 0;
while (true) {
// Find first colon outside quotes
- boolean quoted=false;
- int quoteStart=-1;
+ boolean quoted = false;
+ int quoteStart = -1;
StringBuffer buf = new StringBuffer();
- for (; pos<s.length(); pos++) {
- if (s.charAt(pos)=='"') {
+ for (; pos < s.length(); pos++) {
+ if (s.charAt(pos) == '"') {
if (quoted) {
- //System.out.println(s.substring(quoteStart, pos));
- buf.append(s.substring(quoteStart, pos).replaceAll("\\\\\"", "\\\"").replaceAll("\\\\\\\\","\\\\"));
+ // System.out.println(s.substring(quoteStart, pos));
+ buf.append(s.substring(quoteStart, pos)
+ .replaceAll("\\\\\"", "\\\"")
+ .replaceAll("\\\\\\\\", "\\\\"));
} else {
- quoteStart = pos+1;
+ quoteStart = pos + 1;
}
- quoted=!quoted;
+ quoted = !quoted;
continue;
}
- if(s.charAt(pos)=='\\') pos++;
- if(quoted) continue;
- if(s.charAt(pos)==':') {
+ if (s.charAt(pos) == '\\')
+ pos++;
+ if (quoted)
+ continue;
+ if (s.charAt(pos) == ':') {
break;
}
buf.append(s.charAt(pos));
}
parts.add(buf.toString().trim());
- if (pos>=s.length()) {
+ if (pos >= s.length()) {
break;
}
pos++;
public static Config readConfig(File file) {
Config result = getDefaultConfig();
- result.cattrans = new HashMap<String,String>();
- int fileformat=0; // Assume legacy config file format
+ result.cattrans = new HashMap<String, String>();
+ int fileformat = 0; // Assume legacy config file format
try {
- BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream( file)));
-
- while(true) {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(
+ new FileInputStream(file)));
+
+ while (true) {
String s = reader.readLine();
- if(s==null) break;
- //System.out.println(s);
- if (!s.contains(":")) continue;
- if (s.startsWith("#")) continue;
+ if (s == null)
+ break;
+ // System.out.println(s);
+ if (!s.contains(":"))
+ continue;
+ if (s.startsWith("#"))
+ continue;
List<String> parts = splitLine(s);
- String key = parts.get(0).toLowerCase();
- if(key.equals("channel")) {
+ String key = parts.get(0).toLowerCase();
+ if (key.equals("channel")) {
Channel c = null;
- // System.out.println("Adding channel " + parts + " in file format " + fileformat);
- switch(fileformat) {
+ // System.out.println("Adding channel " + parts +
+ // " in file format " + fileformat);
+ switch (fileformat) {
case 0:
- c = Channel.getChannel(EPGSourceFactory.newInstance().getChannelSourceId("tvgids.nl"), parts.get(1), parts.get(2));
- if (parts.size()>3) {
+ c = Channel.getChannel(EPGSourceFactory.newInstance()
+ .getChannelSourceId("tvgids.nl"), parts.get(1),
+ parts.get(2));
+ if (parts.size() > 3) {
c.addIcon(parts.get(3));
}
break;
case 1:
- c = Channel.getChannel(EPGSourceFactory.newInstance().getChannelSourceId("tvgids.nl"), parts.get(1), parts.get(3));
- if (parts.size()>4) {
+ c = Channel.getChannel(EPGSourceFactory.newInstance()
+ .getChannelSourceId("tvgids.nl"), parts.get(1),
+ parts.get(3));
+ if (parts.size() > 4) {
c.addIcon(parts.get(4));
}
String value = parts.get(2);
if (value.equals("enabled")) {
- c.setEnabled(true);
+ c.setEnabled(true);
} else if (value.equals("disabled")) {
- c.setEnabled(false);
+ c.setEnabled(false);
} else {
- logger.error("Error in config file, unknown channel status \"" + parts.get(2) + "\", should be enabled or disabled");
+ logger.error("Error in config file, unknown channel status \""
+ + parts.get(2)
+ + "\", should be enabled or disabled");
}
break;
case 2:
case 3:
case 4:
int source;
- if (fileformat==2) {
+ if (fileformat == 2) {
source = Integer.parseInt(parts.get(1));
} else {
- source = EPGSourceFactory.newInstance().getChannelSourceId(parts.get(1));
+ source = EPGSourceFactory.newInstance()
+ .getChannelSourceId(parts.get(1));
}
- c = Channel.getChannel(source, parts.get(2), parts.get(4));
- if (parts.size()>5) {
+ c = Channel.getChannel(source, parts.get(2),
+ parts.get(4));
+ if (parts.size() > 5) {
c.addIcon(parts.get(5));
}
value = parts.get(3);
if (value.equals("enabled")) {
- c.setEnabled(true);
+ c.setEnabled(true);
} else if (value.equals("disabled")) {
- c.setEnabled(false);
+ c.setEnabled(false);
} else {
- logger.error("Error in config file, unknown channel status \"" + parts.get(3) + "\", should be enabled or disabled");
+ logger.error("Error in config file, unknown channel status \""
+ + parts.get(3)
+ + "\", should be enabled or disabled");
}
}
- result.channels.add(c);
+ result.channels.add(c);
} else if (key.equals("category")) {
result.cattrans.put(parts.get(1), parts.get(2));
} else if (key.equals("config-file-format")) {
try {
fileformat = Integer.parseInt(parts.get(1));
} catch (NumberFormatException e) {
- logger.error("Unknown config file format " + parts.get(1));
+ logger.error("Unknown config file format "
+ + parts.get(1));
fileformat = CURRENT_FILE_FORMAT; // may crash later
}
if (fileformat > CURRENT_FILE_FORMAT) {
- logger.error("Unknown config file format " + parts.get(1));
+ logger.error("Unknown config file format "
+ + parts.get(1));
fileformat = CURRENT_FILE_FORMAT;
}
} else if (key.equals("cache-file")) {
- if (fileformat<4) {
+ if (fileformat < 4) {
String cacheFile = parts.get(1);
- result.cacheDbHandle = "jdbc:hsqldb:file:"+cacheFile;
+ result.cacheDbHandle = "jdbc:hsqldb:file:" + cacheFile;
result.cacheDbUser = "SA";
result.cacheDbPassword = "";
} else {
- logger.warn("Illegal key cache-file in config file with fileformat "+fileformat+"!");
+ logger.warn("Illegal key cache-file in config file with fileformat "
+ + fileformat + "!");
}
} else if (key.equals("cache-db-handle")) {
result.cacheDbHandle = parts.get(1);
}
public void setCacheFile(String cacheFile) {
- cacheDbHandle = "jdbc:hsqldb:file:"+cacheFile;
+ cacheDbHandle = "jdbc:hsqldb:file:" + cacheFile;
}
}
-
}
public int getId();
+
public void setId(int id);
- public String getName();
+
+ public String getName();
+
// All implementing class must declare a
- // public static final String NAME (e.g tvgids.nl or rtl.nl)
+ // public static final String NAME (e.g tvgids.nl or rtl.nl)
public List<Channel> getChannels();
+
// Convenience method
- public List<Programme> getProgrammes(Channel channel, int day) throws Exception;
- public List<Programme> getProgrammes(List<Channel> channels, int day) throws Exception;
-
+ public List<Programme> getProgrammes(Channel channel, int day)
+ throws Exception;
+
+ public List<Programme> getProgrammes(List<Channel> channels, int day)
+ throws Exception;
+
public Stats getStats();
-
+
public void clearCache();
+
public void close() throws FileNotFoundException, IOException;
}
import org.apache.log4j.Logger;
public class EPGSourceFactory {
- private static Map<String,Integer> ids = new HashMap<String,Integer>();
- private static Map<Integer,Class<EPGSource>> classes = new HashMap<Integer,Class<EPGSource>>();
- private static Map<Integer,String> names = new HashMap<Integer,String>();
- private static boolean initialised=false;
- private static List<Integer> sources=new ArrayList<Integer>();
+ private static Map<String, Integer> ids = new HashMap<String, Integer>();
+ private static Map<Integer, Class<EPGSource>> classes = new HashMap<Integer, Class<EPGSource>>();
+ private static Map<Integer, String> names = new HashMap<Integer, String>();
+ private static boolean initialised = false;
+ private static List<Integer> sources = new ArrayList<Integer>();
static Logger logger = Logger.getLogger(EPGSourceFactory.class);
-
static void init() {
- if(initialised) return;
+ if (initialised)
+ return;
Properties configProp = new Properties();
- ClassLoader loader = ClassLoader.getSystemClassLoader();
- InputStream in = loader.getResourceAsStream("tv_grab_nl_java.properties");
- try {
- configProp.load(in);
- } catch (IOException e) {
- logger.warn("Error reading application properties resource", e);
- }
- for(int source=1; ; source++) {
- String name = configProp.getProperty("org.vanbest.xmltv.epgsource.impl."+source);
- if (name==null) break;
+ ClassLoader loader = ClassLoader.getSystemClassLoader();
+ InputStream in = loader
+ .getResourceAsStream("tv_grab_nl_java.properties");
+ try {
+ configProp.load(in);
+ } catch (IOException e) {
+ logger.warn("Error reading application properties resource", e);
+ }
+ for (int source = 1;; source++) {
+ String name = configProp
+ .getProperty("org.vanbest.xmltv.epgsource.impl." + source);
+ if (name == null)
+ break;
try {
- Class<EPGSource> clazz = (Class<EPGSource>) loader.loadClass(name);
- classes.put(source, clazz);
+ Class<EPGSource> clazz = (Class<EPGSource>) loader
+ .loadClass(name);
+ classes.put(source, clazz);
// System.out.println("clazz: " + clazz.toString());
- Field NAME=clazz.getField("NAME");
+ Field NAME = clazz.getField("NAME");
// System.out.println("NAME: " + NAME.toString());
- String sourceName=(String)NAME.get(null);
- names.put(source,sourceName);
- ids.put(sourceName,source);
+ String sourceName = (String) NAME.get(null);
+ names.put(source, sourceName);
+ ids.put(sourceName, source);
sources.add(source);
} catch (Exception e) {
- logger.error("Error reading EPG Source class "+name, e);
+ logger.error("Error reading EPG Source class " + name, e);
}
- }
- initialised=true;
+ }
+ initialised = true;
}
private EPGSourceFactory() {
public static EPGSourceFactory newInstance() {
return new EPGSourceFactory();
}
-
+
public EPGSource createEPGSource(int source, Config config) {
Constructor<EPGSource> constructor;
try {
- constructor = classes.get(source).getConstructor(Integer.TYPE,Config.class);
+ constructor = classes.get(source).getConstructor(Integer.TYPE,
+ Config.class);
return constructor.newInstance(source, config);
} catch (Exception e) {
- logger.error("Error instantiating EPG source "+classes.get(source), e);
+ logger.error(
+ "Error instantiating EPG source " + classes.get(source), e);
}
return null;
}
-
+
public EPGSource createEPGSource(String source, Config config) {
int sourceId = getChannelSourceId(source);
return createEPGSource(sourceId, config);
}
-
+
public String getChannelSourceName(int id) {
return names.get(id);
}
-
+
public int getChannelSourceId(String name) {
return ids.get(name);
}
public int[] getAll() {
int[] result = new int[sources.size()];
- for(int i=0; i<result.length; i++) {
- result[i]=sources.get(i);
+ for (int i = 0; i < result.length; i++) {
+ result[i] = sources.get(i);
}
return result;
}
import javax.xml.stream.XMLStreamWriter;\r
\r
public class Icon {\r
- final static int UNKNOWN_DIMENSION=-1;\r
+ final static int UNKNOWN_DIMENSION = -1;\r
String url;\r
int width = UNKNOWN_DIMENSION;\r
int height = UNKNOWN_DIMENSION;\r
public void serialize(XMLStreamWriter writer) throws XMLStreamException {\r
writer.writeStartElement("icon");\r
writer.writeAttribute("src", url);\r
- if(width != UNKNOWN_DIMENSION) {\r
+ if (width != UNKNOWN_DIMENSION) {\r
writer.writeAttribute("width", Integer.toString(width));\r
}\r
- if(height!= UNKNOWN_DIMENSION) {\r
+ if (height != UNKNOWN_DIMENSION) {\r
writer.writeAttribute("height", Integer.toString(height));\r
}\r
writer.writeEndElement();\r
package org.vanbest.xmltv;
/*
- Copyright (c) 2012 Jan-Pascal van Best <janpascal@vanbest.org>
+ Copyright (c) 2012 Jan-Pascal van Best <janpascal@vanbest.org>
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
- The full license text can be found in the LICENSE file.
-*/
+ The full license text can be found in the LICENSE file.
+ */
import java.io.BufferedReader;
import java.io.File;
private int days = 5;
private int offset = 0;
private boolean clearCache = false;
-
+
static Logger logger = Logger.getLogger(Main.class);
+
/**
* @param args
*/
-
+
public Main() {
this.configFile = defaultConfigFile();
this.outputWriter = System.out;
- //PropertyConfigurator.configure(args[0]);
+ // PropertyConfigurator.configure(args[0]);
}
public void showHeader() {
- logger.info("tv_grab_nl_java version "+config.project_version + " (built "+config.build_time+")");
+ logger.info("tv_grab_nl_java version " + config.project_version
+ + " (built " + config.build_time + ")");
logger.info("Copyright (C) 2012 Jan-Pascal van Best <janpascal@vanbest.org>");
logger.info("tv_grab_nl_java comes with ABSOLUTELY NO WARRANTY. It is free software, and you are welcome to redistribute it");
logger.info("under certain conditions; `tv_grab_nl_java --license' for details.");
}
-
+
public void run() throws FactoryConfigurationError, Exception {
if (!config.quiet) {
showHeader();
- logger.info("Fetching programme data for " + this.days + " days starting from day " + this.offset);
+ logger.info("Fetching programme data for " + this.days
+ + " days starting from day " + this.offset);
int enabledCount = 0;
- for(Channel c: config.channels) { if (c.enabled) enabledCount++; }
+ for (Channel c : config.channels) {
+ if (c.enabled)
+ enabledCount++;
+ }
logger.info("... from " + enabledCount + " channels");
logger.info("... using cache at " + config.cacheDbHandle);
}
cache.clear();
cache.close();
}
- Map<Integer,EPGSource> guides = new HashMap<Integer,EPGSource>();
+ Map<Integer, EPGSource> guides = new HashMap<Integer, EPGSource>();
EPGSourceFactory factory = EPGSourceFactory.newInstance();
- //EPGSource gids = new TvGids(config);
- //if (clearCache) gids.clearCache();
+ // EPGSource gids = new TvGids(config);
+ // if (clearCache) gids.clearCache();
- XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(outputWriter);
+ XMLStreamWriter writer = XMLOutputFactory.newInstance()
+ .createXMLStreamWriter(outputWriter);
writer.writeStartDocument();
writer.writeCharacters("\n");
writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">");
writer.writeCharacters("\n");
writer.writeStartElement("tv");
- writer.writeAttribute("generator-info-url","http://github.com/janpascal/tv_grab_nl_java");
+ writer.writeAttribute("generator-info-url",
+ "http://github.com/janpascal/tv_grab_nl_java");
writer.writeAttribute("source-info-url", "http://tvgids.nl/");
writer.writeAttribute("source-info-name", "TvGids.nl");
- writer.writeAttribute("generator-info-name", "tv_grab_nl_java release "+config.project_version + ", built " + config.build_time);
+ writer.writeAttribute("generator-info-name", "tv_grab_nl_java release "
+ + config.project_version + ", built " + config.build_time);
writer.writeCharacters(System.getProperty("line.separator"));
- for(Channel c: config.channels) if (c.enabled) c.serialize(writer);
+ for (Channel c : config.channels)
+ if (c.enabled)
+ c.serialize(writer);
- for (int day=offset; day<offset+days; day++) {
- if (!config.quiet) System.out.print("Fetching information for day " + day);
- for(Channel c: config.channels) {
- if (!c.enabled) continue;
- if (!config.quiet) System.out.print(".");
- if(!guides.containsKey(c.source)) {
- guides.put(c.source, factory.createEPGSource(c.source, config));
+ for (int day = offset; day < offset + days; day++) {
+ if (!config.quiet)
+ System.out.print("Fetching information for day " + day);
+ for (Channel c : config.channels) {
+ if (!c.enabled)
+ continue;
+ if (!config.quiet)
+ System.out.print(".");
+ if (!guides.containsKey(c.source)) {
+ guides.put(c.source,
+ factory.createEPGSource(c.source, config));
}
- List<Programme> programmes = guides.get(c.source).getProgrammes(c, day);
- for (Programme p: programmes) p.serialize(writer);
+ List<Programme> programmes = guides.get(c.source)
+ .getProgrammes(c, day);
+ for (Programme p : programmes)
+ p.serialize(writer);
writer.flush();
}
- if (!config.quiet) System.out.println();
+ if (!config.quiet)
+ System.out.println();
}
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();
writer.close();
-
- for(int source: guides.keySet()) {
+
+ for (int source : guides.keySet()) {
guides.get(source).close();
}
if (!config.quiet) {
EPGSource.Stats stats = new EPGSource.Stats();
- for(int source: guides.keySet()) {
+ for (int source : guides.keySet()) {
EPGSource.Stats part = guides.get(source).getStats();
stats.cacheHits += part.cacheHits;
stats.cacheMisses += part.cacheMisses;
logger.warn("Number of fetch errors: " + stats.fetchErrors);
}
}
-
+
public void configure() throws IOException {
showHeader();
- BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
-
- System.out.print("Delay between each request to the server (in milliseconds, default="+config.niceMilliseconds+"):");
- while(true) {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(
+ System.in));
+
+ System.out
+ .print("Delay between each request to the server (in milliseconds, default="
+ + config.niceMilliseconds + "):");
+ while (true) {
String s = reader.readLine().toLowerCase();
if (s.isEmpty()) {
break;
config.niceMilliseconds = Integer.parseInt(s);
break;
} catch (NumberFormatException e) {
- System.out.println("\""+s+"\" is not a valid number, please try again");
+ System.out.println("\"" + s
+ + "\" is not a valid number, please try again");
continue;
}
}
- // TODO configure cache location
+ // TODO configure cache location
// public String cacheDbHandle;
// public String cacheDbUser;
// public String cacheDbPassword;
-
Set<String> oldChannels = new HashSet<String>();
Set<Integer> oldGuides = new HashSet<Integer>();
- for (Channel c: config.channels) {
- if (c.enabled) {
- oldChannels.add(c.source+"::"+c.id);
+ for (Channel c : config.channels) {
+ if (c.enabled) {
+ oldChannels.add(c.source + "::" + c.id);
oldGuides.add(c.source);
}
}
-
+
EPGSourceFactory factory = EPGSourceFactory.newInstance();
int[] sources = factory.getAll();
-
- System.out.println("Please select the TV programme information sources to use");
+
+ System.out
+ .println("Please select the TV programme information sources to use");
List<EPGSource> guides = new ArrayList<EPGSource>();
- for(int source: sources) {
+ for (int source : sources) {
boolean selected = oldGuides.contains(source);
EPGSource guide = factory.createEPGSource(source, config);
- System.out.print(" Use \"" + guide.getName() + "\" (Y/N, default=" + (selected?"Y":"N")+"):");
- while(true) {
+ System.out.print(" Use \"" + guide.getName()
+ + "\" (Y/N, default=" + (selected ? "Y" : "N") + "):");
+ while (true) {
String s = reader.readLine().toLowerCase();
if (s.isEmpty()) {
- if(selected) guides.add(guide);
+ if (selected)
+ guides.add(guide);
break;
} else if (s.startsWith("y")) {
guides.add(guide);
}
}
}
-
+
List<Channel> channels = new ArrayList<Channel>();
- for(EPGSource guide: guides) {
+ for (EPGSource guide : guides) {
channels.addAll(guide.getChannels());
}
-
+
boolean all = false;
boolean none = false;
boolean keep = false;
- for (Channel c: channels) {
- boolean selected = oldChannels.contains(c.source+"::"+c.id);
- System.out.print("add channel " + c.getXmltvChannelId() + " (" + c.defaultName() + ") [[y]es,[n]o,[a]ll,[none],[k]eep selection (default=" + (selected?"yes":"no") + ")] ");
+ for (Channel c : channels) {
+ boolean selected = oldChannels.contains(c.source + "::" + c.id);
+ System.out.print("add channel " + c.getXmltvChannelId() + " ("
+ + c.defaultName()
+ + ") [[y]es,[n]o,[a]ll,[none],[k]eep selection (default="
+ + (selected ? "yes" : "no") + ")] ");
if (keep) {
c.enabled = selected;
- System.out.println(selected?"Y":"N");
+ System.out.println(selected ? "Y" : "N");
continue;
- }
+ }
if (all) {
c.enabled = true;
System.out.println("Y");
continue;
- }
+ }
if (none) {
c.enabled = false;
System.out.println("N");
continue;
- }
- while(true) {
+ }
+ while (true) {
String s = reader.readLine().toLowerCase();
if (s.isEmpty()) {
c.enabled = selected;
break;
- } else if ( s.startsWith("k")) {
+ } else if (s.startsWith("k")) {
c.enabled = selected;
keep = true;
break;
- } else if ( s.startsWith("y")) {
+ } else if (s.startsWith("y")) {
c.enabled = true;
break;
- } else if ( s.startsWith("a")) {
+ } else if (s.startsWith("a")) {
c.enabled = true;
all = true;
break;
- } else if ( s.startsWith("none")) {
+ } else if (s.startsWith("none")) {
c.enabled = false;
none = true;
break;
- } else if ( s.startsWith("n")) {
+ } else if (s.startsWith("n")) {
c.enabled = false;
break;
}
}
}
-
+
config.setChannels(channels);
try {
config.writeConfig(configFile);
logger.info("Configuration file written to " + configFile.getPath());
} catch (FileNotFoundException e) {
- logger.warn("File not found trying to write config file to "+configFile.getPath(), e);
+ logger.warn("File not found trying to write config file to "
+ + configFile.getPath(), e);
} catch (IOException e) {
- logger.warn("IO Exception trying to write config file to "+configFile.getPath(), e);
+ logger.warn("IO Exception trying to write config file to "
+ + configFile.getPath(), e);
}
}
- static String copyright = "Copyright (c) 2012 Jan-Pascal van Best <janpascal@vanbest.org>" + System.getProperty("line.separator") +
- "" + System.getProperty("line.separator") +
- "This program is free software; you can redistribute it and/or modify" + System.getProperty("line.separator") +
- "it under the terms of the GNU General Public License as published by" + System.getProperty("line.separator") +
- "the Free Software Foundation; either version 2 of the License, or" + System.getProperty("line.separator") +
- "(at your option) any later version." + System.getProperty("line.separator") +
- "" + System.getProperty("line.separator") +
- "This program is distributed in the hope that it will be useful," + System.getProperty("line.separator") +
- "but WITHOUT ANY WARRANTY; without even the implied warranty of" + System.getProperty("line.separator") +
- "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the" + System.getProperty("line.separator") +
- "GNU General Public License for more details." + System.getProperty("line.separator") +
- "" + System.getProperty("line.separator") +
- "You should have received a copy of the GNU General Public License along" + System.getProperty("line.separator") +
- "with this program; if not, write to the Free Software Foundation, Inc.," + System.getProperty("line.separator") +
- "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.";
-
- public void showLicense() {
- System.out.println(copyright);
- }
-
- public void processOptions(String[] args) throws FileNotFoundException {
- Options options = new Options();
- options.addOption(OptionBuilder
- .withLongOpt("description")
- .withDescription("Display a description to identify this grabber")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("capabilities")
- .withDescription("Show grabber capabilities")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("quiet")
- .withDescription("Disable progress information. Also set log-level to ERROR")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("output")
- .hasArg()
- .withDescription("Set xlmtv output filename")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("days")
- .hasArg()
- .withDescription("Number of days to grab")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("offset")
- .hasArg()
- .withDescription("Start day for grabbing (0=today)")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("configure")
- .withDescription("Interactive configuration")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("config-file")
- .hasArg()
- .withDescription("Configuration file location")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("cache")
- .hasArg()
- .withDescription("Cache file location")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("clear-cache")
- .withDescription("Clear cache, remove all cached info")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("help")
- .withDescription("Show this help")
- .create())
- .addOption(OptionBuilder
- .withLongOpt("log-level")
- .hasArg()
- .withDescription("Set log level (ERROR,WARN,INFO,DEBUG,TRACE)")
+ static String copyright = "Copyright (c) 2012 Jan-Pascal van Best <janpascal@vanbest.org>"
+ + System.getProperty("line.separator")
+ + ""
+ + System.getProperty("line.separator")
+ + "This program is free software; you can redistribute it and/or modify"
+ + System.getProperty("line.separator")
+ + "it under the terms of the GNU General Public License as published by"
+ + System.getProperty("line.separator")
+ + "the Free Software Foundation; either version 2 of the License, or"
+ + System.getProperty("line.separator")
+ + "(at your option) any later version."
+ + System.getProperty("line.separator")
+ + ""
+ + System.getProperty("line.separator")
+ + "This program is distributed in the hope that it will be useful,"
+ + System.getProperty("line.separator")
+ + "but WITHOUT ANY WARRANTY; without even the implied warranty of"
+ + System.getProperty("line.separator")
+ + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"
+ + System.getProperty("line.separator")
+ + "GNU General Public License for more details."
+ + System.getProperty("line.separator")
+ + ""
+ + System.getProperty("line.separator")
+ + "You should have received a copy of the GNU General Public License along"
+ + System.getProperty("line.separator")
+ + "with this program; if not, write to the Free Software Foundation, Inc.,"
+ + System.getProperty("line.separator")
+ + "51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.";
+
+ public void showLicense() {
+ System.out.println(copyright);
+ }
+
+ public void processOptions(String[] args) throws FileNotFoundException {
+ Options options = new Options();
+ options.addOption(
+ OptionBuilder
+ .withLongOpt("description")
+ .withDescription(
+ "Display a description to identify this grabber")
.create())
- .addOption(OptionBuilder
- .withLongOpt("license")
- .withDescription("Show license information")
- .create());
- //.addOption(OptionBuilder.withLongOpt("preferredmethod").withDescription("Show preferred method").create();
+ .addOption(
+ OptionBuilder.withLongOpt("capabilities")
+ .withDescription("Show grabber capabilities")
+ .create())
+ .addOption(
+ OptionBuilder
+ .withLongOpt("quiet")
+ .withDescription(
+ "Disable progress information. Also set log-level to ERROR")
+ .create())
+ .addOption(
+ OptionBuilder.withLongOpt("output").hasArg()
+ .withDescription("Set xlmtv output filename")
+ .create())
+ .addOption(
+ OptionBuilder.withLongOpt("days").hasArg()
+ .withDescription("Number of days to grab")
+ .create())
+ .addOption(
+ OptionBuilder
+ .withLongOpt("offset")
+ .hasArg()
+ .withDescription(
+ "Start day for grabbing (0=today)")
+ .create())
+ .addOption(
+ OptionBuilder.withLongOpt("configure")
+ .withDescription("Interactive configuration")
+ .create())
+ .addOption(
+ OptionBuilder.withLongOpt("config-file").hasArg()
+ .withDescription("Configuration file location")
+ .create())
+ .addOption(
+ OptionBuilder.withLongOpt("cache").hasArg()
+ .withDescription("Cache file location")
+ .create())
+ .addOption(
+ OptionBuilder
+ .withLongOpt("clear-cache")
+ .withDescription(
+ "Clear cache, remove all cached info")
+ .create())
+ .addOption(
+ OptionBuilder.withLongOpt("help")
+ .withDescription("Show this help").create())
+ .addOption(
+ OptionBuilder
+ .withLongOpt("log-level")
+ .hasArg()
+ .withDescription(
+ "Set log level (ERROR,WARN,INFO,DEBUG,TRACE)")
+ .create())
+ .addOption(
+ OptionBuilder.withLongOpt("license")
+ .withDescription("Show license information")
+ .create());
+ // .addOption(OptionBuilder.withLongOpt("preferredmethod").withDescription("Show preferred method").create();
CommandLine line = null;
try {
logger.error("Error parsing command-line options", e);
}
- if(line.hasOption("license")) {
- showLicense();
- System.exit(0);
+ if (line.hasOption("license")) {
+ showLicense();
+ System.exit(0);
}
- if(line.hasOption("config-file")) {
- configFile = new File(line.getOptionValue("config-file"));
+ if (line.hasOption("config-file")) {
+ configFile = new File(line.getOptionValue("config-file"));
}
config = Config.readConfig(configFile);
if (line.hasOption("quiet")) {
if (line.hasOption("description")) {
showHeader();
System.out.println();
- System.out.println("tv_grab_nl_java is a parser for Dutch TV listings using the tvgids.nl JSON interface");
+ System.out
+ .println("tv_grab_nl_java is a parser for Dutch TV listings using the tvgids.nl JSON interface");
System.exit(0);
}
if (line.hasOption("help")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
- formatter.printHelp( "tv_grab_nl_java", options );
+ formatter.printHelp("tv_grab_nl_java", options);
System.exit(0);
}
if (line.hasOption("output")) {
- this.outputWriter = new PrintStream( new FileOutputStream(line.getOptionValue("output")));
+ this.outputWriter = new PrintStream(new FileOutputStream(
+ line.getOptionValue("output")));
}
if (line.hasOption("log-level")) {
String arg = line.getOptionValue("log-level");
- // TODO: make distinction between levels for console and
- // file appenders
- Logger.getRootLogger().setLevel(Level.toLevel(arg, Level.INFO));
+ // TODO: make distinction between levels for console and
+ // file appenders
+ Logger.getRootLogger().setLevel(Level.toLevel(arg, Level.INFO));
}
if (line.hasOption("cache")) {
config.setCacheFile(line.getOptionValue("cache"));
System.exit(0);
}
}
-
+
public static File defaultConfigFile() {
- return FileUtils.getFile(FileUtils.getUserDirectory(), ".xmltv", "tv_grab_nl_java.conf");
+ return FileUtils.getFile(FileUtils.getUserDirectory(), ".xmltv",
+ "tv_grab_nl_java.conf");
}
-
- public static void main(String[] args) {
+
+ public static void main(String[] args) {
Main main = new Main();
try {
main.processOptions(args);
class Title implements Serializable {
String title;
String lang;
- public Title(String title, String lang) {
- this.title = title;
- this.lang = lang;
- }
+
+ public Title(String title, String lang) {
+ this.title = title;
+ this.lang = lang;
+ }
}
+
class Actor implements Serializable {
String name;
String role;
}
+
class Credits implements Serializable {
List<String> directors;
List<Actor> actors;
List<String> commentators;
List<String> guests;
}
+
class Length implements Serializable {
- TimeUnit unit;
+ TimeUnit unit;
int count;
}
- /* See separate java source file for the Icon class
- class Icon implements Serializable {
- URL url;
- int width;
- int height;
- }
- */
+
+ /*
+ * See separate java source file for the Icon class class Icon implements
+ * Serializable { URL url; int width; int height; }
+ */
class Episode implements Serializable {
- String episode;
- String system; // onscreen or xmltv_ns
+ String episode;
+ String system; // onscreen or xmltv_ns
}
+
class Video implements Serializable {
boolean present = true; // FIXME should be default null
boolean colour = true; // FIXME should be default null
String aspect; // eg. 16:9, 4:3
String quality; // eg. 'HDTV', '800x600'.
}
+
class Audio implements Serializable {
boolean present;
- String stereo; // 'mono','stereo','dolby','dolby digital','bilingual' or 'surround'.
+ String stereo; // 'mono','stereo','dolby','dolby digital','bilingual' or
+ // 'surround'.
}
+
class PreviouslyShown implements Serializable {
String start;
String channel;
}
+
class Subtitle implements Serializable {
String type; // teletext | onscreen | deaf-signed
Title language;
}
+
class Rating implements Serializable {
String system;
String value;
List<Icon> icons;
}
+
public Date startTime; // required
public Date endTime;
- public Date pdcStart;
- public Date vpsStart;
- public String showview;
- public String videoplus;
+ public Date pdcStart;
+ public Date vpsStart;
+ public String showview;
+ public String videoplus;
public String channel; // required xmltvid of the associated channel
- public String clumpidx;
-
- public List<Title> titles; // at least one
- public List<Title> secondaryTitles;
- public List<Title> descriptions;
- public Credits credits;
- public Date date; // copyright date, original date
- public List<Title> categories;
- Title language;
- Title origLanguage;
- Length length;
- public List<Icon> icons;
- public List<String> urls;
- public List<Title> countries;
- public List<Episode> episodes;
- public Video video;
- public Audio audio;
- public PreviouslyShown previouslyShown;
- /*
- premiere?, last-chance?, new?,
- */
- public List<Subtitle> subtitles;
- public List<Rating> ratings;
- /*star-rating*, review*
- */
-
- public void addTitle(String title) {
- addTitle(title, null);
- }
- public void addTitle(String title, String lang) {
- if(titles==null) titles = new ArrayList<Title>();
- titles.add(new Title(title,lang));
- }
+ public String clumpidx;
+
+ public List<Title> titles; // at least one
+ public List<Title> secondaryTitles;
+ public List<Title> descriptions;
+ public Credits credits;
+ public Date date; // copyright date, original date
+ public List<Title> categories;
+ Title language;
+ Title origLanguage;
+ Length length;
+ public List<Icon> icons;
+ public List<String> urls;
+ public List<Title> countries;
+ public List<Episode> episodes;
+ public Video video;
+ public Audio audio;
+ public PreviouslyShown previouslyShown;
+ /*
+ * premiere?, last-chance?, new?,
+ */
+ public List<Subtitle> subtitles;
+ public List<Rating> ratings;
+
+ /*
+ * star-rating*, review*
+ */
+
+ public void addTitle(String title) {
+ addTitle(title, null);
+ }
+
+ public void addTitle(String title, String lang) {
+ if (titles == null)
+ titles = new ArrayList<Title>();
+ titles.add(new Title(title, lang));
+ }
+
public void addSecondaryTitle(String title) {
- addSecondaryTitle(title,null);
+ addSecondaryTitle(title, null);
+ }
+
+ public void addSecondaryTitle(String title, String lang) {
+ if (secondaryTitles == null)
+ secondaryTitles = new ArrayList<Title>();
+ secondaryTitles.add(new Title(title, lang));
}
- public void addSecondaryTitle(String title, String lang) {
- if(secondaryTitles==null) secondaryTitles = new ArrayList<Title>();
- secondaryTitles.add(new Title(title,lang));
- }
+
public void addDescription(String title) {
- addDescription(title,null);
+ addDescription(title, null);
}
- public void addDescription(String title, String lang) {
- if(descriptions==null) descriptions = new ArrayList<Title>();
- descriptions.add(new Title(title,lang));
- }
-
+
+ public void addDescription(String title, String lang) {
+ if (descriptions == null)
+ descriptions = new ArrayList<Title>();
+ descriptions.add(new Title(title, lang));
+ }
+
public void addCategory(String category) {
- addCategory(category, null);
- }
- public void addCategory(String category, String lang) {
- if(categories==null) categories = new ArrayList<Title>();
- categories.add(new Title(category,lang));
- }
+ addCategory(category, null);
+ }
+
+ public void addCategory(String category, String lang) {
+ if (categories == null)
+ categories = new ArrayList<Title>();
+ categories.add(new Title(category, lang));
+ }
+
public void addSubtitle(String type) {
- addSubtitle(type, null, null);
- }
- public void addSubtitle(String type, String language, String language_lang) {
- if(subtitles==null) subtitles = new ArrayList<Subtitle>();
- Subtitle s = new Subtitle();
- s.type = type;
- if (language != null) {
- s.language = new Title(language,language_lang);
- }
- subtitles.add(s);
- }
+ addSubtitle(type, null, null);
+ }
+
+ public void addSubtitle(String type, String language, String language_lang) {
+ if (subtitles == null)
+ subtitles = new ArrayList<Subtitle>();
+ Subtitle s = new Subtitle();
+ s.type = type;
+ if (language != null) {
+ s.language = new Title(language, language_lang);
+ }
+ subtitles.add(s);
+ }
+
public void addPresenter(String pres) {
- if (credits == null) credits = new Credits();
- if (credits.presenters==null) {
- credits.presenters=new ArrayList<String>();
+ if (credits == null)
+ credits = new Credits();
+ if (credits.presenters == null) {
+ credits.presenters = new ArrayList<String>();
}
credits.presenters.add(pres);
}
- public void addDirector(String director) {
- if (credits == null) credits = new Credits();
- if (credits.directors==null) credits.directors = new ArrayList<String>();
- credits.directors.add(director);
- }
- public void addActor(String name) {
- addActor(name, null);
- }
- public void addActor(String name, String role) {
- if (credits == null) credits = new Credits();
- if (credits.actors==null) credits.actors = new ArrayList<Actor>();
- Actor actor = new Actor();
- actor.name = name;
- actor.role = role;
- credits.actors.add(actor);
- }
+
+ public void addDirector(String director) {
+ if (credits == null)
+ credits = new Credits();
+ if (credits.directors == null)
+ credits.directors = new ArrayList<String>();
+ credits.directors.add(director);
+ }
+
+ public void addActor(String name) {
+ addActor(name, null);
+ }
+
+ public void addActor(String name, String role) {
+ if (credits == null)
+ credits = new Credits();
+ if (credits.actors == null)
+ credits.actors = new ArrayList<Actor>();
+ Actor actor = new Actor();
+ actor.name = name;
+ actor.role = role;
+ credits.actors.add(actor);
+ }
+
public void setVideoAspect(String aspect) {
- if (video==null) video = new Video();
+ if (video == null)
+ video = new Video();
video.aspect = aspect;
}
+
public void setVideoQuality(String quality) {
- if (video==null) video = new Video();
+ if (video == null)
+ video = new Video();
video.quality = quality;
}
+
public void setVideoColour(boolean colour) {
- if (video==null) video = new Video();
+ if (video == null)
+ video = new Video();
video.colour = colour;
}
+
public void setAudioStereo(String stereo) {
- if (audio==null) audio = new Audio();
+ if (audio == null)
+ audio = new Audio();
audio.stereo = stereo;
}
+
public void addUrl(String url) {
- if(urls==null) urls=new ArrayList<String>();
+ if (urls == null)
+ urls = new ArrayList<String>();
urls.add(url);
}
+
// Convenience method, set "rerun" flag without any additional information
public void setPreviouslyShown() {
setPreviouslyShown(null, null);
}
+
public void setPreviouslyShown(String startTime, String channel) {
- if (previouslyShown == null) previouslyShown = new PreviouslyShown();
+ if (previouslyShown == null)
+ previouslyShown = new PreviouslyShown();
previouslyShown.start = startTime;
previouslyShown.channel = channel;
}
+
public boolean hasCategory(String category) {
- if(categories==null) return false;
- for(Title t: categories) {
- if (t.title.toLowerCase().equals(category)) return true;
+ if (categories == null)
+ return false;
+ for (Title t : categories) {
+ if (t.title.toLowerCase().equals(category))
+ return true;
}
return false;
}
+
public void addRating(String system, String value) {
- if (ratings==null) ratings = new ArrayList<Rating>();
+ if (ratings == null)
+ ratings = new ArrayList<Rating>();
Rating r = new Rating();
r.system = system;
r.value = value;
ratings.add(r);
}
-
- private void writeTitle(Title title, String tag,
- XMLStreamWriter writer) throws XMLStreamException {
- if(title==null) return;
+ private void writeTitle(Title title, String tag, XMLStreamWriter writer)
+ throws XMLStreamException {
+ if (title == null)
+ return;
writer.writeStartElement(tag);
- if (title.lang != null) writer.writeAttribute("lang", title.lang);
- if (title.title != null) writer.writeCharacters(title.title);
+ if (title.lang != null)
+ writer.writeAttribute("lang", title.lang);
+ if (title.title != null)
+ writer.writeCharacters(title.title);
writer.writeEndElement();
}
+
private void writeTitleList(List<Title> titles, String tag,
XMLStreamWriter writer) throws XMLStreamException {
- if(titles==null) return;
- for(Title title: titles) {
- writeTitle(title,tag,writer);
+ if (titles == null)
+ return;
+ for (Title title : titles) {
+ writeTitle(title, tag, writer);
}
}
- private void writeString(String s, String tag,
- XMLStreamWriter writer) throws XMLStreamException {
- if(s==null) return;
+
+ private void writeString(String s, String tag, XMLStreamWriter writer)
+ throws XMLStreamException {
+ if (s == null)
+ return;
writer.writeStartElement(tag);
writer.writeCharacters(s);
writer.writeEndElement();
}
+
private void writeStringList(List<String> strings, String tag,
XMLStreamWriter writer) throws XMLStreamException {
- if(strings==null) return;
- for(String s:strings) {
+ if (strings == null)
+ return;
+ for (String s : strings) {
writeString(s, tag, writer);
}
}
- private void writeActorList(List<Actor> actors,XMLStreamWriter writer) throws XMLStreamException {
- if(actors==null) return;
- for(Actor actor: actors) {
+
+ private void writeActorList(List<Actor> actors, XMLStreamWriter writer)
+ throws XMLStreamException {
+ if (actors == null)
+ return;
+ for (Actor actor : actors) {
writer.writeStartElement("actor");
- if (actor.role!=null) writer.writeAttribute("role", actor.role);
- if (actor.name!=null) writer.writeCharacters(actor.name);
+ if (actor.role != null)
+ writer.writeAttribute("role", actor.role);
+ if (actor.name != null)
+ writer.writeCharacters(actor.name);
writer.writeEndElement();
}
}
- private void writeIconList(List<Icon> icons, XMLStreamWriter writer) throws XMLStreamException {
- if(icons==null) return;
- for(Icon i: icons) {
+
+ private void writeIconList(List<Icon> icons, XMLStreamWriter writer)
+ throws XMLStreamException {
+ if (icons == null)
+ return;
+ for (Icon i : icons) {
i.serialize(writer);
}
}
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss Z");
writer.writeStartElement("programme");
- if(startTime != null) writer.writeAttribute("start", df.format(startTime));
- if(endTime != null) writer.writeAttribute("stop", df.format(endTime));
- if(channel != null) writer.writeAttribute("channel", ""+channel);
- writeTitleList(titles,"title",writer);
- writeTitleList(secondaryTitles,"sub-title", writer);
+ if (startTime != null)
+ writer.writeAttribute("start", df.format(startTime));
+ if (endTime != null)
+ writer.writeAttribute("stop", df.format(endTime));
+ if (channel != null)
+ writer.writeAttribute("channel", "" + channel);
+ writeTitleList(titles, "title", writer);
+ writeTitleList(secondaryTitles, "sub-title", writer);
writeTitleList(descriptions, "desc", writer);
- if(credits != null) {
+ if (credits != null) {
writer.writeStartElement("credits");
writeStringList(credits.directors, "director", writer);
writeActorList(credits.actors, writer);
- writeStringList(credits.presenters,"presenter",writer);
+ writeStringList(credits.presenters, "presenter", writer);
writer.writeEndElement();
}
writeTitleList(categories, "category", writer);
writeIconList(icons, writer);
- writeStringList(urls,"url",writer);
- if (video!=null) {
+ writeStringList(urls, "url", writer);
+ if (video != null) {
writer.writeStartElement("video");
- if(!video.present) {
+ if (!video.present) {
writer.writeStartElement("present");
writer.writeCharacters("no");
writer.writeEndElement();
writer.writeCharacters("no");
writer.writeEndElement();
}
- if (video.aspect!=null) {
+ if (video.aspect != null) {
writer.writeStartElement("aspect");
writer.writeCharacters(video.aspect);
writer.writeEndElement();
}
- if (video.quality!=null) {
+ if (video.quality != null) {
writer.writeStartElement("quality");
writer.writeCharacters(video.quality);
writer.writeEndElement();
}
writer.writeEndElement();
}
- if (audio!=null) {
+ if (audio != null) {
writer.writeStartElement("audio");
- if (audio.stereo!=null) {
+ if (audio.stereo != null) {
writer.writeStartElement("stereo");
writer.writeCharacters(audio.stereo);
writer.writeEndElement();
}
writer.writeEndElement();
}
- if(previouslyShown!=null) {
+ if (previouslyShown != null) {
writer.writeStartElement("previously-shown");
- if (previouslyShown.start!=null) writer.writeAttribute("start", previouslyShown.start);
- if (previouslyShown.channel!=null) writer.writeAttribute("channel", previouslyShown.channel);
+ if (previouslyShown.start != null)
+ writer.writeAttribute("start", previouslyShown.start);
+ if (previouslyShown.channel != null)
+ writer.writeAttribute("channel", previouslyShown.channel);
writer.writeEndElement();
}
- if(subtitles != null) {
- for(Subtitle s: subtitles) {
+ if (subtitles != null) {
+ for (Subtitle s : subtitles) {
writer.writeStartElement("subtitles");
- if (s.type != null) writer.writeAttribute("type", s.type);
- if (s.language != null) writeTitle(s.language,"language",writer);
+ if (s.type != null)
+ writer.writeAttribute("type", s.type);
+ if (s.language != null)
+ writeTitle(s.language, "language", writer);
writer.writeEndElement();
}
}
- if(ratings != null) {
- for(Rating r: ratings) {
+ if (ratings != null) {
+ for (Rating r : ratings) {
writer.writeStartElement("rating");
- if (r.system != null) writer.writeAttribute("system", r.system);
- if (r.value != null) writeString(r.value, "value", writer);
+ if (r.system != null)
+ writer.writeAttribute("system", r.system);
+ if (r.value != null)
+ writeString(r.value, "value", writer);
writeIconList(icons, writer);
writer.writeEndElement();
}
-
+
}
writer.writeEndElement();
writer.writeCharacters(System.getProperty("line.separator"));
}
-
+
public String getFirstTitle() {
- if (titles==null || titles.isEmpty()) return null;
+ if (titles == null || titles.isEmpty())
+ return null;
return titles.get(0).title;
}
-
+
public String toString() {
StringBuilder s = new StringBuilder();
s.append("[Programme ").append(getFirstTitle());
package org.vanbest.xmltv;
/*
- Copyright (c) 2012 Jan-Pascal van Best <janpascal@vanbest.org>
+ Copyright (c) 2012 Jan-Pascal van Best <janpascal@vanbest.org>
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
- The full license text can be found in the LICENSE file.
-*/
+ The full license text can be found in the LICENSE file.
+ */
import java.sql.Connection;
import java.sql.DriverManager;
private PreparedStatement removeStatement;
private PreparedStatement clearStatement;
private PreparedStatement clearSourceStatement;
-
- private final static Integer SCHEMA_VERSION=1;
- private final static String SCHEMA_KEY="TV_GRAB_NL_JAVA_SCHEMA_VERSION";
-
+
+ private final static Integer SCHEMA_VERSION = 1;
+ private final static String SCHEMA_KEY = "TV_GRAB_NL_JAVA_SCHEMA_VERSION";
+
static Logger logger = Logger.getLogger(ProgrammeCache.class);
-
+
public ProgrammeCache(Config config) {
this.config = config;
- try {
- db = DriverManager.getConnection(config.cacheDbHandle, config.cacheDbUser, config.cacheDbPassword);
- /* Test for upgrade path from legacy database
- Statement stat = db.createStatement();
- .println("Dropping old table");
- stat.execute("DROP TABLE IF EXISTS cache");
- System.out.println("Creating new table");
- stat.execute("CREATE CACHED TABLE IF NOT EXISTS cache (id VARCHAR(64) PRIMARY KEY, date DATE, programme OTHER)");
- */
+ try {
+ db = DriverManager.getConnection(config.cacheDbHandle,
+ config.cacheDbUser, config.cacheDbPassword);
+ /*
+ * Test for upgrade path from legacy database Statement stat =
+ * db.createStatement(); .println("Dropping old table");
+ * stat.execute("DROP TABLE IF EXISTS cache");
+ * System.out.println("Creating new table"); stat.execute(
+ * "CREATE CACHED TABLE IF NOT EXISTS cache (id VARCHAR(64) PRIMARY KEY, date DATE, programme OTHER)"
+ * );
+ */
} catch (SQLException e) {
db = null;
if (!config.quiet) {
logger.warn("Unable to open cache database, proceeding without cache");
logger.debug("Stack trace: ", e);
}
- }
- boolean recreateTable = false;
- if (db != null) {
- try {
- PreparedStatement stat = db.prepareStatement("SELECT programme FROM cache WHERE source=? AND id=?");
+ }
+ boolean recreateTable = false;
+ if (db != null) {
+ try {
+ PreparedStatement stat = db
+ .prepareStatement("SELECT programme FROM cache WHERE source=? AND id=?");
stat.setInt(1, 1);
stat.setString(2, SCHEMA_KEY);
ResultSet result = stat.executeQuery();
if (!result.next()) {
logger.debug("No schema version found in database");
- recreateTable=true;
+ recreateTable = true;
} else {
- Integer currentSchema = (Integer) result.getObject("programme");
- if (currentSchema<SCHEMA_VERSION) {
- logger.debug("Current cache database schema version " + currentSchema + " is lower than my version " + SCHEMA_VERSION);
+ Integer currentSchema = (Integer) result
+ .getObject("programme");
+ if (currentSchema < SCHEMA_VERSION) {
+ logger.debug("Current cache database schema version "
+ + currentSchema + " is lower than my version "
+ + SCHEMA_VERSION);
recreateTable = true;
- } else if (currentSchema>SCHEMA_VERSION) {
- logger.warn("Got a database schema from the future, since my version is " + SCHEMA_VERSION+ " and yours is " + currentSchema);
+ } else if (currentSchema > SCHEMA_VERSION) {
+ logger.warn("Got a database schema from the future, since my version is "
+ + SCHEMA_VERSION
+ + " and yours is "
+ + currentSchema);
recreateTable = true;
}
-
+
}
stat.close();
} catch (SQLException e) {
}
recreateTable = true;
}
- if (recreateTable) {
- logger.info("Unknown cache schema, removing and recreating cache");
- try {
+ if (recreateTable) {
+ logger.info("Unknown cache schema, removing and recreating cache");
+ try {
Statement stat = db.createStatement();
// System.out.println("Dropping old table");
stat.execute("DROP TABLE IF EXISTS cache");
stat.close();
// System.out.println("Writing new schema version to database");
- PreparedStatement stat2 = db.prepareStatement("INSERT INTO cache VALUES (?,?,?,?)");
+ PreparedStatement stat2 = db
+ .prepareStatement("INSERT INTO cache VALUES (?,?,?,?)");
stat2.setInt(1, 1);
stat2.setString(2, SCHEMA_KEY);
- stat2.setDate(3, new java.sql.Date(new java.util.Date(2100,11,31).getTime()));
+ stat2.setDate(3, new java.sql.Date(new java.util.Date(2100,
+ 11, 31).getTime()));
stat2.setObject(4, SCHEMA_VERSION);
// System.out.println(stat2.toString());
stat2.executeUpdate();
db = null;
}
}
- try {
- //System.out.println("Preparing statements");
- getStatement = db.prepareStatement("SELECT programme FROM cache WHERE source=? AND id=?");
- putStatement = db.prepareStatement("INSERT INTO cache VALUES (?,?,?,?)");
- removeStatement = db.prepareStatement("DELETE FROM cache WHERE source=? AND id=?");
+ try {
+ // System.out.println("Preparing statements");
+ getStatement = db
+ .prepareStatement("SELECT programme FROM cache WHERE source=? AND id=?");
+ putStatement = db
+ .prepareStatement("INSERT INTO cache VALUES (?,?,?,?)");
+ removeStatement = db
+ .prepareStatement("DELETE FROM cache WHERE source=? AND id=?");
clearStatement = db.prepareStatement("DELETE FROM cache");
- clearSourceStatement = db.prepareStatement("DELETE FROM cache WHERE source=?");
+ clearSourceStatement = db
+ .prepareStatement("DELETE FROM cache WHERE source=?");
} catch (SQLException e) {
if (!config.quiet) {
logger.warn("Unable to prepare statements, proceeding without cache");
logger.debug("stack trace: ", e);
}
db = null;
- }
+ }
- }
+ }
}
-
+
public Programme get(int source, String id) {
- if (db==null) return null;
+ if (db == null)
+ return null;
try {
getStatement.setInt(1, source);
getStatement.setString(2, id);
ResultSet r = getStatement.executeQuery();
- if (!r.next()) return null; // not found
+ if (!r.next())
+ return null; // not found
try {
Programme result = (Programme) r.getObject("programme");
return result;
}
} catch (SQLException e) {
if (!config.quiet) {
- logger.warn("Error fetching programme ("+source+","+id+") from cache");
+ logger.warn("Error fetching programme (" + source + "," + id
+ + ") from cache");
logger.debug("stack trace: ", e);
}
return null;
}
}
-
+
private void removeCacheEntry(int source, String id) {
try {
removeStatement.setInt(1, source);
removeStatement.setString(2, id);
removeStatement.execute();
} catch (SQLException e) {
- logger.warn("Exception trying to remove item "+id+" from source "+source+" from cache");
+ logger.warn("Exception trying to remove item " + id
+ + " from source " + source + " from cache");
logger.debug("Stack trace: ", e);
}
}
public void put(int source, String id, Programme prog) {
- if (db == null) return;
+ if (db == null)
+ return;
try {
putStatement.setInt(1, source);
putStatement.setString(2, id);
- putStatement.setDate(3, new java.sql.Date(prog.startTime.getTime()));
+ putStatement
+ .setDate(3, new java.sql.Date(prog.startTime.getTime()));
putStatement.setObject(4, prog);
- //System.out.println(putStatement.toString());
+ // System.out.println(putStatement.toString());
int count = putStatement.executeUpdate();
- if (count!=1 && !config.quiet) {
- logger.warn("Weird, cache database update statement affected " + count + " rows");
+ if (count != 1 && !config.quiet) {
+ logger.warn("Weird, cache database update statement affected "
+ + count + " rows");
}
} catch (SQLException e) {
- logger.warn("Error writing programme ("+source+","+id+") to cache");
+ logger.warn("Error writing programme (" + source + "," + id
+ + ") to cache");
logger.debug("stack trace:", e);
}
}
public void cleanup() {
- if (db==null) return;
+ if (db == null)
+ return;
Statement stat;
try {
stat = db.createStatement();
- int count = stat.executeUpdate("DELETE FROM cache WHERE date<CURRENT_DATE - 3 DAY");
- if (!config.quiet && count>0) {
+ int count = stat
+ .executeUpdate("DELETE FROM cache WHERE date<CURRENT_DATE - 3 DAY");
+ if (!config.quiet && count > 0) {
logger.info("Purged " + count + " old entries from cache");
}
stat.close();
}
public void clear() {
- if (db==null) return;
+ if (db == null)
+ return;
try {
int count = clearStatement.executeUpdate();
- if (!config.quiet && count>0) {
+ if (!config.quiet && count > 0) {
logger.info("Cleared " + count + " entries from cache");
}
} catch (SQLException e) {
}
public void clear(int source) {
- if (db==null) return;
+ if (db == null)
+ return;
try {
clearSourceStatement.setInt(1, source);
int count = clearSourceStatement.executeUpdate();
- if (!config.quiet && count>0) {
+ if (!config.quiet && count > 0) {
logger.info("Cleared " + count + " entries from cache");
}
} catch (SQLException e) {
import org.w3c.dom.Node;\r
import org.w3c.dom.NodeList;\r
\r
-public class RTL extends AbstractEPGSource implements EPGSource {\r
+public class RTL extends AbstractEPGSource implements EPGSource {\r
\r
- private static final String programme_url="http://www.rtl.nl/active/epg_data/dag_data/";\r
- private static final String detail_url="http://www.rtl.nl/active/epg_data/uitzending_data/";\r
- private static final String icon_url="http://www.rtl.nl/service/gids/components/vaste_componenten/";\r
+ private static final String programme_url = "http://www.rtl.nl/active/epg_data/dag_data/";\r
+ private static final String detail_url = "http://www.rtl.nl/active/epg_data/uitzending_data/";\r
+ private static final String icon_url = "http://www.rtl.nl/service/gids/components/vaste_componenten/";\r
private static final int MAX_PROGRAMMES_PER_DAY = 9999;\r
- public static final String NAME="rtl.nl";\r
+ public static final String NAME = "rtl.nl";\r
static Logger logger = Logger.getLogger(RTL.class);\r
\r
- \r
- String[] xmlKeys = {"zendernr", "pgmsoort", "genre", "bijvnwlanden", "ondertiteling", "begintijd", "titel", \r
- "site_path", "wwwadres", "presentatie", "omroep", "eindtijd", "inhoud", "tt_inhoud", "alginhoud", "afl_titel", "kijkwijzer" };\r
- Map<String,Integer> xmlKeyMap = new HashMap<String,Integer>();\r
- \r
+ String[] xmlKeys = { "zendernr", "pgmsoort", "genre", "bijvnwlanden",\r
+ "ondertiteling", "begintijd", "titel", "site_path", "wwwadres",\r
+ "presentatie", "omroep", "eindtijd", "inhoud", "tt_inhoud",\r
+ "alginhoud", "afl_titel", "kijkwijzer" };\r
+ Map<String, Integer> xmlKeyMap = new HashMap<String, Integer>();\r
+\r
static boolean debug = false;\r
PrintWriter debugWriter;\r
- \r
+\r
class RTLException extends Exception {\r
public RTLException(String s) {\r
super(s);\r
}\r
}\r
- \r
+\r
class DateStatus {\r
Date programDate;\r
Calendar prevStartTime = null;\r
- final static int START_TIME=1;\r
- final static int END_TIME=2;\r
+ final static int START_TIME = 1;\r
+ final static int END_TIME = 2;\r
+\r
public DateStatus(Date date) {\r
reset(date);\r
}\r
+\r
public void reset(Date date) {\r
this.programDate = date;\r
this.prevStartTime = null;\r
}\r
}\r
- \r
+\r
class DescStatus {\r
String inhoud;\r
String alginhoud;\r
String tt_inhoud;\r
}\r
- \r
+\r
public RTL(int sourceId, Config config) {\r
super(sourceId, config);\r
- if(debug) {\r
- for(int i=0; i<xmlKeys.length; i++) {\r
+ if (debug) {\r
+ for (int i = 0; i < xmlKeys.length; i++) {\r
xmlKeyMap.put(xmlKeys[i], i);\r
}\r
}\r
}\r
- \r
+\r
public String getName() {\r
return NAME;\r
}\r
- \r
+\r
public List<Channel> getChannels() {\r
List<Channel> result = new ArrayList<Channel>(10);\r
\r
URL url = null;\r
try {\r
- url = new URL(programme_url+"1");\r
+ url = new URL(programme_url + "1");\r
} catch (MalformedURLException e) {\r
logger.error("Exception creating RTL channel list url", e);\r
}\r
Document xml = null;\r
try {\r
- xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openStream());\r
+ xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()\r
+ .parse(url.openStream());\r
} catch (Exception e) {\r
- logger.error("Exception reading info from "+url+" and transforming to XML", e);\r
+ logger.error("Exception reading info from " + url\r
+ + " and transforming to XML", e);\r
}\r
Element root = xml.getDocumentElement();\r
String json = root.getTextContent();\r
- JSONObject o = JSONObject.fromObject( json );\r
- for( Object k: o.keySet()) {\r
+ JSONObject o = JSONObject.fromObject(json);\r
+ for (Object k : o.keySet()) {\r
JSONArray j = (JSONArray) o.get(k);\r
String id = genericChannelId(k.toString());\r
String name = (String) j.get(0);\r
- String icon = icon_url+id+".gif";\r
- \r
+ String icon = icon_url + id + ".gif";\r
+\r
Channel c = Channel.getChannel(getId(), id, name, icon);\r
result.add(c);\r
}\r
\r
Collections.sort(result, new Comparator<Channel>() {\r
public int compare(Channel o1, Channel o2) {\r
- if (o1.source==o2.source) {\r
- int c1=Integer.parseInt(o1.id);\r
- int c2=Integer.parseInt(o2.id);\r
- return (c1==c2 ? 0 : ((c1<c2)?-1:1) );\r
- } else {\r
- return o1.source<o2.source?-1:1;\r
+ if (o1.source == o2.source) {\r
+ int c1 = Integer.parseInt(o1.id);\r
+ int c2 = Integer.parseInt(o2.id);\r
+ return (c1 == c2 ? 0 : ((c1 < c2) ? -1 : 1));\r
+ } else {\r
+ return o1.source < o2.source ? -1 : 1;\r
}\r
}\r
});\r
return result;\r
}\r
- \r
+\r
private String genericChannelId(String jsonid) {\r
return jsonid.replaceAll("^Z", ""); // remove initial Z\r
}\r
- \r
- /*\r
- * <?xml version="1.0" encoding="iso-8859-1" ?>\r
- * <uitzending_data>\r
- * <uitzending_data_item>\r
- * <zendernr>5</zendernr>\r
- * <pgmsoort>Realityserie</pgmsoort>\r
- * <genre>Amusement</genre>\r
- * <bijvnwlanden></bijvnwlanden>\r
- * <ondertiteling></ondertiteling>\r
- * <begintijd>05:00</begintijd>\r
- * <titel>Marriage Under Construction</titel>\r
- * <site_path>0</site_path>\r
- * <wwwadres></wwwadres>\r
- * <presentatie></presentatie>\r
- * <omroep></omroep>\r
- * <eindtijd>06:00</eindtijd>\r
- * <inhoud></inhoud>\r
- * <tt_inhoud>Een jong stel wordt gevolgd bij het zoeken naar, en vervolgens verbouwen en inrichten van, hun eerste huis. Dit verloopt uiteraard niet zonder slag of stoot.</tt_inhoud>\r
- * <alginhoud>Een jong stel wordt gevolgd bij het zoeken naar, en vervolgens verbouwen en inrichten van, hun eerste huis. Dit verloopt uiteraard niet zonder slag of stoot.</alginhoud>\r
- * <afl_titel></afl_titel>\r
- * <kijkwijzer></kijkwijzer>\r
- * </uitzending_data_item>\r
- * </uitzending_data>\r
\r
+ /*\r
+ * <?xml version="1.0" encoding="iso-8859-1" ?> <uitzending_data>\r
+ * <uitzending_data_item> <zendernr>5</zendernr>\r
+ * <pgmsoort>Realityserie</pgmsoort> <genre>Amusement</genre>\r
+ * <bijvnwlanden></bijvnwlanden> <ondertiteling></ondertiteling>\r
+ * <begintijd>05:00</begintijd> <titel>Marriage Under Construction</titel>\r
+ * <site_path>0</site_path> <wwwadres></wwwadres>\r
+ * <presentatie></presentatie> <omroep></omroep> <eindtijd>06:00</eindtijd>\r
+ * <inhoud></inhoud> <tt_inhoud>Een jong stel wordt gevolgd bij het zoeken\r
+ * naar, en vervolgens verbouwen en inrichten van, hun eerste huis. Dit\r
+ * verloopt uiteraard niet zonder slag of stoot.</tt_inhoud> <alginhoud>Een\r
+ * jong stel wordt gevolgd bij het zoeken naar, en vervolgens verbouwen en\r
+ * inrichten van, hun eerste huis. Dit verloopt uiteraard niet zonder slag\r
+ * of stoot.</alginhoud> <afl_titel></afl_titel> <kijkwijzer></kijkwijzer>\r
+ * </uitzending_data_item> </uitzending_data>\r
*/\r
- private void fetchDetail(Programme prog, DateStatus dateStatus, String id) throws Exception {\r
+ private void fetchDetail(Programme prog, DateStatus dateStatus, String id)\r
+ throws Exception {\r
URL url = detailUrl(id);\r
Thread.sleep(config.niceMilliseconds);\r
- Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openStream());\r
+ Document xml = DocumentBuilderFactory.newInstance()\r
+ .newDocumentBuilder().parse(url.openStream());\r
Element root = xml.getDocumentElement();\r
if (root.hasAttributes()) {\r
logger.warn("Unknown attributes for RTL detail root node");\r
}\r
NodeList nodes = root.getChildNodes();\r
DescStatus descStatus = new DescStatus();\r
- for(int i=0; i<nodes.getLength(); i++) {\r
+ for (int i = 0; i < nodes.getLength(); i++) {\r
Node n = nodes.item(i);\r
if (!n.getNodeName().equals("uitzending_data_item")) {\r
- logger.warn("Ignoring RTL detail, tag " + n.getNodeName() +", full xml:");\r
- Transformer t = TransformerFactory.newInstance().newTransformer();\r
+ logger.warn("Ignoring RTL detail, tag " + n.getNodeName()\r
+ + ", full xml:");\r
+ Transformer t = TransformerFactory.newInstance()\r
+ .newTransformer();\r
StringWriter writer = new StringWriter();\r
StreamResult result = new StreamResult(writer);\r
- t.transform(new DOMSource(xml),result);\r
+ t.transform(new DOMSource(xml), result);\r
logger.debug(writer.toString());\r
continue;\r
}\r
// we have a uitzending_data_item node\r
NodeList subnodes = n.getChildNodes();\r
String[] result = new String[xmlKeys.length];\r
- for( int j=0; j<subnodes.getLength(); j++) {\r
+ for (int j = 0; j < subnodes.getLength(); j++) {\r
try {\r
if (debug) {\r
Node sub = subnodes.item(j);\r
- String key = ((Element)sub).getTagName();\r
+ String key = ((Element) sub).getTagName();\r
int index = xmlKeyMap.get(key);\r
- String value = "\"" + sub.getTextContent().replaceAll("\\s", " ") + "\"";\r
+ String value = "\""\r
+ + sub.getTextContent().replaceAll("\\s", " ")\r
+ + "\"";\r
result[index] = value;\r
}\r
handleNode(prog, dateStatus, descStatus, subnodes.item(j));\r
} catch (RTLException e) {\r
- Transformer t = TransformerFactory.newInstance().newTransformer();\r
+ Transformer t = TransformerFactory.newInstance()\r
+ .newTransformer();\r
StringWriter writer = new StringWriter();\r
StreamResult result2 = new StreamResult(writer);\r
- t.transform(new DOMSource(xml),result2);\r
+ t.transform(new DOMSource(xml), result2);\r
logger.debug(writer.toString(), e);\r
continue;\r
}\r
}\r
if (debug) {\r
- for(int k=0; k<result.length; k++) {\r
+ for (int k = 0; k < result.length; k++) {\r
debugWriter.print(result[k]);\r
debugWriter.print(",");\r
}\r
}\r
}\r
StringBuilder description = new StringBuilder();\r
- if (descStatus.alginhoud!=null) description.append(descStatus.alginhoud);\r
- if (descStatus.inhoud!=null) {\r
- if (description.length()!=0) {\r
+ if (descStatus.alginhoud != null)\r
+ description.append(descStatus.alginhoud);\r
+ if (descStatus.inhoud != null) {\r
+ if (description.length() != 0) {\r
description.append("<p>");\r
}\r
description.append(descStatus.inhoud);\r
}\r
- if (description.length()==0 && descStatus.tt_inhoud!=null) {\r
- // only use tt_inhoud if the other two are both empty, since it is almost\r
+ if (description.length() == 0 && descStatus.tt_inhoud != null) {\r
+ // only use tt_inhoud if the other two are both empty, since it is\r
+ // almost\r
// always a summary of those fields and others such as <presenter>\r
description.append(descStatus.tt_inhoud);\r
}\r
prog.addDescription(description.toString());\r
}\r
\r
- \r
- private void handleNode(Programme prog, DateStatus dateStatus, DescStatus descStatus, Node n) throws RTLException, DOMException, SQLException {\r
+ private void handleNode(Programme prog, DateStatus dateStatus,\r
+ DescStatus descStatus, Node n) throws RTLException, DOMException,\r
+ SQLException {\r
if (n.getNodeType() != Node.ELEMENT_NODE) {\r
- throw new RTLException("Ignoring non-element node " + n.getNodeName());\r
+ throw new RTLException("Ignoring non-element node "\r
+ + n.getNodeName());\r
}\r
if (n.hasAttributes()) {\r
- throw new RTLException("Unknown attributes for RTL detail node " + n.getNodeName());\r
+ throw new RTLException("Unknown attributes for RTL detail node "\r
+ + n.getNodeName());\r
}\r
if (n.hasChildNodes()) {\r
NodeList list = n.getChildNodes();\r
- for( int i=0; i<list.getLength(); i++) {\r
- if(list.item(i).getNodeType() == Node.ELEMENT_NODE) {\r
- throw new RTLException("RTL detail node " + n.getNodeName() + " has unexpected child element " + list.item(i).getNodeName());\r
+ for (int i = 0; i < list.getLength(); i++) {\r
+ if (list.item(i).getNodeType() == Node.ELEMENT_NODE) {\r
+ throw new RTLException("RTL detail node " + n.getNodeName()\r
+ + " has unexpected child element "\r
+ + list.item(i).getNodeName());\r
}\r
}\r
}\r
- Element e = (Element)n;\r
+ Element e = (Element) n;\r
String tag = e.getTagName();\r
\r
if (e.getTextContent().isEmpty()) {\r
if (tag.equals("genre")) {\r
prog.addCategory(config.translateCategory(e.getTextContent()));\r
} else if (tag.equals("eindtijd")) {\r
- prog.endTime = parseTime(e.getTextContent(), dateStatus, DateStatus.END_TIME);\r
+ prog.endTime = parseTime(e.getTextContent(), dateStatus,\r
+ DateStatus.END_TIME);\r
} else if (tag.equals("omroep")) {\r
} else if (tag.equals("kijkwijzer")) {\r
logger.trace(prog.toString());\r
// mythtv doesn't understand multiple <rating> tags\r
prog.addRating("kijkwijzer", StringUtils.join(list, ","));\r
} else {\r
- for(String rating: list) {\r
+ for (String rating : list) {\r
prog.addRating("kijkwijzer", rating);\r
}\r
}\r
} else if (tag.equals("presentatie")) {\r
// A; A en B; A, B, C en D\r
String[] presentatoren = e.getTextContent().split(", | en ");\r
- for(String pres:presentatoren) {\r
+ for (String pres : presentatoren) {\r
prog.addPresenter(pres);\r
}\r
} else if (tag.equals("wwwadres")) {\r
prog.addSecondaryTitle(e.getTextContent());\r
} else if (tag.equals("site_path")) {\r
} else if (tag.equals("ondertiteling")) {\r
- if(e.getTextContent().equals("J")) {\r
+ if (e.getTextContent().equals("J")) {\r
prog.addSubtitle("teletext");\r
} else {\r
- throw new RTLException("Ignoring unknown value \"" + n.getTextContent() + "\" for tag ondertiteling");\r
+ throw new RTLException("Ignoring unknown value \""\r
+ + n.getTextContent() + "\" for tag ondertiteling");\r
}\r
} else if (tag.equals("begintijd")) {\r
} else if (tag.equals("pgmsoort")) {\r
} else {\r
- throw new RTLException("Ignoring unknown tag " + n.getNodeName() + ", content: \"" + e.getTextContent() + "\"");\r
+ throw new RTLException("Ignoring unknown tag " + n.getNodeName()\r
+ + ", content: \"" + e.getTextContent() + "\"");\r
}\r
- //prog.endTime = parseTime(date, root.)\r
+ // prog.endTime = parseTime(date, root.)\r
}\r
\r
@Override\r
- public List<Programme> getProgrammes(List<Channel> channels, int day) throws Exception {\r
+ public List<Programme> getProgrammes(List<Channel> channels, int day)\r
+ throws Exception {\r
List<Programme> result = new LinkedList<Programme>();\r
- Map<String,Channel> channelMap = new HashMap<String,Channel>();\r
- for(Channel c: channels) {\r
- if (c.enabled && c.source==getId()) channelMap.put(c.id, c);\r
+ Map<String, Channel> channelMap = new HashMap<String, Channel>();\r
+ for (Channel c : channels) {\r
+ if (c.enabled && c.source == getId())\r
+ channelMap.put(c.id, c);\r
}\r
URL url = programmeUrl(day);\r
- //String xmltext = fetchURL(url);\r
- //System.out.println(xmltext);\r
+ // String xmltext = fetchURL(url);\r
+ // System.out.println(xmltext);\r
Thread.sleep(config.niceMilliseconds);\r
- Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(url.openStream());\r
+ Document xml = DocumentBuilderFactory.newInstance()\r
+ .newDocumentBuilder().parse(url.openStream());\r
Element root = xml.getDocumentElement();\r
- Date date = new SimpleDateFormat("yyyy-MM-dd").parse(root.getAttribute("date"));\r
+ Date date = new SimpleDateFormat("yyyy-MM-dd").parse(root\r
+ .getAttribute("date"));\r
DateStatus dateStatus = new DateStatus(date);\r
- //System.out.println("date: " + date);\r
+ // System.out.println("date: " + date);\r
String json = root.getTextContent();\r
- //System.out.println("json: " + json);\r
- JSONObject o = JSONObject.fromObject( json );\r
+ // System.out.println("json: " + json);\r
+ JSONObject o = JSONObject.fromObject(json);\r
String prevChannel = null;\r
- for( Object k: o.keySet()) {\r
+ for (Object k : o.keySet()) {\r
String id = genericChannelId(k.toString());\r
- if(!channelMap.containsKey(id)) {\r
- //if (!config.quiet) System.out.println("Skipping programmes for channel " + id);\r
+ if (!channelMap.containsKey(id)) {\r
+ // if (!config.quiet)\r
+ // System.out.println("Skipping programmes for channel " + id);\r
continue;\r
}\r
if (!id.equals(prevChannel)) {\r
prevChannel = id;\r
}\r
JSONArray j = (JSONArray) o.get(k);\r
- //System.out.println(k.toString()+": "+j.toString());\r
- //System.out.println("Channel name:" + j.get(0));\r
- for (int i=1; i<j.size() && i<MAX_PROGRAMMES_PER_DAY; i++) {\r
+ // System.out.println(k.toString()+": "+j.toString());\r
+ // System.out.println("Channel name:" + j.get(0));\r
+ for (int i = 1; i < j.size() && i < MAX_PROGRAMMES_PER_DAY; i++) {\r
JSONArray p = (JSONArray) j.get(i);\r
String starttime = p.getString(0);\r
String title = p.getString(1);\r
String programme_id = p.getString(2);\r
String genre_id = p.getString(3); // 1 = amusement, etc\r
String quark2 = p.getString(4); // 0 of 1, movie flag?\r
- if(debug) debugWriter.print("\""+id+"\",\""+starttime+"\",\""+title+"\",\""+genre_id+"\",\""+quark2+"\",");\r
+ if (debug)\r
+ debugWriter.print("\"" + id + "\",\"" + starttime + "\",\""\r
+ + title + "\",\"" + genre_id + "\",\"" + quark2\r
+ + "\",");\r
Programme prog = cache.get(getId(), programme_id);\r
if (prog == null) {\r
stats.cacheMisses++;\r
prog = new Programme();\r
prog.addTitle(title);\r
- prog.startTime = parseTime(starttime, dateStatus, DateStatus.START_TIME);\r
+ prog.startTime = parseTime(starttime, dateStatus,\r
+ DateStatus.START_TIME);\r
prog.channel = channelMap.get(id).getXmltvChannelId();\r
if (config.fetchDetails) {\r
fetchDetail(prog, dateStatus, programme_id);\r
Calendar result = Calendar.getInstance();\r
result.setTime(status.programDate);\r
String[] parts = time.split(":");\r
- if(parts.length != 2) {\r
- if (!config.quiet) logger.debug("Wrong time format " + time); \r
+ if (parts.length != 2) {\r
+ if (!config.quiet)\r
+ logger.debug("Wrong time format " + time);\r
// ignore\r
}\r
result.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));\r
result.set(Calendar.MINUTE, Integer.parseInt(parts[1]));\r
Calendar prev = status.prevStartTime;\r
- // Check if the start time of a new program is at most one hour before the start time of \r
- // the previous one. End time of a program should be at or after the start time of the \r
+ // Check if the start time of a new program is at most one hour before\r
+ // the start time of\r
+ // the previous one. End time of a program should be at or after the\r
+ // start time of the\r
// program. Else, assume it's on the next day.\r
if (prev != null) {\r
- if (mode == DateStatus.START_TIME){ \r
+ if (mode == DateStatus.START_TIME) {\r
prev.add(Calendar.HOUR_OF_DAY, -1);\r
}\r
if (result.before(prev)) {\r
- result.add(Calendar.DAY_OF_MONTH, 1); \r
+ result.add(Calendar.DAY_OF_MONTH, 1);\r
}\r
}\r
- if (mode==DateStatus.START_TIME) {\r
+ if (mode == DateStatus.START_TIME) {\r
status.prevStartTime = result;\r
}\r
return result.getTime();\r
}\r
\r
private static URL programmeUrl(int day) throws MalformedURLException {\r
- return new URL(programme_url+day);\r
+ return new URL(programme_url + day);\r
}\r
- \r
+\r
private static URL detailUrl(String id) throws Exception {\r
- return new URL(detail_url+id);\r
+ return new URL(detail_url + id);\r
}\r
\r
/**\r
* @param args\r
- * @throws FileNotFoundException \r
+ * @throws FileNotFoundException\r
*/\r
public static void main(String[] args) throws FileNotFoundException {\r
debug = true;\r
- Logger.getRootLogger().setLevel(Level.TRACE);\r
+ Logger.getRootLogger().setLevel(Level.TRACE);\r
\r
Config config = Config.getDefaultConfig();\r
config.niceMilliseconds = 50;\r
if (debug) {\r
rtl.cache.clear();\r
logger.info("Writing CSV to rtl.csv");\r
- rtl.debugWriter = new PrintWriter( new BufferedOutputStream(new FileOutputStream("rtl.csv")));\r
- rtl.debugWriter.print("\"zender\",\"starttime\",\"title\",\"quark1\",\"quark2\",");\r
- for(int k=0; k<rtl.xmlKeys.length; k++) {\r
+ rtl.debugWriter = new PrintWriter(new BufferedOutputStream(\r
+ new FileOutputStream("rtl.csv")));\r
+ rtl.debugWriter\r
+ .print("\"zender\",\"starttime\",\"title\",\"quark1\",\"quark2\",");\r
+ for (int k = 0; k < rtl.xmlKeys.length; k++) {\r
rtl.debugWriter.print(rtl.xmlKeys[k]);\r
rtl.debugWriter.print(",");\r
}\r
try {\r
List<Channel> channels = rtl.getChannels();\r
logger.info("Channels: " + channels);\r
- XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter("rtl.xml"));\r
+ XMLStreamWriter writer = XMLOutputFactory.newInstance()\r
+ .createXMLStreamWriter(new FileWriter("rtl.xml"));\r
writer.writeStartDocument();\r
writer.writeCharacters("\n");\r
writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">");\r
writer.writeCharacters("\n");\r
writer.writeStartElement("tv");\r
- for(Channel c: channels) {c.serialize(writer);}\r
+ for (Channel c : channels) {\r
+ c.serialize(writer);\r
+ }\r
writer.flush();\r
- //List<Programme> programmes = rtl.getProgrammes(channels.subList(6, 9), 0);\r
- for(int day=0; day<10; day++) {\r
+ // List<Programme> programmes =\r
+ // rtl.getProgrammes(channels.subList(6, 9), 0);\r
+ for (int day = 0; day < 10; day++) {\r
List<Programme> programmes = rtl.getProgrammes(channels, day);\r
- for(Programme p: programmes) {p.serialize(writer);}\r
+ for (Programme p : programmes) {\r
+ p.serialize(writer);\r
+ }\r
}\r
writer.writeEndElement();\r
writer.writeEndDocument();\r
writer.flush();\r
if (!config.quiet) {\r
EPGSource.Stats stats = rtl.getStats();\r
- logger.info("Number of programmes from cache: " + stats.cacheHits);\r
- logger.info("Number of programmes fetched: " + stats.cacheMisses);\r
+ logger.info("Number of programmes from cache: "\r
+ + stats.cacheHits);\r
+ logger.info("Number of programmes fetched: "\r
+ + stats.cacheMisses);\r
logger.info("Number of fetch errors: " + stats.fetchErrors);\r
}\r
if (debug) {\r
package org.vanbest.xmltv;
/*
- Copyright (c) 2012 Jan-Pascal van Best <janpascal@vanbest.org>
+ Copyright (c) 2012 Jan-Pascal van Best <janpascal@vanbest.org>
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation; either version 2 of the License, or
- (at your option) any later version.
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
- The full license text can be found in the LICENSE file.
-*/
+ The full license text can be found in the LICENSE file.
+ */
import java.io.BufferedReader;
import java.io.FileWriter;
public class TvGids extends AbstractEPGSource implements EPGSource {
- static String channels_url="http://www.tvgids.nl/json/lists/channels.php";
- static String programme_base_url="http://www.tvgids.nl/json/lists/programs.php";
+ static String channels_url = "http://www.tvgids.nl/json/lists/channels.php";
+ static String programme_base_url = "http://www.tvgids.nl/json/lists/programs.php";
static String detail_base_url = "http://www.tvgids.nl/json/lists/program.php";
static String html_detail_base_url = "http://www.tvgids.nl/programma/";
-
+
private static final int MAX_PROGRAMMES_PER_DAY = 9999;
private static final int MAX_DAYS_AHEAD_SUPPORTED_BY_TVGIDS = 3;
-
- public static String NAME="tvgids.nl";
-
+
+ public static String NAME = "tvgids.nl";
+
static Logger logger = Logger.getLogger(TvGids.class);
public TvGids(int sourceId, Config config) {
super(sourceId, config);
}
-
+
public String getName() {
return NAME;
}
-
- public static URL programmeUrl(List<Channel> channels, int day) throws Exception {
+
+ public static URL programmeUrl(List<Channel> channels, int day)
+ throws Exception {
StringBuilder s = new StringBuilder(programme_base_url);
if (channels.size() < 1) {
throw new Exception("should have at least one channel");
}
s.append("?channels=");
boolean first = true;
- for(Channel i: channels) {
+ for (Channel i : channels) {
if (first) {
s.append(i.id);
first = false;
} else {
- s.append(","+i.id);
+ s.append("," + i.id);
}
}
s.append("&day=");
s.append(day);
-
+
return new URL(s.toString());
}
-
+
public static URL JSONDetailUrl(String id) throws Exception {
StringBuilder s = new StringBuilder(detail_base_url);
s.append("?id=");
s.append(id);
return new URL(s.toString());
}
-
+
public static URL HTMLDetailUrl(String id) throws Exception {
StringBuilder s = new StringBuilder(html_detail_base_url);
s.append(id);
return new URL(s.toString());
}
- /* (non-Javadoc)
+ /*
+ * (non-Javadoc)
+ *
* @see org.vanbest.xmltv.EPGSource#getChannels()
*/
@Override
} catch (MalformedURLException e) {
logger.error("Exception creating tvgids channel list url", e);
}
-
+
StringBuffer json = new StringBuffer();
try {
- BufferedReader reader = new BufferedReader( new InputStreamReader( url.openStream()));
+ BufferedReader reader = new BufferedReader(new InputStreamReader(
+ url.openStream()));
String s;
- while ((s = reader.readLine()) != null) json.append(s);
+ while ((s = reader.readLine()) != null)
+ json.append(s);
} catch (IOException e) {
- logger.error("IO Exception reading channel information from tvgids url "+url.toString(), e);
+ logger.error(
+ "IO Exception reading channel information from tvgids url "
+ + url.toString(), e);
}
logger.debug("tvgids channels json: " + json.toString());
- JSONArray jsonArray = JSONArray.fromObject( json.toString() );
- // System.out.println( jsonArray );
-
- for( int i=0; i<jsonArray.size(); i++ ) {
+ JSONArray jsonArray = JSONArray.fromObject(json.toString());
+ // System.out.println( jsonArray );
+
+ for (int i = 0; i < jsonArray.size(); i++) {
JSONObject zender = jsonArray.getJSONObject(i);
- //System.out.println( "id: " + zender.getString("id"));
- //System.out.println( "name: " + zender.getString("name"));
+ // System.out.println( "id: " + zender.getString("id"));
+ // System.out.println( "name: " + zender.getString("name"));
int id = zender.getInt("id");
- String name = org.apache.commons.lang.StringEscapeUtils.unescapeHtml(zender.getString("name"));
- String icon = "http://tvgidsassets.nl/img/channels/53x27/" + id + ".png";
- Channel c = Channel.getChannel(getId(), Integer.toString(id), name, icon);
+ String name = org.apache.commons.lang.StringEscapeUtils
+ .unescapeHtml(zender.getString("name"));
+ String icon = "http://tvgidsassets.nl/img/channels/53x27/" + id
+ + ".png";
+ Channel c = Channel.getChannel(getId(), Integer.toString(id), name,
+ icon);
result.add(c);
}
- return result;
+ return result;
}
-
+
private JSONObject fetchJSON(URL url) throws Exception {
String json = fetchURL(url);
logger.debug(json);
- return JSONObject.fromObject( json );
+ return JSONObject.fromObject(json);
}
-
- /* (non-Javadoc)
- * @see org.vanbest.xmltv.EPGSource#getProgrammes(java.util.List, int, boolean)
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.vanbest.xmltv.EPGSource#getProgrammes(java.util.List, int,
+ * boolean)
*/
@Override
- public List<Programme> getProgrammes(List<Channel> channels, int day) throws Exception {
+ public List<Programme> getProgrammes(List<Channel> channels, int day)
+ throws Exception {
List<Programme> result = new ArrayList<Programme>();
- if (day>MAX_DAYS_AHEAD_SUPPORTED_BY_TVGIDS) {
+ if (day > MAX_DAYS_AHEAD_SUPPORTED_BY_TVGIDS) {
return result; // empty list
}
URL url = programmeUrl(channels, day);
- JSONObject jsonObject = fetchJSON(url);
-
- for(Channel c: channels) {
+ JSONObject jsonObject = fetchJSON(url);
+
+ for (Channel c : channels) {
JSON ps = (JSON) jsonObject.get(c.id);
- if ( ps.isArray() ) {
+ if (ps.isArray()) {
JSONArray programs = (JSONArray) ps;
- for( int i=0; i<programs.size() && i<MAX_PROGRAMMES_PER_DAY; i++ ) {
+ for (int i = 0; i < programs.size()
+ && i < MAX_PROGRAMMES_PER_DAY; i++) {
JSONObject programme = programs.getJSONObject(i);
- Programme p = programmeFromJSON(programme, config.fetchDetails);
+ Programme p = programmeFromJSON(programme,
+ config.fetchDetails);
p.channel = c.getXmltvChannelId();
result.add(p);
}
- } else {
+ } else {
JSONObject programs = (JSONObject) ps;
int count = 0;
- for( Object o: programs.keySet() ) {
- if (count>MAX_PROGRAMMES_PER_DAY) break;
+ for (Object o : programs.keySet()) {
+ if (count > MAX_PROGRAMMES_PER_DAY)
+ break;
JSONObject programme = programs.getJSONObject(o.toString());
- Programme p = programmeFromJSON(programme, config.fetchDetails);
+ Programme p = programmeFromJSON(programme,
+ config.fetchDetails);
p.channel = c.getXmltvChannelId();
result.add(p);
count++;
return result;
}
-
+
/*
- * {"4":
- * [{"db_id":"12436404",
- * "titel":"RTL Boulevard",
- * "genre":"Amusement",
- * "soort":"Amusementsprogramma",
- * "kijkwijzer":"",
- * "artikel_id":null,
- * "datum_start":"2012-03-30 23:45:00",
- * "datum_end":"2012-03-31 00:40:00"},
- * {"db_id":"12436397","titel":"Teleshop 4","genre":"Overige","soort":"Homeshopping","kijkwijzer":"","artikel_id":null,"datum_start":"2012-03-31 00:40:00","datum_end":"2012-03-31 00:41:00"},
- * {"db_id":"12436398","titel":"Cupido TV","genre":"Overige","soort":"","kijkwijzer":"","artikel_id":null,"datum_start":"2012-03-31 00:41:00","datum_end":"2012-03-31 04:30:00"},
- * {"db_id":"12436399","titel":"Morning chat","genre":"Overige","soort":"","kijkwijzer":"","artikel_id":null,"datum_start":"2012-03-31 04:30:00","datum_end":"2012-03-31 06:00:00"},
- * ....... ]}
+ * {"4": [{"db_id":"12436404", "titel":"RTL Boulevard", "genre":"Amusement",
+ * "soort":"Amusementsprogramma", "kijkwijzer":"", "artikel_id":null,
+ * "datum_start":"2012-03-30 23:45:00", "datum_end":"2012-03-31 00:40:00"},
+ * {"db_id":"12436397","titel":"Teleshop 4","genre":"Overige","soort":
+ * "Homeshopping"
+ * ,"kijkwijzer":"","artikel_id":null,"datum_start":"2012-03-31 00:40:00"
+ * ,"datum_end":"2012-03-31 00:41:00"},
+ * {"db_id":"12436398","titel":"Cupido TV"
+ * ,"genre":"Overige","soort":"","kijkwijzer"
+ * :"","artikel_id":null,"datum_start"
+ * :"2012-03-31 00:41:00","datum_end":"2012-03-31 04:30:00"},
+ * {"db_id":"12436399"
+ * ,"titel":"Morning chat","genre":"Overige","soort":"","kijkwijzer"
+ * :"","artikel_id"
+ * :null,"datum_start":"2012-03-31 04:30:00","datum_end":"2012-03-31 06:00:00"
+ * }, ....... ]}
*/
- private Programme programmeFromJSON(JSONObject programme, boolean fetchDetails) throws Exception {
+ private Programme programmeFromJSON(JSONObject programme,
+ boolean fetchDetails) throws Exception {
String id = programme.getString("db_id");
Programme result = cache.get(getId(), id);
boolean cached = (result != null);
if (result == null) {
stats.cacheMisses++;
result = new Programme();
- // Do this here, because we can only add to these fields. Pity if they're updated
+ // Do this here, because we can only add to these fields. Pity if
+ // they're updated
result.addTitle(programme.getString("titel"));
String genre = programme.getString("genre");
- if (genre != null && !genre.isEmpty()) result.addCategory(config.translateCategory(genre));
+ if (genre != null && !genre.isEmpty())
+ result.addCategory(config.translateCategory(genre));
String kijkwijzer = programme.getString("kijkwijzer");
- if (kijkwijzer!=null && !kijkwijzer.isEmpty()) {
+ if (kijkwijzer != null && !kijkwijzer.isEmpty()) {
List<String> list = parseKijkwijzer(kijkwijzer);
if (config.joinKijkwijzerRatings) {
// mythtv doesn't understand multiple <rating> tags
result.addRating("kijkwijzer", StringUtils.join(list, ","));
} else {
- for(String rating: list) {
+ for (String rating : list) {
result.addRating("kijkwijzer", rating);
}
}
// TODO add icon from HTML detail page
}
} else {
- //System.out.println("From cache: " + programme.getString("titel"));
+ // System.out.println("From cache: " +
+ // programme.getString("titel"));
stats.cacheHits++;
}
logger.trace(" titel:" + programme.getString("titel"));
logger.trace("datum_start:" + programme.getString("datum_start"));
logger.trace(" datum_end:" + programme.getString("datum_end"));
logger.trace(" genre:" + programme.getString("genre"));
- SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", new Locale("nl"));
+ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
+ new Locale("nl"));
result.startTime = df.parse(programme.getString("datum_start"));
- result.endTime = df.parse(programme.getString("datum_end"));
+ result.endTime = df.parse(programme.getString("datum_end"));
// TODO other fields
-
+
if (fetchDetails && !cached) {
// TODO also read details if those have not been cached
fillDetails(id, result);
try {
fillJSONDetails(id, result);
} catch (Exception e) {
- logger.warn("Error fetching details for programme " + result.toString() );
+ logger.warn("Error fetching details for programme "
+ + result.toString());
}
try {
fillScraperDetails(id, result);
} catch (Exception e) {
- logger.warn("Error fetching details for programme " + result.toString() );
+ logger.warn("Error fetching details for programme "
+ + result.toString());
}
-
- if ((result.secondaryTitles==null || result.secondaryTitles.isEmpty()) &&
- (!result.hasCategory("movies") && !result.hasCategory("film"))) {
- for(Programme.Title t: result.titles) {
+
+ if ((result.secondaryTitles == null || result.secondaryTitles.isEmpty())
+ && (!result.hasCategory("movies") && !result
+ .hasCategory("film"))) {
+ for (Programme.Title t : result.titles) {
String[] parts = t.title.split("\\s*:\\s*", 2);
- if (parts.length >= 2 && parts[0].length()>=5) {
- logger.debug("Splitting title from \"" + t.title + "\" to: \"" + parts[0].trim() + "\"; sub-title: \"" + parts[1].trim() + "\"");
+ if (parts.length >= 2 && parts[0].length() >= 5) {
+ logger.debug("Splitting title from \"" + t.title
+ + "\" to: \"" + parts[0].trim()
+ + "\"; sub-title: \"" + parts[1].trim() + "\"");
t.title = parts[0].trim();
result.addSecondaryTitle(parts[1].trim());
}
}
/*
- * {"db_id":"12436404",
- * "titel":"RTL Boulevard",
- * "datum":"2012-03-30",
- * "btijd":"23:45:00",
- * "etijd":"00:40:00",
- * "synop":"Amusementsprogramma Actualiteiten, vermaak en opinies met \u00e9\u00e9n of twee deskundigen, gasten of andere nieuwsmakers. In hoog tempo volgen afwisselende items en reportages elkaar op met de thema's showbizz, crime, royalty en lifestyle.<br><br>",
- * "kijkwijzer":"",
- * "genre":"Amusement",
+ * {"db_id":"12436404", "titel":"RTL Boulevard", "datum":"2012-03-30",
+ * "btijd":"23:45:00", "etijd":"00:40:00", "synop":
+ * "Amusementsprogramma Actualiteiten, vermaak en opinies met \u00e9\u00e9n of twee deskundigen, gasten of andere nieuwsmakers. In hoog tempo volgen afwisselende items en reportages elkaar op met de thema's showbizz, crime, royalty en lifestyle.<br><br>"
+ * , "kijkwijzer":"", "genre":"Amusement",
* "presentatie":"Winston Gerschtanowitz, Albert Verlinde",
- * "acteursnamen_rolverdeling":"",
- * "regisseur":"",
- * "zender_id":"4"}
+ * "acteursnamen_rolverdeling":"", "regisseur":"", "zender_id":"4"}
*/
private void fillJSONDetails(String id, Programme result) throws Exception {
URL url = JSONDetailUrl(id);
JSONObject json = fetchJSON(url);
Set<String> keys = json.keySet();
- for(String key: keys) {
+ for (String key : keys) {
String value = StringEscapeUtils.unescapeHtml(json.getString(key));
- if (value.isEmpty()) continue;
- if(key.equals("synop")) {
- value = value.replaceAll("<br>", " ").
- replaceAll("<br />", " ").
- replaceAll("<p[^>]*>", " ").
- replaceAll("</p>", " ").
- replaceAll("<strong>", " ").
- replaceAll("</strong>", " ").
- replaceAll("<em>", " ").
- replaceAll("</em>", " ").
- trim();
- if (value.isEmpty()) continue ;
+ if (value.isEmpty())
+ continue;
+ if (key.equals("synop")) {
+ value = value.replaceAll("<br>", " ").replaceAll("<br />", " ")
+ .replaceAll("<p[^>]*>", " ").replaceAll("</p>", " ")
+ .replaceAll("<strong>", " ")
+ .replaceAll("</strong>", " ").replaceAll("<em>", " ")
+ .replaceAll("</em>", " ").trim();
+ if (value.isEmpty())
+ continue;
result.addDescription(value);
} else if (key.equals("presentatie")) {
String[] parts = value.split(",");
- for (String s: parts) {
+ for (String s : parts) {
result.addPresenter(s.trim());
}
} else if (key.equals("acteursnamen_rolverdeling")) {
- // TODO hoe zouden rollen kunnen worden aangegeven? Geen voorbeelden van gezien.
+ // TODO hoe zouden rollen kunnen worden aangegeven? Geen
+ // voorbeelden van gezien.
String[] parts = value.split(",");
- for (String s: parts) {
+ for (String s : parts) {
result.addActor(s.trim());
}
} else if (key.equals("regisseur")) {
String[] parts = value.split(",");
- for (String s: parts) {
+ for (String s : parts) {
result.addDirector(s.trim());
}
} else if (key.equals("kijkwijzer")) {
} else if (key.equals("zender_id")) {
// ignore
} else {
- logger.warn("Unknown key in tvgids.nl json details: \"" + key + "\"");
+ logger.warn("Unknown key in tvgids.nl json details: \"" + key
+ + "\"");
}
}
}
- private void fillScraperDetails(String id, Programme result) throws Exception {
- Pattern progInfoPattern = Pattern.compile("prog-info-content.*prog-info-footer", Pattern.DOTALL);
- Pattern infoLinePattern = Pattern.compile("<li><strong>(.*?):</strong>(.*?)</li>");
+ private void fillScraperDetails(String id, Programme result)
+ throws Exception {
+ Pattern progInfoPattern = Pattern.compile(
+ "prog-info-content.*prog-info-footer", Pattern.DOTALL);
+ Pattern infoLinePattern = Pattern
+ .compile("<li><strong>(.*?):</strong>(.*?)</li>");
Pattern HDPattern = Pattern.compile("HD \\d+[ip]?");
- Pattern kijkwijzerPattern = Pattern.compile("<img src=\"http://tvgidsassets.nl/img/kijkwijzer/.*?\" alt=\"(.*?)\" />");
+ Pattern kijkwijzerPattern = Pattern
+ .compile("<img src=\"http://tvgidsassets.nl/img/kijkwijzer/.*?\" alt=\"(.*?)\" />");
URL url = HTMLDetailUrl(id);
- String clob=fetchURL(url);
+ String clob = fetchURL(url);
Matcher m = progInfoPattern.matcher(clob);
if (m.find()) {
String progInfo = m.group();
String value = m2.group(2);
if (key.equals("bijzonderheden")) {
String[] list = value.split(",");
- for( String item: list) {
+ for (String item : list) {
if (item.toLowerCase().contains("teletekst")) {
result.addSubtitle("teletext");
} else if (item.toLowerCase().contains("breedbeeld")) {
if (m3.find()) {
result.setVideoQuality(m3.group());
} else {
- logger.warn(" Unknown value in 'bijzonderheden': " + item);
+ logger.warn(" Unknown value in 'bijzonderheden': "
+ + item);
}
}
}
kijkwijzer.add(m3.group(1));
}
if (!kijkwijzer.isEmpty()) {
- //logger.debug(" kijkwijzer: " + kijkwijzer);
+ // logger.debug(" kijkwijzer: " + kijkwijzer);
}
}
}
try {
List<Channel> channels = gids.getChannels();
System.out.println("Channels: " + channels);
- XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(new FileWriter("tvgids.xml"));
+ XMLStreamWriter writer = XMLOutputFactory.newInstance()
+ .createXMLStreamWriter(new FileWriter("tvgids.xml"));
writer.writeStartDocument();
writer.writeCharacters("\n");
writer.writeDTD("<!DOCTYPE tv SYSTEM \"xmltv.dtd\">");
writer.writeCharacters("\n");
writer.writeStartElement("tv");
- //List<Channel> my_channels = channels;
- List<Channel> my_channels = channels.subList(0,15);
- for(Channel c: my_channels) {c.serialize(writer);}
+ // List<Channel> my_channels = channels;
+ List<Channel> my_channels = channels.subList(0, 15);
+ for (Channel c : my_channels) {
+ c.serialize(writer);
+ }
writer.flush();
List<Programme> programmes = gids.getProgrammes(my_channels, 2);
- for(Programme p: programmes) {p.serialize(writer);}
+ for (Programme p : programmes) {
+ p.serialize(writer);
+ }
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();
if (!config.quiet) {
EPGSource.Stats stats = gids.getStats();
- System.out.println("Number of programmes from cache: " + stats.cacheHits);
- System.out.println("Number of programmes fetched: " + stats.cacheMisses);
- System.out.println("Number of fetch errors: " + stats.fetchErrors);
+ System.out.println("Number of programmes from cache: "
+ + stats.cacheHits);
+ System.out.println("Number of programmes fetched: "
+ + stats.cacheMisses);
+ System.out.println("Number of fetch errors: "
+ + stats.fetchErrors);
}
gids.close();
} catch (Exception e) {
public class RTLTest {
private static RTL rtl;
- private final static int RTL_SOURCE_ID=2;
+ private final static int RTL_SOURCE_ID = 2;
private static List<Channel> channels = null;
-
+
@BeforeClass
public static void setUp() throws Exception {
Config config = Config.getDefaultConfig();
@Test
public void testgetChannels() {
fetchChannels();
-
+
// there should be a least 20 channels
- assertTrue("There should be at least 20 channels from rtl.nl", channels.size()>=20);
+ assertTrue("There should be at least 20 channels from rtl.nl",
+ channels.size() >= 20);
// there should be an "RTL 4" channel
boolean foundRTL4 = false;
- for(Channel c: channels) {
- if(c.defaultName().equals("RTL 4")) {
+ for (Channel c : channels) {
+ if (c.defaultName().equals("RTL 4")) {
foundRTL4 = true;
- assertFalse("RTL 4 channel should have at least one icon", c.icons.isEmpty());
+ assertFalse("RTL 4 channel should have at least one icon",
+ c.icons.isEmpty());
}
- assertEquals("All channels should have RTL.nl source id", RTL_SOURCE_ID, c.source);
+ assertEquals("All channels should have RTL.nl source id",
+ RTL_SOURCE_ID, c.source);
}
- if(!foundRTL4) {
+ if (!foundRTL4) {
fail("Channel RTL4 not found, should be there");
}
}
private void fetchChannels() {
- if(channels==null) channels = rtl.getChannels();
+ if (channels == null)
+ channels = rtl.getChannels();
}
@Test
public void testFindGTSTRerun() throws Exception {
fetchChannels();
Channel rtl4 = null;
- for(Channel c: channels) {
- if(c.defaultName().equals("RTL 4")) {
+ for (Channel c : channels) {
+ if (c.defaultName().equals("RTL 4")) {
rtl4 = c;
}
}
assertNotNull("Should be able to find RTL 4 channel", rtl4);
-
+
List<Programme> today = rtl.getProgrammes(rtl4, 0);
- assertTrue("Expect at leat 10 programmes for a day", today.size()>=10);
-
+ assertTrue("Expect at leat 10 programmes for a day", today.size() >= 10);
+
Calendar now = Calendar.getInstance();
- if(now.get(Calendar.MONTH)<=Calendar.MAY || now.get(Calendar.MONTH)>=Calendar.SEPTEMBER) {
+ if (now.get(Calendar.MONTH) <= Calendar.MAY
+ || now.get(Calendar.MONTH) >= Calendar.SEPTEMBER) {
int offset;
- switch(now.get(Calendar.DAY_OF_WEEK)) {
- case Calendar.SATURDAY: offset = 2; break;
- case Calendar.SUNDAY: offset = 1; break;
- default: offset = 0;
+ switch (now.get(Calendar.DAY_OF_WEEK)) {
+ case Calendar.SATURDAY:
+ offset = 2;
+ break;
+ case Calendar.SUNDAY:
+ offset = 1;
+ break;
+ default:
+ offset = 0;
}
int rerun;
- switch(now.get(Calendar.DAY_OF_WEEK)) {
- case Calendar.FRIDAY: rerun = 3; break;
- case Calendar.SATURDAY: rerun = 2; break;
- default: rerun = 1;
+ switch (now.get(Calendar.DAY_OF_WEEK)) {
+ case Calendar.FRIDAY:
+ rerun = 3;
+ break;
+ case Calendar.SATURDAY:
+ rerun = 2;
+ break;
+ default:
+ rerun = 1;
}
- List<Programme> first = rtl.getProgrammes(rtl4, offset);
+ List<Programme> first = rtl.getProgrammes(rtl4, offset);
Programme gtstOriginal = null;
- for(Programme p: first) {
- if(p.getFirstTitle().matches("Goede Tijden.*")) {
- if (p.startTime.getHours()>=19) {
+ for (Programme p : first) {
+ if (p.getFirstTitle().matches("Goede Tijden.*")) {
+ if (p.startTime.getHours() >= 19) {
gtstOriginal = p;
break;
}
}
}
- assertNotNull("Should have a programme called Goede Tijden, Slechte Tijden after 19:00 on date with offset "+offset+ " for today", gtstOriginal);
- assertNotNull("GTST should have a description", gtstOriginal.descriptions);
- assertTrue("GTST should have at least one description", gtstOriginal.descriptions.size()>0);
- assertNotNull("GTST should have at least one non-empty description", gtstOriginal.descriptions.get(0).title);
- assertFalse("GTST should have at least one non-empty description", gtstOriginal.descriptions.get(0).title.isEmpty());
-
- assertNotNull("GTST should have kijkwijzer information", gtstOriginal.ratings);
- assertTrue("GTST should have at least two kijkwijzer ratings", gtstOriginal.ratings.size()>=2);
- assertNotNull("GTST rating should have kijkwijzer system", gtstOriginal.ratings.get(0).system);
- assertTrue("GTST rating should have kijkwijzer system filled in", gtstOriginal.ratings.get(0).system.matches(".*ijkwijz.*"));
- assertNotNull("GTST rating should have value", gtstOriginal.ratings.get(0).value);
- assertFalse("GTST rating should have value", gtstOriginal.ratings.get(0).value.isEmpty());
-
- List<Programme> reruns = rtl.getProgrammes(rtl4, rerun);
+ assertNotNull(
+ "Should have a programme called Goede Tijden, Slechte Tijden after 19:00 on date with offset "
+ + offset + " for today", gtstOriginal);
+ assertNotNull("GTST should have a description",
+ gtstOriginal.descriptions);
+ assertTrue("GTST should have at least one description",
+ gtstOriginal.descriptions.size() > 0);
+ assertNotNull(
+ "GTST should have at least one non-empty description",
+ gtstOriginal.descriptions.get(0).title);
+ assertFalse("GTST should have at least one non-empty description",
+ gtstOriginal.descriptions.get(0).title.isEmpty());
+
+ assertNotNull("GTST should have kijkwijzer information",
+ gtstOriginal.ratings);
+ assertTrue("GTST should have at least two kijkwijzer ratings",
+ gtstOriginal.ratings.size() >= 2);
+ assertNotNull("GTST rating should have kijkwijzer system",
+ gtstOriginal.ratings.get(0).system);
+ assertTrue("GTST rating should have kijkwijzer system filled in",
+ gtstOriginal.ratings.get(0).system.matches(".*ijkwijz.*"));
+ assertNotNull("GTST rating should have value",
+ gtstOriginal.ratings.get(0).value);
+ assertFalse("GTST rating should have value",
+ gtstOriginal.ratings.get(0).value.isEmpty());
+
+ List<Programme> reruns = rtl.getProgrammes(rtl4, rerun);
Programme gtstRerun = null;
- for(Programme p: reruns) {
- if(p.getFirstTitle().matches("Goede Tijden.*")) {
- if (p.startTime.getHours()<=15) {
+ for (Programme p : reruns) {
+ if (p.getFirstTitle().matches("Goede Tijden.*")) {
+ if (p.startTime.getHours() <= 15) {
gtstRerun = p;
break;
}
}
}
- assertNotNull("Should have a programme called Goede Tijden, Slechte Tijden before 15:00 on date with offset "+rerun, gtstRerun);
+ assertNotNull(
+ "Should have a programme called Goede Tijden, Slechte Tijden before 15:00 on date with offset "
+ + rerun, gtstRerun);
- assertEquals("GTST rerun should have the same description as the original", gtstRerun.descriptions.get(0).title, gtstOriginal.descriptions.get(0).title);
+ assertEquals(
+ "GTST rerun should have the same description as the original",
+ gtstRerun.descriptions.get(0).title,
+ gtstOriginal.descriptions.get(0).title);
}
}
}