added files.
This commit is contained in:
commit
c02e6e5596
430 files changed
+42104
No files matched your search
@@ -0,0 +1,9 @@
|
|||||||
|
.gradle/
|
||||||
|
build/
|
||||||
|
out/
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
.classpath
|
||||||
|
.project
|
||||||
|
.settings/
|
||||||
|
*.log
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
<p align="center">
|
||||||
|
<img src="assets/ss.png" alt="Skid Solutions Banner" width="350" />
|
||||||
|
<br>
|
||||||
|
<sub>all credits to SugarMountainfloor Aka. Showman</sub>
|
||||||
|
<br><br>
|
||||||
|
<a href="https://discord.gg/skidsolutions">
|
||||||
|
<img src="https://img.shields.io/badge/Discord-Skid%20Solutions-18181b?style=for-the-badge&logo=discord&logoColor=ffffff&labelColor=09090b" alt="Discord" />
|
||||||
|
</a>
|
||||||
|
<img src="https://img.shields.io/badge/Version-10.10--2--56528ba-27272a?style=for-the-badge&labelColor=09090b" alt="Version 10.10-2-56528ba" />
|
||||||
|
<img src="https://img.shields.io/badge/Java-8-3f3f46?style=for-the-badge&logo=openjdk&logoColor=ffffff&labelColor=09090b" alt="Java 8" />
|
||||||
|
<img src="https://img.shields.io/badge/Gradle-8.14.3-52525b?style=for-the-badge&logo=gradle&logoColor=ffffff&labelColor=09090b" alt="Gradle 8.14.3" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://discord.gg/skidsolutions">https://discord.gg/skidsolutions</a>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="assets/divider.svg" alt="" width="720" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="assets/jak.jpg" alt="jak" height="150" />
|
||||||
|
<img src="assets/hack.jpg" alt="hack" height="150" />
|
||||||
|
<img src="assets/deobf2.png" alt="deobf2" height="150" />
|
||||||
|
<img src="assets/deobf.jpg" alt="deobf" height="150" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="assets/divider.svg" alt="" width="720" />
|
||||||
|
</p>
|
||||||
|
|
||||||
|
## How to build
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
- **Java Development Kit**: JDK 8 (compile toolchain) and JDK 17 (Gradle 8.14.3 launcher; newer JDKs such as JDK 25 are not supported by Gradle 8.14.3)
|
||||||
|
|
||||||
|
### Building OpenReflex
|
||||||
|
|
||||||
|
Run from this folder:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$env:JAVA_HOME = "C:\Program Files\Java\jdk-17"
|
||||||
|
|
||||||
|
.\gradlew.bat prepareIde
|
||||||
|
.\gradlew.bat clean build
|
||||||
|
```
|
||||||
|
|
||||||
|
Generated `build/libs/`:
|
||||||
|
- `OpenReflex-10.10-2-56528ba.jar`
|
||||||
|
- `OpenReflex-10.10-2-56528ba-sources.jar`
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
Copy `build\libs\OpenReflex-10.10-2-56528ba.jar` into your Spigot or Paper server's `plugins/` folder (Minecraft 1.8 to 1.13). Requires ProtocolLib; ViaVersion and PlaceholderAPI are optional.
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 76 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 135 KiB |
@@ -0,0 +1,26 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 820 20" width="820" height="20" role="img" aria-hidden="true">
|
||||||
|
<defs>
|
||||||
|
<linearGradient id="baseLine" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#000000" stop-opacity="0" />
|
||||||
|
<stop offset="25%" stop-color="#404040" stop-opacity="0.7" />
|
||||||
|
<stop offset="50%" stop-color="#d4d4d4" stop-opacity="0.95" />
|
||||||
|
<stop offset="75%" stop-color="#404040" stop-opacity="0.7" />
|
||||||
|
<stop offset="100%" stop-color="#000000" stop-opacity="0" />
|
||||||
|
</linearGradient>
|
||||||
|
<linearGradient id="pulse" x1="0%" y1="0%" x2="100%" y2="0%">
|
||||||
|
<stop offset="0%" stop-color="#ffffff" stop-opacity="0" />
|
||||||
|
<stop offset="50%" stop-color="#ffffff" stop-opacity="1" />
|
||||||
|
<stop offset="100%" stop-color="#ffffff" stop-opacity="0" />
|
||||||
|
</linearGradient>
|
||||||
|
<clipPath id="lineClip">
|
||||||
|
<rect x="40" y="8" width="740" height="4" rx="2" />
|
||||||
|
</clipPath>
|
||||||
|
</defs>
|
||||||
|
|
||||||
|
<rect x="40" y="9.25" width="740" height="1.5" rx="0.75" fill="url(#baseLine)" />
|
||||||
|
<g clip-path="url(#lineClip)">
|
||||||
|
<rect x="-120" y="8.5" width="140" height="3" rx="1.5" fill="url(#pulse)">
|
||||||
|
<animate attributeName="x" values="-120;820" dur="3.4s" repeatCount="indefinite" />
|
||||||
|
</rect>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1.2 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.0 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.3 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 323 KiB |
+116
@@ -0,0 +1,116 @@
|
|||||||
|
plugins {
|
||||||
|
id 'java'
|
||||||
|
id 'idea'
|
||||||
|
id 'eclipse'
|
||||||
|
}
|
||||||
|
|
||||||
|
group = 'rip.reflex'
|
||||||
|
version = '10.10-2-56528ba'
|
||||||
|
|
||||||
|
def javaVersion = 8
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
maven { url = uri('https://hub.spigotmc.org/nexus/content/repositories/snapshots/') }
|
||||||
|
maven { url = uri('https://repo.dmulloy2.net/repository/public/') }
|
||||||
|
maven { url = uri('https://repo.extendedclip.com/content/repositories/placeholderapi/') }
|
||||||
|
}
|
||||||
|
|
||||||
|
configurations {
|
||||||
|
apiGenerator
|
||||||
|
}
|
||||||
|
|
||||||
|
def generatorClasses = layout.buildDirectory.dir('api-generator/classes')
|
||||||
|
tasks.register('compileApiGenerator', JavaCompile) {
|
||||||
|
source = files('gradle/GenerateCompileApis.java')
|
||||||
|
classpath = configurations.apiGenerator
|
||||||
|
destinationDirectory = generatorClasses
|
||||||
|
javaCompiler = javaToolchains.compilerFor { languageVersion = JavaLanguageVersion.of(javaVersion) }
|
||||||
|
options.encoding = 'UTF-8'
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.register('generateCompileApis', JavaExec) {
|
||||||
|
group = 'build setup'
|
||||||
|
description = 'Generates compile-only API headers from text declarations.'
|
||||||
|
dependsOn tasks.named('compileApiGenerator')
|
||||||
|
inputs.dir('gradle/api-signatures')
|
||||||
|
outputs.dir(layout.buildDirectory.dir('compile-apis'))
|
||||||
|
classpath = files(generatorClasses) + configurations.apiGenerator
|
||||||
|
javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(javaVersion) }
|
||||||
|
mainClass = 'GenerateCompileApis'
|
||||||
|
args file('gradle/api-signatures').absolutePath, layout.buildDirectory.dir('compile-apis').get().asFile.absolutePath
|
||||||
|
}
|
||||||
|
|
||||||
|
def compileApi = { String name ->
|
||||||
|
files(layout.buildDirectory.file("compile-apis/${name}.jar")).builtBy(tasks.named('generateCompileApis'))
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.register('prepareIde') {
|
||||||
|
group = 'ide'
|
||||||
|
description = 'Generates the compile-only API headers used by the IDE import.'
|
||||||
|
dependsOn tasks.named('generateCompileApis')
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
toolchain {
|
||||||
|
languageVersion = JavaLanguageVersion.of(javaVersion)
|
||||||
|
}
|
||||||
|
withSourcesJar()
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
apiGenerator 'org.ow2.asm:asm:9.8'
|
||||||
|
apiGenerator 'com.google.code.gson:gson:2.10.1'
|
||||||
|
|
||||||
|
compileOnly compileApi('reflex')
|
||||||
|
compileOnly('org.spigotmc:spigot-api:1.13.2-R0.1-SNAPSHOT') {
|
||||||
|
exclude group: 'net.md-5', module: 'bungeecord-chat'
|
||||||
|
}
|
||||||
|
compileOnly 'net.md-5:bungeecord-chat:1.16-R0.4'
|
||||||
|
compileOnly 'com.comphenix.protocol:ProtocolLib:4.4.0'
|
||||||
|
compileOnly 'me.clip:placeholderapi:2.11.6'
|
||||||
|
compileOnly 'org.mongodb:mongo-java-driver:3.12.14'
|
||||||
|
compileOnly 'com.google.guava:guava:21.0'
|
||||||
|
compileOnly 'com.google.code.gson:gson:2.8.9'
|
||||||
|
compileOnly 'commons-codec:commons-codec:1.11'
|
||||||
|
compileOnly 'commons-io:commons-io:2.4'
|
||||||
|
compileOnly 'commons-lang:commons-lang:2.6'
|
||||||
|
compileOnly 'org.apache.httpcomponents:httpcore:4.4.16'
|
||||||
|
compileOnly 'org.bouncycastle:bcprov-jdk18on:1.78.1'
|
||||||
|
compileOnly 'com.googlecode.json-simple:json-simple:1.1.1'
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType(JavaCompile).configureEach {
|
||||||
|
if (name != 'compileApiGenerator') {
|
||||||
|
dependsOn tasks.named('generateCompileApis')
|
||||||
|
}
|
||||||
|
options.encoding = 'UTF-8'
|
||||||
|
options.compilerArgs += ['-Xlint:none', '-Xmaxerrs', '1000']
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType(AbstractArchiveTask).configureEach {
|
||||||
|
preserveFileTimestamps = false
|
||||||
|
reproducibleFileOrder = true
|
||||||
|
}
|
||||||
|
|
||||||
|
jar {
|
||||||
|
manifest {
|
||||||
|
attributes(
|
||||||
|
'Implementation-Title': 'OpenReflex',
|
||||||
|
'Implementation-Version': project.version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
idea {
|
||||||
|
module {
|
||||||
|
downloadSources = true
|
||||||
|
downloadJavadoc = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
eclipse {
|
||||||
|
classpath {
|
||||||
|
downloadSources = true
|
||||||
|
downloadJavadoc = true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
|
||||||
|
org.gradle.parallel=true
|
||||||
|
org.gradle.caching=true
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
import com.google.gson.JsonArray;
|
||||||
|
import com.google.gson.JsonElement;
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import org.objectweb.asm.AnnotationVisitor;
|
||||||
|
import org.objectweb.asm.ClassWriter;
|
||||||
|
import org.objectweb.asm.FieldVisitor;
|
||||||
|
import org.objectweb.asm.MethodVisitor;
|
||||||
|
import org.objectweb.asm.Opcodes;
|
||||||
|
import org.objectweb.asm.Type;
|
||||||
|
import org.objectweb.asm.TypePath;
|
||||||
|
|
||||||
|
import java.io.Reader;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.SortedMap;
|
||||||
|
import java.util.TreeMap;
|
||||||
|
import java.util.jar.JarEntry;
|
||||||
|
import java.util.jar.JarOutputStream;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
import java.util.stream.Stream;
|
||||||
|
|
||||||
|
public final class GenerateCompileApis implements Opcodes {
|
||||||
|
private interface Factory {
|
||||||
|
AnnotationVisitor create(JsonObject annotation);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String text(JsonObject obj, String key) {
|
||||||
|
return obj.has(key) && !obj.get(key).isJsonNull() ? obj.get(key).getAsString() : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int number(JsonObject obj, String key) {
|
||||||
|
return obj.get(key).getAsInt();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static JsonArray array(JsonObject obj, String key) {
|
||||||
|
return obj.has(key) ? obj.getAsJsonArray(key) : new JsonArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String[] strings(JsonObject obj, String key) {
|
||||||
|
List<String> list = new ArrayList<>();
|
||||||
|
for (JsonElement el : array(obj, key)) {
|
||||||
|
list.add(el.getAsString());
|
||||||
|
}
|
||||||
|
return list.toArray(new String[0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object scalar(JsonObject obj) {
|
||||||
|
String value = text(obj, "value");
|
||||||
|
String type = text(obj, "type");
|
||||||
|
if ("Long".equals(type)) return Long.valueOf(value);
|
||||||
|
if ("Integer".equals(type)) return Integer.valueOf(value);
|
||||||
|
if ("Float".equals(type)) return Float.valueOf(value);
|
||||||
|
if ("Double".equals(type)) return Double.valueOf(value);
|
||||||
|
if ("Byte".equals(type)) return Byte.valueOf(value);
|
||||||
|
if ("Short".equals(type)) return Short.valueOf(value);
|
||||||
|
if ("Character".equals(type)) return value.charAt(0);
|
||||||
|
throw new IllegalArgumentException(obj.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object constant(JsonElement el) {
|
||||||
|
if (el == null || el.isJsonNull()) return null;
|
||||||
|
if (el.isJsonObject()) return scalar(el.getAsJsonObject());
|
||||||
|
return el.getAsString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void annotationValue(AnnotationVisitor visitor, String name, JsonElement value) {
|
||||||
|
if (value.isJsonArray()) {
|
||||||
|
AnnotationVisitor nested = visitor.visitArray(name);
|
||||||
|
for (JsonElement el : value.getAsJsonArray()) {
|
||||||
|
annotationValue(nested, null, el);
|
||||||
|
}
|
||||||
|
nested.visitEnd();
|
||||||
|
} else if (value.isJsonObject()) {
|
||||||
|
JsonObject obj = value.getAsJsonObject();
|
||||||
|
String kind = text(obj, "kind");
|
||||||
|
if ("scalar".equals(kind)) {
|
||||||
|
visitor.visit(name, scalar(obj));
|
||||||
|
} else if ("type".equals(kind)) {
|
||||||
|
visitor.visit(name, Type.getType(text(obj, "descriptor")));
|
||||||
|
} else if ("enum".equals(kind)) {
|
||||||
|
visitor.visitEnum(name, text(obj, "descriptor"), text(obj, "name"));
|
||||||
|
} else if ("annotation".equals(kind)) {
|
||||||
|
JsonObject ann = obj.getAsJsonObject("annotation");
|
||||||
|
writeAnnotation(visitor.visitAnnotation(name, text(ann, "descriptor")), ann);
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException(obj.toString());
|
||||||
|
}
|
||||||
|
} else if (value.getAsJsonPrimitive().isBoolean()) {
|
||||||
|
visitor.visit(name, value.getAsBoolean());
|
||||||
|
} else {
|
||||||
|
visitor.visit(name, value.getAsString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void writeAnnotation(AnnotationVisitor visitor, JsonObject annotation) {
|
||||||
|
if (visitor == null) return;
|
||||||
|
for (Map.Entry<String, JsonElement> entry : annotation.getAsJsonObject("values").entrySet()) {
|
||||||
|
annotationValue(visitor, entry.getKey(), entry.getValue());
|
||||||
|
}
|
||||||
|
visitor.visitEnd();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void annotations(JsonObject obj, String key, Factory factory) {
|
||||||
|
for (JsonElement el : array(obj, key)) {
|
||||||
|
JsonObject ann = el.getAsJsonObject();
|
||||||
|
writeAnnotation(factory.create(ann), ann);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] compile(JsonObject cls) {
|
||||||
|
ClassWriter cw = new ClassWriter(0);
|
||||||
|
cw.visit(
|
||||||
|
number(cls, "version"),
|
||||||
|
number(cls, "access"),
|
||||||
|
text(cls, "name"),
|
||||||
|
text(cls, "signature"),
|
||||||
|
text(cls, "superName"),
|
||||||
|
strings(cls, "interfaces")
|
||||||
|
);
|
||||||
|
if (cls.has("outerClass")) {
|
||||||
|
cw.visitOuterClass(text(cls, "outerClass"), text(cls, "outerMethod"), text(cls, "outerMethodDescriptor"));
|
||||||
|
}
|
||||||
|
annotations(cls, "annotations", a -> cw.visitAnnotation(text(a, "descriptor"), a.get("visible").getAsBoolean()));
|
||||||
|
annotations(cls, "typeAnnotations", a -> cw.visitTypeAnnotation(
|
||||||
|
number(a, "typeRef"), TypePath.fromString(text(a, "typePath")), text(a, "descriptor"), a.get("visible").getAsBoolean()));
|
||||||
|
for (JsonElement el : array(cls, "innerClasses")) {
|
||||||
|
JsonObject inner = el.getAsJsonObject();
|
||||||
|
cw.visitInnerClass(text(inner, "name"), text(inner, "outerName"), text(inner, "innerName"), number(inner, "access"));
|
||||||
|
}
|
||||||
|
for (JsonElement el : array(cls, "fields")) {
|
||||||
|
JsonObject f = el.getAsJsonObject();
|
||||||
|
FieldVisitor fv = cw.visitField(
|
||||||
|
number(f, "access"),
|
||||||
|
text(f, "name"),
|
||||||
|
text(f, "descriptor"),
|
||||||
|
text(f, "signature"),
|
||||||
|
constant(f.get("constant"))
|
||||||
|
);
|
||||||
|
annotations(f, "annotations", a -> fv.visitAnnotation(text(a, "descriptor"), a.get("visible").getAsBoolean()));
|
||||||
|
fv.visitEnd();
|
||||||
|
}
|
||||||
|
for (JsonElement el : array(cls, "methods")) {
|
||||||
|
JsonObject m = el.getAsJsonObject();
|
||||||
|
int access = number(m, "access");
|
||||||
|
String descriptor = text(m, "descriptor");
|
||||||
|
MethodVisitor mv = cw.visitMethod(access, text(m, "name"), descriptor, text(m, "signature"), strings(m, "exceptions"));
|
||||||
|
for (JsonElement pe : array(m, "parameters")) {
|
||||||
|
JsonObject p = pe.getAsJsonObject();
|
||||||
|
mv.visitParameter(text(p, "name"), number(p, "access"));
|
||||||
|
}
|
||||||
|
annotations(m, "annotations", a -> mv.visitAnnotation(text(a, "descriptor"), a.get("visible").getAsBoolean()));
|
||||||
|
if (m.has("annotationDefault")) {
|
||||||
|
AnnotationVisitor av = mv.visitAnnotationDefault();
|
||||||
|
annotationValue(av, null, m.get("annotationDefault"));
|
||||||
|
av.visitEnd();
|
||||||
|
}
|
||||||
|
if ((access & (ACC_ABSTRACT | ACC_NATIVE)) == 0) {
|
||||||
|
mv.visitCode();
|
||||||
|
mv.visitTypeInsn(NEW, "java/lang/UnsupportedOperationException");
|
||||||
|
mv.visitInsn(DUP);
|
||||||
|
mv.visitLdcInsn("Compile-only API header; use the real server or library at runtime");
|
||||||
|
mv.visitMethodInsn(INVOKESPECIAL, "java/lang/UnsupportedOperationException", "<init>", "(Ljava/lang/String;)V", false);
|
||||||
|
mv.visitInsn(ATHROW);
|
||||||
|
int locals = (access & ACC_STATIC) == 0 ? 1 : 0;
|
||||||
|
for (Type t : Type.getArgumentTypes(descriptor)) {
|
||||||
|
locals += t.getSize();
|
||||||
|
}
|
||||||
|
mv.visitMaxs(3, locals);
|
||||||
|
}
|
||||||
|
mv.visitEnd();
|
||||||
|
}
|
||||||
|
cw.visitEnd();
|
||||||
|
return cw.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SortedMap<String, JsonObject> declarations(Path input, Path schema, Set<Path> active) throws Exception {
|
||||||
|
if (!active.add(schema)) {
|
||||||
|
throw new IllegalArgumentException("Cyclic API declaration inheritance: " + schema);
|
||||||
|
}
|
||||||
|
JsonObject data;
|
||||||
|
try (Reader reader = Files.newBufferedReader(schema, StandardCharsets.UTF_8)) {
|
||||||
|
data = JsonParser.parseReader(reader).getAsJsonObject();
|
||||||
|
}
|
||||||
|
SortedMap<String, JsonObject> classes = new TreeMap<>();
|
||||||
|
if (data.has("base")) {
|
||||||
|
classes.putAll(declarations(input, input.resolve(text(data, "base") + ".json"), active));
|
||||||
|
}
|
||||||
|
for (JsonElement entry : array(data, "classes")) {
|
||||||
|
JsonObject cls = entry.getAsJsonObject();
|
||||||
|
classes.put(text(cls, "name"), cls);
|
||||||
|
}
|
||||||
|
active.remove(schema);
|
||||||
|
return classes;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Path input = Paths.get(args[0]);
|
||||||
|
Path output = Paths.get(args[1]);
|
||||||
|
Files.createDirectories(output);
|
||||||
|
List<Path> schemas;
|
||||||
|
try (Stream<Path> stream = Files.list(input)) {
|
||||||
|
schemas = stream.filter(p -> p.toString().endsWith(".json")).sorted().collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
for (Path schema : schemas) {
|
||||||
|
SortedMap<String, JsonObject> classes = declarations(input, schema, new HashSet<>());
|
||||||
|
String name = schema.getFileName().toString().replace(".json", ".jar");
|
||||||
|
Path jar = output.resolve(name);
|
||||||
|
try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jar))) {
|
||||||
|
for (JsonObject cls : classes.values()) {
|
||||||
|
JarEntry entry = new JarEntry(text(cls, "name") + ".class");
|
||||||
|
entry.setTime(0);
|
||||||
|
out.putNextEntry(entry);
|
||||||
|
out.write(compile(cls));
|
||||||
|
out.closeEntry();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
System.out.println("Generated compile API " + name + " (" + classes.size() + " declarations)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
{
|
||||||
|
"classes": [
|
||||||
|
{
|
||||||
|
"version": 52,
|
||||||
|
"access": 33,
|
||||||
|
"name": "org/spigotmc/SpigotConfig",
|
||||||
|
"superName": "java/lang/Object",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"access": 9,
|
||||||
|
"name": "unknownCommandMessage",
|
||||||
|
"descriptor": "Ljava/lang/String;"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"access": 9,
|
||||||
|
"name": "bungee",
|
||||||
|
"descriptor": "Z"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"methods": [
|
||||||
|
{
|
||||||
|
"access": 1,
|
||||||
|
"name": "<init>",
|
||||||
|
"descriptor": "()V"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": 52,
|
||||||
|
"access": 33,
|
||||||
|
"name": "org/spigotmc/AsyncCatcher",
|
||||||
|
"superName": "java/lang/Object",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"access": 9,
|
||||||
|
"name": "enabled",
|
||||||
|
"descriptor": "Z"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"methods": [
|
||||||
|
{
|
||||||
|
"access": 1,
|
||||||
|
"name": "<init>",
|
||||||
|
"descriptor": "()V"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"access": 9,
|
||||||
|
"name": "catchOp",
|
||||||
|
"descriptor": "(Ljava/lang/String;)V"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": 52,
|
||||||
|
"access": 33,
|
||||||
|
"name": "us/myles/ViaVersion/api/Via",
|
||||||
|
"superName": "java/lang/Object",
|
||||||
|
"methods": [
|
||||||
|
{
|
||||||
|
"access": 9,
|
||||||
|
"name": "getAPI",
|
||||||
|
"descriptor": "()Lus/myles/ViaVersion/api/ViaAPI;"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": 52,
|
||||||
|
"access": 1537,
|
||||||
|
"name": "us/myles/ViaVersion/api/ViaAPI",
|
||||||
|
"superName": "java/lang/Object",
|
||||||
|
"methods": [
|
||||||
|
{
|
||||||
|
"access": 1025,
|
||||||
|
"name": "getPlayerVersion",
|
||||||
|
"descriptor": "(Ljava/util/UUID;)I"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": 52,
|
||||||
|
"access": 33,
|
||||||
|
"name": "us/myles/ViaVersion/api/protocol/ProtocolVersion",
|
||||||
|
"superName": "java/lang/Object",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"access": 25,
|
||||||
|
"name": "v1_8",
|
||||||
|
"descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"access": 25,
|
||||||
|
"name": "v1_9",
|
||||||
|
"descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"access": 25,
|
||||||
|
"name": "v1_10",
|
||||||
|
"descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"access": 25,
|
||||||
|
"name": "v1_11",
|
||||||
|
"descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"access": 25,
|
||||||
|
"name": "v1_12",
|
||||||
|
"descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"access": 25,
|
||||||
|
"name": "v1_13",
|
||||||
|
"descriptor": "Lus/myles/ViaVersion/api/protocol/ProtocolVersion;"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"methods": [
|
||||||
|
{
|
||||||
|
"access": 1,
|
||||||
|
"name": "getId",
|
||||||
|
"descriptor": "()I"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Vendored
BIN
Binary file not shown.
+8
@@ -0,0 +1,8 @@
|
|||||||
|
distributionBase=GRADLE_USER_HOME
|
||||||
|
distributionPath=wrapper/dists
|
||||||
|
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||||
|
networkTimeout=10000
|
||||||
|
validateDistributionUrl=true
|
||||||
|
zipStoreBase=GRADLE_USER_HOME
|
||||||
|
zipStorePath=wrapper/dists
|
||||||
|
distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
#
|
||||||
|
# Copyright © 2015-2021 the original authors.
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
# you may not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
#
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
#
|
||||||
|
# Gradle start up script for POSIX generated by Gradle.
|
||||||
|
#
|
||||||
|
# Important for running:
|
||||||
|
#
|
||||||
|
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
|
||||||
|
# noncompliant, but you have some other compliant shell such as ksh or
|
||||||
|
# bash, then to run this script, type that shell name before the whole
|
||||||
|
# command line, like:
|
||||||
|
#
|
||||||
|
# ksh Gradle
|
||||||
|
#
|
||||||
|
# Busybox and similar reduced shells will NOT work, because this script
|
||||||
|
# requires all of these POSIX shell features:
|
||||||
|
# * functions;
|
||||||
|
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
|
||||||
|
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
|
||||||
|
# * compound commands having a testable exit status, especially «case»;
|
||||||
|
# * various built-in commands including «command», «set», and «ulimit».
|
||||||
|
#
|
||||||
|
# Important for patching:
|
||||||
|
#
|
||||||
|
# (2) This script targets any POSIX shell, so it avoids extensions provided
|
||||||
|
# by Bash, Ksh, etc; in particular arrays are avoided.
|
||||||
|
#
|
||||||
|
# The "traditional" practice of packing multiple parameters into a
|
||||||
|
# space-separated string is a well documented source of bugs and security
|
||||||
|
# problems, so this is (mostly) avoided, by progressively accumulating
|
||||||
|
# options in "$@", and eventually passing that to Java.
|
||||||
|
#
|
||||||
|
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
|
||||||
|
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
|
||||||
|
# see the in-line comments for details.
|
||||||
|
#
|
||||||
|
# There are tweaks for specific operating systems such as AIX, CygWin,
|
||||||
|
# Darwin, MinGW, and NonStop.
|
||||||
|
#
|
||||||
|
# (3) This script is generated from the Groovy template
|
||||||
|
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
|
||||||
|
# within the Gradle project.
|
||||||
|
#
|
||||||
|
# You can find Gradle at https://github.com/gradle/gradle/.
|
||||||
|
#
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
# Attempt to set APP_HOME
|
||||||
|
|
||||||
|
# Resolve links: $0 may be a link
|
||||||
|
app_path=$0
|
||||||
|
|
||||||
|
# Need this for daisy-chained symlinks.
|
||||||
|
while
|
||||||
|
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
|
||||||
|
[ -h "$app_path" ]
|
||||||
|
do
|
||||||
|
ls=$( ls -ld "$app_path" )
|
||||||
|
link=${ls#*' -> '}
|
||||||
|
case $link in #(
|
||||||
|
/*) app_path=$link ;; #(
|
||||||
|
*) app_path=$APP_HOME$link ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
# This is normally unused
|
||||||
|
# shellcheck disable=SC2034
|
||||||
|
APP_BASE_NAME=${0##*/}
|
||||||
|
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||||
|
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||||
|
|
||||||
|
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||||
|
MAX_FD=maximum
|
||||||
|
|
||||||
|
warn () {
|
||||||
|
echo "$*"
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
die () {
|
||||||
|
echo
|
||||||
|
echo "$*"
|
||||||
|
echo
|
||||||
|
exit 1
|
||||||
|
} >&2
|
||||||
|
|
||||||
|
# OS specific support (must be 'true' or 'false').
|
||||||
|
cygwin=false
|
||||||
|
msys=false
|
||||||
|
darwin=false
|
||||||
|
nonstop=false
|
||||||
|
case "$( uname )" in #(
|
||||||
|
CYGWIN* ) cygwin=true ;; #(
|
||||||
|
Darwin* ) darwin=true ;; #(
|
||||||
|
MSYS* | MINGW* ) msys=true ;; #(
|
||||||
|
NONSTOP* ) nonstop=true ;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
CLASSPATH="\\\"\\\""
|
||||||
|
|
||||||
|
|
||||||
|
# Determine the Java command to use to start the JVM.
|
||||||
|
if [ -n "$JAVA_HOME" ] ; then
|
||||||
|
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||||
|
# IBM's JDK on AIX uses strange locations for the executables
|
||||||
|
JAVACMD=$JAVA_HOME/jre/sh/java
|
||||||
|
else
|
||||||
|
JAVACMD=$JAVA_HOME/bin/java
|
||||||
|
fi
|
||||||
|
if [ ! -x "$JAVACMD" ] ; then
|
||||||
|
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
JAVACMD=java
|
||||||
|
if ! command -v java >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||||
|
|
||||||
|
Please set the JAVA_HOME variable in your environment to match the
|
||||||
|
location of your Java installation."
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Increase the maximum file descriptors if we can.
|
||||||
|
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
|
||||||
|
case $MAX_FD in #(
|
||||||
|
max*)
|
||||||
|
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
MAX_FD=$( ulimit -H -n ) ||
|
||||||
|
warn "Could not query maximum file descriptor limit"
|
||||||
|
esac
|
||||||
|
case $MAX_FD in #(
|
||||||
|
'' | soft) :;; #(
|
||||||
|
*)
|
||||||
|
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
|
||||||
|
# shellcheck disable=SC2039,SC3045
|
||||||
|
ulimit -n "$MAX_FD" ||
|
||||||
|
warn "Could not set maximum file descriptor limit to $MAX_FD"
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Collect all arguments for the java command, stacking in reverse order:
|
||||||
|
# * args from the command line
|
||||||
|
# * the main class name
|
||||||
|
# * -classpath
|
||||||
|
# * -D...appname settings
|
||||||
|
# * --module-path (only if needed)
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
|
||||||
|
|
||||||
|
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||||
|
if "$cygwin" || "$msys" ; then
|
||||||
|
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
|
||||||
|
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
|
||||||
|
|
||||||
|
JAVACMD=$( cygpath --unix "$JAVACMD" )
|
||||||
|
|
||||||
|
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||||
|
for arg do
|
||||||
|
if
|
||||||
|
case $arg in #(
|
||||||
|
-*) false ;; # don't mess with options #(
|
||||||
|
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
|
||||||
|
[ -e "$t" ] ;; #(
|
||||||
|
*) false ;;
|
||||||
|
esac
|
||||||
|
then
|
||||||
|
arg=$( cygpath --path --ignore --mixed "$arg" )
|
||||||
|
fi
|
||||||
|
# Roll the args list around exactly as many times as the number of
|
||||||
|
# args, so each arg winds up back in the position where it started, but
|
||||||
|
# possibly modified.
|
||||||
|
#
|
||||||
|
# NB: a `for` loop captures its iteration list before it begins, so
|
||||||
|
# changing the positional parameters here affects neither the number of
|
||||||
|
# iterations, nor the values presented in `arg`.
|
||||||
|
shift # remove old arg
|
||||||
|
set -- "$@" "$arg" # push replacement arg
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
|
||||||
|
|
||||||
|
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||||
|
|
||||||
|
# Collect all arguments for the java command:
|
||||||
|
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||||
|
# and any embedded shellness will be escaped.
|
||||||
|
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||||
|
# treated as '${Hostname}' itself on the command line.
|
||||||
|
|
||||||
|
set -- \
|
||||||
|
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||||
|
-classpath "$CLASSPATH" \
|
||||||
|
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||||
|
"$@"
|
||||||
|
|
||||||
|
# Stop when "xargs" is not available.
|
||||||
|
if ! command -v xargs >/dev/null 2>&1
|
||||||
|
then
|
||||||
|
die "xargs is not available"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Use "xargs" to parse quoted args.
|
||||||
|
#
|
||||||
|
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
|
||||||
|
#
|
||||||
|
# In Bash we could simply go:
|
||||||
|
#
|
||||||
|
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
|
||||||
|
# set -- "${ARGS[@]}" "$@"
|
||||||
|
#
|
||||||
|
# but POSIX shell has neither arrays nor command substitution, so instead we
|
||||||
|
# post-process each arg (as a line of input to sed) to backslash-escape any
|
||||||
|
# character that might be a shell metacharacter, then use eval to reverse
|
||||||
|
# that process (while maintaining the separation between arguments), and wrap
|
||||||
|
# the whole thing up as a single "set" statement.
|
||||||
|
#
|
||||||
|
# This will of course break if any of these variables contains a newline or
|
||||||
|
# an unmatched quote.
|
||||||
|
#
|
||||||
|
|
||||||
|
eval "set -- $(
|
||||||
|
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
|
||||||
|
xargs -n1 |
|
||||||
|
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
|
||||||
|
tr '\n' ' '
|
||||||
|
)" '"$@"'
|
||||||
|
|
||||||
|
exec "$JAVACMD" "$@"
|
||||||
Vendored
+94
@@ -0,0 +1,94 @@
|
|||||||
|
@rem
|
||||||
|
@rem Copyright 2015 the original author or authors.
|
||||||
|
@rem
|
||||||
|
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
@rem you may not use this file except in compliance with the License.
|
||||||
|
@rem You may obtain a copy of the License at
|
||||||
|
@rem
|
||||||
|
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
@rem
|
||||||
|
@rem Unless required by applicable law or agreed to in writing, software
|
||||||
|
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
@rem See the License for the specific language governing permissions and
|
||||||
|
@rem limitations under the License.
|
||||||
|
@rem
|
||||||
|
@rem SPDX-License-Identifier: Apache-2.0
|
||||||
|
@rem
|
||||||
|
|
||||||
|
@if "%DEBUG%"=="" @echo off
|
||||||
|
@rem ##########################################################################
|
||||||
|
@rem
|
||||||
|
@rem Gradle startup script for Windows
|
||||||
|
@rem
|
||||||
|
@rem ##########################################################################
|
||||||
|
|
||||||
|
@rem Set local scope for the variables with windows NT shell
|
||||||
|
if "%OS%"=="Windows_NT" setlocal
|
||||||
|
|
||||||
|
set DIRNAME=%~dp0
|
||||||
|
if "%DIRNAME%"=="" set DIRNAME=.
|
||||||
|
@rem This is normally unused
|
||||||
|
set APP_BASE_NAME=%~n0
|
||||||
|
set APP_HOME=%DIRNAME%
|
||||||
|
|
||||||
|
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||||
|
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||||
|
|
||||||
|
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||||
|
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||||
|
|
||||||
|
@rem Find java.exe
|
||||||
|
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||||
|
|
||||||
|
set JAVA_EXE=java.exe
|
||||||
|
%JAVA_EXE% -version >NUL 2>&1
|
||||||
|
if %ERRORLEVEL% equ 0 goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:findJavaFromJavaHome
|
||||||
|
set JAVA_HOME=%JAVA_HOME:"=%
|
||||||
|
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||||
|
|
||||||
|
if exist "%JAVA_EXE%" goto execute
|
||||||
|
|
||||||
|
echo. 1>&2
|
||||||
|
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
|
||||||
|
echo. 1>&2
|
||||||
|
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
|
||||||
|
echo location of your Java installation. 1>&2
|
||||||
|
|
||||||
|
goto fail
|
||||||
|
|
||||||
|
:execute
|
||||||
|
@rem Setup the command line
|
||||||
|
|
||||||
|
set CLASSPATH=
|
||||||
|
|
||||||
|
|
||||||
|
@rem Execute Gradle
|
||||||
|
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||||
|
|
||||||
|
:end
|
||||||
|
@rem End local scope for the variables with windows NT shell
|
||||||
|
if %ERRORLEVEL% equ 0 goto mainEnd
|
||||||
|
|
||||||
|
:fail
|
||||||
|
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||||
|
rem the _cmd.exe /c_ return code!
|
||||||
|
set EXIT_CODE=%ERRORLEVEL%
|
||||||
|
if %EXIT_CODE% equ 0 set EXIT_CODE=1
|
||||||
|
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
|
||||||
|
exit /b %EXIT_CODE%
|
||||||
|
|
||||||
|
:mainEnd
|
||||||
|
if "%OS%"=="Windows_NT" endlocal
|
||||||
|
|
||||||
|
:omega
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = 'OpenReflex'
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package me.darksidecode.e2eep4j;
|
||||||
|
|
||||||
|
public class E2EException extends RuntimeException {
|
||||||
|
public E2EException() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public E2EException(String s) {
|
||||||
|
super(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
public E2EException(Exception e) {
|
||||||
|
super(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
public E2EException(String s, Exception e) {
|
||||||
|
super(s, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package me.darksidecode.e2eep4j;
|
||||||
|
|
||||||
|
import me.darksidecode.e2eep4j.util.Validate;
|
||||||
|
|
||||||
|
public class E2EKey {
|
||||||
|
private byte[] iv;
|
||||||
|
private byte[] aes;
|
||||||
|
private byte[] base;
|
||||||
|
private Object[] coverage;
|
||||||
|
|
||||||
|
public E2EKey(byte[] iv, byte[] aes, byte[] base) {
|
||||||
|
this(iv, aes, base, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public E2EKey(byte[] iv, byte[] aes, byte[] base, Object[] coverage) {
|
||||||
|
this.iv = Validate.ivLength(
|
||||||
|
Validate.notEmpty(Validate.notNull(iv, "Init vector cannot be null"), "Init vector cannot be empty"), "Illegal input vector length"
|
||||||
|
);
|
||||||
|
this.aes = Validate.aesLength(Validate.notEmpty(Validate.notNull(aes, "AES cannot be null"), "AES cannot be empty"), "Illegal AES length");
|
||||||
|
this.base = Validate.baseLength(Validate.notEmpty(Validate.notNull(base, "Base cannot be null"), "Base cannot be empty"), "Illegal base length");
|
||||||
|
this.coverage = coverage == null ? null : Validate.cvgLength(Validate.notEmpty(coverage, "Coverage cannot be empty"), "Illegal coverage length");
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getIV() {
|
||||||
|
byte[] r = (byte[])Validate.notEmpty(this.iv, "Input vector was already used").clone();
|
||||||
|
this.iv = new byte[0];
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getAES() {
|
||||||
|
byte[] r = (byte[])Validate.notEmpty(this.aes, "AES was already used").clone();
|
||||||
|
this.aes = new byte[0];
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] getBase() {
|
||||||
|
byte[] r = (byte[])Validate.notEmpty(this.base, "Base was already used").clone();
|
||||||
|
this.base = new byte[0];
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object[] getCoverage() {
|
||||||
|
Object[] r = Validate.notEmpty(Validate.notNull(this.coverage, "Coverage is not set"), "Coverage was already used").clone();
|
||||||
|
this.coverage = new Object[0];
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean shallCoverage() {
|
||||||
|
return this.coverage != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isUsed() {
|
||||||
|
return this.iv.length == 0 || this.aes.length == 0 || this.base.length == 0 || this.coverage != null && this.coverage.length == 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean equals(Object obj) {
|
||||||
|
throw new E2EException("E2E keys cannot be compared");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
throw new E2EException("E2E keys cannot be hashed");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
throw new E2EException("E2E keys cannot be converted to a string");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object clone() {
|
||||||
|
throw new E2EException("E2E keys cannot be cloned");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package me.darksidecode.e2eep4j.api;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import me.darksidecode.e2eep4j.E2EException;
|
||||||
|
import me.darksidecode.e2eep4j.E2EKey;
|
||||||
|
import me.darksidecode.e2eep4j.enc.CryptoSession;
|
||||||
|
import me.darksidecode.e2eep4j.enc.DecryptionSession;
|
||||||
|
import me.darksidecode.e2eep4j.enc.EncryptionSession;
|
||||||
|
import me.darksidecode.e2eep4j.util.Convert;
|
||||||
|
import me.darksidecode.e2eep4j.util.Generate;
|
||||||
|
|
||||||
|
public class E2EEP4J {
|
||||||
|
public static byte[] encryptBytes(byte[] input, E2EKey key) {
|
||||||
|
return cryptBytes(new EncryptionSession(input, key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] decryptBytes(byte[] input, E2EKey key) {
|
||||||
|
return cryptBytes(new DecryptionSession(input, key));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] cryptBytes(CryptoSession session) {
|
||||||
|
return session.run().result();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static E2EKey generateKey() {
|
||||||
|
return Generate.e2eKey();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static E2EKey generateKey(Object[] coverage) {
|
||||||
|
return Generate.e2eKey(coverage);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void safeKeyToFile(E2EKey key, File f) {
|
||||||
|
try {
|
||||||
|
Files.write(f.toPath(), Convert.e2eKey2Bytes(key));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new E2EException("Failed to save key to file", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static E2EKey readKeyFromFile(File f) {
|
||||||
|
try {
|
||||||
|
return Convert.bytes2e2ekey(Files.readAllBytes(f.toPath()));
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new E2EException("Failed to read key from file", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package me.darksidecode.e2eep4j.enc;
|
||||||
|
|
||||||
|
public interface CryptoSession {
|
||||||
|
CryptoSession run();
|
||||||
|
|
||||||
|
CryptoSession end();
|
||||||
|
|
||||||
|
byte[] result();
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package me.darksidecode.e2eep4j.enc;
|
||||||
|
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
import javax.crypto.spec.IvParameterSpec;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
import me.darksidecode.e2eep4j.E2EException;
|
||||||
|
import me.darksidecode.e2eep4j.E2EKey;
|
||||||
|
import me.darksidecode.e2eep4j.util.Validate;
|
||||||
|
import org.apache.commons.codec.binary.Base64;
|
||||||
|
|
||||||
|
public class DecryptionSession implements CryptoSession {
|
||||||
|
private byte[] input;
|
||||||
|
private byte[] result;
|
||||||
|
private E2EKey k;
|
||||||
|
|
||||||
|
public DecryptionSession(byte[] input, E2EKey k) {
|
||||||
|
this.input = Validate.notEmpty(Validate.notNull(input, "Input cannot be null"), "Input cannot be empty");
|
||||||
|
this.k = Validate.notNull(k, "Key cannot be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CryptoSession run() {
|
||||||
|
try {
|
||||||
|
IvParameterSpec iv = new IvParameterSpec(this.k.getIV());
|
||||||
|
SecretKeySpec skeySpec = new SecretKeySpec(this.k.getAES(), "AES");
|
||||||
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
||||||
|
cipher.init(2, skeySpec, iv);
|
||||||
|
this.result = cipher.doFinal(Base64.decodeBase64(this.input));
|
||||||
|
return this;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new E2EException("Failed to decrypt " + this.input.length + " bytes", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CryptoSession end() {
|
||||||
|
this.input = this.result = new byte[0];
|
||||||
|
this.k = null;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] result() {
|
||||||
|
if (Validate.notNull(this.result, "The session was never ran").length != 0 && this.k != null) {
|
||||||
|
byte[] r = (byte[])this.result.clone();
|
||||||
|
this.end();
|
||||||
|
return r;
|
||||||
|
} else {
|
||||||
|
throw new E2EException("Result was already used");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package me.darksidecode.e2eep4j.enc;
|
||||||
|
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
import javax.crypto.spec.IvParameterSpec;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
import me.darksidecode.e2eep4j.E2EException;
|
||||||
|
import me.darksidecode.e2eep4j.E2EKey;
|
||||||
|
import me.darksidecode.e2eep4j.util.Validate;
|
||||||
|
import org.apache.commons.codec.binary.Base64;
|
||||||
|
|
||||||
|
public class EncryptionSession implements CryptoSession {
|
||||||
|
private byte[] input;
|
||||||
|
private byte[] result;
|
||||||
|
private E2EKey k;
|
||||||
|
|
||||||
|
public EncryptionSession(byte[] input, E2EKey k) {
|
||||||
|
this.input = Validate.notEmpty(Validate.notNull(input, "Input cannot be null"), "Input cannot be empty");
|
||||||
|
this.k = Validate.notNull(k, "Key cannot be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CryptoSession run() {
|
||||||
|
try {
|
||||||
|
IvParameterSpec iv = new IvParameterSpec(this.k.getIV());
|
||||||
|
SecretKeySpec skc = new SecretKeySpec(this.k.getAES(), "AES");
|
||||||
|
Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
||||||
|
c.init(1, skc, iv);
|
||||||
|
this.result = Base64.encodeBase64(c.doFinal(this.input));
|
||||||
|
return this;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new E2EException("Failed to encrypt " + this.input.length + " bytes", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public CryptoSession end() {
|
||||||
|
this.input = this.result = new byte[0];
|
||||||
|
this.k = null;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] result() {
|
||||||
|
if (Validate.notNull(this.result, "The session was never ran").length != 0 && this.k != null) {
|
||||||
|
byte[] r = (byte[])this.result.clone();
|
||||||
|
this.end();
|
||||||
|
return r;
|
||||||
|
} else {
|
||||||
|
throw new E2EException("Result was already used");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
package me.darksidecode.e2eep4j.enc;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import me.darksidecode.e2eep4j.E2EException;
|
||||||
|
|
||||||
|
class Tools {
|
||||||
|
static void reverse(int[] v) {
|
||||||
|
int x = 0;
|
||||||
|
|
||||||
|
for (int y = v.length - 1; y > x; x++) {
|
||||||
|
int tmp = v[y];
|
||||||
|
v[y] = v[x];
|
||||||
|
v[x] = tmp;
|
||||||
|
y--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void swapAdjacent(int[] v) {
|
||||||
|
int[] cp = (int[])v.clone();
|
||||||
|
|
||||||
|
for (int i = 0; i < cp.length && i + 2 <= cp.length; i += 2) {
|
||||||
|
v[i] = cp[i + 1];
|
||||||
|
v[i + 1] = cp[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static byte[] toBytes(int[] arr) {
|
||||||
|
try {
|
||||||
|
StringBuilder result = new StringBuilder();
|
||||||
|
|
||||||
|
for (int i : arr) {
|
||||||
|
result.append(i).append("\u0000");
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.deleteCharAt(result.length() - 1).toString().getBytes("UTF-8");
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new E2EException("Failed to encode " + arr.length + " ints", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static int[] fromBytes(byte[] bytes) {
|
||||||
|
try {
|
||||||
|
String s = new String(bytes, "UTF-8");
|
||||||
|
List<Integer> buf = new ArrayList<>();
|
||||||
|
|
||||||
|
for (String i : s.split("\u0000")) {
|
||||||
|
buf.add(Integer.parseInt(i));
|
||||||
|
}
|
||||||
|
|
||||||
|
int[] res = new int[buf.size()];
|
||||||
|
|
||||||
|
for (int i = 0; i < buf.size(); i++) {
|
||||||
|
res[i] = buf.get(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new E2EException("Failed to decode " + bytes.length + " bytes", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static int cover(Object[] coverage, int i) {
|
||||||
|
if (coverage == null) {
|
||||||
|
return i;
|
||||||
|
} else {
|
||||||
|
int[] var_1 = (int[])coverage[0];
|
||||||
|
int[] var_2 = (int[])coverage[1];
|
||||||
|
int[] var_3 = (int[])coverage[2];
|
||||||
|
int[] var_4 = (int[])coverage[3];
|
||||||
|
int[] var_5 = (int[])coverage[4];
|
||||||
|
int[] var_6 = (int[])coverage[5];
|
||||||
|
int var_7 = ((int[])coverage[5])[1];
|
||||||
|
int var_8 = 0 & var_3[0] & 28 & 28 & ((int[])coverage[5])[2] & 23179 & var_1[0] | 263;
|
||||||
|
int var_9 = 11414;
|
||||||
|
int var_11 = ((int[])coverage[5])[2];
|
||||||
|
int var_12 = var_4[var_2[0] >>> var_11] >> 4827;
|
||||||
|
int var_13 = var_8 & 11410;
|
||||||
|
int var_10 = var_8 & 11414 + -((int[])coverage[5])[3];
|
||||||
|
i ^= 20;
|
||||||
|
var_7++;
|
||||||
|
if (++var_12 != var_12++) {
|
||||||
|
var_1[0] = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
i = i ^ var_1[var_2[var_10] >>> var_11] ^ var_2[var_2[var_10] >>> var_11] ^ ~var_3[0] >>> var_11;
|
||||||
|
i = i
|
||||||
|
^ var_3[var_4[var_2[var_10] >>> var_11] >> 4827]
|
||||||
|
^ var_2[var_2[var_10] >>> var_11]
|
||||||
|
^ var_7
|
||||||
|
^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827])))
|
||||||
|
^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11;
|
||||||
|
i = i ^ var_1[var_2[var_10] >>> var_11] ^ var_7 ^ var_2[var_2[var_10] >>> var_11] ^ var_3[0] >>> var_11;
|
||||||
|
i = var_7 ^ var_2[var_2[var_10] >>> var_11] ^ var_3[0] >>> var_11 ^ i ^ var_1[var_2[var_10] >>> var_11];
|
||||||
|
i = i
|
||||||
|
^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827]
|
||||||
|
^ var_2[var_2[var_10] >>> var_11]
|
||||||
|
^ var_7
|
||||||
|
^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827])))
|
||||||
|
^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11;
|
||||||
|
i = i ^ var_3[var_2[var_10] >>> var_11] ^ var_2[var_2[var_10] >>> var_11] ^ ~(~var_6[var_2[var_10] >>> var_11]) ^ ~var_3[0] >>> var_11;
|
||||||
|
i = i
|
||||||
|
^ var_1[var_4[var_2[var_2[var_4[var_2[var_10] >>> var_11] >>> var_11] >> 4827] >>> var_11] >> 4827]
|
||||||
|
^ var_6[var_2[var_4[var_2[var_10] >>> var_11] >>> var_11] >> 4827]
|
||||||
|
^ var_2[var_2[var_10] >>> var_11]
|
||||||
|
^ var_7
|
||||||
|
^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827])))
|
||||||
|
^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11;
|
||||||
|
i = i
|
||||||
|
^ var_3[var_4[var_2[var_10] >>> var_11] >> 4827]
|
||||||
|
^ var_2[var_2[var_10] >>> var_11]
|
||||||
|
^ var_7
|
||||||
|
^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827])))
|
||||||
|
^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11;
|
||||||
|
i = i ^ var_3[var_2[var_10] >>> var_11] ^ var_2[var_2[var_10] >>> var_11] ^ ~(~var_6[var_2[var_10] >>> var_11]) ^ ~var_3[0] >>> var_11;
|
||||||
|
i = var_7 ^ var_2[var_2[var_10] >>> var_11] ^ var_3[0] >>> var_11 ^ i ^ var_1[var_2[var_10] >>> var_11];
|
||||||
|
i = i ^ var_1[var_2[var_10] >>> var_11] ^ var_4[var_2[var_10] >>> var_11] ^ var_2[var_2[var_10] >>> var_11] ^ var_3[0] >>> var_11;
|
||||||
|
i = i
|
||||||
|
^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827]
|
||||||
|
^ var_2[var_2[var_10] >>> var_11]
|
||||||
|
^ var_7
|
||||||
|
^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827])))
|
||||||
|
^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11;
|
||||||
|
i = i ^ var_1[var_2[var_10] >>> var_11] ^ var_11 ^ var_2[var_2[var_10] >>> var_11] ^ ~var_3[0] >>> var_11;
|
||||||
|
i = i
|
||||||
|
^ var_1[var_4[var_2[var_2[var_4[var_2[var_10] >>> var_11] >>> var_11] >> 4827] >>> var_11] >> 4827]
|
||||||
|
^ var_6[var_2[var_4[var_2[var_10] >>> var_11] >>> var_11] >> 4827]
|
||||||
|
^ var_2[var_2[var_10] >>> var_11]
|
||||||
|
^ var_7
|
||||||
|
^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827])))
|
||||||
|
^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11;
|
||||||
|
if (++var_12 > 9999) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (var_12 == 37) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (var_12 == 3462) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (i != var_11 + (i | i | i & i | i)) {
|
||||||
|
if (i == var_11 + (i & i)) {
|
||||||
|
i = i
|
||||||
|
^ var_1[var_2[var_4[var_10] >>> var_11] >> 4827]
|
||||||
|
^ var_2[var_2[var_10] >>> var_11]
|
||||||
|
^ var_7
|
||||||
|
^ ~(~(~(~var_6[var_4[var_2[var_10] >>> var_11] >> 4827])))
|
||||||
|
^ var_1[var_4[var_2[var_10] >>> var_11] >> 4827] >>> var_11;
|
||||||
|
return i ^ var_3[var_4[var_10] >>> var_11] ^ var_11 ^ var_4[var_2[var_10] >>> var_11] ^ ~var_1[0] >>> var_11;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (var_12 != var_13 && var_7 != var_7 + var_12) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package me.darksidecode.e2eep4j.util;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.io.ObjectOutputStream;
|
||||||
|
import me.darksidecode.e2eep4j.E2EException;
|
||||||
|
import me.darksidecode.e2eep4j.E2EKey;
|
||||||
|
|
||||||
|
public class Convert {
|
||||||
|
public static byte[] e2eKey2Bytes(E2EKey k) {
|
||||||
|
try {
|
||||||
|
byte[] iv = k.getIV();
|
||||||
|
byte[] aes = k.getAES();
|
||||||
|
byte[] base = k.getBase();
|
||||||
|
Object[] cvg = k.shallCoverage() ? k.getCoverage() : new Object[0];
|
||||||
|
Object[] r = new Object[iv.length + aes.length + base.length + cvg.length];
|
||||||
|
int idx = 0;
|
||||||
|
|
||||||
|
for (byte n : iv) {
|
||||||
|
r[idx++] = n;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (byte n : aes) {
|
||||||
|
r[idx++] = n;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (byte n : base) {
|
||||||
|
r[idx++] = n;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Object n : cvg) {
|
||||||
|
r[idx++] = n;
|
||||||
|
}
|
||||||
|
|
||||||
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
|
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||||
|
oos.writeObject(r);
|
||||||
|
oos.flush();
|
||||||
|
oos.close();
|
||||||
|
baos.close();
|
||||||
|
return baos.toByteArray();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new E2EException("E2EKey conversion failed", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static E2EKey bytes2e2ekey(byte[] bytes) {
|
||||||
|
try {
|
||||||
|
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(bis);
|
||||||
|
Object[] r = (Object[])ois.readObject();
|
||||||
|
int idx = 0;
|
||||||
|
byte[] iv = new byte[16];
|
||||||
|
byte[] aes = new byte[16];
|
||||||
|
byte[] base = new byte[32];
|
||||||
|
Object[] cvg = new Object[r.length - 64];
|
||||||
|
|
||||||
|
for (int i = 0; i < iv.length; i++) {
|
||||||
|
iv[i] = (Byte)r[idx++];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < aes.length; i++) {
|
||||||
|
aes[i] = (Byte)r[idx++];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < base.length; i++) {
|
||||||
|
base[i] = (Byte)r[idx++];
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < cvg.length; i++) {
|
||||||
|
cvg[i] = r[idx++];
|
||||||
|
}
|
||||||
|
|
||||||
|
return new E2EKey(iv, aes, base, cvg.length == 0 ? null : cvg);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new E2EException("Bytes conversion failed", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package me.darksidecode.e2eep4j.util;
|
||||||
|
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import me.darksidecode.e2eep4j.E2EKey;
|
||||||
|
|
||||||
|
public class Generate {
|
||||||
|
private static final SecureRandom r = new SecureRandom();
|
||||||
|
|
||||||
|
public static E2EKey e2eKey() {
|
||||||
|
return e2eKey(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static E2EKey e2eKey(Object[] cvg) {
|
||||||
|
return new E2EKey(iv(), aes(), base(), cvg);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] iv() {
|
||||||
|
return byteStream(16);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] aes() {
|
||||||
|
return byteStream(16);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] base() {
|
||||||
|
return byteStream(32);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] byteStream(int len) {
|
||||||
|
byte[] bytes = new byte[Validate.multipleOf(len, 4, "Length must be a multiple of 4")];
|
||||||
|
r.nextBytes(bytes);
|
||||||
|
return (byte[])bytes.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package me.darksidecode.e2eep4j.util;
|
||||||
|
|
||||||
|
public class KeySpecs {
|
||||||
|
public static final int IV = 16;
|
||||||
|
public static final int AES = 16;
|
||||||
|
public static final int BASE = 32;
|
||||||
|
public static final int COVERAGE = 6;
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package me.darksidecode.e2eep4j.util;
|
||||||
|
|
||||||
|
public class Validate {
|
||||||
|
public static <T> T notNull(T obj, String msg) {
|
||||||
|
if (obj == null) {
|
||||||
|
throw new NullPointerException(msg);
|
||||||
|
} else {
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] notEmpty(byte[] arr, String msg) {
|
||||||
|
if (arr.length == 0) {
|
||||||
|
throw new IllegalArgumentException(msg);
|
||||||
|
} else {
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> T[] notEmpty(T[] arr, String msg) {
|
||||||
|
if (arr.length == 0) {
|
||||||
|
throw new IllegalArgumentException(msg);
|
||||||
|
} else {
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int multipleOf(int i, int m, String msg) {
|
||||||
|
if (i % m == 0 && i != 0) {
|
||||||
|
return i;
|
||||||
|
} else {
|
||||||
|
throw new ArithmeticException(msg + " (" + i + "%" + m + "!=0)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] ivLength(byte[] n, String msg) {
|
||||||
|
if (n.length != 16) {
|
||||||
|
throw new IllegalArgumentException(msg + " (" + n.length + "!=" + 16 + ")");
|
||||||
|
} else {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] aesLength(byte[] n, String msg) {
|
||||||
|
if (n.length != 16) {
|
||||||
|
throw new IllegalArgumentException(msg + " (" + n.length + "!=" + 16 + ")");
|
||||||
|
} else {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] baseLength(byte[] n, String msg) {
|
||||||
|
if (n.length != 32) {
|
||||||
|
throw new IllegalArgumentException(msg + " (" + n.length + "!=" + 32 + ")");
|
||||||
|
} else {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object[] cvgLength(Object[] n, String msg) {
|
||||||
|
if (n.length != 6) {
|
||||||
|
throw new IllegalArgumentException(msg + " (" + n.length + "!=" + 6 + ")");
|
||||||
|
} else {
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
package me.darksidecode.easysockets.client;
|
||||||
|
|
||||||
|
import java.io.DataInputStream;
|
||||||
|
import java.io.DataOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.security.KeyManagementException;
|
||||||
|
import java.security.KeyStore;
|
||||||
|
import java.security.KeyStoreException;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.security.cert.CertificateException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import javax.net.SocketFactory;
|
||||||
|
import javax.net.ssl.SSLContext;
|
||||||
|
import javax.net.ssl.SSLSocket;
|
||||||
|
import javax.net.ssl.TrustManagerFactory;
|
||||||
|
import me.darksidecode.easysockets.client.config.SocketClientConfig;
|
||||||
|
import me.darksidecode.easysockets.event.EventCancelledException;
|
||||||
|
import me.darksidecode.easysockets.event.EventManager;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
import me.darksidecode.easysockets.event.client.ClientStartEvent;
|
||||||
|
import me.darksidecode.easysockets.event.client.ClientStopEvent;
|
||||||
|
import me.darksidecode.easysockets.event.client.ClientTimeoutEvent;
|
||||||
|
import me.darksidecode.easysockets.protocol.packet.Packet;
|
||||||
|
import me.darksidecode.easysockets.util.io.Compressor;
|
||||||
|
|
||||||
|
public class BasicSocketClient {
|
||||||
|
private final int protocolVersion;
|
||||||
|
private final String host;
|
||||||
|
private final int port;
|
||||||
|
private final Socket socket;
|
||||||
|
private final DataInputStream input;
|
||||||
|
private final DataOutputStream output;
|
||||||
|
private final ProtocolManager protocolManager;
|
||||||
|
private final EventManager eventManager;
|
||||||
|
private final SocketClientConfig config;
|
||||||
|
private SSLContext sslContext;
|
||||||
|
private boolean stopped;
|
||||||
|
|
||||||
|
@Deprecated
|
||||||
|
public BasicSocketClient(int protocolVersion, String host, int port, Object __, SocketClientConfig config) {
|
||||||
|
this(protocolVersion, host, port, config);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BasicSocketClient(int protocolVersion, String host, int port, SocketClientConfig config) {
|
||||||
|
if (config.isUseSSL()) {
|
||||||
|
if (config.getTrustStoreStream() == null) {
|
||||||
|
throw new RuntimeException("TrustStore stream is null");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
|
||||||
|
KeyStore trustStore = KeyStore.getInstance("jks");
|
||||||
|
trustStore.load(config.getTrustStoreStream(), config.getTrustStorePassword().toCharArray());
|
||||||
|
factory.init(trustStore);
|
||||||
|
this.sslContext = SSLContext.getInstance("TLSv1.2");
|
||||||
|
this.sslContext.init(null, factory.getTrustManagers(), SecureRandom.getInstanceStrong());
|
||||||
|
} catch (CertificateException | KeyStoreException | KeyManagementException | IOException | NoSuchAlgorithmException ex) {
|
||||||
|
this.shutdown();
|
||||||
|
throw new RuntimeException("failed to start a BasicSocketClient: SSL creation error", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
if ((this.eventManager = new EventManager()).callEvent(new ClientStartEvent(EventState.PRE, System.currentTimeMillis()))) {
|
||||||
|
throw new EventCancelledException("Client startup aborted");
|
||||||
|
} else {
|
||||||
|
this.protocolVersion = protocolVersion;
|
||||||
|
this.host = host;
|
||||||
|
this.port = port;
|
||||||
|
this.config = config;
|
||||||
|
this.socket = config.isUseSSL()
|
||||||
|
? this.sslContext.getSocketFactory().createSocket(host, port)
|
||||||
|
: SocketFactory.getDefault().createSocket(host, port);
|
||||||
|
this.socket.setSoTimeout(config.getTimeout());
|
||||||
|
this.socket.setTcpNoDelay(true);
|
||||||
|
this.socket.setKeepAlive(true);
|
||||||
|
if (config.isUseSSL()) {
|
||||||
|
List<String> ciphers = new ArrayList<>(
|
||||||
|
Arrays.asList(
|
||||||
|
"TLS_RSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_RSA_WITH_AES_256_CBC_SHA256",
|
||||||
|
"TLS_DH_RSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_DH_RSA_WITH_AES_256_CBC_SHA256",
|
||||||
|
"TLS_RSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_RSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_DH_RSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_DH_RSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
|
||||||
|
"TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",
|
||||||
|
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
|
||||||
|
"TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",
|
||||||
|
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
|
||||||
|
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
|
||||||
|
"TLS_AES_128_CCM_SHA256",
|
||||||
|
"TLS_AES_128_GCM_SHA256",
|
||||||
|
"TLS_AES_256_GCM_SHA384",
|
||||||
|
"TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
|
||||||
|
"TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_CHACHA20_POLY1305_SHA256"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
ciphers.retainAll(Arrays.asList(this.sslContext.getServerSocketFactory().getSupportedCipherSuites()));
|
||||||
|
((SSLSocket)this.socket).setEnabledCipherSuites(ciphers.toArray(new String[0]));
|
||||||
|
((SSLSocket)this.socket).setEnabledProtocols(new String[]{"TLSv1.2"});
|
||||||
|
}
|
||||||
|
|
||||||
|
this.input = new DataInputStream(Compressor.newInflateInput(this.socket.getInputStream()));
|
||||||
|
this.output = new DataOutputStream(Compressor.newDeflateOutput(this.socket.getOutputStream()));
|
||||||
|
this.protocolManager = new ProtocolManager(protocolVersion, this.socket, this.input, this.output, this.eventManager, config);
|
||||||
|
new Thread(() -> {
|
||||||
|
this.eventManager.callEvent(new ClientStartEvent(EventState.POST, System.currentTimeMillis()));
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (this.socket.isConnected() && !this.socket.isClosed() && !this.stopped) {
|
||||||
|
try {
|
||||||
|
int len = this.input.readInt();
|
||||||
|
if (len > 0 && len <= config.getMaxPacketSize()) {
|
||||||
|
byte[] bytes = new byte[len];
|
||||||
|
this.input.readFully(bytes, 0, len);
|
||||||
|
Packet packet = Packet.receivePacket(bytes);
|
||||||
|
this.protocolManager.receivePacket(packet);
|
||||||
|
this.protocolManager.getReceiveTracker().reset();
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
this.eventManager.callEvent(new ClientTimeoutEvent(EventState.POST, System.currentTimeMillis()));
|
||||||
|
this.shutdown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Exception in packet processing thread", e);
|
||||||
|
} finally {
|
||||||
|
this.shutdown();
|
||||||
|
}
|
||||||
|
}, "Packet Processing Thread").start();
|
||||||
|
}
|
||||||
|
} catch (Exception err) {
|
||||||
|
throw new RuntimeException("Failed to start a BasicSocketClient", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void shutdown() {
|
||||||
|
this.stopped = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (this.socket.isConnected() && !this.socket.isClosed()) {
|
||||||
|
this.socket.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.input.close();
|
||||||
|
this.output.close();
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
|
||||||
|
this.eventManager.callEvent(new ClientStopEvent(EventState.POST, System.currentTimeMillis()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getProtocolVersion() {
|
||||||
|
return this.protocolVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getHost() {
|
||||||
|
return this.host;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPort() {
|
||||||
|
return this.port;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ProtocolManager getProtocolManager() {
|
||||||
|
return this.protocolManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
public EventManager getEventManager() {
|
||||||
|
return this.eventManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isStopped() {
|
||||||
|
return this.stopped;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package me.darksidecode.easysockets.client;
|
||||||
|
|
||||||
|
import java.io.DataInputStream;
|
||||||
|
import java.io.DataOutputStream;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.util.List;
|
||||||
|
import me.darksidecode.easysockets.client.config.SocketClientConfig;
|
||||||
|
import me.darksidecode.easysockets.event.EventManager;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
import me.darksidecode.easysockets.event.client.ClientPacketReceiveEvent;
|
||||||
|
import me.darksidecode.easysockets.event.client.ClientPacketSendEvent;
|
||||||
|
import me.darksidecode.easysockets.protocol.packet.Packet;
|
||||||
|
import me.darksidecode.easysockets.util.LimitedList;
|
||||||
|
import me.darksidecode.easysockets.util.Timer;
|
||||||
|
|
||||||
|
public class ProtocolManager {
|
||||||
|
private final Object sendLock = new Object();
|
||||||
|
private final Object receiveLock = new Object();
|
||||||
|
private final List<Packet> recentSent = new LimitedList<>(100);
|
||||||
|
private final List<Packet> recentReceived = new LimitedList<>(100);
|
||||||
|
private final int protocolVersion;
|
||||||
|
private final Socket socket;
|
||||||
|
private final DataInputStream in;
|
||||||
|
private final DataOutputStream out;
|
||||||
|
private final Timer sendTracker = new Timer(0L);
|
||||||
|
private final Timer receiveTracker = new Timer(0L);
|
||||||
|
private final EventManager eventManager;
|
||||||
|
private final SocketClientConfig config;
|
||||||
|
|
||||||
|
public void sendPacket(Packet packet) {
|
||||||
|
synchronized (this.sendLock) {
|
||||||
|
ClientPacketSendEvent e = new ClientPacketSendEvent(EventState.PRE, packet);
|
||||||
|
if (!this.eventManager.callEvent(e)) {
|
||||||
|
packet = e.getPacket();
|
||||||
|
|
||||||
|
try {
|
||||||
|
packet.writeAll();
|
||||||
|
byte[] bytesToSend = packet.send();
|
||||||
|
this.out.writeInt(bytesToSend.length);
|
||||||
|
this.out.write(bytesToSend);
|
||||||
|
this.out.flush();
|
||||||
|
this.recentSent.add(packet);
|
||||||
|
this.sendTracker.reset();
|
||||||
|
this.eventManager.callEvent(new ClientPacketSendEvent(EventState.POST, packet));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("Failed to send packet", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void receivePacket(Packet packet) {
|
||||||
|
ClientPacketReceiveEvent e = new ClientPacketReceiveEvent(EventState.PRE, packet);
|
||||||
|
if (!this.eventManager.callEvent(e)) {
|
||||||
|
(packet = e.getPacket()).process();
|
||||||
|
this.recentReceived.add(packet);
|
||||||
|
this.eventManager.callEvent(new ClientPacketReceiveEvent(EventState.POST, packet));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public ProtocolManager(int protocolVersion, Socket socket, DataInputStream in, DataOutputStream out, EventManager eventManager, SocketClientConfig config) {
|
||||||
|
this.protocolVersion = protocolVersion;
|
||||||
|
this.socket = socket;
|
||||||
|
this.in = in;
|
||||||
|
this.out = out;
|
||||||
|
this.eventManager = eventManager;
|
||||||
|
this.config = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object getSendLock() {
|
||||||
|
return this.sendLock;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object getReceiveLock() {
|
||||||
|
return this.receiveLock;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Packet> getRecentSent() {
|
||||||
|
return this.recentSent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Packet> getRecentReceived() {
|
||||||
|
return this.recentReceived;
|
||||||
|
}
|
||||||
|
|
||||||
|
Timer getSendTracker() {
|
||||||
|
return this.sendTracker;
|
||||||
|
}
|
||||||
|
|
||||||
|
Timer getReceiveTracker() {
|
||||||
|
return this.receiveTracker;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
package me.darksidecode.easysockets.client.config;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
public class SCConfigBuilder {
|
||||||
|
private final SocketClientConfig config = new SocketClientConfig(30000, 65536, 50, 0, false, null, null);
|
||||||
|
|
||||||
|
public SCConfigBuilder timeout(int timeout) {
|
||||||
|
this.config.setTimeout(timeout);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SCConfigBuilder maxPacketSize(int maxPacketSize) {
|
||||||
|
this.config.setMaxPacketSize(maxPacketSize);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SCConfigBuilder sendRateLimit(int sendRateLimit) {
|
||||||
|
this.config.setSendRateLimit(sendRateLimit);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SCConfigBuilder receiveRateLimit(int receive) {
|
||||||
|
this.config.setReceiveRateLimit(receive);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SCConfigBuilder useSSL(boolean use) {
|
||||||
|
this.config.setUseSSL(use);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SCConfigBuilder trustStoreStream(InputStream trustStoreStream) {
|
||||||
|
this.config.setTrustStoreStream(trustStoreStream);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SCConfigBuilder trustStorePassword(String trustStorePassword) {
|
||||||
|
this.config.setTrustStorePassword(trustStorePassword);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SocketClientConfig build() {
|
||||||
|
return this.config;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static SocketClientConfig def() {
|
||||||
|
return new SCConfigBuilder().build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package me.darksidecode.easysockets.client.config;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
|
||||||
|
public class SocketClientConfig {
|
||||||
|
private int timeout;
|
||||||
|
private int maxPacketSize;
|
||||||
|
private int sendRateLimit;
|
||||||
|
private int receiveRateLimit;
|
||||||
|
private boolean useSSL;
|
||||||
|
private InputStream trustStoreStream;
|
||||||
|
private String trustStorePassword;
|
||||||
|
|
||||||
|
public SocketClientConfig(
|
||||||
|
int timeout, int maxPacketSize, int sendRateLimit, int receiveRateLimit, boolean useSSL, InputStream trustStoreStream, String trustStorePassword
|
||||||
|
) {
|
||||||
|
this.timeout = timeout;
|
||||||
|
this.maxPacketSize = maxPacketSize;
|
||||||
|
this.sendRateLimit = sendRateLimit;
|
||||||
|
this.receiveRateLimit = receiveRateLimit;
|
||||||
|
this.useSSL = useSSL;
|
||||||
|
this.trustStoreStream = trustStoreStream;
|
||||||
|
this.trustStorePassword = trustStorePassword;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getTimeout() {
|
||||||
|
return this.timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getMaxPacketSize() {
|
||||||
|
return this.maxPacketSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getSendRateLimit() {
|
||||||
|
return this.sendRateLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getReceiveRateLimit() {
|
||||||
|
return this.receiveRateLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isUseSSL() {
|
||||||
|
return this.useSSL;
|
||||||
|
}
|
||||||
|
|
||||||
|
public InputStream getTrustStoreStream() {
|
||||||
|
return this.trustStoreStream;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTrustStorePassword() {
|
||||||
|
return this.trustStorePassword;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTimeout(int timeout) {
|
||||||
|
this.timeout = timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMaxPacketSize(int maxPacketSize) {
|
||||||
|
this.maxPacketSize = maxPacketSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSendRateLimit(int sendRateLimit) {
|
||||||
|
this.sendRateLimit = sendRateLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setReceiveRateLimit(int receiveRateLimit) {
|
||||||
|
this.receiveRateLimit = receiveRateLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUseSSL(boolean useSSL) {
|
||||||
|
this.useSSL = useSSL;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTrustStoreStream(InputStream trustStoreStream) {
|
||||||
|
this.trustStoreStream = trustStoreStream;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTrustStorePassword(String trustStorePassword) {
|
||||||
|
this.trustStorePassword = trustStorePassword;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package me.darksidecode.easysockets.event;
|
||||||
|
|
||||||
|
public abstract class Event {
|
||||||
|
private final EventState state;
|
||||||
|
private boolean cancelled;
|
||||||
|
|
||||||
|
public boolean isPre() {
|
||||||
|
return this.state == EventState.PRE;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isPost() {
|
||||||
|
return this.state == EventState.POST;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Event(EventState state) {
|
||||||
|
this.state = state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public EventState getState() {
|
||||||
|
return this.state;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isCancelled() {
|
||||||
|
return this.cancelled;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCancelled(boolean cancelled) {
|
||||||
|
this.cancelled = cancelled;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package me.darksidecode.easysockets.event;
|
||||||
|
|
||||||
|
public class EventCancelledException extends RuntimeException {
|
||||||
|
public EventCancelledException() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public EventCancelledException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public EventCancelledException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public EventCancelledException(Throwable cause) {
|
||||||
|
super(cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package me.darksidecode.easysockets.event;
|
||||||
|
|
||||||
|
public class EventException extends RuntimeException {
|
||||||
|
public EventException() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public EventException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public EventException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public EventException(Throwable cause) {
|
||||||
|
super(cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package me.darksidecode.easysockets.event;
|
||||||
|
|
||||||
|
public interface EventListener {
|
||||||
|
void onEvent(Event event);
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package me.darksidecode.easysockets.event;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class EventManager {
|
||||||
|
private final Object registryLock = new Object();
|
||||||
|
private final Object eventLock = new Object();
|
||||||
|
private final List<EventListener> listeners = new ArrayList<>();
|
||||||
|
|
||||||
|
public void registerListener(EventListener listener) {
|
||||||
|
synchronized (this.registryLock) {
|
||||||
|
if (!this.listeners.contains(listener)) {
|
||||||
|
this.listeners.add(listener);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void unregisterListener(EventListener listener) {
|
||||||
|
synchronized (this.registryLock) {
|
||||||
|
this.listeners.remove(listener);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean callEvent(Event e) {
|
||||||
|
try {
|
||||||
|
((ArrayList<EventListener>)((ArrayList<EventListener>)this.listeners).clone()).forEach(listener -> listener.onEvent(e));
|
||||||
|
return e.isCancelled();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new EventException("Error processing event " + e.getClass().getSimpleName() + "/" + e.getState().name(), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package me.darksidecode.easysockets.event;
|
||||||
|
|
||||||
|
public enum EventState {
|
||||||
|
PRE,
|
||||||
|
POST;
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
package me.darksidecode.easysockets.event.client;
|
||||||
|
|
||||||
|
import me.darksidecode.easysockets.event.Event;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
|
||||||
|
public class ClientKeyExchangeCompleteEvent extends Event {
|
||||||
|
public ClientKeyExchangeCompleteEvent() {
|
||||||
|
super(EventState.POST);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package me.darksidecode.easysockets.event.client;
|
||||||
|
|
||||||
|
import me.darksidecode.easysockets.event.Event;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
import me.darksidecode.easysockets.protocol.packet.Packet;
|
||||||
|
|
||||||
|
public class ClientPacketReceiveEvent extends Event {
|
||||||
|
private Packet packet;
|
||||||
|
|
||||||
|
public ClientPacketReceiveEvent(EventState state, Packet packet) {
|
||||||
|
super(state);
|
||||||
|
this.packet = packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Packet getPacket() {
|
||||||
|
return this.packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPacket(Packet packet) {
|
||||||
|
this.packet = packet;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package me.darksidecode.easysockets.event.client;
|
||||||
|
|
||||||
|
import me.darksidecode.easysockets.event.Event;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
import me.darksidecode.easysockets.protocol.packet.Packet;
|
||||||
|
|
||||||
|
public class ClientPacketSendEvent extends Event {
|
||||||
|
private Packet packet;
|
||||||
|
|
||||||
|
public ClientPacketSendEvent(EventState state, Packet packet) {
|
||||||
|
super(state);
|
||||||
|
this.packet = packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Packet getPacket() {
|
||||||
|
return this.packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPacket(Packet packet) {
|
||||||
|
this.packet = packet;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package me.darksidecode.easysockets.event.client;
|
||||||
|
|
||||||
|
import me.darksidecode.easysockets.event.Event;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
|
||||||
|
public class ClientStartEvent extends Event {
|
||||||
|
private final long time;
|
||||||
|
|
||||||
|
public ClientStartEvent(EventState state, long time) {
|
||||||
|
super(state);
|
||||||
|
this.time = time;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getTime() {
|
||||||
|
return this.time;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package me.darksidecode.easysockets.event.client;
|
||||||
|
|
||||||
|
import me.darksidecode.easysockets.event.Event;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
|
||||||
|
public class ClientStopEvent extends Event {
|
||||||
|
private final long time;
|
||||||
|
|
||||||
|
public ClientStopEvent(EventState state, long time) {
|
||||||
|
super(state);
|
||||||
|
this.time = time;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getTime() {
|
||||||
|
return this.time;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package me.darksidecode.easysockets.event.client;
|
||||||
|
|
||||||
|
import me.darksidecode.easysockets.event.Event;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
|
||||||
|
public class ClientTimeoutEvent extends Event {
|
||||||
|
private final long time;
|
||||||
|
|
||||||
|
public ClientTimeoutEvent(EventState state, long time) {
|
||||||
|
super(state);
|
||||||
|
this.time = time;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getTime() {
|
||||||
|
return this.time;
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package me.darksidecode.easysockets.event.server;
|
||||||
|
|
||||||
|
import java.net.Socket;
|
||||||
|
import me.darksidecode.easysockets.event.Event;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
|
||||||
|
public class ServerKeyExchangeCompleteEvent extends Event {
|
||||||
|
private final Socket client;
|
||||||
|
|
||||||
|
public ServerKeyExchangeCompleteEvent(Socket client) {
|
||||||
|
super(EventState.POST);
|
||||||
|
this.client = client;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Socket getClient() {
|
||||||
|
return this.client;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package me.darksidecode.easysockets.event.server;
|
||||||
|
|
||||||
|
import me.darksidecode.easysockets.event.Event;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
|
||||||
|
public class ServerStartEvent extends Event {
|
||||||
|
private final long time;
|
||||||
|
|
||||||
|
public ServerStartEvent(EventState state, long time) {
|
||||||
|
super(state);
|
||||||
|
this.time = time;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getTime() {
|
||||||
|
return this.time;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package me.darksidecode.easysockets.event.server;
|
||||||
|
|
||||||
|
import me.darksidecode.easysockets.event.Event;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
|
||||||
|
public class ServerStopEvent extends Event {
|
||||||
|
private final long time;
|
||||||
|
|
||||||
|
public ServerStopEvent(EventState state, long time) {
|
||||||
|
super(state);
|
||||||
|
this.time = time;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getTime() {
|
||||||
|
return this.time;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package me.darksidecode.easysockets.event.server.socket;
|
||||||
|
|
||||||
|
import java.net.Socket;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
|
||||||
|
public class SocketConnectEvent extends SocketEvent {
|
||||||
|
public SocketConnectEvent(EventState state, Socket socket) {
|
||||||
|
super(state, socket);
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
package me.darksidecode.easysockets.event.server.socket;
|
||||||
|
|
||||||
|
import java.net.Socket;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
|
||||||
|
public class SocketDisconnectEvent extends SocketEvent {
|
||||||
|
public SocketDisconnectEvent(EventState state, Socket socket) {
|
||||||
|
super(state, socket);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package me.darksidecode.easysockets.event.server.socket;
|
||||||
|
|
||||||
|
import java.net.Socket;
|
||||||
|
import me.darksidecode.easysockets.event.Event;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
|
||||||
|
public class SocketEvent extends Event {
|
||||||
|
private final Socket socket;
|
||||||
|
|
||||||
|
public SocketEvent(EventState state, Socket socket) {
|
||||||
|
super(state);
|
||||||
|
this.socket = socket;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Socket getSocket() {
|
||||||
|
return this.socket;
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package me.darksidecode.easysockets.event.server.socket;
|
||||||
|
|
||||||
|
import java.net.Socket;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
import me.darksidecode.easysockets.protocol.packet.Packet;
|
||||||
|
|
||||||
|
public class SocketPacketReceiveEvent extends SocketEvent {
|
||||||
|
private Packet packet;
|
||||||
|
|
||||||
|
public SocketPacketReceiveEvent(EventState state, Socket socket, Packet packet) {
|
||||||
|
super(state, socket);
|
||||||
|
this.packet = packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Packet getPacket() {
|
||||||
|
return this.packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPacket(Packet packet) {
|
||||||
|
this.packet = packet;
|
||||||
|
}
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package me.darksidecode.easysockets.event.server.socket;
|
||||||
|
|
||||||
|
import java.net.Socket;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
import me.darksidecode.easysockets.protocol.packet.Packet;
|
||||||
|
|
||||||
|
public class SocketPacketSendEvent extends SocketEvent {
|
||||||
|
private Packet packet;
|
||||||
|
|
||||||
|
public SocketPacketSendEvent(EventState state, Socket socket, Packet packet) {
|
||||||
|
super(state, socket);
|
||||||
|
this.packet = packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Packet getPacket() {
|
||||||
|
return this.packet;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPacket(Packet packet) {
|
||||||
|
this.packet = packet;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package me.darksidecode.easysockets.protocol.packet;
|
||||||
|
|
||||||
|
import me.darksidecode.easysockets.protocol.processing.PacketProcessing;
|
||||||
|
import me.darksidecode.easysockets.util.io.IO;
|
||||||
|
|
||||||
|
public class Packet {
|
||||||
|
private PacketContents contents;
|
||||||
|
private final String type;
|
||||||
|
|
||||||
|
public Packet(String type) {
|
||||||
|
this(type, new PacketContents());
|
||||||
|
}
|
||||||
|
|
||||||
|
public Packet(String type, PacketContents contents) {
|
||||||
|
this.type = type;
|
||||||
|
this.contents = contents;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean process() {
|
||||||
|
return PacketProcessing.process(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Packet setContents(PacketContents contents) {
|
||||||
|
this.contents = contents;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] send() {
|
||||||
|
return sendPacket(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Packet receive(byte[] in) {
|
||||||
|
RawPacket raw = receiveRaw(in);
|
||||||
|
if (!raw.getType().equals(this.type)) {
|
||||||
|
throw new PacketSignatureError("Packet type mismatch: " + raw.getType() + ", expected " + this.type);
|
||||||
|
} else {
|
||||||
|
return this.setContents(new PacketContents(raw.getContents()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Packet writeAll() {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Packet readAll() {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] sendPacket(Packet p) {
|
||||||
|
return IO.ser(new RawPacket(p.getType(), p.getContents().getRaw()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.type + this.contents.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Packet receivePacket(byte[] in) {
|
||||||
|
RawPacket raw = receiveRaw(in);
|
||||||
|
return new Packet(raw.getType(), new PacketContents(raw.getContents()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static RawPacket receiveRaw(byte[] in) {
|
||||||
|
Object obj = IO.deser(in);
|
||||||
|
if (obj != null && obj instanceof RawPacket) {
|
||||||
|
return (RawPacket)obj;
|
||||||
|
} else {
|
||||||
|
throw new PacketSignatureError("Invalid packet received");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public PacketContents getContents() {
|
||||||
|
return this.contents;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getType() {
|
||||||
|
return this.type;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
package me.darksidecode.easysockets.protocol.packet;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
public class PacketContents {
|
||||||
|
private final Map<Integer, Object> raw;
|
||||||
|
|
||||||
|
public PacketContents() {
|
||||||
|
this(new ConcurrentHashMap<>());
|
||||||
|
}
|
||||||
|
|
||||||
|
public PacketContents(Map<Integer, Object> source) {
|
||||||
|
this.raw = source;
|
||||||
|
}
|
||||||
|
|
||||||
|
public PacketContents write(int index, Object obj) {
|
||||||
|
if (obj == null) {
|
||||||
|
throw new NullPointerException("Cannot write NULL object");
|
||||||
|
} else {
|
||||||
|
this.raw.put(index, obj);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String readString(int index) {
|
||||||
|
return this.read(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String readStringSafely(int index) {
|
||||||
|
return this.readSafely(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer readInteger(int index) {
|
||||||
|
return this.read(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer readIntegerSafely(int index) {
|
||||||
|
return this.readSafely(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Short readShort(int index) {
|
||||||
|
return this.read(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Short readShortSafely(int index) {
|
||||||
|
return this.readSafely(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long readLong(int index) {
|
||||||
|
return this.read(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long readLongSafely(int index) {
|
||||||
|
return this.readSafely(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Double readDouble(int index) {
|
||||||
|
return this.read(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Double readDoubleSafely(int index) {
|
||||||
|
return this.readSafely(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Float readFloat(int index) {
|
||||||
|
return this.read(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Float readFloatSafely(int index) {
|
||||||
|
return this.readSafely(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Byte readByte(int index) {
|
||||||
|
return this.read(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Byte readByteSafely(int index) {
|
||||||
|
return this.readSafely(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean readBoolean(int index) {
|
||||||
|
return this.read(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean readBooleanSafely(int index) {
|
||||||
|
return this.readSafely(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object readObject(int index) {
|
||||||
|
return this.read(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object readObjectSafely(int index) {
|
||||||
|
return this.readSafely(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> T read(int index) {
|
||||||
|
return (T)this.readRaw(index);
|
||||||
|
}
|
||||||
|
|
||||||
|
public <T> T readSafely(int index) {
|
||||||
|
Object obj = this.readRawSafely(index);
|
||||||
|
return (T)(obj == null ? null : obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object readRaw(int index) {
|
||||||
|
if (!this.raw.containsKey(index)) {
|
||||||
|
throw new IndexOutOfBoundsException("Index out of packet content range: " + index);
|
||||||
|
} else {
|
||||||
|
return this.raw.get(index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Object readRawSafely(int index) {
|
||||||
|
return this.raw.getOrDefault(index, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Class getClass(int index) {
|
||||||
|
Object obj = this.readRawSafely(index);
|
||||||
|
return obj == null ? null : obj.getClass();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
StringBuilder s = new StringBuilder();
|
||||||
|
s.append('[');
|
||||||
|
|
||||||
|
for (Integer k : this.raw.keySet()) {
|
||||||
|
s.append(k).append(": ").append(this.raw.get(k).toString()).append(',');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (s.length() > 1) {
|
||||||
|
s.deleteCharAt(s.length() - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
s.append(']');
|
||||||
|
return s.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<Integer, Object> getRaw() {
|
||||||
|
return this.raw;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package me.darksidecode.easysockets.protocol.packet;
|
||||||
|
|
||||||
|
public class PacketSignatureError extends RuntimeException {
|
||||||
|
public PacketSignatureError() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public PacketSignatureError(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public PacketSignatureError(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public PacketSignatureError(Throwable cause) {
|
||||||
|
super(cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package me.darksidecode.easysockets.protocol.packet;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public class RawPacket implements Serializable {
|
||||||
|
private static final long serialVersionUID = 331896648141185773L;
|
||||||
|
private final String type;
|
||||||
|
private final Map<Integer, Object> contents;
|
||||||
|
|
||||||
|
public RawPacket(String type, Map<Integer, Object> contents) {
|
||||||
|
this.type = type;
|
||||||
|
this.contents = contents;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getType() {
|
||||||
|
return this.type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<Integer, Object> getContents() {
|
||||||
|
return this.contents;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package me.darksidecode.easysockets.protocol.processing;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import me.darksidecode.easysockets.protocol.packet.Packet;
|
||||||
|
|
||||||
|
public class PacketProcessing {
|
||||||
|
private static final Map<String, PacketProcessor> processors = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
public static boolean process(Packet packet) {
|
||||||
|
PacketProcessor pp = processors.get(packet.getType());
|
||||||
|
return pp == null ? false : pp.process(packet);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setProcessor(String type, PacketProcessor pp) {
|
||||||
|
processors.put(type, pp);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package me.darksidecode.easysockets.protocol.processing;
|
||||||
|
|
||||||
|
import me.darksidecode.easysockets.protocol.packet.Packet;
|
||||||
|
|
||||||
|
public interface PacketProcessor {
|
||||||
|
boolean process(Packet packet);
|
||||||
|
}
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
package me.darksidecode.easysockets.server;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.security.Security;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.Timer;
|
||||||
|
import java.util.TimerTask;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import javax.net.ServerSocketFactory;
|
||||||
|
import javax.net.ssl.SSLServerSocket;
|
||||||
|
import javax.net.ssl.SSLServerSocketFactory;
|
||||||
|
import me.darksidecode.easysockets.event.EventCancelledException;
|
||||||
|
import me.darksidecode.easysockets.event.EventManager;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
import me.darksidecode.easysockets.event.server.ServerStartEvent;
|
||||||
|
import me.darksidecode.easysockets.event.server.ServerStopEvent;
|
||||||
|
import me.darksidecode.easysockets.server.config.SocketServerConfig;
|
||||||
|
import org.bouncycastle.jce.provider.BouncyCastleProvider;
|
||||||
|
|
||||||
|
public class BasicSocketServer {
|
||||||
|
private static final long KICK_FREQ = TimeUnit.MINUTES.toMillis(1L);
|
||||||
|
private final Object kickQueueLock = new Object();
|
||||||
|
private final int protocolVersion;
|
||||||
|
private final int port;
|
||||||
|
private final ServerSocket serverSocket;
|
||||||
|
private final ProtocolManager protocolManager;
|
||||||
|
private final EventManager eventManager;
|
||||||
|
private final SocketServerConfig config;
|
||||||
|
private final Map<Socket, SocketListener> socketListeners = new ConcurrentHashMap<>();
|
||||||
|
private final Set<Socket> kickQueue = new HashSet<>();
|
||||||
|
private final int maxConnections;
|
||||||
|
private final ServerStats stats;
|
||||||
|
|
||||||
|
@Deprecated
|
||||||
|
public BasicSocketServer(int protocolVersion, int port, int backlog, int maxConnections, Object __, SocketServerConfig config) {
|
||||||
|
this(protocolVersion, port, backlog, maxConnections, config);
|
||||||
|
}
|
||||||
|
|
||||||
|
public BasicSocketServer(int protocolVersion, int port, int backlog, int maxConnections, SocketServerConfig config) {
|
||||||
|
if ((this.eventManager = new EventManager()).callEvent(new ServerStartEvent(EventState.PRE, System.currentTimeMillis()))) {
|
||||||
|
throw new EventCancelledException("Server startup aborted");
|
||||||
|
} else {
|
||||||
|
if (config.isUseSSL()) {
|
||||||
|
File keyStoreFile = new File(config.getPathToKeyStore());
|
||||||
|
if (!keyStoreFile.exists()) {
|
||||||
|
throw new RuntimeException("KeyStore file does not exist: " + keyStoreFile.getAbsolutePath());
|
||||||
|
}
|
||||||
|
|
||||||
|
Security.addProvider(new BouncyCastleProvider());
|
||||||
|
System.setProperty("javax.net.ssl.keyStore", keyStoreFile.getAbsolutePath());
|
||||||
|
System.setProperty("javax.net.ssl.keyStorePassword", config.getKeyStorePassword());
|
||||||
|
}
|
||||||
|
|
||||||
|
this.protocolVersion = protocolVersion;
|
||||||
|
this.port = port;
|
||||||
|
this.maxConnections = maxConnections;
|
||||||
|
this.config = config;
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.serverSocket = config.isUseSSL()
|
||||||
|
? SSLServerSocketFactory.getDefault().createServerSocket()
|
||||||
|
: ServerSocketFactory.getDefault().createServerSocket();
|
||||||
|
this.stats = new ServerStats(System.currentTimeMillis());
|
||||||
|
this.protocolManager = new ProtocolManager(this, protocolVersion, this.serverSocket, this.stats, this.eventManager, config);
|
||||||
|
if (config.isUseSSL()) {
|
||||||
|
List<String> ciphers = new ArrayList<>(
|
||||||
|
Arrays.asList(
|
||||||
|
"TLS_RSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_RSA_WITH_AES_256_CBC_SHA256",
|
||||||
|
"TLS_DH_RSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_DH_RSA_WITH_AES_256_CBC_SHA256",
|
||||||
|
"TLS_RSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_RSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_DH_RSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_DH_RSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
|
||||||
|
"TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384",
|
||||||
|
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
|
||||||
|
"TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256",
|
||||||
|
"TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384",
|
||||||
|
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
|
||||||
|
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
|
||||||
|
"TLS_AES_128_CCM_SHA256",
|
||||||
|
"TLS_AES_128_GCM_SHA256",
|
||||||
|
"TLS_AES_256_GCM_SHA384",
|
||||||
|
"TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
|
||||||
|
"TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
|
||||||
|
"TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
|
||||||
|
"TLS_CHACHA20_POLY1305_SHA256"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
ciphers.retainAll(Arrays.asList(((SSLServerSocketFactory)SSLServerSocketFactory.getDefault()).getSupportedCipherSuites()));
|
||||||
|
((SSLServerSocket)this.serverSocket).setEnabledCipherSuites(ciphers.toArray(new String[0]));
|
||||||
|
((SSLServerSocket)this.serverSocket).setEnabledProtocols(new String[]{"TLSv1.2"});
|
||||||
|
}
|
||||||
|
|
||||||
|
this.serverSocket.bind(new InetSocketAddress("0.0.0.0", this.port), backlog);
|
||||||
|
new Thread(() -> {
|
||||||
|
new Timer().schedule(new TimerTask() {
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
synchronized (BasicSocketServer.this.kickQueueLock) {
|
||||||
|
BasicSocketServer.this.kickQueue.forEach(x$0 -> BasicSocketServer.this.kick0(x$0));
|
||||||
|
BasicSocketServer.this.kickQueue.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, KICK_FREQ, KICK_FREQ);
|
||||||
|
this.eventManager.callEvent(new ServerStartEvent(EventState.POST, System.currentTimeMillis()));
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (!this.serverSocket.isClosed()) {
|
||||||
|
try {
|
||||||
|
if (this.socketListeners.keySet().size() < maxConnections) {
|
||||||
|
Socket client = this.serverSocket.accept();
|
||||||
|
SocketListener listener = new SocketListener(this, client, this.protocolManager, this.stats, this.eventManager, config);
|
||||||
|
this.socketListeners.put(client, listener);
|
||||||
|
listener.start();
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
if (!(ex instanceof EventCancelledException)) {
|
||||||
|
System.err.println("[EasySockets] Error accepting new socket connection");
|
||||||
|
ex.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("Exception starting packet processing thread", e);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.shutdown();
|
||||||
|
}, "Packet Processing Thread").start();
|
||||||
|
} catch (Exception cause) {
|
||||||
|
throw new RuntimeException("Failed to start a BasicSocketServer", cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void kick0(Socket s) {
|
||||||
|
SocketListener listener = this.socketListeners.get(s);
|
||||||
|
if (listener != null) {
|
||||||
|
this.socketListeners.remove(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void addToKickQueue(Socket s) {
|
||||||
|
synchronized (this.kickQueue) {
|
||||||
|
this.kickQueue.add(s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void kick(Socket s) {
|
||||||
|
SocketListener listener = this.socketListeners.get(s);
|
||||||
|
if (listener != null) {
|
||||||
|
this.socketListeners.remove(s);
|
||||||
|
listener.endQuietly();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void shutdown() {
|
||||||
|
try {
|
||||||
|
if (!this.serverSocket.isClosed()) {
|
||||||
|
this.serverSocket.close();
|
||||||
|
}
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
|
||||||
|
this.eventManager.callEvent(new ServerStopEvent(EventState.POST, System.currentTimeMillis()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getProtocolVersion() {
|
||||||
|
return this.protocolVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getPort() {
|
||||||
|
return this.port;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ProtocolManager getProtocolManager() {
|
||||||
|
return this.protocolManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
public EventManager getEventManager() {
|
||||||
|
return this.eventManager;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SocketServerConfig getConfig() {
|
||||||
|
return this.config;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<Socket, SocketListener> getSocketListeners() {
|
||||||
|
return this.socketListeners;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Set<Socket> getKickQueue() {
|
||||||
|
return this.kickQueue;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getMaxConnections() {
|
||||||
|
return this.maxConnections;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ServerStats getStats() {
|
||||||
|
return this.stats;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
package me.darksidecode.easysockets.server;
|
||||||
|
|
||||||
|
import java.io.DataOutputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.ServerSocket;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.net.SocketException;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
import me.darksidecode.easysockets.event.EventManager;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
import me.darksidecode.easysockets.event.server.socket.SocketDisconnectEvent;
|
||||||
|
import me.darksidecode.easysockets.event.server.socket.SocketPacketReceiveEvent;
|
||||||
|
import me.darksidecode.easysockets.event.server.socket.SocketPacketSendEvent;
|
||||||
|
import me.darksidecode.easysockets.protocol.packet.Packet;
|
||||||
|
import me.darksidecode.easysockets.server.config.SocketServerConfig;
|
||||||
|
import me.darksidecode.easysockets.util.LimitedList;
|
||||||
|
import me.darksidecode.easysockets.util.Timer;
|
||||||
|
import me.darksidecode.easysockets.util.io.Compressor;
|
||||||
|
|
||||||
|
public class ProtocolManager {
|
||||||
|
private final BasicSocketServer server;
|
||||||
|
private final Map<Socket, Object> sendLocks = new ConcurrentHashMap<>();
|
||||||
|
private final Map<Socket, Object> receiveLocks = new ConcurrentHashMap<>();
|
||||||
|
private final Map<Socket, DataOutputStream> dosMap = new ConcurrentHashMap<>();
|
||||||
|
private final List<Packet> recentSent = new LimitedList<>(100);
|
||||||
|
private final List<Packet> recentReceived = new LimitedList<>(100);
|
||||||
|
private final int protocolVersion;
|
||||||
|
private final ServerSocket socket;
|
||||||
|
private final ServerStats stats;
|
||||||
|
private final Map<Socket, Timer> sendTrackers = new ConcurrentHashMap<>();
|
||||||
|
private final Map<Socket, Timer> receiveTrackers = new ConcurrentHashMap<>();
|
||||||
|
private final EventManager eventManager;
|
||||||
|
private final SocketServerConfig config;
|
||||||
|
|
||||||
|
public void sendPacketSynchronouslyLazily(Socket target, Packet packet) {
|
||||||
|
if (target.isClosed()) {
|
||||||
|
this.socketDisconnected(target);
|
||||||
|
} else {
|
||||||
|
SocketListener listenerThread = this.server.getSocketListeners().get(target);
|
||||||
|
if (listenerThread != null) {
|
||||||
|
listenerThread.addToSyncLazySendQueue(packet);
|
||||||
|
} else {
|
||||||
|
System.err
|
||||||
|
.println(
|
||||||
|
"Unable to send packet "
|
||||||
|
+ packet.toString()
|
||||||
|
+ " synchronously lazily to "
|
||||||
|
+ target.getInetAddress().getHostAddress()
|
||||||
|
+ ": no listener thread bound"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void sendPacket(Socket target, Packet packet) {
|
||||||
|
if (target.isClosed()) {
|
||||||
|
this.socketDisconnected(target);
|
||||||
|
} else {
|
||||||
|
Timer sendTracker = this.getSendTracker(target);
|
||||||
|
SocketPacketSendEvent e = new SocketPacketSendEvent(EventState.PRE, target, packet);
|
||||||
|
if (!this.eventManager.callEvent(e)) {
|
||||||
|
packet = e.getPacket();
|
||||||
|
long debugId = System.nanoTime() % 1000L;
|
||||||
|
long beginTime = System.currentTimeMillis();
|
||||||
|
|
||||||
|
try {
|
||||||
|
packet.writeAll();
|
||||||
|
long serBegin = System.currentTimeMillis();
|
||||||
|
byte[] bytesToSend = packet.send();
|
||||||
|
long serEnd = System.currentTimeMillis();
|
||||||
|
|
||||||
|
try {
|
||||||
|
long dosBegin = System.currentTimeMillis();
|
||||||
|
DataOutputStream dataOut = this.getDataOutputStream(target);
|
||||||
|
long dosEnd = System.currentTimeMillis();
|
||||||
|
if (dataOut == null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
long wintBegin = System.currentTimeMillis();
|
||||||
|
dataOut.writeInt(bytesToSend.length);
|
||||||
|
long wintEnd = System.currentTimeMillis();
|
||||||
|
long wbytesBegin = System.currentTimeMillis();
|
||||||
|
dataOut.write(bytesToSend);
|
||||||
|
long wbytesEnd = System.currentTimeMillis();
|
||||||
|
dataOut.flush();
|
||||||
|
this.stats.bytesSent += (long)bytesToSend.length;
|
||||||
|
long endTime = System.currentTimeMillis();
|
||||||
|
long elapsed = endTime - beginTime;
|
||||||
|
} catch (SocketException ignored) {
|
||||||
|
this.socketDisconnected(target);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.recentSent.add(packet);
|
||||||
|
sendTracker.reset();
|
||||||
|
this.eventManager.callEvent(new SocketPacketSendEvent(EventState.POST, target, packet));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
System.err.println("### pain in the ass ###");
|
||||||
|
System.err.println("socket: " + target.getInetAddress().getHostAddress() + ", packet: " + packet.toString() + ", stacktrace:");
|
||||||
|
ex.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void receivePacket(Socket sender, Packet packet) {
|
||||||
|
SocketPacketReceiveEvent e = new SocketPacketReceiveEvent(EventState.PRE, sender, packet);
|
||||||
|
if (!this.eventManager.callEvent(e)) {
|
||||||
|
(packet = e.getPacket()).process();
|
||||||
|
this.recentReceived.add(packet);
|
||||||
|
this.eventManager.callEvent(new SocketPacketReceiveEvent(EventState.POST, sender, packet));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void socketDisconnected(Socket s) {
|
||||||
|
this.receiveTrackers.remove(s);
|
||||||
|
this.receiveLocks.remove(s);
|
||||||
|
this.sendTrackers.remove(s);
|
||||||
|
this.sendLocks.remove(s);
|
||||||
|
this.dosMap.remove(s);
|
||||||
|
this.eventManager.callEvent(new SocketDisconnectEvent(EventState.POST, s));
|
||||||
|
}
|
||||||
|
|
||||||
|
private DataOutputStream getDataOutputStream(Socket s) {
|
||||||
|
return this.dosMap.computeIfAbsent(s, k -> {
|
||||||
|
try {
|
||||||
|
return new DataOutputStream(Compressor.newDeflateOutput(s.getOutputStream()));
|
||||||
|
} catch (SocketException ignored) {
|
||||||
|
this.socketDisconnected(s);
|
||||||
|
return null;
|
||||||
|
} catch (IOException ex) {
|
||||||
|
throw new RuntimeException("Failed to obtain DOS of " + s.getInetAddress().getHostAddress(), ex);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Timer getSendTracker(Socket s) {
|
||||||
|
return this.sendTrackers.computeIfAbsent(s, k -> new Timer());
|
||||||
|
}
|
||||||
|
|
||||||
|
Timer getReceiveTracker(Socket s) {
|
||||||
|
return this.receiveTrackers.computeIfAbsent(s, k -> new Timer(0L));
|
||||||
|
}
|
||||||
|
|
||||||
|
public ProtocolManager(
|
||||||
|
BasicSocketServer server, int protocolVersion, ServerSocket socket, ServerStats stats, EventManager eventManager, SocketServerConfig config
|
||||||
|
) {
|
||||||
|
this.server = server;
|
||||||
|
this.protocolVersion = protocolVersion;
|
||||||
|
this.socket = socket;
|
||||||
|
this.stats = stats;
|
||||||
|
this.eventManager = eventManager;
|
||||||
|
this.config = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<Socket, Object> getSendLocks() {
|
||||||
|
return this.sendLocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<Socket, Object> getReceiveLocks() {
|
||||||
|
return this.receiveLocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<Socket, DataOutputStream> getDosMap() {
|
||||||
|
return this.dosMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Packet> getRecentSent() {
|
||||||
|
return this.recentSent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Packet> getRecentReceived() {
|
||||||
|
return this.recentReceived;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<Socket, Timer> getSendTrackers() {
|
||||||
|
return this.sendTrackers;
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<Socket, Timer> getReceiveTrackers() {
|
||||||
|
return this.receiveTrackers;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package me.darksidecode.easysockets.server;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
|
||||||
|
public class ServerStats implements Serializable {
|
||||||
|
private static final long serialVersionUID = 2770526316580474952L;
|
||||||
|
public final long startTime;
|
||||||
|
public volatile long bytesSent;
|
||||||
|
public volatile long bytesReceived;
|
||||||
|
public volatile long connectionsRegistered;
|
||||||
|
|
||||||
|
public ServerStats(long startTime) {
|
||||||
|
this.startTime = startTime;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
package me.darksidecode.easysockets.server;
|
||||||
|
|
||||||
|
import java.io.DataInputStream;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.Socket;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import me.darksidecode.easysockets.event.EventCancelledException;
|
||||||
|
import me.darksidecode.easysockets.event.EventManager;
|
||||||
|
import me.darksidecode.easysockets.event.EventState;
|
||||||
|
import me.darksidecode.easysockets.event.server.socket.SocketConnectEvent;
|
||||||
|
import me.darksidecode.easysockets.protocol.packet.Packet;
|
||||||
|
import me.darksidecode.easysockets.server.config.SocketServerConfig;
|
||||||
|
import me.darksidecode.easysockets.util.io.Compressor;
|
||||||
|
|
||||||
|
class SocketListener extends Thread {
|
||||||
|
private final BasicSocketServer server;
|
||||||
|
private final Socket socket;
|
||||||
|
private final EventManager eventManager;
|
||||||
|
private final ProtocolManager protocolManager;
|
||||||
|
private final ServerStats stats;
|
||||||
|
private final SocketServerConfig config;
|
||||||
|
private boolean closed;
|
||||||
|
private boolean error;
|
||||||
|
private final List<Packet> syncLazySendQueue = new ArrayList<>();
|
||||||
|
private final Object syncLazySendQueueLock = new Object();
|
||||||
|
|
||||||
|
SocketListener(
|
||||||
|
BasicSocketServer server, Socket socket, ProtocolManager protocolManager, ServerStats stats, EventManager eventManager, SocketServerConfig config
|
||||||
|
) throws IOException {
|
||||||
|
this.setName(socket.getInetAddress().getHostName() + " Socket Listener Thread #" + System.nanoTime());
|
||||||
|
this.server = server;
|
||||||
|
this.socket = socket;
|
||||||
|
this.config = config;
|
||||||
|
this.eventManager = eventManager;
|
||||||
|
this.protocolManager = protocolManager;
|
||||||
|
this.stats = stats;
|
||||||
|
if (eventManager.callEvent(new SocketConnectEvent(EventState.PRE, socket))) {
|
||||||
|
if (!socket.isClosed()) {
|
||||||
|
socket.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new EventCancelledException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void run() {
|
||||||
|
this.establishConnection();
|
||||||
|
|
||||||
|
try {
|
||||||
|
DataInputStream in = new DataInputStream(Compressor.newInflateInput(this.socket.getInputStream()));
|
||||||
|
|
||||||
|
while (this.socket.isConnected() && !this.socket.isClosed() && !this.closed) {
|
||||||
|
int len = in.readInt();
|
||||||
|
if (len > 0 && len <= this.config.getMaxPacketSize()) {
|
||||||
|
byte[] bytes = new byte[len];
|
||||||
|
in.readFully(bytes, 0, len);
|
||||||
|
this.stats.bytesReceived += (long)bytes.length;
|
||||||
|
Packet packet = Packet.receivePacket(bytes);
|
||||||
|
this.protocolManager.receivePacket(this.socket, packet);
|
||||||
|
}
|
||||||
|
|
||||||
|
synchronized (this.syncLazySendQueueLock) {
|
||||||
|
int i = 0;
|
||||||
|
|
||||||
|
for (Packet packet : this.syncLazySendQueue) {
|
||||||
|
try {
|
||||||
|
this.protocolManager.sendPacket(this.socket, packet);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
System.err
|
||||||
|
.println(
|
||||||
|
"Failed to send packet "
|
||||||
|
+ packet.toString()
|
||||||
|
+ " (index "
|
||||||
|
+ i
|
||||||
|
+ ") synchronously to "
|
||||||
|
+ this.socket.getInetAddress().getHostAddress()
|
||||||
|
+ " (through socket listener thread: "
|
||||||
|
+ this.getName()
|
||||||
|
+ "). Stacktrace:"
|
||||||
|
);
|
||||||
|
ex.printStackTrace();
|
||||||
|
} finally {
|
||||||
|
i++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.syncLazySendQueue.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.error && !this.closed) {
|
||||||
|
this.end(null);
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
this.end(new RuntimeException("Exception in " + this.getName(), e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void addToSyncLazySendQueue(Packet packet) {
|
||||||
|
synchronized (this.syncLazySendQueueLock) {
|
||||||
|
this.syncLazySendQueue.add(packet);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void establishConnection() {
|
||||||
|
try {
|
||||||
|
this.socket.setSoTimeout(this.config.getTimeout());
|
||||||
|
this.stats.connectionsRegistered++;
|
||||||
|
this.protocolManager.getReceiveLocks().put(this.socket, new Object());
|
||||||
|
this.protocolManager.getSendLocks().put(this.socket, new Object());
|
||||||
|
this.socket.setTcpNoDelay(true);
|
||||||
|
this.socket.setKeepAlive(true);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("Failed to setup a socket listener", ex);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.eventManager.callEvent(new SocketConnectEvent(EventState.POST, this.socket));
|
||||||
|
}
|
||||||
|
|
||||||
|
void end(Throwable problem) {
|
||||||
|
if (!this.closed || problem != null) {
|
||||||
|
this.error = problem != null;
|
||||||
|
this.closed = true;
|
||||||
|
if (this.error) {
|
||||||
|
problem.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.socket.isClosed()) {
|
||||||
|
try {
|
||||||
|
this.socket.close();
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.protocolManager.socketDisconnected(this.socket);
|
||||||
|
this.server.addToKickQueue(this.socket);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void endQuietly() {
|
||||||
|
this.closed = true;
|
||||||
|
if (!this.socket.isClosed()) {
|
||||||
|
try {
|
||||||
|
this.socket.close();
|
||||||
|
} catch (Exception ignoredEx) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.protocolManager.socketDisconnected(this.socket);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isClosed() {
|
||||||
|
return this.closed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isError() {
|
||||||
|
return this.error;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setClosed(boolean closed) {
|
||||||
|
this.closed = closed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setError(boolean error) {
|
||||||
|
this.error = error;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package me.darksidecode.easysockets.server.config;
|
||||||
|
|
||||||
|
public class SSConfigBuilder {
|
||||||
|
private final SocketServerConfig config = new SocketServerConfig(30000, 65536, 50, 0, false, null, null);
|
||||||
|
|
||||||
|
public SSConfigBuilder timeout(int timeout) {
|
||||||
|
this.config.setTimeout(timeout);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SSConfigBuilder maxPacketSize(int maxPacketSize) {
|
||||||
|
this.config.setMaxPacketSize(maxPacketSize);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SSConfigBuilder sendRateLimit(int sendRateLimit) {
|
||||||
|
this.config.setSendRateLimit(sendRateLimit);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SSConfigBuilder receiveRateLimit(int receive) {
|
||||||
|
this.config.setReceiveRateLimit(receive);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SSConfigBuilder useSSL(boolean use) {
|
||||||
|
this.config.setUseSSL(use);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SSConfigBuilder pathToKeyStore(String pathToKeyStore) {
|
||||||
|
this.config.setPathToKeyStore(pathToKeyStore);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SSConfigBuilder keyStorePassword(String keyStorePassword) {
|
||||||
|
this.config.setKeyStorePassword(keyStorePassword);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public SocketServerConfig build() {
|
||||||
|
return this.config;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static SocketServerConfig def() {
|
||||||
|
return new SSConfigBuilder().build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
package me.darksidecode.easysockets.server.config;
|
||||||
|
|
||||||
|
public class SocketServerConfig {
|
||||||
|
private int timeout;
|
||||||
|
private int maxPacketSize;
|
||||||
|
private int sendRateLimit;
|
||||||
|
private int receiveRateLimit;
|
||||||
|
private boolean useSSL;
|
||||||
|
private String pathToKeyStore;
|
||||||
|
private String keyStorePassword;
|
||||||
|
|
||||||
|
public SocketServerConfig(
|
||||||
|
int timeout, int maxPacketSize, int sendRateLimit, int receiveRateLimit, boolean useSSL, String pathToKeyStore, String keyStorePassword
|
||||||
|
) {
|
||||||
|
this.timeout = timeout;
|
||||||
|
this.maxPacketSize = maxPacketSize;
|
||||||
|
this.sendRateLimit = sendRateLimit;
|
||||||
|
this.receiveRateLimit = receiveRateLimit;
|
||||||
|
this.useSSL = useSSL;
|
||||||
|
this.pathToKeyStore = pathToKeyStore;
|
||||||
|
this.keyStorePassword = keyStorePassword;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getTimeout() {
|
||||||
|
return this.timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getMaxPacketSize() {
|
||||||
|
return this.maxPacketSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getSendRateLimit() {
|
||||||
|
return this.sendRateLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getReceiveRateLimit() {
|
||||||
|
return this.receiveRateLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isUseSSL() {
|
||||||
|
return this.useSSL;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPathToKeyStore() {
|
||||||
|
return this.pathToKeyStore;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getKeyStorePassword() {
|
||||||
|
return this.keyStorePassword;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTimeout(int timeout) {
|
||||||
|
this.timeout = timeout;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMaxPacketSize(int maxPacketSize) {
|
||||||
|
this.maxPacketSize = maxPacketSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSendRateLimit(int sendRateLimit) {
|
||||||
|
this.sendRateLimit = sendRateLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setReceiveRateLimit(int receiveRateLimit) {
|
||||||
|
this.receiveRateLimit = receiveRateLimit;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUseSSL(boolean useSSL) {
|
||||||
|
this.useSSL = useSSL;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPathToKeyStore(String pathToKeyStore) {
|
||||||
|
this.pathToKeyStore = pathToKeyStore;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setKeyStorePassword(String keyStorePassword) {
|
||||||
|
this.keyStorePassword = keyStorePassword;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package me.darksidecode.easysockets.util;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
|
||||||
|
public class LimitedList<T> extends ArrayList<T> implements Serializable {
|
||||||
|
private static final long serialVersionUID = -3776468374308090201L;
|
||||||
|
private final int capacity;
|
||||||
|
|
||||||
|
public LimitedList(int capacity) {
|
||||||
|
if (capacity <= 50000 && capacity >= 2) {
|
||||||
|
this.capacity = capacity;
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Invalid capacity: " + capacity);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean add(T t) {
|
||||||
|
boolean r = super.add(t);
|
||||||
|
if (this.size() > this.capacity) {
|
||||||
|
this.remove(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isFull() {
|
||||||
|
return this.size() == this.capacity;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int getCapacity() {
|
||||||
|
return this.capacity;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
package me.darksidecode.easysockets.util;
|
||||||
|
|
||||||
|
public class Timer {
|
||||||
|
private long startTime;
|
||||||
|
|
||||||
|
public Timer(long startTime) {
|
||||||
|
this.startTime = startTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer() {
|
||||||
|
this(System.currentTimeMillis());
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer add(long millis) {
|
||||||
|
this.startTime = this.startTime + Math.abs(millis);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer addTicks(long ticks) {
|
||||||
|
this.startTime = this.startTime + Math.abs(ticks * 50L);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer addSeconds(long seconds) {
|
||||||
|
this.startTime = this.startTime + Math.abs(seconds * 1000L);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer subtract(long millis) {
|
||||||
|
this.startTime = this.startTime - Math.abs(millis);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer subtractTicks(long ticks) {
|
||||||
|
this.startTime = this.startTime - Math.abs(ticks) * 50L;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer subtractSeconds(long seconds) {
|
||||||
|
this.startTime = this.startTime - Math.abs(seconds * 1000L);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer offset(long millis) {
|
||||||
|
this.startTime += millis;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer offsetTicks(long ticks) {
|
||||||
|
this.startTime += ticks * 50L;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer offsetSeconds(long seconds) {
|
||||||
|
this.startTime += seconds * 1000L;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasPassed(long millis) {
|
||||||
|
return this.getTimePassed() >= millis;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean hasTicked(long ticks) {
|
||||||
|
return this.getTimeTicked() >= ticks;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getTimePassed() {
|
||||||
|
return System.currentTimeMillis() - this.startTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getTimeTicked() {
|
||||||
|
return this.getTimePassed() / 50L;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long getStartTime() {
|
||||||
|
return this.startTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer setStartTime(long newTime) {
|
||||||
|
if (newTime < 1L) {
|
||||||
|
this.reset();
|
||||||
|
} else {
|
||||||
|
this.startTime = newTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Timer reset() {
|
||||||
|
this.setStartTime(System.currentTimeMillis());
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package me.darksidecode.easysockets.util;
|
||||||
|
|
||||||
|
public class Validate {
|
||||||
|
public static <T> T notNull(T object, String message) {
|
||||||
|
if (object == null) {
|
||||||
|
throw new NullPointerException(message);
|
||||||
|
} else {
|
||||||
|
return object;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static char[] notEmpty(char[] array, String message) {
|
||||||
|
if (notNull(array, message).length == 0) {
|
||||||
|
throw new ArrayIndexOutOfBoundsException(message);
|
||||||
|
} else {
|
||||||
|
return array;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package me.darksidecode.easysockets.util.crypto;
|
||||||
|
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
import javax.crypto.spec.IvParameterSpec;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
|
||||||
|
public class AES128Encryptor implements Encryptor {
|
||||||
|
private static final String ALGO = "AES/CBC/PKCS5PADDING";
|
||||||
|
private final byte[] key;
|
||||||
|
private final byte[] iv;
|
||||||
|
|
||||||
|
public AES128Encryptor(byte[] key, byte[] iv) {
|
||||||
|
if (key == null || key.length != 16) {
|
||||||
|
throw new IllegalArgumentException("Invalid key. Required length: 16");
|
||||||
|
} else if (iv != null && iv.length == 16) {
|
||||||
|
this.key = key;
|
||||||
|
this.iv = iv;
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Invalid init vector. Required length: 16");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] encrypt(byte[] input) {
|
||||||
|
try {
|
||||||
|
IvParameterSpec iv = new IvParameterSpec(this.iv);
|
||||||
|
SecretKeySpec skc = new SecretKeySpec(this.key, "AES");
|
||||||
|
Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
||||||
|
c.init(1, skc, iv);
|
||||||
|
return c.doFinal(input);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("failed to encrypt " + input.length + " bytes with AES (128)", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] decrypt(byte[] input) {
|
||||||
|
try {
|
||||||
|
IvParameterSpec iv = new IvParameterSpec(this.iv);
|
||||||
|
SecretKeySpec skeySpec = new SecretKeySpec(this.key, "AES");
|
||||||
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
||||||
|
cipher.init(2, skeySpec, iv);
|
||||||
|
return cipher.doFinal(input);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("failed to decrypt " + input.length + " bytes with AES (128)", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package me.darksidecode.easysockets.util.crypto;
|
||||||
|
|
||||||
|
import java.security.AlgorithmParameters;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.spec.InvalidKeySpecException;
|
||||||
|
import java.security.spec.KeySpec;
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
import javax.crypto.SecretKey;
|
||||||
|
import javax.crypto.SecretKeyFactory;
|
||||||
|
import javax.crypto.spec.IvParameterSpec;
|
||||||
|
import javax.crypto.spec.PBEKeySpec;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
|
||||||
|
public class AES256Encryptor implements Encryptor {
|
||||||
|
public static final int DEFAULT_ITERATIONS = 65536;
|
||||||
|
private static final String KEYGEN_ALGO = "PBKDF2WithHmacSHA256";
|
||||||
|
private static final String CRYPT_ALGO = "AES/CBC/PKCS5PADDING";
|
||||||
|
private final char[] key;
|
||||||
|
private final byte[] salt;
|
||||||
|
private final int iterations;
|
||||||
|
|
||||||
|
public AES256Encryptor(char[] key, byte[] salt) {
|
||||||
|
this(key, salt, 65536);
|
||||||
|
}
|
||||||
|
|
||||||
|
public AES256Encryptor(char[] key, byte[] salt, int iterations) {
|
||||||
|
if (key != null && key.length != 0) {
|
||||||
|
if (salt == null || salt.length != 8) {
|
||||||
|
throw new IllegalArgumentException("Invalid salt. Required length: 8");
|
||||||
|
} else if (iterations < 2) {
|
||||||
|
throw new IllegalArgumentException("Too few iterations. Expected at least 2");
|
||||||
|
} else {
|
||||||
|
this.key = key;
|
||||||
|
this.salt = salt;
|
||||||
|
this.iterations = iterations;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("key cannot be null or empty");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private SecretKey getSecret() throws InvalidKeySpecException, NoSuchAlgorithmException {
|
||||||
|
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
|
||||||
|
KeySpec spec = new PBEKeySpec(this.key, this.salt, this.iterations, 256);
|
||||||
|
SecretKey secret = factory.generateSecret(spec);
|
||||||
|
return new SecretKeySpec(secret.getEncoded(), "AES");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] encrypt(byte[] input) {
|
||||||
|
try {
|
||||||
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
||||||
|
cipher.init(1, this.getSecret());
|
||||||
|
AlgorithmParameters params = cipher.getParameters();
|
||||||
|
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
|
||||||
|
byte[] cipherData = cipher.doFinal(input);
|
||||||
|
return new AES256Encryptor.CipherObj(cipherData, iv).getBytes();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("failed to encrypt " + input.length + " bytes with AES (256)", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] decrypt(byte[] input) {
|
||||||
|
try {
|
||||||
|
AES256Encryptor.CipherObj cObj = AES256Encryptor.CipherObj.from(input);
|
||||||
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||||
|
cipher.init(2, this.getSecret(), new IvParameterSpec(cObj.iv));
|
||||||
|
return cipher.doFinal(cObj.cipherData);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("failed to decrypt " + input.length + " bytes with AES (256)", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class CipherObj {
|
||||||
|
private final byte[] cipherData;
|
||||||
|
private final byte[] iv;
|
||||||
|
|
||||||
|
private CipherObj(byte[] cipherData, byte[] iv) {
|
||||||
|
if (cipherData == null || cipherData.length == 0 || cipherData.length % 16 != 0) {
|
||||||
|
throw new RuntimeException("invalid cipherdata");
|
||||||
|
} else if (iv != null && iv.length == 16) {
|
||||||
|
this.cipherData = cipherData;
|
||||||
|
this.iv = iv;
|
||||||
|
} else {
|
||||||
|
throw new RuntimeException("invalid init vector");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] getBytes() {
|
||||||
|
byte[] b = new byte[16 + this.cipherData.length];
|
||||||
|
System.arraycopy(this.iv, 0, b, 0, 16);
|
||||||
|
System.arraycopy(this.cipherData, 0, b, 16, this.cipherData.length);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AES256Encryptor.CipherObj from(byte[] b) {
|
||||||
|
byte[] iv = new byte[16];
|
||||||
|
byte[] cipherData = new byte[b.length - 16];
|
||||||
|
System.arraycopy(b, 0, iv, 0, 16);
|
||||||
|
System.arraycopy(b, 16, cipherData, 0, cipherData.length);
|
||||||
|
return new AES256Encryptor.CipherObj(cipherData, iv);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package me.darksidecode.easysockets.util.crypto;
|
||||||
|
|
||||||
|
public interface Encryptor {
|
||||||
|
byte[] encrypt(byte[] input);
|
||||||
|
|
||||||
|
byte[] decrypt(byte[] input);
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package me.darksidecode.easysockets.util.io;
|
||||||
|
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.util.zip.Deflater;
|
||||||
|
import java.util.zip.DeflaterOutputStream;
|
||||||
|
import java.util.zip.InflaterInputStream;
|
||||||
|
|
||||||
|
public class Compressor {
|
||||||
|
public static InputStream newInflateInput(InputStream input) {
|
||||||
|
return new InflaterInputStream(input);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static OutputStream newDeflateOutput(OutputStream output) {
|
||||||
|
return new DeflaterOutputStream(output, new Deflater(-1), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
package me.darksidecode.easysockets.util.io;
|
||||||
|
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.ObjectInputStream;
|
||||||
|
import java.io.ObjectOutputStream;
|
||||||
|
|
||||||
|
public class IO {
|
||||||
|
public static byte[] ser(Object obj) {
|
||||||
|
if (obj == null) {
|
||||||
|
return new byte[0];
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||||
|
ObjectOutputStream oos = new ObjectOutputStream(baos);
|
||||||
|
oos.writeObject(obj);
|
||||||
|
oos.close();
|
||||||
|
byte[] bytes = baos.toByteArray();
|
||||||
|
baos.close();
|
||||||
|
return bytes;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("failed to serialize " + obj.getClass().getName(), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Object deser(byte[] bytes) {
|
||||||
|
if (bytes != null && bytes.length != 0) {
|
||||||
|
try {
|
||||||
|
ByteArrayInputStream bain = new ByteArrayInputStream(bytes);
|
||||||
|
ObjectInputStream ois = new ObjectInputStream(bain);
|
||||||
|
Object obj = ois.readObject();
|
||||||
|
bain.close();
|
||||||
|
ois.close();
|
||||||
|
return obj;
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("failed to deserialize " + bytes.length + " bytes", e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package me.darksidecode.kantanj.crypto;
|
||||||
|
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
import javax.crypto.spec.IvParameterSpec;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
|
||||||
|
public class AES128Encryptor implements Encryptor {
|
||||||
|
private static final String ALGO = "AES/CBC/PKCS5PADDING";
|
||||||
|
private final byte[] key;
|
||||||
|
private final byte[] iv;
|
||||||
|
|
||||||
|
public AES128Encryptor(byte[] key, byte[] iv) {
|
||||||
|
if (key == null || key.length != 16) {
|
||||||
|
throw new IllegalArgumentException("Invalid key. Required length: 16");
|
||||||
|
} else if (iv != null && iv.length == 16) {
|
||||||
|
this.key = key;
|
||||||
|
this.iv = iv;
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("Invalid init vector. Required length: 16");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] encrypt(byte[] input) {
|
||||||
|
try {
|
||||||
|
IvParameterSpec iv = new IvParameterSpec(this.iv);
|
||||||
|
SecretKeySpec skc = new SecretKeySpec(this.key, "AES");
|
||||||
|
Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
||||||
|
c.init(1, skc, iv);
|
||||||
|
return c.doFinal(input);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("failed to encrypt " + input.length + " bytes with AES (128)", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] decrypt(byte[] input) {
|
||||||
|
try {
|
||||||
|
IvParameterSpec iv = new IvParameterSpec(this.iv);
|
||||||
|
SecretKeySpec skeySpec = new SecretKeySpec(this.key, "AES");
|
||||||
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
||||||
|
cipher.init(2, skeySpec, iv);
|
||||||
|
return cipher.doFinal(input);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("failed to decrypt " + input.length + " bytes with AES (128)", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package me.darksidecode.kantanj.crypto;
|
||||||
|
|
||||||
|
import java.security.AlgorithmParameters;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.spec.InvalidKeySpecException;
|
||||||
|
import java.security.spec.KeySpec;
|
||||||
|
import javax.crypto.Cipher;
|
||||||
|
import javax.crypto.SecretKey;
|
||||||
|
import javax.crypto.SecretKeyFactory;
|
||||||
|
import javax.crypto.spec.IvParameterSpec;
|
||||||
|
import javax.crypto.spec.PBEKeySpec;
|
||||||
|
import javax.crypto.spec.SecretKeySpec;
|
||||||
|
|
||||||
|
public class AES256Encryptor implements Encryptor {
|
||||||
|
public static final int DEFAULT_ITERATIONS = 65536;
|
||||||
|
private static final String KEYGEN_ALGO = "PBKDF2WithHmacSHA256";
|
||||||
|
private static final String CRYPT_ALGO = "AES/CBC/PKCS5PADDING";
|
||||||
|
private final char[] key;
|
||||||
|
private final byte[] salt;
|
||||||
|
private final int iterations;
|
||||||
|
|
||||||
|
public AES256Encryptor(char[] key, byte[] salt) {
|
||||||
|
this(key, salt, 65536);
|
||||||
|
}
|
||||||
|
|
||||||
|
public AES256Encryptor(char[] key, byte[] salt, int iterations) {
|
||||||
|
if (key != null && key.length != 0) {
|
||||||
|
if (salt == null || salt.length != 8) {
|
||||||
|
throw new IllegalArgumentException("Invalid salt. Required length: 8");
|
||||||
|
} else if (iterations < 2) {
|
||||||
|
throw new IllegalArgumentException("Too few iterations. Expected at least 2");
|
||||||
|
} else {
|
||||||
|
this.key = (char[])key.clone();
|
||||||
|
this.salt = salt;
|
||||||
|
this.iterations = iterations;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("key cannot be null or empty");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private SecretKey getSecret() throws InvalidKeySpecException, NoSuchAlgorithmException {
|
||||||
|
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
|
||||||
|
KeySpec spec = new PBEKeySpec(this.key, this.salt, this.iterations, 256);
|
||||||
|
SecretKey secret = factory.generateSecret(spec);
|
||||||
|
return new SecretKeySpec(secret.getEncoded(), "AES");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] encrypt(byte[] input) {
|
||||||
|
try {
|
||||||
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
|
||||||
|
cipher.init(1, this.getSecret());
|
||||||
|
AlgorithmParameters params = cipher.getParameters();
|
||||||
|
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
|
||||||
|
byte[] cipherData = cipher.doFinal(input);
|
||||||
|
return new AES256Encryptor.CipherObj(cipherData, iv).getBytes();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("failed to encrypt " + input.length + " bytes with AES (256)", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public byte[] decrypt(byte[] input) {
|
||||||
|
try {
|
||||||
|
AES256Encryptor.CipherObj cObj = AES256Encryptor.CipherObj.from(input);
|
||||||
|
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||||
|
cipher.init(2, this.getSecret(), new IvParameterSpec(cObj.iv));
|
||||||
|
return cipher.doFinal(cObj.cipherData);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("failed to decrypt " + input.length + " bytes with AES (256)", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class CipherObj {
|
||||||
|
private final byte[] cipherData;
|
||||||
|
private final byte[] iv;
|
||||||
|
|
||||||
|
private CipherObj(byte[] cipherData, byte[] iv) {
|
||||||
|
if (cipherData == null || cipherData.length == 0 || cipherData.length % 16 != 0) {
|
||||||
|
throw new RuntimeException("invalid cipherdata");
|
||||||
|
} else if (iv != null && iv.length == 16) {
|
||||||
|
this.cipherData = cipherData;
|
||||||
|
this.iv = iv;
|
||||||
|
} else {
|
||||||
|
throw new RuntimeException("invalid init vector");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private byte[] getBytes() {
|
||||||
|
byte[] b = new byte[16 + this.cipherData.length];
|
||||||
|
System.arraycopy(this.iv, 0, b, 0, 16);
|
||||||
|
System.arraycopy(this.cipherData, 0, b, 16, this.cipherData.length);
|
||||||
|
return b;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AES256Encryptor.CipherObj from(byte[] b) {
|
||||||
|
byte[] iv = new byte[16];
|
||||||
|
byte[] cipherData = new byte[b.length - 16];
|
||||||
|
System.arraycopy(b, 0, iv, 0, 16);
|
||||||
|
System.arraycopy(b, 16, cipherData, 0, cipherData.length);
|
||||||
|
return new AES256Encryptor.CipherObj(cipherData, iv);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package me.darksidecode.kantanj.crypto;
|
||||||
|
|
||||||
|
public interface Encryptor {
|
||||||
|
byte[] encrypt(byte[] input);
|
||||||
|
|
||||||
|
byte[] decrypt(byte[] input);
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package me.darksidecode.kantanj.currency;
|
||||||
|
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
|
||||||
|
public enum Currency {
|
||||||
|
USD("US Dollar", (short)840),
|
||||||
|
EUR("Euro", (short)978),
|
||||||
|
RUB("Russian Ruble", (short)643),
|
||||||
|
CNY("Yuan Renminbi", (short)156),
|
||||||
|
GBP("Pound Sterling", (short)826),
|
||||||
|
JPY("Yen", (short)392),
|
||||||
|
CHF("Swiss Franc", (short)756),
|
||||||
|
AUD("Australian Dollar", (short)30),
|
||||||
|
CAD("Canadian Dollar", (short)124),
|
||||||
|
SEK("Swedish Krona", (short)752),
|
||||||
|
NZD("New Zealand Dollar", (short)554);
|
||||||
|
|
||||||
|
private final String name;
|
||||||
|
private final short number;
|
||||||
|
|
||||||
|
private Currency(String name, short number) {
|
||||||
|
this.name = name;
|
||||||
|
this.number = number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.name() + '/' + this.number + " (" + this.name + ")";
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Currency byHumanReadableName(String name) throws NoSuchElementException {
|
||||||
|
Check.notNull(name, "currency name cannot be null");
|
||||||
|
return Arrays.stream(values())
|
||||||
|
.filter(currency -> currency.getName().equalsIgnoreCase(name))
|
||||||
|
.findAny()
|
||||||
|
.orElseThrow(() -> new NoSuchElementException("unsupported currency: name: " + name));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Currency byNumber(short number) throws NoSuchElementException {
|
||||||
|
if (number >= 0 && number <= 999) {
|
||||||
|
return Arrays.stream(values())
|
||||||
|
.filter(currency -> currency.getNumber() == number)
|
||||||
|
.findAny()
|
||||||
|
.orElseThrow(() -> new NoSuchElementException("unsupported currency: number: " + number));
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("currency number must be between 0 and 999 (inclusive)");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public short getNumber() {
|
||||||
|
return this.number;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package me.darksidecode.kantanj.currency;
|
||||||
|
|
||||||
|
public interface CurrencyConverter {
|
||||||
|
float convert(float amount, Currency from, Currency to);
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package me.darksidecode.kantanj.currency;
|
||||||
|
|
||||||
|
import com.google.gson.JsonObject;
|
||||||
|
import com.google.gson.JsonParser;
|
||||||
|
import me.darksidecode.kantanj.networking.GetHttpRequest;
|
||||||
|
import me.darksidecode.kantanj.networking.Networking;
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
import org.apache.http.entity.ContentType;
|
||||||
|
|
||||||
|
public class SimpleCurrencyConverter implements CurrencyConverter {
|
||||||
|
public static final String FREE_URL = "https://free.currencyconverterapi.com";
|
||||||
|
public static final String PREMIUM_URL = "https://api.currencyconverterapi.com";
|
||||||
|
public static final String V6 = "v6";
|
||||||
|
private final String baseUrl;
|
||||||
|
private final String apiKey;
|
||||||
|
private String apiVersion = "v6";
|
||||||
|
|
||||||
|
public SimpleCurrencyConverter(String apiKey) {
|
||||||
|
this(false, apiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
public SimpleCurrencyConverter(boolean premium, String apiKey) {
|
||||||
|
this.baseUrl = premium ? "https://api.currencyconverterapi.com" : "https://free.currencyconverterapi.com";
|
||||||
|
this.apiKey = Check.notNull(apiKey, "API key cannot be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
public SimpleCurrencyConverter apiVersion(String apiVersion) {
|
||||||
|
this.apiVersion = Check.notNull(apiVersion, "API version cannot be null");
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public float convert(float amount, Currency from, Currency to) {
|
||||||
|
if (amount < 0.0F) {
|
||||||
|
throw new IllegalArgumentException("amount cannot be negative");
|
||||||
|
} else if (amount == 0.0F) {
|
||||||
|
return 0.0F;
|
||||||
|
} else {
|
||||||
|
Check.notNull(from, "source currency cannot be null");
|
||||||
|
Check.notNull(to, "target currency cannot be null");
|
||||||
|
|
||||||
|
try {
|
||||||
|
String arg = from.name() + '_' + to.name();
|
||||||
|
GetHttpRequest getRequest = (GetHttpRequest)new GetHttpRequest()
|
||||||
|
.baseUrl(this.baseUrl)
|
||||||
|
.path("api/" + this.apiVersion + "/convert")
|
||||||
|
.queryParams("q", arg, "compact", "ultra", "apiKey", this.apiKey)
|
||||||
|
.requestProperty("Content-Type", ContentType.APPLICATION_JSON.toString())
|
||||||
|
.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101");
|
||||||
|
String response = Networking.Http.get(getRequest);
|
||||||
|
JsonObject json = new JsonParser().parse(response).getAsJsonObject();
|
||||||
|
float conversionRate = json.get(arg).getAsFloat();
|
||||||
|
return amount * conversionRate;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("failed to convert " + amount + " " + from.name() + " to " + to.name(), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package me.darksidecode.kantanj.db;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
|
||||||
|
public interface Database {
|
||||||
|
int prepare(DatabaseConfiguration config) throws DatabaseAuthenticationException;
|
||||||
|
|
||||||
|
<T extends Serializable> DatabaseObject<T> fetch(String key);
|
||||||
|
|
||||||
|
<T extends Serializable> DatabaseObject<T> fetch(Predicate<? super DatabaseObject> predicate);
|
||||||
|
|
||||||
|
void insert(DatabaseObject object) throws IllegalStateException;
|
||||||
|
|
||||||
|
boolean remove(DatabaseObject object);
|
||||||
|
|
||||||
|
boolean remove(String key);
|
||||||
|
|
||||||
|
boolean remove(Predicate<? super DatabaseObject> predicate);
|
||||||
|
|
||||||
|
void update(DatabaseObject target, DatabaseObject replacement);
|
||||||
|
|
||||||
|
void update(String key, DatabaseObject replacement);
|
||||||
|
|
||||||
|
void update(Predicate<? super DatabaseObject> predicate, DatabaseObject replacement);
|
||||||
|
|
||||||
|
boolean contains(DatabaseObject object);
|
||||||
|
|
||||||
|
boolean contains(String key);
|
||||||
|
|
||||||
|
boolean contains(Predicate<? super DatabaseObject> predicate);
|
||||||
|
|
||||||
|
<T extends Serializable> DatabaseObject<T>[] allObjects();
|
||||||
|
|
||||||
|
long size();
|
||||||
|
|
||||||
|
default void drop() throws DropConfirmationException {
|
||||||
|
throw new DropConfirmationException(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
void __dropConfirm00__();
|
||||||
|
|
||||||
|
boolean save();
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package me.darksidecode.kantanj.db;
|
||||||
|
|
||||||
|
public class DatabaseAuthenticationException extends Exception {
|
||||||
|
public DatabaseAuthenticationException(String message) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public DatabaseAuthenticationException(Throwable cause) {
|
||||||
|
super(cause);
|
||||||
|
}
|
||||||
|
|
||||||
|
public DatabaseAuthenticationException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package me.darksidecode.kantanj.db;
|
||||||
|
|
||||||
|
import me.darksidecode.kantanj.crypto.Encryptor;
|
||||||
|
|
||||||
|
public interface DatabaseConfiguration {
|
||||||
|
Encryptor getEncryptor();
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package me.darksidecode.kantanj.db;
|
||||||
|
|
||||||
|
import com.google.gson.internal.LinkedTreeMap;
|
||||||
|
import java.io.Serializable;
|
||||||
|
import me.darksidecode.kantanj.formatting.CommonJson;
|
||||||
|
import me.darksidecode.kantanj.formatting.Formatting;
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
import org.bson.Document;
|
||||||
|
|
||||||
|
public class DatabaseObject<T extends Serializable> implements Serializable, Cloneable {
|
||||||
|
private static final long serialVersionUID = 6177749799489717775L;
|
||||||
|
private static final String DB_OBJ_LINE = "\u0000";
|
||||||
|
private String uniqueId;
|
||||||
|
private T value;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
String json = Formatting.unixLines(CommonJson.toJson(this));
|
||||||
|
if (json.contains("\u0000")) {
|
||||||
|
throw new UnknownError("json contains invalid null chars");
|
||||||
|
} else {
|
||||||
|
return json.replace("\n", "\u0000");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setUniqueId(String uniqueId) {
|
||||||
|
this.uniqueId = Check.notNull(uniqueId, "uniqueId cannot be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setValue(T value) {
|
||||||
|
this.value = Check.notNull(value, "value cannot be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
public DatabaseObject clone() {
|
||||||
|
return new DatabaseObject(this.uniqueId, this.value);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T extends Serializable> DatabaseObject<T> fromString(String dbJson) {
|
||||||
|
if (dbJson.contains("\n")) {
|
||||||
|
throw new IllegalArgumentException("json contains illegal non-db line chars");
|
||||||
|
} else {
|
||||||
|
DatabaseObject<T> obj = CommonJson.fromJson(dbJson.replace("\u0000", "\n"), DatabaseObject.class);
|
||||||
|
if (obj.getValue() instanceof LinkedTreeMap && GlobalDatabasesOptions.isConvertLinkedTreeMapToBsonDocument()) {
|
||||||
|
try {
|
||||||
|
obj.setValue((T)(new Document((LinkedTreeMap)obj.getValue())));
|
||||||
|
} catch (ClassCastException ex) {
|
||||||
|
throw new RuntimeException(
|
||||||
|
"failed to convert a LinkedTreeMap to a BSON Document (unexpected T generic type); see me.darksidecode.kantanj.db.GlobalDatabasesOptions#convertLinkedTreeMapToBsonDocument",
|
||||||
|
ex
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return obj;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public DatabaseObject(String uniqueId, T value) {
|
||||||
|
this.uniqueId = uniqueId;
|
||||||
|
this.value = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getUniqueId() {
|
||||||
|
return this.uniqueId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public T getValue() {
|
||||||
|
return this.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package me.darksidecode.kantanj.db;
|
||||||
|
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
|
||||||
|
public class DropConfirmationException extends Exception {
|
||||||
|
private final Database database;
|
||||||
|
|
||||||
|
public DropConfirmationException(Database database) {
|
||||||
|
this.database = Check.notNull(database, "database cannot be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
public Database confirmAndDrop() {
|
||||||
|
this.database.__dropConfirm00__();
|
||||||
|
return this.database;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package me.darksidecode.kantanj.db;
|
||||||
|
|
||||||
|
public class GlobalDatabasesOptions {
|
||||||
|
private static volatile boolean convertLinkedTreeMapToBsonDocument = true;
|
||||||
|
|
||||||
|
public static boolean isConvertLinkedTreeMapToBsonDocument() {
|
||||||
|
return convertLinkedTreeMapToBsonDocument;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setConvertLinkedTreeMapToBsonDocument(boolean convertLinkedTreeMapToBsonDocument) {
|
||||||
|
GlobalDatabasesOptions.convertLinkedTreeMapToBsonDocument = convertLinkedTreeMapToBsonDocument;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
package me.darksidecode.kantanj.db.file;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.NoSuchElementException;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.function.Predicate;
|
||||||
|
import javax.crypto.BadPaddingException;
|
||||||
|
import me.darksidecode.kantanj.db.Database;
|
||||||
|
import me.darksidecode.kantanj.db.DatabaseAuthenticationException;
|
||||||
|
import me.darksidecode.kantanj.db.DatabaseConfiguration;
|
||||||
|
import me.darksidecode.kantanj.db.DatabaseObject;
|
||||||
|
import me.darksidecode.kantanj.system.FileUtils;
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
|
||||||
|
public class KantanjFileDatabase implements Database {
|
||||||
|
public static final String FILE_HEADER = "![kantanj.sfdb]\n";
|
||||||
|
private static final byte[] HEADER_BYTES = "![kantanj.sfdb]\n".getBytes(StandardCharsets.UTF_8);
|
||||||
|
private final Object lock = new Object();
|
||||||
|
private boolean prepared;
|
||||||
|
private KantanjFileDatabaseConfiguration conf;
|
||||||
|
private final Set<DatabaseObject> objects = new HashSet<>();
|
||||||
|
private int initialHash;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int prepare(DatabaseConfiguration dbConf) throws DatabaseAuthenticationException {
|
||||||
|
Check.state(this.prepared, "already prepared");
|
||||||
|
this.conf = Check.instanceOf(dbConf, KantanjFileDatabaseConfiguration.class, "illegal database configuration");
|
||||||
|
if (this.conf.getSourceFile().exists()) {
|
||||||
|
byte[] db;
|
||||||
|
try {
|
||||||
|
db = dbConf.getEncryptor() == null
|
||||||
|
? FileUtils.readGZIP(this.conf.getSourceFile())
|
||||||
|
: FileUtils.readEncryptedGZIP(this.conf.getSourceFile(), this.conf.getEncryptor());
|
||||||
|
} catch (Exception ex) {
|
||||||
|
if (ex.getCause() instanceof RuntimeException && ex.getCause().getCause() instanceof BadPaddingException) {
|
||||||
|
throw new DatabaseAuthenticationException("invalid credentials");
|
||||||
|
}
|
||||||
|
|
||||||
|
throw ex;
|
||||||
|
}
|
||||||
|
|
||||||
|
String dbStr = new String(db, StandardCharsets.UTF_8);
|
||||||
|
if (!dbStr.startsWith("![kantanj.sfdb]\n")) {
|
||||||
|
throw new IllegalArgumentException("not a kantanj SimpleFileDatabase file");
|
||||||
|
} else {
|
||||||
|
dbStr = dbStr.replace("![kantanj.sfdb]\n", "");
|
||||||
|
String[] lines = dbStr.split("\n");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
for (String line : lines) {
|
||||||
|
line = line.trim();
|
||||||
|
if (!line.isEmpty() && !line.startsWith("#")) {
|
||||||
|
DatabaseObject obj = DatabaseObject.fromString(line);
|
||||||
|
this.objects.add(obj);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.prepared = true;
|
||||||
|
this.initialHash = this.objects.hashCode();
|
||||||
|
this.addShutdownHookIfEnabled();
|
||||||
|
return this.objects.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (this.conf.getEncryptor() == null) {
|
||||||
|
FileUtils.writeGZIP(this.conf.getSourceFile(), HEADER_BYTES, FileUtils.OverwriteMode.THROW_STATE_EXCEPTION);
|
||||||
|
} else {
|
||||||
|
FileUtils.writeEncryptedGZIP(this.conf.getSourceFile(), HEADER_BYTES, this.conf.getEncryptor(), FileUtils.OverwriteMode.THROW_STATE_EXCEPTION);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.prepared = true;
|
||||||
|
this.initialHash = 0;
|
||||||
|
this.addShutdownHookIfEnabled();
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addShutdownHookIfEnabled() {
|
||||||
|
if (this.conf.isFlushOnExit()) {
|
||||||
|
Runtime.getRuntime().addShutdownHook(new Thread(this::save, "KantanjFileDatabase Shutdown Hook | " + System.nanoTime()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends Serializable> DatabaseObject<T> fetch(String uniqueId) {
|
||||||
|
Check.notNull(uniqueId, "uniqueId cannot be null");
|
||||||
|
return this.fetch(obj -> obj.getUniqueId().equals(uniqueId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends Serializable> DatabaseObject<T> fetch(Predicate<? super DatabaseObject> predicate) {
|
||||||
|
Check.state(!this.prepared, "database must be prepared first");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
return (DatabaseObject<T>)this.objects.stream().filter(Check.notNull(predicate, "predicate cannot be null")).findFirst().orElse(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void insert(DatabaseObject obj) throws IllegalStateException {
|
||||||
|
Check.state(!this.prepared, "database must be prepared first");
|
||||||
|
Check.notNull(obj, "cannot insert null object into database");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
Check.state(this.contains(obj.getUniqueId()), "object with uniqueId " + obj.getUniqueId() + " is already present in the database");
|
||||||
|
this.objects.add(obj);
|
||||||
|
if (this.conf.isFlushInstantly()) {
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean remove(DatabaseObject obj) {
|
||||||
|
Check.state(!this.prepared, "database must be prepared first");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
boolean anythingRemoved = this.objects.remove(Check.notNull(obj, "obj cannot be null"));
|
||||||
|
if (this.conf.isFlushInstantly()) {
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
return anythingRemoved;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean remove(String uniqueId) {
|
||||||
|
Check.notNull(uniqueId, "uniqueId cannot be null");
|
||||||
|
return this.remove(obj -> obj.getUniqueId().equals(uniqueId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean remove(Predicate<? super DatabaseObject> predicate) {
|
||||||
|
synchronized (this.lock) {
|
||||||
|
DatabaseObject obj = this.fetch(predicate);
|
||||||
|
if (obj != null) {
|
||||||
|
this.objects.remove(obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.conf.isFlushInstantly()) {
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
return obj != null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void update(DatabaseObject oldObj, DatabaseObject newObj) {
|
||||||
|
Check.state(!this.prepared, "database must be prepared first");
|
||||||
|
Check.notNull(oldObj, "oldObj cannot be null");
|
||||||
|
Check.notNull(newObj, "newObj cannot be null");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
if (this.objects.contains(oldObj)) {
|
||||||
|
this.objects.remove(oldObj);
|
||||||
|
this.objects.add(newObj);
|
||||||
|
if (this.conf.isFlushInstantly()) {
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new NoSuchElementException("no such object in the database");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void update(String uniqueId, DatabaseObject newObj) {
|
||||||
|
Check.notNull(uniqueId, "uniqueId cannot be null");
|
||||||
|
this.update(obj -> obj.getUniqueId().equals(uniqueId), newObj);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void update(Predicate<? super DatabaseObject> oldObjPredicate, DatabaseObject newObj) {
|
||||||
|
synchronized (this.lock) {
|
||||||
|
DatabaseObject oldObj = this.fetch(oldObjPredicate);
|
||||||
|
if (oldObj != null) {
|
||||||
|
this.objects.remove(oldObj);
|
||||||
|
this.objects.add(newObj);
|
||||||
|
if (this.conf.isFlushInstantly()) {
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new NoSuchElementException("no such object in the database");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean contains(DatabaseObject obj) {
|
||||||
|
Check.state(!this.prepared, "database must be prepared first");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
return this.objects.contains(Check.notNull(obj, "obj cannot be null"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean contains(String uniqueId) {
|
||||||
|
Check.notNull(uniqueId, "uniqueId cannot be null");
|
||||||
|
return this.contains(obj -> obj.getUniqueId().equals(uniqueId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean contains(Predicate<? super DatabaseObject> predicate) {
|
||||||
|
Check.state(!this.prepared, "database must be prepared first");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
return this.objects.stream().anyMatch(Check.notNull(predicate, "predicate cannot be null"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public <T extends Serializable> DatabaseObject<T>[] allObjects() {
|
||||||
|
Check.state(!this.prepared, "database must be prepared first");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
return this.objects.toArray(new DatabaseObject[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public long size() {
|
||||||
|
Check.state(!this.prepared, "database must be prepared first");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
return (long)this.objects.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void __dropConfirm00__() {
|
||||||
|
Check.state(!this.prepared, "database must be prepared first");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
this.objects.clear();
|
||||||
|
if (this.conf.isFlushInstantly()) {
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean save() {
|
||||||
|
Check.state(!this.prepared, "database must be prepared first");
|
||||||
|
synchronized (this.lock) {
|
||||||
|
if (this.objects.hashCode() == this.initialHash) {
|
||||||
|
return false;
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
StringBuilder dbStr = new StringBuilder();
|
||||||
|
dbStr.append("![kantanj.sfdb]\n");
|
||||||
|
|
||||||
|
for (DatabaseObject obj : this.objects) {
|
||||||
|
dbStr.append(obj.toString()).append('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
byte[] dbBytes = dbStr.toString().getBytes(StandardCharsets.UTF_8);
|
||||||
|
File newFile = new File(this.conf.getSourceFile().getAbsolutePath() + ".tmp" + System.nanoTime() + '~');
|
||||||
|
if (this.conf.getEncryptor() == null) {
|
||||||
|
FileUtils.writeGZIP(newFile, dbBytes, FileUtils.OverwriteMode.THROW_STATE_EXCEPTION);
|
||||||
|
} else {
|
||||||
|
FileUtils.writeEncryptedGZIP(newFile, dbBytes, this.conf.getEncryptor(), FileUtils.OverwriteMode.THROW_STATE_EXCEPTION);
|
||||||
|
}
|
||||||
|
|
||||||
|
Files.move(newFile.toPath(), this.conf.getSourceFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
return true;
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException("failed to save the database to file", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package me.darksidecode.kantanj.db.file;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import me.darksidecode.kantanj.crypto.AES256Encryptor;
|
||||||
|
import me.darksidecode.kantanj.crypto.Encryptor;
|
||||||
|
import me.darksidecode.kantanj.db.DatabaseConfiguration;
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
|
||||||
|
public class KantanjFileDatabaseConfiguration implements DatabaseConfiguration {
|
||||||
|
private File sourceFile;
|
||||||
|
private boolean flushInstantly;
|
||||||
|
private boolean flushOnExit;
|
||||||
|
private Encryptor encryptor;
|
||||||
|
|
||||||
|
public static KantanjFileDatabaseConfiguration.Builder builder() {
|
||||||
|
return new KantanjFileDatabaseConfiguration.Builder();
|
||||||
|
}
|
||||||
|
|
||||||
|
public File getSourceFile() {
|
||||||
|
return this.sourceFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isFlushInstantly() {
|
||||||
|
return this.flushInstantly;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isFlushOnExit() {
|
||||||
|
return this.flushOnExit;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Encryptor getEncryptor() {
|
||||||
|
return this.encryptor;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final class Builder {
|
||||||
|
private static final byte[] ENC_SALT = new byte[]{-128, 62, 60, 10, -11, -101, -70, -112};
|
||||||
|
private final KantanjFileDatabaseConfiguration conf = new KantanjFileDatabaseConfiguration();
|
||||||
|
private int aesIterations = 65536;
|
||||||
|
|
||||||
|
Builder() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public KantanjFileDatabaseConfiguration build() {
|
||||||
|
return this.conf;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KantanjFileDatabaseConfiguration.Builder file(String path) {
|
||||||
|
return this.file(new File(path));
|
||||||
|
}
|
||||||
|
|
||||||
|
public KantanjFileDatabaseConfiguration.Builder file(Path path) {
|
||||||
|
return this.file(path.toFile());
|
||||||
|
}
|
||||||
|
|
||||||
|
public KantanjFileDatabaseConfiguration.Builder file(File sourceFile) {
|
||||||
|
this.conf.sourceFile = Check.notNull(sourceFile, "sourceFile cannot be null");
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KantanjFileDatabaseConfiguration.Builder flushInstantly(boolean flushInstantly) {
|
||||||
|
this.conf.flushInstantly = flushInstantly;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KantanjFileDatabaseConfiguration.Builder flushOnExit(boolean flushOnExit) {
|
||||||
|
this.conf.flushOnExit = flushOnExit;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KantanjFileDatabaseConfiguration.Builder aesIterations(int aesIterations) {
|
||||||
|
if (aesIterations < 1) {
|
||||||
|
throw new IllegalArgumentException("must iterate at least once");
|
||||||
|
} else {
|
||||||
|
Check.state(this.conf.encryptor != null, "encryptor already set (aesIterations must be set before password)");
|
||||||
|
this.aesIterations = aesIterations;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public KantanjFileDatabaseConfiguration.Builder password(char[] password) {
|
||||||
|
this.conf.encryptor = new AES256Encryptor(password, ENC_SALT, this.aesIterations);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public KantanjFileDatabaseConfiguration.Builder encryptor(Encryptor encryptor) {
|
||||||
|
this.conf.encryptor = encryptor;
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package me.darksidecode.kantanj.db.mongo;
|
||||||
|
|
||||||
|
import org.bson.Document;
|
||||||
|
|
||||||
|
public interface Cacheable {
|
||||||
|
void fetch(MongoManager manager, Object key);
|
||||||
|
|
||||||
|
Document create();
|
||||||
|
|
||||||
|
Document push();
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
package me.darksidecode.kantanj.db.mongo;
|
||||||
|
|
||||||
|
import com.mongodb.MongoClient;
|
||||||
|
import com.mongodb.MongoCredential;
|
||||||
|
import com.mongodb.ServerAddress;
|
||||||
|
import com.mongodb.client.FindIterable;
|
||||||
|
import com.mongodb.client.MongoCollection;
|
||||||
|
import com.mongodb.client.MongoDatabase;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
import org.bson.Document;
|
||||||
|
|
||||||
|
public class MongoManager implements AutoCloseable {
|
||||||
|
private static final int DEFAULT_MONGO_PORT = 27017;
|
||||||
|
private MongoClient client;
|
||||||
|
private MongoDatabase selected;
|
||||||
|
|
||||||
|
public MongoManager noLogs() {
|
||||||
|
Logger.getLogger("com.mongodb").setLevel(Level.OFF);
|
||||||
|
Logger.getLogger("org.mongodb").setLevel(Level.OFF);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MongoManager connectLocal() {
|
||||||
|
try {
|
||||||
|
this.client = new MongoClient();
|
||||||
|
return this;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("failed to connect to default local database", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public MongoManager connectLocal(String username, String database, char[] password) {
|
||||||
|
try {
|
||||||
|
return this.connect("localhost", 27017, username, database, password);
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("failed to connect to default local database", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public MongoManager connect(String host) {
|
||||||
|
if (host != null && !host.trim().isEmpty()) {
|
||||||
|
try {
|
||||||
|
this.client = new MongoClient(host);
|
||||||
|
return this;
|
||||||
|
} catch (Exception err) {
|
||||||
|
throw new RuntimeException("failed to connect to remote database \"" + host + "\" (default port)", err);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("invalid (null, empty or 'spaces-only') host");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public MongoManager connect(String host, int port) {
|
||||||
|
if (host == null || host.trim().isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("invalid (null, empty or 'spaces-only') host");
|
||||||
|
} else if (port >= 1 && port <= 65535) {
|
||||||
|
try {
|
||||||
|
this.client = new MongoClient(host, port);
|
||||||
|
return this;
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
throw new RuntimeException(String.format("failed to connect to remote database \"%s\" at port %s", host, port));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("invalid port " + port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public MongoManager connect(String host, int port, String username, String database, char[] password) {
|
||||||
|
if (host == null || host.trim().isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("invalid (null, empty or 'spaces-only') host");
|
||||||
|
} else if (username == null || username.trim().isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("invalid (null, empty or 'spaces-only') username");
|
||||||
|
} else if (database == null || database.trim().isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("invalid (null, empty or 'spaces-only') database");
|
||||||
|
} else if (password == null || password.length == 0) {
|
||||||
|
throw new IllegalArgumentException("invalid (null or empty) password");
|
||||||
|
} else if (port >= 1 && port <= 65535) {
|
||||||
|
try {
|
||||||
|
MongoCredential cred = MongoCredential.createCredential(username, database, password);
|
||||||
|
|
||||||
|
for (int i = 0; i < password.length; i++) {
|
||||||
|
password[i] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.client = new MongoClient(new ServerAddress(host, port), Collections.singletonList(cred));
|
||||||
|
return this;
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("failed to connect to default local database (with user&pass)", ex);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("invalid port " + port);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public MongoManager select(String database) {
|
||||||
|
this.ensureConnected();
|
||||||
|
this.selected = this.client.getDatabase(Check.notNull(database, "database name cannot be null"));
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MongoDatabase getSelectedDatabase() {
|
||||||
|
this.ensureSelected();
|
||||||
|
return this.selected;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isDatabaseSelected() {
|
||||||
|
this.ensureConnected();
|
||||||
|
return this.selected != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isConnected() {
|
||||||
|
return this.client != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureSelected() {
|
||||||
|
this.ensureConnected();
|
||||||
|
if (!this.isDatabaseSelected()) {
|
||||||
|
throw new IllegalStateException("no database selected");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureConnected() {
|
||||||
|
if (!this.isConnected()) {
|
||||||
|
throw new IllegalStateException("not connected");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
if (this.isConnected()) {
|
||||||
|
try {
|
||||||
|
this.client.close();
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T checkStateAndReturn(T object) {
|
||||||
|
this.ensureSelected();
|
||||||
|
return object;
|
||||||
|
}
|
||||||
|
|
||||||
|
public MongoCollection<Document> getCollection(String collection) {
|
||||||
|
return this.checkStateAndReturn(this.selected.getCollection(Check.notNull(collection, "collection name cannot be null")));
|
||||||
|
}
|
||||||
|
|
||||||
|
public FindIterable<Document> fetch(String collection, String key, Object val) {
|
||||||
|
return this.getCollection(collection).find(new Document(Check.notNull(key, "key cannot be null"), val));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Document fetchFirst(String collection, String key, Object val) {
|
||||||
|
return (Document)this.fetch(collection, key, val).first();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertOne(String collection, Document doc) {
|
||||||
|
this.getCollection(collection).insertOne(Check.notNull(doc, "doc cannot be null"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void insertMany(String collection, List<Document> docs) {
|
||||||
|
if (Check.notNull(docs, "docs list cannot be null").isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("nothing to insert");
|
||||||
|
} else {
|
||||||
|
MongoCollection<Document> col = this.getCollection(collection);
|
||||||
|
if (docs.size() == 1) {
|
||||||
|
col.insertOne(docs.get(0));
|
||||||
|
} else {
|
||||||
|
col.insertMany(docs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public Document updateOne(String collection, String idKey, Object idVal, Document updatedData) {
|
||||||
|
Check.notNull(idKey, "target entry ID key cannot be null");
|
||||||
|
Check.notNull(updatedData, "updated data cannot be null");
|
||||||
|
MongoCollection<Document> col = this.getCollection(collection);
|
||||||
|
Document targetEntry = (Document)col.find(new Document(idKey, idVal)).first();
|
||||||
|
Check.notNull(targetEntry, "no entries with \"%s\"=\"%s\" found", idKey, idVal);
|
||||||
|
col.updateOne(targetEntry, new Document("$set", updatedData));
|
||||||
|
return targetEntry;
|
||||||
|
}
|
||||||
|
|
||||||
|
public long deleteOne(String collection, String idKey, Object idVal) {
|
||||||
|
Check.notNull(idKey, "target entry ID key cannot be null");
|
||||||
|
MongoCollection<Document> col = this.getCollection(collection);
|
||||||
|
return col.deleteOne(new Document(idKey, idVal)).getDeletedCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
public long count(String collection) {
|
||||||
|
return this.getCollection(collection).countDocuments();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package me.darksidecode.kantanj.formatting;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.GsonBuilder;
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
|
||||||
|
public final class CommonJson {
|
||||||
|
private static final Gson simpleGsonNoHtmlEsc = new GsonBuilder().disableHtmlEscaping().create();
|
||||||
|
private static final Gson prettyGsonNoHtmlEsc = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
|
||||||
|
|
||||||
|
private CommonJson() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static <T> T fromJson(String json, Class<T> typeOfT) {
|
||||||
|
return (T)simpleGsonNoHtmlEsc.fromJson(Check.notNull(json, "json cannot be null"), Check.notNull(typeOfT, "typeOfT cannot be null"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String toJson(Object obj) {
|
||||||
|
return simpleGsonNoHtmlEsc.toJson(Check.notNull(obj, "obj cannot be null"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String toPrettyJson(Object obj) {
|
||||||
|
return prettyGsonNoHtmlEsc.toJson(Check.notNull(obj, "obj cannot be null"));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Gson getSimpleGsonNoHtmlEsc() {
|
||||||
|
return simpleGsonNoHtmlEsc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Gson getPrettyGsonNoHtmlEsc() {
|
||||||
|
return prettyGsonNoHtmlEsc;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
package me.darksidecode.kantanj.formatting;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
import jdk.nashorn.internal.runtime.regexp.joni.exception.SyntaxException;
|
||||||
|
|
||||||
|
public class Condition {
|
||||||
|
final List<Condition.Branch> branches = new ArrayList<>();
|
||||||
|
Condition.Branch elseBranch;
|
||||||
|
String pre;
|
||||||
|
private boolean validated;
|
||||||
|
private int validatedHash = -1;
|
||||||
|
|
||||||
|
void validate() {
|
||||||
|
int h = this.hashCode();
|
||||||
|
if (!this.validated || h == 0 || h != this.validatedHash) {
|
||||||
|
this.validated = false;
|
||||||
|
if (this.pre == null) {
|
||||||
|
this.pre = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.branches.isEmpty()) {
|
||||||
|
throw new SyntaxException("missing conditional branches");
|
||||||
|
} else if (this.elseBranch == null) {
|
||||||
|
throw new SyntaxException("missing else branch");
|
||||||
|
} else if (this.elseBranch.result == null) {
|
||||||
|
throw new SyntaxException("missing result at the else branch");
|
||||||
|
} else {
|
||||||
|
for (int i = 0; i < this.branches.size(); i++) {
|
||||||
|
Condition.Branch branch = this.branches.get(i);
|
||||||
|
if (branch.obj == -1) {
|
||||||
|
throw new SyntaxException("missing target obj pointer at branch " + i);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (branch.op == null) {
|
||||||
|
throw new SyntaxException("missing comparison operator at branch " + i);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (branch.against == null) {
|
||||||
|
throw new SyntaxException("missing against obj at branch " + i);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (branch.result == null) {
|
||||||
|
throw new SyntaxException("missing result at branch " + i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.validated = true;
|
||||||
|
this.validatedHash = this.hashCode();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ensureValidated() {
|
||||||
|
if (!this.validated) {
|
||||||
|
throw new IllegalStateException("condition is not validated");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String apply(Object... args) {
|
||||||
|
if (args != null && args.length != 0) {
|
||||||
|
this.ensureValidated();
|
||||||
|
StringBuilder s = new StringBuilder(this.pre);
|
||||||
|
String result = null;
|
||||||
|
|
||||||
|
for (Condition.Branch branch : this.branches) {
|
||||||
|
if (branch.test(args)) {
|
||||||
|
result = branch.result;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result == null) {
|
||||||
|
result = this.elseBranch.result;
|
||||||
|
}
|
||||||
|
|
||||||
|
s.append(result);
|
||||||
|
return s.toString();
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("args must not be empty or null");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
if (this.elseBranch != null && this.pre != null) {
|
||||||
|
int h = 31 * (1 + this.branches.size());
|
||||||
|
h += this.pre.hashCode();
|
||||||
|
h += 31 * this.elseBranch.result.hashCode();
|
||||||
|
|
||||||
|
for (int i = 0; i < this.branches.size(); i++) {
|
||||||
|
int hBranch = this.branches.get(i).hashCode();
|
||||||
|
if (hBranch == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
h += 31 * (i + 1) + 31 * hBranch;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.abs(h);
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
this.ensureValidated();
|
||||||
|
StringBuilder s = new StringBuilder("Condition: { branches: (");
|
||||||
|
if (this.branches.isEmpty()) {
|
||||||
|
s.append("none");
|
||||||
|
} else {
|
||||||
|
for (int i = 0; i < this.branches.size(); i++) {
|
||||||
|
s.append(this.branches.get(i).toString());
|
||||||
|
if (i < this.branches.size() - 1) {
|
||||||
|
s.append(", ");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
s.append("); elseBranch: ").append(this.elseBranch.toString());
|
||||||
|
s.append("; pre: \"").append(this.pre).append("\"}");
|
||||||
|
return s.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
static class Branch {
|
||||||
|
private static final String RANGE_LIMITS_SPLIT = Pattern.quote("..");
|
||||||
|
int obj = -1;
|
||||||
|
String op;
|
||||||
|
boolean negate;
|
||||||
|
String against;
|
||||||
|
String result;
|
||||||
|
|
||||||
|
private boolean test(Object... args) {
|
||||||
|
if (this.obj >= args.length) {
|
||||||
|
throw new IllegalArgumentException("too few args: expected value at index " + this.obj);
|
||||||
|
} else {
|
||||||
|
Object target = args[this.obj];
|
||||||
|
if (target == null) {
|
||||||
|
throw new NullPointerException("object at index " + this.obj + " must not be null");
|
||||||
|
} else {
|
||||||
|
int idxOfOpening = this.against.indexOf(123);
|
||||||
|
int idxOfClosing = this.against.indexOf(125);
|
||||||
|
Object compareTo;
|
||||||
|
if (idxOfClosing > idxOfOpening) {
|
||||||
|
String pointerStr = this.against.replace("{", "").replace("}", "");
|
||||||
|
|
||||||
|
int pointer;
|
||||||
|
try {
|
||||||
|
pointer = Integer.parseInt(pointerStr);
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
throw new SyntaxException("invalid pointer: " + this.against);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pointer >= args.length) {
|
||||||
|
throw new IllegalArgumentException("too few args: expected value at index " + pointer);
|
||||||
|
}
|
||||||
|
|
||||||
|
compareTo = args[pointer];
|
||||||
|
if (compareTo == null) {
|
||||||
|
throw new NullPointerException("object at index " + this.obj + " must not be null");
|
||||||
|
}
|
||||||
|
} else if (this.op.equals("~")) {
|
||||||
|
compareTo = null;
|
||||||
|
} else if (this.against.contains(".")) {
|
||||||
|
try {
|
||||||
|
compareTo = Double.parseDouble(this.against);
|
||||||
|
} catch (NumberFormatException ignoredEx) {
|
||||||
|
compareTo = this.against;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
compareTo = Integer.parseInt(this.against);
|
||||||
|
} catch (NumberFormatException ignoredErr) {
|
||||||
|
compareTo = this.against;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Class targetClass = target.getClass();
|
||||||
|
Class againstClass = compareTo == null ? null : compareTo.getClass();
|
||||||
|
if (compareTo != null && targetClass != againstClass) {
|
||||||
|
throw new SyntaxException(String.format("types mismatch: cannot compare %s to %s", targetClass.getSimpleName(), againstClass.getSimpleName()));
|
||||||
|
} else {
|
||||||
|
boolean match;
|
||||||
|
if (this.op.equals("~")) {
|
||||||
|
if (!(target instanceof Number)) {
|
||||||
|
throw new SyntaxException("target object must be a number for range checks");
|
||||||
|
}
|
||||||
|
|
||||||
|
String[] limits = this.against.split(RANGE_LIMITS_SPLIT);
|
||||||
|
double low = Double.parseDouble(limits[0]);
|
||||||
|
double high = Double.parseDouble(limits[1]);
|
||||||
|
if (low >= high) {
|
||||||
|
throw new SyntaxException(String.format("low range limit must be less than high range limit; low: %s, high: %s", low, high));
|
||||||
|
}
|
||||||
|
|
||||||
|
double tNum = ((Number)target).doubleValue();
|
||||||
|
match = tNum >= low && tNum <= high;
|
||||||
|
} else {
|
||||||
|
assert compareTo != null;
|
||||||
|
|
||||||
|
if (target instanceof Number) {
|
||||||
|
double nTarget = ((Number)target).doubleValue();
|
||||||
|
double nAgainst = ((Number)compareTo).doubleValue();
|
||||||
|
match = this.compareNumbers(nTarget, nAgainst);
|
||||||
|
} else {
|
||||||
|
if (!this.op.equals("=")) {
|
||||||
|
throw new SyntaxException("operator " + this.op + " is not applicable for objects of type String");
|
||||||
|
}
|
||||||
|
|
||||||
|
match = target.equals(compareTo);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.negate != match;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean compareNumbers(double nTarget, double nAgainst) {
|
||||||
|
switch (this.op) {
|
||||||
|
case "=":
|
||||||
|
return nTarget == nAgainst;
|
||||||
|
case "<":
|
||||||
|
return nTarget < nAgainst;
|
||||||
|
case "<=":
|
||||||
|
return nTarget <= nAgainst;
|
||||||
|
case ">":
|
||||||
|
return nTarget > nAgainst;
|
||||||
|
case ">=":
|
||||||
|
return nTarget >= nAgainst;
|
||||||
|
default:
|
||||||
|
throw new SyntaxException("operator " + this.op + " is not applicable for objects of type Number");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
if (this.obj != -1 && this.op != null && this.against != null && this.result != null) {
|
||||||
|
int h = 31 * this.obj + (this.negate ? 33 : 31) * this.op.hashCode() + this.against.hashCode() + this.result.hashCode();
|
||||||
|
return Math.abs(h);
|
||||||
|
} else {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return String.format("Branch[obj: %s, op: %s, negate: %s, against: %s, result: \"%s\"]", this.obj, this.op, this.negate, this.against, this.result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
package me.darksidecode.kantanj.formatting;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import jdk.nashorn.internal.runtime.regexp.joni.exception.SyntaxException;
|
||||||
|
|
||||||
|
public class ConditionalFormatter {
|
||||||
|
private static final String OPS = "~<=>";
|
||||||
|
private static final int EXPECTING_OBJ = 0;
|
||||||
|
private static final int EXPECTING_CONDITION = 1;
|
||||||
|
private static final int EXPECTING_RESULT = 2;
|
||||||
|
private static final int EXPECT_RANGE_START = 0;
|
||||||
|
private static final int EXPECT_ONE_DOT = 1;
|
||||||
|
private static final int EXPECT_RANGE_END = 2;
|
||||||
|
private final List<Condition> conditions = new ArrayList<>();
|
||||||
|
private String plainTail = "";
|
||||||
|
private boolean openingQuote;
|
||||||
|
private int lastQuotePos;
|
||||||
|
private int state = 0;
|
||||||
|
private int rangeSpecState = 0;
|
||||||
|
private StringBuilder curNum = new StringBuilder();
|
||||||
|
private StringBuilder op = new StringBuilder();
|
||||||
|
private StringBuilder against = new StringBuilder();
|
||||||
|
private StringBuilder result = new StringBuilder();
|
||||||
|
private Condition.Branch curBranch = new Condition.Branch();
|
||||||
|
private Condition curCond;
|
||||||
|
private boolean appendCurNum;
|
||||||
|
private boolean elseBranch;
|
||||||
|
private boolean rangeSpec;
|
||||||
|
|
||||||
|
public ConditionalFormatter(String s) {
|
||||||
|
if (s != null && !s.trim().isEmpty()) {
|
||||||
|
char[] chars = s.toCharArray();
|
||||||
|
StringBuilder pre = new StringBuilder();
|
||||||
|
|
||||||
|
for (int i = 0; i < chars.length; i++) {
|
||||||
|
char c = chars[i];
|
||||||
|
if (c == '\'') {
|
||||||
|
this.openingQuote = !this.openingQuote;
|
||||||
|
this.lastQuotePos = i;
|
||||||
|
if (this.openingQuote) {
|
||||||
|
if (i == chars.length - 1) {
|
||||||
|
throw new SyntaxException("unclosed quote at char " + (i + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
i = this.parseCondition(chars, i, pre.toString());
|
||||||
|
pre = new StringBuilder();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
pre.append(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.openingQuote) {
|
||||||
|
throw new SyntaxException("unclosed quote at char " + (this.lastQuotePos + 1));
|
||||||
|
} else {
|
||||||
|
if (pre.length() > 0) {
|
||||||
|
this.plainTail = pre.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
this.conditions.forEach(Condition::validate);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
throw new IllegalArgumentException("input string cannot be empty");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int parseCondition(char[] chars, int start, String pre) {
|
||||||
|
char[] innerChars = this.getInner(chars, start);
|
||||||
|
this.curCond = new Condition();
|
||||||
|
this.curCond.pre = pre;
|
||||||
|
|
||||||
|
for (int pos = 0; pos < innerChars.length; pos++) {
|
||||||
|
char ic = innerChars[pos];
|
||||||
|
boolean skipSpace = ic == ' ' && this.state != 2;
|
||||||
|
boolean skipColon = ic == ':' && this.elseBranch;
|
||||||
|
if (!skipSpace && !skipColon) {
|
||||||
|
switch (this.state) {
|
||||||
|
case 0:
|
||||||
|
this.parseExpectingObj(ic, start, pos);
|
||||||
|
break;
|
||||||
|
case 1:
|
||||||
|
this.parseExpectingCondition(ic, start, pos);
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
int skip = this.parseExpectingResult(ic, start, pos);
|
||||||
|
if (skip != -1) {
|
||||||
|
return skip;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new IllegalStateException(Integer.toString(this.state));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new SyntaxException("unterminated condition at char " + (start + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void parseExpectingObj(char ic, int start, int pos) {
|
||||||
|
if (ic == '*') {
|
||||||
|
this.elseBranch = true;
|
||||||
|
this.state = 2;
|
||||||
|
} else if (ic == '{') {
|
||||||
|
this.appendCurNum = true;
|
||||||
|
} else if (this.appendCurNum) {
|
||||||
|
if (ic == '}') {
|
||||||
|
if (this.curNum.length() == 0) {
|
||||||
|
throw new SyntaxException("empty pointer at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.curBranch.obj = Integer.parseInt(this.curNum.toString());
|
||||||
|
this.curNum = new StringBuilder();
|
||||||
|
this.appendCurNum = false;
|
||||||
|
this.state = 1;
|
||||||
|
} else {
|
||||||
|
if (!Character.isDigit(ic)) {
|
||||||
|
throw new SyntaxException("invalid non-int pointer at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.curNum.append(ic);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void parseExpectingCondition(char ic, int start, int pos) {
|
||||||
|
boolean operatorChar = "~<=>".indexOf(ic) != -1;
|
||||||
|
if (!this.rangeSpec) {
|
||||||
|
this.rangeSpec = this.op.length() == 1 && this.op.charAt(0) == '~';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ic == '!') {
|
||||||
|
this.curBranch.negate = true;
|
||||||
|
} else if (!operatorChar && !this.rangeSpec) {
|
||||||
|
if (this.curBranch.op == null) {
|
||||||
|
if (this.op.length() == 0) {
|
||||||
|
throw new SyntaxException("empty comparison operator at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.curBranch.op = this.op.toString();
|
||||||
|
this.op = new StringBuilder();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ic == ':') {
|
||||||
|
if (this.against.length() == 0) {
|
||||||
|
throw new SyntaxException("nothing to compare to at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.curBranch.against = this.against.toString();
|
||||||
|
this.against = new StringBuilder();
|
||||||
|
this.state = 2;
|
||||||
|
} else {
|
||||||
|
this.against.append(ic);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
boolean prevCharDigit = this.op.length() > 1 && Character.isDigit(this.op.charAt(this.op.length() - 1));
|
||||||
|
this.op.append(ic);
|
||||||
|
if (this.rangeSpec) {
|
||||||
|
boolean validChar = ic == '.' || ic == ':' || Character.isDigit(ic);
|
||||||
|
if (!validChar) {
|
||||||
|
throw new SyntaxException(String.format("illegal symbol %s in range spec at char %s", ic, start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.rangeSpecState == 0 && ic == '.') {
|
||||||
|
if (!prevCharDigit) {
|
||||||
|
throw new SyntaxException("expected range start number at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.rangeSpecState = 1;
|
||||||
|
} else if (this.rangeSpecState == 1) {
|
||||||
|
if (ic != '.') {
|
||||||
|
throw new SyntaxException("expected range start/end separator \"..\" at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.rangeSpecState = 2;
|
||||||
|
} else if (this.rangeSpecState == 2) {
|
||||||
|
if (ic == '.') {
|
||||||
|
throw new SyntaxException("expected colon \":\" at the end of range spec at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ic == ':') {
|
||||||
|
if (!prevCharDigit) {
|
||||||
|
throw new SyntaxException("expected range end number at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.curBranch.op = "~";
|
||||||
|
this.curBranch.against = this.op.substring(1, this.op.length() - 1);
|
||||||
|
this.rangeSpecState = 0;
|
||||||
|
this.rangeSpec = false;
|
||||||
|
this.op = new StringBuilder();
|
||||||
|
this.against = new StringBuilder();
|
||||||
|
this.state = 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private int parseExpectingResult(char ic, int start, int pos) {
|
||||||
|
if (ic == '|') {
|
||||||
|
if (this.elseBranch) {
|
||||||
|
throw new SyntaxException("else branch must be the last branch of a condition: unexpected OR operator at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
String r = this.result.toString().trim();
|
||||||
|
if (r.isEmpty()) {
|
||||||
|
throw new SyntaxException("expected result at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.curBranch.result = r;
|
||||||
|
this.curCond.branches.add(this.curBranch);
|
||||||
|
this.result = new StringBuilder();
|
||||||
|
this.curBranch = new Condition.Branch();
|
||||||
|
this.state = 0;
|
||||||
|
} else {
|
||||||
|
if (ic == '\'') {
|
||||||
|
if (!this.elseBranch) {
|
||||||
|
throw new SyntaxException("illegal condition end: missing else branch at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
String r = this.result.toString().trim();
|
||||||
|
if (r.isEmpty()) {
|
||||||
|
throw new SyntaxException("expected result at char " + (start + 1 + pos + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
this.openingQuote = !this.openingQuote;
|
||||||
|
this.lastQuotePos = start;
|
||||||
|
this.curBranch.result = r;
|
||||||
|
this.curCond.elseBranch = this.curBranch;
|
||||||
|
this.conditions.add(this.curCond);
|
||||||
|
return start + pos + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.result.append(ic);
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
private char[] getInner(char[] chars, int start) {
|
||||||
|
StringBuilder inner = new StringBuilder();
|
||||||
|
|
||||||
|
for (int j = start + 1; j < chars.length; j++) {
|
||||||
|
char next = chars[j];
|
||||||
|
inner.append(next);
|
||||||
|
if (next == '\'') {
|
||||||
|
if (j == start + 1) {
|
||||||
|
throw new SyntaxException("empty condition at char " + (start + 1));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return inner.toString().toCharArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String format(Object... args) {
|
||||||
|
if (args == null) {
|
||||||
|
throw new NullPointerException("args cannot be null");
|
||||||
|
} else {
|
||||||
|
StringBuilder formatted = new StringBuilder();
|
||||||
|
this.conditions.forEach(cond -> formatted.append(cond.apply(args)));
|
||||||
|
String f = formatted.toString() + this.plainTail;
|
||||||
|
|
||||||
|
for (int i = 0; i < args.length; i++) {
|
||||||
|
Object o = args[i];
|
||||||
|
if (o == null) {
|
||||||
|
throw new NullPointerException("object at index " + i + " must not be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
f = f.replace("{" + i + "}", o.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package me.darksidecode.kantanj.formatting;
|
||||||
|
|
||||||
|
import java.io.UnsupportedEncodingException;
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
|
||||||
|
public final class Formatting {
|
||||||
|
private Formatting() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String urlEncodeUtf8(String s) {
|
||||||
|
try {
|
||||||
|
return URLEncoder.encode(Check.notNull(s, "cannot encode null string"), "UTF-8");
|
||||||
|
} catch (UnsupportedEncodingException ignored) {
|
||||||
|
throw new RuntimeException("error in utf8 url encoding for string: " + s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String unixLines(String s) {
|
||||||
|
return s.replace("\r\n", "\n").replace("\r", "\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package me.darksidecode.kantanj.formatting;
|
||||||
|
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.FileInputStream;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.charset.Charset;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import javax.xml.bind.DatatypeConverter;
|
||||||
|
|
||||||
|
public enum Hash {
|
||||||
|
MD5("MD5"),
|
||||||
|
SHA1("SHA1"),
|
||||||
|
SHA256("SHA-256"),
|
||||||
|
SHA512("SHA-512");
|
||||||
|
|
||||||
|
private String name;
|
||||||
|
|
||||||
|
private Hash(String name) {
|
||||||
|
this.name = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getName() {
|
||||||
|
return this.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] checksum(File input) {
|
||||||
|
try (InputStream in = new FileInputStream(input)) {
|
||||||
|
MessageDigest digest = MessageDigest.getInstance(this.name);
|
||||||
|
byte[] block = new byte[4096];
|
||||||
|
|
||||||
|
int length;
|
||||||
|
while ((length = in.read(block)) > 0) {
|
||||||
|
digest.update(block, 0, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
return digest.digest();
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("failed to get checksum of " + input.getAbsolutePath(), ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String checksumString(File input) {
|
||||||
|
return DatatypeConverter.printHexBinary(this.checksum(input));
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] checksum(byte[] input) {
|
||||||
|
try {
|
||||||
|
MessageDigest digest = MessageDigest.getInstance(this.name);
|
||||||
|
digest.update(input);
|
||||||
|
return digest.digest();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("failed to get checksum of " + input.length + " bytes", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String checksumString(byte[] input) {
|
||||||
|
return DatatypeConverter.printHexBinary(this.checksum(input));
|
||||||
|
}
|
||||||
|
|
||||||
|
public byte[] checksum(String input, Charset encoding) {
|
||||||
|
return this.checksum(input.getBytes(encoding));
|
||||||
|
}
|
||||||
|
|
||||||
|
public String checksumString(String input, Charset encoding) {
|
||||||
|
return DatatypeConverter.printHexBinary(this.checksum(input, encoding));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
package me.darksidecode.kantanj.ipapi;
|
||||||
|
|
||||||
|
import com.google.common.cache.Cache;
|
||||||
|
import com.google.common.cache.CacheBuilder;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
import me.darksidecode.kantanj.formatting.CommonJson;
|
||||||
|
import me.darksidecode.kantanj.networking.GetHttpRequest;
|
||||||
|
import me.darksidecode.kantanj.networking.Networking;
|
||||||
|
import me.darksidecode.kantanj.system.Threads;
|
||||||
|
import me.darksidecode.kantanj.time.ExpiringList;
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
import org.apache.http.entity.ContentType;
|
||||||
|
|
||||||
|
public class IPAPI {
|
||||||
|
public static final String BASE_URL = "http://ip-api.com";
|
||||||
|
private static final int MAX_REQUESTS_PER_MIN = 145;
|
||||||
|
private static final long MIN_BLOCK_MILLIS = 1000L;
|
||||||
|
private static boolean enableCaching = true;
|
||||||
|
private static boolean blockOnLimitExcess = true;
|
||||||
|
private static long threadBlockMillis = TimeUnit.SECONDS.toMillis(30L);
|
||||||
|
private static final ExpiringList requestCounter = new ExpiringList(1L, TimeUnit.MINUTES);
|
||||||
|
private static final Cache<Integer, IPAddress> cache = CacheBuilder.newBuilder().expireAfterWrite(1L, TimeUnit.DAYS).build();
|
||||||
|
private static final Object cacheLock = new Object();
|
||||||
|
private static final Object requestLock = new Object();
|
||||||
|
|
||||||
|
public static void setThreadBlockTime(long blockTime, TimeUnit timeUnit) {
|
||||||
|
if (blockTime < 1L) {
|
||||||
|
throw new IllegalArgumentException("blockTime cannot be negative or zero");
|
||||||
|
} else {
|
||||||
|
long millis = Check.notNull(timeUnit, "timeUnit cannot be null").toMillis(blockTime);
|
||||||
|
if (millis < 1000L) {
|
||||||
|
throw new IllegalArgumentException("cannot block for less than 1 second");
|
||||||
|
} else {
|
||||||
|
threadBlockMillis = millis;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IPAddress info(InetAddress address) {
|
||||||
|
return info(address.getHostAddress());
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IPAddress info(InetAddress address, IPAPILanguage lang) {
|
||||||
|
return info(address.getHostAddress(), lang);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IPAddress info(String ip) {
|
||||||
|
return info(ip, IPAPILanguage.ENGLISH);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IPAddress info(String ip, IPAPILanguage lang) {
|
||||||
|
if (enableCaching) {
|
||||||
|
IPAPI.IPAPIRequest ipapiRequest = new IPAPI.IPAPIRequest(ip, lang);
|
||||||
|
int hash = ipapiRequest.hashCode();
|
||||||
|
synchronized (cacheLock) {
|
||||||
|
IPAddress cached = (IPAddress)cache.getIfPresent(hash);
|
||||||
|
if (cached != null) {
|
||||||
|
return cached;
|
||||||
|
} else {
|
||||||
|
IPAddress ipAddr = info0(ip, lang);
|
||||||
|
cache.put(hash, ipAddr);
|
||||||
|
return ipAddr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return info0(ip, lang);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static IPAddress info0(String ip, IPAPILanguage lang) {
|
||||||
|
synchronized (requestLock) {
|
||||||
|
int requestsLastMin = requestCounter.updateAndCount();
|
||||||
|
if (requestsLastMin > 145 && blockOnLimitExcess) {
|
||||||
|
Threads.sleepQuietly(threadBlockMillis);
|
||||||
|
}
|
||||||
|
|
||||||
|
GetHttpRequest request = (GetHttpRequest)new GetHttpRequest()
|
||||||
|
.baseUrl("http://ip-api.com")
|
||||||
|
.path("json/" + ip)
|
||||||
|
.queryParam("lang", lang.getIso639Name())
|
||||||
|
.requestProperty("Content-Type", ContentType.APPLICATION_JSON.toString())
|
||||||
|
.userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101");
|
||||||
|
String response = Networking.Http.get(request);
|
||||||
|
return CommonJson.fromJson(response, IPAddress.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isEnableCaching() {
|
||||||
|
return enableCaching;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setEnableCaching(boolean enableCaching) {
|
||||||
|
IPAPI.enableCaching = enableCaching;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static boolean isBlockOnLimitExcess() {
|
||||||
|
return blockOnLimitExcess;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void setBlockOnLimitExcess(boolean blockOnLimitExcess) {
|
||||||
|
IPAPI.blockOnLimitExcess = blockOnLimitExcess;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class IPAPIRequest {
|
||||||
|
private final String ip;
|
||||||
|
private final IPAPILanguage lang;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public int hashCode() {
|
||||||
|
return this.ip.hashCode() + this.lang.name().hashCode();
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getIp() {
|
||||||
|
return this.ip;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IPAPILanguage getLang() {
|
||||||
|
return this.lang;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IPAPIRequest(String ip, IPAPILanguage lang) {
|
||||||
|
this.ip = ip;
|
||||||
|
this.lang = lang;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package me.darksidecode.kantanj.ipapi;
|
||||||
|
|
||||||
|
public enum IPAPILanguage {
|
||||||
|
ENGLISH("en", "English (default)"),
|
||||||
|
GERMAN("de", "Deutsch (German)"),
|
||||||
|
SPANISH("es", "Español (Spanish)"),
|
||||||
|
PORTUGUESE("pt-BR", "Español - Argentina (Spanish)"),
|
||||||
|
FRENCH("fr", "Français (French)"),
|
||||||
|
JAPANESE("ja", "日本語 (Japanese)"),
|
||||||
|
CHINESE("zh-CN", "中国 (Chinese)"),
|
||||||
|
RUSSIAN("ru", "Русский (Russian)");
|
||||||
|
|
||||||
|
private final String iso639Name;
|
||||||
|
private final String description;
|
||||||
|
|
||||||
|
private IPAPILanguage(String iso639Name, String description) {
|
||||||
|
this.iso639Name = iso639Name;
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getIso639Name() {
|
||||||
|
return this.iso639Name;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return this.description;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
package me.darksidecode.kantanj.ipapi;
|
||||||
|
|
||||||
|
import com.google.gson.Gson;
|
||||||
|
import java.io.Serializable;
|
||||||
|
import me.darksidecode.kantanj.formatting.CommonJson;
|
||||||
|
|
||||||
|
public class IPAddress implements Serializable {
|
||||||
|
private static final long serialVersionUID = 1423606597409892108L;
|
||||||
|
private String status;
|
||||||
|
private String message;
|
||||||
|
private String country;
|
||||||
|
private String countryCode;
|
||||||
|
private String region;
|
||||||
|
private String regionName;
|
||||||
|
private String city;
|
||||||
|
private String district;
|
||||||
|
private String zip;
|
||||||
|
private float lat;
|
||||||
|
private float lon;
|
||||||
|
private String timezone;
|
||||||
|
private String isp;
|
||||||
|
private String org;
|
||||||
|
private String as;
|
||||||
|
private String reverse;
|
||||||
|
private boolean cellular;
|
||||||
|
private boolean proxy;
|
||||||
|
private String query;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String toString() {
|
||||||
|
return this.toString(CommonJson.getPrettyGsonNoHtmlEsc());
|
||||||
|
}
|
||||||
|
|
||||||
|
public String toString(Gson gson) {
|
||||||
|
return gson.toJson(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getStatus() {
|
||||||
|
return this.status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getMessage() {
|
||||||
|
return this.message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCountry() {
|
||||||
|
return this.country;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCountryCode() {
|
||||||
|
return this.countryCode;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRegion() {
|
||||||
|
return this.region;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRegionName() {
|
||||||
|
return this.regionName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCity() {
|
||||||
|
return this.city;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDistrict() {
|
||||||
|
return this.district;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getZip() {
|
||||||
|
return this.zip;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getLat() {
|
||||||
|
return this.lat;
|
||||||
|
}
|
||||||
|
|
||||||
|
public float getLon() {
|
||||||
|
return this.lon;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTimezone() {
|
||||||
|
return this.timezone;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getIsp() {
|
||||||
|
return this.isp;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getOrg() {
|
||||||
|
return this.org;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getAs() {
|
||||||
|
return this.as;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getReverse() {
|
||||||
|
return this.reverse;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isCellular() {
|
||||||
|
return this.cellular;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isProxy() {
|
||||||
|
return this.proxy;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getQuery() {
|
||||||
|
return this.query;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package me.darksidecode.kantanj.logging;
|
||||||
|
|
||||||
|
import java.io.PrintStream;
|
||||||
|
|
||||||
|
public interface BasicLogger {
|
||||||
|
default boolean isEnableDebug() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
default void setEnableDebug() {
|
||||||
|
throw new UnsupportedOperationException("setEnableDebug is not implemented in " + this.getClass().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
default void debug(String message, Object... format) {
|
||||||
|
if (this.isEnableDebug()) {
|
||||||
|
this.print(System.out, message, format);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
default void info(String message, Object... format) {
|
||||||
|
this.print(System.out, message, format);
|
||||||
|
}
|
||||||
|
|
||||||
|
default void warning(String message, Object... format) {
|
||||||
|
this.print(System.err, message, format);
|
||||||
|
}
|
||||||
|
|
||||||
|
default void error(String message, Object... format) {
|
||||||
|
this.print(System.err, message, format);
|
||||||
|
}
|
||||||
|
|
||||||
|
default void print(PrintStream printStream, String message, Object... format) {
|
||||||
|
message = format != null && format.length > 0 ? String.format(message, format) : message;
|
||||||
|
printStream.println(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package me.darksidecode.kantanj.networking;
|
||||||
|
|
||||||
|
public class GetHttpRequest extends SimpleHttpRequest {
|
||||||
|
public GetHttpRequest done() {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SimpleHttpRequest requestMethod(RequestMethod requestMethod) {
|
||||||
|
throw new IllegalStateException("cannot change request method for " + this.getClass().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public RequestMethod getRequestMethod() {
|
||||||
|
return RequestMethod.GET;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SimpleHttpRequest doInput(boolean doInput) {
|
||||||
|
throw new IllegalStateException("cannot change doInput for " + this.getClass().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean shouldDoInput() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public SimpleHttpRequest doOutput(boolean doOutput) {
|
||||||
|
throw new IllegalStateException("cannot change doOutput for " + this.getClass().getName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean shouldDoOutput() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package me.darksidecode.kantanj.networking;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public interface HttpRequest {
|
||||||
|
String getUserAgent() throws IllegalStateException;
|
||||||
|
|
||||||
|
RequestMethod getRequestMethod() throws IllegalStateException;
|
||||||
|
|
||||||
|
boolean isSecured() throws IllegalStateException;
|
||||||
|
|
||||||
|
Map<String, String> getRequestProperties();
|
||||||
|
|
||||||
|
int getConnectTimeout();
|
||||||
|
|
||||||
|
int getReadTimeout();
|
||||||
|
|
||||||
|
boolean shouldFollowRedirects();
|
||||||
|
|
||||||
|
boolean shouldDoInput();
|
||||||
|
|
||||||
|
boolean shouldDoOutput();
|
||||||
|
|
||||||
|
String getURL() throws IllegalStateException;
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package me.darksidecode.kantanj.networking;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.io.OutputStream;
|
||||||
|
import java.net.HttpURLConnection;
|
||||||
|
import java.net.Inet4Address;
|
||||||
|
import java.net.InetAddress;
|
||||||
|
import java.net.URL;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.Map;
|
||||||
|
import me.darksidecode.kantanj.types.Check;
|
||||||
|
import org.apache.commons.io.IOUtils;
|
||||||
|
import org.apache.http.entity.ContentType;
|
||||||
|
|
||||||
|
public final class Networking {
|
||||||
|
private Networking() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void removeJavaUserAgentSuffixGlobally() {
|
||||||
|
System.setProperty("http.agent", "");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String resolveIPv4(String host) {
|
||||||
|
try {
|
||||||
|
Check.notNull(host, "host cannot be null");
|
||||||
|
|
||||||
|
for (InetAddress inetAddress : InetAddress.getAllByName(host)) {
|
||||||
|
if (inetAddress instanceof Inet4Address) {
|
||||||
|
return inetAddress.getHostAddress();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new UnknownHostException("unknown host " + host);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
throw new RuntimeException("failed to resolve IPv4 of " + host, ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static final class Http {
|
||||||
|
private Http() {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String post(PostHttpRequest request) {
|
||||||
|
try {
|
||||||
|
HttpURLConnection con = openConnection(request);
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
OutputStream outputStream = con.getOutputStream();
|
||||||
|
outputStream.write(request.getPostData());
|
||||||
|
outputStream.close();
|
||||||
|
if (request.shouldDoInput()) {
|
||||||
|
return readResponseAndDisconnect(con, response);
|
||||||
|
} else {
|
||||||
|
con.disconnect();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException("http POST request failed", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String get(GetHttpRequest request) {
|
||||||
|
try {
|
||||||
|
HttpURLConnection con = openConnection(request);
|
||||||
|
StringBuilder response = new StringBuilder();
|
||||||
|
return readResponseAndDisconnect(con, response);
|
||||||
|
} catch (Exception err) {
|
||||||
|
throw new RuntimeException("http GET request failed", err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static HttpURLConnection openConnection(HttpRequest request) {
|
||||||
|
Check.notNull(request, "request cannot be null");
|
||||||
|
|
||||||
|
try {
|
||||||
|
URL url = new URL(request.getURL());
|
||||||
|
HttpURLConnection con = (HttpURLConnection)url.openConnection();
|
||||||
|
con.setRequestMethod(request.getRequestMethod().name());
|
||||||
|
Map<String, String> requestProps = request.getRequestProperties();
|
||||||
|
|
||||||
|
for (String prop : requestProps.keySet()) {
|
||||||
|
con.setRequestProperty(prop, requestProps.get(prop));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request instanceof PostHttpRequest) {
|
||||||
|
if (!requestProps.containsKey("Content-Type")) {
|
||||||
|
con.setRequestProperty("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
con.setRequestProperty("Content-Length", String.valueOf(((PostHttpRequest)request).getPostData().length));
|
||||||
|
}
|
||||||
|
|
||||||
|
con.setRequestProperty("User-Agent", request.getUserAgent());
|
||||||
|
con.setInstanceFollowRedirects(request.shouldFollowRedirects());
|
||||||
|
con.setConnectTimeout(request.getConnectTimeout());
|
||||||
|
con.setReadTimeout(request.getReadTimeout());
|
||||||
|
con.setDoInput(request.shouldDoInput());
|
||||||
|
con.setDoOutput(request.shouldDoOutput());
|
||||||
|
return con;
|
||||||
|
} catch (Exception cause) {
|
||||||
|
throw new RuntimeException("failed to establish a new connection", cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String readResponseAndDisconnect(HttpURLConnection con, StringBuilder response) throws IOException {
|
||||||
|
InputStream inputStream = con.getInputStream();
|
||||||
|
|
||||||
|
for (String line : IOUtils.readLines(inputStream, StandardCharsets.UTF_8)) {
|
||||||
|
response.append(line).append('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
inputStream.close();
|
||||||
|
con.disconnect();
|
||||||
|
if (response.length() > 0 && response.charAt(response.length() - 1) == '\n') {
|
||||||
|
response.deleteCharAt(response.length() - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 430 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user