-
Notifications
You must be signed in to change notification settings - Fork 222
Expand file tree
/
Copy pathUserFactory.java
More file actions
64 lines (55 loc) · 1.83 KB
/
UserFactory.java
File metadata and controls
64 lines (55 loc) · 1.83 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
package scorekeep;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
public class UserFactory {
private final UserModel model = new UserModel();
public UserFactory(){
}
public User newUser() throws IOException {
String id = Identifiers.random();
User user = new User(id);
String name = randomName();
user.setName(name);
model.saveUser(user);
return user;
}
public User newUser(String name) throws IOException {
String id = Identifiers.random();
User user = new User(id);
user.setName(name);
model.saveUser(user);
return user;
}
public String randomName() throws IOException {
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://uinames.com/api/");
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
ObjectMapper mapper = new ObjectMapper();
Map<String, String> jsonMap = mapper.readValue(inputStream, Map.class);
String name = jsonMap.get("name");
EntityUtils.consume(entity);
Sns.sendNotification("Scorekeep user created", "Name: " + name);
return name;
} finally {
response.close();
}
}
public User getUser(String userId) throws UserNotFoundException {
return model.loadUser(userId);
}
public List<User> getUsers() {
return model.loadUsers();
}
}