Java Code Examples for com.griefcraft.lwc.LWC#getInstance()

The following examples show how to use com.griefcraft.lwc.LWC#getInstance() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LWCPlayerListener.java    From Modern-LWC with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerArmorStandManipulate(PlayerArmorStandManipulateEvent e) {
    Entity entity = e.getRightClicked();
    if (plugin.getLWC().isProtectable(e.getRightClicked().getType())) {
        int A = 50000 + entity.getUniqueId().hashCode();

        LWC lwc = LWC.getInstance();
        Protection protection = lwc.getPhysicalDatabase().loadProtection(entity.getWorld().getName(), A, A, A);
        Player p = e.getPlayer();
        boolean canAccess = lwc.canAccessProtection(p, protection);
        if (onPlayerEntityInteract(p, entity, e.isCancelled())) {
            e.setCancelled(true);
        }
        if (protection != null) {
            if (canAccess)
                return;
            e.setCancelled(true);
        }
    }
}
 
Example 2
Source File: LWCPlayerListener.java    From Modern-LWC with MIT License 6 votes vote down vote up
@EventHandler
public void minecartBreak(VehicleDestroyEvent e) {
    Entity entity = e.getVehicle();
    if (plugin.getLWC().isProtectable(e.getVehicle().getType())) {
        int A = 50000 + entity.getUniqueId().hashCode();
        LWC lwc = LWC.getInstance();
        Protection protection = lwc.getPhysicalDatabase().loadProtection(entity.getWorld().getName(), A, A, A);
        if ((((entity instanceof StorageMinecart)) || ((entity instanceof HopperMinecart)))
                && (protection != null)) {
            if (e.getAttacker() instanceof Projectile) {
                e.setCancelled(true);
            }
            Player p = (Player) e.getAttacker();
            boolean canAccess = lwc.canAccessProtection(p, protection);
            if (canAccess) {
                protection.remove();
                protection.removeAllPermissions();
                protection.removeCache();
                return;
            }
            e.setCancelled(true);
        }
    }
}
 
Example 3
Source File: LimitsModule.java    From Modern-LWC with MIT License 6 votes vote down vote up
/**
 * Resolve a configuration node for a player. Tries nodes in this order:
 * <pre>
 * players.PLAYERNAME.node
 * groups.GROUPNAME.node
 * master.node
 * </pre>
 *
 * @param player
 * @param node
 * @return
 */
private String resolveString(Player player, String node) {
    LWC lwc = LWC.getInstance();

    // resolve the limits type
    String value;

    // try the player
    value = configuration.getString("players." + player.getName() + "." + node);

    // try the player's groups
    if (value == null) {
        for (String groupName : lwc.getPermissions().getGroups(player)) {
            if (groupName != null && !groupName.isEmpty() && value == null) {
                value = map("groups." + groupName + "." + node);
            }
        }
    }

    // if all else fails, use master
    if (value == null) {
        value = map("master." + node);
    }

    return value != null && !value.isEmpty() ? value : null;
}
 
Example 4
Source File: LWCPlayerListener.java    From Modern-LWC with MIT License 6 votes vote down vote up
@EventHandler
public void onEntityDamage(EntityDamageEvent e) {
    if (e instanceof EntityDamageByEntityEvent
            && !(e.getCause() == DamageCause.BLOCK_EXPLOSION || e.getCause() == DamageCause.ENTITY_EXPLOSION))
        return;
    Entity entity = e.getEntity();
    if (plugin.getLWC().isProtectable(e.getEntity().getType())) {
        int A = 50000 + entity.getUniqueId().hashCode();
        LWC lwc = LWC.getInstance();
        Protection protection = lwc.getPhysicalDatabase().loadProtection(entity.getWorld().getName(), A, A, A);
        if (protection != null) {
            if (e.getCause() != DamageCause.CONTACT)
                e.setCancelled(true);
        }
    }
}
 
Example 5
Source File: LWCEntityListener.java    From Modern-LWC with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGH)
public void onEntityExplode(EntityExplodeEvent event) {
    if (!LWC.ENABLED || event.isCancelled()) {
        return;
    }

    LWC lwc = LWC.getInstance();

    for (Block block : event.blockList()) {
        Protection protection = plugin.getLWC().findProtection(block.getLocation());

        if (protection != null) {
            boolean ignoreExplosions = Boolean
                    .parseBoolean(lwc.resolveProtectionConfiguration(protection.getBlock(), "ignoreExplosions"));

            if (!(ignoreExplosions || protection.hasFlag(Flag.Type.ALLOWEXPLOSIONS))) {
                event.setCancelled(true);
            }
        }
    }
}
 
Example 6
Source File: Towny.java    From Modern-LWC with MIT License 6 votes vote down vote up
public void unclaimTowny(TownUnclaimEvent event) throws NotRegisteredException, TownyException {
    if (towny == null) {
        return;
    }
    List<WorldCoord> wcl = AreaSelectionUtil.selectWorldCoordArea(event.getTown(), event.getWorldCoord(),
            new String[]{"auto"});
    wcl = AreaSelectionUtil.filterOwnedBlocks(event.getTown(), wcl);
    for (WorldCoord wc : wcl) {
        PlotBlockData pbd = new PlotBlockData(wc.getTownBlock());
        for (int z = 0; z < pbd.getSize(); z++)
            for (int x = 0; x < pbd.getSize(); x++)
                for (int y = pbd.getHeight(); y > 0; y--) {
                    Block b = event.getWorldCoord().getBukkitWorld().getBlockAt((pbd.getX() * pbd.getSize()) + x, y,
                            (pbd.getZ() * pbd.getSize()) + z);
                    LWC lwc = LWC.getInstance();
                    Protection protection = lwc.getPhysicalDatabase()
                            .loadProtection(event.getWorldCoord().getWorldName(), b.getX(), b.getY(), b.getZ());
                    if (protection != null) {
                        protection.remove();
                    }

                }
    }
}
 
Example 7
Source File: Updater.java    From Modern-LWC with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
public void init() {
    final LWC lwc = LWC.getInstance();
    if (lwc.getConfiguration().getBoolean("core.updateNotifier", true)) {
        lwc.getPlugin().getServer().getScheduler().scheduleAsyncDelayedTask(lwc.getPlugin(), new Runnable() {
            public void run() {
                Object[] updates = Updater.getLastUpdate();
                if (updates.length == 2) {
                    lwc.log("[ModernLWC] New update avaible:");
                    lwc.log("New version: " + updates[0]);
                    lwc.log(
                            "Your version: " + LWC.getInstance().getPlugin().getDescription().getVersion());
                    lwc.log("What's new: " + updates[1]);
                }
            }

        });
    }
}
 
Example 8
Source File: LWCBlockListener.java    From Modern-LWC with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
    if (!LWC.ENABLED) {
        return;
    }

    LWC lwc = LWC.getInstance();

    Block block = event.getBlock();
    if (!lwc.isProtectable(block)) {
        return;
    }

    Protection protection = lwc.findProtection(block);
    if (protection != null) {
        event.setCancelled(true);
    }
}
 
Example 9
Source File: LWCPlayerListener.java    From Modern-LWC with MIT License 5 votes vote down vote up
@EventHandler
public void onDeath(EntityDeathEvent e) {
    Entity entity = e.getEntity();
    if (plugin.getLWC().isProtectable(e.getEntity().getType())) {
        int A = 50000 + entity.getUniqueId().hashCode();
        Player player = e.getEntity().getKiller();
        LWC lwc = LWC.getInstance();
        Protection protection = lwc.getPhysicalDatabase().loadProtection(entity.getWorld().getName(), A, A, A);
        if (protection != null) {
            boolean canAccess = lwc.canAccessProtection(player, protection);
            boolean canAdmin = lwc.canAdminProtection(player, protection);
            try {
                if (player != null) {
                    LWCProtectionDestroyEvent evt = new LWCProtectionDestroyEvent(player, protection,
                            LWCProtectionDestroyEvent.Method.ENTITY_DESTRUCTION, canAccess, canAdmin);
                    lwc.getModuleLoader().dispatchEvent(evt);
                } else {
                    protection.remove();
                    protection.removeAllPermissions();
                    protection.removeCache();
                }
            } catch (Exception ex) {
                if (player != null) {
                    lwc.sendLocale(player, "protection.internalerror", "id", "ENTITY_DEATH");
                }
                lwc.sendLocale(Bukkit.getServer().getConsoleSender(), "protection.internalerror", "id",
                        "ENTITY_DEATH");
                ex.printStackTrace();
            }
        }
    }
}
 
Example 10
Source File: LWC114Listener.java    From Modern-LWC with MIT License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onPlayerTakeLecternBook(PlayerTakeLecternBookEvent event) {
    LWC lwc = LWC.getInstance();
    Protection protection = lwc.findProtection(event.getLectern());
    if (protection == null || protection.isOwner(event.getPlayer()) || protection.getType() == Protection.Type.PUBLIC) {
        return;
    }
    if (protection.getAccess(event.getPlayer().getUniqueId().toString(), Permission.Type.PLAYER) == Permission.Access.NONE) {
        event.setCancelled(true);
    }
}
 
Example 11
Source File: PhysDB.java    From Modern-LWC with MIT License 5 votes vote down vote up
/**
 * Fill the protection cache as much as possible with protections Caches the
 * most recent protections
 */
public void precache() {
    LWC lwc = LWC.getInstance();
    ProtectionCache cache = lwc.getProtectionCache();

    // clear the cache incase we're working on a dirty cache
    cache.clear();

    int precacheSize = lwc.getConfiguration().getInt("core.precache", -1);

    if (precacheSize == -1) {
        precacheSize = lwc.getConfiguration().getInt("core.cacheSize", 10000);
    }
    try {
        statement = prepare(
                "SELECT id, owner, type, x, y, z, data, blockId, world, password, date, last_accessed FROM "
                        + prefix + "protections ORDER BY id DESC LIMIT ?");
        statement.setInt(1, precacheSize);
        statement.setFetchSize(10);

        // scrape the protections from the result set now
        List<Protection> protections = resolveProtections(statement);

        // throw all of the protections in
        for (Protection protection : protections) {
            cache.addProtection(protection);
        }

    } catch (SQLException e) {
        printException(e);
    }
}
 
Example 12
Source File: History.java    From Modern-LWC with MIT License 5 votes vote down vote up
/**
 * Sync this history object to the database when possible
 */
public void save() {
    // if it was not modified, no point in saving it :-)
    if (!modified || saving) {
        return;
    }

    LWC.getInstance();

    // find the protection the history object is attached to
    Protection protection = getProtection();

    // no protection? weird, just sync anyway
    if (protection == null) {
        saveNow();
        return;
    }

    // wait!
    this.saving = true;

    // ensure the protection knows about us
    protection.checkHistory(this);

    // save it when possible
    protection.save();
}
 
Example 13
Source File: Protection.java    From Modern-LWC with MIT License 5 votes vote down vote up
/**
 * Remove the protection from the database
 */
public void remove() {
    if (removed) {
        return;
    }

    LWC lwc = LWC.getInstance();
    removeTemporaryPermissions();

    // we're removing it, so assume there are no changes
    modified = false;
    removing = true;

    // broadcast the removal event
    // we broadcast before actually removing to give them a chance to use
    // any password that would be removed otherwise
    lwc.getModuleLoader().dispatchEvent(
            new LWCProtectionRemovePostEvent(this));

    // mark related transactions as inactive
    for (History history : getRelatedHistory(History.Type.TRANSACTION)) {
        if (history.getStatus() != History.Status.ACTIVE) {
            continue;
        }

        history.setStatus(History.Status.INACTIVE);
    }

    // ensure all history objects for this protection are saved
    checkAndSaveHistory();

    // make the protection immutable
    removed = true;

    // and now finally remove it from the database
    lwc.getDatabaseThread().removeProtection(this);
    lwc.getPhysicalDatabase().removeProtection(id);
    removeCache();
}
 
Example 14
Source File: LimitsModule.java    From Modern-LWC with MIT License 5 votes vote down vote up
/**
 * Check if a player has reached their protection limit for a specific block type
 *
 * @param player
 * @param block
 * @return true if the player reached their limit
 */
public boolean hasReachedLimit(Player player, Block block) {
    if (configuration == null) {
        return false;
    }

    LWC lwc = LWC.getInstance();
    BlockCache blockCache = BlockCache.getInstance();
    int limit = mapProtectionLimit(player, blockCache.getBlockId(block));

    // if they're limit is unlimited, how could they get above it? :)
    if (limit == UNLIMITED) {
        return false;
    }

    Type type = Type.resolve(resolveString(player, "type"));
    int protections; // 0 = *

    switch (type) {
        case DEFAULT:
            protections = lwc.getPhysicalDatabase().getProtectionCount(player.getName());
            break;
        case CUSTOM:
            protections = lwc.getPhysicalDatabase().getProtectionCount(player.getName(), blockCache.getBlockId(block));
            break;
        default:
            throw new UnsupportedOperationException("Limit type " + type.toString() + " is undefined in LimitsModule::hasReachedLimit");
    }

    return protections >= limit;
}
 
Example 15
Source File: LimitsV2.java    From Modern-LWC with MIT License 5 votes vote down vote up
@Override
public int getProtectionCount(Player player, Material material) {
    LWC lwc = LWC.getInstance();
    BlockCache blockCache = BlockCache.getInstance();
    int signCount = 0;
    for (Material sign : SIGNS) {
        signCount += lwc.getPhysicalDatabase().getProtectionCount(player.getName(), blockCache.getBlockId(sign));
    }
    return signCount;
}
 
Example 16
Source File: ProtectionFinder.java    From Modern-LWC with MIT License 4 votes vote down vote up
/**
 * Try and load a protection for a given block. If succeded, cache it locally
 *
 * @param block
 * @param noAutoCache if a match is found, don't cache it to be the protection we use
 * @return
 */
protected Result tryLoadProtection(BlockState block, boolean noAutoCache) {
    if (matchedProtection != null) {
        return Result.E_FOUND;
    }

    LWC lwc = LWC.getInstance();
    ProtectionCache cache = lwc.getProtectionCache();

    // Check the cache
    if ((matchedProtection = cache.getProtection(block)) != null) {
        searched = true;
        if (matchedProtection.getProtectionFinder() == null) {
            fullMatchBlocks();
            matchedProtection.setProtectionFinder(this);
            cache.addProtection(matchedProtection);
        }
        return Result.E_FOUND;
    }

    // Manual intervention is required
    if (block.getType() == Material.REDSTONE_WIRE || block.getType() == Material.REDSTONE_WALL_TORCH ||
            block.getType() == Material.REDSTONE_TORCH) {
        return Result.E_ABORT;
    }

    // don't bother trying to load it if it is not protectable
    if (!lwc.isProtectable(block)) {
        return Result.E_NOT_FOUND;
    }

    // Null-check
    if (block.getWorld() == null) {
        return Result.E_NOT_FOUND;
    }

    Protection protection = lwc.getPhysicalDatabase().loadProtection(block.getWorld().getName(), block.getX(), block.getY(), block.getZ());

    if (protection != null) {
        if (protection.getProtectionFinder() == null) {
            protection.setProtectionFinder(this);
            fullMatchBlocks();
            cache.addProtection(matchedProtection);
        }

        // ensure it's the right block
        if (protection.getBlockId() > 0) {
            if (protection.isBlockInWorld()) {
                if (noAutoCache) {
                    return Result.E_FOUND;
                }

                this.matchedProtection = protection;
                searched = true;
            } else {
                // Removing orrupted protection
                protection.remove();
            }
        }
    }

    return this.matchedProtection != null ? Result.E_FOUND : Result.E_NOT_FOUND;
}
 
Example 17
Source File: Protection.java    From Modern-LWC with MIT License 4 votes vote down vote up
/**
 * Remove the protection from cache
 */
public void removeCache() {
    LWC lwc = LWC.getInstance();
    lwc.getProtectionCache().removeProtection(this);
    radiusRemoveCache();
}
 
Example 18
Source File: BlockCache.java    From Modern-LWC with MIT License 4 votes vote down vote up
/**
 * Initialization for the block cache.
 */
private BlockCache() {
    lwc = LWC.getInstance();
    intBlockCache = new HashMap<>();
    materialBlockCache = new HashMap<>();
}
 
Example 19
Source File: AdminRebuild.java    From Modern-LWC with MIT License 4 votes vote down vote up
/**
 * Attempt to rebuild the database with what we have
 *
 * @param sender
 */
private void rebuildDatabase(CommandSender sender) {
    LWC lwc = LWC.getInstance();
    sender.sendMessage("Now rebuilding the LWC database.");

    // Get all of the currently active history objects
    lwc.getProtectionCache().clear();
    List<History> fullHistory = lwc.getPhysicalDatabase().loadHistory(History.Status.ACTIVE);

    sender.sendMessage("Loaded " + fullHistory.size() + " history objects");

    // Our start time
    long start = System.currentTimeMillis();

    // The amount of protections we created
    int created = 0;

    // The amount of protections we failed to create
    int failed = 0;

    Iterator<History> iter = fullHistory.iterator();
    while (iter.hasNext()) {
        History history = (History) iter.next();

        // Is it active?
        if (history.getProtection() != null) {
            iter.remove();
            continue;
        }

        // Coordinates
        int x = history.getX();
        int y = history.getY();
        int z = history.getZ();

        // Very old history object
        if (x == 0 && y == 0 && z == 0) {
            iter.remove();
            continue;
        }

        // Protection's creator
        String creator = history.getString("creator");

        if (creator == null) {
            sender.sendMessage(String.format("Unable to match owner at Id:%d", history.getId()));
            failed++;
            iter.remove();
            continue;
        }

        // Bruteforce that shit, yo
        Block block = findProtectableBlock(x, y, z);

        if (block == null) {
            sender.sendMessage(String.format("Unable to match block at Id:%d [%d, %d, %d] (this is probably OK)", history.getId(), x, y, z));
            failed++;
            iter.remove();
            continue;
        }

        // Create the protection!
        BlockCache blockCache = BlockCache.getInstance();
        int blockId = blockCache.getBlockId(block);
        if (blockId < 0) {
            continue;
        }
        Protection protection = lwc.getPhysicalDatabase().registerProtection(blockId,
                Protection.Type.PRIVATE, block.getWorld().getName(), creator, "", x, y, z);

        if (protection == null) {
            sender.sendMessage(String.format("Failed to create protection at Id:%d", history.getId()));
            failed++;
            iter.remove();
            continue;
        }

        // Hell yeah
        created++;
        history.remove();
        protection.saveNow();
        iter.remove();

        // Clean up the cache, we want to conserve as much memory as possible at this time
        lwc.getProtectionCache().clear();
    }

    int total = created + failed; // the total amount of history objects operated on
    long runningTime = System.currentTimeMillis() - start;
    int runningTimeSeconds = (int) runningTime / 1000;
    float ratio = ((float) created / (total)) * 100;
    sender.sendMessage(String.format("LWC rebuild complete (%ds). %.2f%% conversion ratio; %d success and %d failures", runningTimeSeconds, ratio, created, failed));
}
 
Example 20
Source File: MySQLPost200.java    From Modern-LWC with MIT License 4 votes vote down vote up
/**
 * Check for required SQLite->MySQL conversion
 */
public void run() {
    LWC lwc = LWC.getInstance();
    PhysDB physicalDatabase = lwc.getPhysicalDatabase();

    // this patcher only does something exciting if you have mysql enabled
    // :-)
    if (physicalDatabase.getType() != Type.MySQL) {
        return;
    }

    // this patcher only does something exciting if the old SQLite database
    // still exists :-)
    String database = lwc.getConfiguration().getString("database.path");

    if (database == null || database.trim().equals("")) {
        database = "plugins/LWC/lwc.db";
    }

    File file = new File(database);
    if (!file.exists()) {
        return;
    }

    logger.info("######################################################");
    logger.info("######################################################");
    logger.info("SQLite to MySQL conversion required");

    // rev up those sqlite databases because I sure am hungry for some data...
    DatabaseMigrator migrator = new DatabaseMigrator();
    lwc.reloadDatabase();

    // Load the sqlite database
    PhysDB sqlite = new PhysDB(Type.SQLite);

    try {
        sqlite.connect();
        sqlite.load();
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (migrator.migrate(sqlite, lwc.getPhysicalDatabase())) {
        logger.info("Successfully converted.");
        logger.info("Renaming \"" + database + "\" to \"" + database + ".old\"");
        if (!file.renameTo(new File(database + ".old"))) {
            logger.info("NOTICE: FAILED TO RENAME lwc.db!! Please rename this manually!");
        }

        logger.info("SQLite to MySQL conversion is now complete!\n");
        logger.info("Thank you!");
    } else {
        logger.info("#### SEVERE ERROR: Something bad happened when converting the database (Oops!)");
    }

    logger.info("######################################################");
    logger.info("######################################################");
}