AbstractRestViewV1.java
2.04 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
package fi.codecrew.moya.rest.meta.v1;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonValue;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import fi.codecrew.moya.model.EntityMeta;
import fi.codecrew.moya.utilities.JsonUtils;
public abstract class AbstractRestViewV1 {
/**
* Convert List<PathSegment> to List<String>
*
* @param path
* List<PathSegment>
* @return List<String>
*/
public List<String> pathToStrings(List<PathSegment> path) {
ArrayList<String> stringList = new ArrayList<String>(path.size());
for (PathSegment s : path) {
String segmentString = s.getPath();
if (segmentString != null && !segmentString.isEmpty()) {
stringList.add(segmentString);
}
}
return stringList;
}
public JsonObject parseJson(String jsonString) {
JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
JsonObject newData = jsonReader.readObject();
return newData;
}
protected void setEntityMeta(EntityMeta entity, List<PathSegment> keys, String jsonString) {
if (entity == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
JsonObject meta = entity.getMeta();
if (meta == null) {
meta = Json.createObjectBuilder().build();
}
JsonObject alteredMeta = JsonUtils.alterSubObject(meta, pathToStrings(keys), parseJson(jsonString));
if (alteredMeta != null) {
entity.setMeta(alteredMeta);
}
}
protected String getEntityMeta(EntityMeta entity, List<PathSegment> keys) {
if (entity == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
JsonObject meta = entity.getMeta();
if (meta == null) {
meta = Json.createObjectBuilder().build();
}
JsonValue subValue = JsonUtils.getSubObject(meta, pathToStrings(keys));
if (subValue == null) {
subValue = Json.createObjectBuilder().build();
}
return subValue.toString() + "\n";
}
}