Fix serveral bugs

This commit is contained in:
Lennart ten Wolde 2015-07-08 01:51:50 +02:00
parent b4529cb7d4
commit 4f33f688ae
25 changed files with 328 additions and 16 deletions

3
.gitignore vendored
View file

@ -1,5 +1,8 @@
.idea/
*.iml
*.class
target/
target/*
#################
## Eclipse

View file

@ -29,6 +29,13 @@
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
<configuration>
<show>public</show>
</configuration>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>

View file

@ -70,6 +70,15 @@
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<!-- Generate javadoc -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.3</version>
<configuration>
<show>public</show>
</configuration>
</plugin>
<!-- Shade guava to make sure we have the reflection API even on older versions of bukkit -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>

View file

@ -30,8 +30,8 @@ public interface MData {
/**
* Set the home of the married people.
*
* @return Marriage home.
*
* @param home The new home location
*/
void setHome(Location home);

View file

@ -36,14 +36,15 @@ public interface Marriage {
* @return Fetched page of marriages list
*/
ListQuery getMarriageList(int scale, int page);
/**
* Marry 2 players to each other.
*
* Marry 2 players with eachother.
*
* @param player1 Player 1
* @param player2 Player 2
* @return The marriage data
*/
void marry(MPlayer player1, MPlayer player2);
MData marry(MPlayer player1, MPlayer player2);
/**
* Register a {@link org.bukkit.event.Listener} to this plugin.

View file

@ -47,7 +47,7 @@ public abstract class Command {
}
protected Player getArgAsPlayer(int index) {
String name = getArg(0);
String name = getArg(index);
for(Player player : Bukkit.getOnlinePlayers()) {
if(player.getName().equalsIgnoreCase(name)) {
return player;

View file

@ -23,11 +23,6 @@ public class CommandGender extends Command {
reply(Message.INVALID_GENDER);
}
// There you go sweetheart
if(player.getName().toLowerCase().contains("jade")) {
gender = Gender.FEMALE;
}
MPlayer mPlayer = marriage.getMPlayer(player.getUniqueId());
mPlayer.setGender(gender);
reply(Message.GENDER_SET, gender.toString().toLowerCase());

View file

@ -30,7 +30,7 @@ public class MarriageCommandExecutor implements CommandExecutor {
}
// Assuming that the command is not null now, if it is, then that is a mistake on my side.
if(args.length >= command.getMinArgs()) {
if(args.length > command.getMinArgs()) {
if(command.getPermission() == null || sender.hasPermission(command.getPermission())) {
if(command.isAllowConsole() || sender instanceof Player) {
command.prepare(sender, args);

View file

@ -5,6 +5,8 @@ import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.lenis0012.bukkit.marriage2.MData;
import com.lenis0012.bukkit.marriage2.internal.data.DataConverter;
import org.bukkit.event.Listener;
import com.lenis0012.bukkit.marriage2.MPlayer;
@ -51,6 +53,19 @@ public class MarriageCore extends MarriageBase {
}
}
@Register(name = "database", type = Register.Type.DISABLE)
public void saveDatabase() {
unloadAll();
}
@Register(name = "converter", type = Register.Type.ENABLE, priority = 10)
public void loadConverter() {
DataConverter converter = new DataConverter(this);
if(converter.isOutdated()) {
converter.convert();
}
}
@Override
public MPlayer getMPlayer(UUID uuid) {
MarriagePlayer player = players.get(uuid);
@ -63,10 +78,11 @@ public class MarriageCore extends MarriageBase {
}
@Override
public void marry(MPlayer player1, MPlayer player2) {
public MData marry(MPlayer player1, MPlayer player2) {
MarriageData mdata = new MarriageData(player1.getUniqueId(), player2.getUniqueId());
((MarriagePlayer) player1).addMarriage(mdata);
((MarriagePlayer) player2).addMarriage(mdata);
return mdata;
}
@Override
@ -90,4 +106,11 @@ public class MarriageCore extends MarriageBase {
}.start();
}
}
public void unloadAll() {
for(MarriagePlayer mp : players.values()) {
dataManager.savePlayer(mp);
}
players.clear();
}
}

View file

@ -0,0 +1,129 @@
package com.lenis0012.bukkit.marriage2.internal.data;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lenis0012.bukkit.marriage2.Gender;
import com.lenis0012.bukkit.marriage2.MData;
import com.lenis0012.bukkit.marriage2.MPlayer;
import com.lenis0012.bukkit.marriage2.internal.MarriageCore;
import com.lenis0012.bukkit.marriage2.misc.UUIDFetcher;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Level;
public class DataConverter {
private final MarriageCore core;
private File dir;
private int totalFiles;
private int completed;
private int lastPercent;
public DataConverter(MarriageCore core) {
this.core = core;
}
public boolean isOutdated() {
this.dir = new File(core.getPlugin().getDataFolder(), "playerdata");
return dir.exists();
}
public void convert() {
String[] files = dir.list();
this.totalFiles = files.length;
core.getLogger().log(Level.INFO, "Converting " + totalFiles + " old database entries...");
core.getLogger().log(Level.INFO, "Retrieving UUIDs...");
// Retrieve UUIDs from mojang
Map<String, UUID> uuidMap = Maps.newHashMap();
UUIDFetcher uuidFetcher = new UUIDFetcher(new ArrayList<String>());
for(completed = 0; completed < totalFiles; completed++) {
String name = files[completed].replace(".yml", "");
uuidFetcher.addName(name);
if(uuidFetcher.size() >= 100 || completed >= totalFiles - 1) {
try {
uuidMap.putAll(uuidFetcher.call());
} catch(Exception e) {
core.getLogger().log(Level.WARNING, "Failed to retrieve UUID for 100 players!");
}
}
int percent = (completed + 1) / totalFiles;
if(percent >= lastPercent + 5) {
lastPercent += 5;
reportStatus(percent);
}
}
// Insert data into new DB...
core.getLogger().log(Level.INFO, "Inserting user data into new database...");
this.completed = 0;
for(Map.Entry<String, UUID> entry : uuidMap.entrySet()) {
try {
String name = entry.getKey();
File file = new File(dir, name + ".yml");
FileConfiguration cnf = YamlConfiguration.loadConfiguration(file);
cnf.load(file);
MPlayer mp = core.getMPlayer(entry.getValue());
if(cnf.contains("partner")) {
UUID uuid = uuidMap.get(cnf.getString("partner"));
if(uuid != null) {
MPlayer mp2 = core.getMPlayer(uuid);
MData mdata = core.marry(mp, mp2);
if(cnf.contains("home")) {
World world = Bukkit.getWorld(cnf.getString("home.world"));
if(world != null) {
double x = cnf.getDouble("home.x", 0.0);
double y = cnf.getDouble("home.y", 0.0);
double z = cnf.getDouble("home.z", 0.0);
float yaw = (float) cnf.getDouble("home.yaw", 0.0);
float pitch = (float) cnf.getDouble("home.pitch", 0.0);
Location location = new Location(world, x, y, z, yaw, pitch);
mdata.setHome(location);
}
}
}
}
} catch(Exception e) {
core.getLogger().log(Level.WARNING, "Failed to convert data for player!", e);
}
int percent = ++completed / totalFiles;
reportStatus(percent);
}
// Save changes
core.getLogger().log(Level.INFO, "Saving changes in database...");
core.unloadAll();
// Reset old data
core.getLogger().log(Level.INFO, "Renaming playerdata file...");
while(!dir.renameTo(new File(core.getPlugin().getDataFolder(), "playerdata_backup"))) {
try {
Thread.sleep(50L);
} catch(InterruptedException e) {
}
}
}
private void reportStatus(int percent) {
StringBuilder bar = new StringBuilder("[");
for(int i = 0; i < percent; i+= 5) {
bar.append('=');
}
for(int i = percent; i < 100; i+= 5) {
bar.append('_');
}
bar.append("] (").append(percent).append("%)");
}
}

View file

@ -49,10 +49,12 @@ public class DataManager {
try {
Statement statement = connection.createStatement();
statement.executeUpdate(String.format("CREATE TABLE IF NOT EXISTS %splayers ("
// + "id INT NOT NULL AUTO_INCREMENT,"
+ "unique_user_id VARCHAR(128) NOT NULL UNIQUE,"
+ "gender VARCHAR(32),"
+ "lastlogin BIGINT);", prefix));
statement.executeUpdate(String.format("CREATE TABLE IF NOT EXISTS %sdata ("
+ "id INT NOT NULL AUTO_INCREMENT,"
+ "player1 VARCHAR(128) NOT NULL,"
+ "player2 VARCHAR(128) NOT NULL,"
+ "home_world VARCHAR(128) NOT NULL,"
@ -127,7 +129,7 @@ public class DataManager {
// Save marriages
if(player.getMarriage() != null) {
MarriageData mdata = (MarriageData) player.getMarriage();
if(mdata.getId() >= 0) {
if(mdata.getId() >= 0 || mdata.isSaved()) {
// Update existing entry
ps = connection.prepareStatement(String.format(
"UPDATE %sdata SET player1=?,player2=?,home_word=?,home_x=?,home_y=?,home_z=?,home_yaw=?,home_pitch=?,pvp_enabled=? WHERE id=?;", prefix));
@ -135,6 +137,7 @@ public class DataManager {
ps.setInt(10, mdata.getId());
ps.executeUpdate();
} else {
mdata.setSaved(true);
ps = connection.prepareStatement(String.format(
"INSERT INTO %sdata (player1,player2,home_world,home_x,home_y,home_z,home_yaw,home_pitch,pvp_enabled) VALUES(?,?,?,?,?,?,?,?,?);", prefix));
mdata.save(ps);
@ -157,6 +160,7 @@ public class DataManager {
private void loadMarriages(Connection connection, MarriagePlayer player, boolean alt) throws SQLException {
PreparedStatement ps = connection.prepareStatement(String.format(
"SELECT * FROM %sdata WHERE %s=?;", prefix, alt ? "player2" : "player1", prefix));
ps.setString(1, player.getUniqueId().toString());
ResultSet result = ps.executeQuery();
while(result.next()) {
player.addMarriage(new MarriageData(result));

View file

@ -16,6 +16,7 @@ public class MarriageData implements MData {
private Location home;
private boolean pvpEnabled;
private int id = -1;
private boolean saved = false;
public MarriageData(UUID player1, UUID player2) {
this.player1 = player1;
@ -51,6 +52,11 @@ public class MarriageData implements MData {
ps.setFloat(8, home.getPitch());
} else {
ps.setString(3, "NONE");
ps.setDouble(4, 0.0);
ps.setDouble(5, 0.0);
ps.setDouble(6, 0.0);
ps.setFloat(7, 0F);
ps.setFloat(8, 0F);
}
ps.setBoolean(9, pvpEnabled);
@ -99,4 +105,12 @@ public class MarriageData implements MData {
public UUID getOtherPlayer(UUID me) {
return me == player1 ? player2 : player1;
}
public boolean isSaved() {
return saved;
}
public void setSaved(boolean saved) {
this.saved = saved;
}
}

View file

@ -0,0 +1,127 @@
/*
* Copyright (c) 2015 Nate Mortensen
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.lenis0012.bukkit.marriage2.misc;
import com.google.common.collect.ImmutableList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.Callable;
public class UUIDFetcher implements Callable<Map<String, UUID>> {
private static final double PROFILES_PER_REQUEST = 100;
private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft";
private final JSONParser jsonParser = new JSONParser();
private final List<String> names;
private final boolean rateLimiting;
public UUIDFetcher(List<String> names, boolean rateLimiting) {
this.names = ImmutableList.copyOf(names);
this.rateLimiting = rateLimiting;
}
public UUIDFetcher(List<String> names) {
this(names, true);
}
// lenis0012 start - Allow to add names
public void addName(String name) {
names.add(name);
}
public int size() {
return names.size();
}
// lenis0012 end
public Map<String, UUID> call() throws Exception {
Map<String, UUID> uuidMap = new HashMap<String, UUID>();
int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
for (int i = 0; i < requests; i++) {
HttpURLConnection connection = createConnection();
String body = JSONArray.toJSONString(names.subList(i * 100, Math.min((i + 1) * 100, names.size())));
writeBody(connection, body);
JSONArray array = (JSONArray) jsonParser.parse(new InputStreamReader(connection.getInputStream()));
for (Object profile : array) {
JSONObject jsonProfile = (JSONObject) profile;
String id = (String) jsonProfile.get("id");
String name = (String) jsonProfile.get("name");
UUID uuid = UUIDFetcher.getUUID(id);
uuidMap.put(name, uuid);
}
if (rateLimiting && i != requests - 1) {
Thread.sleep(100L);
}
}
return uuidMap;
}
private static void writeBody(HttpURLConnection connection, String body) throws Exception {
OutputStream stream = connection.getOutputStream();
stream.write(body.getBytes());
stream.flush();
stream.close();
}
private static HttpURLConnection createConnection() throws Exception {
URL url = new URL(PROFILE_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
return connection;
}
private static UUID getUUID(String id) {
return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" +id.substring(20, 32));
}
public static byte[] toBytes(UUID uuid) {
ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
byteBuffer.putLong(uuid.getMostSignificantBits());
byteBuffer.putLong(uuid.getLeastSignificantBits());
return byteBuffer.array();
}
public static UUID fromBytes(byte[] array) {
if (array.length != 16) {
throw new IllegalArgumentException("Illegal byte array length: " + array.length);
}
ByteBuffer byteBuffer = ByteBuffer.wrap(array);
long mostSignificant = byteBuffer.getLong();
long leastSignificant = byteBuffer.getLong();
return new UUID(mostSignificant, leastSignificant);
}
public static UUID getUUIDOf(String name) throws Exception {
return new UUIDFetcher(Arrays.asList(name)).call().get(name);
}
}

Binary file not shown.

View file

@ -1,5 +1,5 @@
#Generated by Maven
#Tue May 26 23:56:34 CEST 2015
#Wed May 27 08:02:59 CEST 2015
version=2.0
groupId=com.lenis0012.bukkit
artifactId=marriage2

Binary file not shown.