Compare commits

...
Author SHA1 Message Date
tr7zw ac9582d866 Merge pull request #136 from Toffikk/patch-1
Use Mojang Mappings for fabric mod (3.0-Indev)
2021-08-23 11:49:08 +02:00
Tofik ♡ dc8b6d7611 use mojang mappings for fabric mod 2021-08-21 12:22:50 +02:00
Tofik ♡ a26eb4d725 Update ExampleMixin.java 2021-08-21 12:20:58 +02:00
tr7zw 42ba0475fc Add forge 2021-07-29 20:53:26 +02:00
tr7zw 8a21928afe Merge pull request #132 from spnda/3.0/dev/gradle
Change: Switch to Gradle
2021-07-29 20:39:49 +02:00
tr7zw 4b4f9d0619 Init fabric 1.17 2021-07-29 20:37:45 +02:00
tr7zw fd2abb59b1 Working builds, Parallel builds 2021-07-29 20:24:27 +02:00
spnda ac527eb260 Fix: Tell Dependabot to check for Gradle 2021-07-29 19:05:46 +02:00
spnda b40e53ab79 Fix: Use Gradle for the GH build runner 2021-07-29 19:05:46 +02:00
spnda bbc2c3a6b6 Change: Switch to Gradle
As support for other minecraft modloaders other than Spigot might be supported in the future, we need Gradle to properly build those.
2021-07-29 19:05:03 +02:00
tr7zw 2755718055 Make setters fluent 2021-07-29 18:04:02 +02:00
tr7zw d628ed3810 Some more api prototyping 2021-07-29 18:00:00 +02:00
tr7zw e8f25db579 Merge pull request #133 from spnda/3.0/dev/main
Fix: Add missing NBTType.NBTTagLongArray
2021-07-28 22:10:19 +02:00
spnda 689a131132 Fix: Add missing NBTType.NBTTagLongArray 2021-07-18 13:39:08 +02:00
tr7zw c1903c1a2d Some interface prototyping, nothing set in stone 2021-07-16 20:13:25 +02:00
tr7zw 144a62bb69 Kill the maven build on the 3.0 branch during the design phase 2021-07-16 19:45:12 +02:00
tr7zw 46dc3dd8eb Merge pull request #131 from spnda/3.0/dev/main
Rename to NBTApiException and fix many formalities
2021-07-16 19:40:09 +02:00
spnda 9fede0b017 Update some formalities and javadocs
Renames NbtApiException to NBTApiException to keep it consistent with the rest of the NBT classes. Also adds and fixes some javadocs in the Readable and Writeable interfaces.
2021-07-16 16:36:20 +02:00
spnda 24925e1212 Fix: Unnecessary loop in NBTType#valueOf 2021-07-16 16:07:29 +02:00
tr7zw d08b8784ed Seperate out legacy using tests 2021-07-16 00:01:06 +02:00
tr7zw fda522bedc Clear up some more stuff 2021-07-15 23:55:38 +02:00
tr7zw a7b816cf50 Remove classes from the api module 2021-07-15 23:42:03 +02:00
tr7zw 39f698039d Format project structure 2021-07-15 23:10:51 +02:00
tr7zw 06ec328037 @Deprecated(forRemoval = false) not supported in java 8 2021-07-15 20:36:51 +02:00
tr7zw e51e0e4e47 Init 3.0 INDEV branch 2021-07-15 20:20:32 +02:00
149 changed files with 3758 additions and 5016 deletions

No files matched your search

+1 -8
View File
@@ -1,14 +1,7 @@
version: 2
updates:
- package-ecosystem: maven
- package-ecosystem: gradle
directory: "/"
schedule:
interval: daily
open-pull-requests-limit: 10
ignore:
- dependency-name: com.github.ekryd.sortpom:sortpom-maven-plugin
versions:
- 2.13.1
- 2.14.0
- 2.14.1
- 2.15.0
+16
View File
@@ -0,0 +1,16 @@
name: Java CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up JDK 1.8
uses: actions/setup-java@v2
with:
distribution: 'adopt'
java-version: 8.0.292
- name: Build project
run: ./gradlew build
-17
View File
@@ -1,17 +0,0 @@
name: Java CI
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Set up JDK 1.8
uses: actions/setup-java@v1
with:
java-version: 1.8
- name: Build with Maven
run: mvn --file pom.xml
+6 -1
View File
@@ -6,6 +6,8 @@
*.war
*.ear
!gradle/wrapper/gradle-wrapper.jar
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
@@ -101,4 +103,7 @@ nb-configuration.xml
### Git ###
# Don't exclude the .gitignore itself
!.gitignore
!.gitignore
### VSCode
*.pdf
+4 -2
View File
@@ -1,11 +1,13 @@
# Item-NBT-API
# WIP Indev Branch!
Version 3.0 is not done, not ready for production and will still change! Please keep using the latest 2.x builds for now!
# NBT-API
Add custom NBT tags to Items/Tiles/Entities without NMS! Modify NBT and store it Files, other NBT or as String in yaml/json/SQL/Redis.
[Server Owner/Developer Wiki](https://github.com/tr7zw/Item-NBT-API/wiki)
### Build/Maven/Sonar Status
[![Build Status](https://ci.codemc.org/buildStatus/icon?job=Tr7zw%2FItem-NBT-API)](https://ci.codemc.org/job/Tr7zw/job/Item-NBT-API/)[![](https://sonarcloud.io/api/project_badges/measure?project=de.tr7zw%3Aitem-nbt-parent&metric=alert_status)](https://sonarcloud.io/dashboard?id=de.tr7zw%3Aitem-nbt-parent)[![](https://sonarcloud.io/api/project_badges/measure?project=de.tr7zw%3Aitem-nbt-parent&metric=ncloc)](https://sonarcloud.io/dashboard?id=de.tr7zw%3Aitem-nbt-parent)[![](https://sonarcloud.io/api/project_badges/measure?project=de.tr7zw%3Aitem-nbt-parent&metric=duplicated_lines_density)](https://sonarcloud.io/dashboard?id=de.tr7zw%3Aitem-nbt-parent)[![](https://sonarcloud.io/api/project_badges/measure?project=de.tr7zw%3Aitem-nbt-parent&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=de.tr7zw%3Aitem-nbt-parent)
[![Discord](https://img.shields.io/discord/342814924310970398?color=%237289DA&label=Discord&logo=discord&logoColor=white)](https://discordapp.com/invite/yk4caxM)
[![Patreon](https://img.shields.io/endpoint.svg?url=https%3A%2F%2Fshieldsio-patreon.vercel.app%2Fapi%3Fusername%3Dtr7zw%26type%3Dpatrons&style=for-the-badge)](https://www.patreon.com/tr7zw)
### SpigotMC Status
[![Version](https://badges.spiget.org/resources/version/Version-yellow-7939.svg)](https://www.spigotmc.org/resources/item-entity-tile-nbt-api.7939/)[![Rating](https://badges.spiget.org/resources/rating/Rating-yellow-7939.svg)](https://www.spigotmc.org/resources/item-entity-tile-nbt-api.7939/)[![Rating](https://badges.spiget.org/resources/downloads/SpigotDownloads-yellow-7939.svg)](https://www.spigotmc.org/resources/item-entity-tile-nbt-api.7939/)[![bStats Servers](https://img.shields.io/bstats/servers/1058.svg?color=green&label=OnlineServers&style=plastic)](https://bstats.org/plugin/bukkit/ItemNBTAPI)[![bStats Players](https://img.shields.io/bstats/players/1058.svg?color=green&label=OnlinePlayers&style=plastic)](https://bstats.org/plugin/bukkit/ItemNBTAPI)[![All Contributors](https://img.shields.io/badge/all_contributors-13-green.svg?style=plastic)](#contributors-%e2%9c%a8)
+42
View File
@@ -0,0 +1,42 @@
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
}
plugins {
id 'java'
}
def version = project.nbtapi_version
allprojects {
repositories {
mavenLocal()
maven {
name = 'Spigot'
url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/'
}
maven {
name = 'CodeMC'
url = 'https://repo.codemc.org/repository/maven-public/'
}
maven {
name = 'CodeMC NMS'
url = 'https://repo.codemc.org/repository/nms/'
}
maven {
name = 'Mojang'
url = 'https://libraries.minecraft.net/'
}
mavenCentral()
}
processResources {
inputs.property("version", version)
expand([version: version])
}
}
+10
View File
@@ -0,0 +1,10 @@
plugins {
id 'java-library'
}
dependencies {
api 'de.tr7zw:functional-annotations:0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
+1
View File
@@ -0,0 +1 @@
rootProject.name = 'nbt-api'
@@ -0,0 +1,7 @@
package dev.tr7zw.nbtapi;
public interface INBTItemStack<I> extends NBTCompoundAccessor, NBTCompound {
public I getItemStack();
}
@@ -0,0 +1,52 @@
package dev.tr7zw.nbtapi;
/**
* A generic {@link RuntimeException} that can be thrown by most methods in the
* NBT-API in case of compatibility or logic issues.
*
* @author tr7zw
*/
public class NBTApiException extends RuntimeException {
private static final long serialVersionUID = -993309714559452334L;
/**
*
*/
public NBTApiException() {
super();
}
/**
* @param message
* @param cause
* @param enableSuppression
* @param writableStackTrace
*/
public NBTApiException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
/**
* @param message
* @param cause
*/
public NBTApiException(String message, Throwable cause) {
super(message, cause);
}
/**
* @param message
*/
public NBTApiException(String message) {
super(message);
}
/**
* @param cause
*/
public NBTApiException(Throwable cause) {
super(cause);
}
}
@@ -0,0 +1,13 @@
package dev.tr7zw.nbtapi;
public interface NBTCompound extends NBTCompoundAccessor, Writeable<NBTCompound> {
/**
* Gets an existing compound, or creates it if it
* doesn't exist yet.
*
* @param name The key of the compound.
*/
NBTCompound getOrCreateCompound(String name);
}
@@ -0,0 +1,5 @@
package dev.tr7zw.nbtapi;
public interface NBTCompoundAccessor extends Readable {
}
@@ -0,0 +1,16 @@
package dev.tr7zw.nbtapi;
/**
* Double implementation for NBTLists
*
* @author tr7zw
*
*/
public abstract class NBTDoubleList extends NBTList<Double> {
@Override
public NBTType getType() {
return NBTType.NBTTagDouble;
}
}
@@ -0,0 +1,16 @@
package dev.tr7zw.nbtapi;
/**
* Float implementation for NBTLists
*
* @author tr7zw
*
*/
public abstract class NBTFloatList extends NBTList<Float> {
@Override
public NBTType getType() {
return NBTType.NBTTagFloat;
}
}
@@ -0,0 +1,16 @@
package dev.tr7zw.nbtapi;
/**
* Integer implementation for NBTLists
*
* @author tr7zw
*
*/
public abstract class NBTIntegerList extends NBTList<Integer> {
@Override
public NBTType getType() {
return NBTType.NBTTagInt;
}
}
@@ -0,0 +1,22 @@
package dev.tr7zw.nbtapi;
import java.util.List;
/**
* Abstract List implementation for ListCompounds
*
* @author tr7zw
*
* @param <T>
*/
public abstract class NBTList<T> implements List<T> {
protected abstract Object asTag(T object);
/**
* @return The type that this list contains
*/
public abstract NBTType getType();
}
@@ -0,0 +1,41 @@
package dev.tr7zw.nbtapi;
/**
* Enum of all NBT Types Minecraft contains
*
* @author tr7zw
*
*/
public enum NBTType {
NBTTagEnd(),
NBTTagByte(),
NBTTagShort(),
NBTTagInt(),
NBTTagLong(),
NBTTagFloat(),
NBTTagDouble(),
NBTTagByteArray(),
NBTTagString(),
NBTTagList(),
NBTTagCompound(),
NBTTagIntArray(),
NBTTagLongArray();
/**
* @return Id used by Minecraft internally
*/
public int getId() {
return ordinal();
}
/**
* @param id Internal Minecraft ID
* @return Enum representing the ID, NBTTagEnd for invalid IDs
*/
public static NBTType valueOf(int id) {
NBTType[] values = values();
if (id >= values.length || id < 0)
return NBTTagEnd;
return values[id];
}
}
@@ -0,0 +1,165 @@
package dev.tr7zw.nbtapi;
import java.util.Set;
import java.util.UUID;
public interface Readable {
/**
* Getter
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
String getString(String key);
/**
* Getter
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
Integer getInteger(String key);
/**
* Getter
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
Double getDouble(String key);
/**
* Getter
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
Byte getByte(String key);
/**
* Getter
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
Short getShort(String key);
/**
* Getter
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
Long getLong(String key);
/**
* Getter
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
Float getFloat(String key);
/**
* Getter
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
byte[] getByteArray(String key);
/**
* Getter
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
int[] getIntArray(String key);
/**
* Getter
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
Boolean getBoolean(String key);
/**
* Get the UUID at {@code key}.
*
* @param key The String key.
* @return The stored value or NMS fallback
*/
UUID getUUID(String key);
/**
* Get all keys of this tag.
*
* @return Set of all stored Keys
*/
Set<String> getKeys();
/**
* @param name The String key.
* @return The Compound instance or null
*/
Readable getCompound(String name);
/**
* @param name The String key.
* @return The retrieved String List
*/
NBTList<String> getStringList(String name);
/**
* @param name The String key.
* @return The retrieved Integer List
*/
NBTList<Integer> getIntegerList(String name);
/**
* @param name The String key.
* @return The retrieved Float List
*/
NBTList<Float> getFloatList(String name);
/**
* @param name The String key.
* @return The retrieved Double List
*/
NBTList<Double> getDoubleList(String name);
/**
* @param name The String key.
* @return The retrieved Long List
*/
NBTList<Long> getLongList(String name);
/**
* Returns the type of the list, null if not a list
*
* @param name The String key.
* @return The retrieved type.
*/
NBTType getListType(String name);
/**
* @param name The String key.
* @return The retrieved Compound List
*/
//NBTCompoundList getCompoundList(String name); //FIXME
/**
* @param name The String key.
* @return The type of the given stored key or null
*/
NBTType getType(String name);
/**
* @param name The String key.
* @return True when this key is available
*/
boolean hasKey(String name);
}
@@ -0,0 +1,124 @@
package dev.tr7zw.nbtapi;
import java.util.UUID;
public interface Writeable<W extends Writeable<W>> {
/**
* Merges all data from comp into this compound. This is done in one action, so
* it also works with Tiles/Entities
*
* @param comp
*/
void mergeCompound(Readable comp);
/**
* Setter
*
* @param key The String key.
* @param value
*/
W setString(String key, String value);
/**
* Setter
*
* @param key The String key.
* @param value
*/
W setInteger(String key, Integer value);
/**
* Setter
*
* @param key The String key.
* @param value
*/
W setDouble(String key, Double value);
/**
* Setter
*
* @param key The String key.
* @param value
*/
W setByte(String key, Byte value);
/**
* Setter
*
* @param key The String key.
* @param value
*/
W setShort(String key, Short value);
/**
* Setter
*
* @param key The String key.
* @param value
*/
W setLong(String key, Long value);
/**
* Setter
*
* @param key The String key.
* @param value
*/
W setFloat(String key, Float value);
/**
* Setter
*
* @param key The String key.
* @param value
*/
W setByteArray(String key, byte[] value);
/**
* Setter
*
* @param key The String key.
* @param value
*/
W setIntArray(String key, int[] value);
/**
* Setter
*
* @param key The String key.
* @param value
*/
W setBoolean(String key, Boolean value);
/**
* Set a UUID.
*
* @param key The String key.
* @param value The UUID value.
*/
W setUUID(String key, UUID value);
/**
* Removes the given key and its value.
*
* @param key The key to delete.
*/
W removeKey(String key);
/**
* @param name
* @return The retrieved String List
*/
NBTList<String> getStringList(String name);
/**
* Get the type of a key.
*
* @param name The String key.
* @return The type of the given stored key or null
*/
NBTType getType(String name);
}
@@ -0,0 +1,19 @@
package dev.tr7zw.nbtapi.handler;
import java.util.function.Consumer;
import java.util.function.Function;
import dev.tr7zw.nbtapi.NBTCompound;
import dev.tr7zw.nbtapi.NBTCompoundAccessor;
public interface EntityHandler<E> {
public NBTCompound getEntity(E entity);
public void modifyEntity(E entity, Consumer<NBTCompound> consumer);
public <T> T modifyEntity(E entity, Function<NBTCompound, T> consumer);
public <T> T parseEntity(E entity, Function<NBTCompoundAccessor, T> function);
}
@@ -0,0 +1,20 @@
package dev.tr7zw.nbtapi.handler;
import java.util.function.Consumer;
import java.util.function.Function;
import dev.tr7zw.nbtapi.INBTItemStack;
import dev.tr7zw.nbtapi.NBTCompound;
import dev.tr7zw.nbtapi.NBTCompoundAccessor;
public interface ItemHandler<I, W extends INBTItemStack<I>> {
public W getItemStack(I item);
public void modifyItemStack(I item, Consumer<NBTCompound> consumer);
public <T> T modifyItemStack(I item, Function<NBTCompound, T> consumer);
public <T> T parseItemStack(I item, Function<NBTCompoundAccessor, T> function);
}
@@ -3,18 +3,18 @@
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-parent</artifactId>
<version>2.8.1-SNAPSHOT</version>
<groupId>dev.tr7zw</groupId>
<artifactId>nbt-api-parent</artifactId>
<version>3.0.0-SNAPSHOT</version>
</parent>
<artifactId>nbt-data-api</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-api</artifactId>
<version>2.8.1-SNAPSHOT</version>
<groupId>dev.tr7zw</groupId>
<artifactId>nbt-api</artifactId>
<version>3.0.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
@@ -8,8 +8,8 @@ import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.plugin.Plugin;
import de.tr7zw.changeme.nbtapi.NBTFile;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import dev.tr7zw.nbtapi.NBTFile;
import dev.tr7zw.nbtapi.NBTApiException;
public class NBTData {
@@ -17,7 +17,7 @@ public class NBTData {
try {
return new WorldData(world.getWorldFolder());
} catch (IOException e) {
throw new NbtApiException("Error loading World Data!", e);
throw new NBTApiException("Error loading World Data!", e);
}
}
@@ -25,7 +25,7 @@ public class NBTData {
try {
return new WorldData(worldFolder);
} catch (IOException e) {
throw new NbtApiException("Error loading World Data!", e);
throw new NBTApiException("Error loading World Data!", e);
}
}
@@ -37,7 +37,7 @@ public class NBTData {
try {
return new PlayerData(playerFile);
} catch (IOException e) {
throw new NbtApiException("Error loading player data!", e);
throw new NBTApiException("Error loading player data!", e);
}
}
}
@@ -50,7 +50,7 @@ public class NBTData {
dataFolder.mkdirs();
return new NBTFile(new File(dataFolder, uuid.toString() + ".dat"));
} catch (IOException e) {
throw new NbtApiException("Error getting Player Plugin data!", e);
throw new NBTApiException("Error getting Player Plugin data!", e);
}
}
@@ -59,7 +59,7 @@ public class NBTData {
plugin.getDataFolder().mkdirs();
return new NBTFile(new File(plugin.getDataFolder(), "settings.dat"));
} catch (IOException e) {
throw new NbtApiException("Error getting Plugin data!", e);
throw new NBTApiException("Error getting Plugin data!", e);
}
}
@@ -3,9 +3,9 @@ package de.tr7zw.changeme.nbtapi.data;
import java.io.File;
import java.io.IOException;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTFile;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import dev.tr7zw.nbtapi.NBTFile;
import dev.tr7zw.nbtapi.NBTApiException;
import dev.tr7zw.nbtapi.Readable;
public class PlayerData {
@@ -19,7 +19,7 @@ public class PlayerData {
return file;
}
public NBTCompound getCompound() {
public Readable getCompound() {
return file;
}
@@ -27,7 +27,7 @@ public class PlayerData {
try {
file.save();
} catch (IOException e) {
throw new NbtApiException("Error when saving level data!", e);
throw new NBTApiException("Error when saving level data!", e);
}
}
@@ -6,9 +6,10 @@ import java.io.IOException;
import org.bukkit.util.Vector;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTFile;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import dev.tr7zw.nbtapi.NBTFile;
import dev.tr7zw.nbtapi.NBTApiException;
import dev.tr7zw.nbtapi.Readable;
import dev.tr7zw.nbtapi.Writeable;
public class WorldData {
@@ -23,7 +24,7 @@ public class WorldData {
return file;
}
public NBTCompound getCompound() {
public Readable getCompound() {
return file;
}
@@ -31,7 +32,7 @@ public class WorldData {
try {
file.save();
} catch (IOException e) {
throw new NbtApiException("Error when saving level data!", e);
throw new NBTApiException("Error when saving level data!", e);
}
}
@@ -44,12 +45,12 @@ public class WorldData {
}
public Vector getSpawnPosition(){
NBTCompound data = file.getCompound("Data");
Readable data = file.getCompound("Data");
return new Vector(data.getInteger("SpawnX"), data.getInteger("SpawnY"), data.getInteger("SpawnZ"));
}
public void setSpawnPosition(Vector vec){
NBTCompound data = file.getCompound("Data");
Writeable data = file.getCompound("Data");
data.setInteger("SpawnX", vec.getBlockX());
data.setInteger("SpawnY", vec.getBlockY());
data.setInteger("SpawnZ", vec.getBlockZ());
+86
View File
@@ -0,0 +1,86 @@
plugins {
id 'fabric-loom' version '0.9-SNAPSHOT'
id 'maven-publish'
}
sourceCompatibility = JavaVersion.VERSION_16
targetCompatibility = JavaVersion.VERSION_16
archivesBaseName = project.archives_base_name
version = project.nbtapi_version
group = project.maven_group
repositories {
// Add repositories to retrieve artifacts from in here.
// You should only use this when depending on other mods because
// Loom adds the essential maven repositories to download Minecraft and libraries from automatically.
// See https://docs.gradle.org/current/userguide/declaring_repositories.html
// for more information about repositories.
}
dependencies {
// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
mappings loom.officialMojangMappings()
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
// Fabric API. This is technically optional, but you probably want it anyway.
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
implementation project(':nbt-api')
}
processResources {
inputs.property "version", project.version
filesMatching("fabric.mod.json") {
expand "version": project.version
}
}
tasks.withType(JavaCompile).configureEach {
// ensure that the encoding is set to UTF-8, no matter what the system default is
// this fixes some edge cases with special characters not displaying correctly
// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html
// If Javadoc is generated, this must be specified in that task too.
it.options.encoding = "UTF-8"
// Minecraft 1.17 (21w19a) upwards uses Java 16.
it.options.release = 16
}
java {
// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task
// if it is present.
// If you remove this line, sources will not be generated.
withSourcesJar()
}
jar {
from("LICENSE") {
rename { "${it}_${project.archivesBaseName}"}
}
}
// configure the maven publication
publishing {
publications {
mavenJava(MavenPublication) {
// add all the jars that should be included when publishing to maven
artifact(remapJar) {
builtBy remapJar
}
artifact(sourcesJar) {
builtBy remapSourcesJar
}
}
}
// See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing.
repositories {
// Add repositories to publish to here.
// Notice: This block does NOT have the same function as the block in the top level.
// The repositories here will be used for publishing your artifact, not for
// retrieving dependencies.
}
}
+14
View File
@@ -0,0 +1,14 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx1G
# Fabric Properties
# check these on https://fabricmc.net/versions.html
minecraft_version=1.17.1
yarn_mappings=1.17.1+build.14
loader_version=0.11.6
# Mod Properties
archives_base_name = nbtapi
# Dependencies
fabric_version=0.37.0+1.17
+1
View File
@@ -0,0 +1 @@
rootProject.name = 'fabric1-17'
@@ -0,0 +1,14 @@
package net.fabricmc.example;
import net.fabricmc.api.ModInitializer;
public class ExampleMod implements ModInitializer {
@Override
public void onInitialize() {
// This code runs as soon as Minecraft is in a mod-load-ready state.
// However, some things (like resources) may still be uninitialized.
// Proceed with mild caution.
System.out.println("Hello Fabric world!");
}
}
@@ -0,0 +1,15 @@
package net.fabricmc.example.mixin;
import net.minecraft.client.gui.screens.TitleScreen;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(TitleScreen.class)
public class ExampleMixin {
@Inject(at = @At("HEAD"), method = "init()V")
private void init(CallbackInfo info) {
System.out.println("This line is printed by an example mod mixin!");
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 453 B

@@ -0,0 +1,38 @@
{
"schemaVersion": 1,
"id": "modid",
"version": "${version}",
"name": "Example Mod",
"description": "This is an example description! Tell everyone what your mod is about!",
"authors": [
"Me!"
],
"contact": {
"homepage": "https://fabricmc.net/",
"sources": "https://github.com/FabricMC/fabric-example-mod"
},
"license": "CC0-1.0",
"icon": "assets/modid/icon.png",
"environment": "*",
"entrypoints": {
"main": [
"net.fabricmc.example.ExampleMod"
]
},
"mixins": [
"modid.mixins.json"
],
"depends": {
"fabricloader": ">=0.11.3",
"fabric": "*",
"minecraft": "1.17.x",
"java": ">=16"
},
"suggests": {
"another-mod": "*"
}
}
@@ -0,0 +1,14 @@
{
"required": true,
"minVersion": "0.8",
"package": "net.fabricmc.example.mixin",
"compatibilityLevel": "JAVA_16",
"mixins": [
],
"client": [
"ExampleMixin"
],
"injectors": {
"defaultRequire": 1
}
}
+180
View File
@@ -0,0 +1,180 @@
buildscript {
repositories {
// These repositories are only for Gradle plugins, put any other repositories in the repository block further below
maven { url = 'https://maven.minecraftforge.net' }
mavenCentral()
}
dependencies {
classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true
}
}
apply plugin: 'net.minecraftforge.gradle'
// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup.
apply plugin: 'eclipse'
apply plugin: 'maven-publish'
version = project.nbtapi_version
group = project.maven_group // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'nbtapi'
// Mojang ships Java 16 to end users in 1.17+ instead of Java 8 in 1.16 or lower, so your mod should target Java 16.
java.toolchain.languageVersion = JavaLanguageVersion.of(16)
println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch'))
minecraft {
// The mappings can be changed at any time and must be in the following format.
// Channel: Version:
// snapshot YYYYMMDD Snapshot are built nightly.
// stable # Stables are built at the discretion of the MCP team.
// official MCVersion Official field/method names from Mojang mapping files
//
// You must be aware of the Mojang license when using the 'official' mappings.
// See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
//
// Use non-default mappings at your own risk. They may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: 'official', version: '1.17.1'
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') // Currently, this location cannot be changed from the default.
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
mods {
examplemod {
source sourceSets.main
}
}
}
server {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
mods {
examplemod {
source sourceSets.main
}
}
}
data {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
args '--mod', 'examplemod', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
mods {
examplemod {
source sourceSets.main
}
}
}
}
}
// Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' }
repositories {
// Put repositories for dependencies here
// ForgeGradle automatically adds the Forge maven and Maven Central for you
// If you have mod jar dependencies in ./libs, you can declare them as a repository like so:
// flatDir {
// dir 'libs'
// }
}
dependencies {
// Specify the version of Minecraft to use. If this is any group other than 'net.minecraft', it is assumed
// that the dep is a ForgeGradle 'patcher' dependency, and its patches will be applied.
// The userdev artifact is a special name and will get all sorts of transformations applied to it.
minecraft 'net.minecraftforge:forge:1.17.1-37.0.13'
// Real mod deobf dependency examples - these get remapped to your current mappings
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}:api") // Adds JEI API as a compile dependency
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}") // Adds the full JEI mod as a runtime dependency
// implementation fg.deobf("com.tterrag.registrate:Registrate:MC${mc_version}-${registrate_version}") // Adds registrate as a dependency
implementation project(':nbt-api')
// Examples using mod jars from ./libs
// implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}")
// For more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// Example for how to get properties into the manifest for reading at runtime.
jar {
manifest {
attributes([
"Specification-Title" : "nbtapi",
"Specification-Vendor" : "tr7zw",
"Specification-Version" : "1", // We are version 1 of ourselves
"Implementation-Title" : project.name,
"Implementation-Version" : project.jar.archiveVersion,
"Implementation-Vendor" : "tr7zw",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
}
// Example configuration to allow publishing using the maven-publish plugin
// This is the preferred method to reobfuscate your jar file
jar.finalizedBy('reobfJar')
// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing
// publish.dependsOn('reobfJar')
publishing {
publications {
mavenJava(MavenPublication) {
artifact jar
}
}
repositories {
maven {
url "file://${project.projectDir}/mcmodsrepo"
}
}
}
+4
View File
@@ -0,0 +1,4 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false
+1
View File
@@ -0,0 +1 @@
rootProject.name = 'forge1-17'
@@ -0,0 +1,76 @@
package com.example.examplemod;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegistryEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.InterModComms;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.event.lifecycle.InterModProcessEvent;
import net.minecraftforge.fmlserverevents.FMLServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.stream.Collectors;
// The value here should match an entry in the META-INF/mods.toml file
@Mod("examplemod")
public class ExampleMod
{
// Directly reference a log4j logger.
private static final Logger LOGGER = LogManager.getLogger();
public ExampleMod() {
// Register the setup method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::setup);
// Register the enqueueIMC method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::enqueueIMC);
// Register the processIMC method for modloading
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::processIMC);
// Register ourselves for server and other game events we are interested in
MinecraftForge.EVENT_BUS.register(this);
}
private void setup(final FMLCommonSetupEvent event)
{
// some preinit code
LOGGER.info("HELLO FROM PREINIT");
LOGGER.info("DIRT BLOCK >> {}", Blocks.DIRT.getRegistryName());
}
private void enqueueIMC(final InterModEnqueueEvent event)
{
// some example code to dispatch IMC to another mod
InterModComms.sendTo("examplemod", "helloworld", () -> { LOGGER.info("Hello world from the MDK"); return "Hello world";});
}
private void processIMC(final InterModProcessEvent event)
{
// some example code to receive and process InterModComms from other mods
LOGGER.info("Got IMC {}", event.getIMCStream().
map(m->m.messageSupplier().get()).
collect(Collectors.toList()));
}
// You can use SubscribeEvent and let the Event Bus discover methods to call
@SubscribeEvent
public void onServerStarting(FMLServerStartingEvent event) {
// do something when the server starts
LOGGER.info("HELLO from server starting");
}
// You can use EventBusSubscriber to automatically subscribe events on the contained class (this is subscribing to the MOD
// Event bus for receiving Registry Events)
@Mod.EventBusSubscriber(bus=Mod.EventBusSubscriber.Bus.MOD)
public static class RegistryEvents {
@SubscribeEvent
public static void onBlocksRegistry(final RegistryEvent.Register<Block> blockRegistryEvent) {
// register a new block here
LOGGER.info("HELLO from Register Block");
}
}
}
@@ -0,0 +1,62 @@
# This is an example mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion="[37,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license="All rights reserved"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="examplemod" #mandatory
# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it
# ${file.jarVersion} will substitute the value of the Implementation-Version as read from the mod's JAR file metadata
# see the associated build.gradle script for how to populate this completely automatically during a build
version="${file.jarVersion}" #mandatory
# A display name for the mod
displayName="Example Mod" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://mcforge.readthedocs.io/en/latest/gettingstarted/autoupdate/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
logoFile="examplemod.png" #optional
# A text field displayed in the mod UI
credits="Thanks for this example mod goes to Java" #optional
# A text field displayed in the mod UI
authors="Love, Cheese and small house plants" #optional
# The description text for the mod (multi line!) (#mandatory)
description='''
This is a long form description of the mod. You can write whatever you want here
Have some lorem ipsum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed mollis lacinia magna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed sagittis luctus odio eu tempus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque volutpat ligula eget lacus auctor sagittis. In hac habitasse platea dictumst. Nunc gravida elit vitae sem vehicula efficitur. Donec mattis ipsum et arcu lobortis, eleifend sagittis sem rutrum. Cras pharetra quam eget posuere fermentum. Sed id tincidunt justo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
'''
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.examplemod]] #optional
# the modid of the dependency
modId="forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified
mandatory=true #mandatory
# The version range of the dependency
versionRange="[37,)" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory
ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT or SERVER
side="BOTH"
# Here's another dependency
[[dependencies.examplemod]]
modId="minecraft"
mandatory=true
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="[1.17.1,1.18)"
ordering="NONE"
side="BOTH"
@@ -0,0 +1,7 @@
{
"pack": {
"description": "examplemod resources",
"pack_format": 6,
"_comment": "A pack_format of 6 requires json lang files and some texture changes from 1.16.2. Note: we require v6 pack meta for all mods."
}
}
+8
View File
@@ -0,0 +1,8 @@
nbtapi_version=3.0.0
maven_group=dev.tr7zw.nbtapi
spigot_api=1.17.1-R0.1-SNAPSHOT
authlib_version=1.5.25
# Gradle
org.gradle.parallel=true
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.1.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+185
View File
@@ -0,0 +1,185 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or 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.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# 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"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# 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
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# 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"
which java >/dev/null 2>&1 || 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
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"
Vendored
+89
View File
@@ -0,0 +1,89 @@
@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
@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=.
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%" == "0" goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="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!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
-21
View File
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 - 2021, tr7zw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -1,839 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.bukkit.inventory.ItemStack;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* Base class representing NMS Compounds. For a standalone implementation check
* {@link NBTContainer}
*
* @author tr7zw
*
*/
public class NBTCompound {
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final Lock readLock = readWriteLock.readLock();
private final Lock writeLock = readWriteLock.writeLock();
private String compundName;
private NBTCompound parent;
protected NBTCompound(NBTCompound owner, String name) {
this.compundName = name;
this.parent = owner;
}
protected Lock getReadLock() {
return readLock;
}
protected Lock getWriteLock() {
return writeLock;
}
protected void saveCompound() {
if (parent != null)
parent.saveCompound();
}
/**
* @return The Compound name
*/
public String getName() {
return compundName;
}
/**
* @return The NMS Compound behind this Object
*/
public Object getCompound() {
return parent.getCompound();
}
protected void setCompound(Object compound) {
parent.setCompound(compound);
}
/**
* @return The parent Compound
*/
public NBTCompound getParent() {
return parent;
}
/**
* Merges all data from comp into this compound. This is done in one action, so
* it also works with Tiles/Entities
*
* @param comp
*/
public void mergeCompound(NBTCompound comp) {
try {
writeLock.lock();
NBTReflectionUtil.mergeOtherNBTCompound(this, comp);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Setter
*
* @param key
* @param value
*/
public void setString(String key, String value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_STRING, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public String getString(String key) {
try {
readLock.lock();
return (String) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_STRING, key);
} finally {
readLock.unlock();
}
}
protected String getContent(String key) {
return NBTReflectionUtil.getContent(this, key);
}
/**
* Setter
*
* @param key
* @param value
*/
public void setInteger(String key, Integer value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_INT, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Integer getInteger(String key) {
try {
readLock.lock();
return (Integer) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_INT, key);
} finally {
readLock.unlock();
}
}
/**
* Setter
*
* @param key
* @param value
*/
public void setDouble(String key, Double value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_DOUBLE, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Double getDouble(String key) {
try {
readLock.lock();
return (Double) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_DOUBLE, key);
} finally {
readLock.unlock();
}
}
/**
* Setter
*
* @param key
* @param value
*/
public void setByte(String key, Byte value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_BYTE, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Byte getByte(String key) {
try {
readLock.lock();
return (Byte) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_BYTE, key);
} finally {
readLock.unlock();
}
}
/**
* Setter
*
* @param key
* @param value
*/
public void setShort(String key, Short value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_SHORT, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Short getShort(String key) {
try {
readLock.lock();
return (Short) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_SHORT, key);
} finally {
readLock.unlock();
}
}
/**
* Setter
*
* @param key
* @param value
*/
public void setLong(String key, Long value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_LONG, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Long getLong(String key) {
try {
readLock.lock();
return (Long) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_LONG, key);
} finally {
readLock.unlock();
}
}
/**
* Setter
*
* @param key
* @param value
*/
public void setFloat(String key, Float value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_FLOAT, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Float getFloat(String key) {
try {
readLock.lock();
return (Float) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_FLOAT, key);
} finally {
readLock.unlock();
}
}
/**
* Setter
*
* @param key
* @param value
*/
public void setByteArray(String key, byte[] value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_BYTEARRAY, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public byte[] getByteArray(String key) {
try {
readLock.lock();
return (byte[]) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_BYTEARRAY, key);
} finally {
readLock.unlock();
}
}
/**
* Setter
*
* @param key
* @param value
*/
public void setIntArray(String key, int[] value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_INTARRAY, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public int[] getIntArray(String key) {
try {
readLock.lock();
return (int[]) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_INTARRAY, key);
} finally {
readLock.unlock();
}
}
/**
* Setter
*
* @param key
* @param value
*/
public void setBoolean(String key, Boolean value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_BOOLEAN, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
protected void set(String key, Object val) {
NBTReflectionUtil.set(this, key, val);
saveCompound();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Boolean getBoolean(String key) {
try {
readLock.lock();
return (Boolean) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_BOOLEAN, key);
} finally {
readLock.unlock();
}
}
/**
* Uses Gson to store an {@link Serializable} Object
*
* @param key
* @param value
*/
public void setObject(String key, Object value) {
try {
writeLock.lock();
NBTReflectionUtil.setObject(this, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Uses Gson to retrieve a stored Object
*
* @param key
* @param type Class of the Object
* @return The created Object or null if empty
*/
public <T> T getObject(String key, Class<T> type) {
try {
readLock.lock();
return NBTReflectionUtil.getObject(this, key, type);
} finally {
readLock.unlock();
}
}
/**
* Save an ItemStack as a compound under a given key
*
* @param key
* @param item
*/
public void setItemStack(String key, ItemStack item) {
try {
writeLock.lock();
removeKey(key);
addCompound(key).mergeCompound(NBTItem.convertItemtoNBT(item));
} finally {
writeLock.unlock();
}
}
/**
* Get an ItemStack that was saved at the given key
*
* @param key
* @return
*/
public ItemStack getItemStack(String key) {
try {
readLock.lock();
NBTCompound comp = getCompound(key);
return NBTItem.convertNBTtoItem(comp);
} finally {
readLock.unlock();
}
}
/**
* Setter
*
* @param key
* @param value
*/
public void setUUID(String key, UUID value) {
try {
writeLock.lock();
NBTReflectionUtil.setData(this, ReflectionMethod.COMPOUND_SET_UUID, key, value);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public UUID getUUID(String key) {
try {
readLock.lock();
return (UUID) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_UUID, key);
} finally {
readLock.unlock();
}
}
/**
* @param key
* @return True if the key is set
*/
public Boolean hasKey(String key) {
try {
readLock.lock();
Boolean b = (Boolean) NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_HAS_KEY, key);
if (b == null)
return false;
return b;
} finally {
readLock.unlock();
}
}
/**
* @param key Deletes the given Key
*/
public void removeKey(String key) {
try {
writeLock.lock();
NBTReflectionUtil.remove(this, key);
saveCompound();
} finally {
writeLock.unlock();
}
}
/**
* @return Set of all stored Keys
*/
public Set<String> getKeys() {
try {
readLock.lock();
return NBTReflectionUtil.getKeys(this);
} finally {
readLock.unlock();
}
}
/**
* Creates a subCompound, or returns it if already provided
*
* @param name Key to use
* @return The subCompound Object
*/
public NBTCompound addCompound(String name) {
try {
writeLock.lock();
if (getType(name) == NBTType.NBTTagCompound)
return getCompound(name);
NBTReflectionUtil.addNBTTagCompound(this, name);
NBTCompound comp = getCompound(name);
if (comp == null)
throw new NbtApiException("Error while adding Compound, got null!");
saveCompound();
return comp;
} finally {
writeLock.unlock();
}
}
/**
* @param name
* @return The Compound instance or null
*/
public NBTCompound getCompound(String name) {
try {
readLock.lock();
if (getType(name) != NBTType.NBTTagCompound)
return null;
NBTCompound next = new NBTCompound(this, name);
if (NBTReflectionUtil.valideCompound(next))
return next;
return null;
} finally {
readLock.unlock();
}
}
/**
* The same as addCompound, just with a name that better reflects what it does
*
* @param name
* @return
*/
public NBTCompound getOrCreateCompound(String name) {
return addCompound(name);
}
/**
* @param name
* @return The retrieved String List
*/
public NBTList<String> getStringList(String name) {
try {
writeLock.lock();
NBTList<String> list = NBTReflectionUtil.getList(this, name, NBTType.NBTTagString, String.class);
saveCompound();
return list;
} finally {
writeLock.unlock();
}
}
/**
* @param name
* @return The retrieved Integer List
*/
public NBTList<Integer> getIntegerList(String name) {
try {
writeLock.lock();
NBTList<Integer> list = NBTReflectionUtil.getList(this, name, NBTType.NBTTagInt, Integer.class);
saveCompound();
return list;
} finally {
writeLock.unlock();
}
}
/**
* @param name
* @return The retrieved Float List
*/
public NBTList<Float> getFloatList(String name) {
try {
writeLock.lock();
NBTList<Float> list = NBTReflectionUtil.getList(this, name, NBTType.NBTTagFloat, Float.class);
saveCompound();
return list;
} finally {
writeLock.unlock();
}
}
/**
* @param name
* @return The retrieved Double List
*/
public NBTList<Double> getDoubleList(String name) {
try {
writeLock.lock();
NBTList<Double> list = NBTReflectionUtil.getList(this, name, NBTType.NBTTagDouble, Double.class);
saveCompound();
return list;
} finally {
writeLock.unlock();
}
}
/**
* @param name
* @return The retrieved Long List
*/
public NBTList<Long> getLongList(String name) {
try {
writeLock.lock();
NBTList<Long> list = NBTReflectionUtil.getList(this, name, NBTType.NBTTagLong, Long.class);
saveCompound();
return list;
} finally {
writeLock.unlock();
}
}
/**
* Returns the type of the list, null if not a list
*
* @param name
* @return
*/
public NBTType getListType(String name) {
try {
readLock.lock();
if (getType(name) != NBTType.NBTTagList)
return null;
return NBTReflectionUtil.getListType(this, name);
} finally {
readLock.unlock();
}
}
/**
* @param name
* @return The retrieved Compound List
*/
public NBTCompoundList getCompoundList(String name) {
try {
writeLock.lock();
NBTCompoundList list = (NBTCompoundList) NBTReflectionUtil.getList(this, name, NBTType.NBTTagCompound,
NBTListCompound.class);
saveCompound();
return list;
} finally {
writeLock.unlock();
}
}
/**
* @param name
* @return The type of the given stored key or null
*/
public NBTType getType(String name) {
try {
readLock.lock();
if (MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4) {
Object nbtbase = NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET, name);
if(nbtbase == null)
return null;
return NBTType.valueOf((byte)ReflectionMethod.COMPOUND_OWN_TYPE.run(nbtbase));
}
Object o = NBTReflectionUtil.getData(this, ReflectionMethod.COMPOUND_GET_TYPE, name);
if (o == null)
return null;
return NBTType.valueOf((byte) o);
} finally {
readLock.unlock();
}
}
public void writeCompound(OutputStream stream) {
try {
writeLock.lock();
NBTReflectionUtil.writeApiNBT(this, stream);
} finally {
writeLock.unlock();
}
}
@Override
public String toString() {
/*
* StringBuilder result = new StringBuilder(); for (String key : getKeys()) {
* result.append(toString(key)); } return result.toString();
*/
return asNBTString();
}
/**
* @deprecated Just use toString()
* @param key
* @return A string representation of the given key
*/
@Deprecated
public String toString(String key) {
/*
* StringBuilder result = new StringBuilder(); NBTCompound compound = this;
* while (compound.getParent() != null) { result.append(" "); compound =
* compound.getParent(); } if (this.getType(key) == NBTType.NBTTagCompound) {
* return this.getCompound(key).toString(); } else { return result + "-" + key +
* ": " + getContent(key) + System.lineSeparator(); }
*/
return asNBTString();
}
/**
* @deprecated Just use toString()
* @return A {@link String} representation of the NBT in Mojang JSON. This is different from normal JSON!
*/
@Deprecated
public String asNBTString() {
try {
readLock.lock();
Object comp = NBTReflectionUtil.gettoCompount(getCompound(), this);
if (comp == null)
return "{}";
return comp.toString();
} finally {
readLock.unlock();
}
}
@Override
public int hashCode() {
return toString().hashCode();
}
/**
* Does a deep compare to check if everything is the same
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if(obj instanceof NBTCompound) {
NBTCompound other = (NBTCompound) obj;
if(getKeys().equals(other.getKeys())) {
for(String key : getKeys()) {
if(!isEqual(this, other, key)) {
return false;
}
}
return true;
}
}
return false;
}
protected static boolean isEqual(NBTCompound compA, NBTCompound compB, String key) {
if(compA.getType(key) != compB.getType(key))return false;
switch(compA.getType(key)) {
case NBTTagByte:
return compA.getByte(key).equals(compB.getByte(key));
case NBTTagByteArray:
return Arrays.equals(compA.getByteArray(key), compB.getByteArray(key));
case NBTTagCompound:
return compA.getCompound(key).equals(compB.getCompound(key));
case NBTTagDouble:
return compA.getDouble(key).equals(compB.getDouble(key));
case NBTTagEnd:
return true; //??
case NBTTagFloat:
return compA.getFloat(key).equals(compB.getFloat(key));
case NBTTagInt:
return compA.getInteger(key).equals(compB.getInteger(key));
case NBTTagIntArray:
return Arrays.equals(compA.getIntArray(key), compB.getIntArray(key));
case NBTTagList:
return NBTReflectionUtil.getEntry(compA, key).toString().equals(NBTReflectionUtil.getEntry(compB, key).toString()); // Just string compare the 2 lists
case NBTTagLong:
return compA.getLong(key).equals(compB.getLong(key));
case NBTTagShort:
return compA.getShort(key).equals(compB.getShort(key));
case NBTTagString:
return compA.getString(key).equals(compB.getString(key));
}
return false;
}
}
@@ -1,108 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import org.apache.commons.lang.NotImplementedException;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ClassWrapper;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* {@link NBTListCompound} implementation for NBTLists
*
* @author tr7zw
*
*/
public class NBTCompoundList extends NBTList<NBTListCompound> {
protected NBTCompoundList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
/**
* Adds a new Compound to the end of the List and returns it.
*
* @return The added {@link NBTListCompound}
*/
public NBTListCompound addCompound() {
return (NBTListCompound) addCompound(null);
}
/**
* Adds a copy of the Compound to the end of the List and returns it.
* When null is given, a new Compound will be created
*
* @param comp
* @return
*/
public NBTCompound addCompound(NBTCompound comp) {
try {
Object compound = ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance();
if (MinecraftVersion.getVersion().getVersionId() >= MinecraftVersion.MC1_14_R1.getVersionId()) {
ReflectionMethod.LIST_ADD.run(listObject, size(), compound);
} else {
ReflectionMethod.LEGACY_LIST_ADD.run(listObject, compound);
}
getParent().saveCompound();
NBTListCompound listcomp = new NBTListCompound(this, compound);
if(comp != null){
listcomp.mergeCompound(comp);
}
return listcomp;
} catch (Exception ex) {
throw new NbtApiException(ex);
}
}
/**
* Adds a new Compound to the end of the List.
*
*
* @deprecated Please use addCompound!
* @param empty
* @return True, if compound was added
*/
@Override
@Deprecated
public boolean add(NBTListCompound empty) {
return addCompound(empty) != null;
}
@Override
public void add(int index, NBTListCompound element) {
if (element != null) {
throw new NotImplementedException("You need to pass null! ListCompounds from other lists won't work.");
}
try {
Object compound = ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance();
if (MinecraftVersion.getVersion().getVersionId() >= MinecraftVersion.MC1_14_R1.getVersionId()) {
ReflectionMethod.LIST_ADD.run(listObject, index, compound);
} else {
ReflectionMethod.LEGACY_LIST_ADD.run(listObject, compound);
}
super.getParent().saveCompound();
} catch (Exception ex) {
throw new NbtApiException(ex);
}
}
@Override
public NBTListCompound get(int index) {
try {
Object compound = ReflectionMethod.LIST_GET_COMPOUND.run(listObject, index);
return new NBTListCompound(this, compound);
} catch (Exception ex) {
throw new NbtApiException(ex);
}
}
@Override
public NBTListCompound set(int index, NBTListCompound element) {
throw new NotImplementedException("This method doesn't work in the ListCompound context.");
}
@Override
protected Object asTag(NBTListCompound object) {
return null;
}
}
@@ -1,82 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.io.InputStream;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ClassWrapper;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ObjectCreator;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* A Standalone {@link NBTCompound} implementation. All data is just kept inside
* this Object.
*
* @author tr7zw
*
*/
public class NBTContainer extends NBTCompound {
private Object nbt;
/**
* Creates an empty, standalone NBTCompound
*/
public NBTContainer() {
super(null, null);
nbt = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
/**
* Takes in any NMS Compound to wrap it
*
* @param nbt
*/
public NBTContainer(Object nbt) {
super(null, null);
if (nbt == null) {
throw new NullPointerException("The NBT-Object can't be null!");
}
if (!ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().isAssignableFrom(nbt.getClass())) {
throw new NbtApiException("The object '" + nbt.getClass() + "' is not a valid NBT-Object!");
}
this.nbt = nbt;
}
/**
* Reads in a NBT InputStream
*
* @param inputsteam
*/
public NBTContainer(InputStream inputsteam) {
super(null, null);
this.nbt = NBTReflectionUtil.readNBT(inputsteam);
}
/**
* Parses in a NBT String to a standalone {@link NBTCompound}. Can throw a
* {@link NbtApiException} in case something goes wrong.
*
* @param nbtString
*/
public NBTContainer(String nbtString) {
super(null, null);
if (nbtString == null) {
throw new NullPointerException("The String can't be null!");
}
try {
nbt = ReflectionMethod.PARSE_NBT.run(null, nbtString);
} catch (Exception ex) {
throw new NbtApiException("Unable to parse Malformed Json!", ex);
}
}
@Override
public Object getCompound() {
return nbt;
}
@Override
public void setCompound(Object tag) {
nbt = tag;
}
}
@@ -1,45 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ClassWrapper;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* Double implementation for NBTLists
*
* @author tr7zw
*
*/
public class NBTDoubleList extends NBTList<Double> {
protected NBTDoubleList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
@Override
protected Object asTag(Double object) {
try {
Constructor<?> con = ClassWrapper.NMS_NBTTAGDOUBLE.getClazz().getDeclaredConstructor(double.class);
con.setAccessible(true);
return con.newInstance(object);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new NbtApiException("Error while wrapping the Object " + object + " to it's NMS object!", e);
}
}
@Override
public Double get(int index) {
try {
Object obj = ReflectionMethod.LIST_GET.run(listObject, index);
return Double.valueOf(obj.toString());
} catch (NumberFormatException nf) {
return 0d;
} catch (Exception ex) {
throw new NbtApiException(ex);
}
}
}
@@ -1,80 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ObjectCreator;
/**
* {@link NBTCompound} implementation backed by a {@link File}
*
* @author tr7zw
*
*/
public class NBTFile extends NBTCompound {
private final File file;
private Object nbt;
/**
* Creates a NBTFile that uses @param file to store it's data. If this file
* exists, the data will be loaded.
*
* @param file
* @throws IOException
*/
public NBTFile(File file) throws IOException {
super(null, null);
if (file == null) {
throw new NullPointerException("File can't be null!");
}
this.file = file;
if (file.exists()) {
FileInputStream inputsteam = new FileInputStream(file);
nbt = NBTReflectionUtil.readNBT(inputsteam);
} else {
nbt = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
save();
}
}
/**
* Saves the data to the file
*
* @throws IOException
*/
public void save() throws IOException {
try {
getWriteLock().lock();
if (!file.exists()) {
file.getParentFile().mkdirs();
if (!file.createNewFile())
throw new IOException("Unable to create file at " + file.getAbsolutePath());
}
FileOutputStream outStream = new FileOutputStream(file);
NBTReflectionUtil.writeNBT(nbt, outStream);
} finally {
getWriteLock().unlock();
}
}
/**
* @return The File used to store the data
*/
public File getFile() {
return file;
}
@Override
public Object getCompound() {
return nbt;
}
@Override
protected void setCompound(Object compound) {
nbt = compound;
}
}
@@ -1,45 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ClassWrapper;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* Float implementation for NBTLists
*
* @author tr7zw
*
*/
public class NBTFloatList extends NBTList<Float> {
protected NBTFloatList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
@Override
protected Object asTag(Float object) {
try {
Constructor<?> con = ClassWrapper.NMS_NBTTAGFLOAT.getClazz().getDeclaredConstructor(float.class);
con.setAccessible(true);
return con.newInstance(object);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new NbtApiException("Error while wrapping the Object " + object + " to it's NMS object!", e);
}
}
@Override
public Float get(int index) {
try {
Object obj = ReflectionMethod.LIST_GET.run(listObject, index);
return Float.valueOf(obj.toString());
} catch (NumberFormatException nf) {
return 0f;
} catch (Exception ex) {
throw new NbtApiException(ex);
}
}
}
@@ -1,45 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ClassWrapper;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* Integer implementation for NBTLists
*
* @author tr7zw
*
*/
public class NBTIntegerList extends NBTList<Integer> {
protected NBTIntegerList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
@Override
protected Object asTag(Integer object) {
try {
Constructor<?> con = ClassWrapper.NMS_NBTTAGINT.getClazz().getDeclaredConstructor(int.class);
con.setAccessible(true);
return con.newInstance(object);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new NbtApiException("Error while wrapping the Object " + object + " to it's NMS object!", e);
}
}
@Override
public Integer get(int index) {
try {
Object obj = ReflectionMethod.LIST_GET.run(listObject, index);
return Integer.valueOf(obj.toString());
} catch (NumberFormatException nf) {
return 0;
} catch (Exception ex) {
throw new NbtApiException(ex);
}
}
}
@@ -1,429 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* Abstract List implementation for ListCompounds
*
* @author tr7zw
*
* @param <T>
*/
public abstract class NBTList<T> implements List<T> {
private String listName;
private NBTCompound parent;
private NBTType type;
protected Object listObject;
protected NBTList(NBTCompound owner, String name, NBTType type, Object list) {
parent = owner;
listName = name;
this.type = type;
this.listObject = list;
}
/**
* @return Name of this list-compound
*/
public String getName() {
return listName;
}
/**
* @return The Compound's parent Object
*/
public NBTCompound getParent() {
return parent;
}
protected void save() {
parent.set(listName, listObject);
}
protected abstract Object asTag(T object);
@Override
public boolean add(T element) {
try {
parent.getWriteLock().lock();
if (MinecraftVersion.getVersion().getVersionId() >= MinecraftVersion.MC1_14_R1.getVersionId()) {
ReflectionMethod.LIST_ADD.run(listObject, size(), asTag(element));
} else {
ReflectionMethod.LEGACY_LIST_ADD.run(listObject, asTag(element));
}
save();
return true;
} catch (Exception ex) {
throw new NbtApiException(ex);
} finally {
parent.getWriteLock().unlock();
}
}
@Override
public void add(int index, T element) {
try {
parent.getWriteLock().lock();
if (MinecraftVersion.getVersion().getVersionId() >= MinecraftVersion.MC1_14_R1.getVersionId()) {
ReflectionMethod.LIST_ADD.run(listObject, index, asTag(element));
} else {
ReflectionMethod.LEGACY_LIST_ADD.run(listObject, asTag(element));
}
save();
} catch (Exception ex) {
throw new NbtApiException(ex);
} finally {
parent.getWriteLock().unlock();
}
}
@Override
public T set(int index, T element) {
try {
parent.getWriteLock().lock();
T prev = get(index);
ReflectionMethod.LIST_SET.run(listObject, index, asTag(element));
save();
return prev;
} catch (Exception ex) {
throw new NbtApiException(ex);
} finally {
parent.getWriteLock().unlock();
}
}
public T remove(int i) {
try {
parent.getWriteLock().lock();
T old = get(i);
ReflectionMethod.LIST_REMOVE_KEY.run(listObject, i);
save();
return old;
} catch (Exception ex) {
throw new NbtApiException(ex);
} finally {
parent.getWriteLock().unlock();
}
}
public int size() {
try {
parent.getReadLock().lock();
return (int) ReflectionMethod.LIST_SIZE.run(listObject);
} catch (Exception ex) {
throw new NbtApiException(ex);
} finally {
parent.getReadLock().unlock();
}
}
/**
* @return The type that this list contains
*/
public NBTType getType() {
return type;
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public void clear() {
while (!isEmpty()) {
remove(0);
}
}
@Override
public boolean contains(Object o) {
try {
parent.getReadLock().lock();
for (int i = 0; i < size(); i++) {
if (o.equals(get(i)))
return true;
}
return false;
} finally {
parent.getReadLock().unlock();
}
}
@Override
public int indexOf(Object o) {
try {
parent.getReadLock().lock();
for (int i = 0; i < size(); i++) {
if (o.equals(get(i)))
return i;
}
return -1;
} finally {
parent.getReadLock().unlock();
}
}
@Override
public boolean addAll(Collection<? extends T> c) {
try {
parent.getWriteLock().lock();
int size = size();
for (T ele : c) {
add(ele);
}
return size != size();
} finally {
parent.getWriteLock().unlock();
}
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
try {
parent.getWriteLock().lock();
int size = size();
for (T ele : c) {
add(index++, ele);
}
return size != size();
} finally {
parent.getWriteLock().unlock();
}
}
@Override
public boolean containsAll(Collection<?> c) {
try {
parent.getReadLock().lock();
for (Object ele : c) {
if (!contains(ele))
return false;
}
return true;
} finally {
parent.getReadLock().unlock();
}
}
@Override
public int lastIndexOf(Object o) {
try {
parent.getReadLock().lock();
int index = -1;
for (int i = 0; i < size(); i++) {
if (o.equals(get(i)))
index = i;
}
return index;
} finally {
parent.getReadLock().unlock();
}
}
@Override
public boolean removeAll(Collection<?> c) {
try {
parent.getWriteLock().lock();
int size = size();
for (Object obj : c) {
remove(obj);
}
return size != size();
} finally {
parent.getWriteLock().unlock();
}
}
@Override
public boolean retainAll(Collection<?> c) {
try {
parent.getWriteLock().lock();
int size = size();
for (Object obj : c) {
for (int i = 0; i < size(); i++) {
if (!obj.equals(get(i))) {
remove(i--);
}
}
}
return size != size();
} finally {
parent.getWriteLock().unlock();
}
}
@Override
public boolean remove(Object o) {
try {
parent.getWriteLock().lock();
int size = size();
int id = -1;
while ((id = indexOf(o)) != -1) {
remove(id);
}
return size != size();
} finally {
parent.getWriteLock().unlock();
}
}
@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
private int index = -1;
@Override
public boolean hasNext() {
return size() > index + 1;
}
@Override
public T next() {
if (!hasNext())
throw new NoSuchElementException();
return get(++index);
}
@Override
public void remove() {
NBTList.this.remove(index);
index--;
}
};
}
@Override
public ListIterator<T> listIterator() {
return listIterator(0);
}
@Override
public ListIterator<T> listIterator(int startIndex) {
final NBTList<T> list = this;
return new ListIterator<T>() {
int index = startIndex - 1;
@Override
public void add(T e) {
list.add(index, e);
}
@Override
public boolean hasNext() {
return size() > index + 1;
}
@Override
public boolean hasPrevious() {
return index >= 0 && index <= size();
}
@Override
public T next() {
if (!hasNext())
throw new NoSuchElementException();
return get(++index);
}
@Override
public int nextIndex() {
return index + 1;
}
@Override
public T previous() {
if (!hasPrevious())
throw new NoSuchElementException("Id: " + (index - 1));
return get(index--);
}
@Override
public int previousIndex() {
return index - 1;
}
@Override
public void remove() {
list.remove(index);
index--;
}
@Override
public void set(T e) {
list.set(index, e);
}
};
}
@Override
public Object[] toArray() {
try {
parent.getReadLock().lock();
Object[] ar = new Object[size()];
for (int i = 0; i < size(); i++)
ar[i] = get(i);
return ar;
} finally {
parent.getReadLock().unlock();
}
}
@SuppressWarnings("unchecked")
@Override
public <E> E[] toArray(E[] a) {
try {
parent.getReadLock().lock();
E[] ar = Arrays.copyOf(a, size());
Arrays.fill(ar, null);
Class<?> arrayclass = a.getClass().getComponentType();
for (int i = 0; i < size(); i++) {
T obj = get(i);
if (arrayclass.isInstance(obj)) {
ar[i] = (E) get(i);
} else {
throw new ArrayStoreException("The array does not match the objects stored in the List.");
}
}
return ar;
} finally {
parent.getReadLock().unlock();
}
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
try {
parent.getReadLock().lock();
ArrayList<T> list = new ArrayList<>();
for (int i = fromIndex; i < toIndex; i++)
list.add(get(i));
return list;
} finally {
parent.getReadLock().unlock();
}
}
@Override
public String toString() {
try {
parent.getReadLock().lock();
return listObject.toString();
} finally {
parent.getReadLock().unlock();
}
}
}
@@ -1,45 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ClassWrapper;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* Long implementation for NBTLists
*
* @author tr7zw
*
*/
public class NBTLongList extends NBTList<Long> {
protected NBTLongList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
@Override
protected Object asTag(Long object) {
try {
Constructor<?> con = ClassWrapper.NMS_NBTTAGLONG.getClazz().getDeclaredConstructor(long.class);
con.setAccessible(true);
return con.newInstance(object);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new NbtApiException("Error while wrapping the Object " + object + " to it's NMS object!", e);
}
}
@Override
public Long get(int index) {
try {
Object obj = ReflectionMethod.LIST_GET.run(listObject, index);
return Long.valueOf(obj.toString().replace("L", ""));
} catch (NumberFormatException nf) {
return 0l;
} catch (Exception ex) {
throw new NbtApiException(ex);
}
}
}
@@ -1,31 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.util.Map;
import org.bukkit.persistence.PersistentDataContainer;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
public class NBTPersistentDataContainer extends NBTCompound {
private final PersistentDataContainer container;
protected NBTPersistentDataContainer(PersistentDataContainer container) {
super(null, null);
this.container = container;
}
@Override
public Object getCompound() {
return ReflectionMethod.CRAFT_PERSISTENT_DATA_CONTAINER_TO_TAG.run(container);
}
@Override
protected void setCompound(Object compound) {
@SuppressWarnings("unchecked")
Map<Object, Object> map = (Map<Object, Object>) ReflectionMethod.CRAFT_PERSISTENT_DATA_CONTAINER_GET_MAP.run(container);
map.clear();
ReflectionMethod.CRAFT_PERSISTENT_DATA_CONTAINER_PUT_ALL.run(container, compound);
}
}
@@ -1,618 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
import java.util.Set;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Entity;
import org.bukkit.inventory.meta.ItemMeta;
import de.tr7zw.changeme.nbtapi.utils.GsonWrapper;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ClassWrapper;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ObjectCreator;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* Utility class for translating NBTApi calls to reflections into NMS code All
* methods are allowed to throw {@link NbtApiException}
*
* @author tr7zw
*
*/
public class NBTReflectionUtil {
private static Field field_unhandledTags = null;
static {
try {
field_unhandledTags = ClassWrapper.CRAFT_METAITEM.getClazz().getDeclaredField("unhandledTags");
field_unhandledTags.setAccessible(true);
} catch (NoSuchFieldException e) {
}
}
/**
* Hidden constructor
*/
private NBTReflectionUtil() {
}
/**
* Gets the NMS Entity for a given Bukkit Entity
*
* @param entity Bukkit Entity
* @return NMS Entity
*/
public static Object getNMSEntity(Entity entity) {
try {
return ReflectionMethod.CRAFT_ENTITY_GET_HANDLE.run(ClassWrapper.CRAFT_ENTITY.getClazz().cast(entity));
} catch (Exception e) {
throw new NbtApiException("Exception while getting the NMS Entity from a Bukkit Entity!", e);
}
}
/**
* Reads in a InputStream as NMS Compound
*
* @param stream InputStream of any NBT file
* @return NMS Compound
*/
public static Object readNBT(InputStream stream) {
try {
return ReflectionMethod.NBTFILE_READ.run(null, stream);
} catch (Exception e) {
throw new NbtApiException("Exception while reading a NBT File!", e);
}
}
/**
* Writes a NMS Compound to an OutputStream
*
* @param nbt NMS Compound
* @param stream Stream to write to
* @return ???
*/
public static Object writeNBT(Object nbt, OutputStream stream) {
try {
return ReflectionMethod.NBTFILE_WRITE.run(null, nbt, stream);
} catch (Exception e) {
throw new NbtApiException("Exception while writing NBT!", e);
}
}
/**
* Writes a Compound to an OutputStream
*
* @param comp Compound
* @param stream Stream to write to
*/
public static void writeApiNBT(NBTCompound comp, OutputStream stream) {
try {
Object nbttag = comp.getCompound();
if (nbttag == null) {
nbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp))
return;
Object workingtag = gettoCompount(nbttag, comp);
ReflectionMethod.NBTFILE_WRITE.run(null, workingtag, stream);
} catch (Exception e) {
throw new NbtApiException("Exception while writing NBT!", e);
}
}
/**
* Simulates getOrCreateTag. If an Item doesn't yet have a Tag, it will return a
* new empty tag.
*
* @param nmsitem
* @return NMS Compound
*/
public static Object getItemRootNBTTagCompound(Object nmsitem) {
try {
Object answer = ReflectionMethod.NMSITEM_GETTAG.run(nmsitem);
return answer != null ? answer : ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
} catch (Exception e) {
throw new NbtApiException("Exception while getting an Itemstack's NBTCompound!", e);
}
}
/**
* Converts {@link NBTCompound} to NMS ItemStacks
*
* @param nbtcompound Any valid {@link NBTCompound}
* @return NMS ItemStack
*/
public static Object convertNBTCompoundtoNMSItem(NBTCompound nbtcompound) {
try {
Object nmsComp = gettoCompount(nbtcompound.getCompound(), nbtcompound);
if (MinecraftVersion.getVersion().getVersionId() >= MinecraftVersion.MC1_11_R1.getVersionId()) {
return ObjectCreator.NMS_COMPOUNDFROMITEM.getInstance(nmsComp);
} else {
return ReflectionMethod.NMSITEM_CREATESTACK.run(null, nmsComp);
}
} catch (Exception e) {
throw new NbtApiException("Exception while converting NBTCompound to NMS ItemStack!", e);
}
}
/**
* Converts NMS ItemStacks to {@link NBTContainer}
*
* @param nmsitem NMS ItemStack
* @return {@link NBTContainer} with all the data
*/
public static NBTContainer convertNMSItemtoNBTCompound(Object nmsitem) {
try {
Object answer = ReflectionMethod.NMSITEM_SAVE.run(nmsitem, ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance());
return new NBTContainer(answer);
} catch (Exception e) {
throw new NbtApiException("Exception while converting NMS ItemStack to NBTCompound!", e);
}
}
/**
* Gets a live copy of non-vanilla NBT tags.
*
* @param meta ItemMeta from which tags should be retrieved
* @return Map containing unhandled (custom) NBT tags
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> getUnhandledNBTTags(ItemMeta meta) {
try {
return (Map<String, Object>) field_unhandledTags.get(meta);
} catch (Exception e) {
throw new NbtApiException("Exception while getting unhandled tags from ItemMeta!", e);
}
}
/**
* Gets the Vanilla NBT Compound from a given NMS Entity
*
* @param nmsEntity
* @return NMS NBT Compound
*/
public static Object getEntityNBTTagCompound(Object nmsEntity) {
try {
Object nbt = ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance();
Object answer = ReflectionMethod.NMS_ENTITY_GET_NBT.run(nmsEntity, nbt);
if (answer == null)
answer = nbt;
return answer;
} catch (Exception e) {
throw new NbtApiException("Exception while getting NBTCompound from NMS Entity!", e);
}
}
/**
* Loads all Vanilla tags from a NMS Compound into a NMS Entity
*
* @param nbtTag
* @param nmsEntity
* @return The NMS Entity
*/
public static Object setEntityNBTTag(Object nbtTag, Object nmsEntity) {
try {
ReflectionMethod.NMS_ENTITY_SET_NBT.run(nmsEntity, nbtTag);
return nmsEntity;
} catch (Exception ex) {
throw new NbtApiException("Exception while setting the NBTCompound of an Entity", ex);
}
}
/**
* Gets the NMS Compound from a given TileEntity
*
* @param tile
* @return NMS Compound with the Vanilla data
*/
public static Object getTileEntityNBTTagCompound(BlockState tile) {
try {
Object cworld = ClassWrapper.CRAFT_WORLD.getClazz().cast(tile.getWorld());
Object nmsworld = ReflectionMethod.CRAFT_WORLD_GET_HANDLE.run(cworld);
Object o = null;
if(MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4) {
o = ReflectionMethod.NMS_WORLD_GET_TILEENTITY_1_7_10.run(nmsworld, tile.getX(), tile.getY(), tile.getZ());
}else {
Object pos = ObjectCreator.NMS_BLOCKPOSITION.getInstance(tile.getX(), tile.getY(), tile.getZ());
o = ReflectionMethod.NMS_WORLD_GET_TILEENTITY.run(nmsworld, pos);
}
Object tag = ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance();
Object answer = ReflectionMethod.TILEENTITY_GET_NBT.run(o, tag);
if (answer == null)
answer = tag;
return answer;
} catch (Exception e) {
throw new NbtApiException("Exception while getting NBTCompound from TileEntity!", e);
}
}
/**
* Sets Vanilla tags from a NMS Compound to a TileEntity
*
* @param tile
* @param comp
*/
public static void setTileEntityNBTTagCompound(BlockState tile, Object comp) {
try {
Object cworld = ClassWrapper.CRAFT_WORLD.getClazz().cast(tile.getWorld());
Object nmsworld = ReflectionMethod.CRAFT_WORLD_GET_HANDLE.run(cworld);
Object o = null;
if(MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4) {
o = ReflectionMethod.NMS_WORLD_GET_TILEENTITY_1_7_10.run(nmsworld, tile.getX(), tile.getY(), tile.getZ());
}else {
Object pos = ObjectCreator.NMS_BLOCKPOSITION.getInstance(tile.getX(), tile.getY(), tile.getZ());
o = ReflectionMethod.NMS_WORLD_GET_TILEENTITY.run(nmsworld, pos);
}
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_17_R1)) {
ReflectionMethod.TILEENTITY_SET_NBT.run(o, comp);
}else if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_16_R1)) {
Object blockData = ReflectionMethod.TILEENTITY_GET_BLOCKDATA.run(o);
ReflectionMethod.TILEENTITY_SET_NBT_LEGACY1161.run(o, blockData, comp);
}else {
ReflectionMethod.TILEENTITY_SET_NBT_LEGACY1151.run(o, comp);
}
} catch (Exception e) {
throw new NbtApiException("Exception while setting NBTData for a TileEntity!", e);
}
}
/**
* Gets the subCompound with a given name from a NMS Compound
*
* @param compound
* @param name
* @return NMS Compound or null
*/
public static Object getSubNBTTagCompound(Object compound, String name) {
try {
if ((boolean) ReflectionMethod.COMPOUND_HAS_KEY.run(compound, name)) {
return ReflectionMethod.COMPOUND_GET_COMPOUND.run(compound, name);
} else {
throw new NbtApiException("Tried getting invalide compound '" + name + "' from '" + compound + "'!");
}
} catch (Exception e) {
throw new NbtApiException("Exception while getting NBT subcompounds!", e);
}
}
/**
* Creates a subCompound with a given name in the given NMS Compound
*
* @param comp
* @param name
*/
public static void addNBTTagCompound(NBTCompound comp, String name) {
if (name == null) {
remove(comp, name);
return;
}
Object nbttag = comp.getCompound();
if (nbttag == null) {
nbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp)) {
return;
}
Object workingtag = gettoCompount(nbttag, comp);
try {
ReflectionMethod.COMPOUND_SET.run(workingtag, name,
ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz().newInstance());
comp.setCompound(nbttag);
} catch (Exception e) {
throw new NbtApiException("Exception while adding a Compound!", e);
}
}
/**
* Checks if the Compound is correctly linked to it's roots
*
* @param comp
* @return true if this is a valide Compound, else false
*/
public static Boolean valideCompound(NBTCompound comp) {
Object root = comp.getCompound();
if (root == null) {
root = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
return (gettoCompount(root, comp)) != null;
}
protected static Object gettoCompount(Object nbttag, NBTCompound comp) {
Deque<String> structure = new ArrayDeque<>();
while (comp.getParent() != null) {
structure.add(comp.getName());
comp = comp.getParent();
}
while (!structure.isEmpty()) {
String target = structure.pollLast();
nbttag = getSubNBTTagCompound(nbttag, target);
if (nbttag == null) {
throw new NbtApiException("Unable to find tag '" + target + "' in " + nbttag);
}
}
return nbttag;
}
/**
* Merges the second {@link NBTCompound} into the first one
*
* @param comp Target for the merge
* @param nbtcompoundSrc Data to merge
*/
public static void mergeOtherNBTCompound(NBTCompound comp, NBTCompound nbtcompoundSrc) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp))
throw new NbtApiException("The Compound wasn't able to be linked back to the root!");
Object workingtag = gettoCompount(rootnbttag, comp);
Object rootnbttagSrc = nbtcompoundSrc.getCompound();
if (rootnbttagSrc == null) {
rootnbttagSrc = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(nbtcompoundSrc))
throw new NbtApiException("The Compound wasn't able to be linked back to the root!");
Object workingtagSrc = gettoCompount(rootnbttagSrc, nbtcompoundSrc);
try {
ReflectionMethod.COMPOUND_MERGE.run(workingtag, workingtagSrc);
comp.setCompound(rootnbttag);
} catch (Exception e) {
throw new NbtApiException("Exception while merging two NBTCompounds!", e);
}
}
/**
* Returns the content for a given key inside a Compound
*
* @param comp
* @param key
* @return Content saved under this key
*/
public static String getContent(NBTCompound comp, String key) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp))
throw new NbtApiException("The Compound wasn't able to be linked back to the root!");
Object workingtag = gettoCompount(rootnbttag, comp);
try {
return ReflectionMethod.COMPOUND_GET.run(workingtag, key).toString();
} catch (Exception e) {
throw new NbtApiException("Exception while getting the Content for key '" + key + "'!", e);
}
}
/**
* Sets a key in a {@link NBTCompound} to a given value
*
* @param comp
* @param key
* @param val
*/
public static void set(NBTCompound comp, String key, Object val) {
if (val == null) {
remove(comp, key);
return;
}
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp)) {
throw new NbtApiException("The Compound wasn't able to be linked back to the root!");
}
Object workingtag = gettoCompount(rootnbttag, comp);
try {
ReflectionMethod.COMPOUND_SET.run(workingtag, key, val);
comp.setCompound(rootnbttag);
} catch (Exception e) {
throw new NbtApiException("Exception while setting key '" + key + "' to '" + val + "'!", e);
}
}
/**
* Returns the List saved with a given key.
*
* @param comp
* @param key
* @param type
* @param clazz
* @return The list at that key. Null if it's an invalide type
*/
@SuppressWarnings("unchecked")
public static <T> NBTList<T> getList(NBTCompound comp, String key, NBTType type, Class<T> clazz) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp))
return null;
Object workingtag = gettoCompount(rootnbttag, comp);
try {
Object nbt = ReflectionMethod.COMPOUND_GET_LIST.run(workingtag, key, type.getId());
if (clazz == String.class) {
return (NBTList<T>) new NBTStringList(comp, key, type, nbt);
} else if (clazz == NBTListCompound.class) {
return (NBTList<T>) new NBTCompoundList(comp, key, type, nbt);
} else if (clazz == Integer.class) {
return (NBTList<T>) new NBTIntegerList(comp, key, type, nbt);
} else if (clazz == Float.class) {
return (NBTList<T>) new NBTFloatList(comp, key, type, nbt);
} else if (clazz == Double.class) {
return (NBTList<T>) new NBTDoubleList(comp, key, type, nbt);
} else if (clazz == Long.class) {
return (NBTList<T>) new NBTLongList(comp, key, type, nbt);
} else {
return null;
}
} catch (Exception ex) {
throw new NbtApiException("Exception while getting a list with the type '" + type + "'!", ex);
}
}
public static NBTType getListType(NBTCompound comp, String key) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp))
return null;
Object workingtag = gettoCompount(rootnbttag, comp);
try {
Object nbt = ReflectionMethod.COMPOUND_GET.run(workingtag, key);
String fieldname = "type";
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_17_R1)) {
fieldname = "w";
}
Field f = nbt.getClass().getDeclaredField(fieldname);
f.setAccessible(true);
return NBTType.valueOf(f.getByte(nbt));
} catch (Exception ex) {
throw new NbtApiException("Exception while getting the list type!", ex);
}
}
public static Object getEntry(NBTCompound comp, String key) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp))
return null;
Object workingtag = gettoCompount(rootnbttag, comp);
try {
Object nbt = ReflectionMethod.COMPOUND_GET.run(workingtag, key);
return nbt;
} catch (Exception ex) {
throw new NbtApiException("Exception while getting an Entry!", ex);
}
}
/**
* Uses Gson to set a {@link Serializable} value in a Compound
*
* @param comp
* @param key
* @param value
*/
public static void setObject(NBTCompound comp, String key, Object value) {
if (!MinecraftVersion.hasGsonSupport())
return;
try {
String json = GsonWrapper.getString(value);
setData(comp, ReflectionMethod.COMPOUND_SET_STRING, key, json);
} catch (Exception e) {
throw new NbtApiException("Exception while setting the Object '" + value + "'!", e);
}
}
/**
* Uses Gson to load back a {@link Serializable} object from the Compound
*
* @param comp
* @param key
* @param type
* @return The loaded Object or null, if not found
*/
public static <T> T getObject(NBTCompound comp, String key, Class<T> type) {
if (!MinecraftVersion.hasGsonSupport())
return null;
String json = (String) getData(comp, ReflectionMethod.COMPOUND_GET_STRING, key);
if (json == null) {
return null;
}
return GsonWrapper.deserializeJson(json, type);
}
/**
* Deletes the given key
*
* @param comp
* @param key
*/
public static void remove(NBTCompound comp, String key) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp))
return;
Object workingtag = gettoCompount(rootnbttag, comp);
ReflectionMethod.COMPOUND_REMOVE_KEY.run(workingtag, key);
comp.setCompound(rootnbttag);
}
/**
* Gets the Keyset inside this Compound
*
* @param comp
* @return Set of all keys
*/
@SuppressWarnings("unchecked")
public static Set<String> getKeys(NBTCompound comp) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp))
throw new NbtApiException("The Compound wasn't able to be linked back to the root!");
Object workingtag = gettoCompount(rootnbttag, comp);
return (Set<String>) ReflectionMethod.COMPOUND_GET_KEYS.run(workingtag);
}
/**
* Sets data inside the Compound
*
* @param comp
* @param type
* @param key
* @param data
*/
public static void setData(NBTCompound comp, ReflectionMethod type, String key, Object data) {
if (data == null) {
remove(comp, key);
return;
}
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
rootnbttag = ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance();
}
if (!valideCompound(comp))
throw new NbtApiException("The Compound wasn't able to be linked back to the root!");
Object workingtag = gettoCompount(rootnbttag, comp);
type.run(workingtag, key, data);
comp.setCompound(rootnbttag);
}
/**
* Gets data from the Compound
*
* @param comp
* @param type
* @param key
* @return The value or default fallback from NMS
*/
public static Object getData(NBTCompound comp, ReflectionMethod type, String key) {
Object rootnbttag = comp.getCompound();
if (rootnbttag == null) {
return null;
}
if (!valideCompound(comp))
throw new NbtApiException("The Compound wasn't able to be linked back to the root!");
Object workingtag = gettoCompount(rootnbttag, comp);
return type.run(workingtag, key);
}
}
@@ -1,42 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ClassWrapper;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* String implementation for NBTLists
*
* @author tr7zw
*
*/
public class NBTStringList extends NBTList<String> {
protected NBTStringList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
@Override
public String get(int index) {
try {
return (String) ReflectionMethod.LIST_GET_STRING.run(listObject, index);
} catch (Exception ex) {
throw new NbtApiException(ex);
}
}
@Override
protected Object asTag(String object) {
try {
Constructor<?> con = ClassWrapper.NMS_NBTTAGSTRING.getClazz().getDeclaredConstructor(String.class);
con.setAccessible(true);
return con.newInstance(object);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new NbtApiException("Error while wrapping the Object " + object + " to it's NMS object!", e);
}
}
}
@@ -1,64 +0,0 @@
package de.tr7zw.changeme.nbtapi;
import org.bukkit.block.BlockState;
import de.tr7zw.annotations.FAUtil;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import de.tr7zw.changeme.nbtapi.utils.annotations.AvailableSince;
import de.tr7zw.changeme.nbtapi.utils.annotations.CheckUtil;
/**
* NBT class to access vanilla tags from TileEntities. TileEntities don't
* support custom tags. Use the NBTInjector for custom tags. Changes will be
* instantly applied to the Tile, use the merge method to do many things at
* once.
*
* @author tr7zw
*
*/
public class NBTTileEntity extends NBTCompound {
private final BlockState tile;
/**
* @param tile BlockState from any TileEntity
*/
public NBTTileEntity(BlockState tile) {
super(null, null);
if (tile == null || (MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_8_R3) && !tile.isPlaced())) {
throw new NullPointerException("Tile can't be null/not placed!");
}
this.tile = tile;
}
@Override
public Object getCompound() {
return NBTReflectionUtil.getTileEntityNBTTagCompound(tile);
}
@Override
protected void setCompound(Object compound) {
NBTReflectionUtil.setTileEntityNBTTagCompound(tile, compound);
}
/**
* Gets the NBTCompound used by spigots PersistentDataAPI. This method is only
* available for 1.14+!
*
* @return NBTCompound containing the data of the PersistentDataAPI
*/
@AvailableSince(version = MinecraftVersion.MC1_14_R1)
public NBTCompound getPersistentDataContainer() {
FAUtil.check(this::getPersistentDataContainer, CheckUtil::isAvaliable);
if (hasKey("PublicBukkitValues")) {
return getCompound("PublicBukkitValues");
} else {
NBTContainer container = new NBTContainer();
container.addCompound("PublicBukkitValues").setString("__nbtapi",
"Marker to make the PersistentDataContainer have content");
mergeCompound(container);
return getCompound("PublicBukkitValues");
}
}
}
@@ -1,388 +0,0 @@
package de.tr7zw.changeme.nbtapi.utils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.ServicePriority;
import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
import static de.tr7zw.changeme.nbtapi.utils.MinecraftVersion.getLogger;
/**
* bStats collects some data for plugin authors.
* <p>
* Check out https://bStats.org/ to learn more about bStats!
*
* This class is modified by tr7zw to work when the api is shaded into other peoples plugins.
*/
public class ApiMetricsLite {
private static final String PLUGINNAME = "ItemNBTAPI"; // DO NOT CHANGE THE NAME! else it won't link the data on bStats
// The version of this bStats class
public static final int B_STATS_VERSION = 1;
// The version of the NBT-Api bStats
public static final int NBT_BSTATS_VERSION = 1;
// The url to which the data is sent
private static final String URL = "https://bStats.org/submitData/bukkit";
// Is bStats enabled on this server?
private boolean enabled;
// Should failed requests be logged?
private static boolean logFailedRequests;
// Should the sent data be logged?
private static boolean logSentData;
// Should the response text be logged?
private static boolean logResponseStatusText;
// The uuid of the server
private static String serverUUID;
// The plugin
private Plugin plugin;
/**
* Class constructor.
*
*/
public ApiMetricsLite() {
// The register method just uses any enabled plugin it can find to register. This *shouldn't* cause any problems, since the plugin isn't used any other way.
// Register our service
for(Plugin plug : Bukkit.getPluginManager().getPlugins()) {
plugin = plug;
if(plugin != null)
break;
}
if(plugin == null) {
return;// Didn't find any plugin that could work
}
// Get the config file
File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats");
File configFile = new File(bStatsFolder, "config.yml");
YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);
// Check if the config file exists
if (!config.isSet("serverUuid")) {
// Add default values
config.addDefault("enabled", true);
// Every server gets it's unique random id.
config.addDefault("serverUuid", UUID.randomUUID().toString());
// Should failed request be logged?
config.addDefault("logFailedRequests", false);
// Should the sent data be logged?
config.addDefault("logSentData", false);
// Should the response text be logged?
config.addDefault("logResponseStatusText", false);
// Inform the server owners about bStats
config.options().header(
"bStats collects some data for plugin authors like how many servers are using their plugins.\n" +
"To honor their work, you should not disable it.\n" +
"This has nearly no effect on the server performance!\n" +
"Check out https://bStats.org/ to learn more :)"
).copyDefaults(true);
try {
config.save(configFile);
} catch (IOException ignored) { }
}
// Load the data
serverUUID = config.getString("serverUuid");
logFailedRequests = config.getBoolean("logFailedRequests", false);
enabled = config.getBoolean("enabled", true);
logSentData = config.getBoolean("logSentData", false);
logResponseStatusText = config.getBoolean("logResponseStatusText", false);
if (enabled) {
boolean found = false;
// Search for all other bStats Metrics classes to see if we are the first one
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("NBT_BSTATS_VERSION"); // Create only one instance of the nbt-api bstats.
return;
} catch (NoSuchFieldException ignored) { }
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
found = true; // We aren't the first
break;
} catch (NoSuchFieldException ignored) { }
}
boolean fFound = found;
// Register our service
if(Bukkit.isPrimaryThread()){
Bukkit.getServicesManager().register(ApiMetricsLite.class, this, plugin, ServicePriority.Normal);
if (!fFound) {
getLogger().info("[NBTAPI] Using the plugin '" + plugin.getName() + "' to create a bStats instance!");
// We are the first!
startSubmitting();
}
}else{
Bukkit.getScheduler().runTask(plugin, () -> {
Bukkit.getServicesManager().register(ApiMetricsLite.class, this, plugin, ServicePriority.Normal);
if (!fFound) {
getLogger().info("[NBTAPI] Using the plugin '" + plugin.getName() + "' to create a bStats instance!");
// We are the first!
startSubmitting();
}
});
}
}
}
/**
* Checks if bStats is enabled.
*
* @return Whether bStats is enabled or not.
*/
public boolean isEnabled() {
return enabled;
}
/**
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (!plugin.isEnabled()) { // Plugin was disabled
timer.cancel();
return;
}
// Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler
// Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;)
Bukkit.getScheduler().runTask(plugin, () -> submitData());
}
}, 1000l * 60l * 5l, 1000l * 60l * 30l);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
}
/**
* Gets the plugin specific data.
* This method is called using Reflection.
*
* @return The plugin specific data.
*/
public JsonObject getPluginData() {
JsonObject data = new JsonObject();
data.addProperty("pluginName", PLUGINNAME); // Append the name of the plugin
data.addProperty("pluginVersion", MinecraftVersion.VERSION); // Append the version of the plugin
data.add("customCharts", new JsonArray());
return data;
}
/**
* Gets the server specific data.
*
* @return The server specific data.
*/
private JsonObject getServerData() {
// Minecraft specific data
int playerAmount;
try {
// Around MC 1.8 the return type was changed to a collection from an array,
// This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;
Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers");
playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class)
? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()
: ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;
} catch (Exception e) {
playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed
}
int onlineMode = Bukkit.getOnlineMode() ? 1 : 0;
String bukkitVersion = Bukkit.getVersion();
String bukkitName = Bukkit.getName();
// OS/Java specific data
String javaVersion = System.getProperty("java.version");
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");
String osVersion = System.getProperty("os.version");
int coreCount = Runtime.getRuntime().availableProcessors();
JsonObject data = new JsonObject();
data.addProperty("serverUUID", serverUUID);
data.addProperty("playerAmount", playerAmount);
data.addProperty("onlineMode", onlineMode);
data.addProperty("bukkitVersion", bukkitVersion);
data.addProperty("bukkitName", bukkitName);
data.addProperty("javaVersion", javaVersion);
data.addProperty("osName", osName);
data.addProperty("osArch", osArch);
data.addProperty("osVersion", osVersion);
data.addProperty("coreCount", coreCount);
return data;
}
/**
* Collects the data and sends it afterwards.
*/
private void submitData() {
final JsonObject data = getServerData();
JsonArray pluginData = new JsonArray();
// Search for all other bStats Metrics classes to get their plugin data
for (Class<?> service : Bukkit.getServicesManager().getKnownServices()) {
try {
service.getField("B_STATS_VERSION"); // Our identifier :)
for (RegisteredServiceProvider<?> provider : Bukkit.getServicesManager().getRegistrations(service)) {
try {
Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider());
if (plugin instanceof JsonObject) {
pluginData.add((JsonObject) plugin);
} else { // old bstats version compatibility
try {
Class<?> jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject");
if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) {
Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString");
jsonStringGetter.setAccessible(true);
String jsonString = (String) jsonStringGetter.invoke(plugin);
JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject();
pluginData.add(object);
}
} catch (ClassNotFoundException e) {
// minecraft version 1.14+
if (logFailedRequests) {
getLogger().log(Level.WARNING, "[NBTAPI][BSTATS] Encountered exception while posting request!", e);
// Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time
//this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception ", e);
}
continue; // continue looping since we cannot do any other thing.
}
}
} catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) {
}
}
} catch (NoSuchFieldException ignored) { }
}
data.add("plugins", pluginData);
// Create a new thread for the connection to the bStats server
new Thread(new Runnable() {
@Override
public void run() {
try {
// Send the data
sendData(plugin, data);
} catch (Exception e) {
// Something went wrong! :(
if (logFailedRequests) {
getLogger().log(Level.WARNING, "[NBTAPI][BSTATS] Could not submit plugin stats of " + plugin.getName(), e);
// Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time
//plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e);
}
}
}
}).start();
}
/**
* Sends the data to the bStats server.
*
* @param plugin Any plugin. It's just used to get a logger instance.
* @param data The data to send.
* @throws Exception If the request failed.
*/
private static void sendData(Plugin plugin, JsonObject data) throws Exception {
if (data == null) {
throw new IllegalArgumentException("Data cannot be null!");
}
if (Bukkit.isPrimaryThread()) {
throw new IllegalAccessException("This method must not be called from the main thread!");
}
if (logSentData) {
System.out.println("[NBTAPI][BSTATS] Sending data to bStats: " + data.toString());
// Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time
//plugin.getLogger().info("Sending data to bStats: " + data.toString());
}
HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();
// Compress the data to save bandwidth
byte[] compressedData = compress(data.toString());
// Add headers
connection.setRequestMethod("POST");
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);
// Send data
connection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.write(compressedData);
outputStream.flush();
outputStream.close();
InputStream inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
bufferedReader.close();
if (logResponseStatusText) {
getLogger().info("[NBTAPI][BSTATS] Sent data to bStats and received response: " + builder.toString());
// Not using the plugins logger since the plugin isn't the plugin containing the NBT-Api most of the time
//plugin.getLogger().info("Sent data to bStats and received response: " + builder.toString());
}
}
/**
* Gzips the given String.
*
* @param str The string to gzip.
* @return The gzipped String.
* @throws IOException If the compression failed.
*/
private static byte[] compress(final String str) throws IOException {
if (str == null) {
return new byte[0];
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
gzip.write(str.getBytes(StandardCharsets.UTF_8));
gzip.close();
return outputStream.toByteArray();
}
}
@@ -1,54 +0,0 @@
package de.tr7zw.changeme.nbtapi.utils;
import com.google.gson.Gson;
import de.tr7zw.changeme.nbtapi.NbtApiException;
/**
* Helper class for 1.7 servers without Gson
*
* @author tr7zw
*
*/
public class GsonWrapper {
/**
* Private constructor
*/
private GsonWrapper() {
}
private static final Gson gson = new Gson();
/**
* Turns Objects into Json Strings
*
* @param obj
* @return Json, representing the Object
*/
public static String getString(Object obj) {
return gson.toJson(obj);
}
/**
* Creates an Object of the given type using the Json String
*
* @param json
* @param type
* @return Object that got created, or null if the json is null
*/
public static <T> T deserializeJson(String json, Class<T> type) {
try {
if (json == null) {
return null;
}
T obj = gson.fromJson(json, type);
return type.cast(obj);
} catch (Exception ex) {
throw new NbtApiException("Error while converting json to " + type.getName(), ex);
}
}
}
@@ -1,53 +0,0 @@
package de.tr7zw.changeme.nbtapi.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import de.tr7zw.changeme.nbtapi.NbtApiException;
public final class ReflectionUtil {
private static Field field_modifiers;
static {
try {
field_modifiers = Field.class.getDeclaredField("modifiers");
field_modifiers.setAccessible(true);
} catch (NoSuchFieldException ex) {
try {
// This hacky workaround is for newer jdk versions 11+?
Method fieldGetter = Class.class.getDeclaredMethod("getDeclaredFields0", boolean.class);
fieldGetter.setAccessible(true);
Field[] fields = (Field[]) fieldGetter.invoke(Field.class, false);
for (Field f : fields)
if (f.getName().equals("modifiers")) {
field_modifiers = f;
field_modifiers.setAccessible(true);
break;
}
} catch (Exception e) {
throw new NbtApiException(e);
}
}
if (field_modifiers == null) {
throw new NbtApiException("Unable to init the modifiers Field.");
}
}
public static Field makeNonFinal(Field field) throws IllegalArgumentException, IllegalAccessException {
int mods = field.getModifiers();
if (Modifier.isFinal(mods)) {
field_modifiers.set(field, mods & ~Modifier.FINAL);
}
return field;
}
public static void setFinal(Object obj, Field field, Object newValue)
throws IllegalArgumentException, IllegalAccessException {
field.setAccessible(true);
field = makeNonFinal(field);
field.set(obj, newValue);
}
}
@@ -1,106 +0,0 @@
package de.tr7zw.changeme.nbtapi.utils;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import de.tr7zw.changeme.nbtapi.NBTItem;
/**
* This class uses the Spiget API to check for updates
*
*/
public class VersionChecker {
private static final String USER_AGENT = "nbt-api Version check";
private static final String REQUEST_URL = "https://api.spiget.org/v2/resources/7939/versions?size=100";
protected static void checkForUpdates() throws Exception {
URL url = new URL(REQUEST_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.addRequestProperty("User-Agent", USER_AGENT);// Set
// User-Agent
// If you're not sure if the request will be successful,
// you need to check the response code and use #getErrorStream if it
// returned an error code
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
// This could be either a JsonArray or JsonObject
JsonElement element = new JsonParser().parse(reader);
if (element.isJsonArray()) {
// Is JsonArray
JsonArray updates = (JsonArray) element;
JsonObject latest = (JsonObject) updates.get(updates.size() - 1);
int versionDifference = getVersionDifference(latest.get("name").getAsString());
if (versionDifference == -1) { // Outdated
MinecraftVersion.getLogger().log(Level.WARNING,
"[NBTAPI] The NBT-API at '" + NBTItem.class.getPackage() + "' seems to be outdated!");
MinecraftVersion.getLogger().log(Level.WARNING, "[NBTAPI] Current Version: '" + MinecraftVersion.VERSION
+ "' Newest Version: " + latest.get("name").getAsString() + "'");
MinecraftVersion.getLogger().log(Level.WARNING,
"[NBTAPI] Please update the nbt-api or the plugin that contains the api!");
} else if (versionDifference == 0) {
MinecraftVersion.getLogger().log(Level.INFO, "[NBTAPI] The NBT-API seems to be up-to-date!");
} else if (versionDifference == 1) {
MinecraftVersion.getLogger().log(Level.WARNING, "[NBTAPI] The NBT-API at '" + NBTItem.class.getPackage()
+ "' seems to be a future Version, not yet released on Spigot/CurseForge!");
MinecraftVersion.getLogger().log(Level.WARNING, "[NBTAPI] Current Version: '" + MinecraftVersion.VERSION
+ "' Newest Version: " + latest.get("name").getAsString() + "'");
}
} else {
// wut?!
MinecraftVersion.getLogger().log(Level.WARNING,
"[NBTAPI] Error when looking for Updates! Got non Json Array: '" + element.toString() + "'");
}
}
// -1 = we are outdated
// 0 = up to date
// 1 = using a future version
// This method is only able to compare the Format 0.0.0(-SNAPSHOT)
private static int getVersionDifference(String version) {
String current = MinecraftVersion.VERSION;
if (current.equals(version))
return 0;
String pattern = "\\.";
if (current.split(pattern).length != 3 || version.split(pattern).length != 3)
return -1;
int curMaj = Integer.parseInt(current.split(pattern)[0]);
int curMin = Integer.parseInt(current.split(pattern)[1]);
String curPatch = current.split(pattern)[2];
int relMaj = Integer.parseInt(version.split(pattern)[0]);
int relMin = Integer.parseInt(version.split(pattern)[1]);
String relPatch = version.split(pattern)[2];
if (curMaj < relMaj)
return -1;
if (curMaj > relMaj)
return 1;
if (curMin < relMin)
return -1;
if (curMin > relMin)
return 1;
int curPatchN = Integer.parseInt(curPatch.split("-")[0]);
int relPatchN = Integer.parseInt(relPatch.split("-")[0]);
if (curPatchN < relPatchN)
return -1;
if (curPatchN > relPatchN)
return 1;
if (!relPatch.contains("-") && curPatch.contains("-"))
return -1; // Release has no - but we do = We use a Snapshot of the
// release
if (relPatch.contains("-") && curPatch.contains("-"))
return 0; // Release and cur are Snapshots/alpha/beta
return 1;
}
}
@@ -1,94 +0,0 @@
package de.tr7zw.changeme.nbtapi.utils.nmsmappings;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import static de.tr7zw.changeme.nbtapi.utils.MinecraftVersion.getLogger;
/**
* Wraps NMS and CRAFT classes
*
* @author tr7zw
*
*/
@SuppressWarnings("javadoc")
public enum ClassWrapper {
CRAFT_ITEMSTACK(PackageWrapper.CRAFTBUKKIT, "inventory.CraftItemStack", null, null),
CRAFT_METAITEM(PackageWrapper.CRAFTBUKKIT, "inventory.CraftMetaItem", null, null),
CRAFT_ENTITY(PackageWrapper.CRAFTBUKKIT, "entity.CraftEntity", null, null),
CRAFT_WORLD(PackageWrapper.CRAFTBUKKIT, "CraftWorld", null, null),
CRAFT_PERSISTENTDATACONTAINER(PackageWrapper.CRAFTBUKKIT, "persistence.CraftPersistentDataContainer",
MinecraftVersion.MC1_14_R1, null),
NMS_NBTBASE(PackageWrapper.NMS, "NBTBase", null, null, "net.minecraft.nbt"),
NMS_NBTTAGSTRING(PackageWrapper.NMS, "NBTTagString", null, null, "net.minecraft.nbt"),
NMS_NBTTAGINT(PackageWrapper.NMS, "NBTTagInt", null, null, "net.minecraft.nbt"),
NMS_NBTTAGFLOAT(PackageWrapper.NMS, "NBTTagFloat", null, null, "net.minecraft.nbt"),
NMS_NBTTAGDOUBLE(PackageWrapper.NMS, "NBTTagDouble", null, null, "net.minecraft.nbt"),
NMS_NBTTAGLONG(PackageWrapper.NMS, "NBTTagLong", null, null, "net.minecraft.nbt"),
NMS_ITEMSTACK(PackageWrapper.NMS, "ItemStack", null, null, "net.minecraft.world.item"),
NMS_NBTTAGCOMPOUND(PackageWrapper.NMS, "NBTTagCompound", null, null, "net.minecraft.nbt"),
NMS_NBTTAGLIST(PackageWrapper.NMS, "NBTTagList", null, null, "net.minecraft.nbt"),
NMS_NBTCOMPRESSEDSTREAMTOOLS(PackageWrapper.NMS, "NBTCompressedStreamTools", null, null, "net.minecraft.nbt"),
NMS_MOJANGSONPARSER(PackageWrapper.NMS, "MojangsonParser", null, null, "net.minecraft.nbt"),
NMS_TILEENTITY(PackageWrapper.NMS, "TileEntity", null, null, "net.minecraft.world.level.block.entity"),
NMS_BLOCKPOSITION(PackageWrapper.NMS, "BlockPosition", MinecraftVersion.MC1_8_R3, null, "net.minecraft.core"),
NMS_WORLDSERVER(PackageWrapper.NMS, "WorldServer", null, null, "net.minecraft.server.level"),
NMS_MINECRAFTSERVER(PackageWrapper.NMS, "MinecraftServer", null, null, "net.minecraft.server"),
NMS_WORLD(PackageWrapper.NMS, "World", null, null, "net.minecraft.world.level"),
NMS_ENTITY(PackageWrapper.NMS, "Entity", null, null, "net.minecraft.world.entity"),
NMS_ENTITYTYPES(PackageWrapper.NMS, "EntityTypes", null, null, "net.minecraft.world.entity"),
NMS_REGISTRYSIMPLE(PackageWrapper.NMS, "RegistrySimple", MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_12_R1),
NMS_REGISTRYMATERIALS(PackageWrapper.NMS, "RegistryMaterials", null, null, "net.minecraft.core"),
NMS_IREGISTRY(PackageWrapper.NMS, "IRegistry", null, null, "net.minecraft.core"),
NMS_MINECRAFTKEY(PackageWrapper.NMS, "MinecraftKey", MinecraftVersion.MC1_8_R3, null, "net.minecraft.resources"),
NMS_GAMEPROFILESERIALIZER(PackageWrapper.NMS, "GameProfileSerializer", null, null, "net.minecraft.nbt"),
NMS_IBLOCKDATA(PackageWrapper.NMS, "IBlockData", MinecraftVersion.MC1_8_R3, null,
"net.minecraft.world.level.block.state"),
GAMEPROFILE(PackageWrapper.NONE, "com.mojang.authlib.GameProfile", MinecraftVersion.MC1_8_R3, null);
private Class<?> clazz;
private boolean enabled = false;
ClassWrapper(PackageWrapper packageId, String clazzName, MinecraftVersion from, MinecraftVersion to) {
this(packageId, clazzName, from, to, null);
}
ClassWrapper(PackageWrapper packageId, String clazzName, MinecraftVersion from, MinecraftVersion to,
String mojangMap) {
if (from != null && MinecraftVersion.getVersion().getVersionId() < from.getVersionId()) {
return;
}
if (to != null && MinecraftVersion.getVersion().getVersionId() > to.getVersionId()) {
return;
}
enabled = true;
try {
if (MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_17_R1) && mojangMap != null) {
clazz = Class.forName(mojangMap + "." + clazzName);
} else if (packageId == PackageWrapper.NONE) {
clazz = Class.forName(clazzName);
} else {
String version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3];
clazz = Class.forName(packageId.getUri() + "." + version + "." + clazzName);
}
} catch (Exception ex) {
getLogger().log(Level.WARNING, "[NBTAPI] Error while trying to resolve the class '" + clazzName + "'!", ex);
}
}
/**
* @return The wrapped class
*/
public Class<?> getClazz() {
return clazz;
}
/**
* @return Is this class available in this Version
*/
public boolean isEnabled() {
return enabled;
}
}
@@ -1,56 +0,0 @@
package de.tr7zw.changeme.nbtapi.utils.nmsmappings;
import java.lang.reflect.Constructor;
import java.util.logging.Level;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import static de.tr7zw.changeme.nbtapi.utils.MinecraftVersion.getLogger;
/**
* This Enum wraps Constructors for NMS classes
*
* @author tr7zw
*
*/
@SuppressWarnings("javadoc")
public enum ObjectCreator {
NMS_NBTTAGCOMPOUND(null, null, ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()),
NMS_BLOCKPOSITION(null, null, ClassWrapper.NMS_BLOCKPOSITION.getClazz(), int.class, int.class, int.class),
NMS_COMPOUNDFROMITEM(MinecraftVersion.MC1_11_R1, null, ClassWrapper.NMS_ITEMSTACK.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()),;
private Constructor<?> construct;
private Class<?> targetClass;
ObjectCreator(MinecraftVersion from, MinecraftVersion to, Class<?> clazz, Class<?>... args) {
if (clazz == null)
return;
if (from != null && MinecraftVersion.getVersion().getVersionId() < from.getVersionId())
return;
if (to != null && MinecraftVersion.getVersion().getVersionId() > to.getVersionId())
return;
try {
this.targetClass = clazz;
construct = clazz.getDeclaredConstructor(args);
construct.setAccessible(true);
} catch (Exception ex) {
getLogger().log(Level.SEVERE, "Unable to find the constructor for the class '" + clazz.getName() + "'", ex);
}
}
/**
* Creates an Object instance with given args
*
* @param args
* @return Object created
*/
public Object getInstance(Object... args) {
try {
return construct.newInstance(args);
} catch (Exception ex) {
throw new NbtApiException("Exception while creating a new instance of '" + targetClass + "'", ex);
}
}
}
@@ -1,29 +0,0 @@
package de.tr7zw.changeme.nbtapi.utils.nmsmappings;
/**
* Package enum
*
* @author tr7zw
*
*/
@SuppressWarnings("javadoc")
public enum PackageWrapper {
NMS(new String(new byte[] {'n', 'e', 't', '.', 'm', 'i', 'n', 'e', 'c', 'r', 'a', 'f', 't', '.', 's', 'e', 'r', 'v', 'e', 'r'})),
CRAFTBUKKIT(new String(new byte[] {'o', 'r', 'g', '.', 'b', 'u', 'k', 'k', 'i', 't', '.', 'c', 'r', 'a', 'f', 't', 'b', 'u', 'k', 'k', 'i', 't'})),
NONE("")
;
private final String uri;
private PackageWrapper(String uri) {
this.uri = uri;
}
/**
* @return The Uri for that package
*/
public String getUri() {
return uri;
}
}
@@ -1,198 +0,0 @@
package de.tr7zw.changeme.nbtapi.utils.nmsmappings;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import org.bukkit.inventory.ItemStack;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
/**
* This class caches method reflections, keeps track of method name changes between versions and allows early checking for problems
*
* @author tr7zw
*
*/
@SuppressWarnings("javadoc")
public enum ReflectionMethod {
COMPOUND_SET_FLOAT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, float.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setFloat")),
COMPOUND_SET_STRING(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setString")),
COMPOUND_SET_INT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setInt")),
COMPOUND_SET_BYTEARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, byte[].class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setByteArray")),
COMPOUND_SET_INTARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, int[].class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setIntArray")),
COMPOUND_SET_LONG(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, long.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setLong")),
COMPOUND_SET_SHORT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, short.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setShort")),
COMPOUND_SET_BYTE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, byte.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setByte")),
COMPOUND_SET_DOUBLE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, double.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setDouble")),
COMPOUND_SET_BOOLEAN(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, boolean.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setBoolean")),
COMPOUND_SET_UUID(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, UUID.class}, MinecraftVersion.MC1_16_R1, new Since(MinecraftVersion.MC1_16_R1, "a")),
COMPOUND_MERGE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "a")), //FIXME: No Spigot mapping!
COMPOUND_SET(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "set")),
COMPOUND_GET(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "get")),
COMPOUND_GET_LIST(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class, int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getList")),
COMPOUND_OWN_TYPE(ClassWrapper.NMS_NBTBASE.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getTypeId")), // Only needed for 1.7.10 getType
COMPOUND_GET_FLOAT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getFloat")),
COMPOUND_GET_STRING(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getString")),
COMPOUND_GET_INT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getInt")),
COMPOUND_GET_BYTEARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getByteArray")),
COMPOUND_GET_INTARRAY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getIntArray")),
COMPOUND_GET_LONG(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getLong")),
COMPOUND_GET_SHORT(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getShort")),
COMPOUND_GET_BYTE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getByte")),
COMPOUND_GET_DOUBLE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getDouble")),
COMPOUND_GET_BOOLEAN(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getBoolean")),
COMPOUND_GET_UUID(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_16_R1, new Since(MinecraftVersion.MC1_16_R1, "a")),
COMPOUND_GET_COMPOUND(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getCompound")),
NMSITEM_GETTAG(ClassWrapper.NMS_ITEMSTACK.getClazz(), new Class[] {}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getTag")),
NMSITEM_SAVE(ClassWrapper.NMS_ITEMSTACK.getClazz(), new Class[] {ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "save")),
NMSITEM_CREATESTACK(ClassWrapper.NMS_ITEMSTACK.getClazz(), new Class[] {ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_10_R1, new Since(MinecraftVersion.MC1_7_R4, "createStack")),
COMPOUND_REMOVE_KEY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "remove")),
COMPOUND_HAS_KEY(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "hasKey")),
COMPOUND_GET_TYPE(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "b"), new Since(MinecraftVersion.MC1_9_R1, "d"), new Since(MinecraftVersion.MC1_15_R1, "e"), new Since(MinecraftVersion.MC1_16_R1, "d")), //FIXME: No Spigot mapping!
COMPOUND_GET_KEYS(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "c"), new Since(MinecraftVersion.MC1_13_R1, "getKeys")),
LISTCOMPOUND_GET_KEYS(ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "c"), new Since(MinecraftVersion.MC1_13_R1, "getKeys")),
LIST_REMOVE_KEY(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "a"), new Since(MinecraftVersion.MC1_9_R1, "remove")),
LIST_SIZE(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "size")),
LIST_SET(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class, ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "a"), new Since(MinecraftVersion.MC1_13_R1, "set")),
LEGACY_LIST_ADD(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_13_R2, new Since(MinecraftVersion.MC1_7_R4, "add")),
LIST_ADD(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class, ClassWrapper.NMS_NBTBASE.getClazz()}, MinecraftVersion.MC1_14_R1, new Since(MinecraftVersion.MC1_14_R1, "add")),
LIST_GET_STRING(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getString")),
LIST_GET_COMPOUND(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "get")),
LIST_GET(ClassWrapper.NMS_NBTTAGLIST.getClazz(), new Class[]{int.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "get"), new Since(MinecraftVersion.MC1_8_R3, "g"), new Since(MinecraftVersion.MC1_9_R1, "h"), new Since(MinecraftVersion.MC1_12_R1, "i"), new Since(MinecraftVersion.MC1_13_R1, "get")),
ITEMSTACK_SET_TAG(ClassWrapper.NMS_ITEMSTACK.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "setTag")),
ITEMSTACK_NMSCOPY(ClassWrapper.CRAFT_ITEMSTACK.getClazz(), new Class[]{ItemStack.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "asNMSCopy")),
ITEMSTACK_BUKKITMIRROR(ClassWrapper.CRAFT_ITEMSTACK.getClazz(), new Class[]{ClassWrapper.NMS_ITEMSTACK.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "asCraftMirror")),
CRAFT_WORLD_GET_HANDLE(ClassWrapper.CRAFT_WORLD.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getHandle")),
NMS_WORLD_GET_TILEENTITY(ClassWrapper.NMS_WORLDSERVER.getClazz(), new Class[]{ClassWrapper.NMS_BLOCKPOSITION.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "getTileEntity")),
NMS_WORLD_SET_TILEENTITY(ClassWrapper.NMS_WORLDSERVER.getClazz(), new Class[]{ClassWrapper.NMS_BLOCKPOSITION.getClazz(), ClassWrapper.NMS_TILEENTITY.getClazz()}, MinecraftVersion.MC1_8_R3, MinecraftVersion.MC1_16_R3, new Since(MinecraftVersion.MC1_8_R3, "setTileEntity")),
NMS_WORLD_REMOVE_TILEENTITY(ClassWrapper.NMS_WORLDSERVER.getClazz(), new Class[]{ClassWrapper.NMS_BLOCKPOSITION.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "t"), new Since(MinecraftVersion.MC1_9_R1, "s"), new Since(MinecraftVersion.MC1_13_R1, "n"), new Since(MinecraftVersion.MC1_14_R1, "removeTileEntity")),
NMS_WORLD_GET_TILEENTITY_1_7_10(ClassWrapper.NMS_WORLDSERVER.getClazz(), new Class[]{int.class, int.class, int.class}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getTileEntity")),
TILEENTITY_LOAD_LEGACY191(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_MINECRAFTSERVER.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_9_R1, MinecraftVersion.MC1_9_R1, new Since(MinecraftVersion.MC1_9_R1, "a")), //FIXME: No Spigot mapping!
TILEENTITY_LOAD_LEGACY183(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_8_R3, MinecraftVersion.MC1_9_R2, new Since(MinecraftVersion.MC1_8_R3, "c"), new Since(MinecraftVersion.MC1_9_R1, "a"), new Since(MinecraftVersion.MC1_9_R2, "c")), //FIXME: No Spigot mapping!
TILEENTITY_LOAD_LEGACY1121(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_WORLD.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_10_R1, MinecraftVersion.MC1_12_R1, new Since(MinecraftVersion.MC1_10_R1, "a"), new Since(MinecraftVersion.MC1_12_R1, "create")),
TILEENTITY_LOAD_LEGACY1151(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_13_R1, MinecraftVersion.MC1_15_R1, new Since(MinecraftVersion.MC1_12_R1, "create")),
TILEENTITY_LOAD(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_IBLOCKDATA.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_16_R1, MinecraftVersion.MC1_16_R3, new Since(MinecraftVersion.MC1_16_R1, "create")),
TILEENTITY_GET_NBT(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "b"), new Since(MinecraftVersion.MC1_9_R1, "save")),
TILEENTITY_SET_NBT_LEGACY1151(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, MinecraftVersion.MC1_15_R1, new Since(MinecraftVersion.MC1_7_R4, "a"), new Since(MinecraftVersion.MC1_12_R1, "load")),
TILEENTITY_SET_NBT_LEGACY1161(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_IBLOCKDATA.getClazz(), ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_16_R1, MinecraftVersion.MC1_16_R3, new Since(MinecraftVersion.MC1_16_R1, "load")),
TILEENTITY_SET_NBT(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_17_R1, new Since(MinecraftVersion.MC1_16_R1, "load")),
TILEENTITY_GET_BLOCKDATA(ClassWrapper.NMS_TILEENTITY.getClazz(), new Class[]{}, MinecraftVersion.MC1_16_R1, new Since(MinecraftVersion.MC1_16_R1, "getBlock")),
CRAFT_ENTITY_GET_HANDLE(ClassWrapper.CRAFT_ENTITY.getClazz(), new Class[]{}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "getHandle")),
NMS_ENTITY_SET_NBT(ClassWrapper.NMS_ENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "f"), new Since(MinecraftVersion.MC1_16_R1, "load")), //FIXME: No Spigot mapping!
NMS_ENTITY_GET_NBT(ClassWrapper.NMS_ENTITY.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "e"), new Since(MinecraftVersion.MC1_12_R1, "save")),
NMS_ENTITY_GETSAVEID(ClassWrapper.NMS_ENTITY.getClazz(), new Class[]{}, MinecraftVersion.MC1_14_R1,new Since(MinecraftVersion.MC1_14_R1, "getSaveID")),
NBTFILE_READ(ClassWrapper.NMS_NBTCOMPRESSEDSTREAMTOOLS.getClazz(), new Class[]{InputStream.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a")), //FIXME: No Spigot mapping!
NBTFILE_WRITE(ClassWrapper.NMS_NBTCOMPRESSEDSTREAMTOOLS.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), OutputStream.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "a")), //FIXME: No Spigot mapping!
PARSE_NBT(ClassWrapper.NMS_MOJANGSONPARSER.getClazz(), new Class[]{String.class}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "parse")),
REGISTRY_KEYSET (ClassWrapper.NMS_REGISTRYSIMPLE.getClazz(), new Class[]{}, MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_11_R1, "keySet")),
REGISTRY_GET (ClassWrapper.NMS_REGISTRYSIMPLE.getClazz(), new Class[]{Object.class}, MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_11_R1, "get")),
REGISTRY_SET (ClassWrapper.NMS_REGISTRYSIMPLE.getClazz(), new Class[]{Object.class, Object.class}, MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_11_R1, "a")), //FIXME: No Spigot mapping!
REGISTRY_GET_INVERSE (ClassWrapper.NMS_REGISTRYMATERIALS.getClazz(), new Class[]{Object.class}, MinecraftVersion.MC1_11_R1, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_11_R1, "b")), //FIXME: No Spigot mapping!
REGISTRYMATERIALS_KEYSET (ClassWrapper.NMS_REGISTRYMATERIALS.getClazz(), new Class[]{}, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_13_R1, "keySet")),
REGISTRYMATERIALS_GET (ClassWrapper.NMS_REGISTRYMATERIALS.getClazz(), new Class[]{ClassWrapper.NMS_MINECRAFTKEY.getClazz()}, MinecraftVersion.MC1_13_R1, new Since(MinecraftVersion.MC1_13_R1, "get")),
REGISTRYMATERIALS_GETKEY (ClassWrapper.NMS_REGISTRYMATERIALS.getClazz(), new Class[]{Object.class}, MinecraftVersion.MC1_13_R2, new Since(MinecraftVersion.MC1_13_R2, "getKey")),
GAMEPROFILE_DESERIALIZE (ClassWrapper.NMS_GAMEPROFILESERIALIZER.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_7_R4, new Since(MinecraftVersion.MC1_7_R4, "deserialize")),
GAMEPROFILE_SERIALIZE (ClassWrapper.NMS_GAMEPROFILESERIALIZER.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz(), ClassWrapper.GAMEPROFILE.getClazz()}, MinecraftVersion.MC1_8_R3, new Since(MinecraftVersion.MC1_8_R3, "serialize")),
CRAFT_PERSISTENT_DATA_CONTAINER_TO_TAG (ClassWrapper.CRAFT_PERSISTENTDATACONTAINER.getClazz(), new Class[]{}, MinecraftVersion.MC1_14_R1, new Since(MinecraftVersion.MC1_14_R1, "toTagCompound")),
CRAFT_PERSISTENT_DATA_CONTAINER_GET_MAP (ClassWrapper.CRAFT_PERSISTENTDATACONTAINER.getClazz(), new Class[]{}, MinecraftVersion.MC1_14_R1, new Since(MinecraftVersion.MC1_14_R1, "getRaw")),
CRAFT_PERSISTENT_DATA_CONTAINER_PUT_ALL (ClassWrapper.CRAFT_PERSISTENTDATACONTAINER.getClazz(), new Class[]{ClassWrapper.NMS_NBTTAGCOMPOUND.getClazz()}, MinecraftVersion.MC1_14_R1, new Since(MinecraftVersion.MC1_14_R1, "putAll")),
;
private MinecraftVersion removedAfter;
private Since targetVersion;
private Method method;
private boolean loaded = false;
private boolean compatible = false;
private String methodName = null;
ReflectionMethod(Class<?> targetClass, Class<?>[] args, MinecraftVersion addedSince, MinecraftVersion removedAfter, Since... methodnames){
this.removedAfter = removedAfter;
if(!MinecraftVersion.isAtLeastVersion(addedSince) || (this.removedAfter != null && MinecraftVersion.isNewerThan(removedAfter)))return;
compatible = true;
MinecraftVersion server = MinecraftVersion.getVersion();
Since target = methodnames[0];
for(Since s : methodnames){
if(s.version.getVersionId() <= server.getVersionId() && target.version.getVersionId() < s.version.getVersionId())
target = s;
}
targetVersion = target;
try{
method = targetClass.getMethod(targetVersion.name, args);
method.setAccessible(true);
loaded = true;
methodName = targetVersion.name;
}catch(NullPointerException | NoSuchMethodException | SecurityException ex){
System.out.println("[NBTAPI] Unable to find the method '" + targetVersion.name + "' in '" + (targetClass == null ? "null" : targetClass.getSimpleName()) + "' Enum: " + this); //NOSONAR This gets loaded before the logger is loaded
}
}
ReflectionMethod(Class<?> targetClass, Class<?>[] args, MinecraftVersion addedSince, Since... methodnames){
this(targetClass, args, addedSince, null, methodnames);
}
/**
* Runs the method on a given target object using the given args.
*
* @param target
* @param args
* @return Value returned by the method
*/
public Object run(Object target, Object... args){
if(method == null)
throw new NbtApiException("Method not loaded! '" + this + "'");
try{
return method.invoke(target, args);
}catch(Exception ex){
throw new NbtApiException("Error while calling the method '" + methodName + "', loaded: " + loaded + ", Enum: " + this, ex);
}
}
/**
* @return The MethodName, used in this Minecraft Version
*/
public String getMethodName() {
return methodName;
}
/**
* @return Has this method been linked
*/
public boolean isLoaded() {
return loaded;
}
/**
* @return Is this method available in this Minecraft Version
*/
public boolean isCompatible() {
return compatible;
}
protected static class Since{
public final MinecraftVersion version;
public final String name;
public Since(MinecraftVersion version, String name) {
this.version = version;
this.name = name;
}
}
}
-21
View File
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 - 2021, tr7zw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-115
View File
@@ -1,115 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-parent</artifactId>
<version>2.8.1-SNAPSHOT</version>
</parent>
<artifactId>item-nbt-api-plugin</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-api</artifactId>
<version>2.8.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>de.tr7zw</groupId>
<artifactId>nbt-injector</artifactId>
<version>2.8.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>de.tr7zw</groupId>
<artifactId>nbt-data-api</artifactId>
<version>2.8.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<relocations>
<relocation>
<pattern>de.tr7zw.changeme.nbtapi</pattern>
<shadedPattern>de.tr7zw.nbtapi</shadedPattern>
</relocation>
<relocation>
<pattern>javassist</pattern>
<shadedPattern>de.tr7zw.nbtinjector.javassist</shadedPattern>
</relocation>
<relocation>
<pattern>de.tr7zw.annotations</pattern>
<shadedPattern>de.tr7zw.nbtapi.utils.annotations</shadedPattern>
</relocation>
</relocations>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>LICENSE</resource>
</transformer>
</transformers>
</configuration>
<executions>
<execution>
<id>shade</id>
<goals>
<goal>shade</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
<!-- Start and Stop a SpigotMC server automatically before and after the integration-test phase. -->
<plugin>
<groupId>de.tr7zw.spigotmc.maven</groupId>
<artifactId>tr-spigotmc-maven-plugin</artifactId>
<version>0.0.3-SNAPSHOT</version>
<configuration>
<!-- 1.8.8-R0.1-SNAPSHOT-latest, 1.9.2-R0.1-SNAPSHOT-latest, 1.9.4-R0.1-SNAPSHOT-latest, 1.10.2-R0.1-SNAPSHOT-latest,1.11.2,1.12.2,1.13.2,1.14.4,1.15.1,1.16.1,1.16.2 -->
<versions>
https://repo.codemc.io/repository/nms/org/spigotmc/spigot/1.8.8-R0.1-SNAPSHOT/spigot-1.8.8-R0.1-20190527.160303-7.jar,
https://repo.codemc.io/repository/nms/org/spigotmc/spigot/1.9.4-R0.1-SNAPSHOT/spigot-1.9.4-R0.1-20190527.160755-2.jar,
https://repo.codemc.io/repository/nms/org/spigotmc/spigot/1.10.2-R0.1-SNAPSHOT/spigot-1.10.2-R0.1-20190527.154910-2.jar,
https://repo.codemc.io/repository/nms/org/spigotmc/spigot/1.11.2-R0.1-SNAPSHOT/spigot-1.11.2-R0.1-20191216.091129-1.jar,
https://repo.codemc.io/repository/nms/org/spigotmc/spigot/1.12.2-R0.1-SNAPSHOT/spigot-1.12.2-R0.1-20190527.155359-34.jar,
<!--https://repo.codemc.io/repository/nms/org/spigotmc/spigot/1.13.2-R0.1-SNAPSHOT/spigot-1.13.2-R0.1-20191113.201242-53.jar,-->
https://repo.codemc.io/repository/nms/org/spigotmc/spigot/1.14.4-R0.1-SNAPSHOT/spigot-1.14.4-R0.1-20191224.232152-15.jar,
https://repo.codemc.io/repository/nms/org/spigotmc/spigot/1.15.2-R0.1-SNAPSHOT/spigot-1.15.2-R0.1-20200625.172449-18.jar,
https://repo.codemc.io/repository/nms/org/spigotmc/spigot/1.16.5-R0.1-SNAPSHOT/spigot-1.16.5-R0.1-20210611.090701-17.jar
</versions>
<works>Success! This version of NBT-API</works>
<error>WARNING! This version of NBT-API</error>
<filename>item-nbt-api-plugin-${project.version}.jar</filename>
<foldername>item-nbt-plugin</foldername>
</configuration>
<executions>
<execution>
<id>start-server</id>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-server</id>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
@@ -1,223 +0,0 @@
package de.tr7zw.nbtapi.plugin;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ClassWrapper;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
import de.tr7zw.nbtapi.plugin.tests.GameprofileTest;
import de.tr7zw.nbtapi.plugin.tests.NBTFileTest;
import de.tr7zw.nbtapi.plugin.tests.blocks.BlockNBTTest;
import de.tr7zw.nbtapi.plugin.tests.chunks.ChunkNBTPersistentTest;
import de.tr7zw.nbtapi.plugin.tests.compounds.EqualsTest;
import de.tr7zw.nbtapi.plugin.tests.compounds.ForEachTest;
import de.tr7zw.nbtapi.plugin.tests.compounds.GetterSetterTest;
import de.tr7zw.nbtapi.plugin.tests.compounds.IteratorTest;
import de.tr7zw.nbtapi.plugin.tests.compounds.ListTest;
import de.tr7zw.nbtapi.plugin.tests.compounds.MergeTest;
import de.tr7zw.nbtapi.plugin.tests.compounds.RemovingKeys;
import de.tr7zw.nbtapi.plugin.tests.compounds.StreamTest;
import de.tr7zw.nbtapi.plugin.tests.compounds.SubCompoundsTest;
import de.tr7zw.nbtapi.plugin.tests.compounds.TypeTest;
import de.tr7zw.nbtapi.plugin.tests.data.WorldDataTest;
import de.tr7zw.nbtapi.plugin.tests.entities.EntityCustomNbtPersistentTest;
import de.tr7zw.nbtapi.plugin.tests.entities.EntityTest;
import de.tr7zw.nbtapi.plugin.tests.injector.EntityCustomNbtInjectorTest;
import de.tr7zw.nbtapi.plugin.tests.injector.MergeTileSubCompoundTest;
import de.tr7zw.nbtapi.plugin.tests.injector.SpawnEntityCustomNbtInjectorTest;
import de.tr7zw.nbtapi.plugin.tests.injector.TilesCustomNBTInjectorTest;
import de.tr7zw.nbtapi.plugin.tests.items.DirectApplyTest;
import de.tr7zw.nbtapi.plugin.tests.items.EmptyItemTest;
import de.tr7zw.nbtapi.plugin.tests.items.ItemConvertionTest;
import de.tr7zw.nbtapi.plugin.tests.tiles.TileTest;
import de.tr7zw.nbtapi.plugin.tests.tiles.TilesCustomNBTPersistentTest;
import de.tr7zw.nbtinjector.NBTInjector;
import de.tr7zw.nbtapi.plugin.tests.items.ItemMergingTest;
public class NBTAPI extends JavaPlugin {
private boolean compatible = true;
private ArrayList<de.tr7zw.nbtapi.plugin.tests.Test> apiTests = new ArrayList<>();
private static NBTAPI instance;
public static NBTAPI getInstance() {
return instance;
}
@Override
public void onLoad() {
getConfig().options().copyDefaults(true);
getConfig().addDefault("nbtInjector.enabled", false);
getConfig().addDefault("bStats.enabled", true);
getConfig().addDefault("updateCheck.enabled", true);
saveConfig();
if(!getConfig().getBoolean("bStats.enabled")) {
getLogger().info("bStats disabled");
MinecraftVersion.disableBStats();
}
if(!getConfig().getBoolean("updateCheck.enabled")) {
getLogger().info("Update check disabled");
MinecraftVersion.disableUpdateCheck();
}
//Disabled by default since 2.1. Enable it yourself by calling NBTInjector.inject(); during onLoad/config
if(getConfig().getBoolean("nbtInjector.enabled")) {
getLogger().info("Injecting custom NBT");
try {
NBTInjector.inject();
getLogger().info("Injected!");
} catch (Throwable ex) { // NOSONAR
getLogger().log(Level.SEVERE, "Error while Injecting custom Tile/Entity classes!", ex);
compatible = false;
}
}
// NBTCompounds
apiTests.add(new GetterSetterTest());
apiTests.add(new TypeTest());
apiTests.add(new RemovingKeys());
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_8_R3)) // 1.7.10 list support is not complete at all
apiTests.add(new ListTest());
apiTests.add(new SubCompoundsTest());
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_8_R3)) // 1.7.10 not a thing
apiTests.add(new MergeTest());
apiTests.add(new ForEachTest());
apiTests.add(new StreamTest());
apiTests.add(new EqualsTest());
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_8_R3)) // 1.7.10 list support is not complete at all
apiTests.add(new IteratorTest());
// Items
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_8_R3)) // 1.7.10 not a thing
apiTests.add(new ItemConvertionTest());
apiTests.add(new EmptyItemTest());
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_8_R3)) { // 1.7.10 not a thing
apiTests.add(new ItemMergingTest());
apiTests.add(new DirectApplyTest());
}
// Entity
apiTests.add(new EntityTest());
apiTests.add(new EntityCustomNbtPersistentTest());
// Tiles
apiTests.add(new TileTest());
apiTests.add(new TilesCustomNBTPersistentTest());
// Chunks
apiTests.add(new ChunkNBTPersistentTest());
// Blocks
apiTests.add(new BlockNBTTest());
// Files
apiTests.add(new NBTFileTest());
// Data
apiTests.add(new WorldDataTest());
// Injector
apiTests.add(new TilesCustomNBTInjectorTest());
apiTests.add(new MergeTileSubCompoundTest());
apiTests.add(new EntityCustomNbtInjectorTest());
apiTests.add(new SpawnEntityCustomNbtInjectorTest());
if(MinecraftVersion.isAtLeastVersion(MinecraftVersion.MC1_8_R3))
apiTests.add(new GameprofileTest());
}
@Override
public void onEnable() {
instance = this; // NOSONAR
// new MetricsLite(this); The metrics moved into the API
getLogger().info("Adding listeners...");
Bukkit.getPluginManager().registerEvents(new ReloadListener(), this);
getLogger().info("Gson:");
MinecraftVersion.hasGsonSupport();
getLogger().info("Checking bindings...");
MinecraftVersion.getVersion();
boolean classUnlinked = false;
for (ClassWrapper c : ClassWrapper.values()) {
if (c.isEnabled() && c.getClazz() == null) {
if(!classUnlinked)
getLogger().info("Classes:");
getLogger().warning(c.name() + " did not find it's class!");
compatible = false;
classUnlinked = true;
}
}
if (!classUnlinked)
getLogger().info("All Classes were able to link!");
boolean methodUnlinked = false;
for (ReflectionMethod method : ReflectionMethod.values()) {
if (method.isCompatible() && !method.isLoaded()) {
if(!methodUnlinked)
getLogger().info("Methods:");
getLogger().warning(method.name() + " did not find the method!");
compatible = false;
methodUnlinked = true;
}
}
if (!methodUnlinked)
getLogger().info("All Methods were able to link!");
getLogger().info("Running NBT reflection test...");
Map<de.tr7zw.nbtapi.plugin.tests.Test, Exception> results = new HashMap<>();
for (de.tr7zw.nbtapi.plugin.tests.Test test : apiTests) {
try {
test.test();
results.put(test, null);
} catch (Exception ex) {
results.put(test, ex);
getLogger().log(Level.WARNING, "Error during '" + test.getClass().getSimpleName() + "' test!", ex);
} catch (NoSuchFieldError th) { // NOSONAR
getLogger().log(Level.SEVERE, "Servere error during '" + test.getClass().getSimpleName() + "' test!");
getLogger().warning(
"WARNING! This version of Item-NBT-API seems to be broken with your Spigot version! Canceled the other tests!");
throw th;
}
}
for (Entry<de.tr7zw.nbtapi.plugin.tests.Test, Exception> entry : results.entrySet()) {
if (entry.getValue() != null)
compatible = false;
getLogger().info(entry.getKey().getClass().getSimpleName() + ": "
+ (entry.getValue() == null ? "Ok" : entry.getValue().getMessage()));
}
String checkMessage = "Plugins that don't check properly may throw Exeptions, crash or have unexpected behaviors!";
if (compatible) {
getLogger().info("Success! This version of NBT-API is compatible with your server.");
} else {
getLogger().warning(
"WARNING! This version of NBT-API seems to be broken with your Spigot version! " + checkMessage);
if(MinecraftVersion.getVersion() == MinecraftVersion.MC1_7_R4) {
getLogger().warning("1.7.10 is only partally supported! Some thing will not work/are not yet avaliable in 1.7.10!");
}
}
}
/**
* @return True if all selfchecks succeeded
*/
public boolean isCompatible() {
return compatible;
}
}
@@ -1,42 +0,0 @@
package de.tr7zw.nbtapi.plugin;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import de.tr7zw.nbtinjector.NBTInjector;
/**
* This listener class tries to prevent people from reloading while the NBTInjector is enabled.
*
* @author tr7zw
*
*/
public class ReloadListener implements Listener{
/**
* Console handler
*
* @param event
*/
@EventHandler
public void onCommand(org.bukkit.event.server.ServerCommandEvent event) {
if(event.getCommand().toLowerCase().startsWith("reload") && NBTInjector.isInjected()) {
event.setCancelled(true);
event.getSender().sendMessage("[NBTAPI] The NBTInjector is currently enabled. Reloading will turn the server into an unstable state and data-loss may accure. Please do a clean restart. Canceled reload!");
}
}
/**
* Player handler
*
* @param event
*/
@EventHandler
public void onCommand(org.bukkit.event.player.PlayerCommandPreprocessEvent event) {
if(event.getMessage().toLowerCase().startsWith("/reload") && NBTInjector.isInjected()) {
event.setCancelled(true);
event.getPlayer().sendMessage("[NBTAPI] The NBTInjector is currently enabled. Reloading will turn the server into an unstable state and data-loss may accure. Please do a clean restart. Canceled reload!");
}
}
}
@@ -1,24 +0,0 @@
package de.tr7zw.nbtapi.plugin.tests.data;
import java.io.File;
import org.bukkit.Bukkit;
import org.bukkit.World;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import de.tr7zw.changeme.nbtapi.data.NBTData;
import de.tr7zw.changeme.nbtapi.data.WorldData;
import de.tr7zw.nbtapi.plugin.tests.Test;
public class WorldDataTest implements Test{
@Override
public void test() throws Exception {
for(World world : Bukkit.getWorlds()){
if(!new File(world.getWorldFolder(), "level.dat").exists())continue;
WorldData data = NBTData.getWorldData(world);
if(data.getWorldName() == null || data.getSpawnPosition() == null)throw new NbtApiException("Got Null");
}
}
}
@@ -1,41 +0,0 @@
package de.tr7zw.nbtapi.plugin.tests.injector;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.entity.Animals;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Monster;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTEntity;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import de.tr7zw.nbtapi.plugin.tests.Test;
import de.tr7zw.nbtinjector.NBTInjector;
public class EntityCustomNbtInjectorTest implements Test {
@Override
public void test() throws Exception {
if(!NBTInjector.isInjected())return;
if (!Bukkit.getWorlds().isEmpty()) {
World world = Bukkit.getWorlds().get(0);
try {
if (!world.getEntitiesByClasses(Animals.class, Monster.class).isEmpty()) {
Entity ent = world.getEntitiesByClasses(Animals.class, Monster.class).iterator().next();
ent = NBTInjector.patchEntity(ent);
NBTCompound comp = NBTInjector.getNbtData(ent);
comp.setString("Hello", "World");
NBTEntity nbtent = new NBTEntity(ent);
if (!nbtent.toString().contains("__extraData:{Hello:\"World\"}")) {
throw new NbtApiException("Custom Data did not save to the Entity!");
}
comp.removeKey("Hello");
}
} catch (Exception ex) {
throw new NbtApiException("Wasn't able to use NBTEntities!", ex);
}
}
}
}
@@ -1,46 +0,0 @@
package de.tr7zw.nbtapi.plugin.tests.injector;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTContainer;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import de.tr7zw.nbtapi.plugin.tests.Test;
import de.tr7zw.nbtinjector.NBTInjector;
public class MergeTileSubCompoundTest implements Test {
@Override
public void test() throws Exception {
if (!NBTInjector.isInjected())
return;
if (!Bukkit.getWorlds().isEmpty()) {
World world = Bukkit.getWorlds().get(0);
try {
boolean failed = false;
Block block = world.getBlockAt(world.getSpawnLocation().getBlockX(), 255,
world.getSpawnLocation().getBlockZ());
if (block.getType() == Material.AIR) {
block.setType(Material.CHEST);
NBTCompound comp = NBTInjector.getNbtData(block.getState());
comp.addCompound("subcomp").setString("hello", "world");
NBTContainer cont = new NBTContainer();
cont.mergeCompound(comp.getCompound("subcomp"));
if (!(cont.hasKey("hello") && "world".equals(cont.getString("hello")))) {
failed = true;
}
block.setType(Material.AIR);
if(failed) {
throw new NbtApiException("Data was not correct! " + cont);
}
}
} catch (Exception ex) {
throw new NbtApiException("Wasn't able to use NBTTiles!", ex);
}
}
}
}
@@ -1,41 +0,0 @@
package de.tr7zw.nbtapi.plugin.tests.injector;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTEntity;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import de.tr7zw.nbtapi.plugin.tests.Test;
import de.tr7zw.nbtinjector.NBTInjector;
public class SpawnEntityCustomNbtInjectorTest implements Test {
@Override
public void test() throws Exception {
if (!NBTInjector.isInjected())
return;
if (!Bukkit.getWorlds().isEmpty()) {
World world = Bukkit.getWorlds().get(0);
try {
Entity entity = world.spawnEntity(new Location(world, 0, 0, 0), EntityType.ARMOR_STAND);
entity = NBTInjector.patchEntity(entity);
NBTCompound comp = NBTInjector.getNbtData(entity);
comp.setString("Hello", "World");
NBTEntity nbtent = new NBTEntity(entity);
if (!nbtent.toString().contains("__extraData:{Hello:\"World\"}")) {
throw new NbtApiException("Custom Data did not save to the Entity!");
}
comp.removeKey("Hello");
entity.remove();
} catch (Exception ex) {
throw new NbtApiException("Wasn't able to use NBTEntities!", ex);
}
}
}
}
@@ -1,40 +0,0 @@
package de.tr7zw.nbtapi.plugin.tests.injector;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTTileEntity;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import de.tr7zw.nbtapi.plugin.tests.Test;
import de.tr7zw.nbtinjector.NBTInjector;
public class TilesCustomNBTInjectorTest implements Test {
@Override
public void test() throws Exception {
if(!NBTInjector.isInjected())return;
if (!Bukkit.getWorlds().isEmpty()) {
World world = Bukkit.getWorlds().get(0);
try {
Block block = world.getBlockAt(world.getSpawnLocation().getBlockX(), 255,
world.getSpawnLocation().getBlockZ());
if (block.getType() == Material.AIR) {
block.setType(Material.CHEST);
NBTCompound comp = NBTInjector.getNbtData(block.getState());
comp.setString("Foo", "Bar");
if (!new NBTTileEntity(block.getState()).toString().contains("__extraData:{Foo:\"Bar\"}")) {
block.setType(Material.AIR);
throw new NbtApiException("Custom Data did not save to the Tile!");
}
block.setType(Material.AIR);
}
} catch (Exception ex) {
throw new NbtApiException("Wasn't able to use NBTTiles!", ex);
}
}
}
}
-21
View File
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 - 2021, tr7zw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-21
View File
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 - 2021, tr7zw
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-28
View File
@@ -1,28 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-parent</artifactId>
<version>2.8.1-SNAPSHOT</version>
</parent>
<artifactId>nbt-injector</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-api</artifactId>
<version>2.8.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.28.0-GA</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>clean install javadoc:javadoc</defaultGoal>
</build>
</project>
-165
View File
@@ -1,165 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-parent</artifactId>
<version>2.8.1-SNAPSHOT</version>
<packaging>pom</packaging>
<inceptionYear>2015</inceptionYear>
<organization>
<name>tr7zw</name>
<url>https://github.com/tr7zw/</url>
</organization>
<licenses>
<license>
<name>MIT License</name>
<url>https://opensource.org/licenses/mit-license.php</url>
<distribution>repo</distribution>
</license>
</licenses>
<modules>
<module>item-nbt-api</module>
<module>nbt-injector</module>
<module>nbt-data-api</module>
<module>item-nbt-plugin</module>
</modules>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.spigotmc</groupId>
<artifactId>spigot-api</artifactId>
<version>1.16.4-R0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>de.tr7zw.spigotmc.maven</groupId>
<artifactId>tr-spigotmc-maven-plugin</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.mojang</groupId>
<artifactId>authlib</artifactId>
<version>1.5.25</version>
<scope>provided</scope>
</dependency>
</dependencies>
<repositories>
<!-- CodeMC -->
<repository>
<id>codemc-repo</id>
<url>https://repo.codemc.org/repository/maven-public/</url>
<layout>default</layout>
</repository>
<!-- CodeMC NMS -->
<repository>
<id>codemc-nms-repo</id>
<url>https://repo.codemc.org/repository/nms/</url>
<layout>default</layout>
</repository>
<!-- Mojang -->
<repository>
<id>mojang-libraries</id>
<url>https://libraries.minecraft.net/</url>
<layout>default</layout>
</repository>
</repositories>
<pluginRepositories>
<!-- CodeMC -->
<pluginRepository>
<id>codemc-repo</id>
<url>https://repo.codemc.org/repository/maven-public/</url>
<layout>default</layout>
</pluginRepository>
</pluginRepositories>
<build>
<defaultGoal>clean install</defaultGoal>
<resources>
<resource>
<filtering>false</filtering>
<directory>.</directory>
<includes>
<include>LICENSE</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<source>8</source>
</configuration>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.github.ekryd.sortpom</groupId>
<artifactId>sortpom-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>sortpom</id>
<goals>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>de.tr7zw</groupId>
<artifactId>allcontributors</artifactId>
<version>0.0.1-SNAPSHOT</version>
<executions>
<execution>
<id>update-contributors</id>
<goals>
<goal>update</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>license-maven-plugin</artifactId>
<version>2.0.0</version>
<configuration>
<licenseName>mit</licenseName>
<licenseFile>LICENSE</licenseFile>
<force>true</force>
</configuration>
</plugin>
</plugins>
</build>
</project>
+36
View File
@@ -0,0 +1,36 @@
pluginManagement {
repositories {
maven {
name = 'Fabric'
url = 'https://maven.fabricmc.net/'
}
gradlePluginPortal()
mavenCentral()
}
}
// Core
include 'nbt-api'
project(':nbt-api').projectDir = file('core/nbt-api')
// Spigot
def spigotProjects = ['nbt-api-spigot', 'nbt-api-plugin', 'item-nbt-api-legacy']
spigotProjects.forEach {
include it
project(":$it").projectDir = file("spigot/$it")
}
// Fabric
def fabricProjects = ['fabric1-17']
fabricProjects.forEach {
include it
project(":$it").projectDir = file("fabric/$it")
}
// Forge
def forgeProjects = ['forge1-17']
forgeProjects.forEach {
include it
project(":$it").projectDir = file("forge/$it")
}
+12
View File
@@ -0,0 +1,12 @@
plugins {
id 'java-library'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
implementation 'de.tr7zw:functional-annotations:0.1-SNAPSHOT'
implementation 'com.mojang:authlib:' + authlib_version
compileOnly 'org.spigotmc:spigot-api:' + spigot_api
}
@@ -1,63 +1,63 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>de.tr7zw</groupId>
<artifactId>item-nbt-parent</artifactId>
<version>2.8.1-SNAPSHOT</version>
</parent>
<artifactId>item-nbt-api</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>de.tr7zw</groupId>
<artifactId>functional-annotations</artifactId>
<version>0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>clean install javadoc:javadoc</defaultGoal>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<relocations>
<relocation>
<pattern>de.tr7zw.annotations</pattern>
<shadedPattern>de.tr7zw.changeme.nbtapi.utils.annotations</shadedPattern>
</relocation>
</relocations>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>LICENSE</resource>
</transformer>
</transformers>
</configuration>
<executions>
<execution>
<id>shade</id>
<goals>
<goal>shade</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>dev.tr7zw</groupId>
<artifactId>nbt-api-parent</artifactId>
<version>3.0.0-SNAPSHOT</version>
</parent>
<artifactId>item-nbt-api-legacy</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>de.tr7zw</groupId>
<artifactId>functional-annotations</artifactId>
<version>0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<defaultGoal>clean install javadoc:javadoc</defaultGoal>
<resources>
<resource>
<filtering>true</filtering>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<relocations>
<relocation>
<pattern>de.tr7zw.annotations</pattern>
<shadedPattern>de.tr7zw.changeme.nbtapi.utils.annotations</shadedPattern>
</relocation>
</relocations>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
<resource>LICENSE</resource>
</transformer>
</transformers>
</configuration>
<executions>
<execution>
<id>shade</id>
<goals>
<goal>shade</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
+3
View File
@@ -0,0 +1,3 @@
# Item-NBT-API Legacy
This module provides a bridge for plugins using the 2.x API to use the 3.x API without any changes.
@@ -0,0 +1 @@
rootProject.name = 'nbt-api-legacy'
@@ -1,9 +1,10 @@
package de.tr7zw.changeme.nbtapi;
package de.tr7zw.nbtapi;
import org.bukkit.block.Block;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import de.tr7zw.nbtapi.utils.MinecraftVersion;
@Deprecated
public class NBTBlock {
private final Block block;
@@ -1,18 +1,19 @@
package de.tr7zw.changeme.nbtapi;
package de.tr7zw.nbtapi;
import org.apache.commons.lang.NotImplementedException;
import org.bukkit.Chunk;
import de.tr7zw.annotations.FAUtil;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import de.tr7zw.changeme.nbtapi.utils.annotations.AvailableSince;
import de.tr7zw.changeme.nbtapi.utils.annotations.CheckUtil;
import de.tr7zw.nbtapi.utils.MinecraftVersion;
import de.tr7zw.nbtapi.utils.annotations.AvailableSince;
import de.tr7zw.nbtapi.utils.annotations.CheckUtil;
@Deprecated
public class NBTChunk {
private final Chunk chunk;
public NBTChunk(Chunk chunk) {
this.chunk = chunk;
throw new NotImplementedException();
}
/**
@@ -24,7 +25,7 @@ public class NBTChunk {
@AvailableSince(version = MinecraftVersion.MC1_16_R3)
public NBTCompound getPersistentDataContainer() {
FAUtil.check(this::getPersistentDataContainer, CheckUtil::isAvaliable);
return new NBTPersistentDataContainer(chunk.getPersistentDataContainer());
throw new NotImplementedException();
}
}
@@ -0,0 +1,495 @@
package de.tr7zw.nbtapi;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Set;
import java.util.UUID;
import org.apache.commons.lang.NotImplementedException;
import org.bukkit.inventory.ItemStack;
/**
* Base class representing NMS Compounds. For a standalone implementation check
* {@link NBTContainer}
*
* @author tr7zw
*
*/
@Deprecated
public class NBTCompound {
protected NBTCompound(NBTCompound owner, String name) {
throw new NotImplementedException();
}
protected void saveCompound() {
throw new NotImplementedException();
}
/**
* @return The Compound name
*/
public String getName() {
throw new NotImplementedException();
}
/**
* @return The NMS Compound behind this Object
*/
public Object getCompound() {
throw new NotImplementedException();
}
protected void setCompound(Object compound) {
throw new NotImplementedException();
}
/**
* @return The parent Compound
*/
public NBTCompound getParent() {
throw new NotImplementedException();
}
/**
* Merges all data from comp into this compound. This is done in one action, so
* it also works with Tiles/Entities
*
* @param comp
*/
public void mergeCompound(NBTCompound comp) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setString(String key, String value) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public String getString(String key) {
throw new NotImplementedException();
}
protected String getContent(String key) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setInteger(String key, Integer value) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Integer getInteger(String key) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setDouble(String key, Double value) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Double getDouble(String key) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setByte(String key, Byte value) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Byte getByte(String key) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setShort(String key, Short value) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Short getShort(String key) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setLong(String key, Long value) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Long getLong(String key) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setFloat(String key, Float value) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Float getFloat(String key) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setByteArray(String key, byte[] value) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public byte[] getByteArray(String key) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setIntArray(String key, int[] value) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public int[] getIntArray(String key) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setBoolean(String key, Boolean value) {
throw new NotImplementedException();
}
protected void set(String key, Object val) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public Boolean getBoolean(String key) {
throw new NotImplementedException();
}
/**
* Uses Gson to store an {@link Serializable} Object
*
* @param key
* @param value
*/
public void setObject(String key, Object value) {
throw new NotImplementedException();
}
/**
* Uses Gson to retrieve a stored Object
*
* @param key
* @param type Class of the Object
* @return The created Object or null if empty
*/
public <T> T getObject(String key, Class<T> type) {
throw new NotImplementedException();
}
/**
* Save an ItemStack as a compound under a given key
*
* @param key
* @param item
*/
public void setItemStack(String key, ItemStack item) {
throw new NotImplementedException();
}
/**
* Get an ItemStack that was saved at the given key
*
* @param key
* @return
*/
public ItemStack getItemStack(String key) {
throw new NotImplementedException();
}
/**
* Setter
*
* @param key
* @param value
*/
public void setUUID(String key, UUID value) {
throw new NotImplementedException();
}
/**
* Getter
*
* @param key
* @return The stored value or NMS fallback
*/
public UUID getUUID(String key) {
throw new NotImplementedException();
}
/**
* @param key
* @return True if the key is set
*/
public Boolean hasKey(String key) {
throw new NotImplementedException();
}
/**
* @param key Deletes the given Key
*/
public void removeKey(String key) {
throw new NotImplementedException();
}
/**
* @return Set of all stored Keys
*/
public Set<String> getKeys() {
throw new NotImplementedException();
}
/**
* Creates a subCompound, or returns it if already provided
*
* @param name Key to use
* @return The subCompound Object
*/
public NBTCompound addCompound(String name) {
throw new NotImplementedException();
}
/**
* @param name
* @return The Compound instance or null
*/
public NBTCompound getCompound(String name) {
throw new NotImplementedException();
}
/**
* The same as addCompound, just with a name that better reflects what it does
*
* @param name
* @return
*/
public NBTCompound getOrCreateCompound(String name) {
throw new NotImplementedException();
}
/**
* @param name
* @return The retrieved String List
*/
public NBTList<String> getStringList(String name) {
throw new NotImplementedException();
}
/**
* @param name
* @return The retrieved Integer List
*/
public NBTList<Integer> getIntegerList(String name) {
throw new NotImplementedException();
}
/**
* @param name
* @return The retrieved Float List
*/
public NBTList<Float> getFloatList(String name) {
throw new NotImplementedException();
}
/**
* @param name
* @return The retrieved Double List
*/
public NBTList<Double> getDoubleList(String name) {
throw new NotImplementedException();
}
/**
* @param name
* @return The retrieved Long List
*/
public NBTList<Long> getLongList(String name) {
throw new NotImplementedException();
}
/**
* Returns the type of the list, null if not a list
*
* @param name
* @return
*/
public NBTType getListType(String name) {
throw new NotImplementedException();
}
/**
* @param name
* @return The retrieved Compound List
*/
public NBTCompoundList getCompoundList(String name) {
throw new NotImplementedException();
}
/**
* @param name
* @return The type of the given stored key or null
*/
public NBTType getType(String name) {
throw new NotImplementedException();
}
public void writeCompound(OutputStream stream) {
throw new NotImplementedException();
}
@Override
public String toString() {
throw new NotImplementedException();
}
/**
* @deprecated Just use toString()
* @param key
* @return A string representation of the given key
*/
@Deprecated
public String toString(String key) {
throw new NotImplementedException();
}
/**
* @deprecated Just use toString()
* @return A {@link String} representation of the NBT in Mojang JSON. This is different from normal JSON!
*/
@Deprecated
public String asNBTString() {
throw new NotImplementedException();
}
@Override
public int hashCode() {
throw new NotImplementedException();
}
/**
* Does a deep compare to check if everything is the same
*/
@Override
public boolean equals(Object obj) {
throw new NotImplementedException();
}
protected static boolean isEqual(NBTCompound compA, NBTCompound compB, String key) {
throw new NotImplementedException();
}
}
@@ -0,0 +1,67 @@
package de.tr7zw.nbtapi;
import org.apache.commons.lang.NotImplementedException;
/**
* {@link NBTListCompound} implementation for NBTLists
*
* @author tr7zw
*
*/
@Deprecated
public class NBTCompoundList extends NBTList<NBTListCompound> {
protected NBTCompoundList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
/**
* Adds a new Compound to the end of the List and returns it.
*
* @return The added {@link NBTListCompound}
*/
public NBTListCompound addCompound() {
return (NBTListCompound) addCompound(null);
}
/**
* Adds a copy of the Compound to the end of the List and returns it.
* When null is given, a new Compound will be created
*
* @param comp
* @return
*/
public NBTCompound addCompound(NBTCompound comp) {
throw new NotImplementedException();
}
/**
* Adds a new Compound to the end of the List.
*
*
* @deprecated Please use addCompound!
* @param empty
* @return True, if compound was added
*/
@Override
@Deprecated
public boolean add(NBTListCompound empty) {
throw new NotImplementedException();
}
@Override
public void add(int index, NBTListCompound element) {
throw new NotImplementedException();
}
@Override
public NBTListCompound get(int index) {
throw new NotImplementedException();
}
@Override
public NBTListCompound set(int index, NBTListCompound element) {
throw new NotImplementedException("This method doesn't work in the ListCompound context.");
}
}
@@ -0,0 +1,66 @@
package de.tr7zw.nbtapi;
import java.io.InputStream;
import org.apache.commons.lang.NotImplementedException;
/**
* A Standalone {@link NBTCompound} implementation. All data is just kept inside
* this Object.
*
* @author tr7zw
*
*/
@Deprecated
public class NBTContainer extends NBTCompound {
/**
* Creates an empty, standalone NBTCompound
*/
public NBTContainer() {
super(null, null);
throw new NotImplementedException();
}
/**
* Takes in any NMS Compound to wrap it
*
* @param nbt
*/
public NBTContainer(Object nbt) {
super(null, null);
throw new NotImplementedException();
}
/**
* Reads in a NBT InputStream
*
* @param inputsteam
*/
public NBTContainer(InputStream inputsteam) {
super(null, null);
throw new NotImplementedException();
}
/**
* Parses in a NBT String to a standalone {@link NBTCompound}. Can throw a
* {@link NbtApiException} in case something goes wrong.
*
* @param nbtString
*/
public NBTContainer(String nbtString) {
super(null, null);
throw new NotImplementedException();
}
@Override
public Object getCompound() {
throw new NotImplementedException();
}
@Override
public void setCompound(Object tag) {
throw new NotImplementedException();
}
}
@@ -0,0 +1,23 @@
package de.tr7zw.nbtapi;
import org.apache.commons.lang.NotImplementedException;
/**
* Double implementation for NBTLists
*
* @author tr7zw
*
*/
@Deprecated
public class NBTDoubleList extends NBTList<Double> {
protected NBTDoubleList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
@Override
public Double get(int index) {
throw new NotImplementedException();
}
}
@@ -1,11 +1,10 @@
package de.tr7zw.changeme.nbtapi;
package de.tr7zw.nbtapi;
import org.apache.commons.lang.NotImplementedException;
import org.bukkit.entity.Entity;
import de.tr7zw.annotations.FAUtil;
import de.tr7zw.changeme.nbtapi.utils.MinecraftVersion;
import de.tr7zw.changeme.nbtapi.utils.annotations.AvailableSince;
import de.tr7zw.changeme.nbtapi.utils.annotations.CheckUtil;
import de.tr7zw.nbtapi.utils.MinecraftVersion;
import de.tr7zw.nbtapi.utils.annotations.AvailableSince;
/**
* NBT class to access vanilla tags from Entities. Entities don't support custom
@@ -15,6 +14,7 @@ import de.tr7zw.changeme.nbtapi.utils.annotations.CheckUtil;
* @author tr7zw
*
*/
@Deprecated
public class NBTEntity extends NBTCompound {
private final Entity ent;
@@ -24,20 +24,17 @@ public class NBTEntity extends NBTCompound {
*/
public NBTEntity(Entity entity) {
super(null, null);
if (entity == null) {
throw new NullPointerException("Entity can't be null!");
}
ent = entity;
throw new NotImplementedException();
}
@Override
public Object getCompound() {
return NBTReflectionUtil.getEntityNBTTagCompound(NBTReflectionUtil.getNMSEntity(ent));
throw new NotImplementedException();
}
@Override
protected void setCompound(Object compound) {
NBTReflectionUtil.setEntityNBTTag(compound, NBTReflectionUtil.getNMSEntity(ent));
throw new NotImplementedException();
}
/**
@@ -48,8 +45,7 @@ public class NBTEntity extends NBTCompound {
*/
@AvailableSince(version = MinecraftVersion.MC1_14_R1)
public NBTCompound getPersistentDataContainer() {
FAUtil.check(this::getPersistentDataContainer, CheckUtil::isAvaliable);
return new NBTPersistentDataContainer(ent.getPersistentDataContainer());
throw new NotImplementedException();
}
}
@@ -0,0 +1,50 @@
package de.tr7zw.nbtapi;
import java.io.File;
import java.io.IOException;
import org.apache.commons.lang.NotImplementedException;
/**
* {@link NBTCompound} implementation backed by a {@link File}
*
* @author tr7zw
*
*/
@Deprecated
public class NBTFile extends NBTCompound {
/**
* Creates a NBTFile that uses @param file to store it's data. If this file
* exists, the data will be loaded.
*
* @param file
* @throws IOException
*/
public NBTFile(File file) throws IOException {
super(null, null);
throw new NotImplementedException();
}
/**
* Saves the data to the file
*
* @throws IOException
*/
public void save() throws IOException {
throw new NotImplementedException();
}
/**
* @return The File used to store the data
*/
public File getFile() {
throw new NotImplementedException();
}
@Override
public Object getCompound() {
throw new NotImplementedException();
}
}
@@ -0,0 +1,24 @@
package de.tr7zw.nbtapi;
import org.apache.commons.lang.NotImplementedException;
/**
* Float implementation for NBTLists
*
* @author tr7zw
*
*/
@Deprecated
public class NBTFloatList extends NBTList<Float> {
protected NBTFloatList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
@Override
public Float get(int index) {
throw new NotImplementedException();
}
}
@@ -1,10 +1,10 @@
package de.tr7zw.changeme.nbtapi;
package de.tr7zw.nbtapi;
import org.apache.commons.lang.NotImplementedException;
import com.mojang.authlib.GameProfile;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ObjectCreator;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
@Deprecated
public class NBTGameProfile {
/**
@@ -14,7 +14,7 @@ public class NBTGameProfile {
* @return A NBTContainer with all the GameProfile data
*/
public static NBTCompound toNBT(GameProfile profile) {
return new NBTContainer(ReflectionMethod.GAMEPROFILE_SERIALIZE.run(null, ObjectCreator.NMS_NBTTAGCOMPOUND.getInstance(), profile));
throw new NotImplementedException();
}
/**
@@ -24,7 +24,7 @@ public class NBTGameProfile {
* @return The reconstructed GameProfile
*/
public static GameProfile fromNBT(NBTCompound compound) {
return (GameProfile) ReflectionMethod.GAMEPROFILE_DESERIALIZE.run(null, NBTReflectionUtil.gettoCompount(compound.getCompound(), compound));
throw new NotImplementedException();
}
}
@@ -0,0 +1,23 @@
package de.tr7zw.nbtapi;
import org.apache.commons.lang.NotImplementedException;
/**
* Integer implementation for NBTLists
*
* @author tr7zw
*
*/
@Deprecated
public class NBTIntegerList extends NBTList<Integer> {
protected NBTIntegerList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
@Override
public Integer get(int index) {
throw new NotImplementedException();
}
}
@@ -1,11 +1,9 @@
package de.tr7zw.changeme.nbtapi;
package de.tr7zw.nbtapi;
import org.bukkit.Material;
import org.apache.commons.lang.NotImplementedException;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
/**
* NBT class to access vanilla/custom tags on ItemStacks. This class doesn't
* autosave to the Itemstack, use getItem to get the changed ItemStack
@@ -13,12 +11,9 @@ import de.tr7zw.changeme.nbtapi.utils.nmsmappings.ReflectionMethod;
* @author tr7zw
*
*/
@Deprecated
public class NBTItem extends NBTCompound {
private ItemStack bukkitItem;
private boolean directApply;
private ItemStack originalSrcStack = null;
/**
* Constructor for NBTItems. The ItemStack will be cloned!
*
@@ -38,26 +33,17 @@ public class NBTItem extends NBTCompound {
*/
public NBTItem(ItemStack item, boolean directApply) {
super(null, null);
if (item == null || item.getType() == Material.AIR) {
throw new NullPointerException("ItemStack can't be null/Air!");
}
this.directApply = directApply;
bukkitItem = item.clone();
if(directApply) {
this.originalSrcStack = item;
}
throw new NotImplementedException();
}
@Override
public Object getCompound() {
return NBTReflectionUtil.getItemRootNBTTagCompound(ReflectionMethod.ITEMSTACK_NMSCOPY.run(null, bukkitItem));
throw new NotImplementedException();
}
@Override
protected void setCompound(Object compound) {
Object stack = ReflectionMethod.ITEMSTACK_NMSCOPY.run(null, bukkitItem);
ReflectionMethod.ITEMSTACK_SET_TAG.run(stack, compound);
bukkitItem = (ItemStack) ReflectionMethod.ITEMSTACK_BUKKITMIRROR.run(null, stack);
throw new NotImplementedException();
}
/**
@@ -70,12 +56,7 @@ public class NBTItem extends NBTCompound {
* @param item ItemStack that should get the new NBT data
*/
public void applyNBT(ItemStack item) {
if (item == null || item.getType() == Material.AIR) {
throw new NullPointerException("ItemStack can't be null/Air!");
}
NBTItem nbti = new NBTItem(new ItemStack(item.getType()));
nbti.mergeCompound(this);
item.setItemMeta(nbti.getItem().getItemMeta());
throw new NotImplementedException();
}
/**
@@ -84,9 +65,7 @@ public class NBTItem extends NBTCompound {
* @param item ItemStack that should get the new NBT data
*/
public void mergeNBT(ItemStack item) {
NBTItem nbti = new NBTItem(item);
nbti.mergeCompound(this);
item.setItemMeta(nbti.getItem().getItemMeta());
throw new NotImplementedException();
}
/**
@@ -95,12 +74,7 @@ public class NBTItem extends NBTCompound {
* @param item ItemStack that should get the new NBT data
*/
public void mergeCustomNBT(ItemStack item) {
if (item == null || item.getType() == Material.AIR) {
throw new NullPointerException("ItemStack can't be null/Air!");
}
ItemMeta meta = item.getItemMeta();
NBTReflectionUtil.getUnhandledNBTTags(meta).putAll(NBTReflectionUtil.getUnhandledNBTTags(bukkitItem.getItemMeta()));
item.setItemMeta(meta);
throw new NotImplementedException();
}
@@ -110,28 +84,25 @@ public class NBTItem extends NBTCompound {
* @return true when custom tags are present
*/
public boolean hasCustomNbtData() {
ItemMeta meta = bukkitItem.getItemMeta();
return !NBTReflectionUtil.getUnhandledNBTTags(meta).isEmpty();
throw new NotImplementedException();
}
/**
* Remove all custom (non-vanilla) NBT tags from the NBTItem.
*/
public void clearCustomNBT() {
ItemMeta meta = bukkitItem.getItemMeta();
NBTReflectionUtil.getUnhandledNBTTags(meta).clear();
bukkitItem.setItemMeta(meta);
throw new NotImplementedException();
}
/**
* @return The modified ItemStack
*/
public ItemStack getItem() {
return bukkitItem;
throw new NotImplementedException();
}
protected void setItem(ItemStack item) {
bukkitItem = item;
throw new NotImplementedException();
}
/**
@@ -140,7 +111,7 @@ public class NBTItem extends NBTCompound {
* @return Does the ItemStack have a NBTCompound.
*/
public boolean hasNBTData() {
return getCompound() != null;
throw new NotImplementedException();
}
/**
@@ -151,7 +122,7 @@ public class NBTItem extends NBTCompound {
* @return Standalone {@link NBTContainer} with the Item's data
*/
public static NBTContainer convertItemtoNBT(ItemStack item) {
return NBTReflectionUtil.convertNMSItemtoNBTCompound(ReflectionMethod.ITEMSTACK_NMSCOPY.run(null, item));
throw new NotImplementedException();
}
/**
@@ -162,15 +133,12 @@ public class NBTItem extends NBTCompound {
* @return ItemStack using the {@link NBTCompound}'s data
*/
public static ItemStack convertNBTtoItem(NBTCompound comp) {
return (ItemStack) ReflectionMethod.ITEMSTACK_BUKKITMIRROR.run(null,
NBTReflectionUtil.convertNBTCompoundtoNMSItem(comp));
throw new NotImplementedException();
}
@Override
protected void saveCompound() {
if(directApply) {
applyNBT(originalSrcStack);
}
throw new NotImplementedException();
}
}
@@ -0,0 +1,161 @@
package de.tr7zw.nbtapi;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import org.apache.commons.lang.NotImplementedException;
/**
* Abstract List implementation for ListCompounds
*
* @author tr7zw
*
* @param <T>
*/
@Deprecated
public abstract class NBTList<T> implements List<T> {
protected NBTList(NBTCompound owner, String name, NBTType type, Object list) {
}
/**
* @return Name of this list-compound
*/
public String getName() {
throw new NotImplementedException();
}
/**
* @return The Compound's parent Object
*/
public NBTCompound getParent() {
throw new NotImplementedException();
}
@Override
public boolean add(T element) {
throw new NotImplementedException();
}
@Override
public void add(int index, T element) {
throw new NotImplementedException();
}
@Override
public T set(int index, T element) {
throw new NotImplementedException();
}
public T remove(int i) {
throw new NotImplementedException();
}
public int size() {
throw new NotImplementedException();
}
/**
* @return The type that this list contains
*/
public NBTType getType() {
throw new NotImplementedException();
}
@Override
public boolean isEmpty() {
throw new NotImplementedException();
}
@Override
public void clear() {
throw new NotImplementedException();
}
@Override
public boolean contains(Object o) {
throw new NotImplementedException();
}
@Override
public int indexOf(Object o) {
throw new NotImplementedException();
}
@Override
public boolean addAll(Collection<? extends T> c) {
throw new NotImplementedException();
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
throw new NotImplementedException();
}
@Override
public boolean containsAll(Collection<?> c) {
throw new NotImplementedException();
}
@Override
public int lastIndexOf(Object o) {
throw new NotImplementedException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new NotImplementedException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new NotImplementedException();
}
@Override
public boolean remove(Object o) {
throw new NotImplementedException();
}
@Override
public Iterator<T> iterator() {
throw new NotImplementedException();
}
@Override
public ListIterator<T> listIterator() {
throw new NotImplementedException();
}
@Override
public ListIterator<T> listIterator(int startIndex) {
throw new NotImplementedException();
}
@Override
public Object[] toArray() {
throw new NotImplementedException();
}
@SuppressWarnings("unchecked")
@Override
public <E> E[] toArray(E[] a) {
throw new NotImplementedException();
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
throw new NotImplementedException();
}
@Override
public String toString() {
throw new NotImplementedException();
}
}
@@ -1,4 +1,6 @@
package de.tr7zw.changeme.nbtapi;
package de.tr7zw.nbtapi;
import org.apache.commons.lang.NotImplementedException;
/**
* Cut down version of the {@link NBTCompound} for inside
@@ -9,34 +11,25 @@ package de.tr7zw.changeme.nbtapi;
* @author tr7zw
*
*/
@Deprecated
public class NBTListCompound extends NBTCompound {
private NBTList<?> owner;
private Object compound;
protected NBTListCompound(NBTList<?> parent, Object obj) {
super(null, null);
owner = parent;
compound = obj;
}
public NBTList<?> getListParent() {
return owner;
throw new NotImplementedException();
}
@Override
public Object getCompound() {
return compound;
throw new NotImplementedException();
}
@Override
protected void setCompound(Object compound) {
this.compound = compound;
}
@Override
protected void saveCompound() {
owner.save();
throw new NotImplementedException();
}
}
@@ -0,0 +1,23 @@
package de.tr7zw.nbtapi;
import org.apache.commons.lang.NotImplementedException;
/**
* Long implementation for NBTLists
*
* @author tr7zw
*
*/
@Deprecated
public class NBTLongList extends NBTList<Long> {
protected NBTLongList(NBTCompound owner, String name, NBTType type, Object list) {
super(owner, name, type, list);
}
@Override
public Long get(int index) {
throw new NotImplementedException();
}
}
@@ -0,0 +1,23 @@
package de.tr7zw.nbtapi;
import org.apache.commons.lang.NotImplementedException;
import org.bukkit.persistence.PersistentDataContainer;
@Deprecated
public class NBTPersistentDataContainer extends NBTCompound {
protected NBTPersistentDataContainer(PersistentDataContainer container) {
super(null, null);
}
@Override
public Object getCompound() {
throw new NotImplementedException();
}
@Override
protected void setCompound(Object compound) {
throw new NotImplementedException();
}
}
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff. Show more