/* * Copyright (c) 2017. Developed by Hedgecode. * * 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 org.hedgecode.snooker.request; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; /** * Abstract Data Requester from the portal api.snooker.org. * * @author Dmitry Samoshin aka gotty */ public abstract class AbstractRequester implements Requester { protected static final String API_SNOOKER_URL = "http://api.snooker.org/"; protected static final Charset API_SNOOKER_CHARSET = StandardCharsets.UTF_8; protected abstract String getRequestUrl(int id) throws RequestException; protected abstract String getRequestUrl(RequestParams params) throws RequestException; @Override public String request(int id) throws RequestException { return _request( getRequestUrl(id) ); } @Override public String request(RequestParams params) throws RequestException { return _request( getRequestUrl(params) ); } private String _request(String requestUrl) throws RequestException { StringBuilder result = new StringBuilder(); try { URL url = new URL(requestUrl); URLConnection urlConnection = url.openConnection(); BufferedReader br = new BufferedReader( new InputStreamReader( urlConnection.getInputStream(), API_SNOOKER_CHARSET ) ); String inputLine; while ((inputLine = br.readLine()) != null) { result.append(inputLine); } br.close(); } catch (IOException e) { throw new RequestException(requestUrl, e.getMessage()); } return result.toString(); } protected boolean isCorrectId(int id) { return id > 0; } }