Java tutorial
/** * Copyright 2016 Philipp Arndt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.rnd7.libtvdb; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLEncoder; import java.text.ParseException; import java.util.List; import com.google.common.collect.Iterables; import de.rnd7.libtvdb.api.TVDBException; import de.rnd7.libtvdb.api.TVShow; import de.rnd7.libtvdb.bridge.ModelTransformator; import de.rnd7.libtvdb.bridge.zip.SeriesZipTransformator; import de.rnd7.libtvdb.xml.data.Data; import de.rnd7.urlcache.CachedElement; import de.rnd7.urlcache.URLCache; import de.rnd7.urlcache.URLCacheKey; public class TVDBAccessor { public static final String API_URL = "http://www.thetvdb.com/api"; private final String apiKey; private final String language; private final URLCache cache; public TVDBAccessor(final String apiKey, final String language, final URLCache cache) { this.apiKey = apiKey; this.language = language; this.cache = cache; } /** * * @param showID * (e.g. 72108 for NCIS) * @return * @throws IOException * @throws ParseException */ public TVShow getShow(final int showID) throws TVDBException { try { final URL url = new URL(String.format(TVDBAccessor.API_URL + "/%s/series/%d/all/%s.zip", this.apiKey, showID, this.language)); final CachedElement element = this.cache.get(URLCacheKey.of(url)); try (InputStream inputStream = element.openStream()) { final InputStream xmlStream = SeriesZipTransformator.toSeriesFile(inputStream, this.language); final Data data = ModelTransformator.parse(xmlStream); final List<TVShow> shows = ModelTransformator.toLibModel(data); return Iterables.getOnlyElement(shows); } } catch (final Exception e) { throw new TVDBException(e); } } public List<TVShow> findShows(final String showName) throws TVDBException { try { final String encoded = URLEncoder.encode(showName, "utf-8"); final URL url = new URL(String.format(API_URL + "/GetSeries.php?seriesname=%s", encoded)); try (InputStream inputStream = url.openStream()) { final Data data = ModelTransformator.parse(inputStream); return ModelTransformator.toLibModel(data); } } catch (final Exception e) { throw new TVDBException(e); } } }