[LIB-2] Add snooker-score-api source files
[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
25 /**
26  * Abstract Data Requester from the portal api.snooker.org.
27  *
28  * @author Dmitry Samoshin aka gotty
29  */
30 public abstract class AbstractRequester implements Requester {
31
32     protected static final String API_SNOOKER_URL = "http://api.snooker.org/";
33
34     protected abstract String getRequestUrl(int id) throws RequestException;
35
36     protected abstract String getRequestUrl(RequestParams params) throws RequestException;
37
38     @Override
39     public String request(int id) throws RequestException {
40         return _request(
41                 getRequestUrl(id)
42         );
43     }
44
45     @Override
46     public String request(RequestParams params) throws RequestException {
47         return _request(
48                 getRequestUrl(params)
49         );
50     }
51
52     private String _request(String requestUrl) throws RequestException {
53         StringBuilder result = new StringBuilder();
54         try {
55             URL url = new URL(requestUrl);
56             URLConnection urlConnection = url.openConnection();
57             BufferedReader br = new BufferedReader(
58                     new InputStreamReader(
59                             urlConnection.getInputStream()
60                     )
61             );
62             String inputLine;
63             while ((inputLine = br.readLine()) != null) {
64                 result.append(inputLine);
65             }
66             br.close();
67         } catch (IOException e) {
68             throw new RequestException(requestUrl, e.getMessage());
69         }
70         return result.toString();
71     }
72
73     protected boolean isCorrectId(int id) {
74         return id > 0;
75     }
76
77 }