Search in sources :

Example 1 with PhysicalCrate

use of com.codehusky.huskycrates.crate.PhysicalCrate in project HuskyCrates-Sponge by codeHusky.

the class DBReader method loadHuskyData.

public static void loadHuskyData() throws SQLException {
    connectDB();
    HashMap<Integer, World> worldIDtoWorld = new HashMap<>();
    ResultSet worldInfo = dbConnection.prepareStatement("SELECT * FROM WORLDINFO").executeQuery();
    // HuskyCrates.instance.logger.info("isClosed: " + worldInfo.isClosed());
    while (worldInfo.next()) {
        // HuskyCrates.instance.logger.info("worldInfo thing!");
        String worldUUID = worldInfo.getString("uuid");
        String worldName = worldInfo.getString("name");
        int id = worldInfo.getInt("ID");
        Optional<World> preWorld = Sponge.getServer().getWorld(UUID.fromString(worldUUID));
        if (!preWorld.isPresent()) {
            HuskyCrates.instance.logger.warn("Invalid World UUID (BUG SPONGE DEVS)");
            preWorld = Sponge.getServer().getWorld(worldName);
        }
        if (preWorld.isPresent()) {
            worldIDtoWorld.put(id, preWorld.get());
            HuskyCrates.instance.logger.info("Loaded world \"" + worldName + "\" successfully.");
        } else {
            HuskyCrates.instance.logger.warn("WorldInfo #" + id + " provides invalid world info. Removing from table.");
            Statement removal = dbConnection.createStatement();
            removal.executeQuery("SELECT  * FROM WORLDINFO WHERE ID=" + id);
            removal.executeUpdate("DELETE FROM WORLDINFO");
            removal.close();
        }
    }
    ResultSet cratePositions = dbConnection.prepareStatement("SELECT * FROM CRATELOCATIONS").executeQuery();
    HuskyCrates.instance.crateUtilities.physicalCrates = new HashMap<>();
    // HuskyCrates.instance.logger.info("isClosed: " + cratePositions.isClosed());
    while (cratePositions.next()) {
        // HuskyCrates.instance.logger.info("cratePositions thing!");
        int id = cratePositions.getInt("ID");
        double x = cratePositions.getDouble("X");
        double y = cratePositions.getDouble("Y");
        double z = cratePositions.getDouble("Z");
        int worldID = cratePositions.getInt("worldID");
        boolean entityCrate = cratePositions.getBoolean("isEntityCrate");
        String crateID = cratePositions.getString("crateID");
        if (worldIDtoWorld.containsKey(worldID)) {
            // VALID WORLD
            World world = worldIDtoWorld.get(worldID);
            Location<World> loco = new Location<>(world, x, y, z);
            HuskyCrates.instance.crateUtilities.physicalCrates.put(loco, new PhysicalCrate(loco, crateID, HuskyCrates.instance, entityCrate));
            HuskyCrates.instance.logger.info("Loaded " + crateID + " @ " + x + "," + y + "," + z + ((entityCrate) ? " (ENTITY CRATE)" : ""));
        } else {
            HuskyCrates.instance.logger.warn("CrateLocation #" + id + " provides an invalid world ID. Removing from table.");
            Statement removal = dbConnection.createStatement();
            removal.executeQuery("SELECT  * FROM CRATELOCATIONS WHERE ID=" + id);
            removal.executeUpdate("DELETE FROM CRATELOCATIONS");
            removal.close();
        }
    }
    ResultSet crateKeyUUIDs = dbConnection.prepareStatement("SELECT * FROM VALIDKEYS").executeQuery();
    // HuskyCrates.instance.logger.info("isClosed: " + crateKeyUUIDs.isClosed());
    for (VirtualCrate vc : HuskyCrates.instance.crateUtilities.crateTypes.values()) {
        vc.pendingKeys = new HashMap<>();
        vc.virtualBalances = new HashMap<>();
        PreparedStatement statement = dbConnection.prepareStatement("SELECT * FROM LASTUSED WHERE crateID = ?");
        statement.setString(1, vc.id);
        ResultSet results = statement.executeQuery();
        while (results.next()) {
            vc.lastUsed.put(UUID.fromString(results.getString(1)), LocalDateTime.ofInstant(Instant.ofEpochMilli(results.getLong(3)), ZoneOffset.systemDefault()));
        }
    }
    while (crateKeyUUIDs.next()) {
        // HuskyCrates.instance.logger.info("crateKeyUUIDs thing!");
        UUID keyUUID = UUID.fromString(crateKeyUUIDs.getString("keyUUID"));
        String crateID = crateKeyUUIDs.getString("crateID");
        int amount = crateKeyUUIDs.getInt("amount");
        if (HuskyCrates.instance.crateUtilities.crateTypes.containsKey(crateID)) {
            VirtualCrate vc = HuskyCrates.instance.crateUtilities.crateTypes.get(crateID);
            vc.pendingKeys.put(keyUUID.toString(), amount);
        } else {
            HuskyCrates.instance.logger.warn("ValidKeys " + keyUUID + " provides an invalid crate ID. Removing from table.");
            Statement removal = dbConnection.createStatement();
            removal.executeQuery("SELECT  * FROM CRATELOCATIONS WHERE KEYUUID=" + keyUUID.toString());
            removal.executeUpdate("DELETE FROM CRATELOCATIONS");
            removal.close();
        }
    }
    ResultSet keyBalances = dbConnection.prepareStatement("SELECT * FROM KEYBALANCES").executeQuery();
    // HuskyCrates.instance.logger.info("isClosed: " + keyBalances.isClosed());
    while (keyBalances.next()) {
        // HuskyCrates.instance.logger.info("keyBalances thing!");
        UUID userUUID = UUID.fromString(keyBalances.getString("userUUID"));
        String crateID = keyBalances.getString("crateID");
        int amount = keyBalances.getInt("amount");
        if (HuskyCrates.instance.crateUtilities.getCrateTypes().contains(crateID)) {
            HuskyCrates.instance.crateUtilities.getVirtualCrate(crateID).virtualBalances.put(userUUID.toString(), amount);
        } else {
            HuskyCrates.instance.logger.warn("KeyBalances for UUID " + userUUID + " provides an invalid crate ID. Removing from table.");
            Statement removal = dbConnection.createStatement();
            removal.executeQuery("SELECT  * FROM KEYBALANCES WHERE USERUUID=" + userUUID.toString());
            removal.executeUpdate("DELETE FROM KEYBALANCES");
            removal.close();
        }
    }
/*
            CRATELOCATIONS (ID INTEGER NOT NULL AUTO_INCREMENT, X DOUBLE, Y DOUBLE, Z DOUBLE, worldID INTEGER, isEntityCrate BOOLEAN, crateID CHARACTER,  PRIMARY KEY(ID))
            VALIDKEYS (keyUUID CHARACTER, crateID CHARACTER, amount INTEGER )
            KEYBALANCES (userUUID CHARACTER, crateID CHARACTER, amount INTEGER)
            WORLDINFO (ID INTEGER NOT NULL AUTO_INCREMENT,uuid CHARACTER, name CHARACTER,  PRIMARY KEY(ID))
         */
}
Also used : HashMap(java.util.HashMap) PhysicalCrate(com.codehusky.huskycrates.crate.PhysicalCrate) World(org.spongepowered.api.world.World) VirtualCrate(com.codehusky.huskycrates.crate.VirtualCrate) UUID(java.util.UUID) Location(org.spongepowered.api.world.Location)

Example 2 with PhysicalCrate

use of com.codehusky.huskycrates.crate.PhysicalCrate in project HuskyCrates-Sponge by codeHusky.

the class HuskyCrates method placeBlock.

@Listener(order = Order.PRE)
public void placeBlock(ChangeBlockEvent event) {
    if (forceStop) {
        return;
    }
    if (event.getCause().root() instanceof Player) {
        Player plr = (Player) event.getCause().root();
        if (event instanceof ChangeBlockEvent.Place || event instanceof ChangeBlockEvent.Break) {
            BlockType t = event.getTransactions().get(0).getOriginal().getLocation().get().getBlock().getType();
            Location<World> location = event.getTransactions().get(0).getOriginal().getLocation().get();
            // System.out.println(event instanceof ChangeBlockEvent.Break);
            if (validCrateBlocks.contains(t)) {
                if (event instanceof ChangeBlockEvent.Place) {
                    if (plr.getItemInHand(HandTypes.MAIN_HAND).isPresent()) {
                        Optional<Object> tt = plr.getItemInHand(HandTypes.MAIN_HAND).get().toContainer().get(DataQuery.of("UnsafeData", "crateID"));
                        if (tt.isPresent()) {
                            String crateID = tt.get().toString();
                            if (!plr.hasPermission("huskycrates.tester")) {
                                event.setCancelled(true);
                                return;
                            }
                            if (!crateUtilities.physicalCrates.containsKey(location))
                                crateUtilities.physicalCrates.put(location, new PhysicalCrate(location, crateID, this, false));
                            crateUtilities.physicalCrates.get(location).createHologram();
                            try {
                                DBReader.saveHuskyData();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                            return;
                        }
                    }
                }
            } else if (event instanceof ChangeBlockEvent.Break) {
                if (crateUtilities.physicalCrates.containsKey(location)) {
                    if (!plr.hasPermission("huskycrates.tester")) {
                        event.setCancelled(true);
                        return;
                    }
                    if (!crateUtilities.physicalCrates.get(location).isEntity)
                        crateUtilities.physicalCrates.get(location).ent.remove();
                    crateUtilities.physicalCrates.remove(location);
                    crateUtilities.brokenCrates.add(location);
                    try {
                        DBReader.saveHuskyData();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) SQLException(java.sql.SQLException) PhysicalCrate(com.codehusky.huskycrates.crate.PhysicalCrate) World(org.spongepowered.api.world.World) ChangeBlockEvent(org.spongepowered.api.event.block.ChangeBlockEvent) BlockType(org.spongepowered.api.block.BlockType) JSONObject(org.json.JSONObject) Listener(org.spongepowered.api.event.Listener)

Example 3 with PhysicalCrate

use of com.codehusky.huskycrates.crate.PhysicalCrate in project HuskyCrates-Sponge by codeHusky.

the class HuskyCrates method entityInteract.

@Listener
public void entityInteract(InteractEntityEvent.Secondary.MainHand event) {
    if (forceStop) {
        return;
    }
    // System.out.println(event.getTargetEntity().toContainer().get(DataQuery.of("UnsafeData","crateID")));
    if (event.getCause().root() instanceof Player) {
        Player plr = (Player) event.getCause().root();
        if (plr.getItemInHand(HandTypes.MAIN_HAND).isPresent() && plr.hasPermission("huskycrates.wand")) {
            ItemStack hand = plr.getItemInHand(HandTypes.MAIN_HAND).get();
            if (hand.getType() == ItemTypes.BLAZE_ROD) {
                if (hand.toContainer().get(DataQuery.of("UnsafeData", "crateID")).isPresent()) {
                    if (!crateUtilities.physicalCrates.containsKey(event.getTargetEntity().getLocation())) {
                        // System.out.println(event.getTargetEntity().getLocation().getBlockPosition());
                        event.getTargetEntity().offer(Keys.AI_ENABLED, false);
                        event.getTargetEntity().offer(Keys.IS_SILENT, true);
                        crateUtilities.physicalCrates.put(event.getTargetEntity().getLocation(), new PhysicalCrate(event.getTargetEntity().getLocation(), hand.toContainer().get(DataQuery.of("UnsafeData", "crateID")).get().toString(), this, true));
                        crateUtilities.physicalCrates.get(event.getTargetEntity().getLocation()).createHologram();
                        try {
                            DBReader.saveHuskyData();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    } else {
                        event.getTargetEntity().offer(Keys.AI_ENABLED, true);
                        event.getTargetEntity().offer(Keys.IS_SILENT, false);
                        event.getTargetEntity().offer(Keys.CUSTOM_NAME_VISIBLE, false);
                        event.getTargetEntity().offer(Keys.DISPLAY_NAME, Text.of());
                        crateUtilities.physicalCrates.remove(event.getTargetEntity().getLocation());
                        crateUtilities.brokenCrates.add(event.getTargetEntity().getLocation());
                        try {
                            DBReader.saveHuskyData();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                    event.setCancelled(true);
                    return;
                }
            }
        }
        if (crateUtilities.physicalCrates.containsKey(event.getTargetEntity().getLocation())) {
            String crateType = crateUtilities.physicalCrates.get(event.getTargetEntity().getLocation()).vc.id;
            VirtualCrate vc = crateUtilities.getVirtualCrate(crateType);
            crateUtilities.physicalCrates.get(event.getTargetEntity().getLocation()).createHologram();
            // crateUtilities.recognizeChest(te.getLocation());
            event.setCancelled(true);
            int keyResult = crateUtilities.isAcceptedKey(crateUtilities.physicalCrates.get(event.getTargetEntity().getLocation()), plr.getItemInHand(HandTypes.MAIN_HAND), plr);
            keyHandler(plr, keyResult, vc, event.getTargetEntity().getLocation(), crateType);
        }
    }
}
Also used : VirtualCrate(com.codehusky.huskycrates.crate.VirtualCrate) Player(org.spongepowered.api.entity.living.player.Player) SQLException(java.sql.SQLException) PhysicalCrate(com.codehusky.huskycrates.crate.PhysicalCrate) ItemStack(org.spongepowered.api.item.inventory.ItemStack) Listener(org.spongepowered.api.event.Listener)

Example 4 with PhysicalCrate

use of com.codehusky.huskycrates.crate.PhysicalCrate in project HuskyCrates-Sponge by codeHusky.

the class HuskyCrates method postGameStart.

@Listener(order = Order.POST)
public void postGameStart(GameStartedServerEvent event) {
    checkVersion();
    if (forceStop) {
        // logger.error("Since a blacklisted mod is loaded, HuskyCrates will not start. Please check higher in your logs for the reasoning.");
        return;
    }
    Sponge.getScheduler().createTaskBuilder().execute(new Consumer<Task>() {

        @Override
        public void accept(Task task) {
            logger.info("Deleting existing armor stands...");
            removeArmorstands();
            logger.info("Initalizing config...");
            if (!crateUtilities.hasInitalizedVirtualCrates) {
                crateUtilities.generateVirtualCrates(crateConfig);
            }
            // doublecheck
            crateUtilities.hasInitalizedVirtualCrates = true;
            logger.info("Done initalizing config.");
            logger.info("Attempting legacy Physical Crates method (this will be removed in a later version)");
            CommentedConfigurationNode root = null;
            boolean convertFired = false;
            try {
                root = crateConfig.load();
                double max = root.getNode("positions").getChildrenList().size();
                double count = 0;
                for (VirtualCrate vc : crateUtilities.crateTypes.values()) {
                    if (vc.pendingKeys.size() > 0) {
                        logger.warn("legacy keys loaded! warn warn warn.");
                        if (!root.getNode("keys").isVirtual()) {
                            root.removeChild("keys");
                        }
                        convertFired = true;
                    }
                }
                if (!root.getNode("positions").isVirtual()) {
                    convertFired = true;
                    logger.warn("Legacy position data detected. Will convert.");
                    for (CommentedConfigurationNode node : root.getNode("positions").getChildrenList()) {
                        count++;
                        Location<World> ee;
                        try {
                            ee = node.getNode("location").getValue(TypeToken.of(Location.class));
                        } catch (InvalidDataException err2) {
                            logger.warn("Bug sponge developers about world UUIDs!");
                            ee = new Location<World>(Sponge.getServer().getWorld(node.getNode("location", "WorldName").getString()).get(), node.getNode("location", "X").getDouble(), node.getNode("location", "Y").getDouble(), node.getNode("location", "Z").getDouble());
                        }
                        if (!crateUtilities.physicalCrates.containsKey(ee))
                            crateUtilities.physicalCrates.put(ee, new PhysicalCrate(ee, node.getNode("crateID").getString(), HuskyCrates.instance, node.getNode("location", "BlockType").getString().equals("minecraft:air")));
                        logger.info("(LEGACY) PROGRESS: " + Math.round((count / max) * 100) + "%");
                    }
                    root.removeChild("positions");
                }
                if (!root.getNode("users").isVirtual()) {
                    for (Object uuidPre : root.getNode("users").getChildrenMap().keySet()) {
                        for (Object crateIDPre : root.getNode("users", uuidPre, "keys").getChildrenMap().keySet()) {
                            String uuid = uuidPre.toString();
                            String crateID = crateIDPre.toString();
                            int amount = root.getNode("users", uuid, "keys", crateID).getInt(0);
                            HuskyCrates.instance.crateUtilities.crateTypes.get(crateID).virtualBalances.put(uuid, amount);
                        }
                    }
                    root.removeChild("users");
                }
                crateConfig.save(root);
            } catch (Exception e) {
                crateUtilities.exceptionHandler(e);
                if (event.getCause().root() instanceof Player) {
                    CommandSource cs = (CommandSource) event.getCause().root();
                    cs.sendMessage(Text.of(TextColors.GOLD, "HuskyCrates", TextColors.WHITE, ":", TextColors.RED, " An error has occured. Please check the console for more information."));
                }
                return;
            }
            logger.info("Done with legacy loading technique");
            logger.info("Running DB routine.");
            try {
                DBReader.dbInitCheck();
                if (convertFired) {
                    logger.info("Saving data.");
                    DBReader.saveHuskyData();
                    logger.info("Done saving data.");
                } else {
                    logger.info("Loading data.");
                    DBReader.loadHuskyData();
                    logger.info("Done loading data.");
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            logger.info("DB Data routine finished.");
            crateUtilities.startParticleEffects();
            logger.info("Initalization complete.");
            Sponge.getScheduler().createTaskBuilder().execute(() -> {
                try {
                    DBReader.dbInitCheck();
                    DBReader.saveHuskyData();
                    logger.info("Updated Database.");
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }).interval(15, TimeUnit.MINUTES).delay(15, TimeUnit.MINUTES).async().submit(HuskyCrates.instance);
        }
    }).delayTicks(1).submit(this);
}
Also used : Task(org.spongepowered.api.scheduler.Task) Player(org.spongepowered.api.entity.living.player.Player) SQLException(java.sql.SQLException) PhysicalCrate(com.codehusky.huskycrates.crate.PhysicalCrate) World(org.spongepowered.api.world.World) CommandSource(org.spongepowered.api.command.CommandSource) SQLException(java.sql.SQLException) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) IOException(java.io.IOException) VirtualCrate(com.codehusky.huskycrates.crate.VirtualCrate) CommentedConfigurationNode(ninja.leaping.configurate.commented.CommentedConfigurationNode) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) JSONObject(org.json.JSONObject) Location(org.spongepowered.api.world.Location) Listener(org.spongepowered.api.event.Listener)

Example 5 with PhysicalCrate

use of com.codehusky.huskycrates.crate.PhysicalCrate in project HuskyCrates-Sponge by codeHusky.

the class DBReader method saveHuskyData.

public static void saveHuskyData() throws SQLException {
    /*
            CRATELOCATIONS (ID INTEGER NOT NULL AUTO_INCREMENT, X DOUBLE, Y DOUBLE, Z DOUBLE, worldID INTEGER, isEntityCrate BOOLEAN, crateID CHARACTER
            VALIDKEYS (keyUUID CHARACTER, crateID CHARACTER, amount INTEGER
            KEYBALANCES (userUUID CHARACTER, crateID CHARACTER, amount INTEGER
            WORLDINFO (ID INTEGER NOT NULL AUTO_INCREMENT,uuid CHARACTER, name CHARACTER
        */
    connectDB();
    // crate positions
    HashMap<UUID, Integer> worldsInserted = new HashMap<>();
    ArrayList<Location<World>> locationSurvey = new ArrayList<>();
    locationSurvey.addAll(HuskyCrates.instance.crateUtilities.physicalCrates.keySet());
    locationSurvey.addAll(HuskyCrates.instance.crateUtilities.brokenCrates);
    for (Location<World> location : locationSurvey) {
        if (!worldsInserted.keySet().contains(location.getExtent().getUniqueId())) {
            PreparedStatement statement = dbConnection.prepareStatement("SELECT * FROM WORLDINFO WHERE name = ? OR uuid = ?");
            statement.setString(1, location.getExtent().getName());
            statement.setString(2, location.getExtent().getUniqueId().toString());
            ResultSet results = statement.executeQuery();
            boolean exists = results.next();
            if (exists) {
                worldsInserted.put(location.getExtent().getUniqueId(), results.getInt(1));
            } else {
                dbConnection.prepareStatement("INSERT INTO WORLDINFO(uuid,name) VALUES('" + location.getExtent().getUniqueId().toString() + "','" + location.getExtent().getName() + "')").executeUpdate();
                PreparedStatement fetchPrim = dbConnection.prepareStatement("SELECT * FROM WORLDINFO WHERE name = ? OR uuid = ?");
                fetchPrim.setString(1, location.getExtent().getName());
                fetchPrim.setString(2, location.getExtent().getUniqueId().toString());
                ResultSet primResults = fetchPrim.executeQuery();
                primResults.next();
                worldsInserted.put(location.getExtent().getUniqueId(), primResults.getInt(1));
            }
        }
        if (!HuskyCrates.instance.crateUtilities.brokenCrates.contains(location)) {
            PhysicalCrate crate = HuskyCrates.instance.crateUtilities.physicalCrates.get(location);
            PreparedStatement statement = dbConnection.prepareStatement("SELECT * FROM CRATELOCATIONS WHERE worldID = ? AND X = ? AND Y = ? AND Z = ? AND isEntityCrate = ?");
            statement.setInt(1, worldsInserted.get(location.getExtent().getUniqueId()));
            statement.setDouble(2, location.getX());
            statement.setDouble(3, location.getY());
            statement.setDouble(4, location.getZ());
            statement.setBoolean(5, crate.isEntity);
            ResultSet results = statement.executeQuery();
            boolean exists = results.next();
            if (!exists) {
                dbConnection.prepareStatement("INSERT INTO CRATELOCATIONS(X,Y,Z,worldID,isEntityCrate,crateID) VALUES(" + location.getX() + "," + location.getY() + "," + location.getZ() + "," + worldsInserted.get(location.getExtent().getUniqueId()) + "," + crate.isEntity + ",'" + crate.vc.id + "')").executeUpdate();
            }
        }
    }
    for (Location<World> broken : HuskyCrates.instance.crateUtilities.brokenCrates) {
        PreparedStatement delState = dbConnection.prepareStatement("DELETE FROM CRATELOCATIONS WHERE worldID = ? AND X = ? AND Y = ? AND Z = ?");
        delState.setInt(1, worldsInserted.get(broken.getExtent().getUniqueId()));
        delState.setDouble(2, broken.getX());
        delState.setDouble(3, broken.getY());
        delState.setDouble(4, broken.getZ());
        delState.executeUpdate();
    }
    HuskyCrates.instance.crateUtilities.brokenCrates.clear();
    for (VirtualCrate crate : HuskyCrates.instance.crateUtilities.crateTypes.values()) {
        for (String keyUUID : crate.pendingKeys.keySet()) {
            int amount = crate.pendingKeys.get(keyUUID);
            PreparedStatement statement = dbConnection.prepareStatement("SELECT * FROM VALIDKEYS WHERE keyUUID = ?");
            statement.setString(1, keyUUID);
            ResultSet results = statement.executeQuery();
            boolean exists = results.next();
            if (exists) {
                PreparedStatement uState = dbConnection.prepareStatement("UPDATE VALIDKEYS SET amount = ? WHERE keyUUID = ?");
                uState.setInt(1, amount);
                uState.setString(2, keyUUID);
                uState.executeUpdate();
            } else {
                dbConnection.prepareStatement("INSERT INTO VALIDKEYS(keyUUID,crateID,amount) VALUES('" + keyUUID + "','" + crate.id + "'," + amount + ")").executeUpdate();
            }
        // System.out.println(g);
        }
        for (UUID uuid : crate.lastUsed.keySet()) {
            PreparedStatement statement = dbConnection.prepareStatement("SELECT * FROM LASTUSED WHERE crateID = ? AND userUUID = ?");
            statement.setString(1, crate.id);
            statement.setString(2, uuid.toString());
            ResultSet results = statement.executeQuery();
            long epoch = crate.lastUsed.get(uuid).atZone(ZoneId.systemDefault()).toEpochSecond();
            if (results.next()) {
                // exists
                PreparedStatement crState = dbConnection.prepareStatement("UPDATE LASTUSED SET lastUsed = ? WHERE userUUID = ? AND crateID = ?");
                crState.setString(2, uuid.toString());
                crState.setString(3, crate.id);
                crState.setLong(1, epoch);
                crState.executeUpdate();
            } else {
                PreparedStatement crState = dbConnection.prepareStatement("INSERT INTO LASTUSED(userUUID,crateID,lastUsed) VALUES(?,?,?)");
                crState.setString(1, uuid.toString());
                crState.setString(2, crate.id);
                crState.setLong(3, epoch);
                crState.executeUpdate();
            }
        }
    }
    for (String vcID : HuskyCrates.instance.crateUtilities.getCrateTypes()) {
        VirtualCrate vc = HuskyCrates.instance.crateUtilities.getVirtualCrate(vcID);
        String crateID = vc.id;
        for (String uuid : vc.virtualBalances.keySet()) {
            int amount = vc.virtualBalances.get(uuid);
            PreparedStatement statement = dbConnection.prepareStatement("SELECT * FROM KEYBALANCES WHERE userUUID = ? AND crateID = ?");
            statement.setString(1, uuid);
            statement.setString(2, crateID);
            ResultSet results = statement.executeQuery();
            boolean exists = results.next();
            if (exists) {
                PreparedStatement uState = dbConnection.prepareStatement("UPDATE KEYBALANCES SET amount = ? WHERE userUUID = ? AND crateID = ?");
                uState.setInt(1, amount);
                uState.setString(2, uuid);
                uState.setString(3, crateID);
                uState.executeUpdate();
            } else {
                dbConnection.prepareStatement("INSERT INTO KEYBALANCES(userUUID,crateID,amount) VALUES('" + uuid + "','" + crateID + "'," + amount + ")").executeUpdate();
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) PhysicalCrate(com.codehusky.huskycrates.crate.PhysicalCrate) World(org.spongepowered.api.world.World) VirtualCrate(com.codehusky.huskycrates.crate.VirtualCrate) UUID(java.util.UUID) Location(org.spongepowered.api.world.Location)

Aggregations

PhysicalCrate (com.codehusky.huskycrates.crate.PhysicalCrate)5 VirtualCrate (com.codehusky.huskycrates.crate.VirtualCrate)4 World (org.spongepowered.api.world.World)4 SQLException (java.sql.SQLException)3 Player (org.spongepowered.api.entity.living.player.Player)3 Listener (org.spongepowered.api.event.Listener)3 Location (org.spongepowered.api.world.Location)3 HashMap (java.util.HashMap)2 UUID (java.util.UUID)2 JSONObject (org.json.JSONObject)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 CommentedConfigurationNode (ninja.leaping.configurate.commented.CommentedConfigurationNode)1 BlockType (org.spongepowered.api.block.BlockType)1 CommandSource (org.spongepowered.api.command.CommandSource)1 InvalidDataException (org.spongepowered.api.data.persistence.InvalidDataException)1 ChangeBlockEvent (org.spongepowered.api.event.block.ChangeBlockEvent)1 ItemStack (org.spongepowered.api.item.inventory.ItemStack)1 Task (org.spongepowered.api.scheduler.Task)1