Merge remote-tracking branch 'remotes/pull_117/multiworld-snapshots'

This commit is contained in:
hretsam 2011-08-05 12:29:49 +02:00
commit 990915b23f
17 changed files with 391 additions and 279 deletions

View File

@ -19,11 +19,11 @@
package com.sk89q.worldedit; package com.sk89q.worldedit;
import com.sk89q.worldedit.snapshots.SnapshotRepository;
import java.io.File; import java.io.File;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
import com.sk89q.worldedit.snapshots.SnapshotRepository;
/** /**
* Represents WorldEdit's configuration. * Represents WorldEdit's configuration.

View File

@ -34,6 +34,13 @@ public abstract class LocalWorld {
* Random generator. * Random generator.
*/ */
protected Random random = new Random(); protected Random random = new Random();
/**
* Get the name of the world.
*
* @return
*/
public abstract String getName();
/** /**
* Set block type. * Set block type.

View File

@ -86,10 +86,8 @@ public class BukkitConfiguration extends LocalConfiguration {
LocalSession.EXPIRATION_GRACE = config.getInt("history.expiration", 10) * 60 * 1000; LocalSession.EXPIRATION_GRACE = config.getInt("history.expiration", 10) * 60 * 1000;
String snapshotsDir = config.getString("snapshots.directory", ""); String snapshotsDir = config.getString("snapshots.directory", "");
if (!snapshotsDir.trim().equals("")) { if (!snapshotsDir.isEmpty()){
snapshotRepo = new SnapshotRepository(snapshotsDir); snapshotRepo = new SnapshotRepository(snapshotsDir);
} else {
snapshotRepo = null;
} }
String type = config.getString("shell-save-type", "").trim(); String type = config.getString("shell-save-type", "").trim();

View File

@ -69,6 +69,15 @@ public class BukkitWorld extends LocalWorld {
public World getWorld() { public World getWorld() {
return world; return world;
} }
/**
* Get the name of the world
*
* @return
*/
public String getName() {
return world.getName();
}
/** /**
* Set block type. * Set block type.

View File

@ -15,8 +15,7 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.commands; package com.sk89q.worldedit.commands;
import java.io.File; import java.io.File;
@ -30,6 +29,7 @@ import com.sk89q.minecraft.util.commands.Command;
import com.sk89q.minecraft.util.commands.CommandContext; import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandPermissions; import com.sk89q.minecraft.util.commands.CommandPermissions;
import com.sk89q.worldedit.*; import com.sk89q.worldedit.*;
import com.sk89q.worldedit.data.MissingWorldException;
import com.sk89q.worldedit.snapshots.InvalidSnapshotException; import com.sk89q.worldedit.snapshots.InvalidSnapshotException;
import com.sk89q.worldedit.snapshots.Snapshot; import com.sk89q.worldedit.snapshots.Snapshot;
@ -39,69 +39,72 @@ import com.sk89q.worldedit.snapshots.Snapshot;
* @author sk89q * @author sk89q
*/ */
public class SnapshotCommands { public class SnapshotCommands {
private static Logger logger = Logger.getLogger("Minecraft.WorldEdit"); private static Logger logger = Logger.getLogger("Minecraft.WorldEdit");
private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
@Command( @Command(aliases = {"list"},
aliases = {"list"}, usage = "[num]",
usage = "[num]", desc = "List snapshots",
desc = "List snapshots", min = 0,
min = 0, max = 1)
max = 1
)
@CommandPermissions({"worldedit.snapshots.list"}) @CommandPermissions({"worldedit.snapshots.list"})
public static void list(CommandContext args, WorldEdit we, public static void list(CommandContext args, WorldEdit we,
LocalSession session, LocalPlayer player, EditSession editSession) LocalSession session, LocalPlayer player, EditSession editSession)
throws WorldEditException { throws WorldEditException {
LocalConfiguration config = we.getConfiguration();
int num = args.argsLength() > 0 ?
Math.min(40, Math.max(5, args.getInteger(0))) : 5;
if (config.snapshotRepo != null) { LocalConfiguration config = we.getConfiguration();
List<Snapshot> snapshots = config.snapshotRepo.getSnapshots(true);
if (config.snapshotRepo == null) {
player.printError("Snapshot/backup restore is not configured.");
return;
}
try {
List<Snapshot> snapshots = config.snapshotRepo.getSnapshots(true, player.getWorld().getName());
if (snapshots.size() > 0) { if (snapshots.size() > 0) {
for (byte i = 0; i < Math.min(num, snapshots.size()); ++i) {
int num = args.argsLength() > 0 ? Math.min(40, Math.max(5, args.getInteger(0))) : 5;
player.print("Snapshots for world: '" + player.getWorld().getName() + "'");
for (byte i = 0; i < Math.min(num, snapshots.size()); i++) {
player.print((i + 1) + ". " + snapshots.get(i).getName()); player.print((i + 1) + ". " + snapshots.get(i).getName());
} }
player.print("Use /snap use [snapshot] or /snap use latest."); player.print("Use /snap use [snapshot] or /snap use latest.");
} else { } else {
player.printError("No snapshots are available. See console for details."); player.printError("No snapshots are available. See console for details.");
// Okay, let's toss some debugging information! // Okay, let's toss some debugging information!
File dir = config.snapshotRepo.getDirectory(); File dir = config.snapshotRepo.getDirectory();
try { try {
logger.info("WorldEdit found no snapshots: looked in: " + logger.info("WorldEdit found no snapshots: looked in: "
dir.getCanonicalPath()); + dir.getCanonicalPath());
} catch (IOException e) { } catch (IOException e) {
logger.info("WorldEdit found no snapshots: looked in " logger.info("WorldEdit found no snapshots: looked in "
+ "(NON-RESOLVABLE PATH - does it exist?): " + + "(NON-RESOLVABLE PATH - does it exist?): "
dir.getPath()); + dir.getPath());
} }
} }
} else { } catch (MissingWorldException ex) {
player.printError("Snapshot/backup restore is not configured."); player.printError("No snapshots were found for this world.");
} }
} }
@Command( @Command(aliases = {"use"},
aliases = {"use"}, usage = "<snapshot>",
usage = "<snapshot>", desc = "Choose a snapshot to use",
desc = "Choose a snapshot to use", min = 1,
min = 1, max = 1)
max = 1
)
@CommandPermissions({"worldedit.snapshots.restore"}) @CommandPermissions({"worldedit.snapshots.restore"})
public static void use(CommandContext args, WorldEdit we, public static void use(CommandContext args, WorldEdit we,
LocalSession session, LocalPlayer player, EditSession editSession) LocalSession session, LocalPlayer player, EditSession editSession)
throws WorldEditException { throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
if (config.snapshotRepo == null) { if (config.snapshotRepo == null) {
player.printError("Snapshot/backup restore is not configured."); player.printError("Snapshot/backup restore is not configured.");
return; return;
@ -111,13 +114,17 @@ public class SnapshotCommands {
// Want the latest snapshot? // Want the latest snapshot?
if (name.equalsIgnoreCase("latest")) { if (name.equalsIgnoreCase("latest")) {
Snapshot snapshot = config.snapshotRepo.getDefaultSnapshot(); try {
Snapshot snapshot = config.snapshotRepo.getDefaultSnapshot(player.getWorld().getName());
if (snapshot != null) { if (snapshot != null) {
session.setSnapshot(null); session.setSnapshot(null);
player.print("Now using newest snapshot."); player.print("Now using newest snapshot.");
} else { } else {
player.printError("No snapshots were found."); player.printError("No snapshots were found.");
}
} catch (MissingWorldException ex) {
player.printError("No snapshots were found for this world.");
} }
} else { } else {
try { try {
@ -128,77 +135,80 @@ public class SnapshotCommands {
} }
} }
} }
@Command( @Command(aliases = {"before"},
aliases = {"before"}, usage = "<date>",
usage = "<date>", desc = "Choose the nearest snapshot before a date",
desc = "Choose the nearest snapshot before a date", min = 1,
min = 1, max = -1)
max = -1
)
@CommandPermissions({"worldedit.snapshots.restore"}) @CommandPermissions({"worldedit.snapshots.restore"})
public static void before(CommandContext args, WorldEdit we, public static void before(CommandContext args, WorldEdit we,
LocalSession session, LocalPlayer player, EditSession editSession) LocalSession session, LocalPlayer player, EditSession editSession)
throws WorldEditException { throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
if (config.snapshotRepo == null) { if (config.snapshotRepo == null) {
player.printError("Snapshot/backup restore is not configured."); player.printError("Snapshot/backup restore is not configured.");
return; return;
} }
Calendar date = session.detectDate(args.getJoinedStrings(0)); Calendar date = session.detectDate(args.getJoinedStrings(0));
if (date == null) { if (date == null) {
player.printError("Could not detect the date inputted."); player.printError("Could not detect the date inputted.");
} else { } else {
dateFormat.setTimeZone(session.getTimeZone()); try {
Snapshot snapshot = config.snapshotRepo.getSnapshotBefore(date, player.getWorld().getName());
Snapshot snapshot = config.snapshotRepo.getSnapshotBefore(date);
if (snapshot == null) { if (snapshot == null) {
player.printError("Couldn't find a snapshot before " dateFormat.setTimeZone(session.getTimeZone());
+ dateFormat.format(date.getTime()) + "."); player.printError("Couldn't find a snapshot before "
} else { + dateFormat.format(date.getTime()) + ".");
session.setSnapshot(snapshot); } else {
player.print("Snapshot set to: " + snapshot.getName()); session.setSnapshot(snapshot);
player.print("Snapshot set to: " + snapshot.getName());
}
} catch (MissingWorldException ex) {
player.printError("No snapshots were found for this world.");
} }
} }
} }
@Command( @Command(aliases = {"after"},
aliases = {"after"}, usage = "<date>",
usage = "<date>", desc = "Choose the nearest snapshot after a date",
desc = "Choose the nearest snapshot after a date", min = 1,
min = 1, max = -1)
max = -1
)
@CommandPermissions({"worldedit.snapshots.restore"}) @CommandPermissions({"worldedit.snapshots.restore"})
public static void after(CommandContext args, WorldEdit we, public static void after(CommandContext args, WorldEdit we,
LocalSession session, LocalPlayer player, EditSession editSession) LocalSession session, LocalPlayer player, EditSession editSession)
throws WorldEditException { throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
if (config.snapshotRepo == null) { if (config.snapshotRepo == null) {
player.printError("Snapshot/backup restore is not configured."); player.printError("Snapshot/backup restore is not configured.");
return; return;
} }
Calendar date = session.detectDate(args.getJoinedStrings(0)); Calendar date = session.detectDate(args.getJoinedStrings(0));
if (date == null) { if (date == null) {
player.printError("Could not detect the date inputted."); player.printError("Could not detect the date inputted.");
} else { } else {
dateFormat.setTimeZone(session.getTimeZone()); try {
Snapshot snapshot = config.snapshotRepo.getSnapshotAfter(date, player.getWorld().getName());
Snapshot snapshot = config.snapshotRepo.getSnapshotAfter(date); if (snapshot == null) {
if (snapshot == null) { dateFormat.setTimeZone(session.getTimeZone());
player.printError("Couldn't find a snapshot after " player.printError("Couldn't find a snapshot after "
+ dateFormat.format(date.getTime()) + "."); + dateFormat.format(date.getTime()) + ".");
} else { } else {
session.setSnapshot(snapshot); session.setSnapshot(snapshot);
player.print("Snapshot set to: " + snapshot.getName()); player.print("Snapshot set to: " + snapshot.getName());
}
} catch (MissingWorldException ex) {
player.printError("No snapshots were found for this world.");
} }
} }
} }

View File

@ -15,7 +15,7 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.commands; package com.sk89q.worldedit.commands;
@ -34,36 +34,34 @@ import com.sk89q.worldedit.WorldEdit;
import com.sk89q.worldedit.WorldEditException; import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.data.ChunkStore; import com.sk89q.worldedit.data.ChunkStore;
import com.sk89q.worldedit.data.DataException; import com.sk89q.worldedit.data.DataException;
import com.sk89q.worldedit.data.MissingWorldException;
import com.sk89q.worldedit.regions.Region; import com.sk89q.worldedit.regions.Region;
import com.sk89q.worldedit.snapshots.InvalidSnapshotException; import com.sk89q.worldedit.snapshots.InvalidSnapshotException;
import com.sk89q.worldedit.snapshots.Snapshot; import com.sk89q.worldedit.snapshots.Snapshot;
import com.sk89q.worldedit.snapshots.SnapshotRestore; import com.sk89q.worldedit.snapshots.SnapshotRestore;
public class SnapshotUtilCommands { public class SnapshotUtilCommands {
private static Logger logger = Logger.getLogger("Minecraft.WorldEdit"); private static Logger logger = Logger.getLogger("Minecraft.WorldEdit");
@Command( @Command(aliases = {"snapshot", "snap"},
aliases = {"snapshot", "snap"}, desc = "Snapshot commands")
desc = "Snapshot commands"
)
@NestedCommand({SnapshotCommands.class}) @NestedCommand({SnapshotCommands.class})
public static void snapshot(CommandContext args, WorldEdit we, public static void snapshot(CommandContext args, WorldEdit we,
LocalSession session, LocalPlayer player, EditSession editSession) LocalSession session, LocalPlayer player, EditSession editSession)
throws WorldEditException { throws WorldEditException {
} }
@Command( @Command(aliases = {"restore", "/restore"},
aliases = {"restore", "/restore"}, usage = "[snapshot]",
usage = "[snapshot]", desc = "Restore the selection from a snapshot",
desc = "Restore the selection from a snapshot", min = 0,
min = 0, max = 1)
max = 1
)
@CommandPermissions({"worldedit.snapshots.restore"}) @CommandPermissions({"worldedit.snapshots.restore"})
public static void restore(CommandContext args, WorldEdit we, public static void restore(CommandContext args, WorldEdit we,
LocalSession session, LocalPlayer player, EditSession editSession) LocalSession session, LocalPlayer player, EditSession editSession)
throws WorldEditException { throws WorldEditException {
LocalConfiguration config = we.getConfiguration(); LocalConfiguration config = we.getConfiguration();
if (config.snapshotRepo == null) { if (config.snapshotRepo == null) {
@ -84,32 +82,37 @@ public class SnapshotUtilCommands {
} else { } else {
snapshot = session.getSnapshot(); snapshot = session.getSnapshot();
} }
ChunkStore chunkStore = null;
// No snapshot set? // No snapshot set?
if (snapshot == null) { if (snapshot == null) {
snapshot = config.snapshotRepo.getDefaultSnapshot(); try {
snapshot = config.snapshotRepo.getDefaultSnapshot(player.getWorld().getName());
if (snapshot == null) { if (snapshot == null) {
player.printError("No snapshots were found. See console for details."); player.printError("No snapshots were found. See console for details.");
// Okay, let's toss some debugging information! // Okay, let's toss some debugging information!
File dir = config.snapshotRepo.getDirectory(); File dir = config.snapshotRepo.getDirectory();
try { try {
logger.info("WorldEdit found no snapshots: looked in: " + logger.info("WorldEdit found no snapshots: looked in: "
dir.getCanonicalPath()); + dir.getCanonicalPath());
} catch (IOException e) { } catch (IOException e) {
logger.info("WorldEdit found no snapshots: looked in " logger.info("WorldEdit found no snapshots: looked in "
+ "(NON-RESOLVABLE PATH - does it exist?): " + + "(NON-RESOLVABLE PATH - does it exist?): "
dir.getPath()); + dir.getPath());
}
return;
} }
} catch (MissingWorldException ex) {
player.printError("No snapshots were found for this world.");
return; return;
} }
} }
ChunkStore chunkStore = null;
// Load chunk store // Load chunk store
try { try {
chunkStore = snapshot.getChunkStore(); chunkStore = snapshot.getChunkStore();

View File

@ -50,7 +50,7 @@ public abstract class ChunkStore {
* @throws DataException * @throws DataException
* @throws IOException * @throws IOException
*/ */
public abstract CompoundTag getChunkTag(Vector2D pos) public abstract CompoundTag getChunkTag(Vector2D pos, String world)
throws DataException, IOException; throws DataException, IOException;
/** /**
@ -62,9 +62,9 @@ public abstract class ChunkStore {
* @throws IOException * @throws IOException
* @throws DataException * @throws DataException
*/ */
public Chunk getChunk(Vector2D pos) public Chunk getChunk(Vector2D pos, String world)
throws DataException, IOException { throws DataException, IOException {
return new Chunk(getChunkTag(pos)); return new Chunk(getChunkTag(pos, world));
} }
/** /**

View File

@ -42,13 +42,16 @@ public class FileMcRegionChunkStore extends McRegionChunkStore {
} }
@Override @Override
protected InputStream getInputStream(String name) throws IOException, protected InputStream getInputStream(String name, String world) throws IOException,
DataException { DataException {
String fileName = "region" + File.separator + name;
String file = "region" + File.separator + name; File file = new File(path, fileName);
if (!file.exists()) {
file = new File(path, "DIM-1" + File.separator + fileName);
}
try { try {
return new FileInputStream(new File(path, file)); return new FileInputStream(file);
} catch (FileNotFoundException e) { } catch (FileNotFoundException e) {
throw new MissingChunkException(); throw new MissingChunkException();
} }
@ -56,7 +59,8 @@ public class FileMcRegionChunkStore extends McRegionChunkStore {
@Override @Override
public boolean isValid() { public boolean isValid() {
return new File(path, "region").isDirectory(); return new File(path, "region").isDirectory() ||
new File(path, "DIM-1" + File.separator + "region").isDirectory();
} }
} }

View File

@ -74,7 +74,7 @@ public abstract class LegacyChunkStore extends ChunkStore {
* @throws IOException * @throws IOException
*/ */
@Override @Override
public CompoundTag getChunkTag(Vector2D pos) public CompoundTag getChunkTag(Vector2D pos, String world)
throws DataException, IOException { throws DataException, IOException {
int x = pos.getBlockX(); int x = pos.getBlockX();
int z = pos.getBlockZ(); int z = pos.getBlockZ();

View File

@ -46,7 +46,7 @@ public abstract class McRegionChunkStore extends ChunkStore {
return filename; return filename;
} }
protected McRegionReader getReader(Vector2D pos) throws DataException, IOException { protected McRegionReader getReader(Vector2D pos, String worldname) throws DataException, IOException {
String filename = getFilename(pos); String filename = getFilename(pos);
if (curFilename != null) { if (curFilename != null) {
if (curFilename.equals(filename)) { if (curFilename.equals(filename)) {
@ -58,17 +58,17 @@ public abstract class McRegionChunkStore extends ChunkStore {
} }
} }
} }
InputStream stream = getInputStream(filename); InputStream stream = getInputStream(filename, worldname);
cachedReader = new McRegionReader(stream); cachedReader = new McRegionReader(stream);
//curFilename = filename; //curFilename = filename;
return cachedReader; return cachedReader;
} }
@Override @Override
public CompoundTag getChunkTag(Vector2D pos) throws DataException, public CompoundTag getChunkTag(Vector2D pos, String worldname) throws DataException,
IOException { IOException {
McRegionReader reader = getReader(pos); McRegionReader reader = getReader(pos, worldname);
InputStream stream = reader.getChunkInputStream(pos); InputStream stream = reader.getChunkInputStream(pos);
NBTInputStream nbt = new NBTInputStream(stream); NBTInputStream nbt = new NBTInputStream(stream);
Tag tag; Tag tag;
@ -113,7 +113,7 @@ public abstract class McRegionChunkStore extends ChunkStore {
* @return * @return
* @throws IOException * @throws IOException
*/ */
protected abstract InputStream getInputStream(String name) protected abstract InputStream getInputStream(String name, String worldname)
throws IOException, DataException; throws IOException, DataException;

View File

@ -0,0 +1,54 @@
// $Id$
/*
* WorldEdit
* Copyright (C) 2010 sk89q <http://www.sk89q.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldedit.data;
/**
*
* @author sk89q
*/
public class MissingWorldException extends ChunkStoreException {
private static final long serialVersionUID = 6487395784195658467L;
private String worldname;
public MissingWorldException() {
super();
}
public MissingWorldException(String worldname) {
super();
this.worldname = worldname;
}
public MissingWorldException(String msg, String worldname) {
super(msg);
this.worldname = worldname;
}
/**
* Get name of the world in question. May be null if unknown.
*
* @return
*/
public String getWorldname() {
return worldname;
}
}

View File

@ -15,8 +15,7 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.data; package com.sk89q.worldedit.data;
import java.io.*; import java.io.*;
@ -32,6 +31,7 @@ import de.schlichtherle.util.zip.*;
* @author sk89q * @author sk89q
*/ */
public class TrueZipMcRegionChunkStore extends McRegionChunkStore { public class TrueZipMcRegionChunkStore extends McRegionChunkStore {
/** /**
* ZIP file. * ZIP file.
*/ */
@ -59,7 +59,7 @@ public class TrueZipMcRegionChunkStore extends McRegionChunkStore {
throws IOException, ZipException { throws IOException, ZipException {
this.zipFile = zipFile; this.zipFile = zipFile;
this.folder = folder; this.folder = folder;
zip = new ZipFile(zipFile); zip = new ZipFile(zipFile);
} }
@ -88,57 +88,49 @@ public class TrueZipMcRegionChunkStore extends McRegionChunkStore {
*/ */
@Override @Override
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected InputStream getInputStream(String name) protected InputStream getInputStream(String name, String worldname)
throws IOException, DataException { throws IOException, DataException {
String file = "region/" + name;
// Detect subfolder for the world's files // Detect subfolder for the world's files
if (folder != null) { if (folder != null) {
if (!folder.equals("")) { if (!folder.equals("")) {
file = folder + "/" + file; name = folder + "/" + name;
} }
} else { } else {
ZipEntry testEntry = zip.getEntry("level.dat"); Pattern pattern = Pattern.compile(".*\\.mcr$");
// World pattern
// So, the data is not in the root directory Pattern worldPattern = Pattern.compile(worldname + "\\$");
if (testEntry == null) { for (Enumeration<? extends ZipEntry> e = zip.entries();
// Let's try a world/ sub-directory e.hasMoreElements();) {
testEntry = getEntry("world/level.dat"); ZipEntry testEntry = (ZipEntry) e.nextElement();
// Check for world
Pattern pattern = Pattern.compile(".*[\\\\/]level\\.dat$"); if (worldPattern.matcher(worldname).matches()) {
// Check for file
// So not there either... if (pattern.matcher(testEntry.getName()).matches()) {
if (testEntry == null) { folder = testEntry.getName().substring(0, testEntry.getName().lastIndexOf("/"));
for (Enumeration<? extends ZipEntry> e = zip.entries(); name = folder + "/" + name;
e.hasMoreElements(); ) { break;
testEntry = e.nextElement();
// Whoo, found level.dat!
if (pattern.matcher(testEntry.getName()).matches()) {
folder = testEntry.getName().replaceAll("level\\.dat$", "");
folder = folder.substring(0, folder.length() - 1);
file = folder + file;
break;
}
} }
} else {
file = "world/" + file;
} }
} }
// Check if world is found
if (folder == null) {
throw new MissingWorldException("Target world is not present in ZIP.", worldname);
}
} }
ZipEntry entry = getEntry(file); ZipEntry entry = getEntry(name);
if (entry == null) { if (entry == null) {
throw new MissingChunkException(); throw new MissingChunkException();
} }
try { try {
return zip.getInputStream(entry); return zip.getInputStream(entry);
} catch (ZipException e) { } catch (ZipException e) {
throw new IOException("Failed to read " + file + " in ZIP"); throw new IOException("Failed to read " + name + " in ZIP");
} }
} }
/** /**
* Get an entry from the ZIP, trying both types of slashes. * Get an entry from the ZIP, trying both types of slashes.
* *
@ -167,15 +159,15 @@ public class TrueZipMcRegionChunkStore extends McRegionChunkStore {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public boolean isValid() { public boolean isValid() {
for (Enumeration<? extends ZipEntry> e = zip.entries(); for (Enumeration<? extends ZipEntry> e = zip.entries();
e.hasMoreElements(); ) { e.hasMoreElements();) {
ZipEntry testEntry = e.nextElement(); ZipEntry testEntry = e.nextElement();
if (testEntry.getName().matches(".*\\.mcr$")) { if (testEntry.getName().matches(".*\\.mcr$")) {
return true; return true;
} }
} }
return false; return false;
} }
} }

View File

@ -15,8 +15,7 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.data; package com.sk89q.worldedit.data;
import java.io.*; import java.io.*;
@ -30,6 +29,7 @@ import java.util.Enumeration;
* @author sk89q * @author sk89q
*/ */
public class ZippedMcRegionChunkStore extends McRegionChunkStore { public class ZippedMcRegionChunkStore extends McRegionChunkStore {
/** /**
* ZIP file. * ZIP file.
*/ */
@ -57,7 +57,7 @@ public class ZippedMcRegionChunkStore extends McRegionChunkStore {
throws IOException, ZipException { throws IOException, ZipException {
this.zipFile = zipFile; this.zipFile = zipFile;
this.folder = folder; this.folder = folder;
zip = new ZipFile(zipFile); zip = new ZipFile(zipFile);
} }
@ -85,57 +85,47 @@ public class ZippedMcRegionChunkStore extends McRegionChunkStore {
* @throws DataException * @throws DataException
*/ */
@Override @Override
protected InputStream getInputStream(String name) protected InputStream getInputStream(String name, String worldname)
throws IOException, DataException { throws IOException, DataException {
String file = "region/" + name;
// Detect subfolder for the world's files // Detect subfolder for the world's files
if (folder != null) { if (folder != null) {
if (!folder.equals("")) { if (!folder.equals("")) {
file = folder + "/" + file; name = folder + "/" + name;
} }
} else { } else {
ZipEntry testEntry = zip.getEntry("level.dat"); Pattern pattern = Pattern.compile(".*\\.mcr$");
for (Enumeration<? extends ZipEntry> e = zip.entries();
// So, the data is not in the root directory e.hasMoreElements();) {
if (testEntry == null) { ZipEntry testEntry = (ZipEntry) e.nextElement();
// Let's try a world/ sub-directory // Check for world
testEntry = getEntry("world/level.dat"); if (testEntry.getName().startsWith(worldname + "/")) {
if (pattern.matcher(testEntry.getName()).matches()) {
Pattern pattern = Pattern.compile(".*[\\\\/]level\\.dat$"); folder = testEntry.getName().substring(0, testEntry.getName().lastIndexOf("/"));
name = folder + "/" + name;
// So not there either... break;
if (testEntry == null) {
for (Enumeration<? extends ZipEntry> e = zip.entries();
e.hasMoreElements(); ) {
testEntry = (ZipEntry)e.nextElement();
// Whoo, found level.dat!
if (pattern.matcher(testEntry.getName()).matches()) {
folder = testEntry.getName().replaceAll("level\\.dat$", "");
folder = folder.substring(0, folder.length() - 1);
file = folder + file;
break;
}
} }
} else {
file = "world/" + file;
} }
} }
// Check if world is found
if (folder == null) {
throw new MissingWorldException("Target world is not present in ZIP.", worldname);
}
} }
ZipEntry entry = getEntry(file); ZipEntry entry = getEntry(name);
if (entry == null) { if (entry == null) {
throw new MissingChunkException(); throw new MissingChunkException();
} }
try { try {
return zip.getInputStream(entry); return zip.getInputStream(entry);
} catch (ZipException e) { } catch (ZipException e) {
throw new IOException("Failed to read " + file + " in ZIP"); throw new IOException("Failed to read " + name + " in ZIP");
} }
} }
/** /**
* Get an entry from the ZIP, trying both types of slashes. * Get an entry from the ZIP, trying both types of slashes.
* *
@ -163,15 +153,15 @@ public class ZippedMcRegionChunkStore extends McRegionChunkStore {
@Override @Override
public boolean isValid() { public boolean isValid() {
for (Enumeration<? extends ZipEntry> e = zip.entries(); for (Enumeration<? extends ZipEntry> e = zip.entries();
e.hasMoreElements(); ) { e.hasMoreElements();) {
ZipEntry testEntry = e.nextElement(); ZipEntry testEntry = e.nextElement();
if (testEntry.getName().matches(".*\\.mcr$")) { if (testEntry.getName().matches(".*\\.mcr$")) {
return true; return true;
} }
} }
return false; return false;
} }
} }

View File

@ -15,22 +15,22 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.snapshots; package com.sk89q.worldedit.snapshots;
import com.sk89q.worldedit.data.*; import com.sk89q.worldedit.data.*;
import java.io.*; import java.io.*;
import java.util.Calendar; import java.util.Calendar;
import java.util.logging.Logger; import java.util.logging.Logger;
import java.util.zip.ZipFile;
/** /**
* *
* @author sk89q * @author sk89q
*/ */
public class Snapshot implements Comparable<Snapshot> { public class Snapshot implements Comparable<Snapshot> {
protected static Logger logger = Logger.getLogger("Minecraft.WorldEdit"); protected static Logger logger = Logger.getLogger("Minecraft.WorldEdit");
/** /**
* Stores snapshot file. * Stores snapshot file.
*/ */
@ -64,10 +64,10 @@ public class Snapshot implements Comparable<Snapshot> {
*/ */
public ChunkStore getChunkStore() throws IOException, DataException { public ChunkStore getChunkStore() throws IOException, DataException {
ChunkStore chunkStore = _getChunkStore(); ChunkStore chunkStore = _getChunkStore();
logger.info("WorldEdit: Using " + chunkStore.getClass().getCanonicalName() logger.info("WorldEdit: Using " + chunkStore.getClass().getCanonicalName()
+ " for loading snapshot '" + file.getAbsolutePath() + "'"); + " for loading snapshot '" + file.getAbsolutePath() + "'");
return chunkStore; return chunkStore;
} }
@ -82,19 +82,19 @@ public class Snapshot implements Comparable<Snapshot> {
if (file.getName().toLowerCase().endsWith(".zip")) { if (file.getName().toLowerCase().endsWith(".zip")) {
try { try {
ChunkStore chunkStore = new TrueZipMcRegionChunkStore(file); ChunkStore chunkStore = new TrueZipMcRegionChunkStore(file);
if (!chunkStore.isValid()) { if (!chunkStore.isValid()) {
return new TrueZipLegacyChunkStore(file); return new TrueZipLegacyChunkStore(file);
} }
return chunkStore; return chunkStore;
} catch (NoClassDefFoundError e) { } catch (NoClassDefFoundError e) {
ChunkStore chunkStore = new ZippedMcRegionChunkStore(file); ChunkStore chunkStore = new ZippedMcRegionChunkStore(file);
if (!chunkStore.isValid()) { if (!chunkStore.isValid()) {
return new ZippedLegacyChunkStore(file); return new ZippedLegacyChunkStore(file);
} }
return chunkStore; return chunkStore;
} }
} else if (file.getName().toLowerCase().endsWith(".tar.bz2") } else if (file.getName().toLowerCase().endsWith(".tar.bz2")
@ -102,26 +102,60 @@ public class Snapshot implements Comparable<Snapshot> {
|| file.getName().toLowerCase().endsWith(".tar")) { || file.getName().toLowerCase().endsWith(".tar")) {
try { try {
ChunkStore chunkStore = new TrueZipMcRegionChunkStore(file); ChunkStore chunkStore = new TrueZipMcRegionChunkStore(file);
if (!chunkStore.isValid()) { if (!chunkStore.isValid()) {
return new TrueZipLegacyChunkStore(file); return new TrueZipLegacyChunkStore(file);
} }
return chunkStore; return chunkStore;
} catch (NoClassDefFoundError e) { } catch (NoClassDefFoundError e) {
throw new DataException("TrueZIP is required for .tar support"); throw new DataException("TrueZIP is required for .tar support");
} }
} else { } else {
ChunkStore chunkStore = new FileMcRegionChunkStore(file); ChunkStore chunkStore = new FileMcRegionChunkStore(file);
if (!chunkStore.isValid()) { if (!chunkStore.isValid()) {
return new FileLegacyChunkStore(file); return new FileLegacyChunkStore(file);
} }
return chunkStore; return chunkStore;
} }
} }
/**
* Check the zip/tar file it contains the given world.
*
* @return true if the zip/tar file contains the given world
*/
public boolean containsWorld(String worldname) {
try {
if (file.getName().toLowerCase().endsWith(".zip")) {
ZipFile entry = new ZipFile(file);
return entry.getEntry(worldname) != null;
} else if (file.getName().toLowerCase().endsWith(".tar.bz2")
|| file.getName().toLowerCase().endsWith(".tar.gz")
|| file.getName().toLowerCase().endsWith(".tar")) {
try {
de.schlichtherle.util.zip.ZipFile entry = new de.schlichtherle.util.zip.ZipFile(file);
return entry.getEntry(worldname) != null;
} catch (NoClassDefFoundError e) {
throw new DataException("TrueZIP is required for .tar support");
}
} else {
return (file.getName().equalsIgnoreCase(worldname));
}
} catch (IOException ex) {
// Skip the file, but print an error
logger.info("Could not load snapshot: "
+ file.getPath());
} catch (DataException ex) {
// No truezip, so tar file not supported.
// Dont print, just skip the file.
}
return false;
}
/** /**
* Get the snapshot's name. * Get the snapshot's name.
* *
@ -130,7 +164,7 @@ public class Snapshot implements Comparable<Snapshot> {
public String getName() { public String getName() {
return name; return name;
} }
/** /**
* Get the file for the snapshot. * Get the file for the snapshot.
* *
@ -139,7 +173,7 @@ public class Snapshot implements Comparable<Snapshot> {
public File getFile() { public File getFile() {
return file; return file;
} }
/** /**
* Get the date associated with this snapshot. * Get the date associated with this snapshot.
* *
@ -148,7 +182,7 @@ public class Snapshot implements Comparable<Snapshot> {
public Calendar getDate() { public Calendar getDate() {
return date; return date;
} }
/** /**
* Set the date of the snapshot. * Set the date of the snapshot.
* *
@ -160,12 +194,14 @@ public class Snapshot implements Comparable<Snapshot> {
public int compareTo(Snapshot o) { public int compareTo(Snapshot o) {
if (o.date == null || date == null) { if (o.date == null || date == null) {
return name.compareTo(o.name); // Remove the folder from the name
int i = name.indexOf("/"), j = o.name.indexOf("/");
return name.substring((i > 0 ? 0 : i)).compareTo(o.name.substring((j > 0 ? 0 : j)));
} else { } else {
return date.compareTo(o.date); return date.compareTo(o.date);
} }
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (o instanceof Snapshot) { if (o instanceof Snapshot) {

View File

@ -15,10 +15,10 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.snapshots; package com.sk89q.worldedit.snapshots;
import com.sk89q.worldedit.data.MissingWorldException;
import java.io.*; import java.io.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
@ -30,16 +30,15 @@ import java.util.List;
* @author sk89q * @author sk89q
*/ */
public class SnapshotRepository { public class SnapshotRepository {
/** /**
* Stores the directory the snapshots come from. * Stores the directory the snapshots come from.
*/ */
protected File dir; protected File dir;
/** /**
* List of date parsers. * List of date parsers.
*/ */
protected List<SnapshotDateParser> dateParsers protected List<SnapshotDateParser> dateParsers = new ArrayList<SnapshotDateParser>();
= new ArrayList<SnapshotDateParser>();
/** /**
* Create a new instance of a repository. * Create a new instance of a repository.
@ -48,6 +47,8 @@ public class SnapshotRepository {
*/ */
public SnapshotRepository(File dir) { public SnapshotRepository(File dir) {
this.dir = dir; this.dir = dir;
// If folder dont exist, make it.
dir.mkdirs();
dateParsers.add(new YYMMDDHHIISSParser()); dateParsers.add(new YYMMDDHHIISSParser());
dateParsers.add(new ModificationTimerParser()); dateParsers.add(new ModificationTimerParser());
@ -69,7 +70,7 @@ public class SnapshotRepository {
* @param newestFirst * @param newestFirst
* @return * @return
*/ */
public List<Snapshot> getSnapshots(boolean newestFirst) { public List<Snapshot> getSnapshots(boolean newestFirst, String worldname) throws MissingWorldException {
FilenameFilter filter = new FilenameFilter() { FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) { public boolean accept(File dir, String name) {
File f = new File(dir, name); File f = new File(dir, name);
@ -77,13 +78,23 @@ public class SnapshotRepository {
} }
}; };
String[] snapshotNames = dir.list(filter); File[] snapshotFiles = dir.listFiles();
List<Snapshot> list = new ArrayList<Snapshot>(snapshotNames.length); List<Snapshot> list = new ArrayList<Snapshot>(snapshotFiles.length);
for (String name : snapshotNames) { for (File file : snapshotFiles) {
Snapshot snapshot = new Snapshot(this, name); if (isValidSnapshot(file)) {
detectDate(snapshot); Snapshot snapshot = new Snapshot(this, file.getName());
list.add(snapshot); if (snapshot.containsWorld(worldname)) {
detectDate(snapshot);
list.add(snapshot);
}
} else if (file.isDirectory() && file.getName().equalsIgnoreCase(worldname)) {
for (String name : file.list(filter)) {
Snapshot snapshot = new Snapshot(this, file.getName() + "/" + name);
detectDate(snapshot);
list.add(snapshot);
}
}
} }
if (newestFirst) { if (newestFirst) {
@ -94,50 +105,50 @@ public class SnapshotRepository {
return list; return list;
} }
/** /**
* Get the first snapshot after a date. * Get the first snapshot after a date.
* *
* @param date * @param date
* @return * @return
*/ */
public Snapshot getSnapshotAfter(Calendar date) { public Snapshot getSnapshotAfter(Calendar date, String world) throws MissingWorldException {
List<Snapshot> snapshots = getSnapshots(true); List<Snapshot> snapshots = getSnapshots(true, world);
Snapshot last = null; Snapshot last = null;
for (Snapshot snapshot : snapshots) { for (Snapshot snapshot : snapshots) {
if (snapshot.getDate() != null if (snapshot.getDate() != null
&& snapshot.getDate().before(date)) { && snapshot.getDate().before(date)) {
return last; return last;
} }
last = snapshot; last = snapshot;
} }
return last; return last;
} }
/** /**
* Get the first snapshot before a date. * Get the first snapshot before a date.
* *
* @param date * @param date
* @return * @return
*/ */
public Snapshot getSnapshotBefore(Calendar date) { public Snapshot getSnapshotBefore(Calendar date, String world) throws MissingWorldException {
List<Snapshot> snapshots = getSnapshots(false); List<Snapshot> snapshots = getSnapshots(false, world);
Snapshot last = null; Snapshot last = null;
for (Snapshot snapshot : snapshots) { for (Snapshot snapshot : snapshots) {
if (snapshot.getDate().after(date)) { if (snapshot.getDate().after(date)) {
return last; return last;
} }
last = snapshot; last = snapshot;
} }
return last; return last;
} }
/** /**
* Attempt to detect a snapshot's date and assign it. * Attempt to detect a snapshot's date and assign it.
* *
@ -151,7 +162,7 @@ public class SnapshotRepository {
return; return;
} }
} }
snapshot.setDate(null); snapshot.setDate(null);
} }
@ -160,8 +171,8 @@ public class SnapshotRepository {
* *
* @return * @return
*/ */
public Snapshot getDefaultSnapshot() { public Snapshot getDefaultSnapshot(String world) throws MissingWorldException {
List<Snapshot> snapshots = getSnapshots(true); List<Snapshot> snapshots = getSnapshots(true, world);
if (snapshots.size() == 0) { if (snapshots.size() == 0) {
return null; return null;
@ -186,18 +197,16 @@ public class SnapshotRepository {
* @param f * @param f
* @return whether it is a valid snapshot * @return whether it is a valid snapshot
*/ */
public boolean isValidSnapshot(File f) { protected boolean isValidSnapshot(File f) {
if (!f.getName().matches("^[A-Za-z0-9_\\- \\./\\\\'\\$@~!%\\^\\*\\(\\)\\[\\]\\+\\{\\},\\?]+$")) { if (!f.getName().matches("^[A-Za-z0-9_\\- \\./\\\\'\\$@~!%\\^\\*\\(\\)\\[\\]\\+\\{\\},\\?]+$")) {
return false; return false;
} }
return (f.isDirectory() && (new File(f, "level.dat")).exists()) return (f.isDirectory() && (new File(f, "level.dat")).exists())
|| (f.isFile() && ( || (f.isFile() && (f.getName().toLowerCase().endsWith(".zip")
f.getName().toLowerCase().endsWith(".zip") || f.getName().toLowerCase().endsWith(".tar.bz2")
|| f.getName().toLowerCase().endsWith(".tar.bz2") || f.getName().toLowerCase().endsWith(".tar.gz")
|| f.getName().toLowerCase().endsWith(".tar.gz") || f.getName().toLowerCase().endsWith(".tar")));
|| f.getName().toLowerCase().endsWith(".tar")
));
} }
/** /**

View File

@ -147,7 +147,7 @@ public class SnapshotRestore {
Chunk chunk; Chunk chunk;
try { try {
chunk = chunkStore.getChunk(chunkPos); chunk = chunkStore.getChunk(chunkPos, editSession.getWorld().getName());
// Good, the chunk could be at least loaded // Good, the chunk could be at least loaded
// Now just copy blocks! // Now just copy blocks!
@ -157,6 +157,9 @@ public class SnapshotRestore {
} }
} catch (MissingChunkException me) { } catch (MissingChunkException me) {
missingChunks.add(chunkPos); missingChunks.add(chunkPos);
} catch (MissingWorldException me) {
errorChunks.add(chunkPos);
lastErrorMessage = me.getMessage();
} catch (DataException de) { } catch (DataException de) {
errorChunks.add(chunkPos); errorChunks.add(chunkPos);
lastErrorMessage = de.getMessage(); lastErrorMessage = de.getMessage();

View File

@ -15,8 +15,7 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package com.sk89q.worldedit.util; package com.sk89q.worldedit.util;
import java.io.*; import java.io.*;
@ -35,9 +34,10 @@ import com.sk89q.worldedit.snapshots.SnapshotRepository;
* @author sk89q * @author sk89q
*/ */
public class PropertiesConfiguration extends LocalConfiguration { public class PropertiesConfiguration extends LocalConfiguration {
protected Properties properties; protected Properties properties;
protected File path; protected File path;
/** /**
* Construct the object. The configuration isn't loaded yet. * Construct the object. The configuration isn't loaded yet.
* *
@ -45,10 +45,10 @@ public class PropertiesConfiguration extends LocalConfiguration {
*/ */
public PropertiesConfiguration(File path) { public PropertiesConfiguration(File path) {
this.path = path; this.path = path;
properties = new Properties(); properties = new Properties();
} }
/** /**
* Load the configuration file. * Load the configuration file.
*/ */
@ -69,7 +69,7 @@ public class PropertiesConfiguration extends LocalConfiguration {
} }
} }
} }
profile = getBool("profile", profile); profile = getBool("profile", profile);
disallowedBlocks = getIntSet("disallowed-blocks", defaultDisallowedBlocks); disallowedBlocks = getIntSet("disallowed-blocks", defaultDisallowedBlocks);
defaultChangeLimit = getInt("default-max-changed-blocks", defaultChangeLimit); defaultChangeLimit = getInt("default-max-changed-blocks", defaultChangeLimit);
@ -89,16 +89,14 @@ public class PropertiesConfiguration extends LocalConfiguration {
navigationWand = getInt("nav-wand-item", navigationWand); navigationWand = getInt("nav-wand-item", navigationWand);
navigationWandMaxDistance = getInt("nav-wand-distance", navigationWandMaxDistance); navigationWandMaxDistance = getInt("nav-wand-distance", navigationWandMaxDistance);
scriptTimeout = getInt("scripting-timeout", scriptTimeout); scriptTimeout = getInt("scripting-timeout", scriptTimeout);
LocalSession.MAX_HISTORY_SIZE = Math.max(15, getInt("history-size", 15)); LocalSession.MAX_HISTORY_SIZE = Math.max(15, getInt("history-size", 15));
String snapshotsDir = getString("snapshots-dir", ""); String snapshotsDir = getString("snapshots-dir", "");
if (!snapshotsDir.trim().equals("")) { if (!snapshotsDir.isEmpty()) {
snapshotRepo = new SnapshotRepository(snapshotsDir); snapshotRepo = new SnapshotRepository(snapshotsDir);
} else {
snapshotRepo = null;
} }
OutputStream output = null; OutputStream output = null;
path.getParentFile().mkdirs(); path.getParentFile().mkdirs();
try { try {
@ -117,7 +115,7 @@ public class PropertiesConfiguration extends LocalConfiguration {
} }
} }
} }
/** /**
* Get a string value. * Get a string value.
* *
@ -137,7 +135,7 @@ public class PropertiesConfiguration extends LocalConfiguration {
return val; return val;
} }
} }
/** /**
* Get a boolean value. * Get a boolean value.
* *
@ -229,5 +227,4 @@ public class PropertiesConfiguration extends LocalConfiguration {
return set; return set;
} }
} }
} }