[LIB-5] Collection empty objects,reporting and serializable
[snooker-score-api.git] / src / main / java / org / hedgecode / snooker / request / AbstractRequester.java
1 /*
2  * Copyright (c) 2017. Developed by Hedgecode.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.hedgecode.snooker.request;
18
19 import java.io.BufferedReader;
20 import java.io.IOException;
21 import java.io.InputStreamReader;
22 import java.net.URL;
23 import java.net.URLConnection;
24 import java.nio.charset.Charset;
25 import java.nio.charset.StandardCharsets;
26
27 /**
28  * Abstract Data Requester from the portal api.snooker.org.
29  *
30  * @author Dmitry Samoshin aka gotty
31  */
32 public abstract class AbstractRequester implements Requester {
33
34     protected static final String API_SNOOKER_URL = "http://api.snooker.org/";
35     protected static final Charset API_SNOOKER_CHARSET = StandardCharsets.UTF_8;
36
37     protected abstract String getRequestUrl(int id) throws RequestException;
38
39     protected abstract String getRequestUrl(RequestParams params) throws RequestException;
40
41     @Override
42     public String request(int id) throws RequestException {
43         return _request(
44                 getRequestUrl(id)
45         );
46     }
47
48     @Override
49     public String request(RequestParams params) throws RequestException {
50         return _request(
51                 getRequestUrl(params)
52         );
53     }
54
55     private String _request(String requestUrl) throws RequestException {
56         StringBuilder result = new StringBuilder();
57         try {
58             URL url = new URL(requestUrl);
59             URLConnection urlConnection = url.openConnection();
60             BufferedReader br = new BufferedReader(
61                     new InputStreamReader(
62                             urlConnection.getInputStream(), API_SNOOKER_CHARSET
63                     )
64             );
65             String inputLine;
66             while ((inputLine = br.readLine()) != null) {
67                 result.append(inputLine);
68             }
69             br.close();
70         } catch (IOException e) {
71             throw new RequestException(requestUrl, e.getMessage());
72         }
73         return result.toString();
74     }
75
76     protected boolean isCorrectId(int id) {
77         return id > 0;
78     }
79
80 }