Merge branch 'dev' into 'patch-3'

# Conflicts:
#   src/main/java/com/eu/habbo/messages/incoming/guilds/RequestGuildBuyEvent.java
This commit is contained in:
Harmonic 2020-09-25 17:03:57 -04:00
commit e24b2afa31
873 changed files with 5740 additions and 6085 deletions

5
.gitignore vendored
View File

@ -6,11 +6,12 @@ target/**
TODO.txt TODO.txt
packet.pkt packet.pkt
plugins/** plugins/**
src/main/resources/
src/test/ src/test/
target/ target/
config.ini config.ini
*.txt *.txt
*.jar *.jar
*.log *.log
*.zip *.zip
.DS_Store

View File

@ -1,15 +1,18 @@
image: maven:latest image: maven:latest
cache: stages:
paths: - build
- target/
build: build:
stage: build
script: script:
- mvn package - mvn package
only: only:
- dev changes:
- master - src/**/*
- pom.xml
artifacts: artifacts:
paths: expire_in: 2 weeks
- target/Habbo-*.jar paths:
- target/Habbo-*.jar

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "morningstar-default-database"]
path = morningstar-default-database
url = https://git.krews.org/morningstar/morningstar-default-database

View File

@ -11,8 +11,8 @@ TheGeneral's own words were "dont like it then dont use it". We did not like wha
Arcturus Morningstar is released under the [GNU General Public License v3](https://www.gnu.org/licenses/gpl-3.0.txt). Arcturus Morningstar is released under the [GNU General Public License v3](https://www.gnu.org/licenses/gpl-3.0.txt).
## Versions ## ## Versions ##
![image](https://img.shields.io/badge/VERSION-2.3.2-success.svg?style=for-the-badge&logo=appveyor) ![image](https://img.shields.io/badge/VERSION-2.4.0-success.svg?style=for-the-badge&logo=appveyor)
![image](https://img.shields.io/badge/STATUS-STABLE-green.svg?style=for-the-badge&logo=appveyor) ![image](https://img.shields.io/badge/STATUS-UNSTABLE-red.svg?style=for-the-badge&logo=appveyor)
Compiled Download: https://git.krews.org/morningstar/Arcturus-Community/releases Compiled Download: https://git.krews.org/morningstar/Arcturus-Community/releases
@ -34,6 +34,8 @@ When making an bug report or a feature request use the template we provide so th
- Skeletor - Skeletor
- z - z
- ArpyAge - ArpyAge
- Mike
## Discord ## ## Discord ##
Join us on Discord at https://discord.gg/BzfFsTp Join us on Discord at https://discord.gg/BzfFsTp

74
pom.xml
View File

@ -6,7 +6,7 @@
<groupId>com.eu.habbo</groupId> <groupId>com.eu.habbo</groupId>
<artifactId>Habbo</artifactId> <artifactId>Habbo</artifactId>
<version>2.3.2</version> <version>2.4.0</version>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -32,7 +32,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId> <artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version> <version>3.8.1</version>
<configuration> <configuration>
<source>1.8</source> <source>1.8</source>
<target>1.8</target> <target>1.8</target>
@ -42,7 +42,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId> <artifactId>maven-assembly-plugin</artifactId>
<version>2.4.1</version> <version>3.3.0</version>
<configuration> <configuration>
<descriptorRefs> <descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef> <descriptorRef>jar-with-dependencies</descriptorRef>
@ -67,7 +67,7 @@
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId> <artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.0</version> <version>3.2.0</version>
<configuration> <configuration>
<additionalOptions><additionalOption>-Xdoclint:none</additionalOption></additionalOptions> <additionalOptions><additionalOption>-Xdoclint:none</additionalOption></additionalOptions>
<show>public</show> <show>public</show>
@ -92,50 +92,21 @@
<dependency> <dependency>
<groupId>io.netty</groupId> <groupId>io.netty</groupId>
<artifactId>netty-all</artifactId> <artifactId>netty-all</artifactId>
<version>4.1.36.Final</version> <version>4.1.49.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.fusesource.jansi/jansi -->
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>1.18</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec-http</artifactId>
<version>4.1.36.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec-http2</artifactId>
<version>4.1.36.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId>
<version>4.1.36.Final</version>
<scope>compile</scope>
</dependency> </dependency>
<!-- GSON --> <!-- GSON -->
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
<version>2.8.4</version> <version>2.8.6</version>
</dependency> </dependency>
<!-- MySQL Connector --> <!-- MySQL Connector -->
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version> <version>5.1.49</version>
<scope>runtime</scope> <scope>runtime</scope>
</dependency> </dependency>
@ -151,16 +122,17 @@
<dependency> <dependency>
<groupId>com.zaxxer</groupId> <groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId> <artifactId>HikariCP</artifactId>
<version>3.1.0</version> <version>3.4.3</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>3.7</version> <version>3.10</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId> <artifactId>commons-math3</artifactId>
@ -171,35 +143,27 @@
<dependency> <dependency>
<groupId>org.jsoup</groupId> <groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId> <artifactId>jsoup</artifactId>
<version>1.11.3</version> <version>1.13.1</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>ch.qos.logback</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>logback-classic</artifactId>
<version>1.7.25</version> <version>1.2.3</version>
<scope>compile</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.fusesource.jansi</groupId>
<artifactId>slf4j-simple</artifactId> <artifactId>jansi</artifactId>
<version>1.7.25</version> <version>1.18</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>joda-time</groupId> <groupId>joda-time</groupId>
<artifactId>joda-time</artifactId> <artifactId>joda-time</artifactId>
<version>2.9.9</version> <version>2.10.6</version>
</dependency> </dependency>
</dependencies> </dependencies>
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
</project> </project>

View File

@ -1,6 +1,6 @@
#DATABASE UPDATE: 1.0.6 -> 1.0.7 #DATABASE UPDATE: 1.0.6 -> 1.0.7
ALTER TABLE `permissions` ADD `acc_update_notifications` ENUM( '0', '1' ) NOT NULL DEFAULT '0'; ALTER TABLE `permissions` ADD `"acc_update_notifications"` ENUM( '0', '1' ) NOT NULL DEFAULT '0';
DELETE FROM emulator_settings WHERE `key` LIKE 'emulator.version'; DELETE FROM emulator_settings WHERE `key` LIKE 'emulator.version';
#END DATABASE UPDATE: 1.0.5 -> 1.0.6 #END DATABASE UPDATE: 1.0.5 -> 1.0.6

View File

@ -0,0 +1,3 @@
INSERT INTO `emulator_settings`(`key`, `value`) VALUES ('hotel.room.stickies.max', '200');
INSERT INTO `emulator_settings`(`key`, `value`) VALUES ('retro.style.homeroom', '1');

View File

@ -0,0 +1,52 @@
-- Hide email from specific ranks.
ALTER TABLE `permissions` ADD `acc_hide_mail` ENUM('0', '1') NOT NULL DEFAULT '0' AFTER `acc_hide_ip`;
-- Flood with rights.
INSERT INTO `emulator_settings` (`key`, `value`) VALUES ('flood.with.rights', '0');
-- Softkick command.
ALTER TABLE `permissions` ADD `cmd_softkick` ENUM('0', '1') NOT NULL DEFAULT '0' AFTER `cmd_kickall`;
INSERT INTO `emulator_texts` (`key`, `value`) VALUES ('commands.keys.cmd_softkick', 'softkick');
INSERT INTO `emulator_texts` (`key`, `value`) VALUES ('commands.error.cmd_softkick_not_found', '%user% not found');
INSERT INTO `emulator_texts` (`key`, `value`) VALUES ('commands.error.cmd_softkick_error_self', 'You can not softkick yourself!');
-- Rank ignoring
INSERT INTO `emulator_texts` (`key`, `value`) VALUES ('generic.error.ignore_higher_rank', 'You can\'t ignore this user.');
INSERT INTO `emulator_settings`(`key`, `value`) VALUES ('hotel.allow.ignore.staffs', '1');
-- Inventory Limiting
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('error.bots.max.inventory', 'You can\'t buy or pickup anymore bots until you place some, the maximum amount of bots you are allowed is %amount%.');
UPDATE `emulator_texts` SET `value` = 'You\'ve reached the maximum amount of pets in your inventory! The Limit is %amount%!' WHERE `key` = 'error.pets.max.inventory';
-- Tradelock counter
ALTER TABLE `users_settings` ADD `tradelock_amount` INT(11) NOT NULL DEFAULT '0' AFTER `helper_level`;
-- Gift wrapping configuration
INSERT INTO `emulator_settings`(`key`, `value`) VALUES ('hotel.gifts.box_types', '0,1,2,3,4,5,6,8');
INSERT INTO `emulator_settings`(`key`, `value`) VALUES ('hotel.gifts.ribbon_types', '0,1,2,3,4,5,6,7,8,9,10');
-- Configurable mute time
INSERT INTO `emulator_settings`(`key`, `value`) VALUES ('hotel.flood.mute.time', '30');
-- TraxManager Jukebox Limits
INSERT INTO `emulator_settings`(`key`, `value`) VALUES ('hotel.jukebox.limit.large', '20');
INSERT INTO `emulator_settings`(`key`, `value`) VALUES ('hotel.jukebox.limit.normal', '10');
-- Background Toner Scripter Warning
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('scripter.warning.item.bgtoner.permission', '%username% tried to change the background toner without rights in %room% owned by %owner%');
-- Table structure for room_trax
DROP TABLE IF EXISTS `room_trax`;
CREATE TABLE `room_trax` (
`room_id` int(11) NOT NULL,
`trax_item_id` int(11) NOT NULL
) ENGINE = InnoDB CHARACTER SET = armscii8 COLLATE = armscii8_general_ci ROW_FORMAT = Compact;
-- Table structure for trax_playlist
DROP TABLE IF EXISTS `trax_playlist`;
CREATE TABLE `trax_playlist` (
`trax_item_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL
) ENGINE = InnoDB CHARACTER SET = armscii8 COLLATE = armscii8_general_ci ROW_FORMAT = Compact;

View File

@ -0,0 +1,2 @@
-- Recycler value fix
INSERT INTO `emulator_settings` (`key`, `value`) VALUES ('recycler.value', '8');

View File

@ -0,0 +1,3 @@
-- Adds config value for max amount of people to move per roller. Default is like habbo.
INSERT INTO `emulator_settings`(`key`, `value`) VALUES ('hotel.room.rollers.roll_avatars.max', '1');
INSERT INTO `emulator_settings`(`key`, `value`) VALUES ('hotel.nux.gifts.enabled', '0');

View File

@ -1,9 +1,9 @@
package com.eu.habbo; package com.eu.habbo;
import com.eu.habbo.core.CleanerThread; import ch.qos.logback.classic.Level;
import com.eu.habbo.core.ConfigurationManager; import ch.qos.logback.classic.spi.ILoggingEvent;
import com.eu.habbo.core.Logging; import ch.qos.logback.core.ConsoleAppender;
import com.eu.habbo.core.TextsManager; import com.eu.habbo.core.*;
import com.eu.habbo.core.consolecommands.ConsoleCommand; import com.eu.habbo.core.consolecommands.ConsoleCommand;
import com.eu.habbo.database.Database; import com.eu.habbo.database.Database;
import com.eu.habbo.habbohotel.GameEnvironment; import com.eu.habbo.habbohotel.GameEnvironment;
@ -17,7 +17,8 @@ import com.eu.habbo.plugin.events.emulator.EmulatorStartShutdownEvent;
import com.eu.habbo.plugin.events.emulator.EmulatorStoppedEvent; import com.eu.habbo.plugin.events.emulator.EmulatorStoppedEvent;
import com.eu.habbo.threading.ThreadPooling; import com.eu.habbo.threading.ThreadPooling;
import com.eu.habbo.util.imager.badges.BadgeImager; import com.eu.habbo.util.imager.badges.BadgeImager;
import org.fusesource.jansi.AnsiConsole; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*; import java.io.*;
import java.security.MessageDigest; import java.security.MessageDigest;
@ -26,21 +27,19 @@ import java.text.SimpleDateFormat;
import java.util.Date; import java.util.Date;
import java.util.Locale; import java.util.Locale;
import java.util.Random; import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
public final class Emulator { public final class Emulator {
private static final Logger LOGGER = LoggerFactory.getLogger(Emulator.class);
private static final String OS_NAME = System.getProperty("os.name");
private static final String CLASS_PATH = System.getProperty("java.class.path");
public final static int MAJOR = 2; public final static int MAJOR = 2;
public final static int MINOR = 3; public final static int MINOR = 4;
public final static int BUILD = 2; public final static int BUILD = 0;
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_BLUE = "\u001B[34m"; public final static String PREVIEW = "";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_WHITE = "\u001B[37m";
public static final String ANSI_YELLOW = "\u001B[33m";
public final static String PREVIEW = "RC-3";
public static final String version = "Arcturus Morningstar" + " " + MAJOR + "." + MINOR + "." + BUILD; public static final String version = "Arcturus Morningstar" + " " + MAJOR + "." + MINOR + "." + BUILD;
private static final String logo = private static final String logo =
@ -58,21 +57,20 @@ public final class Emulator {
public static boolean isShuttingDown = false; public static boolean isShuttingDown = false;
public static boolean stopped = false; public static boolean stopped = false;
public static boolean debugging = false; public static boolean debugging = false;
private static String classPath = System.getProperty("java.class.path");
private static String osName = System.getProperty("os.name");
private static int timeStarted = 0; private static int timeStarted = 0;
private static Runtime runtime; private static Runtime runtime;
private static ConfigurationManager config; private static ConfigurationManager config;
private static CryptoConfig crypto;
private static TextsManager texts; private static TextsManager texts;
private static GameServer gameServer; private static GameServer gameServer;
private static RCONServer rconServer; private static RCONServer rconServer;
private static CameraClient cameraClient; private static CameraClient cameraClient;
private static Database database;
private static Logging logging; private static Logging logging;
private static Database database;
private static DatabaseLogger databaseLogger;
private static ThreadPooling threading; private static ThreadPooling threading;
private static GameEnvironment gameEnvironment; private static GameEnvironment gameEnvironment;
private static PluginManager pluginManager; private static PluginManager pluginManager;
private static Random random;
private static BadgeImager badgeImager; private static BadgeImager badgeImager;
static { static {
@ -87,26 +85,42 @@ public final class Emulator {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
try { try {
if (osName.startsWith("Windows") && (!classPath.contains("idea_rt.jar"))) { // Check if running on Windows and not in IntelliJ.
AnsiConsole.systemInstall(); // If so, we need to reconfigure the console appender and enable Jansi for colors.
if (OS_NAME.startsWith("Windows") && !CLASS_PATH.contains("idea_rt.jar")) {
ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
ConsoleAppender<ILoggingEvent> appender = (ConsoleAppender<ILoggingEvent>) root.getAppender("Console");
appender.stop();
appender.setWithJansi(true);
appender.start();
} }
Locale.setDefault(new Locale("en")); Locale.setDefault(new Locale("en"));
setBuild(); setBuild();
Emulator.stopped = false; Emulator.stopped = false;
ConsoleCommand.load(); ConsoleCommand.load();
Emulator.logging = new Logging(); Emulator.logging = new Logging();
System.out.println(ANSI_PURPLE + logo );
System.out.println(ANSI_WHITE + "This project is for educational purposes only. This Emulator is an open-source fork of Arcturus created by TheGeneral."); System.out.println(logo);
System.out.println(ANSI_BLUE + "[VERSION] " + ANSI_WHITE + version);
System.out.println(ANSI_RED + "[BUILD] " + ANSI_WHITE + build + "\n"); LOGGER.info("This project is for educational purposes only. This Emulator is an open-source fork of Arcturus created by TheGeneral.");
System.out.println(ANSI_YELLOW + "[KREWS] " + ANSI_WHITE + "Remember to sign up your hotel to join our toplist beta at https://bit.ly/2NN0rxq" ); LOGGER.info("Version: {}", version);
System.out.println(ANSI_YELLOW + "[KREWS] " + ANSI_WHITE + "Join our discord at https://discord.gg/syuqgN" + "\n"); LOGGER.info("Build: {}", build);
random = new Random(); LOGGER.info("Remember to sign up your hotel to join our toplist beta at https://bit.ly/2NN0rxq");
LOGGER.info("Join our discord at https://discord.gg/syuqgN");
long startTime = System.nanoTime(); long startTime = System.nanoTime();
Emulator.runtime = Runtime.getRuntime(); Emulator.runtime = Runtime.getRuntime();
Emulator.config = new ConfigurationManager("config.ini"); Emulator.config = new ConfigurationManager("config.ini");
Emulator.crypto = new CryptoConfig(
Emulator.getConfig().getBoolean("enc.enabled", false),
Emulator.getConfig().getValue("enc.e"),
Emulator.getConfig().getValue("enc.n"),
Emulator.getConfig().getValue("enc.d"));
Emulator.database = new Database(Emulator.getConfig()); Emulator.database = new Database(Emulator.getConfig());
Emulator.databaseLogger = new DatabaseLogger();
Emulator.config.loaded = true; Emulator.config.loaded = true;
Emulator.config.loadFromDatabase(); Emulator.config.loadFromDatabase();
Emulator.threading = new ThreadPooling(Emulator.getConfig().getInt("runtime.threads")); Emulator.threading = new ThreadPooling(Emulator.getConfig().getInt("runtime.threads"));
@ -126,13 +140,17 @@ public final class Emulator {
Emulator.rconServer.initializePipeline(); Emulator.rconServer.initializePipeline();
Emulator.rconServer.connect(); Emulator.rconServer.connect();
Emulator.badgeImager = new BadgeImager(); Emulator.badgeImager = new BadgeImager();
Emulator.getLogging().logStart("Arcturus Morningstar has succesfully loaded. You're running: " + Emulator.version);
Emulator.getLogging().logStart("System launched in: " + (System.nanoTime() - startTime) / 1e6 + "ms. Using: " + (Runtime.getRuntime().availableProcessors() * 2) + " threads!"); LOGGER.info("Arcturus Morningstar has succesfully loaded.");
Emulator.getLogging().logStart("Memory: " + (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024) + "/" + (runtime.freeMemory()) / (1024 * 1024) + "MB"); LOGGER.info("System launched in: {}ms. Using {} threads!", (System.nanoTime() - startTime) / 1e6, Runtime.getRuntime().availableProcessors() * 2);
LOGGER.info("Memory: {}/{}MB", (runtime.totalMemory() - runtime.freeMemory()) / (1024 * 1024), (runtime.freeMemory()) / (1024 * 1024));
Emulator.debugging = Emulator.getConfig().getBoolean("debug.mode"); Emulator.debugging = Emulator.getConfig().getBoolean("debug.mode");
if (debugging) { if (debugging) {
Emulator.getLogging().logDebugLine("Debugging Enabled!"); ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.DEBUG);
LOGGER.debug("Debugging enabled.");
} }
Emulator.getPluginManager().fireEvent(new EmulatorLoadedEvent()); Emulator.getPluginManager().fireEvent(new EmulatorLoadedEvent());
@ -140,7 +158,9 @@ public final class Emulator {
Emulator.timeStarted = getIntUnixTimestamp(); Emulator.timeStarted = getIntUnixTimestamp();
if (Emulator.getConfig().getInt("runtime.threads") < (Runtime.getRuntime().availableProcessors() * 2)) { if (Emulator.getConfig().getInt("runtime.threads") < (Runtime.getRuntime().availableProcessors() * 2)) {
Emulator.getLogging().logStart("Emulator settings runtime.threads (" + Emulator.getConfig().getInt("runtime.threads") + ") can be increased to " + (Runtime.getRuntime().availableProcessors() * 2) + " to possibly increase performance."); LOGGER.warn("Emulator settings runtime.threads ({}) can be increased to {} to possibly increase performance.",
Emulator.getConfig().getInt("runtime.threads"),
Runtime.getRuntime().availableProcessors() * 2);
} }
@ -151,7 +171,6 @@ public final class Emulator {
while (!isShuttingDown && isReady) { while (!isShuttingDown && isReady) {
try { try {
String line = reader.readLine(); String line = reader.readLine();
if (line != null) { if (line != null) {
@ -160,7 +179,7 @@ public final class Emulator {
System.out.println("Waiting for command: "); System.out.println("Waiting for command: ");
} catch (Exception e) { } catch (Exception e) {
if (!(e instanceof IOException && e.getMessage().equals("Bad file descriptor"))) { if (!(e instanceof IOException && e.getMessage().equals("Bad file descriptor"))) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Error while reading command", e);
} }
} }
} }
@ -196,11 +215,12 @@ public final class Emulator {
} }
private static void dispose() { private static void dispose() {
Emulator.getThreading().setCanAdd(false); Emulator.getThreading().setCanAdd(false);
Emulator.isShuttingDown = true; Emulator.isShuttingDown = true;
Emulator.isReady = false; Emulator.isReady = false;
Emulator.getLogging().logShutdownLine("Stopping Arcturus Emulator " + version + "...");
LOGGER.info("Stopping Arcturus Morningstar {}", version);
try { try {
if (Emulator.getPluginManager() != null) if (Emulator.getPluginManager() != null)
Emulator.getPluginManager().fireEvent(new EmulatorStartShutdownEvent()); Emulator.getPluginManager().fireEvent(new EmulatorStartShutdownEvent());
@ -219,7 +239,6 @@ public final class Emulator {
} catch (Exception e) { } catch (Exception e) {
} }
try { try {
if (Emulator.gameEnvironment != null) if (Emulator.gameEnvironment != null)
Emulator.gameEnvironment.dispose(); Emulator.gameEnvironment.dispose();
@ -238,8 +257,6 @@ public final class Emulator {
} catch (Exception e) { } catch (Exception e) {
} }
Emulator.getLogging().saveLogs();
try { try {
if (Emulator.config != null) { if (Emulator.config != null) {
Emulator.config.saveToDatabase(); Emulator.config.saveToDatabase();
@ -252,16 +269,17 @@ public final class Emulator {
Emulator.gameServer.stop(); Emulator.gameServer.stop();
} catch (Exception e) { } catch (Exception e) {
} }
Emulator.getLogging().logShutdownLine("Stopped Arcturus Emulator " + version + "...");
LOGGER.info("Stopped Arcturus Morningstar {}", version);
if (Emulator.database != null) { if (Emulator.database != null) {
Emulator.getDatabase().dispose(); Emulator.getDatabase().dispose();
} }
Emulator.stopped = true; Emulator.stopped = true;
if (osName.startsWith("Windows") && (!classPath.contains("idea_rt.jar"))) { // if (osName.startsWith("Windows") && (!classPath.contains("idea_rt.jar"))) {
AnsiConsole.systemUninstall(); // AnsiConsole.systemUninstall();
} // }
try { try {
if (Emulator.threading != null) if (Emulator.threading != null)
@ -274,6 +292,10 @@ public final class Emulator {
return config; return config;
} }
public static CryptoConfig getCrypto() {
return crypto;
}
public static TextsManager getTexts() { public static TextsManager getTexts() {
return texts; return texts;
} }
@ -282,6 +304,10 @@ public final class Emulator {
return database; return database;
} }
public static DatabaseLogger getDatabaseLogger() {
return databaseLogger;
}
public static Runtime getRuntime() { public static Runtime getRuntime() {
return runtime; return runtime;
} }
@ -294,6 +320,10 @@ public final class Emulator {
return rconServer; return rconServer;
} }
/**
* @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
*/
@Deprecated
public static Logging getLogging() { public static Logging getLogging() {
return logging; return logging;
} }
@ -311,7 +341,7 @@ public final class Emulator {
} }
public static Random getRandom() { public static Random getRandom() {
return random; return ThreadLocalRandom.current();
} }
public static BadgeImager getBadgeImager() { public static BadgeImager getBadgeImager() {
@ -354,7 +384,7 @@ public final class Emulator {
try { try {
res = format.parse(date); res = format.parse(date);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Error parsing date", e);
} }
return res; return res;
} }

View File

@ -6,6 +6,8 @@ import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.messages.incoming.friends.SearchUserEvent; import com.eu.habbo.messages.incoming.friends.SearchUserEvent;
import com.eu.habbo.messages.incoming.navigator.SearchRoomsEvent; import com.eu.habbo.messages.incoming.navigator.SearchRoomsEvent;
import com.eu.habbo.threading.runnables.AchievementUpdater; import com.eu.habbo.threading.runnables.AchievementUpdater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -15,57 +17,26 @@ import java.util.Map;
public class CleanerThread implements Runnable { public class CleanerThread implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(CleanerThread.class);
public static final int DELAY = 10000; private static final int DELAY = 10000;
private static final int RELOAD_HALL_OF_FAME = 1800;
private static final int RELOAD_NEWS_LIST = 3600;
public static final int RELOAD_HALL_OF_FAME = 1800; private static final int REMOVE_INACTIVE_ROOMS = 120;
private static final int REMOVE_INACTIVE_GUILDS = 60;
private static final int REMOVE_INACTIVE_TOURS = 600;
public static final int RELOAD_NEWS_LIST = 3600; private static final int SAVE_ERROR_LOGS = 30;
private static final int CLEAR_CACHED_VALUES = 60 * 60;
public static final int REMOVE_INACTIVE_ROOMS = 120;
public static final int REMOVE_INACTIVE_GUILDS = 60;
public static final int REMOVE_INACTIVE_TOURS = 600;
public static final int SAVE_ERROR_LOGS = 30;
public static final int CLEAR_CACHED_VALUES = 60 * 60;
private static final int CALLBACK_TIME = 60 * 15; private static final int CALLBACK_TIME = 60 * 15;
private static int LAST_HOF_RELOAD = Emulator.getIntUnixTimestamp(); private static int LAST_HOF_RELOAD = Emulator.getIntUnixTimestamp();
private static int LAST_NL_RELOAD = Emulator.getIntUnixTimestamp(); private static int LAST_NL_RELOAD = Emulator.getIntUnixTimestamp();
private static int LAST_INACTIVE_ROOMS_CLEARED = Emulator.getIntUnixTimestamp(); private static int LAST_INACTIVE_ROOMS_CLEARED = Emulator.getIntUnixTimestamp();
private static int LAST_INACTIVE_GUILDS_CLEARED = Emulator.getIntUnixTimestamp(); private static int LAST_INACTIVE_GUILDS_CLEARED = Emulator.getIntUnixTimestamp();
private static int LAST_INACTIVE_TOURS_CLEARED = Emulator.getIntUnixTimestamp(); private static int LAST_INACTIVE_TOURS_CLEARED = Emulator.getIntUnixTimestamp();
private static int LAST_ERROR_LOGS_SAVED = Emulator.getIntUnixTimestamp(); private static int LAST_ERROR_LOGS_SAVED = Emulator.getIntUnixTimestamp();
private static int LAST_DAILY_REFILL = Emulator.getIntUnixTimestamp(); private static int LAST_DAILY_REFILL = Emulator.getIntUnixTimestamp();
private static int LAST_CALLBACK = Emulator.getIntUnixTimestamp(); private static int LAST_CALLBACK = Emulator.getIntUnixTimestamp();
private static int LAST_HABBO_CACHE_CLEARED = Emulator.getIntUnixTimestamp(); private static int LAST_HABBO_CACHE_CLEARED = Emulator.getIntUnixTimestamp();
public CleanerThread() { public CleanerThread() {
@ -110,7 +81,7 @@ public class CleanerThread implements Runnable {
} }
if (time - LAST_ERROR_LOGS_SAVED > SAVE_ERROR_LOGS) { if (time - LAST_ERROR_LOGS_SAVED > SAVE_ERROR_LOGS) {
Emulator.getLogging().saveLogs(); Emulator.getDatabaseLogger().save();
LAST_ERROR_LOGS_SAVED = time; LAST_ERROR_LOGS_SAVED = time;
} }
@ -156,9 +127,10 @@ public class CleanerThread implements Runnable {
statement.execute("DELETE FROM users_effects WHERE total <= 0"); statement.execute("DELETE FROM users_effects WHERE total <= 0");
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
Emulator.getLogging().logStart("Database -> Cleaned!");
LOGGER.info("Database -> Cleaned!");
} }
public void refillDailyRespects() { public void refillDailyRespects() {
@ -167,7 +139,7 @@ public class CleanerThread implements Runnable {
statement.setInt(2, Emulator.getConfig().getInt("hotel.daily.respect.pets")); statement.setInt(2, Emulator.getConfig().getInt("hotel.daily.respect.pets"));
statement.executeUpdate(); statement.executeUpdate();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
if (Emulator.isReady) { if (Emulator.isReady) {
@ -188,7 +160,7 @@ public class CleanerThread implements Runnable {
habbo.clearCaches(); habbo.clearCaches();
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
} }

View File

@ -6,8 +6,9 @@ import com.eu.habbo.habbohotel.commands.Command;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public class CommandLog implements Loggable { public class CommandLog implements DatabaseLoggable {
public static final String insertQuery = "INSERT INTO commandlogs (`user_id`, `timestamp`, `command`, `params`, `succes`) VALUES (?, ?, ?, ?, ?)";
private static final String INSERT_QUERY = "INSERT INTO commandlogs (`user_id`, `timestamp`, `command`, `params`, `succes`) VALUES (?, ?, ?, ?, ?)";
private final int userId; private final int userId;
private final int timestamp = Emulator.getIntUnixTimestamp(); private final int timestamp = Emulator.getIntUnixTimestamp();
@ -15,7 +16,6 @@ public class CommandLog implements Loggable {
private final String params; private final String params;
private final boolean succes; private final boolean succes;
public CommandLog(int userId, Command command, String params, boolean succes) { public CommandLog(int userId, Command command, String params, boolean succes) {
this.userId = userId; this.userId = userId;
this.command = command; this.command = command;
@ -23,6 +23,11 @@ public class CommandLog implements Loggable {
this.succes = succes; this.succes = succes;
} }
@Override
public String getQuery() {
return CommandLog.INSERT_QUERY;
}
@Override @Override
public void log(PreparedStatement statement) throws SQLException { public void log(PreparedStatement statement) throws SQLException {
statement.setInt(1, this.userId); statement.setInt(1, this.userId);
@ -32,4 +37,5 @@ public class CommandLog implements Loggable {
statement.setString(5, this.succes ? "yes" : "no"); statement.setString(5, this.succes ? "yes" : "no");
statement.addBatch(); statement.addBatch();
} }
} }

View File

@ -2,6 +2,9 @@ package com.eu.habbo.core;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.plugin.events.emulator.EmulatorConfigUpdatedEvent; import com.eu.habbo.plugin.events.emulator.EmulatorConfigUpdatedEvent;
import gnu.trove.map.hash.THashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
@ -13,38 +16,85 @@ import java.util.Properties;
public class ConfigurationManager { public class ConfigurationManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationManager.class);
private final Properties properties; private final Properties properties;
private final String configurationPath; private final String configurationPath;
public boolean loaded = false; public boolean loaded = false;
public boolean isLoading = false; public boolean isLoading = false;
public ConfigurationManager(String configurationPath) throws Exception { public ConfigurationManager(String configurationPath) {
this.properties = new Properties(); this.properties = new Properties();
this.configurationPath = configurationPath; this.configurationPath = configurationPath;
this.reload(); this.reload();
} }
public void reload() { public void reload() {
this.isLoading = true; this.isLoading = true;
this.properties.clear(); this.properties.clear();
InputStream input = null; InputStream input = null;
try { String envDbHostname = System.getenv("DB_HOSTNAME");
File f = new File(this.configurationPath);
input = new FileInputStream(f);
this.properties.load(input);
} catch (IOException ex) { boolean useEnvVarsForDbConnection = false;
Emulator.getLogging().logErrorLine("[CRITICAL] FAILED TO LOAD CONFIG FILE! (" + this.configurationPath + ")");
ex.printStackTrace(); if(envDbHostname != null)
} finally { {
if (input != null) { useEnvVarsForDbConnection = envDbHostname.length() > 1;
try { }
input.close();
} catch (IOException e) { if (!useEnvVarsForDbConnection) {
e.printStackTrace(); try {
File f = new File(this.configurationPath);
input = new FileInputStream(f);
this.properties.load(input);
} catch (IOException ex) {
LOGGER.error("Failed to load config file.", ex);
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
Map<String, String> envMapping = new THashMap<>();
// Database section
envMapping.put("db.hostname", "DB_HOSTNAME");
envMapping.put("db.port", "DB_PORT");
envMapping.put("db.database", "DB_DATABASE");
envMapping.put("db.username", "DB_USERNAME");
envMapping.put("db.password", "DB_PASSWORD");
envMapping.put("db.params", "DB_PARAMS");
// Game Configuration
envMapping.put("game.host", "EMU_HOST");
envMapping.put("game.port", "EMU_PORT");
// RCON
envMapping.put("rcon.host", "RCON_HOST");
envMapping.put("rcon.port", "RCON_PORT");
envMapping.put("rcon.allowed", "RCON_ALLOWED");
// Runtime
envMapping.put("runtime.threads", "RT_THREADS");
envMapping.put("logging.errors.runtime", "RT_LOG_ERRORS");
for (Map.Entry<String, String> entry : envMapping.entrySet()) {
String envValue = System.getenv(entry.getValue());
if (envValue == null || envValue.length() == 0) {
LOGGER.info("Cannot find environment-value for variable `" + entry.getValue() + "`");
} else {
this.properties.setProperty(entry.getKey(), envValue);
} }
} }
} }
@ -54,16 +104,15 @@ public class ConfigurationManager {
} }
this.isLoading = false; this.isLoading = false;
Emulator.getLogging().logStart("Configuration Manager -> Loaded!"); LOGGER.info("Configuration Manager -> Loaded!");
if (Emulator.getPluginManager() != null) { if (Emulator.getPluginManager() != null) {
Emulator.getPluginManager().fireEvent(new EmulatorConfigUpdatedEvent()); Emulator.getPluginManager().fireEvent(new EmulatorConfigUpdatedEvent());
} }
} }
public void loadFromDatabase() { public void loadFromDatabase() {
Emulator.getLogging().logStart("Loading configuration from database..."); LOGGER.info("Loading configuration from database...");
long millis = System.currentTimeMillis(); long millis = System.currentTimeMillis();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement()) { try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement()) {
@ -75,10 +124,10 @@ public class ConfigurationManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
Emulator.getLogging().logStart("Configuration -> loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("Configuration -> loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} }
public void saveToDatabase() { public void saveToDatabase() {
@ -89,7 +138,7 @@ public class ConfigurationManager {
statement.executeUpdate(); statement.executeUpdate();
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -104,17 +153,15 @@ public class ConfigurationManager {
return defaultValue; return defaultValue;
if (!this.properties.containsKey(key)) { if (!this.properties.containsKey(key)) {
Emulator.getLogging().logErrorLine("[CONFIG] Key not found: " + key); LOGGER.error("Config key not found {}", key);
} }
return this.properties.getProperty(key, defaultValue); return this.properties.getProperty(key, defaultValue);
} }
public boolean getBoolean(String key) { public boolean getBoolean(String key) {
return this.getBoolean(key, false); return this.getBoolean(key, false);
} }
public boolean getBoolean(String key, boolean defaultValue) { public boolean getBoolean(String key, boolean defaultValue) {
if (this.isLoading) if (this.isLoading)
return defaultValue; return defaultValue;
@ -122,17 +169,15 @@ public class ConfigurationManager {
try { try {
return (this.getValue(key, "0").equals("1")) || (this.getValue(key, "false").equals("true")); return (this.getValue(key, "0").equals("1")) || (this.getValue(key, "false").equals("true"));
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine("Failed to parse key " + key + " with value " + this.getValue(key) + " to type boolean."); LOGGER.error("Failed to parse key {} with value '{}' to type boolean.", key, this.getValue(key));
} }
return defaultValue; return defaultValue;
} }
public int getInt(String key) { public int getInt(String key) {
return this.getInt(key, 0); return this.getInt(key, 0);
} }
public int getInt(String key, Integer defaultValue) { public int getInt(String key, Integer defaultValue) {
if (this.isLoading) if (this.isLoading)
return defaultValue; return defaultValue;
@ -140,17 +185,15 @@ public class ConfigurationManager {
try { try {
return Integer.parseInt(this.getValue(key, defaultValue.toString())); return Integer.parseInt(this.getValue(key, defaultValue.toString()));
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine("Failed to parse key " + key + " with value " + this.getValue(key) + " to type integer."); LOGGER.error("Failed to parse key {} with value '{}' to type integer.", key, this.getValue(key));
} }
return defaultValue; return defaultValue;
} }
public double getDouble(String key) { public double getDouble(String key) {
return this.getDouble(key, 0.0); return this.getDouble(key, 0.0);
} }
public double getDouble(String key, Double defaultValue) { public double getDouble(String key, Double defaultValue) {
if (this.isLoading) if (this.isLoading)
return defaultValue; return defaultValue;
@ -158,13 +201,12 @@ public class ConfigurationManager {
try { try {
return Double.parseDouble(this.getValue(key, defaultValue.toString())); return Double.parseDouble(this.getValue(key, defaultValue.toString()));
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine("Failed to parse key " + key + " with value " + this.getValue(key) + " to type double."); LOGGER.error("Failed to parse key {} with value '{}' to type double.", key, this.getValue(key));
} }
return defaultValue; return defaultValue;
} }
public void update(String key, String value) { public void update(String key, String value) {
this.properties.setProperty(key, value); this.properties.setProperty(key, value);
} }
@ -178,9 +220,9 @@ public class ConfigurationManager {
statement.setString(2, value); statement.setString(2, value);
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
this.update(key, value); this.update(key, value);
} }
} }

View File

@ -2,11 +2,15 @@ package com.eu.habbo.core;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; import java.util.Map;
public class CreditsScheduler extends Scheduler { public class CreditsScheduler extends Scheduler {
private static final Logger LOGGER = LoggerFactory.getLogger(CreditsScheduler.class);
public static boolean IGNORE_HOTEL_VIEW; public static boolean IGNORE_HOTEL_VIEW;
public static boolean IGNORE_IDLED; public static boolean IGNORE_IDLED;
@ -48,7 +52,7 @@ public class CreditsScheduler extends Scheduler {
habbo.giveCredits(habbo.getHabboInfo().getRank().getCreditsTimerAmount()); habbo.giveCredits(habbo.getHabboInfo().getRank().getCreditsTimerAmount());
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
} }

View File

@ -0,0 +1,33 @@
package com.eu.habbo.core;
public class CryptoConfig {
private final boolean enabled;
private final String exponent;
private final String modulus;
private final String privateExponent;
public CryptoConfig(boolean enabled, String exponent, String modulus, String privateExponent) {
this.enabled = enabled;
this.exponent = exponent;
this.modulus = modulus;
this.privateExponent = privateExponent;
}
public boolean isEnabled() {
return enabled;
}
public String getExponent() {
return exponent;
}
public String getModulus() {
return modulus;
}
public String getPrivateExponent() {
return privateExponent;
}
}

View File

@ -3,6 +3,10 @@ package com.eu.habbo.core;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public interface Loggable { public interface DatabaseLoggable {
String getQuery();
void log(PreparedStatement statement) throws SQLException; void log(PreparedStatement statement) throws SQLException;
}
}

View File

@ -0,0 +1,46 @@
package com.eu.habbo.core;
import com.eu.habbo.Emulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentLinkedQueue;
public class DatabaseLogger {
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseLogger.class);
private final ConcurrentLinkedQueue<DatabaseLoggable> loggables = new ConcurrentLinkedQueue<>();
public void store(DatabaseLoggable loggable) {
this.loggables.add(loggable);
}
public void save() {
if (Emulator.getDatabase() == null || Emulator.getDatabase().getDataSource() == null) {
return;
}
if (this.loggables.isEmpty()) {
return;
}
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
while (!this.loggables.isEmpty()) {
DatabaseLoggable loggable = this.loggables.remove();
try (PreparedStatement statement = connection.prepareStatement(loggable.getQuery())) {
loggable.log(statement);
statement.executeBatch();
}
}
} catch (SQLException e) {
LOGGER.error("Exception caught while saving loggables to database.", e);
}
}
}

View File

@ -1,6 +1,8 @@
package com.eu.habbo.core; package com.eu.habbo.core;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
@ -8,9 +10,11 @@ import java.io.StringWriter;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public class ErrorLog implements DatabaseLoggable {
private static final Logger LOGGER = LoggerFactory.getLogger(ErrorLog.class);
private static final String QUERY = "INSERT INTO emulator_errors (timestamp, version, build_hash, type, stacktrace) VALUES (?, ?, ?, ?, ?)";
public class ErrorLog implements Loggable {
public final static String insertQuery = "INSERT INTO emulator_errors (timestamp, version, build_hash, type, stacktrace) VALUES (?, ?, ?, ?, ?)";
public final String version; public final String version;
public final String buildHash; public final String buildHash;
@ -19,7 +23,6 @@ public class ErrorLog implements Loggable {
public final String stackTrace; public final String stackTrace;
public ErrorLog(String type, Throwable e) { public ErrorLog(String type, Throwable e) {
this.version = Emulator.version; this.version = Emulator.version;
this.buildHash = Emulator.version; this.buildHash = Emulator.version;
@ -35,7 +38,7 @@ public class ErrorLog implements Loggable {
pw.close(); pw.close();
sw.close(); sw.close();
} catch (IOException e1) { } catch (IOException e1) {
Emulator.getLogging().logErrorLine(e1); LOGGER.error("Exception caught", e1);
} }
} }
@ -48,6 +51,11 @@ public class ErrorLog implements Loggable {
this.stackTrace = message; this.stackTrace = message;
} }
@Override
public String getQuery() {
return QUERY;
}
@Override @Override
public void log(PreparedStatement statement) throws SQLException { public void log(PreparedStatement statement) throws SQLException {
statement.setInt(1, this.timeStamp); statement.setInt(1, this.timeStamp);

View File

@ -2,11 +2,15 @@ package com.eu.habbo.core;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; import java.util.Map;
public class GotwPointsScheduler extends Scheduler { public class GotwPointsScheduler extends Scheduler {
private static final Logger LOGGER = LoggerFactory.getLogger(GotwPointsScheduler.class);
public static boolean IGNORE_HOTEL_VIEW; public static boolean IGNORE_HOTEL_VIEW;
public static boolean IGNORE_IDLED; public static boolean IGNORE_IDLED;
public static String GOTW_POINTS_NAME; public static String GOTW_POINTS_NAME;
@ -63,7 +67,7 @@ public class GotwPointsScheduler extends Scheduler {
} }
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
} }

View File

@ -1,338 +1,97 @@
package com.eu.habbo.core; package com.eu.habbo.core;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.rooms.RoomChatMessage; import org.slf4j.Logger;
import gnu.trove.set.hash.THashSet; import org.slf4j.LoggerFactory;
import io.netty.util.internal.ConcurrentSet;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public class Logging { public class Logging {
public static final String ANSI_BRIGHT = "\u001B[1m"; private static final Logger LOGGER = LoggerFactory.getLogger("LegacyLogger");
public static final String ANSI_ITALICS = "\u001B[3m";
public static final String ANSI_UNDERLINE = "\u001B[4m";
public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";
private static PrintWriter packetsWriter;
private static PrintWriter packetsUndefinedWriter;
private static PrintWriter errorsPacketsWriter;
private static PrintWriter errorsSQLWriter;
private static PrintWriter errorsRuntimeWriter;
private static PrintWriter debugFileWriter;
private final THashSet<Loggable> errorLogs = new THashSet<>(100);
private final THashSet<Loggable> commandLogs = new THashSet<>(100);
private ConcurrentSet<Loggable> chatLogs = new ConcurrentSet<>();
public Logging() {
File packets = new File("logging//packets//defined.txt");
File packetsUndefined = new File("logging//packets//packets.txt");
File errorsPackets = new File("logging//errors//packets.txt");
File errorsSQL = new File("logging//errors//sql.txt");
File errorsRuntime = new File("logging//errors//runtime.txt");
File debugFile = new File("logging//debug.txt");
try {
if (!packets.exists()) {
if (!packets.getParentFile().exists()) {
packets.getParentFile().mkdirs();
}
packets.createNewFile();
}
if (!packetsUndefined.exists()) {
if (!packetsUndefined.getParentFile().exists()) {
packetsUndefined.getParentFile().mkdirs();
}
packetsUndefined.createNewFile();
}
if (!errorsPackets.exists()) {
if (!errorsPackets.getParentFile().exists()) {
errorsPackets.getParentFile().mkdirs();
}
errorsPackets.createNewFile();
}
if (!errorsSQL.exists()) {
if (!errorsSQL.getParentFile().exists()) {
errorsSQL.getParentFile().mkdirs();
}
errorsSQL.createNewFile();
}
if (!errorsRuntime.exists()) {
if (!errorsRuntime.getParentFile().exists()) {
errorsRuntime.getParentFile().mkdirs();
}
errorsRuntime.createNewFile();
}
if (!debugFile.exists()) {
if (!debugFile.getParentFile().exists()) {
debugFile.getParentFile().mkdirs();
}
debugFile.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
packetsWriter = new PrintWriter(new FileWriter(packets, true));
packetsUndefinedWriter = new PrintWriter(new FileWriter(packetsUndefined, true));
errorsPacketsWriter = new PrintWriter(new FileWriter(errorsPackets, true));
errorsSQLWriter = new PrintWriter(new FileWriter(errorsSQL, true));
errorsRuntimeWriter = new PrintWriter(new FileWriter(errorsRuntime, true));
debugFileWriter = new PrintWriter(new FileWriter(debugFile, true));
} catch (IOException e) {
System.out.println("[CRITICAL] FAILED TO LOAD LOGGING COMPONENT!");
}
}
public static PrintWriter getPacketsWriter() {
return packetsWriter;
}
public static PrintWriter getPacketsUndefinedWriter() {
return packetsUndefinedWriter;
}
/**
* @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
*/
@Deprecated
public void logStart(Object line) { public void logStart(Object line) {
System.out.println("[" + Logging.ANSI_BRIGHT + Logging.ANSI_GREEN + "LOADING" + Logging.ANSI_RESET + "] " + line.toString()); LOGGER.info("[LOADING] {}", line);
} }
/**
* @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
*/
@Deprecated
public void logShutdownLine(Object line) { public void logShutdownLine(Object line) {
if (Emulator.getConfig().getBoolean("logging.debug")) { LOGGER.info("[SHUTDOWN] {}", line);
this.write(debugFileWriter, line.toString());
}
System.out.println("[" + Logging.ANSI_BRIGHT + Logging.ANSI_RED + "SHUTDOWN" + Logging.ANSI_RESET + "] " + line.toString());
} }
/**
* @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
*/
@Deprecated
public void logUserLine(Object line) { public void logUserLine(Object line) {
if (Emulator.getConfig().getBoolean("logging.debug")) { LOGGER.info("[USER] {}", line);
this.write(debugFileWriter, line.toString());
}
if (Emulator.getConfig().getBoolean("debug.show.users")) {
System.out.println("[USER] " + line.toString());
}
} }
public synchronized void logDebugLine(Object line) { /**
if (line instanceof Throwable) { * @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
this.logErrorLine(line); */
return; @Deprecated
} public void logDebugLine(Object line) {
if (Emulator.getConfig().getBoolean("debug.mode")) { LOGGER.debug("[DEBUG] {}", line);
System.out.println("[DEBUG] " + line.toString());
}
if (Emulator.getConfig().getBoolean("logging.debug")) {
this.write(debugFileWriter, line.toString());
}
} }
public synchronized void logPacketLine(Object line) { /**
* @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
*/
@Deprecated
public void logPacketLine(Object line) {
if (Emulator.getConfig().getBoolean("debug.show.packets")) { if (Emulator.getConfig().getBoolean("debug.show.packets")) {
System.out.println("[" + Logging.ANSI_BLUE + "PACKET" + Logging.ANSI_RESET + "]" + line.toString()); LOGGER.debug("[PACKET] {}", line);
}
if (Emulator.getConfig().getBoolean("logging.packets")) {
this.write(packetsWriter, line.toString());
} }
} }
public synchronized void logUndefinedPacketLine(Object line) { /**
* @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
*/
@Deprecated
public void logUndefinedPacketLine(Object line) {
if (Emulator.getConfig().getBoolean("debug.show.packets.undefined")) { if (Emulator.getConfig().getBoolean("debug.show.packets.undefined")) {
System.out.println("[PACKET] [UNDEFINED] " + line.toString()); LOGGER.debug("[PACKET] [UNDEFINED] {}", line);
}
if (Emulator.getConfig().getBoolean("logging.packets.undefined")) {
this.write(packetsUndefinedWriter, line.toString());
} }
} }
public synchronized void logErrorLine(Object line) { /**
if (Emulator.isReady && Emulator.getConfig().getBoolean("debug.show.errors")) { * @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
System.err.println("[ERROR] " + line.toString()); */
} @Deprecated
public void logErrorLine(Object line) {
if (Emulator.getConfig().loaded && Emulator.getConfig().getBoolean("logging.errors.runtime")) { LOGGER.error("[ERROR] {}", line);
this.write(errorsRuntimeWriter, line);
}
if (line instanceof Throwable) {
((Throwable) line).printStackTrace();
if (line instanceof SQLException) {
this.logSQLException((SQLException) line);
return;
}
// Emulator.getThreading().run(new HTTPPostError((Throwable) line));
this.errorLogs.add(new ErrorLog("Exception", (Throwable) line));
return;
}
this.errorLogs.add(new ErrorLog("Emulator", line.toString()));
} }
/**
* @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
*/
@Deprecated
public void logSQLException(SQLException e) { public void logSQLException(SQLException e) {
if (Emulator.getConfig().getBoolean("logging.errors.sql")) { LOGGER.error("[ERROR] SQLException", e);
e.printStackTrace();
this.write(errorsSQLWriter, e);
//Emulator.getThreading().run(new HTTPPostError(e));
}
} }
/**
* @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
*/
@Deprecated
public void logPacketError(Object e) { public void logPacketError(Object e) {
if (Emulator.getConfig().getBoolean("logging.errors.packets")) { LOGGER.error("[ERROR] PacketError {}", e);
if (e instanceof Throwable)
((Exception) e).printStackTrace();
this.write(errorsPacketsWriter, e);
}
if (e instanceof Throwable) {
((Throwable) e).printStackTrace();
if (e instanceof SQLException) {
this.logSQLException((SQLException) e);
return;
}
// Emulator.getThreading().run(new HTTPPostError((Throwable) e));
}
} }
/**
* @deprecated Do not use. Please use LoggerFactory.getLogger(YourClass.class) to log.
*/
@Deprecated
public void handleException(Exception e) { public void handleException(Exception e) {
e.printStackTrace(); LOGGER.error("[ERROR] Exception", e);
} }
private synchronized void write(PrintWriter printWriter, Object message) { }
if (printWriter != null && message != null) {
if (message instanceof Throwable) {
((Exception) message).printStackTrace(printWriter);
} else {
printWriter.write("MSG: " + message.toString() + "\r\n");
}
printWriter.flush();
}
}
public void addLog(Loggable log) {
if (log instanceof ErrorLog) {
synchronized (this.errorLogs) {
this.errorLogs.add(log);
}
} else if (log instanceof CommandLog) {
synchronized (this.commandLogs) {
this.commandLogs.add(log);
}
}
}
public void addChatLog(Loggable chatLog) {
this.chatLogs.add(chatLog);
}
public void saveLogs() {
if (Emulator.getDatabase() != null && Emulator.getDatabase().getDataSource() != null) {
if (!this.errorLogs.isEmpty() || !this.commandLogs.isEmpty() || !this.chatLogs.isEmpty()) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
if (!this.errorLogs.isEmpty()) {
synchronized (this.errorLogs) {
try (PreparedStatement statement = connection.prepareStatement(ErrorLog.insertQuery)) {
for (Loggable log : this.errorLogs) {
log.log(statement);
}
statement.executeBatch();
}
this.errorLogs.clear();
}
}
if (!this.commandLogs.isEmpty()) {
synchronized (this.commandLogs) {
try (PreparedStatement statement = connection.prepareStatement(CommandLog.insertQuery)) {
for (Loggable log : this.commandLogs) {
log.log(statement);
}
statement.executeBatch();
}
this.commandLogs.clear();
}
}
if (!this.chatLogs.isEmpty()) {
ConcurrentSet<Loggable> chatLogs = this.chatLogs;
this.chatLogs = new ConcurrentSet<>();
try (PreparedStatement statement = connection.prepareStatement(RoomChatMessage.insertQuery)) {
for (Loggable log : chatLogs) {
log.log(statement);
}
statement.executeBatch();
}
chatLogs.clear();
}
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
}
}
/*
public static PrintWriter getErrorsPacketsWriter()
{
return errorsPacketsWriter;
}
public static PrintWriter getErrorsSQLWriter()
{
return errorsSQLWriter;
}
public static PrintWriter getErrorsRuntimeWriter()
{
return errorsRuntimeWriter;
}
public static PrintWriter getDebugFileWriter()
{
return debugFileWriter;
}
*/
}

View File

@ -2,11 +2,15 @@ package com.eu.habbo.core;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; import java.util.Map;
public class PixelScheduler extends Scheduler { public class PixelScheduler extends Scheduler {
private static final Logger LOGGER = LoggerFactory.getLogger(PixelScheduler.class);
public static boolean IGNORE_HOTEL_VIEW; public static boolean IGNORE_HOTEL_VIEW;
public static boolean IGNORE_IDLED; public static boolean IGNORE_IDLED;
@ -46,7 +50,7 @@ public class PixelScheduler extends Scheduler {
habbo.givePixels(habbo.getHabboInfo().getRank().getPixelsTimerAmount()); habbo.givePixels(habbo.getHabboInfo().getRank().getPixelsTimerAmount());
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
} }

View File

@ -2,11 +2,15 @@ package com.eu.habbo.core;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; import java.util.Map;
public class PointsScheduler extends Scheduler { public class PointsScheduler extends Scheduler {
private static final Logger LOGGER = LoggerFactory.getLogger(PointsScheduler.class);
public static boolean IGNORE_HOTEL_VIEW; public static boolean IGNORE_HOTEL_VIEW;
public static boolean IGNORE_IDLED; public static boolean IGNORE_IDLED;
@ -49,7 +53,7 @@ public class PointsScheduler extends Scheduler {
habbo.givePoints(habbo.getHabboInfo().getRank().getDiamondsTimerAmount()); habbo.givePoints(habbo.getHabboInfo().getRank().getDiamondsTimerAmount());
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
} }

View File

@ -19,7 +19,7 @@ public class RoomUserPetComposer extends MessageComposer {
} }
@Override @Override
public ServerMessage compose() { protected ServerMessage composeInternal() {
this.response.init(Outgoing.RoomUsersComposer); this.response.init(Outgoing.RoomUsersComposer);
this.response.appendInt(1); this.response.appendInt(1);
this.response.appendInt(this.habbo.getHabboInfo().getId()); this.response.appendInt(this.habbo.getHabboInfo().getId());

View File

@ -1,12 +1,16 @@
package com.eu.habbo.core; package com.eu.habbo.core;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*; import java.sql.*;
import java.util.Properties; import java.util.Properties;
public class TextsManager { public class TextsManager {
private static final Logger LOGGER = LoggerFactory.getLogger(TextsManager.class);
private final Properties texts; private final Properties texts;
public TextsManager() { public TextsManager() {
@ -15,16 +19,14 @@ public class TextsManager {
this.texts = new Properties(); this.texts = new Properties();
try { try {
this.reload(); this.reload();
Emulator.getLogging().logStart("Texts Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("Texts Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
public void reload() throws Exception { public void reload() throws Exception {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM emulator_texts")) { try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM emulator_texts")) {
while (set.next()) { while (set.next()) {
@ -35,54 +37,47 @@ public class TextsManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
public String getValue(String key) { public String getValue(String key) {
return this.getValue(key, ""); return this.getValue(key, "");
} }
public String getValue(String key, String defaultValue) { public String getValue(String key, String defaultValue) {
if (!this.texts.containsKey(key)) { if (!this.texts.containsKey(key)) {
Emulator.getLogging().logErrorLine("[TEXTS] Text key not found: " + key); LOGGER.error("Text key not found: {}", key);
} }
return this.texts.getProperty(key, defaultValue); return this.texts.getProperty(key, defaultValue);
} }
public boolean getBoolean(String key) { public boolean getBoolean(String key) {
return this.getBoolean(key, false); return this.getBoolean(key, false);
} }
public boolean getBoolean(String key, Boolean defaultValue) { public boolean getBoolean(String key, Boolean defaultValue) {
try { try {
return (this.getValue(key, "0").equals("1")) || (this.getValue(key, "false").equals("true")); return (this.getValue(key, "0").equals("1")) || (this.getValue(key, "false").equals("true"));
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
return defaultValue; return defaultValue;
} }
public int getInt(String key) { public int getInt(String key) {
return this.getInt(key, 0); return this.getInt(key, 0);
} }
public int getInt(String key, Integer defaultValue) { public int getInt(String key, Integer defaultValue) {
try { try {
return Integer.parseInt(this.getValue(key, defaultValue.toString())); return Integer.parseInt(this.getValue(key, defaultValue.toString()));
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
return defaultValue; return defaultValue;
} }
public void update(String key, String value) { public void update(String key, String value) {
this.texts.setProperty(key, value); this.texts.setProperty(key, value);
} }
@ -96,7 +91,7 @@ public class TextsManager {
statement.setString(2, value); statement.setString(2, value);
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
this.update(key, value); this.update(key, value);

View File

@ -1,25 +1,21 @@
package com.eu.habbo.core.consolecommands; package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class ConsoleCommand { public abstract class ConsoleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleCommand.class);
private static final THashMap<String, ConsoleCommand> commands = new THashMap<>(); private static final THashMap<String, ConsoleCommand> commands = new THashMap<>();
public final String key; public final String key;
public final String usage; public final String usage;
public ConsoleCommand(String key, String usage) { public ConsoleCommand(String key, String usage) {
this.key = key; this.key = key;
this.usage = usage; this.usage = usage;
} }
public static void load() { public static void load() {
addCommand(new ConsoleShutdownCommand()); addCommand(new ConsoleShutdownCommand());
addCommand(new ConsoleInfoCommand()); addCommand(new ConsoleInfoCommand());
@ -27,6 +23,7 @@ public abstract class ConsoleCommand {
addCommand(new ConsoleReconnectCameraCommand()); addCommand(new ConsoleReconnectCameraCommand());
addCommand(new ShowInteractionsCommand()); addCommand(new ShowInteractionsCommand());
addCommand(new ShowRCONCommands()); addCommand(new ShowRCONCommands());
addCommand(new ThankyouArcturusCommand());
} }
public static void addCommand(ConsoleCommand command) { public static void addCommand(ConsoleCommand command) {
@ -48,14 +45,14 @@ public abstract class ConsoleCommand {
command.handle(message); command.handle(message);
return true; return true;
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} else { } else {
System.out.println("Unknown Console Command " + message[0]); LOGGER.info("Unknown Console Command " + message[0]);
System.out.println("Commands Available (" + commands.size() + "): "); LOGGER.info("Commands Available (" + commands.size() + "): ");
for (ConsoleCommand c : commands.values()) { for (ConsoleCommand c : commands.values()) {
System.out.println(c.key + " - " + c.usage); LOGGER.info(c.key + " - " + c.usage);
} }
} }
} }
@ -64,4 +61,5 @@ public abstract class ConsoleCommand {
} }
public abstract void handle(String[] args) throws Exception; public abstract void handle(String[] args) throws Exception;
} }

View File

@ -2,10 +2,14 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.catalog.CatalogManager; import com.eu.habbo.habbohotel.catalog.CatalogManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class ConsoleInfoCommand extends ConsoleCommand { public class ConsoleInfoCommand extends ConsoleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleInfoCommand.class);
public ConsoleInfoCommand() { public ConsoleInfoCommand() {
super("info", "Show current statistics."); super("info", "Show current statistics.");
} }
@ -18,21 +22,21 @@ public class ConsoleInfoCommand extends ConsoleCommand {
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60); long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60); long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60);
System.out.println("Emulator version: " + Emulator.version); LOGGER.info("Emulator version: " + Emulator.version);
System.out.println("Emulator build: " + Emulator.build); LOGGER.info("Emulator build: " + Emulator.build);
System.out.println(""); LOGGER.info("");
System.out.println("Hotel Statistics"); LOGGER.info("Hotel Statistics");
System.out.println("- Users: " + Emulator.getGameEnvironment().getHabboManager().getOnlineCount()); LOGGER.info("- Users: " + Emulator.getGameEnvironment().getHabboManager().getOnlineCount());
System.out.println("- Rooms: " + Emulator.getGameEnvironment().getRoomManager().getActiveRooms().size()); LOGGER.info("- Rooms: " + Emulator.getGameEnvironment().getRoomManager().getActiveRooms().size());
System.out.println("- Shop: " + Emulator.getGameEnvironment().getCatalogManager().catalogPages.size() + " pages and " + CatalogManager.catalogItemAmount + " items."); LOGGER.info("- Shop: " + Emulator.getGameEnvironment().getCatalogManager().catalogPages.size() + " pages and " + CatalogManager.catalogItemAmount + " items.");
System.out.println("- Furni: " + Emulator.getGameEnvironment().getItemManager().getItems().size() + " items."); LOGGER.info("- Furni: " + Emulator.getGameEnvironment().getItemManager().getItems().size() + " items.");
System.out.println(""); LOGGER.info("");
System.out.println("Server Statistics"); LOGGER.info("Server Statistics");
System.out.println("- Uptime: " + day + (day > 1 ? " days, " : " day, ") + hours + (hours > 1 ? " hours, " : " hour, ") + minute + (minute > 1 ? " minutes, " : " minute, ") + second + (second > 1 ? " seconds!" : " second!")); LOGGER.info("- Uptime: " + day + (day > 1 ? " days, " : " day, ") + hours + (hours > 1 ? " hours, " : " hour, ") + minute + (minute > 1 ? " minutes, " : " minute, ") + second + (second > 1 ? " seconds!" : " second!"));
System.out.println("- RAM Usage: " + (Emulator.getRuntime().totalMemory() - Emulator.getRuntime().freeMemory()) / (1024 * 1024) + "/" + (Emulator.getRuntime().freeMemory()) / (1024 * 1024) + "MB"); LOGGER.info("- RAM Usage: " + (Emulator.getRuntime().totalMemory() - Emulator.getRuntime().freeMemory()) / (1024 * 1024) + "/" + (Emulator.getRuntime().freeMemory()) / (1024 * 1024) + "MB");
System.out.println("- CPU Cores: " + Emulator.getRuntime().availableProcessors()); LOGGER.info("- CPU Cores: " + Emulator.getRuntime().availableProcessors());
System.out.println("- Total Memory: " + Emulator.getRuntime().maxMemory() / (1024 * 1024) + "MB"); LOGGER.info("- Total Memory: " + Emulator.getRuntime().maxMemory() / (1024 * 1024) + "MB");
} }
} }

View File

@ -1,15 +1,19 @@
package com.eu.habbo.core.consolecommands; package com.eu.habbo.core.consolecommands;
import com.eu.habbo.networking.camera.CameraClient; import com.eu.habbo.networking.camera.CameraClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConsoleReconnectCameraCommand extends ConsoleCommand { public class ConsoleReconnectCameraCommand extends ConsoleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleReconnectCameraCommand.class);
public ConsoleReconnectCameraCommand() { public ConsoleReconnectCameraCommand() {
super("camera", "Attempt to reconnect to the camera server."); super("camera", "Attempt to reconnect to the camera server.");
} }
@Override @Override
public void handle(String[] args) throws Exception { public void handle(String[] args) throws Exception {
System.out.println("Connecting to the camera..."); LOGGER.info("Connecting to the camera...");
CameraClient.attemptReconnect = true; CameraClient.attemptReconnect = true;
} }
} }

View File

@ -3,8 +3,12 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConsoleTestCommand extends ConsoleCommand { public class ConsoleTestCommand extends ConsoleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleTestCommand.class);
public ConsoleTestCommand() { public ConsoleTestCommand() {
super("test", "This is just a test."); super("test", "This is just a test.");
} }
@ -12,7 +16,7 @@ public class ConsoleTestCommand extends ConsoleCommand {
@Override @Override
public void handle(String[] args) throws Exception { public void handle(String[] args) throws Exception {
if (Emulator.debugging) { if (Emulator.debugging) {
System.out.println("This is a test command for live debugging."); LOGGER.info("This is a test command for live debugging.");
//AchievementManager.progressAchievement(4, Emulator.getGameEnvironment().getAchievementManager().getAchievement("AllTimeHotelPresence"), 30); //AchievementManager.progressAchievement(4, Emulator.getGameEnvironment().getAchievementManager().getAchievement("AllTimeHotelPresence"), 30);

View File

@ -1,8 +1,12 @@
package com.eu.habbo.core.consolecommands; package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ShowInteractionsCommand extends ConsoleCommand { public class ShowInteractionsCommand extends ConsoleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(ShowInteractionsCommand.class);
public ShowInteractionsCommand() { public ShowInteractionsCommand() {
super("interactions", "Show a list of available furniture interactions."); super("interactions", "Show a list of available furniture interactions.");
} }
@ -10,7 +14,7 @@ public class ShowInteractionsCommand extends ConsoleCommand {
@Override @Override
public void handle(String[] args) throws Exception { public void handle(String[] args) throws Exception {
for (String interaction : Emulator.getGameEnvironment().getItemManager().getInteractionList()) { for (String interaction : Emulator.getGameEnvironment().getItemManager().getInteractionList()) {
System.out.println(interaction); LOGGER.info(interaction);
} }
} }
} }

View File

@ -1,8 +1,12 @@
package com.eu.habbo.core.consolecommands; package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ShowRCONCommands extends ConsoleCommand { public class ShowRCONCommands extends ConsoleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(ShowRCONCommands.class);
public ShowRCONCommands() { public ShowRCONCommands() {
super("rconcommands", "Show a list of all RCON commands"); super("rconcommands", "Show a list of all RCON commands");
} }
@ -10,7 +14,7 @@ public class ShowRCONCommands extends ConsoleCommand {
@Override @Override
public void handle(String[] args) throws Exception { public void handle(String[] args) throws Exception {
for (String command : Emulator.getRconServer().getCommands()) { for (String command : Emulator.getRconServer().getCommands()) {
System.out.println(command); LOGGER.info(command);
} }
} }
} }

View File

@ -0,0 +1,43 @@
package com.eu.habbo.core.consolecommands;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ThankyouArcturusCommand extends ConsoleCommand {
private static final Logger LOGGER = LoggerFactory.getLogger(ThankyouArcturusCommand.class);
public ThankyouArcturusCommand() {
super("thankyou", "A thankyou message.");
}
@Override
public void handle(String[] args) throws Exception {
LOGGER.info("Arcturus Morningstar is an opensource community fork of Arcturus Emulator by TheGeneral");
LOGGER.info("Thankyou to the following people who have helped with it's development:");
LOGGER.info("TheGeneral - For Creating Arcturus.");
LOGGER.info("Capheus - Decompilation");
LOGGER.info("Beny - Lead Developer");
LOGGER.info("Alejandro - Lead Developer");
LOGGER.info("Harmonic - Developer");
LOGGER.info("ArpyAge - Developer");
LOGGER.info("Mike - Developer");
LOGGER.info("Skeletor - Developer");
LOGGER.info("zGrav - Developer");
LOGGER.info("Swirny - Developer");
LOGGER.info("Quadral - Developer");
LOGGER.info("Dome - Developer");
LOGGER.info("Necmi - Developer");
LOGGER.info("Oliver - Support");
LOGGER.info("Rasmus - Support");
LOGGER.info("Layne - Support");
LOGGER.info("Bill - Support");
LOGGER.info("Harmony - Support");
LOGGER.info("Ridge - Catalogue");
LOGGER.info("Tenshie - Catalogue");
LOGGER.info("Wulles - Catalogue");
LOGGER.info("Gizmo - Catalogue");
LOGGER.info("TheJava - Motivation");
LOGGER.info("The Entire Krews.org Community.");
}
}

View File

@ -0,0 +1,108 @@
package com.eu.habbo.crypto;
import com.eu.habbo.crypto.exceptions.HabboCryptoException;
import com.eu.habbo.crypto.utils.BigIntegerUtils;
import com.eu.habbo.util.HexUtils;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ThreadLocalRandom;
public class HabboDiffieHellman {
private static final int DH_PRIMES_BIT_SIZE = 128;
private static final int DH_KEY_BIT_SIZE = 128;
private final HabboRSACrypto crypto;
private BigInteger DHPrime;
private BigInteger DHGenerator;
private BigInteger DHPrivate;
private BigInteger DHPublic;
public HabboDiffieHellman(HabboRSACrypto crypto) {
this.crypto = crypto;
this.generateDHPrimes();
this.generateDHKeys();
}
public BigInteger getDHPrime() {
return DHPrime;
}
public BigInteger getDHGenerator() {
return DHGenerator;
}
private void generateDHPrimes() {
this.DHPrime = BigInteger.probablePrime(DH_PRIMES_BIT_SIZE, ThreadLocalRandom.current());
this.DHGenerator = BigInteger.probablePrime(DH_PRIMES_BIT_SIZE, ThreadLocalRandom.current());
if (this.DHGenerator.compareTo(this.DHPrime) > 0) {
BigInteger temp = this.DHPrime;
this.DHPrime = this.DHGenerator;
this.DHGenerator = temp;
}
}
private void generateDHKeys() {
this.DHPrivate = BigInteger.probablePrime(DH_KEY_BIT_SIZE, ThreadLocalRandom.current());
this.DHPublic = this.DHGenerator.modPow(this.DHPrivate, this.DHPrime);
}
private String encryptBigInteger(BigInteger integer) throws HabboCryptoException {
String str = integer.toString(10);
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
byte[] encrypted = this.crypto.Sign(bytes);
return HexUtils.toHex(encrypted).toLowerCase();
}
private BigInteger decryptBigInteger(String str) throws HabboCryptoException {
byte[] bytes = HexUtils.toBytes(str);
byte[] decrypted = this.crypto.Decrypt(bytes);
String intStr = new String(decrypted, StandardCharsets.UTF_8);
return new BigInteger(intStr, 10);
}
public String getPublicKey() throws HabboCryptoException {
return encryptBigInteger(this.DHPublic);
}
public String getSignedPrime() throws HabboCryptoException {
return encryptBigInteger(this.DHPrime);
}
public String getSignedGenerator() throws HabboCryptoException {
return encryptBigInteger(this.DHGenerator);
}
public void doHandshake(String signedPrime, String signedGenerator) throws HabboCryptoException {
this.DHPrime = decryptBigInteger(signedPrime);
this.DHGenerator = decryptBigInteger(signedGenerator);
if (this.DHPrime == null || this.DHGenerator == null) {
throw new HabboCryptoException("DHPrime or DHGenerator was null.");
}
if (this.DHPrime.compareTo(BigInteger.valueOf(2)) < 1) {
throw new HabboCryptoException("Prime cannot be <= 2!\nPrime: " + this.DHPrime.toString());
}
if (this.DHGenerator.compareTo(this.DHPrime) > -1) {
throw new HabboCryptoException("Generator cannot be >= Prime!\nPrime: " + this.DHPrime.toString() + "\nGenerator: " + this.DHGenerator.toString());
}
generateDHKeys();
}
public byte[] getSharedKey(String publicKeyStr) throws HabboCryptoException {
BigInteger publicKey = this.decryptBigInteger(publicKeyStr);
BigInteger sharedKey = publicKey.modPow(this.DHPrivate, this.DHPrime);
return BigIntegerUtils.toUnsignedByteArray(sharedKey);
}
}

View File

@ -0,0 +1,21 @@
package com.eu.habbo.crypto;
public class HabboEncryption {
private final HabboRSACrypto crypto;
private final HabboDiffieHellman diffie;
public HabboEncryption(String e, String n, String d) {
this.crypto = new HabboRSACrypto(e, n, d);
this.diffie = new HabboDiffieHellman(this.crypto);
}
public HabboRSACrypto getCrypto() {
return crypto;
}
public HabboDiffieHellman getDiffie() {
return diffie;
}
}

View File

@ -0,0 +1,46 @@
package com.eu.habbo.crypto;
public class HabboRC4 {
private int i;
private int j;
private final int[] table = new int[256];
public HabboRC4(byte[] key) {
int length = key.length;
while (this.i < 256) {
table[this.i] = this.i;
this.i++;
}
this.i = 0;
this.j = 0;
while (this.i < 256) {
this.j = ((this.j + this.table[this.i]) + (key[this.i % length] & 0xff)) % 256;
this.swap(this.i, this.j);
this.i++;
}
this.i = 0;
this.j = 0;
}
private void swap(int a, int b) {
int num = table[a];
table[a] = table[b];
table[b] = num;
}
public void parse(byte[] bytes) {
for (int index1 = 0; index1 < bytes.length; index1++) {
this.i = (this.i + 1) % 256;
this.j = (this.j + this.table[this.i]) % 256;
this.swap(this.i, this.j);
bytes[index1] = (byte) ((bytes[index1] & 0xFF) ^ this.table[(this.table[this.i] + this.table[this.j]) % 256]);
}
}
}

View File

@ -0,0 +1,168 @@
package com.eu.habbo.crypto;
import com.eu.habbo.crypto.exceptions.HabboCryptoException;
import com.eu.habbo.crypto.utils.BigIntegerUtils;
import org.apache.commons.lang3.mutable.MutableInt;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.concurrent.ThreadLocalRandom;
public class HabboRSACrypto {
private final BigInteger e;
private final BigInteger n;
private final BigInteger d;
private final int blockSize;
public HabboRSACrypto(String e, String n) {
this.e = new BigInteger(e, 16);
this.n = new BigInteger(n, 16);
this.d = null;
this.blockSize = (this.n.bitLength() + 7) / 8;
}
public HabboRSACrypto(String e, String n, String d) {
this.e = new BigInteger(e, 16);
this.n = new BigInteger(n, 16);
this.d = new BigInteger(d, 16);
this.blockSize = (this.n.bitLength() + 7) / 8;
}
public byte[] Encrypt(byte[] data) throws HabboCryptoException {
return DoEncrypt(data, true, 2);
}
public byte[] Decrypt(byte[] data) throws HabboCryptoException {
return DoDecrypt(data, false, 2);
}
public byte[] Sign(byte[] data) throws HabboCryptoException {
return DoEncrypt(data, false, 1);
}
public byte[] Verify(byte[] data) throws HabboCryptoException {
return DoDecrypt(data, true, 1);
}
private BigInteger DoPublic(BigInteger x) {
return x.modPow(this.e, this.n);
}
private BigInteger DoPrivate(BigInteger x) {
return x.modPow(this.d, this.n);
}
private byte[] DoEncrypt(byte[] data, boolean isPublic, int padType) throws HabboCryptoException {
try (ByteArrayOutputStream dst = new ByteArrayOutputStream()) {
int bl = this.blockSize;
int end = data.length;
MutableInt pos = new MutableInt(0);
while (pos.intValue() < end) {
byte[] padded = Pkcs1Pad(data, pos, end, bl, padType);
BigInteger block = new BigInteger(padded);
BigInteger chunk = isPublic ? DoPublic(block) : DoPrivate(block);
for (int b = (int) (bl - Math.ceil(chunk.bitLength() / 8.0)); b > 0; --b) {
dst.write(0x00);
}
dst.write(BigIntegerUtils.toUnsignedByteArray(chunk));
}
return dst.toByteArray();
} catch (IOException e) {
throw new HabboCryptoException(e);
}
}
private byte[] DoDecrypt(byte[] data, boolean isPublic, int padType) throws HabboCryptoException {
if (data.length % this.blockSize != 0) {
throw new HabboCryptoException("Decryption data was not in blocks of " + this.blockSize + " bytes, total " + data.length + ".");
}
try (ByteArrayOutputStream dst = new ByteArrayOutputStream()) {
int end = data.length;
int pos = 0;
while (pos < end) {
byte[] blockData = new byte[this.blockSize];
System.arraycopy(data, pos, blockData, 0, this.blockSize);
BigInteger block = new BigInteger(1, blockData);
BigInteger chunk = isPublic ? DoPublic(block) : DoPrivate(block);
byte[] unpadded = Pkcs1Unpad(chunk.toByteArray(), this.blockSize, padType);
pos += this.blockSize;
dst.write(unpadded);
}
return dst.toByteArray();
} catch (IOException e) {
throw new HabboCryptoException(e);
}
}
private static byte[] Pkcs1Pad(byte[] src, MutableInt pos, int end, int n, int padType) {
byte[] result = new byte[n];
int p = pos.intValue();
end = Math.min(end, Math.min(src.length, p + n - 11));
pos.setValue(end);
int i = end - 1;
while (i >= p && n > 11) {
result[--n] = src[i--];
}
result[--n] = 0;
if (padType == 2) {
while (n > 2) {
result[--n] = (byte) ThreadLocalRandom.current().nextInt(1, 256);
}
} else {
while (n > 2) {
result[--n] = (byte) 0xFF;
}
}
result[--n] = (byte) padType;
result[--n] = 0;
return result;
}
private static byte[] Pkcs1Unpad(byte[] b, int n, int padType) throws HabboCryptoException {
byte[] result = new byte[n];
int resultPos = 0;
int i = 0;
while (i < b.length && b[i] == 0) {
++i;
}
if (b.length - i != n - 1 || b[i] != padType) {
throw new HabboCryptoException("PKCS#1 unpad: i=" + i + ", expected b[i]==" + padType + ", got b[i]=" + b[i]);
}
++i;
while (b[i] != 0) {
if (++i >= b.length) {
throw new HabboCryptoException("PKCS#1 unpad: i=" + i + ", b[i-1]!=0 (=" + b[i-1] + ")");
}
}
while (++i < b.length) {
result[resultPos++] = b[i];
}
byte[] resultCopy = new byte[resultPos];
System.arraycopy(result, 0, resultCopy, 0, resultPos);
return resultCopy;
}
}

View File

@ -0,0 +1,17 @@
package com.eu.habbo.crypto.exceptions;
public class HabboCryptoException extends Exception {
public HabboCryptoException(String message) {
super(message);
}
public HabboCryptoException(String message, Throwable cause) {
super(message, cause);
}
public HabboCryptoException(Throwable cause) {
super(cause);
}
}

View File

@ -0,0 +1,17 @@
package com.eu.habbo.crypto.utils;
import java.math.BigInteger;
import java.util.Arrays;
public class BigIntegerUtils {
public static byte[] toUnsignedByteArray(BigInteger bigInteger) {
byte[] bytes = bigInteger.toByteArray();
if (bytes[0] == 0) {
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
}
return bytes;
}
}

View File

@ -3,16 +3,17 @@ package com.eu.habbo.database;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.core.ConfigurationManager; import com.eu.habbo.core.ConfigurationManager;
import com.zaxxer.hikari.HikariDataSource; import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Database { public class Database {
private static final Logger LOGGER = LoggerFactory.getLogger(Database.class);
private HikariDataSource dataSource; private HikariDataSource dataSource;
private DatabasePool databasePool; private DatabasePool databasePool;
public Database(ConfigurationManager config) { public Database(ConfigurationManager config) {
long millis = System.currentTimeMillis(); long millis = System.currentTimeMillis();
boolean SQLException = false; boolean SQLException = false;
@ -20,25 +21,23 @@ public class Database {
try { try {
this.databasePool = new DatabasePool(); this.databasePool = new DatabasePool();
if (!this.databasePool.getStoragePooling(config)) { if (!this.databasePool.getStoragePooling(config)) {
Emulator.getLogging().logStart("Failed to connect to the database. Please check config.ini and make sure the MySQL process is running. Shutting down..."); LOGGER.info("Failed to connect to the database. Please check config.ini and make sure the MySQL process is running. Shutting down...");
SQLException = true; SQLException = true;
return; return;
} }
this.dataSource = this.databasePool.getDatabase(); this.dataSource = this.databasePool.getDatabase();
} catch (Exception e) { } catch (Exception e) {
SQLException = true; SQLException = true;
e.printStackTrace(); LOGGER.error("Failed to connect to your database.", e);
Emulator.getLogging().logStart("Failed to connect to your database.");
Emulator.getLogging().logStart(e.getMessage());
} finally { } finally {
if (SQLException) if (SQLException) {
Emulator.prepareShutdown(); Emulator.prepareShutdown();
}
} }
Emulator.getLogging().logStart("Database -> Connected! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("Database -> Connected! ({} MS)", System.currentTimeMillis() - millis);
} }
public void dispose() { public void dispose() {
if (this.databasePool != null) { if (this.databasePool != null) {
this.databasePool.getDatabase().close(); this.databasePool.getDatabase().close();
@ -55,4 +54,3 @@ public class Database {
return this.databasePool; return this.databasePool;
} }
} }

View File

@ -1,10 +1,7 @@
package com.eu.habbo.habbohotel; package com.eu.habbo.habbohotel;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.core.CreditsScheduler; import com.eu.habbo.core.*;
import com.eu.habbo.core.GotwPointsScheduler;
import com.eu.habbo.core.PixelScheduler;
import com.eu.habbo.core.PointsScheduler;
import com.eu.habbo.habbohotel.achievements.AchievementManager; import com.eu.habbo.habbohotel.achievements.AchievementManager;
import com.eu.habbo.habbohotel.bots.BotManager; import com.eu.habbo.habbohotel.bots.BotManager;
import com.eu.habbo.habbohotel.catalog.CatalogManager; import com.eu.habbo.habbohotel.catalog.CatalogManager;
@ -23,8 +20,13 @@ import com.eu.habbo.habbohotel.pets.PetManager;
import com.eu.habbo.habbohotel.polls.PollManager; import com.eu.habbo.habbohotel.polls.PollManager;
import com.eu.habbo.habbohotel.rooms.RoomManager; import com.eu.habbo.habbohotel.rooms.RoomManager;
import com.eu.habbo.habbohotel.users.HabboManager; import com.eu.habbo.habbohotel.users.HabboManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GameEnvironment { public class GameEnvironment {
private static final Logger LOGGER = LoggerFactory.getLogger(GameEnvironment.class);
public CreditsScheduler creditsScheduler; public CreditsScheduler creditsScheduler;
public PixelScheduler pixelScheduler; public PixelScheduler pixelScheduler;
public PointsScheduler pointsScheduler; public PointsScheduler pointsScheduler;
@ -49,7 +51,7 @@ public class GameEnvironment {
private PollManager pollManager; private PollManager pollManager;
public void load() throws Exception { public void load() throws Exception {
Emulator.getLogging().logStart("GameEnvironment -> Loading..."); LOGGER.info("GameEnvironment -> Loading...");
this.permissionsManager = new PermissionsManager(); this.permissionsManager = new PermissionsManager();
this.habboManager = new HabboManager(); this.habboManager = new HabboManager();
@ -85,7 +87,7 @@ public class GameEnvironment {
Emulator.getThreading().run(this.gotwPointsScheduler); Emulator.getThreading().run(this.gotwPointsScheduler);
Emulator.getLogging().logStart("GameEnvironment -> Loaded!"); LOGGER.info("GameEnvironment -> Loaded!");
} }
public void dispose() { public void dispose() {
@ -101,7 +103,7 @@ public class GameEnvironment {
this.roomManager.dispose(); this.roomManager.dispose();
this.itemManager.dispose(); this.itemManager.dispose();
this.hotelViewManager.dispose(); this.hotelViewManager.dispose();
Emulator.getLogging().logShutdownLine("GameEnvironment -> Disposed!"); LOGGER.info("GameEnvironment -> Disposed!");
} }
public HabboManager getHabboManager() { public HabboManager getHabboManager() {

View File

@ -18,20 +18,21 @@ import com.eu.habbo.plugin.events.users.achievements.UserAchievementLeveledEvent
import com.eu.habbo.plugin.events.users.achievements.UserAchievementProgressEvent; import com.eu.habbo.plugin.events.users.achievements.UserAchievementProgressEvent;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import gnu.trove.procedure.TObjectIntProcedure; import gnu.trove.procedure.TObjectIntProcedure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*; import java.sql.*;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
public class AchievementManager { public class AchievementManager {
private static final Logger LOGGER = LoggerFactory.getLogger(AchievementManager.class);
public static boolean TALENTTRACK_ENABLED = false; public static boolean TALENTTRACK_ENABLED = false;
private final THashMap<String, Achievement> achievements; private final THashMap<String, Achievement> achievements;
private final THashMap<TalentTrackType, LinkedHashMap<Integer, TalentTrackLevel>> talentTrackLevels; private final THashMap<TalentTrackType, LinkedHashMap<Integer, TalentTrackLevel>> talentTrackLevels;
public AchievementManager() { public AchievementManager() {
this.achievements = new THashMap<>(); this.achievements = new THashMap<>();
this.talentTrackLevels = new THashMap<>(); this.talentTrackLevels = new THashMap<>();
@ -58,7 +59,7 @@ public class AchievementManager {
statement.setInt(4, amount); statement.setInt(4, amount);
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }
@ -140,7 +141,7 @@ public class AchievementManager {
try { try {
badge = habbo.getInventory().getBadgesComponent().getBadge(("ACH_" + achievement.name + oldLevel.level).toLowerCase()); badge = habbo.getInventory().getBadgesComponent().getBadge(("ACH_" + achievement.name + oldLevel.level).toLowerCase());
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
return; return;
} }
} }
@ -203,7 +204,7 @@ public class AchievementManager {
statement.setInt(3, 1); statement.setInt(3, 1);
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -217,7 +218,7 @@ public class AchievementManager {
} }
statement.executeBatch(); statement.executeBatch();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -231,7 +232,7 @@ public class AchievementManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return 0; return 0;
@ -254,9 +255,9 @@ public class AchievementManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
@ -276,13 +277,13 @@ public class AchievementManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
Emulator.getLogging().logErrorLine("Achievement Manager -> Failed to load!"); LOGGER.error("Achievement Manager -> Failed to load!");
return; return;
} }
} }
Emulator.getLogging().logStart("Achievement Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("Achievement Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} }
public Achievement getAchievement(String name) { public Achievement getAchievement(String name) {

View File

@ -5,27 +5,20 @@ import com.eu.habbo.habbohotel.items.Item;
import gnu.trove.map.TObjectIntMap; import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectIntHashMap; import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class TalentTrackLevel { public class TalentTrackLevel {
private static final Logger LOGGER = LoggerFactory.getLogger(TalentTrackLevel.class);
public TalentTrackType type; public TalentTrackType type;
public int level; public int level;
public TObjectIntMap<Achievement> achievements; public TObjectIntMap<Achievement> achievements;
public THashSet<Item> items; public THashSet<Item> items;
public String[] perks; public String[] perks;
public String[] badges; public String[] badges;
public TalentTrackLevel(ResultSet set) throws SQLException { public TalentTrackLevel(ResultSet set) throws SQLException {
@ -46,7 +39,7 @@ public class TalentTrackLevel {
if (achievement != null) { if (achievement != null) {
this.achievements.put(achievement, Integer.valueOf(achievementLevels[i])); this.achievements.put(achievement, Integer.valueOf(achievementLevels[i]));
} else { } else {
Emulator.getLogging().logErrorLine("Could not find achievement with ID " + achievements[i] + " for talenttrack level " + this.level + " of type " + this.type); LOGGER.error("Could not find achievement with ID " + achievements[i] + " for talenttrack level " + this.level + " of type " + this.type);
} }
} }
} }
@ -57,7 +50,7 @@ public class TalentTrackLevel {
if (item != null) { if (item != null) {
this.items.add(item); this.items.add(item);
} else { } else {
Emulator.getLogging().logStart("Incorrect reward furni (ID: " + s + ") for talent track level " + this.level); LOGGER.error("Incorrect reward furni (ID: " + s + ") for talent track level " + this.level);
} }
} }

View File

@ -12,6 +12,8 @@ import com.eu.habbo.plugin.events.bots.BotShoutEvent;
import com.eu.habbo.plugin.events.bots.BotTalkEvent; import com.eu.habbo.plugin.events.bots.BotTalkEvent;
import com.eu.habbo.plugin.events.bots.BotWhisperEvent; import com.eu.habbo.plugin.events.bots.BotWhisperEvent;
import com.eu.habbo.threading.runnables.BotFollowHabbo; import com.eu.habbo.threading.runnables.BotFollowHabbo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -21,6 +23,8 @@ import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
public class Bot implements Runnable { public class Bot implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Bot.class);
public static final String NO_CHAT_SET = "${bot.skill.chatter.configuration.text.placeholder}"; public static final String NO_CHAT_SET = "${bot.skill.chatter.configuration.text.placeholder}";
public static String[] PLACEMENT_MESSAGES = "Yo!;Hello I'm a real party animal!;Hello!".split(";"); public static String[] PLACEMENT_MESSAGES = "Yo!;Hello I'm a real party animal!;Hello!".split(";");
@ -155,7 +159,7 @@ public class Bot implements Runnable {
statement.execute(); statement.execute();
this.needsUpdate = false; this.needsUpdate = false;
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -5,6 +5,7 @@ import com.eu.habbo.habbohotel.items.Item;
import com.eu.habbo.habbohotel.permissions.Permission; import com.eu.habbo.habbohotel.permissions.Permission;
import com.eu.habbo.habbohotel.rooms.*; import com.eu.habbo.habbohotel.rooms.*;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboInfo;
import com.eu.habbo.habbohotel.users.HabboItem; import com.eu.habbo.habbohotel.users.HabboItem;
import com.eu.habbo.messages.outgoing.generic.alerts.BotErrorComposer; import com.eu.habbo.messages.outgoing.generic.alerts.BotErrorComposer;
import com.eu.habbo.messages.outgoing.generic.alerts.BubbleAlertComposer; import com.eu.habbo.messages.outgoing.generic.alerts.BubbleAlertComposer;
@ -15,19 +16,24 @@ import com.eu.habbo.messages.outgoing.rooms.users.RoomUsersComposer;
import com.eu.habbo.plugin.events.bots.BotPickUpEvent; import com.eu.habbo.plugin.events.bots.BotPickUpEvent;
import com.eu.habbo.plugin.events.bots.BotPlacedEvent; import com.eu.habbo.plugin.events.bots.BotPlacedEvent;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.sql.*; import java.sql.*;
import java.util.Map; import java.util.Map;
public class BotManager { public class BotManager {
private static final Logger LOGGER = LoggerFactory.getLogger(BotManager.class);
final private static THashMap<String, Class<? extends Bot>> botDefenitions = new THashMap<>(); final private static THashMap<String, Class<? extends Bot>> botDefenitions = new THashMap<>();
public static int MINIMUM_CHAT_SPEED = 7; public static int MINIMUM_CHAT_SPEED = 7;
public static int MAXIMUM_CHAT_SPEED = 604800; public static int MAXIMUM_CHAT_SPEED = 604800;
public static int MAXIMUM_CHAT_LENGTH = 120; public static int MAXIMUM_CHAT_LENGTH = 120;
public static int MAXIMUM_NAME_LENGTH = 15; public static int MAXIMUM_NAME_LENGTH = 15;
public static int MAXIMUM_BOT_INVENTORY_SIZE = 25;
public BotManager() throws Exception { public BotManager() throws Exception {
long millis = System.currentTimeMillis(); long millis = System.currentTimeMillis();
@ -38,7 +44,7 @@ public class BotManager {
this.reload(); this.reload();
Emulator.getLogging().logStart("Bot Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("Bot Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} }
public static void addBotDefinition(String type, Class<? extends Bot> botClazz) throws Exception { public static void addBotDefinition(String type, Class<? extends Bot> botClazz) throws Exception {
@ -58,10 +64,10 @@ public class BotManager {
m.setAccessible(true); m.setAccessible(true);
m.invoke(null); m.invoke(null);
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
Emulator.getLogging().logStart("Bot Manager -> Failed to execute initialise method upon bot type '" + set.getKey() + "'. No Such Method!"); LOGGER.info("Bot Manager -> Failed to execute initialise method upon bot type '" + set.getKey() + "'. No Such Method!");
return false; return false;
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logStart("Bot Manager -> Failed to execute initialise method upon bot type '" + set.getKey() + "'. Error: " + e.getMessage()); LOGGER.info("Bot Manager -> Failed to execute initialise method upon bot type '" + set.getKey() + "'. Error: " + e.getMessage());
return false; return false;
} }
} }
@ -88,12 +94,12 @@ public class BotManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return bot; return bot;
@ -107,8 +113,8 @@ public class BotManager {
return; return;
if (room != null && bot != null && habbo != null) { if (room != null && bot != null && habbo != null) {
if (room.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER) || habbo.hasPermission("acc_placefurni")) { if (room.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER) || habbo.hasPermission(Permission.ACC_PLACEFURNI)) {
if (room.getCurrentBots().size() >= Room.MAXIMUM_BOTS && !habbo.hasPermission("acc_unlimited_bots")) { if (room.getCurrentBots().size() >= Room.MAXIMUM_BOTS && !habbo.hasPermission(Permission.ACC_UNLIMITED_BOTS)) {
habbo.getClient().sendResponse(new BotErrorComposer(BotErrorComposer.ROOM_ERROR_MAX_BOTS)); habbo.getClient().sendResponse(new BotErrorComposer(BotErrorComposer.ROOM_ERROR_MAX_BOTS));
return; return;
} }
@ -116,15 +122,18 @@ public class BotManager {
if (room.hasHabbosAt(location.x, location.y) || (!location.isWalkable() && location.state != RoomTileState.SIT && location.state != RoomTileState.LAY)) if (room.hasHabbosAt(location.x, location.y) || (!location.isWalkable() && location.state != RoomTileState.SIT && location.state != RoomTileState.LAY))
return; return;
if (room.hasBotsAt(location.x, location.y)) {
habbo.getClient().sendResponse(new BotErrorComposer(BotErrorComposer.ROOM_ERROR_BOTS_SELECTED_TILE_NOT_FREE));
return;
}
RoomUnit roomUnit = new RoomUnit(); RoomUnit roomUnit = new RoomUnit();
roomUnit.setRotation(RoomUserRotation.SOUTH); roomUnit.setRotation(RoomUserRotation.SOUTH);
roomUnit.setLocation(location); roomUnit.setLocation(location);
HabboItem topItem = room.getTopItemAt(location.x, location.y);
double topItemHeight = 0;
if (topItem != null) topItemHeight = Item.getCurrentHeight(topItem);
roomUnit.setPreviousLocationZ(roomUnit.getCurrentLocation().getStackHeight() - topItemHeight);
double stackHeight = room.getStackHeight(location.x, location.y, false);
roomUnit.setPreviousLocationZ(stackHeight);
roomUnit.setZ(stackHeight);
roomUnit.setPathFinderRoom(room); roomUnit.setPathFinderRoom(room);
roomUnit.setRoomUnitType(RoomUnitType.BOT); roomUnit.setRoomUnitType(RoomUnitType.BOT);
@ -139,13 +148,16 @@ public class BotManager {
habbo.getClient().sendResponse(new RemoveBotComposer(bot)); habbo.getClient().sendResponse(new RemoveBotComposer(bot));
bot.onPlace(habbo, room); bot.onPlace(habbo, room);
HabboItem topItem = room.getTopItemAt(location.x, location.y);
if (topItem != null) { if (topItem != null) {
try { try {
topItem.onWalkOn(bot.getRoomUnit(), room, null); topItem.onWalkOn(bot.getRoomUnit(), room, null);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
bot.cycle(false); bot.cycle(false);
} else { } else {
habbo.getClient().sendResponse(new BubbleAlertComposer(BubbleAlertKeys.FURNITURE_PLACEMENT_ERROR.key, FurnitureMovementError.NO_RIGHTS.errorCode)); habbo.getClient().sendResponse(new BubbleAlertComposer(BubbleAlertKeys.FURNITURE_PLACEMENT_ERROR.key, FurnitureMovementError.NO_RIGHTS.errorCode));
@ -160,27 +172,34 @@ public class BotManager {
} }
public void pickUpBot(Bot bot, Habbo habbo) { public void pickUpBot(Bot bot, Habbo habbo) {
if (bot != null && habbo != null) { HabboInfo receiverInfo = habbo == null ? Emulator.getGameEnvironment().getHabboManager().getHabboInfo(bot.getOwnerId()) : habbo.getHabboInfo();
if (bot != null) {
BotPickUpEvent pickedUpEvent = new BotPickUpEvent(bot, habbo); BotPickUpEvent pickedUpEvent = new BotPickUpEvent(bot, habbo);
Emulator.getPluginManager().fireEvent(pickedUpEvent); Emulator.getPluginManager().fireEvent(pickedUpEvent);
if (pickedUpEvent.isCancelled()) if (pickedUpEvent.isCancelled())
return; return;
if (bot.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER)) { if (habbo == null || (bot.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER))) {
if (!habbo.hasPermission("acc_unlimited_bots") && habbo.getInventory().getBotsComponent().getBots().size() >= 15) if (habbo != null && !habbo.hasPermission(Permission.ACC_UNLIMITED_BOTS) && habbo.getInventory().getBotsComponent().getBots().size() >= BotManager.MAXIMUM_BOT_INVENTORY_SIZE) {
habbo.alert(Emulator.getTexts().getValue("error.bots.max.inventory").replace("%amount%", BotManager.MAXIMUM_BOT_INVENTORY_SIZE + ""));
return; return;
}
bot.onPickUp(habbo, habbo.getHabboInfo().getCurrentRoom()); bot.onPickUp(habbo, receiverInfo.getCurrentRoom());
habbo.getHabboInfo().getCurrentRoom().removeBot(bot); receiverInfo.getCurrentRoom().removeBot(bot);
bot.stopFollowingHabbo(); bot.stopFollowingHabbo();
bot.setOwnerId(habbo.getHabboInfo().getId()); bot.setOwnerId(receiverInfo.getId());
bot.setOwnerName(habbo.getHabboInfo().getUsername()); bot.setOwnerName(receiverInfo.getUsername());
bot.needsUpdate(true); bot.needsUpdate(true);
Emulator.getThreading().run(bot); Emulator.getThreading().run(bot);
habbo.getInventory().getBotsComponent().addBot(bot); Habbo receiver = habbo == null ? Emulator.getGameEnvironment().getHabboManager().getHabbo(receiverInfo.getId()) : habbo;
habbo.getClient().sendResponse(new AddBotComposer(bot)); if (receiver != null) {
receiver.getInventory().getBotsComponent().addBot(bot);
receiver.getClient().sendResponse(new AddBotComposer(bot));
}
} }
} }
} }
@ -193,11 +212,11 @@ public class BotManager {
if (botClazz != null) if (botClazz != null)
return botClazz.getDeclaredConstructor(ResultSet.class).newInstance(set); return botClazz.getDeclaredConstructor(ResultSet.class).newInstance(set);
else else
Emulator.getLogging().logErrorLine("Unknown Bot Type: " + type); LOGGER.error("Unknown Bot Type: " + type);
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
return null; return null;
@ -208,7 +227,7 @@ public class BotManager {
statement.setInt(1, bot.getId()); statement.setInt(1, bot.getId());
return statement.execute(); return statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return false; return false;
@ -221,9 +240,9 @@ public class BotManager {
m.setAccessible(true); m.setAccessible(true);
m.invoke(null); m.invoke(null);
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
Emulator.getLogging().logStart("Bot Manager -> Failed to execute dispose method upon bot type '" + set.getKey() + "'. No Such Method!"); LOGGER.info("Bot Manager -> Failed to execute dispose method upon bot type '" + set.getKey() + "'. No Such Method!");
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logStart("Bot Manager -> Failed to execute dispose method upon bot type '" + set.getKey() + "'. Error: " + e.getMessage()); LOGGER.info("Bot Manager -> Failed to execute dispose method upon bot type '" + set.getKey() + "'. Error: " + e.getMessage());
} }
} }
} }

View File

@ -8,6 +8,8 @@ import com.eu.habbo.threading.runnables.RoomUnitGiveHanditem;
import com.eu.habbo.threading.runnables.RoomUnitWalkToRoomUnit; import com.eu.habbo.threading.runnables.RoomUnitWalkToRoomUnit;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -19,6 +21,7 @@ import java.util.List;
import java.util.Map; import java.util.Map;
public class ButlerBot extends Bot { public class ButlerBot extends Bot {
private static final Logger LOGGER = LoggerFactory.getLogger(ButlerBot.class);
public static THashMap<THashSet<String>, Integer> serveItems = new THashMap<>(); public static THashMap<THashSet<String>, Integer> serveItems = new THashMap<>();
public ButlerBot(ResultSet set) throws SQLException { public ButlerBot(ResultSet set) throws SQLException {
@ -43,7 +46,7 @@ public class ButlerBot extends Bot {
serveItems.put(ks, set.getInt("item")); serveItems.put(ks, set.getInt("item"));
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -75,20 +78,13 @@ public class ButlerBot extends Bot {
tasks.add(new RoomUnitGiveHanditem(serveEvent.habbo.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), serveEvent.itemId)); tasks.add(new RoomUnitGiveHanditem(serveEvent.habbo.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), serveEvent.itemId));
tasks.add(new RoomUnitGiveHanditem(this.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), 0)); tasks.add(new RoomUnitGiveHanditem(this.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), 0));
tasks.add(new Runnable() { tasks.add(() -> b.talk(Emulator.getTexts().getValue("bots.butler.given").replace("%key%", key).replace("%username%", serveEvent.habbo.getHabboInfo().getUsername())));
@Override
public void run() {
b.talk(Emulator.getTexts().getValue("bots.butler.given").replace("%key%", key).replace("%username%", serveEvent.habbo.getHabboInfo().getUsername()));
}
});
List<Runnable> failedReached = new ArrayList(); List<Runnable> failedReached = new ArrayList();
failedReached.add(new Runnable() { failedReached.add(() -> {
public void run() { if (b.getRoomUnit().getCurrentLocation().distance(serveEvent.habbo.getRoomUnit().getCurrentLocation()) <= Emulator.getConfig().getInt("hotel.bot.butler.servedistance", 8)) {
if (b.getRoomUnit().getCurrentLocation().distance(serveEvent.habbo.getRoomUnit().getCurrentLocation()) <= Emulator.getConfig().getInt("hotel.bot.butler.servedistance", 8)) { for (Runnable t : tasks) {
for (Runnable t : tasks) { t.run();
t.run();
}
} }
} }
}); });

View File

@ -56,7 +56,7 @@ public class VisitorBot extends Bot {
public void onUserEnter(Habbo habbo) { public void onUserEnter(Habbo habbo) {
if (!this.showedLog) { if (!this.showedLog) {
if (habbo.getHabboInfo().getCurrentRoom() != null) { if (habbo.getHabboInfo().getCurrentRoom() != null) {
this.visits = Emulator.getGameEnvironment().getModToolManager().getVisitsForRoom(habbo.getHabboInfo().getCurrentRoom(), 10, true, habbo.getHabboInfo().getLastOnline(), Emulator.getIntUnixTimestamp()); this.visits = Emulator.getGameEnvironment().getModToolManager().getVisitsForRoom(habbo.getHabboInfo().getCurrentRoom(), 10, true, habbo.getHabboInfo().getLastOnline(), Emulator.getIntUnixTimestamp(), habbo.getHabboInfo().getCurrentRoom().getOwnerName());
if (this.visits.isEmpty()) { if (this.visits.isEmpty()) {
this.talk(Emulator.getTexts().getValue("bots.visitor.no_visits")); this.talk(Emulator.getTexts().getValue("bots.visitor.no_visits"));

View File

@ -3,9 +3,12 @@ package com.eu.habbo.habbohotel.catalog;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.items.FurnitureType; import com.eu.habbo.habbohotel.items.FurnitureType;
import com.eu.habbo.habbohotel.items.Item; import com.eu.habbo.habbohotel.items.Item;
import com.eu.habbo.habbohotel.users.HabboBadge;
import com.eu.habbo.messages.ISerialize; import com.eu.habbo.messages.ISerialize;
import com.eu.habbo.messages.ServerMessage; import com.eu.habbo.messages.ServerMessage;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -14,7 +17,7 @@ import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem> { public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem> {
private static final Logger LOGGER = LoggerFactory.getLogger(CatalogItem.class);
int id; int id;
int limitedStack; int limitedStack;
private int pageId; private int pageId;
@ -211,7 +214,7 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
identifier = Integer.parseInt(itemId); identifier = Integer.parseInt(itemId);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logStart("Invalid value (" + itemId + ") for items_base column for catalog_item id (" + this.id + "). Value must be integer or of the format of integer:amount;integer:amount"); LOGGER.info("Invalid value (" + itemId + ") for items_base column for catalog_item id (" + this.id + "). Value must be integer or of the format of integer:amount;integer:amount");
continue; continue;
} }
if (identifier > 0) { if (identifier > 0) {
@ -258,8 +261,8 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
} }
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logDebugLine("Failed to load " + this.itemId); LOGGER.debug("Failed to load " + this.itemId);
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} else { } else {
try { try {
@ -343,7 +346,7 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
statement.setInt(3, this.getId()); statement.setInt(3, this.getId());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
this.needsUpdate = false; this.needsUpdate = false;

View File

@ -3,6 +3,8 @@ package com.eu.habbo.habbohotel.catalog;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboItem; import com.eu.habbo.habbohotel.users.HabboItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -11,6 +13,8 @@ import java.util.Collections;
import java.util.LinkedList; import java.util.LinkedList;
public class CatalogLimitedConfiguration implements Runnable { public class CatalogLimitedConfiguration implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(CatalogLimitedConfiguration.class);
private final int itemId; private final int itemId;
private final LinkedList<Integer> limitedNumbers; private final LinkedList<Integer> limitedNumbers;
private int totalSet; private int totalSet;
@ -47,7 +51,7 @@ public class CatalogLimitedConfiguration implements Runnable {
statement.setInt(5, item.getLimitedSells()); statement.setInt(5, item.getLimitedSells());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }
@ -65,7 +69,7 @@ public class CatalogLimitedConfiguration implements Runnable {
statement.executeBatch(); statement.executeBatch();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
this.totalSet += amount; this.totalSet += amount;
@ -98,7 +102,7 @@ public class CatalogLimitedConfiguration implements Runnable {
statement.setInt(3, this.itemId); statement.setInt(3, this.itemId);
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -11,6 +11,7 @@ import com.eu.habbo.habbohotel.items.Item;
import com.eu.habbo.habbohotel.items.SoundTrack; import com.eu.habbo.habbohotel.items.SoundTrack;
import com.eu.habbo.habbohotel.items.interactions.*; import com.eu.habbo.habbohotel.items.interactions.*;
import com.eu.habbo.habbohotel.modtool.ScripterManager; import com.eu.habbo.habbohotel.modtool.ScripterManager;
import com.eu.habbo.habbohotel.permissions.Permission;
import com.eu.habbo.habbohotel.pets.Pet; import com.eu.habbo.habbohotel.pets.Pet;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboBadge; import com.eu.habbo.habbohotel.users.HabboBadge;
@ -39,14 +40,17 @@ import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public class CatalogManager { public class CatalogManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CatalogManager.class);
public static final THashMap<String, Class<? extends CatalogPage>> pageDefinitions = new THashMap<String, Class<? extends CatalogPage>>(CatalogPageLayouts.values().length) { public static final THashMap<String, Class<? extends CatalogPage>> pageDefinitions = new THashMap<String, Class<? extends CatalogPage>>(CatalogPageLayouts.values().length) {
{ {
for (CatalogPageLayouts layout : CatalogPageLayouts.values()) { for (CatalogPageLayouts layout : CatalogPageLayouts.values()) {
@ -209,7 +213,7 @@ public class CatalogManager {
this.ecotronItem = Emulator.getGameEnvironment().getItemManager().getItem("ecotron_box"); this.ecotronItem = Emulator.getGameEnvironment().getItemManager().getItem("ecotron_box");
Emulator.getLogging().logStart("Catalog Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("Catalog Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} }
@ -249,7 +253,7 @@ public class CatalogManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
for (Map.Entry<Integer, LinkedList<Integer>> set : limiteds.entrySet()) { for (Map.Entry<Integer, LinkedList<Integer>> set : limiteds.entrySet()) {
@ -269,7 +273,7 @@ public class CatalogManager {
Class<? extends CatalogPage> pageClazz = pageDefinitions.get(set.getString("page_layout")); Class<? extends CatalogPage> pageClazz = pageDefinitions.get(set.getString("page_layout"));
if (pageClazz == null) { if (pageClazz == null) {
Emulator.getLogging().logStart("Unknown Page Layout: " + set.getString("page_layout")); LOGGER.info("Unknown Page Layout: " + set.getString("page_layout"));
continue; continue;
} }
@ -277,12 +281,12 @@ public class CatalogManager {
CatalogPage page = pageClazz.getConstructor(ResultSet.class).newInstance(set); CatalogPage page = pageClazz.getConstructor(ResultSet.class).newInstance(set);
pages.put(page.getId(), page); pages.put(page.getId(), page);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine("Failed to load layout: " + set.getString("page_layout")); LOGGER.error("Failed to load layout: {}", set.getString("page_layout"));
} }
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
pages.forEachValue((object) -> { pages.forEachValue((object) -> {
@ -294,7 +298,7 @@ public class CatalogManager {
} }
} else { } else {
if (object.parentId != -2) { if (object.parentId != -2) {
Emulator.getLogging().logStart("Parent Page not found for " + object.getPageName() + " (ID: " + object.id + ", parent_id: " + object.parentId + ")"); LOGGER.info("Parent Page not found for " + object.getPageName() + " (ID: " + object.id + ", parent_id: " + object.parentId + ")");
} }
} }
return true; return true;
@ -302,7 +306,7 @@ public class CatalogManager {
this.catalogPages.putAll(pages); this.catalogPages.putAll(pages);
Emulator.getLogging().logStart("Loaded " + this.catalogPages.size() + " Catalog Pages!"); LOGGER.info("Loaded " + this.catalogPages.size() + " Catalog Pages!");
} }
@ -323,7 +327,7 @@ public class CatalogManager {
)); ));
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -367,7 +371,7 @@ public class CatalogManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
for (CatalogPage page : this.catalogPages.valueCollection()) { for (CatalogPage page : this.catalogPages.valueCollection()) {
@ -392,7 +396,7 @@ public class CatalogManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -408,7 +412,7 @@ public class CatalogManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }
@ -423,7 +427,7 @@ public class CatalogManager {
this.vouchers.add(new Voucher(set)); this.vouchers.add(new Voucher(set));
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }
@ -443,11 +447,11 @@ public class CatalogManager {
this.prizes.get(set.getInt("rarity")).add(item); this.prizes.get(set.getInt("rarity")).add(item);
} else { } else {
Emulator.getLogging().logErrorLine("Cannot load item with ID:" + set.getInt("item_id") + " as recycler reward!"); LOGGER.error("Cannot load item with ID: {} as recycler reward!", set.getInt("item_id"));
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }
@ -472,7 +476,7 @@ public class CatalogManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }
@ -489,7 +493,7 @@ public class CatalogManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }
@ -504,7 +508,7 @@ public class CatalogManager {
this.clothing.put(set.getInt("id"), new ClothItem(set)); this.clothing.put(set.getInt("id"), new ClothItem(set));
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }
@ -594,7 +598,7 @@ public class CatalogManager {
return statement.executeUpdate() >= 1; return statement.executeUpdate() >= 1;
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return false; return false;
@ -699,7 +703,7 @@ public class CatalogManager {
if (this.prizes.containsKey(level) && !this.prizes.get(level).isEmpty()) { if (this.prizes.containsKey(level) && !this.prizes.get(level).isEmpty()) {
return (Item) this.prizes.get(level).toArray()[Emulator.getRandom().nextInt(this.prizes.get(level).size())]; return (Item) this.prizes.get(level).toArray()[Emulator.getRandom().nextInt(this.prizes.get(level).size())];
} else { } else {
Emulator.getLogging().logErrorLine("[Recycler] No rewards specified for rarity level " + level); LOGGER.error("No rewards specified for rarity level {}", level);
} }
return null; return null;
@ -730,13 +734,11 @@ public class CatalogManager {
if (pageClazz != null) { if (pageClazz != null) {
try { try {
catalogPage = pageClazz.getConstructor(ResultSet.class).newInstance(page); catalogPage = pageClazz.getConstructor(ResultSet.class).newInstance(page);
} catch (InvocationTargetException e) {
Emulator.getLogging().logErrorLine(e.getCause());
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} else { } else {
Emulator.getLogging().logErrorLine("Unknown Page Layout: " + page.getString("page_layout")); LOGGER.error("Unknown page layout: {}", page.getString("page_layout"));
} }
} }
} }
@ -744,7 +746,7 @@ public class CatalogManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
if (catalogPage != null) { if (catalogPage != null) {
@ -803,7 +805,7 @@ public class CatalogManager {
} }
} }
Emulator.getLogging().logShutdownLine("Catalog Manager -> Disposed!"); LOGGER.info("Catalog Manager -> Disposed!");
} }
@ -872,7 +874,7 @@ public class CatalogManager {
if (amount > 1 && !CatalogItem.haveOffer(item)) { if (amount > 1 && !CatalogItem.haveOffer(item)) {
String message = Emulator.getTexts().getValue("scripter.warning.catalog.amount").replace("%username%", habbo.getHabboInfo().getUsername()).replace("%itemname%", item.getName()).replace("%pagename%", page.getCaption()); String message = Emulator.getTexts().getValue("scripter.warning.catalog.amount").replace("%username%", habbo.getHabboInfo().getUsername()).replace("%itemname%", item.getName()).replace("%pagename%", page.getCaption());
ScripterManager.scripterDetected(habbo.getClient(), message); ScripterManager.scripterDetected(habbo.getClient(), message);
Emulator.getLogging().logUserLine(message); LOGGER.info(message);
habbo.getClient().sendResponse(new AlertPurchaseUnavailableComposer(AlertPurchaseUnavailableComposer.ILLEGAL)); habbo.getClient().sendResponse(new AlertPurchaseUnavailableComposer(AlertPurchaseUnavailableComposer.ILLEGAL));
return; return;
} }
@ -957,7 +959,7 @@ public class CatalogManager {
try { try {
pet = Emulator.getGameEnvironment().getPetManager().createPet(baseItem, data[0], data[1], data[2], habbo.getClient()); pet = Emulator.getGameEnvironment().getPetManager().createPet(baseItem, data[0], data[1], data[2], habbo.getClient());
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
habbo.getClient().sendResponse(new AlertPurchaseFailedComposer(AlertPurchaseFailedComposer.SERVER_ERROR)); habbo.getClient().sendResponse(new AlertPurchaseFailedComposer(AlertPurchaseFailedComposer.SERVER_ERROR));
} }
@ -1012,28 +1014,28 @@ public class CatalogManager {
try { try {
guildId = Integer.parseInt(extradata); guildId = Integer.parseInt(extradata);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
habbo.getClient().sendResponse(new AlertPurchaseFailedComposer(AlertPurchaseFailedComposer.SERVER_ERROR)); habbo.getClient().sendResponse(new AlertPurchaseFailedComposer(AlertPurchaseFailedComposer.SERVER_ERROR));
return; return;
} }
InteractionGuildFurni habboItem = (InteractionGuildFurni) Emulator.getGameEnvironment().getItemManager().createItem(habbo.getClient().getHabbo().getHabboInfo().getId(), baseItem, limitedStack, limitedNumber, extradata); Guild guild = Emulator.getGameEnvironment().getGuildManager().getGuild(guildId);
habboItem.setExtradata("");
habboItem.needsUpdate(true);
Emulator.getThreading().run(habboItem); if (guild != null && Emulator.getGameEnvironment().getGuildManager().getGuildMember(guild, habbo) != null) {
Emulator.getGameEnvironment().getGuildManager().setGuild(habboItem, guildId); InteractionGuildFurni habboItem = (InteractionGuildFurni) Emulator.getGameEnvironment().getItemManager().createItem(habbo.getClient().getHabbo().getHabboInfo().getId(), baseItem, limitedStack, limitedNumber, extradata);
itemsList.add(habboItem); habboItem.setExtradata("");
habboItem.needsUpdate(true);
if (baseItem.getName().equals("guild_forum")) { Emulator.getThreading().run(habboItem);
Guild guild = Emulator.getGameEnvironment().getGuildManager().getGuild(guildId); Emulator.getGameEnvironment().getGuildManager().setGuild(habboItem, guildId);
if (guild != null) { itemsList.add(habboItem);
if (baseItem.getName().equals("guild_forum")) {
guild.setForum(true); guild.setForum(true);
guild.needsUpdate = true; guild.needsUpdate = true;
guild.run(); guild.run();
} }
} }
} else if (baseItem.getInteractionType().getType() == InteractionMusicDisc.class) { } else if (baseItem.getInteractionType().getType() == InteractionMusicDisc.class) {
SoundTrack track = Emulator.getGameEnvironment().getItemManager().getSoundTrack(item.getExtradata()); SoundTrack track = Emulator.getGameEnvironment().getItemManager().getSoundTrack(item.getExtradata());
@ -1069,14 +1071,14 @@ public class CatalogManager {
} }
} }
if (!free && !habbo.getClient().getHabbo().hasPermission("acc_infinite_credits")) { if (!free && !habbo.getClient().getHabbo().hasPermission(Permission.ACC_INFINITE_CREDITS)) {
if (purchasedEvent.totalCredits > 0) { if (purchasedEvent.totalCredits > 0) {
habbo.getClient().getHabbo().getHabboInfo().addCredits(-purchasedEvent.totalCredits); habbo.getClient().getHabbo().getHabboInfo().addCredits(-purchasedEvent.totalCredits);
habbo.getClient().sendResponse(new UserCreditsComposer(habbo.getClient().getHabbo())); habbo.getClient().sendResponse(new UserCreditsComposer(habbo.getClient().getHabbo()));
} }
} }
if (!free && !habbo.getClient().getHabbo().hasPermission("acc_infinite_points")) { if (!free && !habbo.getClient().getHabbo().hasPermission(Permission.ACC_INFINITE_POINTS)) {
if (purchasedEvent.totalPoints > 0) { if (purchasedEvent.totalPoints > 0) {
habbo.getClient().getHabbo().getHabboInfo().addCurrencyAmount(item.getPointsType(), -purchasedEvent.totalPoints); habbo.getClient().getHabbo().getHabboInfo().addCurrencyAmount(item.getPointsType(), -purchasedEvent.totalPoints);
habbo.getClient().sendResponse(new UserPointsComposer(habbo.getClient().getHabbo().getHabboInfo().getCurrencyAmount(item.getPointsType()), -purchasedEvent.totalPoints, item.getPointsType())); habbo.getClient().sendResponse(new UserPointsComposer(habbo.getClient().getHabbo().getHabboInfo().getCurrencyAmount(item.getPointsType()), -purchasedEvent.totalPoints, item.getPointsType()));
@ -1120,7 +1122,7 @@ public class CatalogManager {
habbo.getClient().sendResponse(new InventoryRefreshComposer()); habbo.getClient().sendResponse(new InventoryRefreshComposer());
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logPacketError(e); LOGGER.error("Exception caught", e);
habbo.getClient().sendResponse(new AlertPurchaseFailedComposer(AlertPurchaseFailedComposer.SERVER_ERROR)); habbo.getClient().sendResponse(new AlertPurchaseFailedComposer(AlertPurchaseFailedComposer.SERVER_ERROR));
} }
} finally { } finally {
@ -1156,7 +1158,7 @@ public class CatalogManager {
statement.setInt(3, Emulator.getIntUnixTimestamp()); statement.setInt(3, Emulator.getIntUnixTimestamp());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -1,6 +1,5 @@
package com.eu.habbo.habbohotel.catalog; package com.eu.habbo.habbohotel.catalog;
import com.eu.habbo.Emulator;
import com.eu.habbo.messages.ISerialize; import com.eu.habbo.messages.ISerialize;
import com.eu.habbo.messages.ServerMessage; import com.eu.habbo.messages.ServerMessage;
import gnu.trove.TCollections; import gnu.trove.TCollections;
@ -8,12 +7,16 @@ import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.TIntObjectMap; import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TIntObjectHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize { public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize {
private static final Logger LOGGER = LoggerFactory.getLogger(CatalogPage.class);
protected final TIntArrayList offerIds = new TIntArrayList(); protected final TIntArrayList offerIds = new TIntArrayList();
protected final THashMap<Integer, CatalogPage> childPages = new THashMap<>(); protected final THashMap<Integer, CatalogPage> childPages = new THashMap<>();
private final TIntObjectMap<CatalogItem> catalogItems = TCollections.synchronizedMap(new TIntObjectHashMap<>()); private final TIntObjectMap<CatalogItem> catalogItems = TCollections.synchronizedMap(new TIntObjectHashMap<>());
@ -70,8 +73,8 @@ public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize
try { try {
this.included.add(Integer.valueOf(id)); this.included.add(Integer.valueOf(id));
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
Emulator.getLogging().logErrorLine("Failed to parse includes column value of (" + id + ") for catalog page (" + this.id + ")"); LOGGER.error("Failed to parse includes column value of (" + id + ") for catalog page (" + this.id + ")");
} }
} }
} }

View File

@ -1,6 +1,8 @@
package com.eu.habbo.habbohotel.catalog; package com.eu.habbo.habbohotel.catalog;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -10,6 +12,8 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class Voucher { public class Voucher {
private static final Logger LOGGER = LoggerFactory.getLogger(Voucher.class);
public final int id; public final int id;
public final String code; public final String code;
public final int credits; public final int credits;
@ -41,7 +45,7 @@ public class Voucher {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -64,7 +68,7 @@ public class Voucher {
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -13,11 +13,15 @@ import com.eu.habbo.messages.outgoing.navigator.CanCreateRoomComposer;
import gnu.trove.map.TIntObjectMap; import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.TObjectProcedure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*; import java.sql.*;
import java.util.Map; import java.util.Map;
public class RoomBundleLayout extends SingleBundle { public class RoomBundleLayout extends SingleBundle {
private static final Logger LOGGER = LoggerFactory.getLogger(RoomBundleLayout.class);
public int roomId; public int roomId;
public Room room; public Room room;
private int lastUpdate = 0; private int lastUpdate = 0;
@ -43,7 +47,7 @@ public class RoomBundleLayout extends SingleBundle {
if (this.room != null) if (this.room != null)
this.room.preventUnloading = true; this.room.preventUnloading = true;
} else { } else {
Emulator.getLogging().logErrorLine("No room id specified for room bundle " + this.getPageName() + "(" + this.getId() + ")"); LOGGER.error("No room id specified for room bundle " + this.getPageName() + "(" + this.getId() + ")");
} }
} }
@ -185,7 +189,7 @@ public class RoomBundleLayout extends SingleBundle {
statement.setInt(3, this.room.getId()); statement.setInt(3, this.room.getId());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -219,7 +223,7 @@ public class RoomBundleLayout extends SingleBundle {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
Room r = Emulator.getGameEnvironment().getRoomManager().loadRoom(roomId); Room r = Emulator.getGameEnvironment().getRoomManager().loadRoom(roomId);

View File

@ -16,6 +16,8 @@ import com.eu.habbo.plugin.events.marketplace.MarketPlaceItemCancelledEvent;
import com.eu.habbo.plugin.events.marketplace.MarketPlaceItemOfferedEvent; import com.eu.habbo.plugin.events.marketplace.MarketPlaceItemOfferedEvent;
import com.eu.habbo.plugin.events.marketplace.MarketPlaceItemSoldEvent; import com.eu.habbo.plugin.events.marketplace.MarketPlaceItemSoldEvent;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -26,6 +28,8 @@ import java.util.List;
public class MarketPlace { public class MarketPlace {
private static final Logger LOGGER = LoggerFactory.getLogger(MarketPlace.class);
//Configuration. Loaded from database & updated accordingly. //Configuration. Loaded from database & updated accordingly.
public static boolean MARKETPLACE_ENABLED = true; public static boolean MARKETPLACE_ENABLED = true;
@ -43,7 +47,7 @@ public class MarketPlace {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return offers; return offers;
@ -101,7 +105,7 @@ public class MarketPlace {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
habbo.getClient().sendResponse(new MarketplaceCancelSaleComposer(offer, false)); habbo.getClient().sendResponse(new MarketplaceCancelSaleComposer(offer, false));
} }
} }
@ -110,7 +114,7 @@ public class MarketPlace {
public static List<MarketPlaceOffer> getOffers(int minPrice, int maxPrice, String search, int sort) { public static List<MarketPlaceOffer> getOffers(int minPrice, int maxPrice, String search, int sort) {
List<MarketPlaceOffer> offers = new ArrayList<>(10); List<MarketPlaceOffer> offers = new ArrayList<>(10);
String query = "SELECT B.* FROM marketplace_items a INNER JOIN (SELECT b.item_id AS base_item_id, b.limited_data AS ltd_data, marketplace_items.*, AVG(price) as avg, MIN(marketplace_items.price) as minPrice, MAX(marketplace_items.price) as maxPrice, COUNT(*) as number, (SELECT COUNT(*) FROM marketplace_items c INNER JOIN items as items_b ON c.item_id = items_b.id WHERE state = 2 AND items_b.item_id = base_item_id AND DATE(from_unixtime(sold_timestamp)) = CURDATE()) as sold_count_today FROM marketplace_items INNER JOIN items b ON marketplace_items.item_id = b.id INNER JOIN items_base bi ON b.item_id = bi.id WHERE price = (SELECT MIN(e.price) FROM marketplace_items e, items d WHERE e.item_id = d.id AND d.item_id = b.item_id AND e.state = 1 AND e.timestamp > ? GROUP BY d.item_id) AND state = 1 AND timestamp > ?"; String query = "SELECT B.* FROM marketplace_items a INNER JOIN (SELECT b.item_id AS base_item_id, b.limited_data AS ltd_data, marketplace_items.*, AVG(price) as avg, MIN(marketplace_items.price) as minPrice, MAX(marketplace_items.price) as maxPrice, COUNT(*) as number, (SELECT COUNT(*) FROM marketplace_items c INNER JOIN items as items_b ON c.item_id = items_b.id WHERE state = 2 AND items_b.item_id = base_item_id AND DATE(from_unixtime(sold_timestamp)) = CURDATE()) as sold_count_today FROM marketplace_items INNER JOIN items b ON marketplace_items.item_id = b.id INNER JOIN items_base bi ON b.item_id = bi.id INNER JOIN catalog_items ci ON bi.id = ci.item_ids WHERE price = (SELECT MIN(e.price) FROM marketplace_items e, items d WHERE e.item_id = d.id AND d.item_id = b.item_id AND e.state = 1 AND e.timestamp > ? GROUP BY d.item_id) AND state = 1 AND timestamp > ?";
if (minPrice > 0) { if (minPrice > 0) {
query += " AND CEIL(price + (price / 100)) >= " + minPrice; query += " AND CEIL(price + (price / 100)) >= " + minPrice;
} }
@ -118,7 +122,7 @@ public class MarketPlace {
query += " AND CEIL(price + (price / 100)) <= " + maxPrice; query += " AND CEIL(price + (price / 100)) <= " + maxPrice;
} }
if (search.length() > 0) { if (search.length() > 0) {
query += " AND bi.public_name LIKE ?"; query += " AND bi.public_name LIKE ? OR ci.catalog_name LIKE ?";
} }
query += " GROUP BY base_item_id, ltd_data"; query += " GROUP BY base_item_id, ltd_data";
@ -149,13 +153,15 @@ public class MarketPlace {
query += " AS B ON a.id = B.id"; query += " AS B ON a.id = B.id";
query += " LIMIT 100"; query += " LIMIT 250";
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement(query)) { try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement(query)) {
statement.setInt(1, Emulator.getIntUnixTimestamp() - 172800); statement.setInt(1, Emulator.getIntUnixTimestamp() - 172800);
statement.setInt(2, Emulator.getIntUnixTimestamp() - 172800); statement.setInt(2, Emulator.getIntUnixTimestamp() - 172800);
if (search.length() > 0) if (search.length() > 0) {
statement.setString(3, "%" + search + "%"); statement.setString(3, "%" + search + "%");
statement.setString(4, "%" + search + "%");
}
try (ResultSet set = statement.executeQuery()) { try (ResultSet set = statement.executeQuery()) {
while (set.next()) { while (set.next()) {
@ -163,7 +169,7 @@ public class MarketPlace {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return offers; return offers;
@ -193,7 +199,7 @@ public class MarketPlace {
message.appendInt(1); message.appendInt(1);
message.appendInt(itemId); message.appendInt(itemId);
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -208,7 +214,7 @@ public class MarketPlace {
number = set.getInt("number"); number = set.getInt("number");
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return number; return number;
@ -226,7 +232,7 @@ public class MarketPlace {
avg = set.getInt("avg"); avg = set.getInt("avg");
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return calculateCommision(avg); return calculateCommision(avg);
@ -294,7 +300,7 @@ public class MarketPlace {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -321,7 +327,7 @@ public class MarketPlace {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -388,7 +394,7 @@ public class MarketPlace {
statement.setInt(2, offer.getOfferId()); statement.setInt(2, offer.getOfferId());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }

View File

@ -5,10 +5,14 @@ import com.eu.habbo.habbohotel.items.FurnitureType;
import com.eu.habbo.habbohotel.items.Item; import com.eu.habbo.habbohotel.items.Item;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboItem; import com.eu.habbo.habbohotel.users.HabboItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*; import java.sql.*;
public class MarketPlaceOffer implements Runnable { public class MarketPlaceOffer implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(MarketPlaceOffer.class);
public int avarage; public int avarage;
public int count; public int count;
private int offerId; private int offerId;
@ -66,7 +70,7 @@ public class MarketPlaceOffer implements Runnable {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -86,7 +90,7 @@ public class MarketPlaceOffer implements Runnable {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -160,7 +164,7 @@ public class MarketPlaceOffer implements Runnable {
statement.setInt(3, this.offerId); statement.setInt(3, this.offerId);
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -3,12 +3,16 @@ package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.items.YoutubeManager; import com.eu.habbo.habbohotel.items.YoutubeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public class AddYoutubePlaylistCommand extends Command { public class AddYoutubePlaylistCommand extends Command {
private static final Logger LOGGER = LoggerFactory.getLogger(AddYoutubePlaylistCommand.class);
public AddYoutubePlaylistCommand() { public AddYoutubePlaylistCommand() {
super("cmd_add_youtube_playlist", Emulator.getTexts().getValue("commands.keys.cmd_add_youtube_playlist").split(";")); super("cmd_add_youtube_playlist", Emulator.getTexts().getValue("commands.keys.cmd_add_youtube_playlist").split(";"));
} }
@ -49,7 +53,7 @@ public class AddYoutubePlaylistCommand extends Command {
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_add_youtube_playlist")); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_add_youtube_playlist"));

View File

@ -25,22 +25,32 @@ public class AllowTradingCommand extends Command {
return true; return true;
} }
if (params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes")) || params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.no"))) { final String username = params[1];
String username = params[1]; final String option = params[2];
boolean enabled = params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"));
Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(username); if (option.equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes")) || option.equalsIgnoreCase(Emulator.getTexts().getValue("generic.no"))) {
final boolean enabled = option.equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"));
final Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(username);
if (habbo != null) { if (habbo != null) {
if (!enabled) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("UPDATE users_settings SET tradelock_amount = tradelock_amount + 1 WHERE user_id = ?")) {
statement.setInt(1, habbo.getHabboInfo().getId());
statement.executeUpdate();
}
}
habbo.getHabboStats().setAllowTrade(enabled); habbo.getHabboStats().setAllowTrade(enabled);
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_allow_trading." + (enabled ? "enabled" : "disabled")).replace("%username%", params[1])); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_allow_trading." + (enabled ? "enabled" : "disabled")).replace("%username%", params[1]));
habbo.getClient().sendResponse(new UserPerksComposer(habbo)); habbo.getClient().sendResponse(new UserPerksComposer(habbo));
return true; return true;
} else { } else {
boolean found; boolean found;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_settings INNER JOIN users ON users.id = users_settings.id SET can_trade = ? WHERE users.username LIKE ?")) { try (Connection connection = Emulator.getDatabase().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("UPDATE users_settings INNER JOIN users ON users.id = users_settings.user_id SET can_trade = ?, tradelock_amount = tradelock_amount + ? WHERE users.username LIKE ?")) {
statement.setString(1, enabled ? "1" : "0"); statement.setString(1, enabled ? "1" : "0");
statement.setString(2, username); statement.setInt(2, enabled ? 0 : 1);
statement.setString(3, username);
found = statement.executeUpdate() > 0; found = statement.executeUpdate() > 0;
} }

View File

@ -6,6 +6,8 @@ import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboInfo; import com.eu.habbo.habbohotel.users.HabboInfo;
import com.eu.habbo.habbohotel.users.HabboManager; import com.eu.habbo.habbohotel.users.HabboManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -13,6 +15,8 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class BadgeCommand extends Command { public class BadgeCommand extends Command {
private static final Logger LOGGER = LoggerFactory.getLogger(BadgeCommand.class);
public BadgeCommand() { public BadgeCommand() {
super("cmd_badge", Emulator.getTexts().getValue("commands.keys.cmd_badge").split(";")); super("cmd_badge", Emulator.getTexts().getValue("commands.keys.cmd_badge").split(";"));
} }
@ -72,7 +76,7 @@ public class BadgeCommand extends Command {
return true; return true;
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -2,6 +2,7 @@ package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.permissions.Permission;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles; import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import com.eu.habbo.messages.outgoing.users.MeMenuSettingsComposer; import com.eu.habbo.messages.outgoing.users.MeMenuSettingsComposer;
@ -31,7 +32,7 @@ public class ChatTypeCommand extends Command {
return true; return true;
} }
if (!gameClient.getHabbo().hasPermission("acc_anychatcolor")) { if (!gameClient.getHabbo().hasPermission(Permission.ACC_ANYCHATCOLOR)) {
for (String s : Emulator.getConfig().getValue("commands.cmd_chatcolor.banned_numbers").split(";")) { for (String s : Emulator.getConfig().getValue("commands.cmd_chatcolor.banned_numbers").split(";")) {
if (Integer.valueOf(s) == chatColor) { if (Integer.valueOf(s) == chatColor) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_chatcolor.banned"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_chatcolor.banned"), RoomChatMessageBubbles.ALERT);

View File

@ -15,6 +15,8 @@ import com.eu.habbo.plugin.events.users.UserCommandEvent;
import com.eu.habbo.plugin.events.users.UserExecuteCommandEvent; import com.eu.habbo.plugin.events.users.UserExecuteCommandEvent;
import gnu.trove.iterator.TIntObjectIterator; import gnu.trove.iterator.TIntObjectIterator;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Comparator; import java.util.Comparator;
@ -22,6 +24,9 @@ import java.util.List;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
public class CommandHandler { public class CommandHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(CommandHandler.class);
private final static THashMap<String, Command> commands = new THashMap<>(5); private final static THashMap<String, Command> commands = new THashMap<>(5);
private static final Comparator<Command> ALPHABETICAL_ORDER = new Comparator<Command>() { private static final Comparator<Command> ALPHABETICAL_ORDER = new Comparator<Command>() {
public int compare(Command c1, Command c2) { public int compare(Command c1, Command c2) {
@ -33,7 +38,7 @@ public class CommandHandler {
public CommandHandler() { public CommandHandler() {
long millis = System.currentTimeMillis(); long millis = System.currentTimeMillis();
this.reloadCommands(); this.reloadCommands();
Emulator.getLogging().logStart("Command Handler -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("Command Handler -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} }
public static void addCommand(Command command) { public static void addCommand(Command command) {
@ -48,9 +53,9 @@ public class CommandHandler {
try { try {
//command.getConstructor().setAccessible(true); //command.getConstructor().setAccessible(true);
addCommand(command.newInstance()); addCommand(command.newInstance());
Emulator.getLogging().logDebugLine("Added command: " + command.getName()); LOGGER.debug("Added command: {}", command.getName());
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
@ -67,7 +72,7 @@ public class CommandHandler {
for (String s : command.keys) { for (String s : command.keys) {
if (s.toLowerCase().equals(parts[0].toLowerCase())) { if (s.toLowerCase().equals(parts[0].toLowerCase())) {
boolean succes = false; boolean succes = false;
if (command.permission == null || gameClient.getHabbo().hasPermission(command.permission, gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null && (gameClient.getHabbo().getHabboInfo().getCurrentRoom().hasRights(gameClient.getHabbo())) || gameClient.getHabbo().hasPermission("acc_placefurni") || (gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null && gameClient.getHabbo().getHabboInfo().getCurrentRoom().getGuildId() > 0 && gameClient.getHabbo().getHabboInfo().getCurrentRoom().guildRightLevel(gameClient.getHabbo()) >= 2))) { if (command.permission == null || gameClient.getHabbo().hasPermission(command.permission, gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null && (gameClient.getHabbo().getHabboInfo().getCurrentRoom().hasRights(gameClient.getHabbo())) || gameClient.getHabbo().hasPermission(Permission.ACC_PLACEFURNI) || (gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null && gameClient.getHabbo().getHabboInfo().getCurrentRoom().getGuildId() > 0 && gameClient.getHabbo().getHabboInfo().getCurrentRoom().guildRightLevel(gameClient.getHabbo()) >= 2))) {
try { try {
Emulator.getPluginManager().fireEvent(new UserExecuteCommandEvent(gameClient.getHabbo(), command, parts)); Emulator.getPluginManager().fireEvent(new UserExecuteCommandEvent(gameClient.getHabbo(), command, parts));
@ -79,11 +84,11 @@ public class CommandHandler {
succes = event.succes; succes = event.succes;
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
if (gameClient.getHabbo().getHabboInfo().getRank().isLogCommands()) { if (gameClient.getHabbo().getHabboInfo().getRank().isLogCommands()) {
Emulator.getLogging().addLog(new CommandLog(gameClient.getHabbo().getHabboInfo().getId(), command, commandLine, succes)); Emulator.getDatabaseLogger().store(new CommandLog(gameClient.getHabbo().getHabboInfo().getId(), command, commandLine, succes));
} }
} }
@ -279,6 +284,7 @@ public class CommandHandler {
addCommand(new WordQuizCommand()); addCommand(new WordQuizCommand());
addCommand(new UpdateYoutubePlaylistsCommand()); addCommand(new UpdateYoutubePlaylistsCommand());
addCommand(new AddYoutubePlaylistCommand()); addCommand(new AddYoutubePlaylistCommand());
addCommand(new SoftKickCommand());
addCommand(new TestCommand()); addCommand(new TestCommand());
} }
@ -305,7 +311,6 @@ public class CommandHandler {
public void dispose() { public void dispose() {
commands.clear(); commands.clear();
LOGGER.info("Command Handler -> Disposed!");
Emulator.getLogging().logShutdownLine("Command Handler -> Disposed!");
} }
} }

View File

@ -6,6 +6,7 @@ import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.permissions.Permission; import com.eu.habbo.habbohotel.permissions.Permission;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles; import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.messages.outgoing.inventory.InventoryBotsComposer;
import com.eu.habbo.messages.outgoing.inventory.InventoryRefreshComposer; import com.eu.habbo.messages.outgoing.inventory.InventoryRefreshComposer;
import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.TObjectProcedure;
@ -30,26 +31,24 @@ public class EmptyBotsInventoryCommand extends Command {
} }
if (params.length >= 2 && params[1].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"))) { if (params.length >= 2 && params[1].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"))) {
Habbo habbo = gameClient.getHabbo();
if (params.length == 3 && gameClient.getHabbo().hasPermission(Permission.ACC_EMPTY_OTHERS)) { Habbo habbo = (params.length == 3 && gameClient.getHabbo().hasPermission(Permission.ACC_EMPTY_OTHERS)) ? Emulator.getGameEnvironment().getHabboManager().getHabbo(params[2]) : gameClient.getHabbo();
habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(params[2]);
}
if (habbo != null) { if (habbo != null) {
TIntObjectHashMap<Bot> bots = new TIntObjectHashMap<>(); TIntObjectHashMap<Bot> bots = new TIntObjectHashMap<>();
bots.putAll(habbo.getInventory().getBotsComponent().getBots()); bots.putAll(habbo.getInventory().getBotsComponent().getBots());
habbo.getInventory().getBotsComponent().getBots().clear(); habbo.getInventory().getBotsComponent().getBots().clear();
bots.forEachValue(new TObjectProcedure<Bot>() { bots.forEachValue(object -> {
@Override Emulator.getGameEnvironment().getBotManager().deleteBot(object);
public boolean execute(Bot object) { return true;
Emulator.getGameEnvironment().getBotManager().deleteBot(object);
return true;
}
}); });
habbo.getClient().sendResponse(new InventoryRefreshComposer()); habbo.getClient().sendResponse(new InventoryRefreshComposer());
habbo.getClient().sendResponse(new InventoryBotsComposer(habbo));
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_empty_bots.cleared"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_empty_bots.cleared").replace("%username%", habbo.getHabboInfo().getUsername()), RoomChatMessageBubbles.ALERT);
} else {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_empty_bots"), RoomChatMessageBubbles.ALERT);
} }
} }

View File

@ -32,13 +32,10 @@ public class EmptyInventoryCommand extends Command {
} }
if (params.length >= 2 && params[1].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"))) { if (params.length >= 2 && params[1].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"))) {
Habbo habbo = gameClient.getHabbo();
if (params.length == 3 && gameClient.getHabbo().hasPermission(Permission.ACC_EMPTY_OTHERS)) { Habbo habbo = (params.length == 3 && gameClient.getHabbo().hasPermission(Permission.ACC_EMPTY_OTHERS)) ? Emulator.getGameEnvironment().getHabboManager().getHabbo(params[2]) : gameClient.getHabbo();
habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(params[2]);
}
if (habbo != null) { if (habbo != null) {
TIntObjectMap<HabboItem> items = new TIntObjectHashMap<>(); TIntObjectMap<HabboItem> items = new TIntObjectHashMap<>();
items.putAll(habbo.getInventory().getItemsComponent().getItems()); items.putAll(habbo.getInventory().getItemsComponent().getItems());
habbo.getInventory().getItemsComponent().getItems().clear(); habbo.getInventory().getItemsComponent().getItems().clear();
@ -47,10 +44,12 @@ public class EmptyInventoryCommand extends Command {
habbo.getClient().sendResponse(new InventoryRefreshComposer()); habbo.getClient().sendResponse(new InventoryRefreshComposer());
habbo.getClient().sendResponse(new InventoryItemsComposer(0, 1, gameClient.getHabbo().getInventory().getItemsComponent().getItems())); habbo.getClient().sendResponse(new InventoryItemsComposer(0, 1, gameClient.getHabbo().getInventory().getItemsComponent().getItems()));
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_empty.cleared"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_empty.cleared").replace("%username%", habbo.getHabboInfo().getUsername()), RoomChatMessageBubbles.ALERT);
} else {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_empty"), RoomChatMessageBubbles.ALERT);
} }
} }
return true; return true;
} }
} }

View File

@ -6,6 +6,7 @@ import com.eu.habbo.habbohotel.permissions.Permission;
import com.eu.habbo.habbohotel.pets.Pet; import com.eu.habbo.habbohotel.pets.Pet;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles; import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.messages.outgoing.inventory.InventoryPetsComposer;
import com.eu.habbo.messages.outgoing.inventory.InventoryRefreshComposer; import com.eu.habbo.messages.outgoing.inventory.InventoryRefreshComposer;
import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.TObjectProcedure;
@ -30,25 +31,24 @@ public class EmptyPetsInventoryCommand extends Command {
} }
if (params.length >= 2 && params[1].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"))) { if (params.length >= 2 && params[1].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"))) {
Habbo habbo = gameClient.getHabbo();
if (params.length == 3 && gameClient.getHabbo().hasPermission(Permission.ACC_EMPTY_OTHERS)) { Habbo habbo = (params.length == 3 && gameClient.getHabbo().hasPermission(Permission.ACC_EMPTY_OTHERS)) ? Emulator.getGameEnvironment().getHabboManager().getHabbo(params[2]) : gameClient.getHabbo();
habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(params[2]);
}
if (habbo != null) { if (habbo != null) {
TIntObjectHashMap<Pet> pets = new TIntObjectHashMap<>(); TIntObjectHashMap<Pet> pets = new TIntObjectHashMap<>();
pets.putAll(habbo.getInventory().getPetsComponent().getPets()); pets.putAll(habbo.getInventory().getPetsComponent().getPets());
habbo.getInventory().getPetsComponent().getPets().clear(); habbo.getInventory().getPetsComponent().getPets().clear();
pets.forEachValue(new TObjectProcedure<Pet>() { pets.forEachValue(object -> {
@Override Emulator.getGameEnvironment().getPetManager().deletePet(object);
public boolean execute(Pet object) { return true;
Emulator.getGameEnvironment().getPetManager().deletePet(object);
return true;
}
}); });
habbo.getClient().sendResponse(new InventoryRefreshComposer()); habbo.getClient().sendResponse(new InventoryRefreshComposer());
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_empty_pets.cleared"), RoomChatMessageBubbles.ALERT); habbo.getClient().sendResponse(new InventoryPetsComposer(habbo));
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_empty_pets.cleared").replace("%username%", habbo.getHabboInfo().getUsername()), RoomChatMessageBubbles.ALERT);
} else {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_empty_pets"), RoomChatMessageBubbles.ALERT);
} }
} }

View File

@ -2,10 +2,15 @@ package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.permissions.Permission;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles; import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EnableCommand extends Command { public class EnableCommand extends Command {
private static final Logger LOGGER = LoggerFactory.getLogger(EnableCommand.class);
public EnableCommand() { public EnableCommand() {
super("cmd_enable", Emulator.getTexts().getValue("commands.keys.cmd_enable").split(";")); super("cmd_enable", Emulator.getTexts().getValue("commands.keys.cmd_enable").split(";"));
} }
@ -25,7 +30,7 @@ public class EnableCommand extends Command {
} }
if (target != null) { if (target != null) {
if (target == gameClient.getHabbo() || gameClient.getHabbo().hasPermission("acc_enable_others")) { if (target == gameClient.getHabbo() || gameClient.getHabbo().hasPermission(Permission.ACC_ENABLE_OTHERS)) {
try { try {
if (target.getHabboInfo().getCurrentRoom() != null) { if (target.getHabboInfo().getCurrentRoom() != null) {
if (target.getHabboInfo().getRiding() == null) { if (target.getHabboInfo().getRiding() == null) {
@ -38,7 +43,7 @@ public class EnableCommand extends Command {
} }
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
} }

View File

@ -4,12 +4,16 @@ import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.modtool.WordFilter; import com.eu.habbo.habbohotel.modtool.WordFilter;
import com.eu.habbo.habbohotel.modtool.WordFilterWord; import com.eu.habbo.habbohotel.modtool.WordFilterWord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
public class FilterWordCommand extends Command { public class FilterWordCommand extends Command {
private static final Logger LOGGER = LoggerFactory.getLogger(FilterWordCommand.class);
public FilterWordCommand() { public FilterWordCommand() {
super("cmd_filterword", Emulator.getTexts().getValue("commands.keys.cmd_filterword").split(";")); super("cmd_filterword", Emulator.getTexts().getValue("commands.keys.cmd_filterword").split(";"));
} }
@ -35,7 +39,7 @@ public class FilterWordCommand extends Command {
statement.setString(2, replacement); statement.setString(2, replacement);
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_filterword.error")); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_filterword.error"));
return true; return true;
} }

View File

@ -32,7 +32,6 @@ public class HotelAlertCommand extends Command {
habbo.getClient().sendResponse(msg); habbo.getClient().sendResponse(msg);
} }
} else { } else {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ha.forgot_message"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ha.forgot_message"), RoomChatMessageBubbles.ALERT);
} }

View File

@ -59,24 +59,21 @@ public class MassGiftCommand extends Command {
keys.put("message", Emulator.getTexts().getValue("generic.gift.received.anonymous")); keys.put("message", Emulator.getTexts().getValue("generic.gift.received.anonymous"));
ServerMessage giftNotificiationMessage = new BubbleAlertComposer(BubbleAlertKeys.RECEIVED_BADGE.key, keys).compose(); ServerMessage giftNotificiationMessage = new BubbleAlertComposer(BubbleAlertKeys.RECEIVED_BADGE.key, keys).compose();
Emulator.getThreading().run(new Runnable() { Emulator.getThreading().run(() -> {
@Override for (Map.Entry<Integer, Habbo> set : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) {
public void run() { Habbo habbo = set.getValue();
for (Map.Entry<Integer, Habbo> set : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) {
Habbo habbo = set.getValue();
HabboItem item = Emulator.getGameEnvironment().getItemManager().createItem(0, baseItem, 0, 0, ""); HabboItem item = Emulator.getGameEnvironment().getItemManager().createItem(0, baseItem, 0, 0, "");
Item giftItem = Emulator.getGameEnvironment().getItemManager().getItem((Integer) Emulator.getGameEnvironment().getCatalogManager().giftFurnis.values().toArray()[Emulator.getRandom().nextInt(Emulator.getGameEnvironment().getCatalogManager().giftFurnis.size())]); Item giftItem = Emulator.getGameEnvironment().getItemManager().getItem((Integer) Emulator.getGameEnvironment().getCatalogManager().giftFurnis.values().toArray()[Emulator.getRandom().nextInt(Emulator.getGameEnvironment().getCatalogManager().giftFurnis.size())]);
String extraData = "1\t" + item.getId(); String extraData = "1\t" + item.getId();
extraData += "\t0\t0\t0\t" + finalMessage + "\t0\t0"; extraData += "\t0\t0\t0\t" + finalMessage + "\t0\t0";
Emulator.getGameEnvironment().getItemManager().createGift(habbo.getHabboInfo().getUsername(), giftItem, extraData, 0, 0); Emulator.getGameEnvironment().getItemManager().createGift(habbo.getHabboInfo().getUsername(), giftItem, extraData, 0, 0);
habbo.getClient().sendResponse(new InventoryRefreshComposer()); habbo.getClient().sendResponse(new InventoryRefreshComposer());
habbo.getClient().sendResponse(giftNotificiationMessage); habbo.getClient().sendResponse(giftNotificiationMessage);
}
} }
}); });

View File

@ -2,6 +2,7 @@ package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.permissions.Permission;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles; import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboGender; import com.eu.habbo.habbohotel.users.HabboGender;
@ -27,7 +28,7 @@ public class MimicCommand extends Command {
if (habbo == gameClient.getHabbo()) { if (habbo == gameClient.getHabbo()) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_mimic.not_self"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_mimic.not_self"), RoomChatMessageBubbles.ALERT);
return true; return true;
} else if (habbo.hasPermission("acc_not_mimiced") && !gameClient.getHabbo().hasPermission("acc_not_mimiced")) { } else if (habbo.hasPermission(Permission.ACC_NOT_MIMICED) && !gameClient.getHabbo().hasPermission(Permission.ACC_NOT_MIMICED)) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_mimic.blocked").replace("%user%", params[1]).replace("%gender_name%", (habbo.getHabboInfo().getGender().equals(HabboGender.M) ? Emulator.getTexts().getValue("gender.him") : Emulator.getTexts().getValue("gender.her"))), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_mimic.blocked").replace("%user%", params[1]).replace("%gender_name%", (habbo.getHabboInfo().getGender().equals(HabboGender.M) ? Emulator.getTexts().getValue("gender.him") : Emulator.getTexts().getValue("gender.her"))), RoomChatMessageBubbles.ALERT);
return true; return true;
} else if (!habbo.hasPermission("acc_mimic_unredeemed") && FigureUtil.hasBlacklistedClothing(habbo.getHabboInfo().getLook(), gameClient.getHabbo().getForbiddenClothing())) { } else if (!habbo.hasPermission("acc_mimic_unredeemed") && FigureUtil.hasBlacklistedClothing(habbo.getHabboInfo().getLook(), gameClient.getHabbo().getForbiddenClothing())) {

View File

@ -52,12 +52,6 @@ public class RedeemCommand extends Command {
pointsAmount = Integer.valueOf(item.getBaseItem().getName().split("_")[2]); pointsAmount = Integer.valueOf(item.getBaseItem().getName().split("_")[2]);
points.adjustOrPutValue(pointsType, pointsAmount, pointsAmount); points.adjustOrPutValue(pointsType, pointsAmount, pointsAmount);
} else if (item.getBaseItem().getName().startsWith("CF_diamond_")) {
try {
int amount = Integer.valueOf(item.getBaseItem().getName().split("_")[2]);
points.adjustOrPutValue(5, amount, amount);
} catch (Exception e) {
}
} }
} }
} }

View File

@ -7,10 +7,14 @@ import com.eu.habbo.habbohotel.catalog.CatalogPageLayouts;
import com.eu.habbo.habbohotel.catalog.layouts.RoomBundleLayout; import com.eu.habbo.habbohotel.catalog.layouts.RoomBundleLayout;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles; import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*; import java.sql.*;
public class RoomBundleCommand extends Command { public class RoomBundleCommand extends Command {
private static final Logger LOGGER = LoggerFactory.getLogger(RoomBundleCommand.class);
public RoomBundleCommand() { public RoomBundleCommand() {
super("cmd_bundle", Emulator.getTexts().getValue("commands.keys.cmd_bundle").split(";")); super("cmd_bundle", Emulator.getTexts().getValue("commands.keys.cmd_bundle").split(";"));
} }
@ -62,7 +66,7 @@ public class RoomBundleCommand extends Command {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
((RoomBundleLayout) page).loadItems(gameClient.getHabbo().getHabboInfo().getCurrentRoom()); ((RoomBundleLayout) page).loadItems(gameClient.getHabbo().getHabboInfo().getCurrentRoom());

View File

@ -0,0 +1,38 @@
package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.rooms.Room;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import com.eu.habbo.habbohotel.users.Habbo;
public class SoftKickCommand extends Command {
public SoftKickCommand() {
super("cmd_softkick", Emulator.getTexts().getValue("commands.keys.cmd_softkick").split(";"));
}
@Override
public boolean handle(GameClient gameClient, String[] params) throws Exception {
if (params.length == 2) {
final String username = params[1];
final Habbo habbo = gameClient.getHabbo().getHabboInfo().getCurrentRoom().getHabbo(username);
if (habbo == null) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.keys.cmd_softkick_error").replace("%user%", username), RoomChatMessageBubbles.ALERT);
return true;
}
if (habbo == gameClient.getHabbo()) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.keys.cmd_softkick_error_self"), RoomChatMessageBubbles.ALERT);
return true;
}
final Room room = gameClient.getHabbo().getHabboInfo().getCurrentRoom();
if (room != null) {
room.kickHabbo(habbo, false);
}
}
return true;
}
}

View File

@ -2,7 +2,7 @@ package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.permissions.Permission;
import com.eu.habbo.messages.ServerMessage; import com.eu.habbo.messages.ServerMessage;
public class TestCommand extends Command { public class TestCommand extends Command {
@ -12,7 +12,7 @@ public class TestCommand extends Command {
@Override @Override
public boolean handle(GameClient gameClient, String[] params) throws Exception { public boolean handle(GameClient gameClient, String[] params) throws Exception {
if (gameClient.getHabbo() != null || !gameClient.getHabbo().hasPermission("acc_supporttool") || !Emulator.debugging) if (gameClient.getHabbo() != null || !gameClient.getHabbo().hasPermission(Permission.ACC_SUPPORTTOOL) || !Emulator.debugging)
return false; return false;
int header = Integer.valueOf(params[1]); int header = Integer.valueOf(params[1]);

View File

@ -13,7 +13,7 @@ public class UpdateNavigatorCommand extends Command {
public boolean handle(GameClient gameClient, String[] params) throws Exception { public boolean handle(GameClient gameClient, String[] params) throws Exception {
Emulator.getGameEnvironment().getNavigatorManager().loadNavigator(); Emulator.getGameEnvironment().getNavigatorManager().loadNavigator();
Emulator.getGameEnvironment().getRoomManager().loadRoomModels(); Emulator.getGameEnvironment().getRoomManager().loadRoomModels();
Emulator.getGameEnvironment().getRoomManager().loadPublicRooms();
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_update_navigator"), RoomChatMessageBubbles.ALERT); gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_update_navigator"), RoomChatMessageBubbles.ALERT);
return true; return true;

View File

@ -3,6 +3,7 @@ package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.modtool.ModToolBan; import com.eu.habbo.habbohotel.modtool.ModToolBan;
import com.eu.habbo.habbohotel.permissions.Permission;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles; import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboInfo; import com.eu.habbo.habbohotel.users.HabboInfo;
@ -42,9 +43,9 @@ public class UserInfoCommand extends Command {
Emulator.getTexts().getValue("command.cmd_userinfo.motto") + ": " + habbo.getMotto().replace("<", "[").replace(">", "]") + "\r" + Emulator.getTexts().getValue("command.cmd_userinfo.motto") + ": " + habbo.getMotto().replace("<", "[").replace(">", "]") + "\r" +
Emulator.getTexts().getValue("command.cmd_userinfo.rank") + ": " + habbo.getRank().getName() + " (" + habbo.getRank().getId() + ") \r" + Emulator.getTexts().getValue("command.cmd_userinfo.rank") + ": " + habbo.getRank().getName() + " (" + habbo.getRank().getId() + ") \r" +
Emulator.getTexts().getValue("command.cmd_userinfo.online") + ": " + (onlineHabbo == null ? Emulator.getTexts().getValue("generic.no") : Emulator.getTexts().getValue("generic.yes")) + "\r" + Emulator.getTexts().getValue("command.cmd_userinfo.online") + ": " + (onlineHabbo == null ? Emulator.getTexts().getValue("generic.no") : Emulator.getTexts().getValue("generic.yes")) + "\r" +
Emulator.getTexts().getValue("command.cmd_userinfo.email") + ": " + habbo.getMail() + "\r" + ((habbo.getRank().hasPermission(Permission.ACC_HIDE_MAIL, true)) ? "" : Emulator.getTexts().getValue("command.cmd_userinfo.email") + ": " + habbo.getMail() + "\r") +
((habbo.getRank().hasPermission("acc_hide_ip", true)) ? "" : Emulator.getTexts().getValue("command.cmd_userinfo.ip_register") + ": " + habbo.getIpRegister() + "\r") + ((habbo.getRank().hasPermission(Permission.ACC_HIDE_IP, true)) ? "" : Emulator.getTexts().getValue("command.cmd_userinfo.ip_register") + ": " + habbo.getIpRegister() + "\r") +
((habbo.getRank().hasPermission("acc_hide_ip", true)) || onlineHabbo == null ? "" : Emulator.getTexts().getValue("command.cmd_userinfo.ip_current") + ": " + onlineHabbo.getClient().getChannel().remoteAddress().toString() + "\r") + ((habbo.getRank().hasPermission(Permission.ACC_HIDE_IP, true)) || onlineHabbo == null ? "" : Emulator.getTexts().getValue("command.cmd_userinfo.ip_current") + ": " + onlineHabbo.getClient().getChannel().remoteAddress().toString() + "\r") +
(onlineHabbo != null ? Emulator.getTexts().getValue("command.cmd_userinfo.achievement_score") + ": " + onlineHabbo.getHabboStats().achievementScore + "\r" : "")); (onlineHabbo != null ? Emulator.getTexts().getValue("command.cmd_userinfo.achievement_score") + ": " + onlineHabbo.getHabboStats().achievementScore + "\r" : ""));
ModToolBan ban = Emulator.getGameEnvironment().getModToolManager().checkForBan(habbo.getId()); ModToolBan ban = Emulator.getGameEnvironment().getModToolManager().checkForBan(habbo.getId());

View File

@ -4,6 +4,8 @@ import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.items.Item; import com.eu.habbo.habbohotel.items.Item;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.TObjectProcedure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -11,6 +13,7 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class CraftingManager { public class CraftingManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CraftingManager.class);
private final THashMap<Item, CraftingAltar> altars; private final THashMap<Item, CraftingAltar> altars;
@ -53,14 +56,14 @@ public class CraftingManager {
recipe.addIngredient(ingredientItem, set.getInt("crafting_recipes_ingredients.amount")); recipe.addIngredient(ingredientItem, set.getInt("crafting_recipes_ingredients.amount"));
altar.addIngredient(ingredientItem); altar.addIngredient(ingredientItem);
} else { } else {
Emulator.getLogging().logErrorLine("Unknown ingredient item " + set.getInt("crafting_recipes_ingredients.item_id")); LOGGER.error("Unknown ingredient item " + set.getInt("crafting_recipes_ingredients.item_id"));
} }
} }
} }
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -114,7 +117,7 @@ public class CraftingManager {
} }
statement.executeBatch(); statement.executeBatch();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
this.altars.clear(); this.altars.clear();

View File

@ -1,15 +1,14 @@
package com.eu.habbo.habbohotel.gameclients; package com.eu.habbo.habbohotel.gameclients;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.core.Logging; import com.eu.habbo.crypto.HabboEncryption;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.messages.PacketManager;
import com.eu.habbo.messages.ServerMessage; import com.eu.habbo.messages.ServerMessage;
import com.eu.habbo.messages.incoming.MessageHandler; import com.eu.habbo.messages.incoming.MessageHandler;
import com.eu.habbo.messages.outgoing.MessageComposer; import com.eu.habbo.messages.outgoing.MessageComposer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -18,66 +17,95 @@ import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
public class GameClient { public class GameClient {
public final ConcurrentHashMap<Integer, Integer> incomingPacketCounter = new ConcurrentHashMap<>(25);
private static final Logger LOGGER = LoggerFactory.getLogger(GameClient.class);
private final Channel channel; private final Channel channel;
public long lastPacketCounterCleared = Emulator.getIntUnixTimestamp(); private final HabboEncryption encryption;
private Habbo habbo; private Habbo habbo;
private boolean handshakeFinished;
private String machineId = ""; private String machineId = "";
public final ConcurrentHashMap<Integer, Integer> incomingPacketCounter = new ConcurrentHashMap<>(25);
public final ConcurrentHashMap<Class<? extends MessageHandler>, Long> messageTimestamps = new ConcurrentHashMap<>(); public final ConcurrentHashMap<Class<? extends MessageHandler>, Long> messageTimestamps = new ConcurrentHashMap<>();
public long lastPacketCounterCleared = Emulator.getIntUnixTimestamp();
public GameClient(Channel channel) { public GameClient(Channel channel) {
this.channel = channel; this.channel = channel;
this.encryption = Emulator.getCrypto().isEnabled()
? new HabboEncryption(
Emulator.getCrypto().getExponent(),
Emulator.getCrypto().getModulus(),
Emulator.getCrypto().getPrivateExponent())
: null;
} }
public Channel getChannel() {
return this.channel;
}
public HabboEncryption getEncryption() {
return encryption;
}
public Habbo getHabbo() {
return this.habbo;
}
public void setHabbo(Habbo habbo) {
this.habbo = habbo;
}
public boolean isHandshakeFinished() {
return handshakeFinished;
}
public void setHandshakeFinished(boolean handshakeFinished) {
this.handshakeFinished = handshakeFinished;
}
public String getMachineId() {
return this.machineId;
}
public void setMachineId(String machineId) {
if (machineId == null) {
throw new RuntimeException("Cannot set machineID to NULL");
}
this.machineId = machineId;
}
public void sendResponse(MessageComposer composer) { public void sendResponse(MessageComposer composer) {
if (this.channel.isOpen()) { this.sendResponse(composer.compose());
try {
ServerMessage msg = composer.compose();
this.sendResponse(msg);
} catch (Exception e) {
Emulator.getLogging().logPacketError(e);
}
}
} }
public void sendResponse(ServerMessage response) { public void sendResponse(ServerMessage response) {
if (this.channel.isOpen()) { if (this.channel.isOpen()) {
if (response == null || response.getHeader() <= 0) { if (response == null || response.getHeader() <= 0) {
return; return;
} }
if (PacketManager.DEBUG_SHOW_PACKETS) this.channel.write(response, this.channel.voidPromise());
Emulator.getLogging().logPacketLine("[" + Logging.ANSI_PURPLE + "SERVER" + Logging.ANSI_RESET + "] => [" + response.getHeader() + "] -> " + response.getBodyString());
this.channel.write(response.get(), this.channel.voidPromise());
this.channel.flush(); this.channel.flush();
} }
} }
public void sendResponses(ArrayList<ServerMessage> responses) { public void sendResponses(ArrayList<ServerMessage> responses) {
ByteBuf buffer = Unpooled.buffer();
if (this.channel.isOpen()) { if (this.channel.isOpen()) {
for (ServerMessage response : responses) { for (ServerMessage response : responses) {
if (response == null || response.getHeader() <= 0) { if (response == null || response.getHeader() <= 0) {
return; return;
} }
if (PacketManager.DEBUG_SHOW_PACKETS) this.channel.write(response);
Emulator.getLogging().logPacketLine("[" + Logging.ANSI_PURPLE + "SERVER" + Logging.ANSI_RESET + "] => [" + response.getHeader() + "] -> " + response.getBodyString());
buffer.writeBytes(response.get());
} }
this.channel.write(buffer.copy(), this.channel.voidPromise());
this.channel.flush(); this.channel.flush();
} }
buffer.release();
} }
public void dispose() { public void dispose() {
try { try {
this.channel.close(); this.channel.close();
@ -91,40 +119,7 @@ public class GameClient {
this.habbo = null; this.habbo = null;
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
}
}
public Channel getChannel() {
return this.channel;
}
public Habbo getHabbo() {
return this.habbo;
}
public void setHabbo(Habbo habbo) {
this.habbo = habbo;
}
public String getMachineId() {
return this.machineId;
}
public void setMachineId(String machineId) {
if (machineId == null) {
throw new RuntimeException("Cannot set machineID to NULL");
}
this.machineId = machineId;
if (this.habbo != null) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users SET machine_id = ? WHERE id = ? LIMIT 1")) {
statement.setString(1, this.machineId);
statement.setInt(2, this.habbo.getHabboInfo().getId());
statement.execute();
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
} }
} }
} }

View File

@ -3,8 +3,8 @@ package com.eu.habbo.habbohotel.gameclients;
import com.eu.habbo.habbohotel.users.Habbo; import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.messages.ServerMessage; import com.eu.habbo.messages.ServerMessage;
import com.eu.habbo.messages.outgoing.MessageComposer; import com.eu.habbo.messages.outgoing.MessageComposer;
import com.eu.habbo.networking.gameserver.GameServerAttributes;
import io.netty.channel.*; import io.netty.channel.*;
import io.netty.util.AttributeKey;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -12,7 +12,7 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
public class GameClientManager { public class GameClientManager {
public static final AttributeKey<GameClient> CLIENT = AttributeKey.valueOf("GameClient");
private final ConcurrentMap<ChannelId, GameClient> clients; private final ConcurrentMap<ChannelId, GameClient> clients;
public GameClientManager() { public GameClientManager() {
@ -34,7 +34,7 @@ public class GameClientManager {
} }
}); });
ctx.channel().attr(CLIENT).set(client); ctx.channel().attr(GameServerAttributes.CLIENT).set(client);
ctx.fireChannelRegistered(); ctx.fireChannelRegistered();
return this.clients.putIfAbsent(ctx.channel().id(), client) == null; return this.clients.putIfAbsent(ctx.channel().id(), client) == null;
@ -46,13 +46,13 @@ public class GameClientManager {
} }
private void disposeClient(Channel channel) { private void disposeClient(Channel channel) {
GameClient client = channel.attr(CLIENT).get(); GameClient client = channel.attr(GameServerAttributes.CLIENT).get();
if (client != null) { if (client != null) {
client.dispose(); client.dispose();
} }
channel.deregister(); channel.deregister();
channel.attr(CLIENT).set(null); channel.attr(GameServerAttributes.CLIENT).set(null);
channel.closeFuture(); channel.closeFuture();
channel.close(); channel.close();
this.clients.remove(channel.id()); this.clients.remove(channel.id());

View File

@ -20,12 +20,14 @@ import com.eu.habbo.plugin.events.games.GameStartedEvent;
import com.eu.habbo.plugin.events.games.GameStoppedEvent; import com.eu.habbo.plugin.events.games.GameStoppedEvent;
import com.eu.habbo.threading.runnables.SaveScoreForTeam; import com.eu.habbo.threading.runnables.SaveScoreForTeam;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
public abstract class Game implements Runnable { public abstract class Game implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Game.class);
protected final THashMap<GameTeamColors, GameTeam> teams = new THashMap<>(); protected final THashMap<GameTeamColors, GameTeam> teams = new THashMap<>();
protected final Room room; protected final Room room;
private final Class<? extends GameTeam> gameTeamClazz; private final Class<? extends GameTeam> gameTeamClazz;
@ -73,7 +75,7 @@ public abstract class Game implements Runnable {
return true; return true;
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
return false; return false;
@ -120,6 +122,10 @@ public abstract class Game implements Runnable {
for (HabboItem item : this.room.getRoomSpecialTypes().getItemsOfType(WiredBlob.class)) { for (HabboItem item : this.room.getRoomSpecialTypes().getItemsOfType(WiredBlob.class)) {
((WiredBlob) item).onGameStart(this.room); ((WiredBlob) item).onGameStart(this.room);
} }
for (GameTeam team : this.teams.values()) {
team.resetScores();
}
} }
public void onEnd() { public void onEnd() {
@ -135,9 +141,11 @@ public abstract class Game implements Runnable {
} }
GameTeam winningTeam = null; GameTeam winningTeam = null;
for (GameTeam team : this.teams.values()) { if(totalPointsGained > 0) {
if (winningTeam == null || team.getTotalScore() > winningTeam.getTotalScore()) { for (GameTeam team : this.teams.values()) {
winningTeam = team; if (winningTeam == null || team.getTotalScore() > winningTeam.getTotalScore()) {
winningTeam = team;
}
} }
} }
@ -164,7 +172,7 @@ public abstract class Game implements Runnable {
WiredHandler.handleCustomTrigger(WiredTriggerTeamLoses.class, player.getHabbo().getRoomUnit(), this.room, new Object[]{this}); WiredHandler.handleCustomTrigger(WiredTriggerTeamLoses.class, player.getHabbo().getRoomUnit(), this.room, new Object[]{this});
} }
if (team.getMembers().size() > 0) { if (team.getMembers().size() > 0 && team.getTotalScore() > 0) {
for (HabboItem item : this.room.getRoomSpecialTypes().getItemsOfType(InteractionWiredHighscore.class)) { for (HabboItem item : this.room.getRoomSpecialTypes().getItemsOfType(InteractionWiredHighscore.class)) {
Emulator.getGameEnvironment().getItemManager().getHighscoreManager().addHighscoreData(new WiredHighscoreDataEntry(item.getId(), team.getMembers().stream().map(m -> m.getHabbo().getHabboInfo().getId()).collect(Collectors.toList()), team.getTotalScore(), false, Emulator.getIntUnixTimestamp())); Emulator.getGameEnvironment().getItemManager().getHighscoreManager().addHighscoreData(new WiredHighscoreDataEntry(item.getId(), team.getMembers().stream().map(m -> m.getHabbo().getHabboInfo().getId()).collect(Collectors.toList()), team.getTotalScore(), false, Emulator.getIntUnixTimestamp()));
} }

View File

@ -86,6 +86,8 @@ public class GameTeam {
player.reset(); player.reset();
} }
this.teamScore = 0;
} }

View File

@ -17,12 +17,16 @@ import com.eu.habbo.messages.outgoing.rooms.users.RoomUserActionComposer;
import com.eu.habbo.threading.runnables.BattleBanzaiTilesFlicker; import com.eu.habbo.threading.runnables.BattleBanzaiTilesFlicker;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*; import java.util.*;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
public class BattleBanzaiGame extends Game { public class BattleBanzaiGame extends Game {
private static final Logger LOGGER = LoggerFactory.getLogger(BattleBanzaiGame.class);
public static final int effectId = 32; public static final int effectId = 32;
@ -40,6 +44,7 @@ public class BattleBanzaiGame extends Game {
private final THashMap<Integer, HabboItem> gameTiles; private final THashMap<Integer, HabboItem> gameTiles;
private int tileCount; private int tileCount;
private int countDown; private int countDown;
private int countDown2;
public BattleBanzaiGame(Room room) { public BattleBanzaiGame(Room room) {
super(BattleBanzaiGameTeam.class, BattleBanzaiGamePlayer.class, room, true); super(BattleBanzaiGameTeam.class, BattleBanzaiGamePlayer.class, room, true);
@ -54,8 +59,12 @@ public class BattleBanzaiGame extends Game {
public void initialise() { public void initialise() {
if (!this.state.equals(GameState.IDLE)) if (!this.state.equals(GameState.IDLE))
return; return;
/* The first countdown is activated for the first two seconds emitting only the blue light (second interaction),
the second, after another two seconds, completely activates the sphere (third interaction).
*/
this.countDown = 3; this.countDown = 3;
this.countDown2 = 2;
this.resetMap(); this.resetMap();
@ -101,8 +110,15 @@ public class BattleBanzaiGame extends Game {
if (this.countDown == 0) { if (this.countDown == 0) {
for (HabboItem item : this.room.getRoomSpecialTypes().getItemsOfType(InteractionBattleBanzaiSphere.class)) { for (HabboItem item : this.room.getRoomSpecialTypes().getItemsOfType(InteractionBattleBanzaiSphere.class)) {
item.setExtradata("2"); item.setExtradata("1");
this.room.updateItemState(item); this.room.updateItemState(item);
if(this.countDown2 > 0) {
this.countDown2--;
if(this.countDown2 == 0) {
item.setExtradata("2");
this.room.updateItemState(item);
}
}
} }
} }
@ -149,7 +165,7 @@ public class BattleBanzaiGame extends Game {
} }
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }

View File

@ -23,11 +23,15 @@ import com.eu.habbo.threading.runnables.freeze.FreezeThrowSnowball;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import gnu.trove.procedure.TObjectProcedure; import gnu.trove.procedure.TObjectProcedure;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class FreezeGame extends Game { public class FreezeGame extends Game {
private static final Logger LOGGER = LoggerFactory.getLogger(FreezeGame.class);
public static final int effectId = 39; public static final int effectId = 39;
public static int POWER_UP_POINTS; public static int POWER_UP_POINTS;
@ -261,7 +265,7 @@ public class FreezeGame extends Game {
} }
} }
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }

View File

@ -1,6 +1,8 @@
package com.eu.habbo.habbohotel.guilds; package com.eu.habbo.habbohotel.guilds;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -8,6 +10,7 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class Guild implements Runnable { public class Guild implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(Guild.class);
public boolean needsUpdate; public boolean needsUpdate;
public int lastRequested = Emulator.getIntUnixTimestamp(); public int lastRequested = Emulator.getIntUnixTimestamp();
private int id; private int id;
@ -91,7 +94,7 @@ public class Guild implements Runnable {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -116,7 +119,7 @@ public class Guild implements Runnable {
this.needsUpdate = false; this.needsUpdate = false;
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -13,6 +13,8 @@ import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
@ -20,6 +22,8 @@ import java.util.stream.Collectors;
public class GuildManager { public class GuildManager {
private static final Logger LOGGER = LoggerFactory.getLogger(GuildManager.class);
private final THashMap<GuildPartType, THashMap<Integer, GuildPart>> guildParts; private final THashMap<GuildPartType, THashMap<Integer, GuildPart>> guildParts;
private final TIntObjectMap<Guild> guilds; private final TIntObjectMap<Guild> guilds;
@ -34,7 +38,7 @@ public class GuildManager {
this.loadGuildParts(); this.loadGuildParts();
this.loadGuildViews(); this.loadGuildViews();
Emulator.getLogging().logStart("Guild Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("Guild Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} }
@ -52,7 +56,7 @@ public class GuildManager {
this.guildParts.get(GuildPartType.valueOf(set.getString("type").toUpperCase())).put(set.getInt("id"), new GuildPart(set)); this.guildParts.get(GuildPartType.valueOf(set.getString("type").toUpperCase())).put(set.getInt("id"), new GuildPart(set));
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -66,7 +70,7 @@ public class GuildManager {
this.views.add(new ForumView(set)); this.views.add(new ForumView(set));
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -107,7 +111,7 @@ public class GuildManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
habbo.getHabboStats().addGuild(guild.getId()); habbo.getHabboStats().addGuild(guild.getId());
@ -155,7 +159,7 @@ public class GuildManager {
room.setGuild(0); room.setGuild(0);
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -276,7 +280,7 @@ public class GuildManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -288,7 +292,7 @@ public class GuildManager {
statement.setInt(3, guild.getId()); statement.setInt(3, guild.getId());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -303,7 +307,7 @@ public class GuildManager {
statement.setInt(3, guild.getId()); statement.setInt(3, guild.getId());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -325,7 +329,7 @@ public class GuildManager {
statement.setInt(2, guild.getId()); statement.setInt(2, guild.getId());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -352,7 +356,7 @@ public class GuildManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return member; return member;
@ -375,7 +379,7 @@ public class GuildManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return guildMembers; return guildMembers;
@ -397,7 +401,7 @@ public class GuildManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return guildMembers; return guildMembers;
@ -416,7 +420,7 @@ public class GuildManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return 0; return 0;
@ -434,7 +438,7 @@ public class GuildManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return guildAdmins; return guildAdmins;
@ -466,7 +470,7 @@ public class GuildManager {
if (g != null) if (g != null)
g.loadMemberCount(); g.loadMemberCount();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -494,7 +498,7 @@ public class GuildManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return guilds; return guilds;
@ -514,7 +518,7 @@ public class GuildManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return guilds; return guilds;
@ -593,7 +597,7 @@ public class GuildManager {
statement.setInt(2, furni.getId()); statement.setInt(2, furni.getId());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -608,7 +612,7 @@ public class GuildManager {
guildIterator.remove(); guildIterator.remove();
} }
Emulator.getLogging().logShutdownLine("Guild Manager -> Disposed!"); LOGGER.info("Guild Manager -> Disposed!");
} }
public boolean hasViewedForum(int userId, int guildId) { public boolean hasViewedForum(int userId, int guildId) {
@ -628,7 +632,7 @@ public class GuildManager {
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }

View File

@ -9,11 +9,15 @@ import com.eu.habbo.plugin.events.guilds.forums.GuildForumThreadBeforeCreated;
import com.eu.habbo.plugin.events.guilds.forums.GuildForumThreadCreated; import com.eu.habbo.plugin.events.guilds.forums.GuildForumThreadCreated;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
public class ForumThread implements Runnable, ISerialize { public class ForumThread implements Runnable, ISerialize {
private static final Logger LOGGER = LoggerFactory.getLogger(ForumThread.class);
private final static THashMap<Integer, THashSet<ForumThread>> guildThreadsCache = new THashMap<>(); private final static THashMap<Integer, THashSet<ForumThread>> guildThreadsCache = new THashMap<>();
private final static THashMap<Integer, ForumThread> forumThreadsCache = new THashMap<>(); private final static THashMap<Integer, ForumThread> forumThreadsCache = new THashMap<>();
@ -69,7 +73,8 @@ public class ForumThread implements Runnable, ISerialize {
try { try {
this.lastComment = ForumThreadComment.getById(set.getInt("last_comment_id")); this.lastComment = ForumThreadComment.getById(set.getInt("last_comment_id"));
} catch (Exception e) { } catch (SQLException e) {
LOGGER.error("ForumThread last_comment_id exception", e);
} }
this.comments = new THashMap<>(); this.comments = new THashMap<>();
@ -108,7 +113,7 @@ public class ForumThread implements Runnable, ISerialize {
Emulator.getPluginManager().fireEvent(new GuildForumThreadCreated(createdThread)); Emulator.getPluginManager().fireEvent(new GuildForumThreadCreated(createdThread));
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return createdThread; return createdThread;
@ -156,7 +161,7 @@ public class ForumThread implements Runnable, ISerialize {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return threads; return threads;
@ -195,7 +200,7 @@ public class ForumThread implements Runnable, ISerialize {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return foundThread; return foundThread;
@ -337,7 +342,7 @@ public class ForumThread implements Runnable, ISerialize {
addComment(comment); addComment(comment);
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }
@ -461,7 +466,7 @@ public class ForumThread implements Runnable, ISerialize {
this.needsUpdate = false; this.needsUpdate = false;
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -8,10 +8,13 @@ import com.eu.habbo.messages.ServerMessage;
import com.eu.habbo.plugin.events.guilds.forums.GuildForumThreadCommentBeforeCreated; import com.eu.habbo.plugin.events.guilds.forums.GuildForumThreadCommentBeforeCreated;
import com.eu.habbo.plugin.events.guilds.forums.GuildForumThreadCommentCreated; import com.eu.habbo.plugin.events.guilds.forums.GuildForumThreadCommentCreated;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*; import java.sql.*;
public class ForumThreadComment implements Runnable, ISerialize { public class ForumThreadComment implements Runnable, ISerialize {
private static final Logger LOGGER = LoggerFactory.getLogger(ForumThreadComment.class);
private static THashMap<Integer, ForumThreadComment> forumCommentsCache = new THashMap<>(); private static THashMap<Integer, ForumThreadComment> forumCommentsCache = new THashMap<>();
private final int commentId; private final int commentId;
@ -64,7 +67,7 @@ public class ForumThreadComment implements Runnable, ISerialize {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return foundComment; return foundComment;
@ -103,7 +106,7 @@ public class ForumThreadComment implements Runnable, ISerialize {
Emulator.getPluginManager().fireEvent(new GuildForumThreadCommentCreated(createdComment)); Emulator.getPluginManager().fireEvent(new GuildForumThreadCommentCreated(createdComment));
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return createdComment; return createdComment;
@ -200,7 +203,7 @@ public class ForumThreadComment implements Runnable, ISerialize {
this.needsUpdate = false; this.needsUpdate = false;
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -2,6 +2,8 @@ package com.eu.habbo.habbohotel.hotelview;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -9,6 +11,7 @@ import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
public class HallOfFame { public class HallOfFame {
private static final Logger LOGGER = LoggerFactory.getLogger(HallOfFame.class);
private final THashMap<Integer, HallOfFameWinner> winners = new THashMap<>(); private final THashMap<Integer, HallOfFameWinner> winners = new THashMap<>();
@ -32,7 +35,7 @@ public class HallOfFame {
this.winners.put(winner.getId(), winner); this.winners.put(winner.getId(), winner);
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -1,8 +1,12 @@
package com.eu.habbo.habbohotel.hotelview; package com.eu.habbo.habbohotel.hotelview;
import com.eu.habbo.Emulator; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HotelViewManager { public class HotelViewManager {
private static final Logger LOGGER = LoggerFactory.getLogger(HotelViewManager.class);
private final HallOfFame hallOfFame; private final HallOfFame hallOfFame;
private final NewsList newsList; private final NewsList newsList;
@ -11,7 +15,7 @@ public class HotelViewManager {
this.hallOfFame = new HallOfFame(); this.hallOfFame = new HallOfFame();
this.newsList = new NewsList(); this.newsList = new NewsList();
Emulator.getLogging().logStart("Hotelview Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("Hotelview Manager -> Loaded! ({} MS)", System.currentTimeMillis() - millis);
} }
public HallOfFame getHallOfFame() { public HallOfFame getHallOfFame() {
@ -23,6 +27,7 @@ public class HotelViewManager {
} }
public void dispose() { public void dispose() {
Emulator.getLogging().logShutdownLine("HotelView Manager -> Disposed!"); LOGGER.info("HotelView Manager -> Disposed!");
} }
} }

View File

@ -1,6 +1,8 @@
package com.eu.habbo.habbohotel.hotelview; package com.eu.habbo.habbohotel.hotelview;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection; import java.sql.Connection;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -9,6 +11,8 @@ import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
public class NewsList { public class NewsList {
private static final Logger LOGGER = LoggerFactory.getLogger(NewsList.class);
private final ArrayList<NewsWidget> newsWidgets; private final ArrayList<NewsWidget> newsWidgets;
public NewsList() { public NewsList() {
@ -25,7 +29,7 @@ public class NewsList {
this.newsWidgets.add(new NewsWidget(set)); this.newsWidgets.add(new NewsWidget(set));
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
} }

View File

@ -1,6 +1,8 @@
package com.eu.habbo.habbohotel.items; package com.eu.habbo.habbohotel.items;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
@ -9,6 +11,8 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class CrackableReward { public class CrackableReward {
private static final Logger LOGGER = LoggerFactory.getLogger(CrackableReward.class);
public final int itemId; public final int itemId;
public final int count; public final int count;
public final Map<Integer, Map.Entry<Integer, Integer>> prizes; public final Map<Integer, Map.Entry<Integer, Integer>> prizes;
@ -44,7 +48,7 @@ public class CrackableReward {
itemId = Integer.valueOf(prize.split(":")[0]); itemId = Integer.valueOf(prize.split(":")[0]);
chance = Integer.valueOf(prize.split(":")[1]); chance = Integer.valueOf(prize.split(":")[1]);
} else if (prize.contains(":")) { } else if (prize.contains(":")) {
Emulator.getLogging().logErrorLine("Invalid configuration of crackable prizes (item id: " + this.itemId + "). '" + prize + "' format should be itemId:chance."); LOGGER.error("Invalid configuration of crackable prizes (item id: " + this.itemId + "). '" + prize + "' format should be itemId:chance.");
} else { } else {
itemId = Integer.valueOf(prize.replace(":", "")); itemId = Integer.valueOf(prize.replace(":", ""));
} }
@ -52,7 +56,7 @@ public class CrackableReward {
this.prizes.put(itemId, new AbstractMap.SimpleEntry<>(this.totalChance, this.totalChance + chance)); this.prizes.put(itemId, new AbstractMap.SimpleEntry<>(this.totalChance, this.totalChance + chance));
this.totalChance += chance; this.totalChance += chance;
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
} }

View File

@ -54,7 +54,7 @@ public class Item {
try { try {
int index = Integer.valueOf(item.getExtradata()) % (item.getBaseItem().getMultiHeights().length); int index = Integer.valueOf(item.getExtradata()) % (item.getBaseItem().getMultiHeights().length);
return item.getBaseItem().getMultiHeights()[(item.getExtradata().isEmpty() ? 0 : index)]; return item.getBaseItem().getMultiHeights()[(item.getExtradata().isEmpty() ? 0 : index)];
} catch (Exception e) { } catch (NumberFormatException e) {
} }
} }

View File

@ -60,12 +60,17 @@ import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import gnu.trove.map.hash.TIntObjectHashMap; import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.sql.*; import java.sql.*;
import java.util.*; import java.util.*;
public class ItemManager { public class ItemManager {
private static final Logger LOGGER = LoggerFactory.getLogger(ItemManager.class);
//Configuration. Loaded from database & updated accordingly. //Configuration. Loaded from database & updated accordingly.
public static boolean RECYCLER_ENABLED = true; public static boolean RECYCLER_ENABLED = true;
@ -100,7 +105,7 @@ public class ItemManager {
this.highscoreManager.load(); this.highscoreManager.load();
this.loadNewUserGifts(); this.loadNewUserGifts();
Emulator.getLogging().logStart("Item Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("Item Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
} }
protected void loadItemInteractions() { protected void loadItemInteractions() {
@ -197,12 +202,7 @@ public class ItemManager {
this.interactionsList.add(new ItemInteraction("wf_trg_game_ends", WiredTriggerGameEnds.class)); this.interactionsList.add(new ItemInteraction("wf_trg_game_ends", WiredTriggerGameEnds.class));
this.interactionsList.add(new ItemInteraction("wf_trg_bot_reached_stf", WiredTriggerBotReachedFurni.class)); this.interactionsList.add(new ItemInteraction("wf_trg_bot_reached_stf", WiredTriggerBotReachedFurni.class));
this.interactionsList.add(new ItemInteraction("wf_trg_bot_reached_avtr", WiredTriggerBotReachedHabbo.class)); this.interactionsList.add(new ItemInteraction("wf_trg_bot_reached_avtr", WiredTriggerBotReachedHabbo.class));
this.interactionsList.add(new ItemInteraction("wf_trg_says_command", WiredTriggerHabboSaysCommand.class));
this.interactionsList.add(new ItemInteraction("wf_trg_score_achieved", WiredTriggerScoreAchieved.class)); this.interactionsList.add(new ItemInteraction("wf_trg_score_achieved", WiredTriggerScoreAchieved.class));
this.interactionsList.add(new ItemInteraction("wf_trg_idles", WiredTriggerHabboIdle.class));
this.interactionsList.add(new ItemInteraction("wf_trg_unidles", WiredTriggerHabboUnidle.class));
this.interactionsList.add(new ItemInteraction("wf_trg_starts_dancing", WiredTriggerHabboStartsDancing.class));
this.interactionsList.add(new ItemInteraction("wf_trg_stops_dancing", WiredTriggerHabboStopsDancing.class));
this.interactionsList.add(new ItemInteraction("wf_trg_game_team_win", WiredTriggerTeamWins.class)); this.interactionsList.add(new ItemInteraction("wf_trg_game_team_win", WiredTriggerTeamWins.class));
this.interactionsList.add(new ItemInteraction("wf_trg_game_team_lose", WiredTriggerTeamLoses.class)); this.interactionsList.add(new ItemInteraction("wf_trg_game_team_lose", WiredTriggerTeamLoses.class));
@ -233,22 +233,10 @@ public class ItemManager {
this.interactionsList.add(new ItemInteraction("wf_act_bot_follow_avatar", WiredEffectBotFollowHabbo.class)); this.interactionsList.add(new ItemInteraction("wf_act_bot_follow_avatar", WiredEffectBotFollowHabbo.class));
this.interactionsList.add(new ItemInteraction("wf_act_bot_clothes", WiredEffectBotClothes.class)); this.interactionsList.add(new ItemInteraction("wf_act_bot_clothes", WiredEffectBotClothes.class));
this.interactionsList.add(new ItemInteraction("wf_act_bot_talk_to_avatar", WiredEffectBotTalkToHabbo.class)); this.interactionsList.add(new ItemInteraction("wf_act_bot_talk_to_avatar", WiredEffectBotTalkToHabbo.class));
this.interactionsList.add(new ItemInteraction("wf_act_give_diamonds", WiredEffectGiveDiamonds.class));
this.interactionsList.add(new ItemInteraction("wf_act_give_credits", WiredEffectGiveCredits.class));
this.interactionsList.add(new ItemInteraction("wf_act_give_duckets", WiredEffectGiveDuckets.class));
this.interactionsList.add(new ItemInteraction("wf_act_give_badge", WiredEffectGiveBadge.class));
this.interactionsList.add(new ItemInteraction("wf_act_forward_user", WiredEffectForwardToRoom.class));
this.interactionsList.add(new ItemInteraction("wf_act_roller_speed", WiredEffectRollerSpeed.class));
this.interactionsList.add(new ItemInteraction("wf_act_raise_furni", WiredEffectRaiseFurni.class));
this.interactionsList.add(new ItemInteraction("wf_act_lower_furni", WiredEffectLowerFurni.class));
this.interactionsList.add(new ItemInteraction("wf_act_give_respect", WiredEffectGiveRespect.class)); this.interactionsList.add(new ItemInteraction("wf_act_give_respect", WiredEffectGiveRespect.class));
this.interactionsList.add(new ItemInteraction("wf_act_alert", WiredEffectAlert.class)); this.interactionsList.add(new ItemInteraction("wf_act_alert", WiredEffectAlert.class));
this.interactionsList.add(new ItemInteraction("wf_act_give_handitem", WiredEffectGiveHandItem.class)); this.interactionsList.add(new ItemInteraction("wf_act_give_handitem", WiredEffectGiveHandItem.class));
this.interactionsList.add(new ItemInteraction("wf_act_match_to_sshot2", WiredEffectMatchFurniStaff.class));
this.interactionsList.add(new ItemInteraction("wf_act_give_effect", WiredEffectGiveEffect.class)); this.interactionsList.add(new ItemInteraction("wf_act_give_effect", WiredEffectGiveEffect.class));
this.interactionsList.add(new ItemInteraction("wf_act_open_habbo_pages", WiredEffectOpenHabboPages.class));
this.interactionsList.add(new ItemInteraction("wf_act_give_achievement", WiredEffectGiveAchievement.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_has_furni_on", WiredConditionFurniHaveFurni.class)); this.interactionsList.add(new ItemInteraction("wf_cnd_has_furni_on", WiredConditionFurniHaveFurni.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_furnis_hv_avtrs", WiredConditionFurniHaveHabbo.class)); this.interactionsList.add(new ItemInteraction("wf_cnd_furnis_hv_avtrs", WiredConditionFurniHaveHabbo.class));
@ -274,23 +262,6 @@ public class ItemManager {
this.interactionsList.add(new ItemInteraction("wf_cnd_trggrer_on_frn", WiredConditionTriggerOnFurni.class)); this.interactionsList.add(new ItemInteraction("wf_cnd_trggrer_on_frn", WiredConditionTriggerOnFurni.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_has_handitem", WiredConditionHabboHasHandItem.class)); this.interactionsList.add(new ItemInteraction("wf_cnd_has_handitem", WiredConditionHabboHasHandItem.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_date_rng_active", WiredConditionDateRangeActive.class)); this.interactionsList.add(new ItemInteraction("wf_cnd_date_rng_active", WiredConditionDateRangeActive.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_motto_contains", WiredConditionMottoContains.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_battlebanzai", WiredConditionBattleBanzaiGameActive.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_not_battlebanzai", WiredConditionNotBattleBanzaiGameActive.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_freeze", WiredConditionFreezeGameActive.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_not_freeze", WiredConditionNotFreezeGameActive.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_habbo_has_rank", WiredConditionHabboHasRank.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_habbo_not_rank", WiredConditionHabboNotRank.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_habbo_has_diamonds", WiredConditionHabboHasDiamonds.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_habbo_has_credits", WiredConditionHabboHasCredits.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_habbo_has_duckets", WiredConditionHabboHasDuckets.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_not_habbo_has_diamonds", WiredConditionNotHabboHasDiamonds.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_not_habbo_has_credits", WiredConditionNotHabboHasCredits.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_not_habbo_has_duckets", WiredConditionNotHabboHasDuckets.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_habbo_owns_badge", WiredConditionHabboOwnsBadge.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_not_habbo_owns_badge", WiredConditionNotHabboOwnsBadge.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_habbo_is_dancing", WiredConditionHabboIsDancing.class));
this.interactionsList.add(new ItemInteraction("wf_cnd_not_habbo_is_dancing", WiredConditionNotHabboIsDancing.class));
this.interactionsList.add(new ItemInteraction("wf_xtra_random", WiredExtraRandom.class)); this.interactionsList.add(new ItemInteraction("wf_xtra_random", WiredExtraRandom.class));
@ -388,7 +359,7 @@ public class ItemManager {
return interaction; return interaction;
} }
Emulator.getLogging().logDebugLine("Can't find interaction class:" + type.getName()); LOGGER.debug("Can't find interaction class: {}", type.getName());
return this.getItemInteraction(InteractionDefault.class); return this.getItemInteraction(InteractionDefault.class);
} }
@ -418,12 +389,12 @@ public class ItemManager {
else else
this.items.get(id).update(set); this.items.get(id).update(set);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine("Failed to load Item (" + set.getInt("id") + ")"); LOGGER.error("Failed to load Item ({})", set.getInt("id"));
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -436,16 +407,16 @@ public class ItemManager {
try { try {
reward = new CrackableReward(set); reward = new CrackableReward(set);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine("Failed to load items_crackable item_id = " + set.getInt("item_id")); LOGGER.error("Failed to load items_crackable item_id = {}", set.getInt("item_id"));
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
continue; continue;
} }
this.crackableRewards.put(set.getInt("item_id"), reward); this.crackableRewards.put(set.getInt("item_id"), reward);
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
@ -479,7 +450,7 @@ public class ItemManager {
this.soundTracks.put(set.getString("code"), new SoundTrack(set)); this.soundTracks.put(set.getString("code"), new SoundTrack(set));
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -512,16 +483,16 @@ public class ItemManager {
try { try {
return itemClass.getDeclaredConstructor(int.class, int.class, Item.class, String.class, int.class, int.class).newInstance(set.getInt(1), habboId, item, extraData, limitedStack, limitedSells); return itemClass.getDeclaredConstructor(int.class, int.class, Item.class, String.class, int.class, int.class).newInstance(set.getInt(1), habboId, item, extraData, limitedStack, limitedSells);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
return new InteractionDefault(set.getInt(1), habboId, item, extraData, limitedStack, limitedSells); return new InteractionDefault(set.getInt(1), habboId, item, extraData, limitedStack, limitedSells);
} }
} }
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
return null; return null;
} }
@ -536,7 +507,7 @@ public class ItemManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -561,7 +532,7 @@ public class ItemManager {
statement.setInt(1, item.getId()); statement.setInt(1, item.getId());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -588,7 +559,7 @@ public class ItemManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return item; return item;
@ -628,9 +599,9 @@ public class ItemManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
return item; return item;
@ -642,7 +613,7 @@ public class ItemManager {
statement.setInt(2, itemTwoId); statement.setInt(2, itemTwoId);
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -652,7 +623,7 @@ public class ItemManager {
statement.setInt(2, hopper.getBaseItem().getId()); statement.setInt(2, hopper.getBaseItem().getId());
statement.execute(); statement.execute();
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -667,7 +638,7 @@ public class ItemManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
return a; return a;
@ -683,9 +654,9 @@ public class ItemManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
return item; return item;
@ -706,7 +677,7 @@ public class ItemManager {
return (HabboItem) c.newInstance(set, baseItem); return (HabboItem) c.newInstance(set, baseItem);
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
} }
@ -729,7 +700,7 @@ public class ItemManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
} }
@ -737,7 +708,7 @@ public class ItemManager {
return null; return null;
if (extraData.length() > 1000) { if (extraData.length() > 1000) {
Emulator.getLogging().logErrorLine("Extradata exceeds maximum length of 1000 characters:" + extraData); LOGGER.error("Extradata exceeds maximum length of 1000 characters: {}", extraData);
extraData = extraData.substring(0, 1000); extraData = extraData.substring(0, 1000);
} }
@ -754,7 +725,7 @@ public class ItemManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
if (gift != null) { if (gift != null) {
@ -808,7 +779,7 @@ public class ItemManager {
this.items.clear(); this.items.clear();
this.highscoreManager.dispose(); this.highscoreManager.dispose();
Emulator.getLogging().logShutdownLine("Item Manager -> Disposed!"); LOGGER.info("Item Manager -> Disposed!");
} }
public List<String> getInteractionList() { public List<String> getInteractionList() {

View File

@ -1,10 +1,13 @@
package com.eu.habbo.habbohotel.items; package com.eu.habbo.habbohotel.items;
import com.eu.habbo.Emulator; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays; import java.util.Arrays;
public class RandomStateParams { public class RandomStateParams {
private static final Logger LOGGER = LoggerFactory.getLogger(RandomStateParams.class);
private int states = -1; private int states = -1;
private int delay = -1; private int delay = -1;
@ -22,7 +25,7 @@ public class RandomStateParams {
this.delay = Integer.parseInt(keyValue[1]); this.delay = Integer.parseInt(keyValue[1]);
break; break;
default: default:
Emulator.getLogging().logDebugLine("RandomStateParams: unknown key: " + keyValue[0]); LOGGER.warn("RandomStateParams: unknown key: " + keyValue[0]);
break; break;
} }
}); });

View File

@ -6,12 +6,13 @@ import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
import gnu.trove.map.hash.THashMap; import gnu.trove.map.hash.THashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.sql.*; import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
@ -20,6 +21,8 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
public class YoutubeManager { public class YoutubeManager {
private static final Logger LOGGER = LoggerFactory.getLogger(YoutubeManager.class);
public class YoutubeVideo { public class YoutubeVideo {
private final String id; private final String id;
private final int duration; private final int duration;
@ -80,7 +83,7 @@ public class YoutubeManager {
Emulator.getThreading().run(() -> { Emulator.getThreading().run(() -> {
ExecutorService youtubeDataLoaderPool = Executors.newFixedThreadPool(10); ExecutorService youtubeDataLoaderPool = Executors.newFixedThreadPool(10);
Emulator.getLogging().logStart("YouTube Manager -> Loading..."); LOGGER.info("YouTube Manager -> Loading...");
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT * FROM youtube_playlists")) { try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT * FROM youtube_playlists")) {
try (ResultSet set = statement.executeQuery()) { try (ResultSet set = statement.executeQuery()) {
@ -95,7 +98,7 @@ public class YoutubeManager {
if (playlist != null) { if (playlist != null) {
playlists.add(playlist); playlists.add(playlist);
} else { } else {
Emulator.getLogging().logErrorLine("Failed to load YouTube playlist: " + playlistId); LOGGER.error("Failed to load YouTube playlist: " + playlistId);
} }
this.playlists.put(itemId, playlists); this.playlists.put(itemId, playlists);
@ -103,7 +106,7 @@ public class YoutubeManager {
} }
} }
} catch (SQLException e) { } catch (SQLException e) {
Emulator.getLogging().logSQLException(e); LOGGER.error("Caught SQL exception", e);
} }
youtubeDataLoaderPool.shutdown(); youtubeDataLoaderPool.shutdown();
@ -113,7 +116,7 @@ public class YoutubeManager {
e.printStackTrace(); e.printStackTrace();
} }
Emulator.getLogging().logStart("YouTube Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)"); LOGGER.info("YouTube Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
}); });
} }
@ -130,37 +133,35 @@ public class YoutubeManager {
InputStream is = conn.getInputStream(); InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is); InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr); YoutubePlaylist playlist;
try (BufferedReader br = new BufferedReader(isr)) {
YoutubePlaylist playlist = null; playlist = null;
String inputLine;
String inputLine; while ((inputLine = br.readLine()) != null) {
while ((inputLine = br.readLine()) != null) { if (inputLine.contains("window[\"ytInitialData\"]")) {
if (inputLine.contains("window[\"ytInitialData\"]")) { JsonObject obj = new JsonParser().parse(inputLine.substring(inputLine.indexOf("{")).replace(";", "")).getAsJsonObject();
JsonObject obj = new JsonParser().parse(inputLine.substring(inputLine.indexOf("{")).replace(";", "")).getAsJsonObject();
JsonObject meta = obj.get("microformat").getAsJsonObject().get("microformatDataRenderer").getAsJsonObject();
JsonObject meta = obj.get("microformat").getAsJsonObject().get("microformatDataRenderer").getAsJsonObject(); String name = meta.get("title").getAsString();
String name = meta.get("title").getAsString(); String description = meta.get("description").getAsString();
String description = meta.get("description").getAsString();
ArrayList<YoutubeVideo> videos = new ArrayList<>();
ArrayList<YoutubeVideo> videos = new ArrayList<>();
JsonArray rawVideos = obj.get("contents").getAsJsonObject().get("twoColumnBrowseResultsRenderer").getAsJsonObject().get("tabs").getAsJsonArray().get(0).getAsJsonObject().get("tabRenderer").getAsJsonObject().get("content").getAsJsonObject().get("sectionListRenderer").getAsJsonObject().get("contents").getAsJsonArray().get(0).getAsJsonObject().get("itemSectionRenderer").getAsJsonObject().get("contents").getAsJsonArray().get(0).getAsJsonObject().get("playlistVideoListRenderer").getAsJsonObject().get("contents").getAsJsonArray();
JsonArray rawVideos = obj.get("contents").getAsJsonObject().get("twoColumnBrowseResultsRenderer").getAsJsonObject().get("tabs").getAsJsonArray().get(0).getAsJsonObject().get("tabRenderer").getAsJsonObject().get("content").getAsJsonObject().get("sectionListRenderer").getAsJsonObject().get("contents").getAsJsonArray().get(0).getAsJsonObject().get("itemSectionRenderer").getAsJsonObject().get("contents").getAsJsonArray().get(0).getAsJsonObject().get("playlistVideoListRenderer").getAsJsonObject().get("contents").getAsJsonArray();
for (JsonElement rawVideo : rawVideos) {
for (JsonElement rawVideo : rawVideos) { JsonObject videoData = rawVideo.getAsJsonObject().get("playlistVideoRenderer").getAsJsonObject();
JsonObject videoData = rawVideo.getAsJsonObject().get("playlistVideoRenderer").getAsJsonObject(); if (!videoData.has("lengthSeconds")) continue; // removed videos
if (!videoData.has("lengthSeconds")) continue; // removed videos videos.add(new YoutubeVideo(videoData.get("videoId").getAsString(), Integer.valueOf(videoData.get("lengthSeconds").getAsString())));
videos.add(new YoutubeVideo(videoData.get("videoId").getAsString(), Integer.valueOf(videoData.get("lengthSeconds").getAsString()))); }
playlist = new YoutubePlaylist(playlistId, name, description, videos);
break;
} }
playlist = new YoutubePlaylist(playlistId, name, description, videos);
break;
} }
} }
br.close();
this.playlistCache.put(playlistId, playlist); this.playlistCache.put(playlistId, playlist);
return playlist; return playlist;

View File

@ -3,6 +3,7 @@ package com.eu.habbo.habbohotel.items.interactions;
import com.eu.habbo.Emulator; import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.items.Item; import com.eu.habbo.habbohotel.items.Item;
import com.eu.habbo.habbohotel.modtool.ScripterManager;
import com.eu.habbo.habbohotel.rooms.Room; import com.eu.habbo.habbohotel.rooms.Room;
import com.eu.habbo.habbohotel.rooms.RoomUnit; import com.eu.habbo.habbohotel.rooms.RoomUnit;
import com.eu.habbo.habbohotel.users.HabboItem; import com.eu.habbo.habbohotel.users.HabboItem;
@ -58,9 +59,22 @@ public class InteractionBackgroundToner extends HabboItem {
public void onClick(GameClient client, Room room, Object[] objects) throws Exception { public void onClick(GameClient client, Room room, Object[] objects) throws Exception {
super.onClick(client, room, objects); super.onClick(client, room, objects);
if (client.getHabbo().getRoomUnit().cmdSit && client.getHabbo().getRoomUnit().getEffectId() == 1337) { if(client != null)
Emulator.getThreading().run(new BackgroundAnimation(this, room)); {
return; if (!client.getHabbo().getRoomUnit().getRoom().hasRights(client.getHabbo())) {
ScripterManager.scripterDetected(
client,
Emulator.getTexts().getValue("scripter.warning.item.bgtoner.permission").replace("%username%", client.getHabbo().getHabboInfo().getUsername())
.replace("%room%", room.getName())
.replace("%owner%", room.getOwnerName())
);
return;
}
if (client.getHabbo().getRoomUnit().cmdSit && client.getHabbo().getRoomUnit().getEffectId() == 1337) {
new BackgroundAnimation(this, room).run();
return;
}
} }
if (this.getExtradata().split(":").length == 4) { if (this.getExtradata().split(":").length == 4) {

View File

@ -1,14 +1,17 @@
package com.eu.habbo.habbohotel.items.interactions; package com.eu.habbo.habbohotel.items.interactions;
import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.items.Item; import com.eu.habbo.habbohotel.items.Item;
import com.eu.habbo.habbohotel.rooms.Room; import com.eu.habbo.habbohotel.rooms.Room;
import com.eu.habbo.habbohotel.rooms.RoomUnit; import com.eu.habbo.habbohotel.rooms.RoomUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class InteractionColorPlate extends InteractionDefault { public class InteractionColorPlate extends InteractionDefault {
private static final Logger LOGGER = LoggerFactory.getLogger(InteractionColorPlate.class);
public InteractionColorPlate(ResultSet set, Item baseItem) throws SQLException { public InteractionColorPlate(ResultSet set, Item baseItem) throws SQLException {
super(set, baseItem); super(set, baseItem);
} }
@ -41,7 +44,7 @@ public class InteractionColorPlate extends InteractionDefault {
try { try {
state = Integer.valueOf(this.getExtradata()); state = Integer.valueOf(this.getExtradata());
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logErrorLine(e); LOGGER.error("Caught exception", e);
} }
state += amount; state += amount;

View File

@ -1,6 +1,5 @@
package com.eu.habbo.habbohotel.items.interactions; package com.eu.habbo.habbohotel.items.interactions;
import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.bots.Bot; import com.eu.habbo.habbohotel.bots.Bot;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.items.Item; import com.eu.habbo.habbohotel.items.Item;
@ -10,11 +9,15 @@ import com.eu.habbo.habbohotel.users.HabboGender;
import com.eu.habbo.habbohotel.users.HabboItem; import com.eu.habbo.habbohotel.users.HabboItem;
import com.eu.habbo.habbohotel.wired.WiredEffectType; import com.eu.habbo.habbohotel.wired.WiredEffectType;
import com.eu.habbo.messages.ServerMessage; import com.eu.habbo.messages.ServerMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class InteractionDefault extends HabboItem { public class InteractionDefault extends HabboItem {
private static final Logger LOGGER = LoggerFactory.getLogger(InteractionDefault.class);
public InteractionDefault(ResultSet set, Item baseItem) throws SQLException { public InteractionDefault(ResultSet set, Item baseItem) throws SQLException {
super(set, baseItem); super(set, baseItem);
} }
@ -74,7 +77,7 @@ public class InteractionDefault extends HabboItem {
try { try {
currentState = Integer.valueOf(this.getExtradata()); currentState = Integer.valueOf(this.getExtradata());
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
Emulator.getLogging().logErrorLine("Incorrect extradata (" + this.getExtradata() + ") for item ID (" + this.getId() + ") of type (" + this.getBaseItem().getName() + ")"); LOGGER.error("Incorrect extradata (" + this.getExtradata() + ") for item ID (" + this.getId() + ") of type (" + this.getBaseItem().getName() + ")");
} }
this.setExtradata("" + (currentState + 1) % this.getBaseItem().getStateCount()); this.setExtradata("" + (currentState + 1) % this.getBaseItem().getStateCount());

View File

@ -44,12 +44,9 @@ public class InteractionEffectGiver extends InteractionDefault {
this.setExtradata("1"); this.setExtradata("1");
room.updateItem(this); room.updateItem(this);
Emulator.getThreading().run(new Runnable() { Emulator.getThreading().run(() -> {
@Override InteractionEffectGiver.this.setExtradata("0");
public void run() { room.updateItem(instance);
InteractionEffectGiver.this.setExtradata("0");
room.updateItem(instance);
}
}, 500); }, 500);
} }
} }

View File

@ -29,7 +29,7 @@ public class InteractionEffectVendingMachine extends InteractionVendingMachine {
} }
@Override @Override
public void giveVendingMachineItem(Habbo habbo, Room room) { public void giveVendingMachineItem(Room room, RoomUnit unit) {
room.giveEffect(habbo.getRoomUnit(), this.getBaseItem().getRandomVendingItem(), 30); room.giveEffect(unit, this.getBaseItem().getRandomVendingItem(), 30);
} }
} }

View File

@ -7,7 +7,6 @@ import com.eu.habbo.habbohotel.rooms.Room;
import com.eu.habbo.habbohotel.users.HabboGender; import com.eu.habbo.habbohotel.users.HabboGender;
import com.eu.habbo.habbohotel.users.HabboItem; import com.eu.habbo.habbohotel.users.HabboItem;
import com.eu.habbo.habbohotel.users.inventory.EffectsComponent; import com.eu.habbo.habbohotel.users.inventory.EffectsComponent;
import com.eu.habbo.messages.outgoing.inventory.UserEffectsListComposer;
import com.eu.habbo.messages.outgoing.rooms.items.RemoveFloorItemComposer; import com.eu.habbo.messages.outgoing.rooms.items.RemoveFloorItemComposer;
import com.eu.habbo.threading.runnables.QueryDeleteHabboItem; import com.eu.habbo.threading.runnables.QueryDeleteHabboItem;

View File

@ -3,6 +3,7 @@ package com.eu.habbo.habbohotel.items.interactions;
import com.eu.habbo.habbohotel.gameclients.GameClient; import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.items.Item; import com.eu.habbo.habbohotel.items.Item;
import com.eu.habbo.habbohotel.rooms.Room; import com.eu.habbo.habbohotel.rooms.Room;
import com.eu.habbo.habbohotel.rooms.RoomTile;
import com.eu.habbo.habbohotel.rooms.RoomUnit; import com.eu.habbo.habbohotel.rooms.RoomUnit;
import com.eu.habbo.habbohotel.users.HabboItem; import com.eu.habbo.habbohotel.users.HabboItem;
import com.eu.habbo.habbohotel.wired.WiredEffectType; import com.eu.habbo.habbohotel.wired.WiredEffectType;
@ -38,17 +39,21 @@ public class InteractionGate extends HabboItem {
@Override @Override
public void onClick(GameClient client, Room room, Object[] objects) throws Exception { public void onClick(GameClient client, Room room, Object[] objects) throws Exception {
boolean isWired = (objects.length >= 2 && objects[1] instanceof WiredEffectType && objects[1] == WiredEffectType.TOGGLE_STATE); boolean executedByWired = (objects.length >= 2 && objects[1] instanceof WiredEffectType && objects[1] == WiredEffectType.TOGGLE_STATE);
if (client != null && !room.hasRights(client.getHabbo()) && !isWired)
if (client != null && !room.hasRights(client.getHabbo()) && !executedByWired)
return; return;
if (!isWired && !room.getHabbosAt(this.getX(), this.getY()).isEmpty()) // If a Habbo is standing on a tile occupied by the gate, the gate shouldn't open/close
return; for (RoomTile tile : room.getLayout().getTilesAt(room.getLayout().getTile(this.getX(), this.getY()), this.getBaseItem().getWidth(), this.getBaseItem().getLength(), this.getRotation()))
if (room.hasHabbosAt(tile.x, tile.y))
return;
// Gate closed = 0, open = 1
if (this.getExtradata().length() == 0) if (this.getExtradata().length() == 0)
this.setExtradata("0"); this.setExtradata("0");
this.setExtradata((Integer.valueOf(this.getExtradata()) + 1) % 2 + ""); this.setExtradata((Integer.parseInt(this.getExtradata()) + 1) % 2 + "");
room.updateTile(room.getLayout().getTile(this.getX(), this.getY())); room.updateTile(room.getLayout().getTile(this.getX(), this.getY()));
this.needsUpdate(true); this.needsUpdate(true);
room.updateItemState(this); room.updateItemState(this);

View File

@ -8,11 +8,15 @@ import com.eu.habbo.habbohotel.rooms.RoomUnit;
import com.eu.habbo.habbohotel.users.HabboItem; import com.eu.habbo.habbohotel.users.HabboItem;
import com.eu.habbo.messages.ServerMessage; import com.eu.habbo.messages.ServerMessage;
import gnu.trove.set.hash.THashSet; import gnu.trove.set.hash.THashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class InteractionGift extends HabboItem { public class InteractionGift extends HabboItem {
private static final Logger LOGGER = LoggerFactory.getLogger(InteractionGift.class);
public boolean explode = false; public boolean explode = false;
private int[] itemId; private int[] itemId;
private int colorId = 0; private int colorId = 0;
@ -28,7 +32,7 @@ public class InteractionGift extends HabboItem {
try { try {
this.loadData(); this.loadData();
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logDebugLine("Incorrect extradata for gift with ID " + this.getId()); LOGGER.warn("Incorrect extradata for gift with ID " + this.getId());
} }
} }
@ -38,7 +42,7 @@ public class InteractionGift extends HabboItem {
try { try {
this.loadData(); this.loadData();
} catch (Exception e) { } catch (Exception e) {
Emulator.getLogging().logDebugLine("Incorrect extradata for gift with ID " + this.getId()); LOGGER.warn("Incorrect extradata for gift with ID " + this.getId());
} }
} }

Some files were not shown because too many files have changed in this diff Show More