blob: 57788472259e5c055be62e697dbc729d97a66509 (
plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
package it.niedermann.owncloud.notes.shared.util;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
import java.util.stream.Collectors;
import it.niedermann.owncloud.notes.shared.model.ApiVersion;
public class ApiVersionUtil {
private ApiVersionUtil() {
throw new UnsupportedOperationException("Do not instantiate this util class.");
}
/**
* @return a {@link Collection} of all valid {@link ApiVersion}s which have been found in {@param raw}.
*/
@NonNull
public static Collection<ApiVersion> parse(@Nullable String raw) {
if (TextUtils.isEmpty(raw)) {
return Collections.emptyList();
}
JSONArray a;
try {
a = new JSONArray(raw);
} catch (JSONException e) {
try {
a = new JSONArray("[" + raw + "]");
} catch (JSONException e1) {
return Collections.emptyList();
}
}
final Collection<ApiVersion> result = new ArrayList<>();
for (int i = 0; i < a.length(); i++) {
try {
final ApiVersion version = ApiVersion.of(a.getString(i));
if (version.getMajor() != 0 || version.getMinor() != 0) {
result.add(version);
}
} catch (Exception ignored) {
}
}
return result;
}
/**
* @return a serialized {@link String} of the given {@param apiVersions} or <code>null</code>.
*/
@Nullable
public static String serialize(@Nullable Collection<ApiVersion> apiVersions) {
if (apiVersions == null || apiVersions.isEmpty()) {
return null;
}
return "[" +
apiVersions
.stream()
.filter(Objects::nonNull)
.map(v -> v.getMajor() + "." + v.getMinor())
.collect(Collectors.joining(","))
+ "]";
}
@Nullable
public static String sanitize(@Nullable String raw) {
return serialize(parse(raw));
}
/**
* @return the highest {@link ApiVersion} that is supported by the server according to {@param raw},
* whose major version is also supported by this app (see {@link ApiVersion#SUPPORTED_API_VERSIONS}).
* Returns <code>null</code> if no better version could be found.
*/
@Nullable
public static ApiVersion getPreferredApiVersion(@Nullable String raw) {
return parse(raw)
.stream()
.filter(version -> Arrays.asList(ApiVersion.SUPPORTED_API_VERSIONS).contains(version))
.max((o1, o2) -> {
if (o2.getMajor() > o1.getMajor()) {
return -1;
} else if (o2.getMajor() < o1.getMajor()) {
return 1;
} else if (o2.getMinor() > o1.getMinor()) {
return -1;
} else if (o2.getMinor() < o1.getMinor()) {
return 1;
}
return 0;
})
.orElse(null);
}
}
|