Search in sources :

Example 6 with Configuration

use of org.pepsoft.worldpainter.Configuration in project WorldPainter by Captain-Chaos.

the class ScriptingTool method main.

public static void main(String[] args) throws IOException, ClassNotFoundException {
    // Initialise logging
    LoggerContext logContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    try {
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(logContext);
        logContext.reset();
        configurator.doConfigure(ClassLoader.getSystemResourceAsStream("logback-scriptingtool.xml"));
    } catch (JoranException e) {
    // StatusPrinter will handle this
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(logContext);
    System.err.println("WorldPainter scripting host version " + Version.VERSION + ".\n" + "Copyright 2011-2018 pepsoft.org, The Netherlands.\n" + "This is free software distributed under the terms of the GPL, version 3, a copy\n" + "of which you can find in the installation directory.\n");
    // Check arguments
    if (args.length < 1) {
        System.err.println("Usage:\n" + "\n" + "    wpscript <scriptfile> [<scriptarg> ...]\n" + "\n" + "Where <scriptfile> is the filename, including extension, of the script to\n" + "execute, and [<scriptarg> ...] an optional list of one or more arguments for\n" + "the script, which will be available to the script in the arguments (from index\n" + "0) or argv (from index 1) array.");
        System.exit(1);
    }
    // Load script
    File scriptFile = new File(args[0]);
    if (!scriptFile.isFile()) {
        System.err.println(args[0] + " does not exist or is not a regular file");
        System.exit(1);
    }
    String scriptFileName = scriptFile.getName();
    int p = scriptFileName.lastIndexOf('.');
    if (p == -1) {
        System.err.println("Script file name " + scriptFileName + " has no extension");
        System.exit(1);
    }
    String extension = scriptFileName.substring(p + 1);
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    ScriptEngine scriptEngine = scriptEngineManager.getEngineByExtension(extension);
    if (scriptEngine == null) {
        System.err.println("Script file language " + extension + " not supported");
        System.exit(1);
    }
    scriptEngine.put(ScriptEngine.FILENAME, scriptFileName);
    // Initialise WorldPainter configuration
    Configuration config = Configuration.load();
    if (config == null) {
        logger.info("Creating new configuration");
        config = new Configuration();
    }
    Configuration.setInstance(config);
    // Load trusted WorldPainter root certificate
    X509Certificate trustedCert = null;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        trustedCert = (X509Certificate) certificateFactory.generateCertificate(ClassLoader.getSystemResourceAsStream("wproot.pem"));
    } catch (CertificateException e) {
        logger.error("Certificate exception while loading trusted root certificate", e);
    }
    // Load the plugins
    if (trustedCert != null) {
        File pluginsDir = new File(Configuration.getConfigDir(), "plugins");
        if (pluginsDir.isDirectory()) {
            PluginManager.loadPlugins(pluginsDir, trustedCert.getPublicKey());
        }
    } else {
        logger.error("Trusted root certificate not available; not loading plugins");
    }
    WPPluginManager.initialise(config.getUuid());
    if (args.length > 1) {
        System.err.print("Executing script \"" + scriptFileName + "\" with arguments ");
        for (int i = 1; i < args.length; i++) {
            if (i > 1) {
                System.err.print(", ");
            }
            System.err.print("\"" + args[i] + "\"");
        }
        System.err.println("\n");
    } else {
        System.err.println("Executing script \"" + scriptFileName + "\" with no arguments.\n");
    }
    // Parse arguments
    List<String> argList = new ArrayList<>();
    Map<String, String> paramMap = new HashMap<>();
    for (String arg : args) {
        if (arg.startsWith("--") && (arg.length() > 2) && (arg.charAt(2) != '-')) {
            p = arg.indexOf('=');
            if (p != -1) {
                String key = arg.substring(2, p);
                String value = arg.substring(p + 1);
                paramMap.put(key, value);
            } else {
                paramMap.put(arg.substring(2), "true");
            }
        } else if (arg.startsWith("-") && (arg.length() > 1) && (arg.charAt(1) != '-')) {
            for (int i = 1; i < arg.length(); i++) {
                paramMap.put(arg.substring(i, i + 1), "true");
            }
        } else {
            argList.add(arg);
        }
    }
    // Initialise script context
    ScriptingContext context = new ScriptingContext(true);
    Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("wp", context);
    String[] argArray = argList.toArray(new String[argList.size()]);
    bindings.put("argc", argArray.length);
    bindings.put("argv", argArray);
    String[] scriptArgs = new String[argArray.length - 1];
    System.arraycopy(argArray, 1, scriptArgs, 0, scriptArgs.length);
    bindings.put("arguments", scriptArgs);
    bindings.put("params", paramMap);
    // Execute script
    try {
        scriptEngine.eval(new FileReader(scriptFile));
        // Check that go() was invoked on the last operation:
        context.checkGoCalled(null);
    } catch (RuntimeException e) {
        logger.error(e.getClass().getSimpleName() + " occurred while executing " + scriptFileName, e);
        System.exit(2);
    } catch (ScriptException e) {
        logger.error("ScriptException occurred while executing " + scriptFileName, e);
        System.exit(2);
    }
}
Also used : Configuration(org.pepsoft.worldpainter.Configuration) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) LoggerContext(ch.qos.logback.classic.LoggerContext) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) JoranException(ch.qos.logback.core.joran.spi.JoranException) JoranConfigurator(ch.qos.logback.classic.joran.JoranConfigurator) ScriptingContext(org.pepsoft.worldpainter.tools.scripts.ScriptingContext) FileReader(java.io.FileReader) File(java.io.File)

Example 7 with Configuration

use of org.pepsoft.worldpainter.Configuration in project WorldPainter by Captain-Chaos.

the class LargeContinentFinder method main.

public static void main(String[] args) throws IOException, ClassNotFoundException {
    Configuration config = Configuration.load();
    if (config == null) {
        config = new Configuration();
    }
    Configuration.setInstance(config);
    final BiomeScheme biomeScheme = BiomeSchemeManager.getSharedBiomeScheme(BIOME_ALGORITHM_1_7_LARGE);
    if (biomeScheme == null) {
        System.err.println("Can't continue without a Minecraft 1.7 - 1.10 minecraft.jar");
        System.exit(1);
    }
    long seed = 0;
    final int[] biomes = new int[TILE_SIZE * TILE_SIZE];
    final SortedSet<World> largeContinentWorlds = new TreeSet<>();
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            largeContinentWorlds.forEach(System.out::println);
        }
    });
    while (true) {
        // System.out.println("***");
        // System.out.println("*** Seed " + seed + " ***");
        // System.out.println("***");
        // System.out.print('.');
        biomeScheme.setSeed(seed);
        int continentTilesFound = visitTilesInSpiral((x, z) -> {
            // System.out.println("Visiting " + x + ", " + z);
            biomeScheme.getBiomes(x * TILE_SIZE, z * TILE_SIZE, TILE_SIZE, TILE_SIZE, biomes);
            for (int biome : biomes) {
                if ((biome == BIOME_OCEAN) || (biome == BIOME_DEEP_OCEAN)) {
                    return false;
                }
            }
            return true;
        });
        if (largeContinentWorlds.isEmpty() || (continentTilesFound > largeContinentWorlds.first().continentTiles)) {
            if (largeContinentWorlds.size() > 100) {
                largeContinentWorlds.remove(largeContinentWorlds.first());
            }
            largeContinentWorlds.add(new World(seed, continentTilesFound));
        }
        seed++;
        if ((seed % 100L) == 0) {
            System.out.println("Results after " + seed + " seeds:");
            for (World world : largeContinentWorlds) {
                System.out.println("    " + world);
            }
        }
    }
}
Also used : Configuration(org.pepsoft.worldpainter.Configuration) TreeSet(java.util.TreeSet) BiomeScheme(org.pepsoft.worldpainter.BiomeScheme) Minecraft1_7BiomeScheme(org.pepsoft.worldpainter.biomeschemes.Minecraft1_7BiomeScheme)

Example 8 with Configuration

use of org.pepsoft.worldpainter.Configuration in project WorldPainter by Captain-Chaos.

the class RespawnPlayerDialog method respawn.

private void respawn() {
    try {
        File file = new File(jTextField1.getText());
        RespawnPlayer.respawnPlayer(file);
        Configuration config = Configuration.getInstance();
        if (config != null) {
            config.setSavesDirectory(file.getParentFile().getParentFile());
        }
        JOptionPane.showMessageDialog(this, "Player respawned");
        dispose();
    } catch (IOException e) {
        throw new RuntimeException("I/O error while reading or writing level.dat", e);
    }
}
Also used : Configuration(org.pepsoft.worldpainter.Configuration) IOException(java.io.IOException) File(java.io.File)

Example 9 with Configuration

use of org.pepsoft.worldpainter.Configuration in project WorldPainter by Captain-Chaos.

the class RegressionIT method init.

@BeforeClass
public static void init() {
    Configuration.setInstance(new Configuration());
    BiomeSchemeManager.initialiseInBackground();
}
Also used : Configuration(org.pepsoft.worldpainter.Configuration) BeforeClass(org.junit.BeforeClass)

Example 10 with Configuration

use of org.pepsoft.worldpainter.Configuration in project WorldPainter by Captain-Chaos.

the class SaveWorldOp method go.

@Override
public Void go() throws ScriptException {
    goCalled();
    // TODO: add .world if it is not there
    File file = new File(fileName);
    File dir = file.getAbsoluteFile().getParentFile();
    if (!dir.isDirectory()) {
        throw new ScriptException("Destination directory " + dir + " does not exist or is not a directory");
    }
    if (!dir.canWrite()) {
        throw new ScriptException("Access denied to destination directory " + dir);
    }
    try {
        Configuration config = Configuration.getInstance();
        if ((config.getWorldFileBackups() > 0) && file.isFile()) {
            for (int i = config.getWorldFileBackups(); i > 0; i--) {
                File nextBackupFile = (i > 1) ? BackupUtil.getBackupFile(file, i - 1) : file;
                if (nextBackupFile.isFile()) {
                    File backupFile = BackupUtil.getBackupFile(file, i);
                    if (backupFile.isFile()) {
                        if (!backupFile.delete()) {
                            throw new ScriptException("Could not delete old backup file " + backupFile);
                        }
                    }
                    if (!nextBackupFile.renameTo(backupFile)) {
                        throw new ScriptException("Could not move " + nextBackupFile + " to " + backupFile);
                    }
                }
            }
        }
        WorldIO worldIO = new WorldIO(world);
        worldIO.save(new FileOutputStream(file));
    } catch (IOException e) {
        throw new ScriptException("I/O error saving file (message: " + e.getMessage() + ")", e);
    }
    return null;
}
Also used : Configuration(org.pepsoft.worldpainter.Configuration) FileOutputStream(java.io.FileOutputStream) WorldIO(org.pepsoft.worldpainter.WorldIO) IOException(java.io.IOException) File(java.io.File)

Aggregations

Configuration (org.pepsoft.worldpainter.Configuration)12 File (java.io.File)7 IOException (java.io.IOException)4 CertificateException (java.security.cert.CertificateException)2 CertificateFactory (java.security.cert.CertificateFactory)2 X509Certificate (java.security.cert.X509Certificate)2 TreeSet (java.util.TreeSet)2 BiomeScheme (org.pepsoft.worldpainter.BiomeScheme)2 Minecraft1_7BiomeScheme (org.pepsoft.worldpainter.biomeschemes.Minecraft1_7BiomeScheme)2 LoggerContext (ch.qos.logback.classic.LoggerContext)1 JoranConfigurator (ch.qos.logback.classic.joran.JoranConfigurator)1 JoranException (ch.qos.logback.core.joran.spi.JoranException)1 MouseEvent (java.awt.event.MouseEvent)1 FileOutputStream (java.io.FileOutputStream)1 FileReader (java.io.FileReader)1 KeyManagementException (java.security.KeyManagementException)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 SecureRandom (java.security.SecureRandom)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1