cn.nukkit.utils.Utils Java Examples

The following examples show how to use cn.nukkit.utils.Utils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Item.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
public static Item fromJson(Map<String, Object> data) {
    String nbt = (String) data.get("nbt_b64");
    byte[] nbtBytes;
    if (nbt != null) {
        nbtBytes = Base64.getDecoder().decode(nbt);
    } else { // Support old format for backwards compat
        nbt = (String) data.getOrDefault("nbt_hex", null);
        if (nbt == null) {
            nbtBytes = new byte[0];
        } else {
            nbtBytes = Utils.parseHexBinary(nbt);
        }
    }

    return get(Utils.toInt(data.get("id")), Utils.toInt(data.getOrDefault("damage", 0)), Utils.toInt(data.getOrDefault("count", 1)), nbtBytes);
}
 
Example #2
Source File: PluginBase.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean saveResource(String filename, String outputName, boolean replace) {
    Preconditions.checkArgument(filename != null && outputName != null, "Filename can not be null!");
    Preconditions.checkArgument(filename.trim().length() != 0 && outputName.trim().length() != 0, "Filename can not be empty!");

    File out = new File(dataFolder, outputName);
    if (!out.exists() || replace) {
        try (InputStream resource = getResource(filename)) {
            if (resource != null) {
                File outFolder = out.getParentFile();
                if (!outFolder.exists()) {
                    outFolder.mkdirs();
                }
                Utils.writeFile(out, resource);

                return true;
            }
        } catch (IOException e) {
            Server.getInstance().getLogger().logException(e);
        }
    }
    return false;
}
 
Example #3
Source File: JavaPluginLoader.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PluginDescription getPluginDescription(File file) {
    try (JarFile jar = new JarFile(file)) {
        JarEntry entry = jar.getJarEntry("nukkit.yml");
        if (entry == null) {
            entry = jar.getJarEntry("plugin.yml");
            if (entry == null) {
                return null;
            }
        }
        try (InputStream stream = jar.getInputStream(entry)) {
            return new PluginDescription(Utils.readFile(stream));
        }
    } catch (IOException e) {
        return null;
    }
}
 
Example #4
Source File: BanList.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
public void save() {
    this.removeExpired();

    try {
        File file = new File(this.file);
        if (!file.exists()) {
            file.createNewFile();
        }

        LinkedList<LinkedHashMap<String, String>> list = new LinkedList<>();
        for (BanEntry entry : this.list.values()) {
            list.add(entry.getMap());
        }
        Utils.writeFile(this.file, new ByteArrayInputStream(new GsonBuilder().setPrettyPrinting().create().toJson(list).getBytes(StandardCharsets.UTF_8)));
    } catch (IOException e) {
        MainLogger.getLogger().error("Could not save ban list ", e);
    }
}
 
Example #5
Source File: BanList.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
public void load() {
    this.list = new LinkedHashMap<>();
    File file = new File(this.file);
    try {
        if (!file.exists()) {
            file.createNewFile();
            this.save();
        } else {

            LinkedList<TreeMap<String, String>> list = new Gson().fromJson(Utils.readFile(this.file), new TypeToken<LinkedList<TreeMap<String, String>>>() {
            }.getType());
            for (TreeMap<String, String> map : list) {
                BanEntry entry = BanEntry.fromMap(map);
                this.list.put(entry.getName(), entry);
            }
        }
    } catch (IOException e) {
        MainLogger.getLogger().error("Could not load ban list: ", e);
    }

}
 
Example #6
Source File: PluginBase.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean saveResource(String filename, String outputName, boolean replace) {
    Preconditions.checkArgument(filename != null && outputName != null, "Filename can not be null!");
    Preconditions.checkArgument(filename.trim().length() != 0 && outputName.trim().length() != 0, "Filename can not be empty!");

    File out = new File(dataFolder, outputName);
    if (!out.exists() || replace) {
        try (InputStream resource = getResource(filename)) {
            if (resource != null) {
                File outFolder = out.getParentFile();
                if (!outFolder.exists()) {
                    outFolder.mkdirs();
                }
                Utils.writeFile(out, resource);

                return true;
            }
        } catch (IOException e) {
            Server.getInstance().getLogger().logException(e);
        }
    }
    return false;
}
 
Example #7
Source File: JavaPluginLoader.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PluginDescription getPluginDescription(File file) {
    try (JarFile jar = new JarFile(file)) {
        JarEntry entry = jar.getJarEntry("nukkit.yml");
        if (entry == null) {
            entry = jar.getJarEntry("plugin.yml");
            if (entry == null) {
                return null;
            }
        }
        try (InputStream stream = jar.getInputStream(entry)) {
            return new PluginDescription(Utils.readFile(stream));
        }
    } catch (IOException e) {
        return null;
    }
}
 
Example #8
Source File: BanList.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
public void save() {
    this.removeExpired();

    try {
        File file = new File(this.file);
        if (!file.exists()) {
            file.createNewFile();
        }

        LinkedList<LinkedHashMap<String, String>> list = new LinkedList<>();
        for (BanEntry entry : this.list.values()) {
            list.add(entry.getMap());
        }
        Utils.writeFile(this.file, new ByteArrayInputStream(new GsonBuilder().setPrettyPrinting().create().toJson(list).getBytes(StandardCharsets.UTF_8)));
    } catch (IOException e) {
        MainLogger.getLogger().error("Could not save ban list ", e);
    }
}
 
Example #9
Source File: Server.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
public void saveOfflinePlayerData(String name, CompoundTag tag, boolean async) {
    if (this.shouldSavePlayerData()) {
        try {
            if (async) {
                this.getScheduler().scheduleAsyncTask(new FileWriteTask(FastAppender.get(this.getDataPath() + "players/", name.toLowerCase(), ".dat"), NBTIO.writeGZIPCompressed(tag, ByteOrder.BIG_ENDIAN)));
            } else {
                Utils.writeFile(FastAppender.get(this.getDataPath(), "players/", name.toLowerCase(), ".dat"), new ByteArrayInputStream(NBTIO.writeGZIPCompressed(tag, ByteOrder.BIG_ENDIAN)));
            }
        } catch (Exception e) {
            this.logger.critical(this.getLanguage().translateString("nukkit.data.saveError", new String[]{name, e.getMessage()}));
            if (Nukkit.DEBUG > 1) {
                this.logger.logException(e);
            }
        }
    }
}
 
Example #10
Source File: BanList.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
public void load() {
    this.list = new LinkedHashMap<>();
    File file = new File(this.file);
    try {
        if (!file.exists()) {
            file.createNewFile();
            this.save();
        } else {

            LinkedList<TreeMap<String, String>> list = new Gson().fromJson(Utils.readFile(this.file), new TypeToken<LinkedList<TreeMap<String, String>>>() {
            }.getType());
            for (TreeMap<String, String> map : list) {
                BanEntry entry = BanEntry.fromMap(map);
                this.list.put(entry.getName(), entry);
            }
        }
    } catch (IOException e) {
        MainLogger.getLogger().error("Could not load ban list: ", e);
    }

}
 
Example #11
Source File: EntityHuman.java    From Nukkit with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void initEntity() {
    this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, false);
    this.setDataFlag(DATA_FLAGS, DATA_FLAG_GRAVITY);

    this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, 0, 0, 0), false);

    if (!(this instanceof Player)) {
        if (this.namedTag.contains("NameTag")) {
            this.setNameTag(this.namedTag.getString("NameTag"));
        }

        if (this.namedTag.contains("Skin") && this.namedTag.get("Skin") instanceof CompoundTag) {
            if (!this.namedTag.getCompound("Skin").contains("Transparent")) {
                this.namedTag.getCompound("Skin").putBoolean("Transparent", false);
            }
            this.setSkin(new Skin(this.namedTag.getCompound("Skin").getByteArray("Data"), this.namedTag.getCompound("Skin").getString("ModelId")));
        }

        this.uuid = Utils.dataToUUID(String.valueOf(this.getId()).getBytes(StandardCharsets.UTF_8), this.getSkin()
                .getData(), this.getNameTag().getBytes(StandardCharsets.UTF_8));
    }

    super.initEntity();
}
 
Example #12
Source File: PluginBase.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean saveResource(String filename, String outputName, boolean replace) {
    Preconditions.checkArgument(filename != null && outputName != null, "Filename can not be null!");
    Preconditions.checkArgument(filename.trim().length() != 0 && outputName.trim().length() != 0, "Filename can not be empty!");

    File out = new File(dataFolder, outputName);
    if (!out.exists() || replace) {
        try (InputStream resource = getResource(filename)) {
            if (resource != null) {
                File outFolder = out.getParentFile();
                if (!outFolder.exists()) {
                    outFolder.mkdirs();
                }
                Utils.writeFile(out, resource);

                return true;
            }
        } catch (IOException e) {
            Server.getInstance().getLogger().logException(e);
        }
    }
    return false;
}
 
Example #13
Source File: JavaPluginLoader.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
@Override
public PluginDescription getPluginDescription(File file) {
    try (JarFile jar = new JarFile(file)) {
        JarEntry entry = jar.getJarEntry("nukkit.yml");
        if (entry == null) {
            entry = jar.getJarEntry("plugin.yml");
            if (entry == null) {
                return null;
            }
        }
        try (InputStream stream = jar.getInputStream(entry)) {
            return new PluginDescription(Utils.readFile(stream));
        }
    } catch (IOException e) {
        return null;
    }
}
 
Example #14
Source File: BanList.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
public void save() {
    this.removeExpired();

    try {
        File file = new File(this.file);
        if (!file.exists()) {
            file.createNewFile();
        }

        LinkedList<LinkedHashMap<String, String>> list = new LinkedList<>();
        for (BanEntry entry : this.list.values()) {
            list.add(entry.getMap());
        }
        Utils.writeFile(this.file, new ByteArrayInputStream(new GsonBuilder().setPrettyPrinting().create().toJson(list).getBytes(StandardCharsets.UTF_8)));
    } catch (IOException e) {
        MainLogger.getLogger().error("Could not save ban list ", e);
    }
}
 
Example #15
Source File: BanList.java    From Jupiter with GNU General Public License v3.0 6 votes vote down vote up
public void load() {
    this.list = new LinkedHashMap<>();
    File file = new File(this.file);
    try {
        if (!file.exists()) {
            file.createNewFile();
            this.save();
        } else {

            LinkedList<TreeMap<String, String>> list = new Gson().fromJson(Utils.readFile(this.file), new TypeToken<LinkedList<TreeMap<String, String>>>() {
            }.getType());
            for (TreeMap<String, String> map : list) {
                BanEntry entry = BanEntry.fromMap(map);
                this.list.put(entry.getName(), entry);
            }
        }
    } catch (IOException e) {
        MainLogger.getLogger().error("Could not load ban list: ", e);
    }

}
 
Example #16
Source File: SimpleCommandMap.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean dispatch(CommandSender sender, String cmdLine) {
    ArrayList<String> parsed = parseArguments(cmdLine);
    if (parsed.size() == 0) {
        return false;
    }

    String sentCommandLabel = parsed.remove(0).toLowerCase();
    String[] args = parsed.toArray(new String[0]);
    Command target = this.getCommand(sentCommandLabel);

    if (target == null) {
        return false;
    }

    target.timing.startTiming();
    try {
        target.execute(sender, sentCommandLabel, args);
    } catch (Exception e) {
        sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.exception"));
        this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.command.exception", cmdLine, target.toString(), Utils.getExceptionMessage(e)));
        MainLogger logger = sender.getServer().getLogger();
        if (logger != null) {
            logger.logException(e);
        }
    }
    target.timing.stopTiming();

    return true;
}
 
Example #17
Source File: Language.java    From EssentialsNK with GNU General Public License v3.0 5 votes vote down vote up
private static Map<String, String> loadLang(InputStream stream) {
    try {
        String content = Utils.readFile(stream);
        Map<String, String> d = new HashMap<>();
        for (String line : content.split("\n")) {
            line = line.trim();
            if (line.equals("") || line.charAt(0) == '#') {
                continue;
            }
            String[] t = line.split("=");
            if (t.length < 2) {
                continue;
            }
            String key = t[0];
            StringBuilder value = new StringBuilder();
            for (int i = 1; i < t.length - 1; i++) {
                value.append(t[i]).append("=");
            }
            value.append(t[t.length - 1]);
            if (value.toString().equals("")) {
                continue;
            }
            d.put(key, value.toString());
        }
        return d;
    } catch (IOException e) {
        Server.getInstance().getLogger().logException(e);
        return null;
    }
}
 
Example #18
Source File: EconomyAPI.java    From EconomyAPI with GNU General Public License v3.0 5 votes vote down vote up
private void importLanguages(){
	this.language = new HashMap<>();
	
	for(String lang : langList){
		InputStream is = this.getResource("lang_" + lang + ".json");
		try {
			JSONObject obj = new JSONObject(Utils.readFile(is));
			this.language.put(lang, obj);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 
Example #19
Source File: PluginManager.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
private HandlerList getEventListeners(Class<? extends Event> type) throws IllegalAccessException {
    try {
        Method method = getRegistrationClass(type).getDeclaredMethod("getHandlers");
        method.setAccessible(true);
        return (HandlerList) method.invoke(null);
    } catch (Exception e) {
        throw new IllegalAccessException(Utils.getExceptionMessage(e));
    }
}
 
Example #20
Source File: EconomyAPI.java    From EconomyAPI with GNU General Public License v3.0 5 votes vote down vote up
private void importLanguages(){
	this.language = new HashMap<>();
	
	for(String lang : langList){
		InputStream is = this.getResource("lang_" + lang + ".json");
		try {
			JSONObject obj = new JSONObject(Utils.readFile(is));
			this.language.put(lang, obj);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
 
Example #21
Source File: PluginBase.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void reloadConfig() {
    this.config = new Config(this.configFile);
    InputStream configStream = this.getResource("config.yml");
    if (configStream != null) {
        DumperOptions dumperOptions = new DumperOptions();
        dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        Yaml yaml = new Yaml(dumperOptions);
        try {
            this.config.setDefault(yaml.loadAs(Utils.readFile(this.configFile), LinkedHashMap.class));
        } catch (IOException e) {
            Server.getInstance().getLogger().logException(e);
        }
    }
}
 
Example #22
Source File: RakNetInterface.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setName(String name) {
    QueryRegenerateEvent info = this.server.getQueryInformation();
    String[] names = name.split("!@#");  //Split double names within the program
    this.handler.sendOption("name",
            "MCPE;" + Utils.rtrim(names[0].replace(";", "\\;"), '\\') + ";" +
                    ProtocolInfo.CURRENT_PROTOCOL + ";;" +
                    info.getPlayerCount() + ";" +
                    info.getMaxPlayerCount() + ";" +
                    this.server.getServerUniqueId().toString() + ";" +
                    (names.length > 1 ? Utils.rtrim(names[1].replace(";", "\\;"), '\\') : "") + ";" +
                    Server.getGamemodeString(this.server.getDefaultGamemode(), true) + ";");
}
 
Example #23
Source File: ChunkSection.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public boolean compress() {
    if (!palette.compress()) {
        if (blockLight != null) {
            byte[] arr1 = blockLight;
            hasBlockLight = !Utils.isByteArrayEmpty(arr1);
            byte[] arr2;
            if (skyLight != null) {
                arr2 = skyLight;
                hasSkyLight = !Utils.isByteArrayEmpty(skyLight);
            } else {
                arr2 = EmptyChunkSection.EMPTY_LIGHT_ARR;
                hasSkyLight = false;
            }
            blockLight = null;
            skyLight = null;
            if (hasBlockLight && hasSkyLight) {
                try {
                    compressedLight = Zlib.deflate(Binary.appendBytes(arr1, arr2), 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return true;
        }
        return false;
    }
    return true;
}
 
Example #24
Source File: CraftingManager.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public void registerRecipe(Recipe recipe) {
    if (recipe instanceof CraftingRecipe) {
        UUID id = Utils.dataToUUID(String.valueOf(++RECIPE_COUNT), String.valueOf(recipe.getResult().getId()), String.valueOf(recipe.getResult().getDamage()), String.valueOf(recipe.getResult().getCount()), Arrays.toString(recipe.getResult().getCompoundTag()));

        ((CraftingRecipe) recipe).setId(id);
        this.recipes.add(recipe);
    }

    recipe.registerToCraftingManager(this);
}
 
Example #25
Source File: BaseLang.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
protected Map<String, String> loadLang(String path) {
    try {
        String content = Utils.readFile(path);
        Map<String, String> d = new HashMap<>();
        for (String line : content.split("\n")) {
            line = line.trim();
            if (line.equals("") || line.charAt(0) == '#') {
                continue;
            }
            String[] t = line.split("=");
            if (t.length < 2) {
                continue;
            }
            String key = t[0];
            String value = "";
            for (int i = 1; i < t.length - 1; i++) {
                value += t[i] + "=";
            }
            value += t[t.length - 1];
            if (value.equals("")) {
                continue;
            }
            d.put(key, value);
        }
        return d;
    } catch (IOException e) {
        Server.getInstance().getLogger().logException(e);
        return null;
    }
}
 
Example #26
Source File: BaseLang.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
protected Map<String, String> loadLang(InputStream stream) {
    try {
        String content = Utils.readFile(stream);
        Map<String, String> d = new HashMap<>();
        for (String line : content.split("\n")) {
            line = line.trim();
            if (line.equals("") || line.charAt(0) == '#') {
                continue;
            }
            String[] t = line.split("=");
            if (t.length < 2) {
                continue;
            }
            String key = t[0];
            String value = "";
            for (int i = 1; i < t.length - 1; i++) {
                value += t[i] + "=";
            }
            value += t[t.length - 1];
            if (value.equals("")) {
                continue;
            }
            d.put(key, value);
        }
        return d;
    } catch (IOException e) {
        Server.getInstance().getLogger().logException(e);
        return null;
    }
}
 
Example #27
Source File: FileWriteTask.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onRun() {
    try {
        Utils.writeFile(file, contents);
    } catch (IOException e) {
        Server.getInstance().getLogger().logException(e);
    }
}
 
Example #28
Source File: SimpleCommandMap.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean dispatch(CommandSender sender, String cmdLine) {
    ArrayList<String> parsed = parseArguments(cmdLine);
    if (parsed.size() == 0) {
        return false;
    }

    String sentCommandLabel = parsed.remove(0).toLowerCase();
    String[] args = parsed.toArray(new String[parsed.size()]);
    Command target = this.getCommand(sentCommandLabel);

    if (target == null) {
        return false;
    }

    target.timing.startTiming();
    try {
        target.execute(sender, sentCommandLabel, args);
    } catch (Exception e) {
        sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.exception"));
        this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.command.exception", cmdLine, target.toString(), Utils.getExceptionMessage(e)));
        MainLogger logger = sender.getServer().getLogger();
        if (logger != null) {
            logger.logException(e);
        }
    }
    target.timing.stopTiming();

    return true;
}
 
Example #29
Source File: EntityHuman.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void initEntity() {
    this.setDataFlag(DATA_PLAYER_FLAGS, DATA_PLAYER_FLAG_SLEEP, false);
    this.setDataFlag(DATA_FLAGS, DATA_FLAG_GRAVITY);

    this.setDataProperty(new IntPositionEntityData(DATA_PLAYER_BED_POSITION, 0, 0, 0), false);

    if (!(this instanceof Player)) {
        if (this.namedTag.contains("NameTag")) {
            this.setNameTag(this.namedTag.getString("NameTag"));
        }

        if (this.namedTag.contains("Skin") && this.namedTag.get("Skin") instanceof CompoundTag) {
            if (!this.namedTag.getCompound("Skin").contains("Transparent")) {
                this.namedTag.getCompound("Skin").putBoolean("Transparent", false);
            }
            this.setSkin(new Skin(
                    this.namedTag.getCompound("Skin").getString("skinId"),
                    this.namedTag.getCompound("Skin").getByteArray("skinData"),
                    this.namedTag.getCompound("Skin").getCompound("capeData").getByteArray("capeData"),
                    this.namedTag.getCompound("Skin").getString("geometryName"),
                    this.namedTag.getCompound("Skin").getCompound("geometryData").getString("geometryData")
            ));
        }

        this.uuid = Utils.dataToUUID(String.valueOf(this.getId()).getBytes(StandardCharsets.UTF_8), this.getSkin()
                .getSkinData(), this.getNameTag().getBytes(StandardCharsets.UTF_8));
    }

    super.initEntity();

    if (this instanceof Player) {
        ((Player) this).addWindow(this.inventory, 0);
    }
}
 
Example #30
Source File: BaseLang.java    From Jupiter with GNU General Public License v3.0 5 votes vote down vote up
protected Map<String, String> loadLang(InputStream stream) {
    try {
        String content = Utils.readFile(new BufferedInputStream(stream));
        Map<String, String> d = new HashMap<>();
        for (String line : content.split("\n")) {
            line = line.trim();
            if (line.equals("") || line.charAt(0) == '#') {
                continue;
            }
            String[] t = line.split("=");
            if (t.length < 2) {
                continue;
            }
            String key = t[0];
            String value = "";
            for (int i = 1; i < t.length - 1; i++) {
                value += t[i] + "=";
            }
            value += t[t.length - 1];
            if (value.equals("")) {
                continue;
            }
            d.put(key, value);
        }
        return d;
    } catch (IOException e) {
        Server.getInstance().getLogger().logException(e);
        return null;
    }
}