Skip to content

Commit

Permalink
Some misc tidying up
Browse files Browse the repository at this point in the history
  • Loading branch information
lucko committed Dec 23, 2020
1 parent 5c44333 commit 8dfeef9
Show file tree
Hide file tree
Showing 28 changed files with 703 additions and 682 deletions.
Expand Up @@ -93,8 +93,8 @@ public boolean test(DataType dataType) {
};

private static final List<DataType> ALL_LIST = Collections.unmodifiableList(Arrays.asList(DataType.NORMAL, DataType.TRANSIENT));
private static final List<DataType> NORMAL_ONLY_LIST = Collections.unmodifiableList(Collections.singletonList(DataType.NORMAL));
private static final List<DataType> TRANSIENT_ONLY_LIST = Collections.unmodifiableList(Collections.singletonList(DataType.TRANSIENT));
private static final List<DataType> NORMAL_ONLY_LIST = Collections.singletonList(DataType.NORMAL);
private static final List<DataType> TRANSIENT_ONLY_LIST = Collections.singletonList(DataType.TRANSIENT);

/**
* Gets a {@link List} of all {@link DataType}s, filtered by the {@code predicate}.
Expand Down
Expand Up @@ -157,24 +157,20 @@ public void setUserMeta(String world, UUID uuid, String key, Object value) {
@Override
public String getGroupChatPrefix(String world, String name) {
Objects.requireNonNull(name, "name");
Group group = getGroup(name);
if (group == null) {
MetaCache metaData = getGroupMetaCache(name, world);
if (metaData == null) {
return null;
}
QueryOptions queryOptions = this.vaultPermission.getQueryOptions(null, world);
MetaCache metaData = group.getCachedData().getMetaData(queryOptions);
return Strings.nullToEmpty(metaData.getPrefix(MetaCheckEvent.Origin.THIRD_PARTY_API));
}

@Override
public String getGroupChatSuffix(String world, String name) {
Objects.requireNonNull(name, "name");
Group group = getGroup(name);
if (group == null) {
MetaCache metaData = getGroupMetaCache(name, world);
if (metaData == null) {
return null;
}
QueryOptions queryOptions = this.vaultPermission.getQueryOptions(null, world);
MetaCache metaData = group.getCachedData().getMetaData(queryOptions);
return Strings.nullToEmpty(metaData.getSuffix(MetaCheckEvent.Origin.THIRD_PARTY_API));
}

Expand Down Expand Up @@ -202,12 +198,10 @@ public void setGroupChatSuffix(String world, String name, String suffix) {
public String getGroupMeta(String world, String name, String key) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(key, "key");
Group group = getGroup(name);
if (group == null) {
MetaCache metaData = getGroupMetaCache(name, world);
if (metaData == null) {
return null;
}
QueryOptions queryOptions = this.vaultPermission.getQueryOptions(null, world);
MetaCache metaData = group.getCachedData().getMetaData(queryOptions);
return metaData.getMetaValue(key, MetaCheckEvent.Origin.THIRD_PARTY_API);
}

Expand All @@ -228,6 +222,15 @@ private Group getGroup(String name) {
return this.plugin.getGroupManager().getByDisplayName(name);
}

private MetaCache getGroupMetaCache(String name, String world) {
Group group = getGroup(name);
if (group == null) {
return null;
}
QueryOptions queryOptions = this.vaultPermission.getQueryOptions(null, world);
return group.getCachedData().getMetaData(queryOptions);
}

private void setChatMeta(PermissionHolder holder, ChatMetaType type, String value, String world) {
// remove all prefixes/suffixes directly set on the user/group
holder.removeIf(DataType.NORMAL, null, type.nodeType()::matches, false);
Expand Down
4 changes: 3 additions & 1 deletion common/build.gradle
@@ -1,5 +1,7 @@
test {
useJUnitPlatform()
useJUnitPlatform {
excludeTags 'dependency_checksum'
}
}

dependencies {
Expand Down
Expand Up @@ -100,7 +100,7 @@ public void dispatchFromApi(LoggedAction entry) {
try {
this.plugin.getStorage().logAction(entry).get();
} catch (Exception e) {
plugin.getLogger().warn("Error whilst storing action", e);
this.plugin.getLogger().warn("Error whilst storing action", e);
}
}

Expand Down
Expand Up @@ -37,7 +37,6 @@

import java.util.Objects;

@SuppressWarnings({"unchecked", "rawtypes"})
public class ApiPlayerAdapter<S, P extends S> implements PlayerAdapter<P> {
private final UserManager<?> userManager;
private final ContextManager<S, P> contextManager;
Expand Down
Expand Up @@ -263,7 +263,7 @@ protected void processOutput(JsonObject json) {
}

try {
String pasteId = this.plugin.getBytebin().postContent(bytesOut.toByteArray(), AbstractHttpClient.JSON_TYPE, false).key();
String pasteId = this.plugin.getBytebin().postContent(bytesOut.toByteArray(), AbstractHttpClient.JSON_TYPE).key();
this.log.getListeners().forEach(l -> Message.EXPORT_WEB_SUCCESS.send(l, pasteId, this.label));
} catch (UnsuccessfulRequestException e) {
this.log.getListeners().forEach(l -> Message.HTTP_REQUEST_FAILURE.send(l, e.getResponse().code(), e.getResponse().message()));
Expand Down
Expand Up @@ -124,7 +124,7 @@ private ConfigKeys() {}
*/
public static final ConfigKey<ContextSatisfyMode> CONTEXT_SATISFY_MODE = key(c -> {
String value = c.getString("context-satisfy-mode", "at-least-one-value-per-key");
if (value.toLowerCase().equals("all-values-per-key")) {
if (value.equalsIgnoreCase("all-values-per-key")) {
return ContextSatisfyMode.ALL_VALUES_PER_KEY;
}
return ContextSatisfyMode.AT_LEAST_ONE_VALUE_PER_KEY;
Expand Down Expand Up @@ -199,11 +199,11 @@ private ConfigKeys() {}
String option = PRIMARY_GROUP_CALCULATION_METHOD.get(c);
switch (option) {
case "stored":
return (Function<User, PrimaryGroupHolder>) PrimaryGroupHolder.Stored::new;
return PrimaryGroupHolder.Stored::new;
case "parents-by-weight":
return (Function<User, PrimaryGroupHolder>) PrimaryGroupHolder.ParentsByWeight::new;
return PrimaryGroupHolder.ParentsByWeight::new;
default:
return (Function<User, PrimaryGroupHolder>) PrimaryGroupHolder.AllParentsByWeight::new;
return PrimaryGroupHolder.AllParentsByWeight::new;
}
}));

Expand Down
Expand Up @@ -88,7 +88,7 @@ public boolean getBoolean(String path, boolean def) {
@Override
public List<String> getStringList(String path, List<String> def) {
ConfigurationNode node = resolvePath(path);
if (node.isVirtual() || !node.hasListChildren()) {
if (node.isVirtual() || !node.isList()) {
return def;
}

Expand All @@ -98,7 +98,7 @@ public List<String> getStringList(String path, List<String> def) {
@Override
public List<String> getKeys(String path, List<String> def) {
ConfigurationNode node = resolvePath(path);
if (node.isVirtual() || !node.hasMapChildren()) {
if (node.isVirtual() || !node.isMap()) {
return def;
}

Expand Down
Expand Up @@ -34,7 +34,6 @@
import net.luckperms.api.context.MutableContextSet;

import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.SimpleConfigurationNode;

import java.util.ArrayList;
import java.util.List;
Expand All @@ -45,7 +44,7 @@ public final class ContextSetConfigurateSerializer {
private ContextSetConfigurateSerializer() {}

public static ConfigurationNode serializeContextSet(ContextSet contextSet) {
ConfigurationNode data = SimpleConfigurationNode.root();
ConfigurationNode data = ConfigurationNode.root();
Map<String, Set<String>> map = contextSet.toMap();

for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
Expand All @@ -63,7 +62,7 @@ public static ConfigurationNode serializeContextSet(ContextSet contextSet) {
}

public static ContextSet deserializeContextSet(ConfigurationNode data) {
Preconditions.checkArgument(data.hasMapChildren());
Preconditions.checkArgument(data.isMap());
Map<Object, ? extends ConfigurationNode> dataMap = data.getChildrenMap();

if (dataMap.isEmpty()) {
Expand All @@ -75,9 +74,8 @@ public static ContextSet deserializeContextSet(ConfigurationNode data) {
String k = e.getKey().toString();
ConfigurationNode v = e.getValue();

if (v.hasListChildren()) {
List<? extends ConfigurationNode> values = v.getChildrenList();
for (ConfigurationNode value : values) {
if (v.isList()) {
for (ConfigurationNode value : v.getChildrenList()) {
map.add(k, value.getString());
}
} else {
Expand Down
Expand Up @@ -340,37 +340,4 @@ public static MessageDigest createDigest() {
}
}

/*
public static void main(String[] args) {
Dependency[] dependencies = values();
DependencyRepository[] repos = DependencyRepository.values();
java.util.concurrent.ExecutorService pool = java.util.concurrent.Executors.newCachedThreadPool();
for (Dependency dependency : dependencies) {
for (DependencyRepository repo : repos) {
pool.submit(() -> {
try {
byte[] hash = createDigest().digest(repo.downloadRaw(dependency));
if (!dependency.checksumMatches(hash)) {
System.out.println("NO MATCH - " + repo.name() + " - " + dependency.name() + ": " + Base64.getEncoder().encodeToString(hash));
} else {
System.out.println("OK - " + repo.name() + " - " + dependency.name());
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
pool.shutdown();
try {
pool.awaitTermination(1, java.util.concurrent.TimeUnit.HOURS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
*/

}
Expand Up @@ -83,64 +83,25 @@ public Response makeHttpRequest(Request request) throws IOException, Unsuccessfu
*
* @param buf the compressed content
* @param contentType the type of the content
* @param allowModification if the paste should be modifiable
* @return the key of the resultant content
* @throws IOException if an error occurs
*/
public Content postContent(byte[] buf, MediaType contentType, boolean allowModification) throws IOException, UnsuccessfulRequestException {
public Content postContent(byte[] buf, MediaType contentType) throws IOException, UnsuccessfulRequestException {
RequestBody body = RequestBody.create(contentType, buf);

Request.Builder requestBuilder = new Request.Builder()
.url(this.url + "post")
.header("User-Agent", this.userAgent)
.header("Content-Encoding", "gzip");

if (allowModification) {
requestBuilder.header("Allow-Modification", "true");
}

Request request = requestBuilder.post(body).build();
try (Response response = makeHttpRequest(request)) {
String key = response.header("Location");
if (key == null) {
throw new IllegalStateException("Key not returned");
}

if (allowModification) {
String modificationKey = response.header("Modification-Key");
if (modificationKey == null) {
throw new IllegalStateException("Modification key not returned");
}
return new Content(key, modificationKey);
} else {
return new Content(key);
}
}
}

/**
* PUTs modified GZIP compressed content to bytebin in place of existing content.
*
* @param existingContent the existing content
* @param buf the compressed content to put
* @param contentType the type of the content
* @throws IOException if an error occurs
*/
public void modifyContent(Content existingContent, byte[] buf, MediaType contentType) throws IOException, UnsuccessfulRequestException {
if (!existingContent.modifiable) {
throw new IllegalArgumentException("Existing content is not modifiable");
return new Content(key);
}

RequestBody body = RequestBody.create(contentType, buf);

Request.Builder requestBuilder = new Request.Builder()
.url(this.url + existingContent.key())
.header("User-Agent", this.userAgent)
.header("Content-Encoding", "gzip")
.header("Modification-Key", existingContent.modificationKey);

Request request = requestBuilder.put(body).build();
makeHttpRequest(request).close();
}

/**
Expand Down Expand Up @@ -173,19 +134,9 @@ public JsonElement getJsonContent(String id) throws IOException, UnsuccessfulReq

public static final class Content {
private final String key;
private final boolean modifiable;
private final String modificationKey;

Content(String key) {
this.key = key;
this.modifiable = false;
this.modificationKey = null;
}

Content(String key, String modificationKey) {
this.key = key;
this.modifiable = true;
this.modificationKey = modificationKey;
}

public String key() {
Expand Down
Expand Up @@ -320,10 +320,5 @@ public int read(byte[] b, int off, int len) throws IOException {
}
return res;
}

@Override
public void close() throws IOException {
super.close();
}
}
}
Expand Up @@ -64,7 +64,7 @@ public void init(String address, String password, boolean ssl) {
this.jedisPool = new JedisPool(new JedisPoolConfig(), host, port, Protocol.DEFAULT_TIMEOUT, password, ssl);

this.sub = new Subscription(this);
this.plugin.getBootstrap().getScheduler().executeAsync(sub);
this.plugin.getBootstrap().getScheduler().executeAsync(this.sub);
}

@Override
Expand Down Expand Up @@ -95,13 +95,13 @@ public void run() {
while (!Thread.interrupted() && !this.parent.jedisPool.isClosed()) {
try (Jedis jedis = this.parent.jedisPool.getResource()) {
if (wasBroken) {
parent.plugin.getLogger().info("Redis pubsub connection re-established");
this.parent.plugin.getLogger().info("Redis pubsub connection re-established");
wasBroken = false;
}
jedis.subscribe(this, CHANNEL);
} catch (Exception e) {
wasBroken = true;
parent.plugin.getLogger().warn("Redis pubsub connection dropped, trying to re-open the connection: " + e.getMessage());
this.parent.plugin.getLogger().warn("Redis pubsub connection dropped, trying to re-open the connection: " + e.getMessage());
try {
unsubscribe();
} catch (Exception ignored) {
Expand Down

0 comments on commit 8dfeef9

Please sign in to comment.