Java Code Examples for cn.nukkit.utils.Utils#writeFile()

The following examples show how to use cn.nukkit.utils.Utils#writeFile() . 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: 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 2
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 3
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 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: 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 6
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 7
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 8
Source File: LevelDB.java    From Jupiter with 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 9
Source File: FileWriteTask.java    From Jupiter 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 10
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 11
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 12
Source File: LevelDB.java    From Jupiter with GNU General Public License v3.0 4 votes vote down vote up
public static void generate(String path, String name, long seed, Class<? extends Generator> generator, Map<String, String> options) throws IOException {
    if (!new File(path + "/db").exists()) {
        new File(path + "/db").mkdirs();
    }

    CompoundTag levelData = new CompoundTag("")
            .putLong("currentTick", 0)
            .putInt("DayCycleStopTime", -1)
            .putInt("GameType", 0)
            .putInt("Generator", Generator.getGeneratorType(generator))
            .putBoolean("hasBeenLoadedInCreative", false)
            .putLong("LastPlayed", System.currentTimeMillis() / 1000)
            .putString("LevelName", name)
            .putFloat("lightningLevel", 0)
            .putInt("lightningTime", new Random().nextInt())
            .putInt("limitedWorldOriginX", 128)
            .putInt("limitedWorldOriginY", 70)
            .putInt("limitedWorldOriginZ", 128)
            .putInt("Platform", 0)
            .putFloat("rainLevel", 0)
            .putInt("rainTime", new Random().nextInt())
            .putLong("RandomSeed", seed)
            .putByte("spawnMobs", 0)
            .putInt("SpawnX", 128)
            .putInt("SpawnY", 70)
            .putInt("SpawnZ", 128)
            .putInt("storageVersion", 4)
            .putLong("Time", 0)
            .putLong("worldStartCount", ((long) Integer.MAX_VALUE) & 0xffffffffL);

    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()));

    DB db = Iq80DBFactory.factory.open(new File(path + "/db"), new Options().createIfMissing(true));
    db.close();
}
 
Example 13
Source File: BugReportGenerator.java    From Nukkit with GNU General Public License v3.0 4 votes vote down vote up
private String generate() throws IOException {
    File reports = new File(Nukkit.DATA_PATH, "logs/bug_reports");
    if (!reports.isDirectory()) {
        reports.mkdirs();
    }

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmSS");
    String date = simpleDateFormat.format(new Date());

    StringBuilder model = new StringBuilder();
    long totalDiskSpace = 0;
    int diskNum = 0;
    for (Path root : FileSystems.getDefault().getRootDirectories()) {
        try {
            FileStore store = Files.getFileStore(root);
            model.append("Disk ").append(diskNum++).append(":(avail=").append(getCount(store.getUsableSpace(), true))
                    .append(", total=").append(getCount(store.getTotalSpace(), true))
                    .append(") ");
            totalDiskSpace += store.getTotalSpace();
        } catch (IOException e) {
            //
        }
    }

    StringWriter stringWriter = new StringWriter();
    throwable.printStackTrace(new PrintWriter(stringWriter));

    StackTraceElement[] stackTrace = throwable.getStackTrace();
    boolean pluginError = false;
    if (stackTrace.length > 0) {
        pluginError = !throwable.getStackTrace()[0].getClassName().startsWith("cn.nukkit");
    }


    File mdReport = new File(reports, date + "_" + throwable.getClass().getSimpleName() + ".md");
    mdReport.createNewFile();
    String content = Utils.readFile(this.getClass().getClassLoader().getResourceAsStream("report_template.md"));

    String cpuType = System.getenv("PROCESSOR_IDENTIFIER");
    OperatingSystemMXBean osMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
    content = content.replace("${NUKKIT_VERSION}", Nukkit.VERSION);
    content = content.replace("${JAVA_VERSION}", System.getProperty("java.vm.name") + " (" + System.getProperty("java.runtime.version") + ")");
    content = content.replace("${HOSTOS}", osMXBean.getName() + "-" + osMXBean.getArch() + " [" + osMXBean.getVersion() + "]");
    content = content.replace("${MEMORY}", getCount(osMXBean.getTotalPhysicalMemorySize(), true));
    content = content.replace("${STORAGE_SIZE}", getCount(totalDiskSpace, true));
    content = content.replace("${CPU_TYPE}", cpuType == null ? "UNKNOWN" : cpuType);
    content = content.replace("${AVAILABLE_CORE}", String.valueOf(osMXBean.getAvailableProcessors()));
    content = content.replace("${STACKTRACE}", stringWriter.toString());
    content = content.replace("${PLUGIN_ERROR}", Boolean.toString(pluginError).toUpperCase());
    content = content.replace("${STORAGE_TYPE}", model.toString());

    Utils.writeFile(mdReport, content);

    return mdReport.getAbsolutePath();
}
 
Example 14
Source File: BugReportGenerator.java    From Nukkit with GNU General Public License v3.0 4 votes vote down vote up
private String generate() throws IOException {
    File reports = new File(Nukkit.DATA_PATH, "logs/bug_reports");
    if (!reports.isDirectory()) {
        reports.mkdirs();
    }

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmSS");
    String date = simpleDateFormat.format(new Date());

    SystemInfo systemInfo = new SystemInfo();
    long totalDiskSize = 0;
    StringBuilder model = new StringBuilder();
    for (HWDiskStore hwDiskStore : systemInfo.getHardware().getDiskStores()) {
        totalDiskSize += hwDiskStore.getSize();
        if (!model.toString().contains(hwDiskStore.getModel())) {
            model.append(hwDiskStore.getModel()).append(" ");
        }
    }

    StringWriter stringWriter = new StringWriter();
    throwable.printStackTrace(new PrintWriter(stringWriter));


    File mdReport = new File(reports, date + "_" + throwable.getClass().getSimpleName() + ".md");
    mdReport.createNewFile();
    String content = Utils.readFile(this.getClass().getClassLoader().getResourceAsStream("report_template.md"));

    Properties properties = getGitRepositoryState();
    System.out.println(properties.getProperty("git.commit.id.abbrev"));
    String abbrev = properties.getProperty("git.commit.id.abbrev");

    content = content.replace("${NUKKIT_VERSION}", Nukkit.VERSION);
    content = content.replace("${GIT_COMMIT_ABBREV}", abbrev);
    content = content.replace("${JAVA_VERSION}", System.getProperty("java.vm.name") + " (" + System.getProperty("java.runtime.version") + ")");
    content = content.replace("${HOSTOS}", systemInfo.getOperatingSystem().getFamily() + " [" + systemInfo.getOperatingSystem().getVersion().getVersion() + "]");
    content = content.replace("${MEMORY}", getCount(systemInfo.getHardware().getMemory().getTotal(), true));
    content = content.replace("${STORAGE_SIZE}", getCount(totalDiskSize, true));
    content = content.replace("${CPU_TYPE}", systemInfo.getHardware().getProcessor().getName());
    content = content.replace("${PHYSICAL_CORE}", String.valueOf(systemInfo.getHardware().getProcessor().getPhysicalProcessorCount()));
    content = content.replace("${LOGICAL_CORE}", String.valueOf(systemInfo.getHardware().getProcessor().getLogicalProcessorCount()));
    content = content.replace("${STACKTRACE}", stringWriter.toString());
    content = content.replace("${PLUGIN_ERROR}", String.valueOf(!throwable.getStackTrace()[0].getClassName().startsWith("cn.nukkit")).toUpperCase());
    content = content.replace("${STORAGE_TYPE}", model.toString());

    Utils.writeFile(mdReport, content);

    return mdReport.getAbsolutePath();
}