-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkManager.java
More file actions
90 lines (78 loc) · 2.4 KB
/
NetworkManager.java
File metadata and controls
90 lines (78 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* NetworkManager.java
*
* @version:
* 1.0.1
*
* @revision:
* 1
*/
import java.io.*;
import java.net.*;
import java.util.Date;
/**
* The NetworkManager API takes care of all file/network operations as needed.
* It opens up a connection to the quotes file when instantiated and also provides
* a getNextQuote() method to return the next available quote to the
* caller in realtime.
*
* This is a singleton implementation of the FileManager since only
* one shared file instance is to be used across multiple clients.
*
* The file endpoint is hosted on github.com
*/
public class NetworkManager {
private BufferedReader bufferedReader;
private static final String ENDPOINT = "https://ishanguliani.github.io/";
private static NetworkManager instance = null;
/**
* The singleton helper. Lazily loads FileManager instance
* @return
*/
public static NetworkManager getInstance() {
if( instance == null) {
instance = new NetworkManager();
}
return instance;
}
/**
* Open the file for reading in the constructor
*/
public NetworkManager() {
// establish connection to the network endpoint
try {
URI mURI = new URI(ENDPOINT);
URL mURL = mURI.toURL();
// open connection
URLConnection connection = mURL.openConnection();
// get an input stream from the connection
this.bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
Log.network("Connection established to endpoint: " + mURL.toString());
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Return the next quote from the linked file
* @return
*/
public String getNextQuote() {
String inputLine = "";
try {
if( (inputLine = bufferedReader.readLine()) != null) {
// print the line
Log.network("Reading: " + inputLine);
}else {
inputLine = new Date().toString();
}
}catch(IOException ex) {
ex.printStackTrace();
}
Log.server("I read : " + inputLine);
return inputLine;
}
}