Java Code Examples for cn.nukkit.utils.Utils

The following examples show how to use cn.nukkit.utils.Utils. These examples are extracted from open source projects. 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 Project: Jupiter   Source File: BanList.java    License: 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 2
Source Project: Jupiter   Source File: BanList.java    License: 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 3
Source Project: Jupiter   Source File: JavaPluginLoader.java    License: 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 Project: Jupiter   Source File: PluginBase.java    License: 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 5
Source Project: Jupiter   Source File: Server.java    License: 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 6
Source Project: Nukkit   Source File: BanList.java    License: 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 7
Source Project: Nukkit   Source File: BanList.java    License: 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 8
Source Project: Nukkit   Source File: JavaPluginLoader.java    License: 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 9
Source Project: Nukkit   Source File: PluginBase.java    License: 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 10
Source Project: Nukkit   Source File: Item.java    License: 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 11
Source Project: Nukkit   Source File: EntityHuman.java    License: 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 Project: Nukkit   Source File: BanList.java    License: 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 13
Source Project: Nukkit   Source File: BanList.java    License: 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 14
Source Project: Nukkit   Source File: JavaPluginLoader.java    License: 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 15
Source Project: Nukkit   Source File: PluginBase.java    License: 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 16
Source Project: Jupiter   Source File: EntityHuman.java    License: 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 17
Source Project: Jupiter   Source File: PluginManager.java    License: 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 18
Source Project: Jupiter   Source File: PluginBase.java    License: 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 19
Source Project: Jupiter   Source File: RakNetInterface.java    License: 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("[email protected]#");  //Split double names within the program
    this.handler.sendOption("name",
            "MCPE;" + Utils.rtrim(names[0].replace(";", "\\;"), '\\') + ";" +
                    ProtocolInfo.CURRENT_PROTOCOL + ";" +
                    ProtocolInfo.MINECRAFT_VERSION_NETWORK + ";" +
                    info.getPlayerCount() + ";" +
                    info.getMaxPlayerCount() + ";" +
                    this.server.getServerUniqueId().toString() + ";" +
                    (names.length > 1 ? Utils.rtrim(names[1].replace(";", "\\;"), '\\') : "") + ";" +
                    Server.getGamemodeString(this.server.getDefaultGamemode(), true) + ";");
}
 
Example 20
Source Project: Jupiter   Source File: LevelDB.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void saveLevelData() {
    try {
        byte[] data = NBTIO.write(levelData, ByteOrder.LITTLE_ENDIAN);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(Binary.writeLInt(3));
        outputStream.write(Binary.writeLInt(data.length));
        outputStream.write(data);

        Utils.writeFile(path + "level.dat", new ByteArrayInputStream(outputStream.toByteArray()));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 21
Source Project: Jupiter   Source File: BaseLang.java    License: 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 22
Source Project: Jupiter   Source File: BaseLang.java    License: 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;
    }
}
 
Example 23
Source Project: Jupiter   Source File: FileWriteTask.java    License: 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 24
Source Project: Jupiter   Source File: SimpleCommandMap.java    License: 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 25
Source Project: Nukkit   Source File: PluginBase.java    License: 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 26
Source Project: Nukkit   Source File: RakNetInterface.java    License: 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("[email protected]#");  //Split double names within the program
    this.handler.sendOption("name",
            "MCPE;" + Utils.rtrim(names[0].replace(";", "\\;"), '\\') + ";" +
                    ProtocolInfo.CURRENT_PROTOCOL + ";" +
                    ProtocolInfo.MINECRAFT_VERSION_NETWORK + ";" +
                    info.getPlayerCount() + ";" +
                    info.getMaxPlayerCount() + ";" +
                    this.server.getServerUniqueId().toString() + ";" +
                    (names.length > 1 ? Utils.rtrim(names[1].replace(";", "\\;"), '\\') : "") + ";" +
                    Server.getGamemodeString(this.server.getDefaultGamemode(), true) + ";");
}
 
Example 27
Source Project: Nukkit   Source File: Network.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void processInterfaces() {
    for (SourceInterface interfaz : this.interfaces) {
        try {
            interfaz.process();
        } catch (Exception e) {
            if (Nukkit.DEBUG > 1) {
                this.server.getLogger().logException(e);
            }

            interfaz.emergencyShutdown();
            this.unregisterInterface(interfaz);
            log.fatal(this.server.getLanguage().translateString("nukkit.server.networkError", new String[]{interfaz.getClass().getName(), Utils.getExceptionMessage(e)}));
        }
    }
}
 
Example 28
Source Project: Nukkit   Source File: CraftingManager.java    License: 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 29
Source Project: Nukkit   Source File: BaseLang.java    License: 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 30
Source Project: Nukkit   Source File: BaseLang.java    License: 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;
    }
}