Merge branch 'dev' into 'master'

2.1.0 Stable

See merge request morningstar/Arcturus-Community!45
This commit is contained in:
Harmonic 2019-07-05 09:18:57 -04:00
commit 9bdbf7d19a
1728 changed files with 22275 additions and 38513 deletions

10
pom.xml
View File

@ -6,7 +6,7 @@
<groupId>com.eu.habbo</groupId>
<artifactId>Habbo</artifactId>
<version>2.0.0</version>
<version>2.1.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
@ -88,27 +88,27 @@
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.24.Final</version>
<version>4.1.36.Final</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec-http</artifactId>
<version>4.1.24.Final</version>
<version>4.1.36.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-codec-http2</artifactId>
<version>4.1.24.Final</version>
<version>4.1.36.Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId>
<version>4.1.24.Final</version>
<version>4.1.36.Final</version>
<scope>compile</scope>
</dependency>

View File

@ -0,0 +1,126 @@
CREATE TABLE `users_saved_searches` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`search_code` varchar(255) NOT NULL,
`filter` varchar(255) NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
ALTER TABLE `users_settings`
ADD COLUMN `ui_flags` int(11) NOT NULL DEFAULT 1 AFTER `forums_post_count`;
ALTER TABLE `users_settings`
ADD COLUMN `has_gotten_default_saved_searches` tinyint(1) NOT NULL DEFAULT 0 AFTER `ui_flags`;
ALTER TABLE `support_tickets`
ADD COLUMN `group_id` int(11) NOT NULL AFTER `category`,
ADD COLUMN `thread_id` int(11) NOT NULL AFTER `group_id`,
ADD COLUMN `comment_id` int(11) NOT NULL AFTER `thread_id`;
ALTER TABLE `pet_actions`
ADD COLUMN `can_swim` enum('1','0') NULL DEFAULT '0' AFTER `random_actions`;
UPDATE `pet_actions` SET `can_swim` = '1' WHERE `pet_type` = 9 OR `pet_type` = 14 OR `pet_type` = 23 OR `pet_type` = 24 OR `pet_type` = 25 OR `pet_type` = 28 OR `pet_type` = 29 OR `pet_type` = 30 OR `pet_type` = 32;
UPDATE `items_base` SET `customparams` = '30,60,120,180,300,600', `interaction_type` = 'game_timer', `interaction_modes_count` = 1 WHERE `item_name` IN ('fball_counter','bb_counter','es_counter');
ALTER TABLE `youtube_playlists`
CHANGE COLUMN `video_id` `playlist_id` varchar(255) NOT NULL COMMENT 'YouTube playlist ID' AFTER `item_id`;
DROP TABLE `youtube_items`;
TRUNCATE TABLE `youtube_playlists`;
DROP PROCEDURE IF EXISTS DEFAULT_YTTV_PLAYLISTS;
DELIMITER ;;
CREATE PROCEDURE DEFAULT_YTTV_PLAYLISTS()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE a INT DEFAULT 0;
DECLARE itemId INT default 0;
SELECT COUNT(*) FROM `items_base` WHERE `interaction_type` = 'youtube' INTO n;
SET i=0;
SET @defaultPlaylistIds = '["PL4YfV2mXS8WXOkxFly7YsGL8cKtqp873p","PL4F5KzcUTpEdux38c8CYunT9uNh_k2NPt","PL4F5KzcUTpEcO-1iw3P6gavJ_ALTxqNHn","PL4F5KzcUTpEfpHad_B7j_MulB3-cwtLFh","PL4F5KzcUTpEekJPbcVOaNYVV6VLSo9zRB","PL80F08DAE1B614BA9","PL4F5KzcUTpEfeS5t7EiEIYbpplZivDZTL","PL4ACB18CA629E650A","PL4F5KzcUTpEfyRBCOVKQ4qxlSoHsGDZ82","PL4F5KzcUTpEet7EMwhw0ge5n2oNMr7JY8","PL4F5KzcUTpEfTW4fkX9vrt497MEvWorwK","PL4F5KzcUTpEcit3i1q55-IFFndmo_dsR8","PL4F5KzcUTpEeJleVUhO1MWRJyYDWWp9Do","PL4F5KzcUTpEcFzCpH2_EXtwzKQH8mJGd9","PL4F5KzcUTpEcIiSOH2x3sg2jwACNbSIm9","PL4F5KzcUTpEfRxBiXwTBA7oiybPqoZD_j","PL4YfV2mXS8WUo09aevZX-b47k4PD08-i8","PL4F5KzcUTpEcFzCpH2_EXtwzKQH8mJGd9"]';
WHILE i < n DO
SET itemId = (SELECT id FROM `items_base` WHERE `interaction_type` = 'youtube' LIMIT i, 1);
WHILE a<JSON_LENGTH(@defaultPlaylistIds) DO
INSERT IGNORE INTO `youtube_playlists` (item_id, playlist_id) VALUES (itemId, TRIM(BOTH '"' FROM JSON_EXTRACT(@defaultPlaylistIds, CONCAT('$[',a,']'))));
SET a = a + 1;
END WHILE;
SET a = 0;
SET i = i + 1;
END WHILE;
END;
;;
DELIMITER ;
CALL DEFAULT_YTTV_PLAYLISTS();
DROP PROCEDURE IF EXISTS DEFAULT_YTTV_PLAYLISTS;
ALTER TABLE `permissions`
ADD COLUMN `cmd_update_youtube_playlists` enum('0','1') NOT NULL DEFAULT '0';
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.keys.cmd_update_youtube_playlists', 'update_youtube;update_youtube_playlists');
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.succes.cmd_update_youtube_playlists', 'YouTube playlists have been refreshed!');
DROP PROCEDURE IF EXISTS UPDATE_TEAM_WIREDS;
DELIMITER ;;
CREATE PROCEDURE UPDATE_TEAM_WIREDS()
BEGIN
IF (SELECT COUNT(*) FROM emulator_settings WHERE `key` = 'team.wired.update.rc-1') = 0 THEN
INSERT INTO emulator_settings (`key`, `value`) VALUES ('team.wired.update.rc-1', 'DO NOT REMOVE THIS SETTING!');
UPDATE
items
INNER JOIN
items_base
ON
items.item_id = items_base.id
SET items.wired_data = CONCAT(
SUBSTRING_INDEX(items.wired_data, ';', 2),
';',
CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(items.wired_data, ';', 3), ';', -1) AS SIGNED INTEGER) + 1,
';',
SUBSTRING_INDEX(SUBSTRING_INDEX(items.wired_data, ';', 4), ';', -1)
)
WHERE
items_base.interaction_type = 'wf_act_give_score_tm';
UPDATE
items
INNER JOIN
items_base
ON
items.item_id = items_base.id
SET items.wired_data = CONCAT(
SUBSTRING_INDEX(items.wired_data, '\t', 1),
'\t',
CAST(SUBSTRING_INDEX(items.wired_data, '\t', -1) AS SIGNED INTEGER) + 1
)
WHERE
items_base.interaction_type = 'wf_act_join_team';
UPDATE
items
INNER JOIN
items_base
ON
items.item_id = items_base.id
SET items.wired_data = CAST(items.wired_data AS SIGNED INTEGER) + 1
WHERE
items_base.interaction_type = 'wf_cnd_actor_in_team' OR items_base.interaction_type = 'wf_cnd_not_in_team';
END IF;
END;
;;
DELIMITER ;
CALL UPDATE_TEAM_WIREDS();
DROP PROCEDURE IF EXISTS UPDATE_TEAM_WIREDS;

View File

@ -0,0 +1,10 @@
ALTER TABLE `permissions`
ADD COLUMN `cmd_add_youtube_playlist` enum('0','1') NOT NULL DEFAULT '0';
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.keys.cmd_add_youtube_playlist', 'add_youtube;add_playlist;add_youtube_playlist');
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.error.cmd_add_youtube_playlist.usage', 'Usage: base_item_id youtube_playlist_id');
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.error.cmd_add_youtube_playlist.no_base_item', 'A base item with that ID could not be found.');
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.error.cmd_add_youtube_playlist.failed_playlist', 'Error: unable to fetch the given YouTube playlist.');
INSERT INTO `emulator_texts`(`key`, `value`) VALUES ('commands.succes.cmd_add_youtube_playlist', 'The playlist has been added successfully!');
UPDATE `emulator_texts` SET `value` = 'Superwired Usage Information. Possible reward types:<br/>badge: BADGE CODE<br/>Credits: credits#amount<br/>Pixels: pixels#amount<br/>Points: points#amount<br/>Respect: respect#amount<br/>Furniture: furni#FurnitureID<br/>Catalog Item: cata#CatalogItemID' WHERE `key` = 'hotel.wired.superwired.info';

View File

@ -7,7 +7,6 @@ import com.eu.habbo.core.TextsManager;
import com.eu.habbo.core.consolecommands.ConsoleCommand;
import com.eu.habbo.database.Database;
import com.eu.habbo.habbohotel.GameEnvironment;
import com.eu.habbo.habbohotel.messenger.MessengerBuddy;
import com.eu.habbo.networking.camera.CameraClient;
import com.eu.habbo.networking.gameserver.GameServer;
import com.eu.habbo.networking.rconserver.RCONServer;
@ -17,7 +16,6 @@ import com.eu.habbo.plugin.events.emulator.EmulatorLoadedEvent;
import com.eu.habbo.plugin.events.emulator.EmulatorStartShutdownEvent;
import com.eu.habbo.plugin.events.emulator.EmulatorStoppedEvent;
import com.eu.habbo.threading.ThreadPooling;
import com.eu.habbo.threading.runnables.CameraClientAutoReconnect;
import com.eu.habbo.util.imager.badges.BadgeImager;
import java.io.BufferedReader;
@ -30,34 +28,35 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
import java.util.zip.Checksum;
public final class Emulator
{
public final class Emulator {
public final static int MAJOR = 2;
public final static int MINOR = 0;
public final static int MINOR = 1;
public final static int BUILD = 0;
public final static String PREVIEW = "";
public final static String PREVIEW = "Stable";
public static final String version = "Arcturus Morningstar"+ " " + MAJOR + "." + MINOR + "." + BUILD;
public static final String version = "Arcturus Morningstar" + " " + MAJOR + "." + MINOR + "." + BUILD + " " + PREVIEW;
private static final String logo =
" \n" +
" __ ___ _ A R C T U R U S __ \n" +
" / |/ /___ _________ (_)___ ____ ______/ /_____ ______ \n" +
" / /|_/ / __ \\/ ___/ __ \\/ / __ \\/ __ `/ ___/ __/ __ `/ ___/ \n" +
" / / / / /_/ / / / / / / / / / / /_/ (__ ) /_/ /_/ / / \n" +
"/_/ /_/\\____/_/ /_/ /_/_/_/ /_/\\__, /____/\\__/\\__,_/_/ \n" +
" /____/ \n";
public static String build = "";
public static boolean isReady = false;
public static boolean isShuttingDown = false;
public static boolean stopped = false;
public static boolean debugging = false;
private static int timeStarted = 0;
private static Runtime runtime;
private static ConfigurationManager config;
@ -73,12 +72,9 @@ public final class Emulator
private static Random random;
private static BadgeImager badgeImager;
static
{
Thread hook = new Thread(new Runnable()
{
public synchronized void run()
{
static {
Thread hook = new Thread(new Runnable() {
public synchronized void run() {
Emulator.dispose();
}
});
@ -86,11 +82,8 @@ public final class Emulator
Runtime.getRuntime().addShutdownHook(hook);
}
public static void main(String[] args) throws Exception
{
try
{
public static void main(String[] args) throws Exception {
try {
Locale.setDefault(new Locale("en"));
setBuild();
@ -104,13 +97,6 @@ public final class Emulator
Emulator.runtime = Runtime.getRuntime();
Emulator.config = new ConfigurationManager("config.ini");
if (Emulator.getConfig().getValue("username").isEmpty())
{
Emulator.getLogging().logErrorLine("Please make sure you enter your forum login details!");
Thread.sleep(2000);
}
Emulator.database = new Database(Emulator.getConfig());
Emulator.config.loaded = true;
Emulator.config.loadFromDatabase();
@ -131,12 +117,6 @@ public final class Emulator
Emulator.rconServer.initializePipeline();
Emulator.rconServer.connect();
Emulator.badgeImager = new BadgeImager();
// Removed Wesleys Camera Server lol.
/* if (Emulator.getConfig().getBoolean("camera.enabled"))
{
Emulator.getThreading().run(new CameraClientAutoReconnect());
}
*/
Emulator.getLogging().logStart("Habbo Hotel Emulator has succesfully loaded.");
Emulator.getLogging().logStart("You're running: " + Emulator.version);
Emulator.getLogging().logStart("System launched in: " + (System.nanoTime() - startTime) / 1e6 + "ms. Using: " + (Runtime.getRuntime().availableProcessors() * 2) + " threads!");
@ -144,8 +124,7 @@ public final class Emulator
Emulator.debugging = Emulator.getConfig().getBoolean("debug.mode");
if (debugging)
{
if (debugging) {
Emulator.getLogging().logDebugLine("Debugging Enabled!");
}
@ -153,18 +132,15 @@ public final class Emulator
Emulator.isReady = true;
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.");
}
Emulator.getThreading().run(new Runnable()
{
Emulator.getThreading().run(new Runnable() {
@Override
public void run()
{
Emulator.getLogging().logStart("Thankyou for downloading Arcturus Morningstar! This is a Release Candidate for 2.0.0, if you find any bugs please place them on our git repository.");
public void run() {
Emulator.getLogging().logStart("Thankyou for downloading Arcturus Morningstar! This is a stable 2.1.0 build, it should be more than stable for daily use on hotels, if you find any bugs please place them on our git repository.");
Emulator.getLogging().logStart("Please note, Arcturus Emulator is a project by TheGeneral, we take no credit for the original work, and only the work we have continued. If you'd like to support the project, join our discord at: ");
Emulator.getLogging().logStart("https://discord.gg/syuqgN");
System.out.println("Waiting for commands: ");
@ -173,56 +149,46 @@ public final class Emulator
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (!isShuttingDown && isReady)
{
try
{
while (!isShuttingDown && isReady && reader.ready()) {
try {
String line = reader.readLine();
if (line != null)
{
if (line != null) {
ConsoleCommand.handle(line);
}
System.out.println("Waiting for command: ");
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
}
}
catch (Exception e)
{
} catch (Exception e) {
e.printStackTrace();
}
}
private static void setBuild() {
if(Emulator.class.getProtectionDomain().getCodeSource() == null) {
if (Emulator.class.getProtectionDomain().getCodeSource() == null) {
build = "UNKNOWN";
return;
}
StringBuilder sb = new StringBuilder();
try
{
try {
String filepath = new File(Emulator.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getAbsolutePath();
MessageDigest md = MessageDigest.getInstance("MD5");// MD5
FileInputStream fis = new FileInputStream(filepath);
byte[] dataBytes = new byte[1024];
int nread = 0;
while((nread = fis.read(dataBytes)) != -1)
while ((nread = fis.read(dataBytes)) != -1)
md.update(dataBytes, 0, nread);
byte[] mdbytes = md.digest();
for(int i=0; i<mdbytes.length; i++)
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100 , 16).substring(1));
}
catch(Exception e)
{
for (int i = 0; i < mdbytes.length; i++)
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
} catch (Exception e) {
build = "UNKNOWN";
return;
}
@ -230,193 +196,147 @@ public final class Emulator
build = sb.toString();
}
private static void dispose()
{
private static void dispose() {
Emulator.getThreading().setCanAdd(false);
Emulator.isShuttingDown = true;
Emulator.isReady = false;
Emulator.getLogging().logShutdownLine("Stopping Arcturus Emulator " + version + "...");
try
{
try {
if (Emulator.getPluginManager() != null)
Emulator.getPluginManager().fireEvent(new EmulatorStartShutdownEvent());
} catch (Exception e) {
}
catch (Exception e) {}
try
{
try {
if (Emulator.cameraClient != null)
Emulator.cameraClient.disconnect();
} catch (Exception e) {
}
catch (Exception e) {}
try
{
try {
if (Emulator.rconServer != null)
Emulator.rconServer.stop();
} catch (Exception e) {
}
catch (Exception e) {}
try
{
try {
if (Emulator.gameEnvironment != null)
Emulator.gameEnvironment.dispose();
} catch (Exception e) {
}
catch (Exception e) {}
try
{
try {
if (Emulator.getPluginManager() != null)
Emulator.getPluginManager().fireEvent(new EmulatorStoppedEvent());
} catch (Exception e) {
}
catch (Exception e) {}
try
{
try {
if (Emulator.pluginManager != null)
Emulator.pluginManager.dispose();
} catch (Exception e) {
}
catch (Exception e) {}
Emulator.getLogging().saveLogs();
try
{
if (Emulator.config != null)
{
try {
if (Emulator.config != null) {
Emulator.config.saveToDatabase();
}
} catch (Exception e) {
}
catch (Exception e) {}
try
{
try {
if (Emulator.gameServer != null)
Emulator.gameServer.stop();
} catch (Exception e) {
}
catch (Exception e) {}
Emulator.getLogging().logShutdownLine("Stopped Arcturus Emulator " + version + "...");
if (Emulator.database != null)
{
if (Emulator.database != null) {
Emulator.getDatabase().dispose();
}
Emulator.stopped = true;
try
{
try {
if (Emulator.threading != null)
Emulator.threading.shutDown();
} catch (Exception e) {
}
catch (Exception e) {}
}
public static ConfigurationManager getConfig()
{
public static ConfigurationManager getConfig() {
return config;
}
public static TextsManager getTexts()
{
public static TextsManager getTexts() {
return texts;
}
public static Database getDatabase()
{
public static Database getDatabase() {
return database;
}
public static Runtime getRuntime()
{
public static Runtime getRuntime() {
return runtime;
}
public static GameServer getGameServer()
{
public static GameServer getGameServer() {
return gameServer;
}
public static RCONServer getRconServer()
{
public static RCONServer getRconServer() {
return rconServer;
}
public static Logging getLogging()
{
public static Logging getLogging() {
return logging;
}
public static ThreadPooling getThreading()
{
public static ThreadPooling getThreading() {
return threading;
}
public static GameEnvironment getGameEnvironment()
{
public static GameEnvironment getGameEnvironment() {
return gameEnvironment;
}
public static PluginManager getPluginManager()
{
public static PluginManager getPluginManager() {
return pluginManager;
}
public static Random getRandom()
{
public static Random getRandom() {
return random;
}
public static BadgeImager getBadgeImager()
{
public static BadgeImager getBadgeImager() {
return badgeImager;
}
public static CameraClient getCameraClient()
{
public static CameraClient getCameraClient() {
return cameraClient;
}
public static synchronized void setCameraClient(CameraClient client)
{
public static synchronized void setCameraClient(CameraClient client) {
cameraClient = client;
}
public static int getTimeStarted()
{
public static int getTimeStarted() {
return timeStarted;
}
public static int getOnlineTime()
{
public static int getOnlineTime() {
return getIntUnixTimestamp() - timeStarted;
}
public static void prepareShutdown()
{
public static void prepareShutdown() {
System.exit(0);
}
private static String dateToUnixTimestamp(Date date)
{
private static String dateToUnixTimestamp(Date date) {
String res = "";
Date aux = stringToDate("1970-01-01 00:00:00");
Timestamp aux1 = dateToTimeStamp(aux);
@ -426,55 +346,42 @@ public final class Emulator
return res + seconds;
}
private static Date stringToDate(String date)
{
private static Date stringToDate(String date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date res = null;
try
{
try {
res = format.parse(date);
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
return res;
}
public static Timestamp dateToTimeStamp(Date date)
{
public static Timestamp dateToTimeStamp(Date date) {
return new Timestamp(date.getTime());
}
public static Date getDate()
{
public static Date getDate() {
return new Date(System.currentTimeMillis());
}
public static String getUnixTimestamp()
{
public static String getUnixTimestamp() {
return dateToUnixTimestamp(getDate());
}
public static int getIntUnixTimestamp()
{
public static int getIntUnixTimestamp() {
return (int) (System.currentTimeMillis() / 1000);
}
public static boolean isNumeric(String string)
throws IllegalArgumentException
{
throws IllegalArgumentException {
boolean isnumeric = false;
if ((string != null) && (!string.equals("")))
{
if ((string != null) && (!string.equals(""))) {
isnumeric = true;
char[] chars = string.toCharArray();
for (char aChar : chars)
{
for (char aChar : chars) {
isnumeric = Character.isDigit(aChar);
if (!isnumeric)
{
if (!isnumeric) {
break;
}
}
@ -482,23 +389,11 @@ public final class Emulator
return isnumeric;
}
public int getUserCount()
{
public int getUserCount() {
return gameEnvironment.getHabboManager().getOnlineCount();
}
public int getRoomCount()
{
public int getRoomCount() {
return gameEnvironment.getRoomManager().getActiveRooms().size();
}
private static final String logo =
" \n" +
" __ ___ _ A R C T U R U S __ \n" +
" / |/ /___ _________ (_)___ ____ ______/ /_____ ______ \n" +
" / /|_/ / __ \\/ ___/ __ \\/ / __ \\/ __ `/ ___/ __/ __ `/ ___/ \n" +
" / / / / /_/ / / / / / / / / / / /_/ (__ ) /_/ /_/ / / \n" +
"/_/ /_/\\____/_/ /_/ /_/_/_/ /_/\\__, /____/\\__/\\__,_/_/ \n" +
" /____/ \n";
}

View File

@ -7,7 +7,6 @@ import com.eu.habbo.messages.incoming.friends.SearchUserEvent;
import com.eu.habbo.messages.incoming.navigator.SearchRoomsEvent;
import com.eu.habbo.threading.runnables.AchievementUpdater;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@ -41,8 +40,7 @@ public class CleanerThread implements Runnable {
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();
@ -70,8 +68,7 @@ public class CleanerThread implements Runnable {
private static int LAST_HABBO_CACHE_CLEARED = Emulator.getIntUnixTimestamp();
public CleanerThread()
{
public CleanerThread() {
this.databaseCleanup();
Emulator.getThreading().run(this, DELAY);
@ -81,63 +78,53 @@ public class CleanerThread implements Runnable {
}
@Override
public void run()
{
public void run() {
Emulator.getThreading().run(this, DELAY);
int time = Emulator.getIntUnixTimestamp();
if (time - LAST_HOF_RELOAD > RELOAD_HALL_OF_FAME)
{
if (time - LAST_HOF_RELOAD > RELOAD_HALL_OF_FAME) {
Emulator.getGameEnvironment().getHotelViewManager().getHallOfFame().reload();
LAST_HOF_RELOAD = time;
}
if (time - LAST_NL_RELOAD > RELOAD_NEWS_LIST)
{
if (time - LAST_NL_RELOAD > RELOAD_NEWS_LIST) {
Emulator.getGameEnvironment().getHotelViewManager().getNewsList().reload();
LAST_NL_RELOAD = time;
}
if (time - LAST_INACTIVE_ROOMS_CLEARED > REMOVE_INACTIVE_ROOMS)
{
if (time - LAST_INACTIVE_ROOMS_CLEARED > REMOVE_INACTIVE_ROOMS) {
Emulator.getGameEnvironment().getRoomManager().clearInactiveRooms();
LAST_INACTIVE_ROOMS_CLEARED = time;
}
if (time - LAST_INACTIVE_GUILDS_CLEARED > REMOVE_INACTIVE_GUILDS)
{
if (time - LAST_INACTIVE_GUILDS_CLEARED > REMOVE_INACTIVE_GUILDS) {
Emulator.getGameEnvironment().getGuildManager().clearInactiveGuilds();
ForumThread.clearCache();
LAST_INACTIVE_GUILDS_CLEARED = time;
}
if (time - LAST_INACTIVE_TOURS_CLEARED > REMOVE_INACTIVE_TOURS)
{
if (time - LAST_INACTIVE_TOURS_CLEARED > REMOVE_INACTIVE_TOURS) {
Emulator.getGameEnvironment().getGuideManager().cleanup();
LAST_INACTIVE_TOURS_CLEARED = time;
}
if (time - LAST_ERROR_LOGS_SAVED > SAVE_ERROR_LOGS)
{
if (time - LAST_ERROR_LOGS_SAVED > SAVE_ERROR_LOGS) {
Emulator.getLogging().saveLogs();
LAST_ERROR_LOGS_SAVED = time;
}
if (time - LAST_CALLBACK > CALLBACK_TIME)
{
if (time - LAST_CALLBACK > CALLBACK_TIME) {
// Emulator.getThreading().run(new HTTPPostStatus());
LAST_CALLBACK = time;
}
if (time - LAST_DAILY_REFILL > Emulator.getConfig().getInt("hotel.refill.daily"))
{
if (time - LAST_DAILY_REFILL > Emulator.getConfig().getInt("hotel.refill.daily")) {
this.refillDailyRespects();
LAST_DAILY_REFILL = time;
}
if (time - LAST_HABBO_CACHE_CLEARED > CLEAR_CACHED_VALUES)
{
if (time - LAST_HABBO_CACHE_CLEARED > CLEAR_CACHED_VALUES) {
this.clearCachedValues();
LAST_HABBO_CACHE_CLEARED = time;
}
@ -147,15 +134,12 @@ public class CleanerThread implements Runnable {
}
void databaseCleanup()
{
void databaseCleanup() {
this.refillDailyRespects();
int time = Emulator.getIntUnixTimestamp();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection())
{
try (Statement statement = connection.createStatement())
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
try (Statement statement = connection.createStatement()) {
statement.execute("UPDATE users SET online = '0' WHERE online = '1'");
statement.execute("UPDATE rooms SET users = '0' WHERE users > 0");
statement.execute("DELETE FROM room_mutes WHERE ends < " + time);
@ -163,63 +147,47 @@ public class CleanerThread implements Runnable {
statement.execute("DELETE users_favorite_rooms FROM users_favorite_rooms LEFT JOIN rooms ON room_id = rooms.id WHERE rooms.id IS NULL");
}
try (PreparedStatement statement = connection.prepareStatement("UPDATE users_effects SET total = total - 1 WHERE activation_timestamp < ? AND activation_timestamp != 0"))
{
try (PreparedStatement statement = connection.prepareStatement("UPDATE users_effects SET total = total - 1 WHERE activation_timestamp < ? AND activation_timestamp != 0")) {
statement.setInt(1, Emulator.getIntUnixTimestamp() - 86400);
statement.execute();
}
try (Statement statement = connection.createStatement())
{
try (Statement statement = connection.createStatement()) {
statement.execute("DELETE FROM users_effects WHERE total <= 0");
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
Emulator.getLogging().logStart("Database -> Cleaned!");
}
public void refillDailyRespects()
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_settings SET daily_respect_points = ?, daily_pet_respect_points = ?"))
{
public void refillDailyRespects() {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_settings SET daily_respect_points = ?, daily_pet_respect_points = ?")) {
statement.setInt(1, Emulator.getConfig().getInt("hotel.daily.respect"));
statement.setInt(2, Emulator.getConfig().getInt("hotel.daily.respect.pets"));
statement.executeUpdate();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
if (Emulator.isReady)
{
for (Habbo habbo : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().values())
{
if (Emulator.isReady) {
for (Habbo habbo : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().values()) {
habbo.getHabboStats().petRespectPointsToGive = Emulator.getConfig().getInt("hotel.daily.respect");
habbo.getHabboStats().respectPointsToGive = Emulator.getConfig().getInt("hotel.daily.respect.pets");
}
}
}
private void clearCachedValues()
{
private void clearCachedValues() {
Habbo habbo;
for(Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet())
{
for (Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) {
habbo = map.getValue();
try
{
if (habbo != null)
{
try {
if (habbo != null) {
habbo.clearCaches();
}
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
}

View File

@ -6,8 +6,7 @@ import com.eu.habbo.habbohotel.commands.Command;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class CommandLog implements Loggable
{
public class CommandLog implements Loggable {
public static final String insertQuery = "INSERT INTO commandlogs (`user_id`, `timestamp`, `command`, `params`, `succes`) VALUES (?, ?, ?, ?, ?)";
private final int userId;
@ -17,8 +16,7 @@ public class CommandLog implements Loggable
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.command = command;
this.params = params;
@ -26,8 +24,7 @@ public class CommandLog implements Loggable
}
@Override
public void log(PreparedStatement statement) throws SQLException
{
public void log(PreparedStatement statement) throws SQLException {
statement.setInt(1, this.userId);
statement.setInt(2, this.timestamp);
statement.setString(3, this.command.getClass().getSimpleName());

View File

@ -11,128 +11,95 @@ import java.sql.*;
import java.util.Map;
import java.util.Properties;
public class ConfigurationManager
{
public boolean loaded = false;
public boolean isLoading = false;
public class ConfigurationManager {
private final Properties properties;
private final String configurationPath;
public boolean loaded = false;
public boolean isLoading = false;
public ConfigurationManager(String configurationPath) throws Exception
{
public ConfigurationManager(String configurationPath) throws Exception {
this.properties = new Properties();
this.configurationPath = configurationPath;
this.reload();
}
public void reload()
{
public void reload() {
this.isLoading = true;
this.properties.clear();
InputStream input = null;
try
{
try {
File f = new File(this.configurationPath);
input = new FileInputStream(f);
this.properties.load(input);
}
catch (IOException ex)
{
} catch (IOException ex) {
Emulator.getLogging().logErrorLine("[CRITICAL] FAILED TO LOAD CONFIG FILE! (" + this.configurationPath + ")");
ex.printStackTrace();
}
finally
{
if (input != null)
{
try
{
} finally {
if (input != null) {
try {
input.close();
}
catch (IOException e)
{
} catch (IOException e) {
e.printStackTrace();
}
}
}
if(this.loaded)
{
if (this.loaded) {
this.loadFromDatabase();
}
this.isLoading = false;
Emulator.getLogging().logStart("Configuration Manager -> Loaded!");
if (Emulator.getPluginManager() != null)
{
if (Emulator.getPluginManager() != null) {
Emulator.getPluginManager().fireEvent(new EmulatorConfigUpdatedEvent());
}
}
public void loadFromDatabase()
{
public void loadFromDatabase() {
Emulator.getLogging().logStart("Loading configuration from database...");
long millis = System.currentTimeMillis();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement())
{
if (statement.execute("SELECT * FROM emulator_settings"))
{
try (ResultSet set = statement.getResultSet())
{
while (set.next())
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement()) {
if (statement.execute("SELECT * FROM emulator_settings")) {
try (ResultSet set = statement.getResultSet()) {
while (set.next()) {
this.properties.put(set.getString("key"), set.getString("value"));
}
}
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
Emulator.getLogging().logStart("Configuration -> loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
}
public void saveToDatabase()
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE emulator_settings SET `value` = ? WHERE `key` = ? LIMIT 1"))
{
for (Map.Entry<Object, Object> entry : this.properties.entrySet())
{
public void saveToDatabase() {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE emulator_settings SET `value` = ? WHERE `key` = ? LIMIT 1")) {
for (Map.Entry<Object, Object> entry : this.properties.entrySet()) {
statement.setString(1, entry.getValue().toString());
statement.setString(2, entry.getKey().toString());
statement.executeUpdate();
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
public String getValue(String key)
{
public String getValue(String key) {
return this.getValue(key, "");
}
public String getValue(String key, String defaultValue)
{
public String getValue(String key, String defaultValue) {
if (this.isLoading)
return defaultValue;
@ -143,68 +110,54 @@ public class ConfigurationManager
}
public boolean getBoolean(String key)
{
public boolean getBoolean(String key) {
return this.getBoolean(key, false);
}
public boolean getBoolean(String key, boolean defaultValue)
{
public boolean getBoolean(String key, boolean defaultValue) {
if (this.isLoading)
return defaultValue;
try
{
try {
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.");
}
return defaultValue;
}
public int getInt(String key)
{
public int getInt(String key) {
return this.getInt(key, 0);
}
public int getInt(String key, Integer defaultValue)
{
public int getInt(String key, Integer defaultValue) {
if (this.isLoading)
return defaultValue;
try
{
try {
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.");
}
return defaultValue;
}
public double getDouble(String key)
{
public double getDouble(String key) {
return this.getDouble(key, 0.0);
}
public double getDouble(String key, Double defaultValue)
{
public double getDouble(String key, Double defaultValue) {
if (this.isLoading)
return defaultValue;
try
{
try {
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.");
}
@ -212,24 +165,19 @@ public class ConfigurationManager
}
public void update(String key, String value)
{
public void update(String key, String value) {
this.properties.setProperty(key, value);
}
public void register(String key, String value)
{
public void register(String key, String value) {
if (this.properties.getProperty(key, null) != null)
return;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO emulator_settings VALUES (?, ?)"))
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO emulator_settings VALUES (?, ?)")) {
statement.setString(1, key);
statement.setString(2, value);
statement.execute();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}

View File

@ -5,8 +5,7 @@ import com.eu.habbo.habbohotel.users.Habbo;
import java.util.Map;
public class CreditsScheduler extends Scheduler
{
public class CreditsScheduler extends Scheduler {
public static boolean IGNORE_HOTEL_VIEW;
@ -22,8 +21,7 @@ public class CreditsScheduler extends Scheduler
}
public void reloadConfig() {
if(Emulator.getConfig().getBoolean("hotel.auto.credits.enabled"))
{
if (Emulator.getConfig().getBoolean("hotel.auto.credits.enabled")) {
IGNORE_HOTEL_VIEW = Emulator.getConfig().getBoolean("hotel.auto.credits.ignore.hotelview");
IGNORE_IDLED = Emulator.getConfig().getBoolean("hotel.auto.credits.ignore.idled");
CREDITS = Emulator.getConfig().getInt("hotel.auto.credits.amount");
@ -31,27 +29,21 @@ public class CreditsScheduler extends Scheduler
this.disposed = false;
this.run();
}
}
else
{
} else {
this.disposed = true;
}
}
@Override
public void run()
{
public void run() {
super.run();
Habbo habbo;
for(Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet())
{
for (Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) {
habbo = map.getValue();
try
{
if (habbo != null)
{
try {
if (habbo != null) {
if (habbo.getHabboInfo().getCurrentRoom() == null && IGNORE_HOTEL_VIEW)
continue;
@ -60,21 +52,17 @@ public class CreditsScheduler extends Scheduler
habbo.giveCredits(CREDITS);
}
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
}
}
public boolean isDisposed()
{
public boolean isDisposed() {
return this.disposed;
}
public void setDisposed(boolean disposed)
{
public void setDisposed(boolean disposed) {
this.disposed = disposed;
}
}

View File

@ -1,7 +1,7 @@
package com.eu.habbo.core;
public interface Disposable
{
public interface Disposable {
void dispose();
boolean disposed();
}

View File

@ -8,13 +8,10 @@ import com.eu.habbo.messages.outgoing.rooms.users.RoomUserWhisperComposer;
import com.eu.habbo.plugin.EventHandler;
import com.eu.habbo.plugin.events.users.UserSavedMottoEvent;
public class Easter
{
public class Easter {
@EventHandler
public static void onUserChangeMotto(UserSavedMottoEvent event)
{
if(event.newMotto.equalsIgnoreCase("crickey!"))
{
public static void onUserChangeMotto(UserSavedMottoEvent event) {
if (event.newMotto.equalsIgnoreCase("crickey!")) {
event.habbo.getClient().sendResponse(new RoomUserWhisperComposer(new RoomChatMessage(event.newMotto, event.habbo, event.habbo, RoomChatMessageBubbles.ALERT)));
Room room = event.habbo.getHabboInfo().getCurrentRoom();

View File

@ -9,8 +9,7 @@ import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ErrorLog implements Loggable
{
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 buildHash;
@ -19,8 +18,7 @@ public class ErrorLog implements Loggable
public final String type;
public final String stackTrace;
public ErrorLog(String type, Throwable e)
{
public ErrorLog(String type, Throwable e) {
this.version = Emulator.version;
this.buildHash = Emulator.version;
@ -33,18 +31,15 @@ public class ErrorLog implements Loggable
e.printStackTrace(pw);
this.stackTrace = sw.toString();
try
{
try {
pw.close();
sw.close();
} catch (IOException e1)
{
} catch (IOException e1) {
Emulator.getLogging().logErrorLine(e1);
}
}
public ErrorLog(String type, String message)
{
public ErrorLog(String type, String message) {
this.version = Emulator.version;
this.buildHash = Emulator.build;
@ -54,8 +49,7 @@ public class ErrorLog implements Loggable
}
@Override
public void log(PreparedStatement statement) throws SQLException
{
public void log(PreparedStatement statement) throws SQLException {
statement.setInt(1, this.timeStamp);
statement.setString(2, this.version);
statement.setString(3, this.buildHash);

View File

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

View File

@ -13,28 +13,12 @@ import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Logging
{
private static PrintWriter packetsWriter;
private static PrintWriter packetsUndefinedWriter;
private static PrintWriter errorsPacketsWriter;
private static PrintWriter errorsSQLWriter;
private static PrintWriter errorsRuntimeWriter;
private static PrintWriter debugFileWriter;
public class Logging {
public static final String ANSI_BRIGHT = "\u001B[1m";
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";
@ -43,8 +27,12 @@ public class Logging
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);
@ -52,8 +40,7 @@ public class Logging
private ConcurrentSet<Loggable> chatLogs = new ConcurrentSet<>();
public Logging()
{
public Logging() {
File packets = new File("logging//packets//defined.txt");
@ -67,121 +54,101 @@ public class Logging
File debugFile = new File("logging//debug.txt");
try
{
if (!packets.exists())
{
if (!packets.getParentFile().exists())
{
try {
if (!packets.exists()) {
if (!packets.getParentFile().exists()) {
packets.getParentFile().mkdirs();
}
packets.createNewFile();
}
if (!packetsUndefined.exists())
{
if (!packetsUndefined.getParentFile().exists())
{
if (!packetsUndefined.exists()) {
if (!packetsUndefined.getParentFile().exists()) {
packetsUndefined.getParentFile().mkdirs();
}
packetsUndefined.createNewFile();
}
if (!errorsPackets.exists())
{
if (!errorsPackets.getParentFile().exists())
{
if (!errorsPackets.exists()) {
if (!errorsPackets.getParentFile().exists()) {
errorsPackets.getParentFile().mkdirs();
}
errorsPackets.createNewFile();
}
if (!errorsSQL.exists())
{
if (!errorsSQL.getParentFile().exists())
{
if (!errorsSQL.exists()) {
if (!errorsSQL.getParentFile().exists()) {
errorsSQL.getParentFile().mkdirs();
}
errorsSQL.createNewFile();
}
if (!errorsRuntime.exists())
{
if (!errorsRuntime.getParentFile().exists())
{
if (!errorsRuntime.exists()) {
if (!errorsRuntime.getParentFile().exists()) {
errorsRuntime.getParentFile().mkdirs();
}
errorsRuntime.createNewFile();
}
if (!debugFile.exists())
{
if (!debugFile.getParentFile().exists())
{
if (!debugFile.exists()) {
if (!debugFile.getParentFile().exists()) {
debugFile.getParentFile().mkdirs();
}
debugFile.createNewFile();
}
}
catch(Exception e)
{
} catch (Exception e) {
e.printStackTrace();
}
try
{
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)
{
} catch (IOException e) {
System.out.println("[CRITICAL] FAILED TO LOAD LOGGING COMPONENT!");
}
}
public static PrintWriter getPacketsWriter() {
return packetsWriter;
}
public void logStart(Object line)
{
public static PrintWriter getPacketsUndefinedWriter() {
return packetsUndefinedWriter;
}
public void logStart(Object line) {
System.out.println("[" + Logging.ANSI_BRIGHT + Logging.ANSI_GREEN + "LOADING" + Logging.ANSI_RESET + "] " + line.toString());
}
public void logShutdownLine(Object line)
{
if(Emulator.getConfig().getBoolean("logging.debug"))
{
public void logShutdownLine(Object line) {
if (Emulator.getConfig().getBoolean("logging.debug")) {
this.write(debugFileWriter, line.toString());
}
System.out.println("[" + Logging.ANSI_BRIGHT + Logging.ANSI_GREEN + "SHUTDOWN" + Logging.ANSI_RESET + "] " + line.toString());
}
public void logUserLine(Object line)
{
if(Emulator.getConfig().getBoolean("logging.debug"))
{
public void logUserLine(Object line) {
if (Emulator.getConfig().getBoolean("logging.debug")) {
this.write(debugFileWriter, line.toString());
}
if (Emulator.getConfig().getBoolean("debug.show.users"))
{
if (Emulator.getConfig().getBoolean("debug.show.users")) {
System.out.println("[USER] " + line.toString());
}
}
public synchronized void logDebugLine(Object line)
{
if (line instanceof Throwable)
{
public synchronized void logDebugLine(Object line) {
if (line instanceof Throwable) {
this.logErrorLine(line);
return;
}
@ -189,54 +156,43 @@ public class Logging
System.out.println("[DEBUG] " + line.toString());
}
if(Emulator.getConfig().getBoolean("logging.debug"))
{
if (Emulator.getConfig().getBoolean("logging.debug")) {
this.write(debugFileWriter, line.toString());
}
}
public synchronized void logPacketLine(Object line)
{
public synchronized void logPacketLine(Object line) {
if (Emulator.getConfig().getBoolean("debug.show.packets")) {
System.out.println("[" + Logging.ANSI_BLUE + "PACKET" + Logging.ANSI_RESET + "]" + line.toString());
}
if(Emulator.getConfig().getBoolean("logging.packets"))
{
if (Emulator.getConfig().getBoolean("logging.packets")) {
this.write(packetsWriter, line.toString());
}
}
public synchronized void logUndefinedPacketLine(Object line)
{
if (Emulator.getConfig().getBoolean("debug.show.packets.undefined"))
{
public synchronized void logUndefinedPacketLine(Object line) {
if (Emulator.getConfig().getBoolean("debug.show.packets.undefined")) {
System.out.println("[PACKET] [UNDEFINED] " + line.toString());
}
if (Emulator.getConfig().getBoolean("logging.packets.undefined"))
{
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"))
{
public synchronized void logErrorLine(Object line) {
if (Emulator.isReady && Emulator.getConfig().getBoolean("debug.show.errors")) {
System.err.println("[ERROR] " + line.toString());
}
if (Emulator.getConfig().loaded && Emulator.getConfig().getBoolean("logging.errors.runtime"))
{
if (Emulator.getConfig().loaded && Emulator.getConfig().getBoolean("logging.errors.runtime")) {
this.write(errorsRuntimeWriter, line);
}
if(line instanceof Throwable)
{
if (line instanceof Throwable) {
((Throwable) line).printStackTrace();
if (line instanceof SQLException)
{
if (line instanceof SQLException) {
this.logSQLException((SQLException) line);
return;
}
@ -250,10 +206,8 @@ public class Logging
this.errorLogs.add(new ErrorLog("Emulator", line.toString()));
}
public void logSQLException(SQLException e)
{
if(Emulator.getConfig().getBoolean("logging.errors.sql"))
{
public void logSQLException(SQLException e) {
if (Emulator.getConfig().getBoolean("logging.errors.sql")) {
e.printStackTrace();
this.write(errorsSQLWriter, e);
@ -261,21 +215,17 @@ public class Logging
}
}
public void logPacketError(Object e)
{
if(Emulator.getConfig().getBoolean("logging.errors.packets"))
{
if(e instanceof Throwable)
public void logPacketError(Object e) {
if (Emulator.getConfig().getBoolean("logging.errors.packets")) {
if (e instanceof Throwable)
((Exception) e).printStackTrace();
this.write(errorsPacketsWriter, e);
}
if(e instanceof Throwable)
{
if (e instanceof Throwable) {
((Throwable) e).printStackTrace();
if (e instanceof SQLException)
{
if (e instanceof SQLException) {
this.logSQLException((SQLException) e);
return;
}
@ -284,21 +234,15 @@ public class Logging
}
}
public void handleException(Exception e)
{
public void handleException(Exception e) {
e.printStackTrace();
}
private synchronized void write(PrintWriter printWriter, Object message)
{
if(printWriter != null && message != null)
{
if(message instanceof Throwable)
{
private synchronized void write(PrintWriter printWriter, Object message) {
if (printWriter != null && message != null) {
if (message instanceof Throwable) {
((Exception) message).printStackTrace(printWriter);
}
else
{
} else {
printWriter.write("MSG: " + message.toString() + "\r\n");
}
@ -306,45 +250,30 @@ public class Logging
}
}
public void addLog(Loggable log)
{
if (log instanceof ErrorLog)
{
synchronized (this.errorLogs)
{
public void addLog(Loggable log) {
if (log instanceof ErrorLog) {
synchronized (this.errorLogs) {
this.errorLogs.add(log);
}
}
else if (log instanceof CommandLog)
{
synchronized (this.commandLogs)
{
} else if (log instanceof CommandLog) {
synchronized (this.commandLogs) {
this.commandLogs.add(log);
}
}
}
public void addChatLog(Loggable chatLog)
{
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)
{
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();
@ -353,14 +282,10 @@ public class Logging
}
}
if (!this.commandLogs.isEmpty())
{
synchronized (this.commandLogs)
{
try (PreparedStatement statement = connection.prepareStatement(CommandLog.insertQuery))
{
for (Loggable log : this.commandLogs)
{
if (!this.commandLogs.isEmpty()) {
synchronized (this.commandLogs) {
try (PreparedStatement statement = connection.prepareStatement(CommandLog.insertQuery)) {
for (Loggable log : this.commandLogs) {
log.log(statement);
}
@ -370,15 +295,12 @@ public class Logging
}
}
if (!this.chatLogs.isEmpty())
{
if (!this.chatLogs.isEmpty()) {
ConcurrentSet<Loggable> chatLogs = this.chatLogs;
this.chatLogs = new ConcurrentSet<>();
try (PreparedStatement statement = connection.prepareStatement(RoomChatMessage.insertQuery))
{
for (Loggable log : chatLogs)
{
try (PreparedStatement statement = connection.prepareStatement(RoomChatMessage.insertQuery)) {
for (Loggable log : chatLogs) {
log.log(statement);
}
@ -386,24 +308,12 @@ public class Logging
}
chatLogs.clear();
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
}
}
public static PrintWriter getPacketsWriter()
{
return packetsWriter;
}
public static PrintWriter getPacketsUndefinedWriter()
{
return packetsUndefinedWriter;
}
/*
public static PrintWriter getErrorsPacketsWriter()
{

View File

@ -5,8 +5,7 @@ import com.eu.habbo.habbohotel.users.Habbo;
import java.util.Map;
public class PixelScheduler extends Scheduler
{
public class PixelScheduler extends Scheduler {
public static boolean IGNORE_HOTEL_VIEW;
@ -16,15 +15,37 @@ public class PixelScheduler extends Scheduler
private static int PIXELS;
public PixelScheduler()
{
public PixelScheduler() {
super(Emulator.getConfig().getInt("hotel.auto.pixels.interval"));
this.reloadConfig();
}
public static boolean isIgnoreHotelView() {
return IGNORE_HOTEL_VIEW;
}
public static void setIgnoreHotelView(boolean ignoreHotelView) {
IGNORE_HOTEL_VIEW = ignoreHotelView;
}
public static boolean isIgnoreIdled() {
return IGNORE_IDLED;
}
public static void setIgnoreIdled(boolean ignoreIdled) {
IGNORE_IDLED = ignoreIdled;
}
public static int getPIXELS() {
return PIXELS;
}
public static void setPIXELS(int PIXELS) {
PixelScheduler.PIXELS = PIXELS;
}
public void reloadConfig() {
if(Emulator.getConfig().getBoolean("hotel.auto.pixels.enabled"))
{
if (Emulator.getConfig().getBoolean("hotel.auto.pixels.enabled")) {
IGNORE_HOTEL_VIEW = Emulator.getConfig().getBoolean("hotel.auto.pixels.ignore.hotelview");
IGNORE_IDLED = Emulator.getConfig().getBoolean("hotel.auto.pixels.ignore.idled");
PIXELS = Emulator.getConfig().getInt("hotel.auto.pixels.amount");
@ -32,27 +53,21 @@ public class PixelScheduler extends Scheduler
this.disposed = false;
this.run();
}
}
else
{
} else {
this.disposed = true;
}
}
@Override
public void run()
{
public void run() {
super.run();
Habbo habbo;
for(Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet())
{
for (Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) {
habbo = map.getValue();
try
{
if (habbo != null)
{
try {
if (habbo != null) {
if (habbo.getHabboInfo().getCurrentRoom() == null && IGNORE_HOTEL_VIEW)
continue;
@ -61,51 +76,17 @@ public class PixelScheduler extends Scheduler
habbo.givePixels(PIXELS);
}
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
}
}
public static boolean isIgnoreHotelView()
{
return IGNORE_HOTEL_VIEW;
}
public static void setIgnoreHotelView(boolean ignoreHotelView)
{
IGNORE_HOTEL_VIEW = ignoreHotelView;
}
public static boolean isIgnoreIdled()
{
return IGNORE_IDLED;
}
public static void setIgnoreIdled(boolean ignoreIdled)
{
IGNORE_IDLED = ignoreIdled;
}
public static int getPIXELS()
{
return PIXELS;
}
public static void setPIXELS(int PIXELS)
{
PixelScheduler.PIXELS = PIXELS;
}
public boolean isDisposed()
{
public boolean isDisposed() {
return this.disposed;
}
public void setDisposed(boolean disposed)
{
public void setDisposed(boolean disposed) {
this.disposed = disposed;
}
}

View File

@ -5,8 +5,7 @@ import com.eu.habbo.habbohotel.users.Habbo;
import java.util.Map;
public class PointsScheduler extends Scheduler
{
public class PointsScheduler extends Scheduler {
public static boolean IGNORE_HOTEL_VIEW;
@ -16,15 +15,37 @@ public class PointsScheduler extends Scheduler
private static int POINTS;
public PointsScheduler()
{
public PointsScheduler() {
super(Emulator.getConfig().getInt("hotel.auto.points.interval"));
this.reloadConfig();
}
public static boolean isIgnoreHotelView() {
return IGNORE_HOTEL_VIEW;
}
public static void setIgnoreHotelView(boolean ignoreHotelView) {
IGNORE_HOTEL_VIEW = ignoreHotelView;
}
public static boolean isIgnoreIdled() {
return IGNORE_IDLED;
}
public static void setIgnoreIdled(boolean ignoreIdled) {
IGNORE_IDLED = ignoreIdled;
}
public static int getPOINTS() {
return POINTS;
}
public static void setPOINTS(int POINTS) {
PointsScheduler.POINTS = POINTS;
}
public void reloadConfig() {
if(Emulator.getConfig().getBoolean("hotel.auto.points.enabled"))
{
if (Emulator.getConfig().getBoolean("hotel.auto.points.enabled")) {
IGNORE_HOTEL_VIEW = Emulator.getConfig().getBoolean("hotel.auto.points.ignore.hotelview");
IGNORE_IDLED = Emulator.getConfig().getBoolean("hotel.auto.points.ignore.idled");
POINTS = Emulator.getConfig().getInt("hotel.auto.points.amount");
@ -32,27 +53,21 @@ public class PointsScheduler extends Scheduler
this.disposed = false;
this.run();
}
}
else
{
} else {
this.disposed = true;
}
}
@Override
public void run()
{
public void run() {
super.run();
Habbo habbo;
for(Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet())
{
for (Map.Entry<Integer, Habbo> map : Emulator.getGameEnvironment().getHabboManager().getOnlineHabbos().entrySet()) {
habbo = map.getValue();
try
{
if (habbo != null)
{
try {
if (habbo != null) {
if (habbo.getHabboInfo().getCurrentRoom() == null && IGNORE_HOTEL_VIEW)
continue;
@ -61,51 +76,17 @@ public class PointsScheduler extends Scheduler
habbo.givePoints(POINTS);
}
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
}
}
public static boolean isIgnoreHotelView()
{
return IGNORE_HOTEL_VIEW;
}
public static void setIgnoreHotelView(boolean ignoreHotelView)
{
IGNORE_HOTEL_VIEW = ignoreHotelView;
}
public static boolean isIgnoreIdled()
{
return IGNORE_IDLED;
}
public static void setIgnoreIdled(boolean ignoreIdled)
{
IGNORE_IDLED = ignoreIdled;
}
public static int getPOINTS()
{
return POINTS;
}
public static void setPOINTS(int POINTS)
{
PointsScheduler.POINTS = POINTS;
}
public boolean isDisposed()
{
public boolean isDisposed() {
return this.disposed;
}
public void setDisposed(boolean disposed)
{
public void setDisposed(boolean disposed) {
this.disposed = disposed;
}
}

View File

@ -5,15 +5,13 @@ import com.eu.habbo.messages.ServerMessage;
import com.eu.habbo.messages.outgoing.MessageComposer;
import com.eu.habbo.messages.outgoing.Outgoing;
public class RoomUserPetComposer extends MessageComposer
{
public class RoomUserPetComposer extends MessageComposer {
private final int petType;
private final int race;
private final String color;
private final Habbo habbo;
public RoomUserPetComposer(int petType, int race, String color, Habbo habbo)
{
public RoomUserPetComposer(int petType, int race, String color, Habbo habbo) {
this.petType = petType;
this.race = race;
this.color = color;
@ -21,8 +19,7 @@ public class RoomUserPetComposer extends MessageComposer
}
@Override
public ServerMessage compose()
{
public ServerMessage compose() {
this.response.init(Outgoing.RoomUsersComposer);
this.response.appendInt(1);
this.response.appendInt(this.habbo.getHabboInfo().getId());

View File

@ -2,39 +2,32 @@ package com.eu.habbo.core;
import com.eu.habbo.Emulator;
public class Scheduler implements Runnable
{
public class Scheduler implements Runnable {
protected boolean disposed;
protected int interval;
public Scheduler(int interval)
{
public Scheduler(int interval) {
this.interval = interval;
}
public boolean isDisposed()
{
public boolean isDisposed() {
return this.disposed;
}
public void setDisposed(boolean disposed)
{
public void setDisposed(boolean disposed) {
this.disposed = disposed;
}
public int getInterval()
{
public int getInterval() {
return this.interval;
}
public void setInterval(int interval)
{
public void setInterval(int interval) {
this.interval = interval;
}
@Override
public void run()
{
public void run() {
if (this.disposed)
return;

View File

@ -5,62 +5,47 @@ import com.eu.habbo.Emulator;
import java.sql.*;
import java.util.Properties;
public class TextsManager
{
public class TextsManager {
private final Properties texts;
public TextsManager()
{
public TextsManager() {
long millis = System.currentTimeMillis();
this.texts = new Properties();
try
{
try {
this.reload();
Emulator.getLogging().logStart("Texts Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
}
catch (Exception e)
{
} catch (Exception e) {
e.printStackTrace();
}
}
public void reload() throws Exception
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM emulator_texts"))
{
while(set.next())
{
if(this.texts.containsKey(set.getString("key")))
{
public void reload() throws Exception {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM emulator_texts")) {
while (set.next()) {
if (this.texts.containsKey(set.getString("key"))) {
this.texts.setProperty(set.getString("key"), set.getString("value"));
}
else
{
} else {
this.texts.put(set.getString("key"), set.getString("value"));
}
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
public String getValue(String key)
{
public String getValue(String key) {
return this.getValue(key, "");
}
public String getValue(String key, String defaultValue)
{
public String getValue(String key, String defaultValue) {
if (!this.texts.containsKey(key)) {
Emulator.getLogging().logErrorLine("[TEXTS] Text key not found: " + key);
}
@ -68,64 +53,49 @@ public class TextsManager
}
public boolean getBoolean(String key)
{
public boolean getBoolean(String key) {
return this.getBoolean(key, false);
}
public boolean getBoolean(String key, Boolean defaultValue)
{
try
{
public boolean getBoolean(String key, Boolean defaultValue) {
try {
return (this.getValue(key, "0").equals("1")) || (this.getValue(key, "false").equals("true"));
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
return defaultValue;
}
public int getInt(String key)
{
public int getInt(String key) {
return this.getInt(key, 0);
}
public int getInt(String key, Integer defaultValue)
{
try
{
public int getInt(String key, Integer defaultValue) {
try {
return Integer.parseInt(this.getValue(key, defaultValue.toString()));
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
return defaultValue;
}
public void update(String key, String value)
{
public void update(String key, String value) {
this.texts.setProperty(key, value);
}
public void register(String key, String value)
{
public void register(String key, String value) {
if (this.texts.getProperty(key, null) != null)
return;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO emulator_texts VALUES (?, ?)"))
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO emulator_texts VALUES (?, ?)")) {
statement.setString(1, key);
statement.setString(2, value);
statement.execute();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}

View File

@ -3,8 +3,7 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator;
import gnu.trove.map.hash.THashMap;
public abstract class ConsoleCommand
{
public abstract class ConsoleCommand {
private static final THashMap<String, ConsoleCommand> commands = new THashMap<>();
@ -15,15 +14,13 @@ public abstract class ConsoleCommand
public final String usage;
public ConsoleCommand(String key, String usage)
{
public ConsoleCommand(String key, String usage) {
this.key = key;
this.usage = usage;
}
public static void load()
{
public static void load() {
addCommand(new ConsoleShutdownCommand());
addCommand(new ConsoleInfoCommand());
addCommand(new ConsoleTestCommand());
@ -32,49 +29,32 @@ public abstract class ConsoleCommand
addCommand(new ShowRCONCommands());
}
public abstract void handle(String[] args) throws Exception;
public static void addCommand(ConsoleCommand command)
{
public static void addCommand(ConsoleCommand command) {
commands.put(command.key, command);
}
public static ConsoleCommand findCommand(String key)
{
public static ConsoleCommand findCommand(String key) {
return commands.get(key);
}
public static boolean handle(String line)
{
public static boolean handle(String line) {
String[] message = line.split(" ");
if (message.length > 0)
{
if (message.length > 0) {
ConsoleCommand command = ConsoleCommand.findCommand(message[0]);
if (command != null)
{
try
{
if (command != null) {
try {
command.handle(message);
return true;
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
}
else
{
} else {
System.out.println("Unknown Console Command " + message[0]);
System.out.println("Commands Available (" + commands.size() + "): ");
for (ConsoleCommand c : commands.values())
{
for (ConsoleCommand c : commands.values()) {
System.out.println(c.key + " - " + c.usage);
}
}
@ -82,4 +62,6 @@ public abstract class ConsoleCommand
return false;
}
public abstract void handle(String[] args) throws Exception;
}

View File

@ -5,21 +5,18 @@ import com.eu.habbo.habbohotel.catalog.CatalogManager;
import java.util.concurrent.TimeUnit;
public class ConsoleInfoCommand extends ConsoleCommand
{
public ConsoleInfoCommand()
{
public class ConsoleInfoCommand extends ConsoleCommand {
public ConsoleInfoCommand() {
super("info", "Show current statistics.");
}
@Override
public void handle(String[] args) throws Exception
{
public void handle(String[] args) throws Exception {
int seconds = Emulator.getIntUnixTimestamp() - Emulator.getTimeStarted();
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60);
System.out.println("Emulator version: " + Emulator.version);
System.out.println("Emulator build: " + Emulator.build);

View File

@ -2,16 +2,13 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.networking.camera.CameraClient;
public class ConsoleReconnectCameraCommand extends ConsoleCommand
{
public ConsoleReconnectCameraCommand()
{
public class ConsoleReconnectCameraCommand extends ConsoleCommand {
public ConsoleReconnectCameraCommand() {
super("camera", "Attempt to reconnect to the camera server.");
}
@Override
public void handle(String[] args) throws Exception
{
public void handle(String[] args) throws Exception {
System.out.println("Connecting to the camera...");
CameraClient.attemptReconnect = true;
}

View File

@ -2,16 +2,13 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.habbohotel.commands.ShutdownCommand;
public class ConsoleShutdownCommand extends ConsoleCommand
{
public ConsoleShutdownCommand()
{
public class ConsoleShutdownCommand extends ConsoleCommand {
public ConsoleShutdownCommand() {
super("stop", "Stop the emulator.");
}
@Override
public void handle(String[] args) throws Exception
{
public void handle(String[] args) throws Exception {
new ShutdownCommand().handle(null, args);
}
}

View File

@ -4,23 +4,17 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.users.Habbo;
public class ConsoleTestCommand extends ConsoleCommand
{
public ConsoleTestCommand()
{
public class ConsoleTestCommand extends ConsoleCommand {
public ConsoleTestCommand() {
super("test", "This is just a test.");
}
@Override
public void handle(String[] args) throws Exception
{
if (Emulator.debugging)
{
public void handle(String[] args) throws Exception {
if (Emulator.debugging) {
System.out.println("This is a test command for live debugging.");
//AchievementManager.progressAchievement(4, Emulator.getGameEnvironment().getAchievementManager().getAchievement("AllTimeHotelPresence"), 30);
Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(1);
habbo.getHabboInfo().getMachineID();

View File

@ -2,18 +2,14 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator;
public class ShowInteractionsCommand extends ConsoleCommand
{
public ShowInteractionsCommand()
{
public class ShowInteractionsCommand extends ConsoleCommand {
public ShowInteractionsCommand() {
super("interactions", "Show a list of available furniture interactions.");
}
@Override
public void handle(String[] args) throws Exception
{
for (String interaction : Emulator.getGameEnvironment().getItemManager().getInteractionList())
{
public void handle(String[] args) throws Exception {
for (String interaction : Emulator.getGameEnvironment().getItemManager().getInteractionList()) {
System.out.println(interaction);
}
}

View File

@ -2,18 +2,14 @@ package com.eu.habbo.core.consolecommands;
import com.eu.habbo.Emulator;
public class ShowRCONCommands extends ConsoleCommand
{
public ShowRCONCommands()
{
public class ShowRCONCommands extends ConsoleCommand {
public ShowRCONCommands() {
super("rconcommands", "Show a list of all RCON commands");
}
@Override
public void handle(String[] args) throws Exception
{
for (String command : Emulator.getRconServer().getCommands())
{
public void handle(String[] args) throws Exception {
for (String command : Emulator.getRconServer().getCommands()) {
System.out.println(command);
}
}

View File

@ -4,41 +4,33 @@ import com.eu.habbo.Emulator;
import com.eu.habbo.core.ConfigurationManager;
import com.zaxxer.hikari.HikariDataSource;
public class Database
{
public class Database {
private HikariDataSource dataSource;
private DatabasePool databasePool;
public Database(ConfigurationManager config)
{
public Database(ConfigurationManager config) {
long millis = System.currentTimeMillis();
boolean SQLException = false;
try
{
try {
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...");
SQLException = true;
return;
}
this.dataSource = this.databasePool.getDatabase();
}
catch (Exception e)
{
} catch (Exception e) {
SQLException = true;
e.printStackTrace();
Emulator.getLogging().logStart("Failed to connect to your database.");
Emulator.getLogging().logStart(e.getMessage());
}
finally
{
} finally {
if (SQLException)
Emulator.prepareShutdown();
}
@ -47,23 +39,19 @@ public class Database
}
public void dispose()
{
if (this.databasePool != null)
{
public void dispose() {
if (this.databasePool != null) {
this.databasePool.getDatabase().close();
}
this.dataSource.close();
}
public HikariDataSource getDataSource()
{
public HikariDataSource getDataSource() {
return this.dataSource;
}
public DatabasePool getDatabasePool()
{
public DatabasePool getDatabasePool() {
return this.databasePool;
}
}

View File

@ -1,21 +1,17 @@
package com.eu.habbo.database;
import com.eu.habbo.core.ConfigurationManager;
import com.eu.habbo.core.Logging;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class DatabasePool
{
class DatabasePool {
private final Logger log = LoggerFactory.getLogger(DatabasePool.class);
private HikariDataSource database;
public boolean getStoragePooling(ConfigurationManager config)
{
try
{
public boolean getStoragePooling(ConfigurationManager config) {
try {
HikariConfig databaseConfiguration = new HikariConfig();
databaseConfiguration.setMaximumPoolSize(config.getInt("db.pool.maxsize", 50));
databaseConfiguration.setMinimumIdle(config.getInt("db.pool.minsize", 10));
@ -34,7 +30,7 @@ class DatabasePool
databaseConfiguration.addDataSourceProperty("cachePrepStmts", "true");
databaseConfiguration.addDataSourceProperty("useServerPrepStmts", "true");
databaseConfiguration.addDataSourceProperty("rewriteBatchedStatements", "true");
databaseConfiguration.addDataSourceProperty("useUnicode","true");
databaseConfiguration.addDataSourceProperty("useUnicode", "true");
databaseConfiguration.setAutoCommit(true);
databaseConfiguration.setConnectionTimeout(300000L);
databaseConfiguration.setValidationTimeout(5000L);
@ -43,16 +39,13 @@ class DatabasePool
databaseConfiguration.setIdleTimeout(600000L);
//databaseConfiguration.setDriverClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
this.database = new HikariDataSource(databaseConfiguration);
}
catch (Exception e)
{
} catch (Exception e) {
return false;
}
return true;
}
public HikariDataSource getDatabase()
{
public HikariDataSource getDatabase() {
return this.database;
}
}

View File

@ -22,8 +22,10 @@ import com.eu.habbo.habbohotel.polls.PollManager;
import com.eu.habbo.habbohotel.rooms.RoomManager;
import com.eu.habbo.habbohotel.users.HabboManager;
public class GameEnvironment
{
public class GameEnvironment {
public CreditsScheduler creditsScheduler;
public PixelScheduler pixelScheduler;
public PointsScheduler pointsScheduler;
private HabboManager habboManager;
private NavigatorManager navigatorManager;
private GuildManager guildManager;
@ -42,12 +44,7 @@ public class GameEnvironment
private CraftingManager craftingManager;
private PollManager pollManager;
public CreditsScheduler creditsScheduler;
public PixelScheduler pixelScheduler;
public PointsScheduler pointsScheduler;
public void load() throws Exception
{
public void load() throws Exception {
Emulator.getLogging().logStart("GameEnvironment -> Loading...");
this.permissionsManager = new PermissionsManager();
@ -83,8 +80,7 @@ public class GameEnvironment
Emulator.getLogging().logStart("GameEnvironment -> Loaded!");
}
public void dispose()
{
public void dispose() {
this.pointsScheduler.setDisposed(true);
this.pixelScheduler.setDisposed(true);
this.creditsScheduler.setDisposed(true);
@ -99,88 +95,71 @@ public class GameEnvironment
Emulator.getLogging().logShutdownLine("GameEnvironment -> Disposed!");
}
public HabboManager getHabboManager()
{
public HabboManager getHabboManager() {
return this.habboManager;
}
public NavigatorManager getNavigatorManager()
{
public NavigatorManager getNavigatorManager() {
return this.navigatorManager;
}
public GuildManager getGuildManager()
{
public GuildManager getGuildManager() {
return this.guildManager;
}
public ItemManager getItemManager()
{
public ItemManager getItemManager() {
return this.itemManager;
}
public CatalogManager getCatalogManager()
{
public CatalogManager getCatalogManager() {
return this.catalogManager;
}
public HotelViewManager getHotelViewManager()
{
public HotelViewManager getHotelViewManager() {
return this.hotelViewManager;
}
public RoomManager getRoomManager()
{
public RoomManager getRoomManager() {
return this.roomManager;
}
public CommandHandler getCommandHandler()
{
public CommandHandler getCommandHandler() {
return this.commandHandler;
}
public PermissionsManager getPermissionsManager()
{
public PermissionsManager getPermissionsManager() {
return this.permissionsManager;
}
public BotManager getBotManager()
{
public BotManager getBotManager() {
return this.botManager;
}
public ModToolManager getModToolManager()
{
public ModToolManager getModToolManager() {
return this.modToolManager;
}
public PetManager getPetManager()
{
public PetManager getPetManager() {
return this.petManager;
}
public AchievementManager getAchievementManager()
{
public AchievementManager getAchievementManager() {
return this.achievementManager;
}
public GuideManager getGuideManager()
{
public GuideManager getGuideManager() {
return this.guideManager;
}
public WordFilter getWordFilter()
{
public WordFilter getWordFilter() {
return this.wordFilter;
}
public CraftingManager getCraftingManager()
{
public CraftingManager getCraftingManager() {
return this.craftingManager;
}
public PollManager getPollManager()
{
public PollManager getPollManager() {
return this.pollManager;
}

View File

@ -5,8 +5,7 @@ import gnu.trove.map.hash.THashMap;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Achievement
{
public class Achievement {
public final int id;
@ -20,8 +19,7 @@ public class Achievement
public final THashMap<Integer, AchievementLevel> levels;
public Achievement(ResultSet set) throws SQLException
{
public Achievement(ResultSet set) throws SQLException {
this.levels = new THashMap<>();
this.id = set.getInt("id");
@ -32,28 +30,20 @@ public class Achievement
}
public void addLevel(AchievementLevel level)
{
synchronized (this.levels)
{
public void addLevel(AchievementLevel level) {
synchronized (this.levels) {
this.levels.put(level.level, level);
}
}
public AchievementLevel getLevelForProgress(int progress)
{
public AchievementLevel getLevelForProgress(int progress) {
AchievementLevel l = null;
if (progress > 0)
{
for (AchievementLevel level : this.levels.values())
{
if (progress >= level.progress)
{
if (l != null)
{
if (l.level > level.level)
{
if (progress > 0) {
for (AchievementLevel level : this.levels.values()) {
if (progress >= level.progress) {
if (l != null) {
if (l.level > level.level) {
continue;
}
}
@ -66,26 +56,22 @@ public class Achievement
}
public AchievementLevel getNextLevel(int currentLevel)
{
public AchievementLevel getNextLevel(int currentLevel) {
AchievementLevel l = null;
for(AchievementLevel level : this.levels.values())
{
if(level.level == (currentLevel + 1))
for (AchievementLevel level : this.levels.values()) {
if (level.level == (currentLevel + 1))
return level;
}
return null;
}
public AchievementLevel firstLevel()
{
public AchievementLevel firstLevel() {
return this.levels.get(1);
}
public void clearLevels()
{
public void clearLevels() {
this.levels.clear();
}
}

View File

@ -1,7 +1,6 @@
package com.eu.habbo.habbohotel.achievements;
public enum AchievementCategories
{
public enum AchievementCategories {
IDENTITY,

View File

@ -3,8 +3,7 @@ package com.eu.habbo.habbohotel.achievements;
import java.sql.ResultSet;
import java.sql.SQLException;
public class AchievementLevel
{
public class AchievementLevel {
public final int level;
@ -20,8 +19,7 @@ public class AchievementLevel
public final int progress;
public AchievementLevel(ResultSet set) throws SQLException
{
public AchievementLevel(ResultSet set) throws SQLException {
this.level = set.getInt("level");
this.rewardAmount = set.getInt("reward_amount");
this.rewardType = set.getInt("reward_type");

View File

@ -23,8 +23,7 @@ import java.sql.*;
import java.util.LinkedHashMap;
import java.util.Map;
public class AchievementManager
{
public class AchievementManager {
public static boolean TALENTTRACK_ENABLED = false;
@ -33,154 +32,43 @@ public class AchievementManager
private final THashMap<TalentTrackType, LinkedHashMap<Integer, TalentTrackLevel>> talentTrackLevels;
public AchievementManager()
{
public AchievementManager() {
this.achievements = new THashMap<>();
this.talentTrackLevels = new THashMap<>();
}
public void reload()
{
long millis = System.currentTimeMillis();
synchronized (this.achievements)
{
for (Achievement achievement : this.achievements.values())
{
achievement.clearLevels();
}
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection())
{
try (Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM achievements"))
{
while (set.next())
{
if (!this.achievements.containsKey(set.getString("name")))
{
this.achievements.put(set.getString("name"), new Achievement(set));
}
else
{
this.achievements.get(set.getString("name")).addLevel(new AchievementLevel(set));
}
}
}
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e);
}
catch (Exception e)
{
Emulator.getLogging().logErrorLine(e);
}
synchronized (this.talentTrackLevels)
{
this.talentTrackLevels.clear();
try (Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM achievements_talents ORDER BY level ASC"))
{
while (set.next())
{
TalentTrackLevel level = new TalentTrackLevel(set);
if (!this.talentTrackLevels.containsKey(level.type))
{
this.talentTrackLevels.put(level.type, new LinkedHashMap<>());
}
this.talentTrackLevels.get(level.type).put(level.level, level);
}
}
}
}
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e);
Emulator.getLogging().logErrorLine("Achievement Manager -> Failed to load!");
return;
}
}
Emulator.getLogging().logStart("Achievement Manager -> Loaded! ("+(System.currentTimeMillis() - millis)+" MS)");
}
public Achievement getAchievement(String name)
{
return this.achievements.get(name);
}
public Achievement getAchievement(int id)
{
synchronized (this.achievements)
{
for (Map.Entry<String, Achievement> set : this.achievements.entrySet())
{
if (set.getValue().id == id)
{
return set.getValue();
}
}
}
return null;
}
public THashMap<String, Achievement> getAchievements()
{
return this.achievements;
}
public static void progressAchievement(int habboId, Achievement achievement)
{
public static void progressAchievement(int habboId, Achievement achievement) {
progressAchievement(habboId, achievement, 1);
}
public static void progressAchievement(int habboId, Achievement achievement, int amount)
{
if (achievement != null)
{
public static void progressAchievement(int habboId, Achievement achievement, int amount) {
if (achievement != null) {
Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(habboId);
if (habbo != null)
{
if (habbo != null) {
progressAchievement(habbo, achievement, amount);
}
else
{
} else {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection();
PreparedStatement statement = connection.prepareStatement("" +
"INSERT INTO users_achievements_queue (user_id, achievement_id, amount) VALUES (?, ?, ?) " +
"ON DUPLICATE KEY UPDATE amount = amount + ?"))
{
"ON DUPLICATE KEY UPDATE amount = amount + ?")) {
statement.setInt(1, habboId);
statement.setInt(2, achievement.id);
statement.setInt(3, amount);
statement.setInt(4, amount);
statement.execute();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
}
}
public static void progressAchievement(Habbo habbo, Achievement achievement)
{
public static void progressAchievement(Habbo habbo, Achievement achievement) {
progressAchievement(habbo, achievement, 1);
}
public static void progressAchievement(Habbo habbo, Achievement achievement, int amount)
{
public static void progressAchievement(Habbo habbo, Achievement achievement, int amount) {
if (achievement == null)
return;
@ -192,41 +80,34 @@ public class AchievementManager
int currentProgress = habbo.getHabboStats().getAchievementProgress(achievement);
if(currentProgress == -1)
{
if (currentProgress == -1) {
currentProgress = 0;
createUserEntry(habbo, achievement);
habbo.getHabboStats().setProgress(achievement, 0);
}
if(Emulator.getPluginManager().isRegistered(UserAchievementProgressEvent.class, true))
{
if (Emulator.getPluginManager().isRegistered(UserAchievementProgressEvent.class, true)) {
Event userAchievementProgressedEvent = new UserAchievementProgressEvent(habbo, achievement, amount);
Emulator.getPluginManager().fireEvent(userAchievementProgressedEvent);
if(userAchievementProgressedEvent.isCancelled())
if (userAchievementProgressedEvent.isCancelled())
return;
}
AchievementLevel oldLevel = achievement.getLevelForProgress(currentProgress);
if(oldLevel != null && (oldLevel.level == achievement.levels.size() && currentProgress >= oldLevel.progress)) //Maximum achievement gotten.
if (oldLevel != null && (oldLevel.level == achievement.levels.size() && currentProgress >= oldLevel.progress)) //Maximum achievement gotten.
return;
habbo.getHabboStats().setProgress(achievement, currentProgress + amount);
AchievementLevel newLevel = achievement.getLevelForProgress(currentProgress + amount);
if (AchievementManager.TALENTTRACK_ENABLED)
{
for (TalentTrackType type : TalentTrackType.values())
{
if (Emulator.getGameEnvironment().getAchievementManager().talentTrackLevels.containsKey(type))
{
for (Map.Entry<Integer, TalentTrackLevel> entry : Emulator.getGameEnvironment().getAchievementManager().talentTrackLevels.get(type).entrySet())
{
if (entry.getValue().achievements.containsKey(achievement))
{
if (AchievementManager.TALENTTRACK_ENABLED) {
for (TalentTrackType type : TalentTrackType.values()) {
if (Emulator.getGameEnvironment().getAchievementManager().talentTrackLevels.containsKey(type)) {
for (Map.Entry<Integer, TalentTrackLevel> entry : Emulator.getGameEnvironment().getAchievementManager().talentTrackLevels.get(type).entrySet()) {
if (entry.getValue().achievements.containsKey(achievement)) {
Emulator.getGameEnvironment().getAchievementManager().handleTalentTrackAchievement(habbo, type, achievement);
break;
}
@ -235,19 +116,15 @@ public class AchievementManager
}
}
if(newLevel == null ||
(oldLevel != null &&(oldLevel.level == newLevel.level && newLevel.level < achievement.levels.size())))
{
if (newLevel == null ||
(oldLevel != null && (oldLevel.level == newLevel.level && newLevel.level < achievement.levels.size()))) {
habbo.getClient().sendResponse(new AchievementProgressComposer(habbo, achievement));
}
else
{
if(Emulator.getPluginManager().isRegistered(UserAchievementLeveledEvent.class, true))
{
} else {
if (Emulator.getPluginManager().isRegistered(UserAchievementLeveledEvent.class, true)) {
Event userAchievementLeveledEvent = new UserAchievementLeveledEvent(habbo, achievement, oldLevel, newLevel);
Emulator.getPluginManager().fireEvent(userAchievementLeveledEvent);
if(userAchievementLeveledEvent.isCancelled())
if (userAchievementLeveledEvent.isCancelled())
return;
}
@ -259,25 +136,20 @@ public class AchievementManager
//the badge would result in an nullpointer exception. This is normal behaviour.
HabboBadge badge = null;
if (oldLevel != null)
{
try
{
if (oldLevel != null) {
try {
badge = habbo.getInventory().getBadgesComponent().getBadge(("ACH_" + achievement.name + oldLevel.level).toLowerCase());
} catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
return;
}
}
if (badge != null)
{
if (badge != null) {
badge.setCode("ACH_" + achievement.name + newLevel.level);
badge.needsInsert(false);
badge.needsUpdate(true);
} else
{
} else {
badge = new HabboBadge(0, "ACH_" + achievement.name + newLevel.level, 0, habbo);
habbo.getClient().sendResponse(new AddUserBadgeComposer(badge));
badge.needsInsert(true);
@ -287,10 +159,8 @@ public class AchievementManager
Emulator.getThreading().run(badge);
if(badge.getSlot() > 0)
{
if(habbo.getHabboInfo().getCurrentRoom() != null)
{
if (badge.getSlot() > 0) {
if (habbo.getHabboInfo().getCurrentRoom() != null) {
habbo.getHabboInfo().getCurrentRoom().sendComposer(new UserBadgesComposer(habbo.getInventory().getBadgesComponent().getWearingBadges(), habbo.getHabboInfo().getId()).compose());
}
}
@ -299,31 +169,26 @@ public class AchievementManager
habbo.getHabboStats().addAchievementScore(newLevel.points);
if (newLevel.rewardAmount > 0)
{
if (newLevel.rewardAmount > 0) {
habbo.givePoints(newLevel.rewardType, newLevel.rewardAmount);
}
if (habbo.getHabboInfo().getCurrentRoom() != null)
{
if (habbo.getHabboInfo().getCurrentRoom() != null) {
habbo.getHabboInfo().getCurrentRoom().sendComposer(new RoomUserDataComposer(habbo).compose());
}
}
}
public static boolean hasAchieved(Habbo habbo, Achievement achievement)
{
public static boolean hasAchieved(Habbo habbo, Achievement achievement) {
int currentProgress = habbo.getHabboStats().getAchievementProgress(achievement);
if(currentProgress == -1)
{
if (currentProgress == -1) {
return false;
}
AchievementLevel level = achievement.getLevelForProgress(currentProgress);
if(level == null)
if (level == null)
return false;
AchievementLevel nextLevel = achievement.levels.get(level.level + 1);
@ -331,83 +196,128 @@ public class AchievementManager
return nextLevel == null && currentProgress >= level.progress;
}
public static void createUserEntry(Habbo habbo, Achievement achievement)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO users_achievements (user_id, achievement_name, progress) VALUES (?, ?, ?)"))
{
public static void createUserEntry(Habbo habbo, Achievement achievement) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO users_achievements (user_id, achievement_name, progress) VALUES (?, ?, ?)")) {
statement.setInt(1, habbo.getHabboInfo().getId());
statement.setString(2, achievement.name);
statement.setInt(3, 1);
statement.execute();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
public static void saveAchievements(Habbo habbo)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_achievements SET progress = ? WHERE achievement_name = ? AND user_id = ? LIMIT 1"))
{
public static void saveAchievements(Habbo habbo) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE users_achievements SET progress = ? WHERE achievement_name = ? AND user_id = ? LIMIT 1")) {
statement.setInt(3, habbo.getHabboInfo().getId());
for(Map.Entry<Achievement, Integer> map : habbo.getHabboStats().getAchievementProgress().entrySet())
{
for (Map.Entry<Achievement, Integer> map : habbo.getHabboStats().getAchievementProgress().entrySet()) {
statement.setInt(1, map.getValue());
statement.setString(2, map.getKey().name);
statement.addBatch();
}
statement.executeBatch();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
public static int getAchievementProgressForHabbo(int userId, Achievement achievement)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT progress FROM users_achievements WHERE user_id = ? AND achievement_name = ? LIMIT 1"))
{
public static int getAchievementProgressForHabbo(int userId, Achievement achievement) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT progress FROM users_achievements WHERE user_id = ? AND achievement_name = ? LIMIT 1")) {
statement.setInt(1, userId);
statement.setString(2, achievement.name);
try (ResultSet set = statement.executeQuery())
{
if (set.next())
{
try (ResultSet set = statement.executeQuery()) {
if (set.next()) {
return set.getInt("progress");
}
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
return 0;
}
public LinkedHashMap<Integer, TalentTrackLevel> getTalenTrackLevels(TalentTrackType type)
{
public void reload() {
long millis = System.currentTimeMillis();
synchronized (this.achievements) {
for (Achievement achievement : this.achievements.values()) {
achievement.clearLevels();
}
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
try (Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM achievements")) {
while (set.next()) {
if (!this.achievements.containsKey(set.getString("name"))) {
this.achievements.put(set.getString("name"), new Achievement(set));
} else {
this.achievements.get(set.getString("name")).addLevel(new AchievementLevel(set));
}
}
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
synchronized (this.talentTrackLevels) {
this.talentTrackLevels.clear();
try (Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM achievements_talents ORDER BY level ASC")) {
while (set.next()) {
TalentTrackLevel level = new TalentTrackLevel(set);
if (!this.talentTrackLevels.containsKey(level.type)) {
this.talentTrackLevels.put(level.type, new LinkedHashMap<>());
}
this.talentTrackLevels.get(level.type).put(level.level, level);
}
}
}
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
Emulator.getLogging().logErrorLine("Achievement Manager -> Failed to load!");
return;
}
}
Emulator.getLogging().logStart("Achievement Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
}
public Achievement getAchievement(String name) {
return this.achievements.get(name);
}
public Achievement getAchievement(int id) {
synchronized (this.achievements) {
for (Map.Entry<String, Achievement> set : this.achievements.entrySet()) {
if (set.getValue().id == id) {
return set.getValue();
}
}
}
return null;
}
public THashMap<String, Achievement> getAchievements() {
return this.achievements;
}
public LinkedHashMap<Integer, TalentTrackLevel> getTalenTrackLevels(TalentTrackType type) {
return this.talentTrackLevels.get(type);
}
public TalentTrackLevel calculateTalenTrackLevel(Habbo habbo, TalentTrackType type)
{
public TalentTrackLevel calculateTalenTrackLevel(Habbo habbo, TalentTrackType type) {
TalentTrackLevel level = null;
for (Map.Entry<Integer, TalentTrackLevel> entry : this.talentTrackLevels.get(type).entrySet())
{
for (Map.Entry<Integer, TalentTrackLevel> entry : this.talentTrackLevels.get(type).entrySet()) {
final boolean[] allCompleted = {true};
entry.getValue().achievements.forEachEntry(new TObjectIntProcedure<Achievement>()
{
entry.getValue().achievements.forEachEntry(new TObjectIntProcedure<Achievement>() {
@Override
public boolean execute(Achievement a, int b)
{
if (habbo.getHabboStats().getAchievementProgress(a) < b)
{
public boolean execute(Achievement a, int b) {
if (habbo.getHabboStats().getAchievementProgress(a) < b) {
allCompleted[0] = false;
}
@ -415,15 +325,11 @@ public class AchievementManager
}
});
if (allCompleted[0])
{
if (level == null || level.level < entry.getValue().level)
{
if (allCompleted[0]) {
if (level == null || level.level < entry.getValue().level) {
level = entry.getValue();
}
}
else
{
} else {
break;
}
}
@ -431,24 +337,17 @@ public class AchievementManager
return level;
}
public void handleTalentTrackAchievement(Habbo habbo, TalentTrackType type, Achievement achievement)
{
public void handleTalentTrackAchievement(Habbo habbo, TalentTrackType type, Achievement achievement) {
TalentTrackLevel currentLevel = this.calculateTalenTrackLevel(habbo, type);
if (currentLevel != null)
{
if (currentLevel.level > habbo.getHabboStats().talentTrackLevel(type))
{
for (int i = habbo.getHabboStats().talentTrackLevel(type); i <= currentLevel.level; i++)
{
if (currentLevel != null) {
if (currentLevel.level > habbo.getHabboStats().talentTrackLevel(type)) {
for (int i = habbo.getHabboStats().talentTrackLevel(type); i <= currentLevel.level; i++) {
TalentTrackLevel level = this.getTalentTrackLevel(type, i);
if (level != null)
{
if (level.items != null && !level.items.isEmpty())
{
for (Item item : level.items)
{
if (level != null) {
if (level.items != null && !level.items.isEmpty()) {
for (Item item : level.items) {
HabboItem rewardItem = Emulator.getGameEnvironment().getItemManager().createItem(habbo.getHabboInfo().getId(), item, 0, 0, "");
habbo.getInventory().getItemsComponent().addItem(rewardItem);
habbo.getClient().sendResponse(new AddHabboItemComposer(rewardItem));
@ -456,12 +355,9 @@ public class AchievementManager
}
}
if (level.badges != null && level.badges.length > 0 )
{
for (String badge : level.badges)
{
if (!badge.isEmpty())
{
if (level.badges != null && level.badges.length > 0) {
for (String badge : level.badges) {
if (!badge.isEmpty()) {
HabboBadge b = new HabboBadge(0, badge, 0, habbo);
Emulator.getThreading().run(b);
habbo.getInventory().getBadgesComponent().addBadge(b);
@ -470,12 +366,9 @@ public class AchievementManager
}
}
if (level.perks != null && level.perks.length > 0 )
{
for (String perk : level.perks)
{
if (perk.equalsIgnoreCase("TRADE"))
{
if (level.perks != null && level.perks.length > 0) {
for (String perk : level.perks) {
if (perk.equalsIgnoreCase("TRADE")) {
habbo.getHabboStats().perkTrade = true;
}
}
@ -489,8 +382,7 @@ public class AchievementManager
}
}
public TalentTrackLevel getTalentTrackLevel(TalentTrackType type, int level)
{
public TalentTrackLevel getTalentTrackLevel(TalentTrackType type, int level) {
return this.talentTrackLevels.get(type).get(level);
}
}

View File

@ -9,8 +9,7 @@ import gnu.trove.set.hash.THashSet;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TalentTrackLevel
{
public class TalentTrackLevel {
public TalentTrackType type;
@ -29,8 +28,7 @@ public class TalentTrackLevel
public String[] badges;
public TalentTrackLevel(ResultSet set) throws SQLException
{
public TalentTrackLevel(ResultSet set) throws SQLException {
this.type = TalentTrackType.valueOf(set.getString("type").toUpperCase());
this.level = set.getInt("level");
this.achievements = new TObjectIntHashMap<>();
@ -38,47 +36,36 @@ public class TalentTrackLevel
String[] achievements = set.getString("achievement_ids").split(",");
String[] achievementLevels = set.getString("achievement_levels").split(",");
if (achievementLevels.length == achievements.length)
{
for (int i = 0; i < achievements.length; i++)
{
if (achievementLevels.length == achievements.length) {
for (int i = 0; i < achievements.length; i++) {
if (achievements[i].isEmpty() || achievementLevels[i].isEmpty())
continue;
Achievement achievement = Emulator.getGameEnvironment().getAchievementManager().getAchievement(Integer.valueOf(achievements[i]));
if (achievement != null)
{
if (achievement != null) {
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);
}
}
}
for (String s : set.getString("reward_furni").split(","))
{
for (String s : set.getString("reward_furni").split(",")) {
Item item = Emulator.getGameEnvironment().getItemManager().getItem(Integer.valueOf(s));
if (item != null)
{
if (item != null) {
this.items.add(item);
}
else
{
} else {
Emulator.getLogging().logStart("Incorrect reward furni (ID: " + s + ") for talent track level " + this.level);
}
}
if (!set.getString("reward_perks").isEmpty())
{
if (!set.getString("reward_perks").isEmpty()) {
this.perks = set.getString("reward_perks").split(",");
}
if (!set.getString("reward_badges").isEmpty())
{
if (!set.getString("reward_badges").isEmpty()) {
this.badges = set.getString("reward_badges").split(",");
}
}

View File

@ -1,7 +1,6 @@
package com.eu.habbo.habbohotel.achievements;
public enum TalentTrackType
{
public enum TalentTrackType {
CITIZENSHIP,

View File

@ -6,10 +6,7 @@ import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboGender;
import com.eu.habbo.habbohotel.wired.WiredHandler;
import com.eu.habbo.habbohotel.wired.WiredTriggerType;
import com.eu.habbo.messages.outgoing.rooms.users.RoomUserShoutComposer;
import com.eu.habbo.messages.outgoing.rooms.users.RoomUserTalkComposer;
import com.eu.habbo.messages.outgoing.rooms.users.RoomUserWhisperComposer;
import com.eu.habbo.messages.outgoing.rooms.users.RoomUsersComposer;
import com.eu.habbo.messages.outgoing.rooms.users.*;
import com.eu.habbo.plugin.events.bots.BotChatEvent;
import com.eu.habbo.plugin.events.bots.BotShoutEvent;
import com.eu.habbo.plugin.events.bots.BotTalkEvent;
@ -23,55 +20,23 @@ import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
public class Bot implements Runnable
{
public class Bot implements Runnable {
public static final String NO_CHAT_SET = "${bot.skill.chatter.configuration.text.placeholder}";
private transient int id;
private String name;
private String motto;
private String figure;
private HabboGender gender;
private int ownerId;
private String ownerName;
private Room room;
private RoomUnit roomUnit;
private boolean chatAuto;
private boolean chatRandom;
private short chatDelay;
private int chatTimeOut;
private int chatTimestamp;
private final ArrayList<String> chatLines;
private transient int id;
private String name;
private String motto;
private String figure;
private HabboGender gender;
private int ownerId;
private String ownerName;
private Room room;
private RoomUnit roomUnit;
private boolean chatAuto;
private boolean chatRandom;
private short chatDelay;
private int chatTimeOut;
private int chatTimestamp;
private short lastChatIndex;
@ -88,8 +53,7 @@ public class Bot implements Runnable
private transient int followingHabboId;
public Bot(int id, String name, String motto, String figure, HabboGender gender, int ownerId, String ownerName)
{
public Bot(int id, String name, String motto, String figure, HabboGender gender, int ownerId, String ownerName) {
this.id = id;
this.name = name;
this.motto = motto;
@ -105,8 +69,7 @@ public class Bot implements Runnable
this.room = null;
}
public Bot(ResultSet set) throws SQLException
{
public Bot(ResultSet set) throws SQLException {
this.id = set.getInt("id");
this.name = set.getString("name");
this.motto = set.getString("motto");
@ -127,8 +90,7 @@ public class Bot implements Runnable
this.needsUpdate = false;
}
public Bot(Bot bot)
{
public Bot(Bot bot) {
this.name = bot.getName();
this.motto = bot.getMotto();
this.figure = bot.getFigure();
@ -146,25 +108,26 @@ public class Bot implements Runnable
this.needsUpdate = false;
}
public static void initialise() {
public void needsUpdate(boolean needsUpdate)
{
}
public static void dispose() {
}
public void needsUpdate(boolean needsUpdate) {
this.needsUpdate = needsUpdate;
}
public boolean needsUpdate()
{
public boolean needsUpdate() {
return this.needsUpdate;
}
@Override
public void run()
{
if(this.needsUpdate)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE bots SET name = ?, motto = ?, figure = ?, gender = ?, user_id = ?, room_id = ?, x = ?, y = ?, z = ?, rot = ?, dance = ?, freeroam = ?, chat_lines = ?, chat_auto = ?, chat_random = ?, chat_delay = ?, effect = ? WHERE id = ?"))
{
public void run() {
if (this.needsUpdate) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE bots SET name = ?, motto = ?, figure = ?, gender = ?, user_id = ?, room_id = ?, x = ?, y = ?, z = ?, rot = ?, dance = ?, freeroam = ?, chat_lines = ?, chat_auto = ?, chat_random = ?, chat_delay = ?, effect = ? WHERE id = ?")) {
statement.setString(1, this.name);
statement.setString(2, this.motto);
statement.setString(3, this.figure);
@ -178,8 +141,7 @@ public class Bot implements Runnable
statement.setInt(11, this.roomUnit == null ? 0 : this.roomUnit.getDanceType().getType());
statement.setString(12, this.canWalk ? "1" : "0");
StringBuilder text = new StringBuilder();
for(String s : this.chatLines)
{
for (String s : this.chatLines) {
text.append(s).append("\r");
}
statement.setString(13, text.toString());
@ -190,46 +152,33 @@ public class Bot implements Runnable
statement.setInt(18, this.id);
statement.execute();
this.needsUpdate = false;
}
catch(SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
}
public void cycle(boolean allowBotsWalk)
{
if(this.roomUnit != null)
{
if(allowBotsWalk && this.canWalk)
{
if (!this.roomUnit.isWalking())
{
if (this.roomUnit.getWalkTimeOut() < Emulator.getIntUnixTimestamp() && this.followingHabboId == 0)
{
public void cycle(boolean allowBotsWalk) {
if (this.roomUnit != null) {
if (allowBotsWalk && this.canWalk) {
if (!this.roomUnit.isWalking()) {
if (this.roomUnit.getWalkTimeOut() < Emulator.getIntUnixTimestamp() && this.followingHabboId == 0) {
this.roomUnit.setGoalLocation(this.room.getRandomWalkableTile());
int timeOut = Emulator.getRandom().nextInt(20) * 2;
this.roomUnit.setWalkTimeOut((timeOut < 10 ? 5 : timeOut) + Emulator.getIntUnixTimestamp());
}
} else
{
for (RoomTile t : this.room.getLayout().getTilesAround(this.room.getLayout().getTile(this.getRoomUnit().getX(), this.getRoomUnit().getY())))
{
} else {
for (RoomTile t : this.room.getLayout().getTilesAround(this.room.getLayout().getTile(this.getRoomUnit().getX(), this.getRoomUnit().getY()))) {
WiredHandler.handle(WiredTriggerType.BOT_REACHED_STF, this.roomUnit, this.room, this.room.getItemsAt(t).toArray());
}
}
}
if(!this.chatLines.isEmpty() && this.chatTimeOut <= Emulator.getIntUnixTimestamp() && this.chatAuto)
{
if(this.room != null)
{
this.lastChatIndex = (this.chatRandom ? (short)Emulator.getRandom().nextInt(this.chatLines.size()) : (this.lastChatIndex == (this.chatLines.size() - 1) ? 0 : this.lastChatIndex++));
if (!this.chatLines.isEmpty() && this.chatTimeOut <= Emulator.getIntUnixTimestamp() && this.chatAuto) {
if (this.room != null) {
this.lastChatIndex = (this.chatRandom ? (short) Emulator.getRandom().nextInt(this.chatLines.size()) : (this.lastChatIndex == (this.chatLines.size() - 1) ? 0 : this.lastChatIndex++));
if (this.lastChatIndex >= this.chatLines.size())
{
if (this.lastChatIndex >= this.chatLines.size()) {
this.lastChatIndex = 0;
}
@ -246,41 +195,40 @@ public class Bot implements Runnable
}
}
public void talk(String message)
{
if(this.room != null)
{
public void talk(String message) {
if (this.room != null) {
BotChatEvent event = new BotTalkEvent(this, message);
if(Emulator.getPluginManager().fireEvent(event).isCancelled())
if (Emulator.getPluginManager().fireEvent(event).isCancelled())
return;
this.chatTimestamp = Emulator.getIntUnixTimestamp();
this.room.botChat(new RoomUserTalkComposer(new RoomChatMessage(event.message, this.roomUnit, RoomChatMessageBubbles.BOT_RENTABLE)).compose());
if (message.equals("o/") || message.equals("_o/")) {
this.room.sendComposer(new RoomUserActionComposer(this.roomUnit, RoomUserAction.WAVE).compose());
}
}
}
public void shout(String message)
{
if(this.room != null)
{
public void shout(String message) {
if (this.room != null) {
BotChatEvent event = new BotShoutEvent(this, message);
if(Emulator.getPluginManager().fireEvent(event).isCancelled())
if (Emulator.getPluginManager().fireEvent(event).isCancelled())
return;
this.chatTimestamp = Emulator.getIntUnixTimestamp();
this.room.botChat(new RoomUserShoutComposer(new RoomChatMessage(event.message, this.roomUnit, RoomChatMessageBubbles.BOT_RENTABLE)).compose());
if (message.equals("o/") || message.equals("_o/")) {
this.room.sendComposer(new RoomUserActionComposer(this.roomUnit, RoomUserAction.WAVE).compose());
}
}
}
public void whisper(String message, Habbo habbo)
{
if(this.room != null && habbo != null)
{
public void whisper(String message, Habbo habbo) {
if (this.room != null && habbo != null) {
BotWhisperEvent event = new BotWhisperEvent(this, message, habbo);
if(Emulator.getPluginManager().fireEvent(event).isCancelled())
if (Emulator.getPluginManager().fireEvent(event).isCancelled())
return;
this.chatTimestamp = Emulator.getIntUnixTimestamp();
@ -288,48 +236,33 @@ public class Bot implements Runnable
}
}
public void onPlace(Habbo habbo, Room room)
{
if (this.roomUnit != null)
{
public void onPlace(Habbo habbo, Room room) {
if (this.roomUnit != null) {
room.giveEffect(this.roomUnit, this.effect, -1);
}
}
public void onPickUp(Habbo habbo, Room room)
{
public void onPickUp(Habbo habbo, Room room) {
}
public void onUserSay(final RoomChatMessage message)
{
public void onUserSay(final RoomChatMessage message) {
}
public int getId()
{
public int getId() {
return this.id;
}
public void setId(int id)
{
public void setId(int id) {
this.id = id;
}
public String getName()
{
public String getName() {
return this.name;
}
public void setName(String name)
{
public void setName(String name) {
this.name = name;
this.needsUpdate = true;
@ -337,259 +270,178 @@ public class Bot implements Runnable
//this.room.sendComposer(new ChangeNameUpdatedComposer(this.getRoomUnit(), this.getName()).compose());
}
public String getMotto()
{
public String getMotto() {
return this.motto;
}
public void setMotto(String motto)
{
public void setMotto(String motto) {
this.motto = motto;
this.needsUpdate = true;
}
public String getFigure()
{
public String getFigure() {
return this.figure;
}
public void setFigure(String figure)
{
public void setFigure(String figure) {
this.figure = figure;
this.needsUpdate = true;
if(this.room != null)
if (this.room != null)
this.room.sendComposer(new RoomUsersComposer(this).compose());
}
public HabboGender getGender()
{
public HabboGender getGender() {
return this.gender;
}
public void setGender(HabboGender gender)
{
public void setGender(HabboGender gender) {
this.gender = gender;
this.needsUpdate = true;
if(this.room != null)
if (this.room != null)
this.room.sendComposer(new RoomUsersComposer(this).compose());
}
public int getOwnerId()
{
public int getOwnerId() {
return this.ownerId;
}
public void setOwnerId(int ownerId)
{
public void setOwnerId(int ownerId) {
this.ownerId = ownerId;
this.needsUpdate = true;
if(this.room != null)
if (this.room != null)
this.room.sendComposer(new RoomUsersComposer(this).compose());
}
public String getOwnerName()
{
public String getOwnerName() {
return this.ownerName;
}
public void setOwnerName(String ownerName)
{
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
this.needsUpdate = true;
if(this.room != null)
if (this.room != null)
this.room.sendComposer(new RoomUsersComposer(this).compose());
}
public Room getRoom()
{
public Room getRoom() {
return this.room;
}
public void setRoom(Room room)
{
public void setRoom(Room room) {
this.room = room;
}
public RoomUnit getRoomUnit()
{
public RoomUnit getRoomUnit() {
return this.roomUnit;
}
public void setRoomUnit(RoomUnit roomUnit)
{
public void setRoomUnit(RoomUnit roomUnit) {
this.roomUnit = roomUnit;
}
public boolean isChatAuto()
{
public boolean isChatAuto() {
return this.chatAuto;
}
public void setChatAuto(boolean chatAuto)
{
public void setChatAuto(boolean chatAuto) {
this.chatAuto = chatAuto;
this.needsUpdate = true;
}
public boolean isChatRandom()
{
public boolean isChatRandom() {
return this.chatRandom;
}
public boolean hasChat()
{
return !this.chatLines.isEmpty();
}
public void setChatRandom(boolean chatRandom)
{
public void setChatRandom(boolean chatRandom) {
this.chatRandom = chatRandom;
this.needsUpdate = true;
}
public boolean hasChat() {
return !this.chatLines.isEmpty();
}
public int getChatDelay()
{
public int getChatDelay() {
return this.chatDelay;
}
public void setChatDelay(short chatDelay)
{
this.chatDelay = (short)Math.min(Math.max(chatDelay, BotManager.MINIMUM_CHAT_SPEED), BotManager.MAXIMUM_CHAT_SPEED);
public void setChatDelay(short chatDelay) {
this.chatDelay = (short) Math.min(Math.max(chatDelay, BotManager.MINIMUM_CHAT_SPEED), BotManager.MAXIMUM_CHAT_SPEED);
this.needsUpdate = true;
this.chatTimeOut = Emulator.getIntUnixTimestamp() + this.chatDelay;
}
public int getChatTimestamp()
{
public int getChatTimestamp() {
return this.chatTimestamp;
}
public void clearChat()
{
synchronized (this.chatLines)
{
public void clearChat() {
synchronized (this.chatLines) {
this.chatLines.clear();
this.needsUpdate = true;
}
}
public String getType()
{
public String getType() {
return this.type;
}
public int getEffect()
{
public int getEffect() {
return this.effect;
}
public void setEffect(int effect, int duration)
{
public void setEffect(int effect, int duration) {
this.effect = effect;
this.needsUpdate = true;
if (this.roomUnit != null)
{
if (this.room != null)
{
if (this.roomUnit != null) {
if (this.room != null) {
this.room.giveEffect(this.roomUnit, this.effect, duration);
}
}
}
public void addChatLines(ArrayList<String> chatLines)
{
synchronized (this.chatLines)
{
public void addChatLines(ArrayList<String> chatLines) {
synchronized (this.chatLines) {
this.chatLines.addAll(chatLines);
this.needsUpdate = true;
}
}
public void addChatLine(String chatLine)
{
synchronized (this.chatLines)
{
public void addChatLine(String chatLine) {
synchronized (this.chatLines) {
this.chatLines.add(chatLine);
this.needsUpdate = true;
}
}
public ArrayList<String> getChatLines()
{
public ArrayList<String> getChatLines() {
return this.chatLines;
}
public int getFollowingHabboId()
{
public int getFollowingHabboId() {
return this.followingHabboId;
}
public void startFollowingHabbo(Habbo habbo)
{
public void startFollowingHabbo(Habbo habbo) {
this.followingHabboId = habbo.getHabboInfo().getId();
Emulator.getThreading().run(new BotFollowHabbo(this, habbo, habbo.getHabboInfo().getCurrentRoom()));
}
public void stopFollowingHabbo()
{
public void stopFollowingHabbo() {
this.followingHabboId = 0;
}
public static void initialise()
{
}
public static void dispose()
{
}
public boolean canWalk()
{
public boolean canWalk() {
return this.canWalk;
}
public void setCanWalk(boolean canWalk)
{
public void setCanWalk(boolean canWalk) {
this.canWalk = canWalk;
}

View File

@ -20,25 +20,16 @@ import java.lang.reflect.Method;
import java.sql.*;
import java.util.Map;
public class BotManager
{
public static int MINIMUM_CHAT_SPEED = 7;
public static int MAXIMUM_CHAT_SPEED = 604800;
public static int MAXIMUM_CHAT_LENGTH = 120;
public static int MAXIMUM_NAME_LENGTH = 15;
public class BotManager {
final private static THashMap<String, Class<? extends Bot>> botDefenitions = new THashMap<>();
public static int MINIMUM_CHAT_SPEED = 7;
public static int MAXIMUM_CHAT_SPEED = 604800;
public static int MAXIMUM_CHAT_LENGTH = 120;
public static int MAXIMUM_NAME_LENGTH = 15;
public BotManager() throws Exception
{
public BotManager() throws Exception {
long millis = System.currentTimeMillis();
addBotDefinition("generic", Bot.class);
@ -47,27 +38,29 @@ public class BotManager
this.reload();
Emulator.getLogging().logStart("Bot Manager -> Loaded! ("+(System.currentTimeMillis() - millis)+" MS)");
Emulator.getLogging().logStart("Bot Manager -> Loaded! (" + (System.currentTimeMillis() - millis) + " MS)");
}
public static void addBotDefinition(String type, Class<? extends Bot> botClazz) throws Exception {
if (botClazz.getDeclaredConstructor(ResultSet.class) == null) {
throw new Exception("Missing Bot(ResultSet) constructor!");
} else {
botClazz.getDeclaredConstructor(ResultSet.class).setAccessible(true);
public boolean reload()
{
for(Map.Entry<String, Class<? extends Bot>> set : botDefenitions.entrySet())
{
try
{
botDefenitions.put(type, botClazz);
}
}
public boolean reload() {
for (Map.Entry<String, Class<? extends Bot>> set : botDefenitions.entrySet()) {
try {
Method m = set.getValue().getMethod("initialise");
m.setAccessible(true);
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!");
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());
return false;
}
@ -76,63 +69,46 @@ public class BotManager
return true;
}
public Bot createBot(THashMap<String, String> data, String type)
{
public Bot createBot(THashMap<String, String> data, String type) {
Bot bot = null;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO bots (user_id, room_id, name, motto, figure, gender, type) VALUES (0, 0, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS))
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO bots (user_id, room_id, name, motto, figure, gender, type) VALUES (0, 0, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
statement.setString(1, data.get("name"));
statement.setString(2, data.get("motto"));
statement.setString(3, data.get("figure"));
statement.setString(4, data.get("gender").toUpperCase());
statement.setString(5, type);
statement.execute();
try (ResultSet set = statement.getGeneratedKeys())
{
if (set.next())
{
try (PreparedStatement stmt = connection.prepareStatement("SELECT users.username AS owner_name, bots.* FROM bots LEFT JOIN users ON bots.user_id = users.id WHERE bots.id = ? LIMIT 1"))
{
try (ResultSet set = statement.getGeneratedKeys()) {
if (set.next()) {
try (PreparedStatement stmt = connection.prepareStatement("SELECT users.username AS owner_name, bots.* FROM bots LEFT JOIN users ON bots.user_id = users.id WHERE bots.id = ? LIMIT 1")) {
stmt.setInt(1, set.getInt(1));
try (ResultSet resultSet = stmt.executeQuery())
{
if (resultSet.next())
{
try (ResultSet resultSet = stmt.executeQuery()) {
if (resultSet.next()) {
bot = this.loadBot(resultSet);
}
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
}
}
catch(SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
return bot;
}
public void placeBot(Bot bot, Habbo habbo, Room room, RoomTile location)
{
public void placeBot(Bot bot, Habbo habbo, Room room, RoomTile location) {
BotPlacedEvent event = new BotPlacedEvent(bot, location, habbo);
Emulator.getPluginManager().fireEvent(event);
if(event.isCancelled())
if (event.isCancelled())
return;
if(room != null && bot != null && habbo != null)
{
if (room.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER) || habbo.hasPermission("acc_placefurni"))
{
if (room.getCurrentBots().size() >= Room.MAXIMUM_BOTS && !habbo.hasPermission("acc_unlimited_bots"))
{
if (room != null && bot != null && habbo != null) {
if (room.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER) || habbo.hasPermission("acc_placefurni")) {
if (room.getCurrentBots().size() >= Room.MAXIMUM_BOTS && !habbo.hasPermission("acc_unlimited_bots")) {
habbo.getClient().sendResponse(new BotErrorComposer(BotErrorComposer.ROOM_ERROR_MAX_BOTS));
return;
}
@ -159,48 +135,36 @@ public class BotManager
habbo.getClient().sendResponse(new RemoveBotComposer(bot));
bot.onPlace(habbo, room);
if (topItem != null)
{
if (topItem != null) {
roomUnit.setZ(topItem.getBaseItem().allowSit() ? topItem.getZ() : topItem.getZ() + Item.getCurrentHeight(topItem));
try
{
try {
topItem.onWalkOn(bot.getRoomUnit(), room, null);
} catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
}
bot.cycle(false);
}
else
{
} else {
habbo.getClient().sendResponse(new BubbleAlertComposer(BubbleAlertKeys.FURNITURE_PLACEMENT_ERROR.key, FurnitureMovementError.NO_RIGHTS.errorCode));
}
}
}
public void pickUpBot(int botId, Habbo habbo)
{
if(habbo.getHabboInfo().getCurrentRoom() != null)
{
public void pickUpBot(int botId, Habbo habbo) {
if (habbo.getHabboInfo().getCurrentRoom() != null) {
this.pickUpBot(habbo.getHabboInfo().getCurrentRoom().getBot(Math.abs(botId)), habbo);
}
}
public void pickUpBot(Bot bot, Habbo habbo)
{
if(bot != null && habbo != null)
{
public void pickUpBot(Bot bot, Habbo habbo) {
if (bot != null && habbo != null) {
BotPickUpEvent pickedUpEvent = new BotPickUpEvent(bot, habbo);
Emulator.getPluginManager().fireEvent(pickedUpEvent);
if(pickedUpEvent.isCancelled())
if (pickedUpEvent.isCancelled())
return;
if (bot.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER))
{
if (bot.getOwnerId() == habbo.getHabboInfo().getId() || habbo.hasPermission(Permission.ACC_ANYROOMOWNER)) {
if (!habbo.hasPermission("acc_unlimited_bots") && habbo.getInventory().getBotsComponent().getBots().size() >= 15)
return;
@ -218,79 +182,44 @@ public class BotManager
}
}
public Bot loadBot(ResultSet set)
{
try
{
public Bot loadBot(ResultSet set) {
try {
String type = set.getString("type");
Class<? extends Bot> botClazz = botDefenitions.get(type);
if(botClazz != null)
if (botClazz != null)
return botClazz.getDeclaredConstructor(ResultSet.class).newInstance(set);
else
Emulator.getLogging().logErrorLine("Unknown Bot Type: " + type);
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
}
return null;
}
public boolean deleteBot(Bot bot)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("DELETE FROM bots WHERE id = ? LIMIT 1"))
{
public boolean deleteBot(Bot bot) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("DELETE FROM bots WHERE id = ? LIMIT 1")) {
statement.setInt(1, bot.getId());
return statement.execute();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
return false;
}
public static void addBotDefinition(String type, Class<? extends Bot> botClazz) throws Exception
{
if(botClazz.getDeclaredConstructor(ResultSet.class) == null)
{
throw new Exception("Missing Bot(ResultSet) constructor!");
}
else
{
botClazz.getDeclaredConstructor(ResultSet.class).setAccessible(true);
botDefenitions.put(type, botClazz);
}
}
public void dispose()
{
for(Map.Entry<String, Class<? extends Bot>> set : botDefenitions.entrySet())
{
try
{
public void dispose() {
for (Map.Entry<String, Class<? extends Bot>> set : botDefenitions.entrySet()) {
try {
Method m = set.getValue().getMethod("dispose");
m.setAccessible(true);
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!");
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logStart("Bot Manager -> Failed to execute dispose method upon bot type '" + set.getKey() + "'. Error: " + e.getMessage());
}
}

View File

@ -18,71 +18,55 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
public class ButlerBot extends Bot
{
public class ButlerBot extends Bot {
public static THashMap<THashSet<String>, Integer> serveItems = new THashMap<>();
public ButlerBot(ResultSet set) throws SQLException
{
public ButlerBot(ResultSet set) throws SQLException {
super(set);
}
public ButlerBot(Bot bot)
{
public ButlerBot(Bot bot) {
super(bot);
}
public static void initialise()
{
if(serveItems == null)
public static void initialise() {
if (serveItems == null)
serveItems = new THashMap<>();
serveItems.clear();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM bot_serves"))
{
while (set.next())
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); Statement statement = connection.createStatement(); ResultSet set = statement.executeQuery("SELECT * FROM bot_serves")) {
while (set.next()) {
String[] keys = set.getString("keys").split(";");
THashSet<String> ks = new THashSet<>();
Collections.addAll(ks, keys);
serveItems.put(ks, set.getInt("item"));
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
public static void dispose()
{
public static void dispose() {
serveItems.clear();
}
@Override
public void onUserSay(final RoomChatMessage message)
{
if(this.getRoomUnit().hasStatus(RoomUnitStatus.MOVE))
public void onUserSay(final RoomChatMessage message) {
if (this.getRoomUnit().hasStatus(RoomUnitStatus.MOVE))
return;
if (this.getRoomUnit().getCurrentLocation().distance(message.getHabbo().getRoomUnit().getCurrentLocation()) <= Emulator.getConfig().getInt("hotel.bot.butler.commanddistance"))
if(message.getUnfilteredMessage() != null)
{
for(Map.Entry<THashSet<String>, Integer> set : serveItems.entrySet())
{
for(String s : set.getKey())
{
if(message.getUnfilteredMessage().toLowerCase().contains(s))
{
if (message.getUnfilteredMessage() != null) {
for (Map.Entry<THashSet<String>, Integer> set : serveItems.entrySet()) {
for (String s : set.getKey()) {
if (message.getUnfilteredMessage().toLowerCase().contains(s)) {
BotServerItemEvent serveEvent = new BotServerItemEvent(this, message.getHabbo(), set.getValue());
if (Emulator.getPluginManager().fireEvent(serveEvent).isCancelled())
{
if (Emulator.getPluginManager().fireEvent(serveEvent).isCancelled()) {
return;
}
if (this.getRoomUnit().canWalk())
{
if (this.getRoomUnit().canWalk()) {
final String key = s;
final Bot b = this;
b.lookAt(serveEvent.habbo);
@ -91,20 +75,16 @@ public class ButlerBot extends Bot
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 Runnable()
{
tasks.add(new Runnable() {
@Override
public void run()
{
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();
failedReached.add(new Runnable()
{
public void run()
{
failedReached.add(new Runnable() {
public void run() {
if (b.getRoomUnit().getCurrentLocation().distance(serveEvent.habbo.getRoomUnit().getCurrentLocation()) <= Emulator.getConfig().getInt("hotel.bot.butler.servedistance", 8)) {
for (Runnable t : tasks) {
t.run();
@ -117,13 +97,10 @@ public class ButlerBot extends Bot
if (b.getRoomUnit().getCurrentLocation().distance(serveEvent.habbo.getRoomUnit().getCurrentLocation()) > Emulator.getConfig().getInt("hotel.bot.butler.reachdistance", 3)) {
Emulator.getThreading().run(new RoomUnitWalkToRoomUnit(this.getRoomUnit(), serveEvent.habbo.getRoomUnit(), serveEvent.habbo.getHabboInfo().getCurrentRoom(), tasks, failedReached, Emulator.getConfig().getInt("hotel.bot.butler.reachdistance", 3)));
}
else {
} else {
Emulator.getThreading().run(failedReached.get(0), 1000);
}
}
else
{
} else {
this.getRoom().giveHandItem(serveEvent.habbo, serveEvent.itemId);
this.talk(Emulator.getTexts().getValue("bots.butler.given").replace("%key%", s).replace("%username%", serveEvent.habbo.getHabboInfo().getUsername()));
}

View File

@ -11,36 +11,33 @@ import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class VisitorBot extends Bot
{
public class VisitorBot extends Bot {
private static SimpleDateFormat DATE_FORMAT;
private boolean showedLog = false;
private THashSet<ModToolRoomVisit> visits = new THashSet<>(3);
public VisitorBot(ResultSet set) throws SQLException
{
public VisitorBot(ResultSet set) throws SQLException {
super(set);
}
public VisitorBot(Bot bot)
{
public VisitorBot(Bot bot) {
super(bot);
}
public static void initialise() {
DATE_FORMAT = new SimpleDateFormat(Emulator.getConfig().getValue("bots.visitor.dateformat"));
}
@Override
public void onUserSay(final RoomChatMessage message)
{
if(!this.showedLog)
{
if(message.getMessage().equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes")))
{
public void onUserSay(final RoomChatMessage message) {
if (!this.showedLog) {
if (message.getMessage().equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"))) {
this.showedLog = true;
String visitMessage = Emulator.getTexts().getValue("bots.visitor.list").replace("%count%", this.visits.size() + "");
StringBuilder list = new StringBuilder();
for(ModToolRoomVisit visit : this.visits)
{
for (ModToolRoomVisit visit : this.visits) {
list.append("\r");
list.append(visit.roomName).append(" ");
list.append(Emulator.getTexts().getValue("generic.time.at")).append(" ");
@ -56,29 +53,18 @@ public class VisitorBot extends Bot
}
}
public void onUserEnter(Habbo habbo)
{
if(!this.showedLog)
{
if(habbo.getHabboInfo().getCurrentRoom() != null)
{
public void onUserEnter(Habbo habbo) {
if (!this.showedLog) {
if (habbo.getHabboInfo().getCurrentRoom() != null) {
this.visits = Emulator.getGameEnvironment().getModToolManager().getVisitsForRoom(habbo.getHabboInfo().getCurrentRoom(), 10, true, habbo.getHabboInfo().getLastOnline(), Emulator.getIntUnixTimestamp());
if(this.visits.isEmpty())
{
if (this.visits.isEmpty()) {
this.talk(Emulator.getTexts().getValue("bots.visitor.no_visits"));
}
else
{
} else {
this.talk(Emulator.getTexts().getValue("bots.visitor.visits").replace("%count%", this.visits.size() + "").replace("%positive%", Emulator.getTexts().getValue("generic.yes")));
}
}
}
}
public static void initialise()
{
DATE_FORMAT = new SimpleDateFormat(Emulator.getConfig().getValue("bots.visitor.dateformat"));
}
}

View File

@ -6,8 +6,7 @@ import com.eu.habbo.habbohotel.users.Habbo;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CalendarRewardObject
{
public class CalendarRewardObject {
private final int id;
private final String name;
private final String customImage;
@ -17,8 +16,7 @@ public class CalendarRewardObject
private final String badge;
private final int catalogItemId;
public CalendarRewardObject(ResultSet set) throws SQLException
{
public CalendarRewardObject(ResultSet set) throws SQLException {
this.id = set.getInt("id");
this.name = set.getString("name");
this.customImage = set.getString("custom_image");
@ -29,71 +27,57 @@ public class CalendarRewardObject
this.catalogItemId = set.getInt("catalog_item_id");
}
public void give(Habbo habbo)
{
if (this.credits > 0)
{
public void give(Habbo habbo) {
if (this.credits > 0) {
habbo.giveCredits(this.credits);
}
if (this.points > 0)
{
if (this.points > 0) {
habbo.givePoints(this.pointsType, this.points);
}
if (!this.badge.isEmpty())
{
if (!this.badge.isEmpty()) {
habbo.addBadge(this.badge);
}
if (this.catalogItemId > 0)
{
if (this.catalogItemId > 0) {
CatalogItem item = this.getCatalogItem();
if (item != null)
{
if (item != null) {
Emulator.getGameEnvironment().getCatalogManager().purchaseItem(null, item, habbo, 1, "", true);
}
}
}
public int getId()
{
public int getId() {
return this.id;
}
public String getName()
{
public String getName() {
return this.name;
}
public String getCustomImage()
{
public String getCustomImage() {
return this.customImage;
}
public int getCredits()
{
public int getCredits() {
return this.credits;
}
public int getPoints()
{
public int getPoints() {
return this.points;
}
public int getPointsType()
{
public int getPointsType() {
return this.pointsType;
}
public String getBadge()
{
public String getBadge() {
return this.badge;
}
public CatalogItem getCatalogItem()
{
public CatalogItem getCatalogItem() {
return Emulator.getGameEnvironment().getCatalogManager().getCatalogItem(this.catalogItemId);
}
}

View File

@ -4,21 +4,7 @@ import com.eu.habbo.Emulator;
import com.eu.habbo.messages.ISerialize;
import com.eu.habbo.messages.ServerMessage;
public class CatalogFeaturedPage implements ISerialize
{
public enum Type
{
PAGE_NAME(0),
PAGE_ID(1),
PRODUCT_NAME(2);
public final int type;
Type(int type)
{
this.type = type;
}
}
public class CatalogFeaturedPage implements ISerialize {
private final int slotId;
private final String caption;
private final String image;
@ -27,9 +13,7 @@ public class CatalogFeaturedPage implements ISerialize
private final String pageName;
private final int pageId;
private final String productName;
public CatalogFeaturedPage(int slotId, String caption, String image, Type type, int expireTimestamp, String pageName, int pageId, String productName)
{
public CatalogFeaturedPage(int slotId, String caption, String image, Type type, int expireTimestamp, String pageName, int pageId, String productName) {
this.slotId = slotId;
this.caption = caption;
this.image = image;
@ -41,21 +25,34 @@ public class CatalogFeaturedPage implements ISerialize
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendInt(this.slotId);
message.appendString(this.caption);
message.appendString(this.image);
message.appendInt(this.type.type);
switch (this.type)
{
switch (this.type) {
case PAGE_NAME:
message.appendString(this.pageName); break;
message.appendString(this.pageName);
break;
case PAGE_ID:
message.appendInt(this.pageId); break;
message.appendInt(this.pageId);
break;
case PRODUCT_NAME:
message.appendString(this.productName); break;
message.appendString(this.productName);
break;
}
message.appendInt(Emulator.getIntUnixTimestamp() - this.expireTimestamp);
}
public enum Type {
PAGE_NAME(0),
PAGE_ID(1),
PRODUCT_NAME(2);
public final int type;
Type(int type) {
this.type = type;
}
}
}

View File

@ -13,39 +13,18 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem>
{
public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem> {
int id;
private int pageId;
private String itemId;
private String name;
private int credits;
private int points;
private short pointsType;
private int amount;
private boolean allowGift = false;
int limitedStack;
private int pageId;
private String itemId;
private String name;
private int credits;
private int points;
private short pointsType;
private int amount;
private boolean allowGift = false;
private int limitedSells;
@ -69,20 +48,40 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
private HashMap<Integer, Integer> bundle;
public CatalogItem(ResultSet set) throws SQLException
{
public CatalogItem(ResultSet set) throws SQLException {
this.load(set);
this.needsUpdate = false;
}
public static boolean haveOffer(CatalogItem item) {
if (!item.haveOffer)
return false;
public void update(ResultSet set) throws SQLException
{
if (item.getAmount() != 1)
return false;
if (item.isLimited())
return false;
if (item.bundle.size() > 1)
return false;
if (item.getName().toLowerCase().startsWith("cf_") || item.getName().toLowerCase().startsWith("cfc_"))
return false;
for (Item i : item.getBaseItems()) {
if (i.getName().toLowerCase().startsWith("cf_") || i.getName().toLowerCase().startsWith("cfc_") || i.getName().toLowerCase().startsWith("rentable_bot"))
return false;
}
return !item.getName().toLowerCase().startsWith("rentable_bot_");
}
public void update(ResultSet set) throws SQLException {
this.load(set);
}
private void load(ResultSet set) throws SQLException
{
private void load(ResultSet set) throws SQLException {
this.id = set.getInt("id");
this.pageId = set.getInt("page_id");
this.itemId = set.getString("item_Ids");
@ -103,168 +102,119 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
this.loadBundle();
}
public int getId()
{
public int getId() {
return this.id;
}
public int getPageId()
{
public int getPageId() {
return this.pageId;
}
public void setPageId(int pageId)
{
public void setPageId(int pageId) {
this.pageId = pageId;
}
public String getItemId()
{
public String getItemId() {
return this.itemId;
}
public void setItemId(String itemId)
{
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getName()
{
public String getName() {
return this.name;
}
public int getCredits()
{
public int getCredits() {
return this.credits;
}
public int getPoints()
{
public int getPoints() {
return this.points;
}
public int getPointsType()
{
public int getPointsType() {
return this.pointsType;
}
public int getAmount()
{
public int getAmount() {
return this.amount;
}
public int getLimitedStack()
{
public int getLimitedStack() {
return this.limitedStack;
}
public int getLimitedSells()
{
public int getLimitedSells() {
CatalogLimitedConfiguration ltdConfig = Emulator.getGameEnvironment().getCatalogManager().getLimitedConfig(this);
if (ltdConfig != null)
{
if (ltdConfig != null) {
return this.limitedStack - ltdConfig.available();
}
return this.limitedStack;
}
public String getExtradata()
{
public String getExtradata() {
return this.extradata;
}
public boolean isClubOnly()
{
public boolean isClubOnly() {
return this.clubOnly;
}
public boolean isHaveOffer()
{
public boolean isHaveOffer() {
return this.haveOffer;
}
public int getOfferId()
{
public int getOfferId() {
return this.offerId;
}
public boolean isLimited()
{
public boolean isLimited() {
return this.limitedStack > 0;
}
private int getOrderNumber()
{
private int getOrderNumber() {
return this.orderNumber;
}
public synchronized void sellRare()
{
public synchronized void sellRare() {
this.limitedSells++;
this.needsUpdate = true;
if(this.limitedSells == this.limitedStack)
{
if (this.limitedSells == this.limitedStack) {
Emulator.getGameEnvironment().getCatalogManager().moveCatalogItem(this, Emulator.getConfig().getInt("catalog.ltd.page.soldout"));
}
Emulator.getThreading().run(this);
}
public THashSet<Item> getBaseItems()
{
public THashSet<Item> getBaseItems() {
THashSet<Item> items = new THashSet<>();
if(!this.itemId.isEmpty())
{
if (!this.itemId.isEmpty()) {
String[] itemIds = this.itemId.split(";");
for (String itemId : itemIds)
{
for (String itemId : itemIds) {
if (itemId.isEmpty())
continue;
if (itemId.contains(":"))
{
if (itemId.contains(":")) {
itemId = itemId.split(":")[0];
}
int identifier;
try
{
try {
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");
continue;
}
if (identifier > 0)
{
if (identifier > 0) {
Item item = Emulator.getGameEnvironment().getItemManager().getItem(identifier);
if (item != null)
@ -276,76 +226,55 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
return items;
}
public int getItemAmount(int id)
{
if(this.bundle.containsKey(id))
public int getItemAmount(int id) {
if (this.bundle.containsKey(id))
return this.bundle.get(id);
else
return this.amount;
}
public HashMap<Integer, Integer> getBundle()
{
public HashMap<Integer, Integer> getBundle() {
return this.bundle;
}
public void loadBundle()
{
public void loadBundle() {
int intItemId;
if(this.itemId.contains(";"))
{
try
{
if (this.itemId.contains(";")) {
try {
String[] itemIds = this.itemId.split(";");
for (String itemId : itemIds)
{
if (itemId.contains(":"))
{
for (String itemId : itemIds) {
if (itemId.contains(":")) {
String[] data = itemId.split(":");
if (data.length > 1 && Integer.parseInt(data[0]) > 0 && Integer.parseInt(data[1]) > 0)
{
if (data.length > 1 && Integer.parseInt(data[0]) > 0 && Integer.parseInt(data[1]) > 0) {
this.bundle.put(Integer.parseInt(data[0]), Integer.parseInt(data[1]));
}
} else
{
if (!itemId.isEmpty())
{
} else {
if (!itemId.isEmpty()) {
intItemId = (Integer.parseInt(itemId));
this.bundle.put(intItemId, 1);
}
}
}
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logDebugLine("Failed to load " + this.itemId);
Emulator.getLogging().logErrorLine(e);
}
}
else
{
try
{
} else {
try {
Item item = Emulator.getGameEnvironment().getItemManager().getItem(Integer.valueOf(this.itemId));
if (item != null)
{
if (item != null) {
this.allowGift = item.allowGift();
}
} catch (Exception e) {
}
catch (Exception e)
{}
}
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendInt(this.getId());
message.appendString(this.getName());
message.appendBoolean(false);
@ -358,60 +287,41 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
message.appendInt(items.size());
for(Item item : items)
{
for (Item item : items) {
message.appendString(item.getType().code.toLowerCase());
if(item.getType() == FurnitureType.BADGE)
{
if (item.getType() == FurnitureType.BADGE) {
message.appendString(item.getName());
}
else
{
} else {
message.appendInt(item.getSpriteId());
if(this.getName().contains("wallpaper_single") || this.getName().contains("floor_single") || this.getName().contains("landscape_single"))
{
if (this.getName().contains("wallpaper_single") || this.getName().contains("floor_single") || this.getName().contains("landscape_single")) {
message.appendString(this.getName().split("_")[2]);
}
else if(item.getName().contains("bot") && item.getType() == FurnitureType.ROBOT)
{
} else if (item.getName().contains("bot") && item.getType() == FurnitureType.ROBOT) {
boolean lookFound = false;
for (String s : this.getExtradata().split(";"))
{
if (s.startsWith("figure:"))
{
for (String s : this.getExtradata().split(";")) {
if (s.startsWith("figure:")) {
lookFound = true;
message.appendString(s.replace("figure:", ""));
break;
}
}
if (!lookFound)
{
if (!lookFound) {
message.appendString(this.getExtradata());
}
}
else if(item.getType() == FurnitureType.ROBOT)
{
} else if (item.getType() == FurnitureType.ROBOT) {
message.appendString(this.getExtradata());
}
else if(item.getName().equalsIgnoreCase("poster"))
{
} else if (item.getName().equalsIgnoreCase("poster")) {
message.appendString(this.getExtradata());
}
else if(this.getName().startsWith("SONG "))
{
} else if (this.getName().startsWith("SONG ")) {
message.appendString(this.getExtradata());
}
else
{
} else {
message.appendString("");
}
message.appendInt(this.getItemAmount(item.getId()));
message.appendBoolean(this.isLimited());
if(this.isLimited())
{
if (this.isLimited()) {
message.appendInt(this.getLimitedStack());
message.appendInt(this.getLimitedStack() - this.getLimitedSells());
}
@ -425,19 +335,14 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
}
@Override
public void run()
{
if(this.needsUpdate)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items SET limited_sells = ?, page_id = ? WHERE id = ?"))
{
public void run() {
if (this.needsUpdate) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items SET limited_sells = ?, page_id = ? WHERE id = ?")) {
statement.setInt(1, this.getLimitedSells());
statement.setInt(2, this.pageId);
statement.setInt(3, this.getId());
statement.execute();
}
catch(SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
@ -447,42 +352,11 @@ public class CatalogItem implements ISerialize, Runnable, Comparable<CatalogItem
@SuppressWarnings("NullableProblems")
@Override
public int compareTo(CatalogItem catalogItem)
{
if (CatalogManager.SORT_USING_ORDERNUM)
{
public int compareTo(CatalogItem catalogItem) {
if (CatalogManager.SORT_USING_ORDERNUM) {
return this.getOrderNumber() - catalogItem.getOrderNumber();
}
else
{
} else {
return this.getId() - catalogItem.getId();
}
}
public static boolean haveOffer(CatalogItem item)
{
if(!item.haveOffer)
return false;
if(item.getAmount() != 1)
return false;
if(item.isLimited())
return false;
if (item.bundle.size() > 1)
return false;
if(item.getName().toLowerCase().startsWith("cf_") || item.getName().toLowerCase().startsWith("cfc_"))
return false;
for(Item i : item.getBaseItems())
{
if(i.getName().toLowerCase().startsWith("cf_") || i.getName().toLowerCase().startsWith("cfc_") || i.getName().toLowerCase().startsWith("rentable_bot"))
return false;
}
return !item.getName().toLowerCase().startsWith("rentable_bot_");
}
}

View File

@ -10,119 +10,94 @@ import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedList;
public class CatalogLimitedConfiguration implements Runnable
{
public class CatalogLimitedConfiguration implements Runnable {
private final int itemId;
private int totalSet;
private final LinkedList<Integer> limitedNumbers;
private int totalSet;
public CatalogLimitedConfiguration(int itemId, LinkedList<Integer> availableNumbers, int totalSet)
{
public CatalogLimitedConfiguration(int itemId, LinkedList<Integer> availableNumbers, int totalSet) {
this.itemId = itemId;
this.totalSet = totalSet;
this.limitedNumbers = availableNumbers;
if(Emulator.getConfig().getBoolean("catalog.ltd.random", true)) {
if (Emulator.getConfig().getBoolean("catalog.ltd.random", true)) {
Collections.shuffle(this.limitedNumbers);
}
else {
} else {
Collections.reverse(this.limitedNumbers);
}
}
public int getNumber()
{
synchronized (this.limitedNumbers)
{
public int getNumber() {
synchronized (this.limitedNumbers) {
int num = this.limitedNumbers.pop();
if(this.limitedNumbers.isEmpty())
{
if (this.limitedNumbers.isEmpty()) {
Emulator.getGameEnvironment().getCatalogManager().moveCatalogItem(Emulator.getGameEnvironment().getCatalogManager().getCatalogItem(this.itemId), Emulator.getConfig().getInt("catalog.ltd.page.soldout"));
}
return num;
}
}
public void limitedSold(int catalogItemId, Habbo habbo, HabboItem item)
{
synchronized (this.limitedNumbers)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items_limited SET user_id = ?, timestamp = ?, item_id = ? WHERE catalog_item_id = ? AND number = ? AND user_id = 0 LIMIT 1"))
{
public void limitedSold(int catalogItemId, Habbo habbo, HabboItem item) {
synchronized (this.limitedNumbers) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items_limited SET user_id = ?, timestamp = ?, item_id = ? WHERE catalog_item_id = ? AND number = ? AND user_id = 0 LIMIT 1")) {
statement.setInt(1, habbo.getHabboInfo().getId());
statement.setInt(2, Emulator.getIntUnixTimestamp());
statement.setInt(3, item.getId());
statement.setInt(4, catalogItemId);
statement.setInt(5, item.getLimitedSells());
statement.execute();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
}
public void generateNumbers(int starting, int amount)
{
synchronized (this.limitedNumbers)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO catalog_items_limited (catalog_item_id, number) VALUES (?, ?)"))
{
public void generateNumbers(int starting, int amount) {
synchronized (this.limitedNumbers) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO catalog_items_limited (catalog_item_id, number) VALUES (?, ?)")) {
statement.setInt(1, this.itemId);
for (int i = starting; i <= amount; i++)
{
for (int i = starting; i <= amount; i++) {
statement.setInt(2, i);
statement.addBatch();
this.limitedNumbers.push(i);
}
statement.executeBatch();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
this.totalSet += amount;
if(Emulator.getConfig().getBoolean("catalog.ltd.random", true)) {
if (Emulator.getConfig().getBoolean("catalog.ltd.random", true)) {
Collections.shuffle(this.limitedNumbers);
}
else {
} else {
Collections.reverse(this.limitedNumbers);
}
}
}
public int available()
{
public int available() {
return this.limitedNumbers.size();
}
public int getTotalSet()
{
public int getTotalSet() {
return this.totalSet;
}
public void setTotalSet(int totalSet)
{
public void setTotalSet(int totalSet) {
this.totalSet = totalSet;
}
@Override
public void run()
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items SET limited_stack = ?, limited_sells = ? WHERE id = ?"))
{
public void run() {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE catalog_items SET limited_stack = ?, limited_sells = ? WHERE id = ?")) {
statement.setInt(1, this.totalSet);
statement.setInt(2, this.totalSet - this.available());
statement.setInt(3, this.itemId);
statement.execute();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}

View File

@ -13,8 +13,11 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize
{
public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize {
protected final TIntArrayList offerIds = new TIntArrayList();
protected final THashMap<Integer, CatalogPage> childPages = new THashMap<>();
private final TIntObjectMap<CatalogItem> catalogItems = TCollections.synchronizedMap(new TIntObjectHashMap<>());
private final ArrayList<Integer> included = new ArrayList<>();
protected int id;
protected int parentId;
protected int rank;
@ -34,13 +37,11 @@ public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize
protected String textTwo;
protected String textDetails;
protected String textTeaser;
protected final TIntArrayList offerIds = new TIntArrayList();
protected final THashMap<Integer, CatalogPage> childPages = new THashMap<>();
private final TIntObjectMap<CatalogItem> catalogItems = TCollections.synchronizedMap(new TIntObjectHashMap<>());
private final ArrayList<Integer> included = new ArrayList<>();
public CatalogPage(ResultSet set) throws SQLException
{
public CatalogPage() {
}
public CatalogPage(ResultSet set) throws SQLException {
if (set == null)
return;
@ -64,16 +65,11 @@ public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize
this.textDetails = set.getString("page_text_details");
this.textTeaser = set.getString("page_text_teaser");
if (!set.getString("includes").isEmpty())
{
for (String id : set.getString("includes").split(";"))
{
try
{
if (!set.getString("includes").isEmpty()) {
for (String id : set.getString("includes").split(";")) {
try {
this.included.add(Integer.valueOf(id));
}
catch (Exception e)
{
} catch (Exception e) {
Emulator.getLogging().logErrorLine(e);
Emulator.getLogging().logErrorLine("Failed to parse includes column value of (" + id + ") for catalog page (" + this.id + ")");
}
@ -81,147 +77,118 @@ public abstract class CatalogPage implements Comparable<CatalogPage>, ISerialize
}
}
public int getId()
{
public int getId() {
return this.id;
}
public int getParentId()
{
public int getParentId() {
return this.parentId;
}
public int getRank()
{
public int getRank() {
return this.rank;
}
public void setRank(int rank)
{
public void setRank(int rank) {
this.rank = rank;
}
public String getCaption()
{
public String getCaption() {
return this.caption;
}
public String getPageName()
{
public String getPageName() {
return this.pageName;
}
public int getIconColor()
{
public int getIconColor() {
return this.iconColor;
}
public int getIconImage()
{
public int getIconImage() {
return this.iconImage;
}
public int getOrderNum()
{
public int getOrderNum() {
return this.orderNum;
}
public boolean isVisible()
{
public boolean isVisible() {
return this.visible;
}
public boolean isEnabled()
{
public boolean isEnabled() {
return this.enabled;
}
public boolean isClubOnly()
{
public boolean isClubOnly() {
return this.clubOnly;
}
public String getLayout()
{
public String getLayout() {
return this.layout;
}
public String getHeaderImage()
{
public String getHeaderImage() {
return this.headerImage;
}
public String getTeaserImage()
{
public String getTeaserImage() {
return this.teaserImage;
}
public String getSpecialImage()
{
public String getSpecialImage() {
return this.specialImage;
}
public String getTextOne()
{
public String getTextOne() {
return this.textOne;
}
public String getTextTwo()
{
public String getTextTwo() {
return this.textTwo;
}
public String getTextDetails()
{
public String getTextDetails() {
return this.textDetails;
}
public String getTextTeaser()
{
public String getTextTeaser() {
return this.textTeaser;
}
public TIntArrayList getOfferIds()
{
public TIntArrayList getOfferIds() {
return this.offerIds;
}
public void addOfferId(int offerId)
{
public void addOfferId(int offerId) {
this.offerIds.add(offerId);
}
public void addItem(CatalogItem item)
{
public void addItem(CatalogItem item) {
this.catalogItems.put(item.getId(), item);
}
public TIntObjectMap<CatalogItem> getCatalogItems()
{
public TIntObjectMap<CatalogItem> getCatalogItems() {
return this.catalogItems;
}
public CatalogItem getCatalogItem(int id)
{
public CatalogItem getCatalogItem(int id) {
return this.catalogItems.get(id);
}
public ArrayList<Integer> getIncluded()
{
public ArrayList<Integer> getIncluded() {
return this.included;
}
public THashMap<Integer, CatalogPage> getChildPages()
{
public THashMap<Integer, CatalogPage> getChildPages() {
return this.childPages;
}
public void addChildPage(CatalogPage page)
{
public void addChildPage(CatalogPage page) {
this.childPages.put(page.getId(), page);
if (page.getRank() < this.getRank())
{
if (page.getRank() < this.getRank()) {
page.setRank(this.getRank());
}
}

View File

@ -1,7 +1,6 @@
package com.eu.habbo.habbohotel.catalog;
public enum CatalogPageLayouts
{
public enum CatalogPageLayouts {
default_3x3,

View File

@ -1,7 +1,6 @@
package com.eu.habbo.habbohotel.catalog;
public enum CatalogPageType
{
public enum CatalogPageType {
NORMAL,

View File

@ -3,8 +3,7 @@ package com.eu.habbo.habbohotel.catalog;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ClothItem
{
public class ClothItem {
public int id;
@ -14,15 +13,13 @@ public class ClothItem
public int[] setId;
public ClothItem(ResultSet set) throws SQLException
{
public ClothItem(ResultSet set) throws SQLException {
this.id = set.getInt("id");
this.name = set.getString("name");
String[] parts = set.getString("setid").split(",");
this.setId = new int[parts.length];
for (int i = 0; i < this.setId.length; i++)
{
for (int i = 0; i < this.setId.length; i++) {
this.setId[i] = Integer.valueOf(parts[i]);
}
}

View File

@ -3,8 +3,7 @@ package com.eu.habbo.habbohotel.catalog;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ClubOffer
{
public class ClubOffer {
private final int id;
@ -29,8 +28,7 @@ public class ClubOffer
private final boolean deal;
public ClubOffer(ResultSet set) throws SQLException
{
public ClubOffer(ResultSet set) throws SQLException {
this.id = set.getInt("id");
this.name = set.getString("name");
this.days = set.getInt("days");
@ -41,43 +39,35 @@ public class ClubOffer
this.deal = set.getString("deal").equals("1");
}
public int getId()
{
public int getId() {
return this.id;
}
public String getName()
{
public String getName() {
return this.name;
}
public int getDays()
{
public int getDays() {
return this.days;
}
public int getCredits()
{
public int getCredits() {
return this.credits;
}
public int getPoints()
{
public int getPoints() {
return this.points;
}
public int getPointsType()
{
public int getPointsType() {
return this.pointsType;
}
public boolean isVip()
{
public boolean isVip() {
return this.vip;
}
public boolean isDeal()
{
public boolean isDeal() {
return this.deal;
}
}

View File

@ -8,8 +8,7 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TargetOffer
{
public class TargetOffer {
public static int ACTIVE_TARGET_OFFER_ID = 0;
private final int id;
@ -26,8 +25,7 @@ public class TargetOffer
private final String icon;
private final String[] vars;
public TargetOffer(ResultSet set) throws SQLException
{
public TargetOffer(ResultSet set) throws SQLException {
this.id = set.getInt("id");
this.identifier = set.getString("offer_code");
this.priceInCredits = set.getInt("credits");
@ -43,8 +41,7 @@ public class TargetOffer
this.catalogItem = set.getInt("catalog_item");
}
public void serialize(ServerMessage message, HabboOfferPurchase purchase)
{
public void serialize(ServerMessage message, HabboOfferPurchase purchase) {
message.appendInt(purchase.getState());
message.appendInt(this.id);
message.appendString(this.identifier);
@ -60,74 +57,60 @@ public class TargetOffer
message.appendString(this.icon);
message.appendInt(0);
message.appendInt(this.vars.length);
for (String variable : this.vars)
{
for (String variable : this.vars) {
message.appendString(variable);
}
}
public int getId()
{
public int getId() {
return this.id;
}
public String getIdentifier()
{
public String getIdentifier() {
return this.identifier;
}
public int getPriceInCredits()
{
public int getPriceInCredits() {
return this.priceInCredits;
}
public int getPriceInActivityPoints()
{
public int getPriceInActivityPoints() {
return this.priceInActivityPoints;
}
public int getActivityPointsType()
{
public int getActivityPointsType() {
return this.activityPointsType;
}
public int getPurchaseLimit()
{
public int getPurchaseLimit() {
return this.purchaseLimit;
}
public int getExpirationTime()
{
public int getExpirationTime() {
return this.expirationTime;
}
public String getTitle()
{
public String getTitle() {
return this.title;
}
public String getDescription()
{
public String getDescription() {
return this.description;
}
public String getImageUrl()
{
public String getImageUrl() {
return this.imageUrl;
}
public String getIcon()
{
public String getIcon() {
return this.icon;
}
public String[] getVars()
{
public String[] getVars() {
return this.vars;
}
public int getCatalogItem()
{
public int getCatalogItem() {
return this.catalogItem;
}
}

View File

@ -3,8 +3,7 @@ package com.eu.habbo.habbohotel.catalog;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Voucher
{
public class Voucher {
public final int id;
@ -24,8 +23,7 @@ public class Voucher
public final int catalogItemId;
public Voucher(ResultSet set) throws SQLException
{
public Voucher(ResultSet set) throws SQLException {
this.id = set.getInt("id");
this.code = set.getString("code");
this.credits = set.getInt("credits");

View File

@ -7,10 +7,8 @@ import java.sql.ResultSet;
import java.sql.SQLException;
public class BadgeDisplayLayout extends CatalogPage
{
public BadgeDisplayLayout(ResultSet set) throws SQLException
{
public class BadgeDisplayLayout extends CatalogPage {
public BadgeDisplayLayout(ResultSet set) throws SQLException {
super(set);
}

View File

@ -7,16 +7,13 @@ import java.sql.ResultSet;
import java.sql.SQLException;
public class BotsLayout extends CatalogPage
{
public BotsLayout(ResultSet set) throws SQLException
{
public class BotsLayout extends CatalogPage {
public BotsLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("bots");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -7,16 +7,13 @@ import java.sql.ResultSet;
import java.sql.SQLException;
public class BuildersClubAddonsLayout extends CatalogPage
{
public BuildersClubAddonsLayout(ResultSet set) throws SQLException
{
public class BuildersClubAddonsLayout extends CatalogPage {
public BuildersClubAddonsLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("builders_club_addons");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -7,16 +7,13 @@ import java.sql.ResultSet;
import java.sql.SQLException;
public class BuildersClubFrontPageLayout extends CatalogPage
{
public BuildersClubFrontPageLayout(ResultSet set) throws SQLException
{
public class BuildersClubFrontPageLayout extends CatalogPage {
public BuildersClubFrontPageLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("builders_club_frontpage");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -7,16 +7,13 @@ import java.sql.ResultSet;
import java.sql.SQLException;
public class BuildersClubLoyaltyLayout extends CatalogPage
{
public BuildersClubLoyaltyLayout(ResultSet set) throws SQLException
{
public class BuildersClubLoyaltyLayout extends CatalogPage {
public BuildersClubLoyaltyLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("builders_club_loyalty");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -6,10 +6,12 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CatalogRootLayout extends CatalogPage
{
public CatalogRootLayout(ResultSet set) throws SQLException
{
public class CatalogRootLayout extends CatalogPage {
public CatalogRootLayout() {
super();
}
public CatalogRootLayout(ResultSet set) throws SQLException {
super(null);
this.id = -1;
@ -25,8 +27,7 @@ public class CatalogRootLayout extends CatalogPage
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
}
}

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ClubBuyLayout extends CatalogPage
{
public ClubBuyLayout(ResultSet set) throws SQLException
{
public class ClubBuyLayout extends CatalogPage {
public ClubBuyLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("club_buy");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ClubGiftsLayout extends CatalogPage
{
public ClubGiftsLayout(ResultSet set) throws SQLException
{
public class ClubGiftsLayout extends CatalogPage {
public ClubGiftsLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("club_gifts");
message.appendInt(1);
message.appendString(super.getHeaderImage());

View File

@ -6,10 +6,8 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ColorGroupingLayout extends CatalogPage
{
public ColorGroupingLayout(ResultSet set) throws SQLException
{
public class ColorGroupingLayout extends CatalogPage {
public ColorGroupingLayout(ResultSet set) throws SQLException {
super(set);
}

View File

@ -8,14 +8,12 @@ import java.sql.SQLException;
public class Default_3x3Layout extends CatalogPage {
public Default_3x3Layout(ResultSet set) throws SQLException
{
public Default_3x3Layout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("default_3x3");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -8,29 +8,24 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class FrontPageFeaturedLayout extends CatalogPage
{
public FrontPageFeaturedLayout(ResultSet set) throws SQLException
{
public class FrontPageFeaturedLayout extends CatalogPage {
public FrontPageFeaturedLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("frontpage_featured");
String[] teaserImages = super.getTeaserImage().split(";");
String[] specialImages = super.getSpecialImage().split(";");
message.appendInt(1 + teaserImages.length + specialImages.length);
message.appendString(super.getHeaderImage());
for (String s : teaserImages)
{
for (String s : teaserImages) {
message.appendString(s);
}
for (String s : specialImages)
{
for (String s : specialImages) {
message.appendString(s);
}
message.appendInt(3);
@ -39,13 +34,11 @@ public class FrontPageFeaturedLayout extends CatalogPage
message.appendString(super.getTextTeaser());
}
public void serializeExtra(ServerMessage message)
{
public void serializeExtra(ServerMessage message) {
message.appendInt(Emulator.getGameEnvironment().getCatalogManager().getCatalogFeaturedPages().size());
for (CatalogFeaturedPage page : Emulator.getGameEnvironment().getCatalogManager().getCatalogFeaturedPages().valueCollection())
{
for (CatalogFeaturedPage page : Emulator.getGameEnvironment().getCatalogManager().getCatalogFeaturedPages().valueCollection()) {
page.serialize(message);
}
message.appendInt(1); //Position

View File

@ -8,8 +8,7 @@ import java.sql.SQLException;
public class FrontpageLayout extends CatalogPage {
public FrontpageLayout(ResultSet set) throws SQLException
{
public FrontpageLayout(ResultSet set) throws SQLException {
super(set);
}

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class GuildForumLayout extends CatalogPage
{
public GuildForumLayout(ResultSet set) throws SQLException
{
public class GuildForumLayout extends CatalogPage {
public GuildForumLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("guild_forum");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class GuildFrontpageLayout extends CatalogPage
{
public GuildFrontpageLayout(ResultSet set) throws SQLException
{
public class GuildFrontpageLayout extends CatalogPage {
public GuildFrontpageLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("guild_frontpage");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class GuildFurnitureLayout extends CatalogPage
{
public GuildFurnitureLayout(ResultSet set) throws SQLException
{
public class GuildFurnitureLayout extends CatalogPage {
public GuildFurnitureLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("guild_custom_furni");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class InfoDucketsLayout extends CatalogPage
{
public InfoDucketsLayout(ResultSet set) throws SQLException
{
public class InfoDucketsLayout extends CatalogPage {
public InfoDucketsLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("info_duckets");
message.appendInt(1);
message.appendString(this.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class InfoLoyaltyLayout extends CatalogPage
{
public InfoLoyaltyLayout(ResultSet set) throws SQLException
{
public class InfoLoyaltyLayout extends CatalogPage {
public InfoLoyaltyLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("info_loyalty");
message.appendInt(1);
message.appendString(this.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class InfoPetsLayout extends CatalogPage
{
public InfoPetsLayout(ResultSet set) throws SQLException
{
public class InfoPetsLayout extends CatalogPage {
public InfoPetsLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("info_pets");
message.appendInt(2);
message.appendString(this.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class InfoRentablesLayout extends CatalogPage
{
public InfoRentablesLayout(ResultSet set) throws SQLException
{
public class InfoRentablesLayout extends CatalogPage {
public InfoRentablesLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
String[] data = this.getTextOne().split("\\|\\|");
message.appendString("info_rentables");
message.appendInt(1);

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoyaltyVipBuyLayout extends CatalogPage
{
public LoyaltyVipBuyLayout(ResultSet set) throws SQLException
{
public class LoyaltyVipBuyLayout extends CatalogPage {
public LoyaltyVipBuyLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("loyalty_vip_buy");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MarketplaceLayout extends CatalogPage
{
public MarketplaceLayout(ResultSet set) throws SQLException
{
public class MarketplaceLayout extends CatalogPage {
public MarketplaceLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("marketplace");
message.appendInt(0);
message.appendInt(0);

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MarketplaceOwnItems extends CatalogPage
{
public MarketplaceOwnItems(ResultSet set) throws SQLException
{
public class MarketplaceOwnItems extends CatalogPage {
public MarketplaceOwnItems(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("marketplace_own_items");
message.appendInt(0);
message.appendInt(0);

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PetCustomizationLayout extends CatalogPage
{
public PetCustomizationLayout(ResultSet set) throws SQLException
{
public class PetCustomizationLayout extends CatalogPage {
public PetCustomizationLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("petcustomization");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Pets2Layout extends CatalogPage
{
public Pets2Layout(ResultSet set) throws SQLException
{
public class Pets2Layout extends CatalogPage {
public Pets2Layout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("pets2");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Pets3Layout extends CatalogPage
{
public Pets3Layout(ResultSet set) throws SQLException
{
public class Pets3Layout extends CatalogPage {
public Pets3Layout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("pets3");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PetsLayout extends CatalogPage
{
public PetsLayout(ResultSet set) throws SQLException
{
public class PetsLayout extends CatalogPage {
public PetsLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("pets");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class ProductPage1Layout extends CatalogPage
{
public ProductPage1Layout(ResultSet set) throws SQLException
{
public class ProductPage1Layout extends CatalogPage {
public ProductPage1Layout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("productpage1");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -6,10 +6,8 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RecentPurchasesLayout extends CatalogPage
{
public RecentPurchasesLayout(ResultSet set) throws SQLException
{
public class RecentPurchasesLayout extends CatalogPage {
public RecentPurchasesLayout(ResultSet set) throws SQLException {
super(set);
}

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RecyclerInfoLayout extends CatalogPage
{
public RecyclerInfoLayout(ResultSet set) throws SQLException
{
public class RecyclerInfoLayout extends CatalogPage {
public RecyclerInfoLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("recycler_info");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RecyclerLayout extends CatalogPage
{
public RecyclerLayout(ResultSet set) throws SQLException
{
public class RecyclerLayout extends CatalogPage {
public RecyclerLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("recycler");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RecyclerPrizesLayout extends CatalogPage
{
public RecyclerPrizesLayout(ResultSet set) throws SQLException
{
public class RecyclerPrizesLayout extends CatalogPage {
public RecyclerPrizesLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("recycler_prizes");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class RoomAdsLayout extends CatalogPage
{
public RoomAdsLayout(ResultSet set) throws SQLException
{
public class RoomAdsLayout extends CatalogPage {
public RoomAdsLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("roomads");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -17,57 +17,46 @@ import gnu.trove.procedure.TObjectProcedure;
import java.sql.*;
import java.util.Map;
public class RoomBundleLayout extends SingleBundle
{
public class RoomBundleLayout extends SingleBundle {
public int roomId;
public Room room;
private int lastUpdate = 0;
private boolean loaded = false;
public RoomBundleLayout(ResultSet set) throws SQLException
{
public RoomBundleLayout(ResultSet set) throws SQLException {
super(set);
this.roomId = set.getInt("room_id");
}
@Override
public TIntObjectMap<CatalogItem> getCatalogItems()
{
if(Emulator.getIntUnixTimestamp() - this.lastUpdate < 120)
{
public TIntObjectMap<CatalogItem> getCatalogItems() {
if (Emulator.getIntUnixTimestamp() - this.lastUpdate < 120) {
this.lastUpdate = Emulator.getIntUnixTimestamp();
return super.getCatalogItems();
}
if(this.room == null)
{
if (this.roomId > 0)
{
if (this.room == null) {
if (this.roomId > 0) {
this.room = Emulator.getGameEnvironment().getRoomManager().loadRoom(this.roomId);
if (this.room != null)
this.room.preventUnloading = true;
}
else
{
} else {
Emulator.getLogging().logErrorLine("No room id specified for room bundle " + this.getPageName() + "(" + this.getId() + ")");
}
}
if(this.room == null)
{
if (this.room == null) {
return super.getCatalogItems();
}
final CatalogItem[] item = {null};
super.getCatalogItems().forEachValue(new TObjectProcedure<CatalogItem>()
{
super.getCatalogItems().forEachValue(new TObjectProcedure<CatalogItem>() {
@Override
public boolean execute(CatalogItem object)
{
if(object == null)
public boolean execute(CatalogItem object) {
if (object == null)
return true;
item[0] = object;
@ -75,47 +64,39 @@ public class RoomBundleLayout extends SingleBundle
}
});
if (this.room.isPreLoaded())
{
if (this.room.isPreLoaded()) {
this.room.loadData();
this.room.preventUncaching = true;
this.room.preventUnloading = true;
}
if(item[0] != null)
{
if (item[0] != null) {
item[0].getBundle().clear();
THashMap<Item, Integer> items = new THashMap<>();
for(HabboItem i : this.room.getFloorItems())
{
if(!items.contains(i.getBaseItem()))
{
for (HabboItem i : this.room.getFloorItems()) {
if (!items.contains(i.getBaseItem())) {
items.put(i.getBaseItem(), 0);
}
items.put(i.getBaseItem(), items.get(i.getBaseItem()) + 1);
}
for(HabboItem i : this.room.getWallItems())
{
if(!items.contains(i.getBaseItem()))
{
for (HabboItem i : this.room.getWallItems()) {
if (!items.contains(i.getBaseItem())) {
items.put(i.getBaseItem(), 0);
}
items.put(i.getBaseItem(), items.get(i.getBaseItem()) + 1);
}
if (!item[0].getExtradata().isEmpty())
{
if (!item[0].getExtradata().isEmpty()) {
items.put(Emulator.getGameEnvironment().getItemManager().getItem(Integer.valueOf(item[0].getExtradata())), 1);
}
StringBuilder data = new StringBuilder();
for(Map.Entry<Item, Integer> set : items.entrySet())
{
for (Map.Entry<Item, Integer> set : items.entrySet()) {
data.append(set.getKey().getId()).append(":").append(set.getValue()).append(";");
}
@ -126,10 +107,8 @@ public class RoomBundleLayout extends SingleBundle
return super.getCatalogItems();
}
public void loadItems(Room room)
{
if(this.room != null)
{
public void loadItems(Room room) {
if (this.room != null) {
this.room.preventUnloading = false;
}
@ -139,60 +118,49 @@ public class RoomBundleLayout extends SingleBundle
this.loaded = true;
}
public void buyRoom(Habbo habbo)
{
public void buyRoom(Habbo habbo) {
this.buyRoom(habbo, habbo.getHabboInfo().getId(), habbo.getHabboInfo().getUsername());
}
public void buyRoom(Habbo habbo, int userId, String userName)
{
if (!this.loaded)
{
public void buyRoom(Habbo habbo, int userId, String userName) {
if (!this.loaded) {
this.loadItems(Emulator.getGameEnvironment().getRoomManager().loadRoom(this.roomId));
}
if (habbo != null)
{
if (habbo != null) {
int count = Emulator.getGameEnvironment().getRoomManager().getRoomsForHabbo(habbo).size();
int max = habbo.getHabboStats().hasActiveClub() ? Emulator.getConfig().getInt("hotel.max.rooms.vip") : Emulator.getConfig().getInt("hotel.max.rooms.user");
if (count >= max)
{
if (count >= max) {
habbo.getClient().sendResponse(new CanCreateRoomComposer(count, max));
return;
}
}
if(this.room == null)
if (this.room == null)
return;
this.room.save();
for(HabboItem item : this.room.getFloorItems())
{
for (HabboItem item : this.room.getFloorItems()) {
item.run();
}
for(HabboItem item : this.room.getWallItems())
{
for (HabboItem item : this.room.getWallItems()) {
item.run();
}
this.getCatalogItems();
int roomId = 0;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection())
{
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO rooms (owner_id, owner_name, name, description, model, password, state, users_max, category, paper_floor, paper_wall, paper_landscape, thickness_wall, thickness_floor, moodlight_data, override_model) (SELECT ?, ?, name, description, model, password, state, users_max, category, paper_floor, paper_wall, paper_landscape, thickness_wall, thickness_floor, moodlight_data, override_model FROM rooms WHERE id = ?)", Statement.RETURN_GENERATED_KEYS))
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO rooms (owner_id, owner_name, name, description, model, password, state, users_max, category, paper_floor, paper_wall, paper_landscape, thickness_wall, thickness_floor, moodlight_data, override_model) (SELECT ?, ?, name, description, model, password, state, users_max, category, paper_floor, paper_wall, paper_landscape, thickness_wall, thickness_floor, moodlight_data, override_model FROM rooms WHERE id = ?)", Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, userId);
statement.setString(2, userName);
statement.setInt(3, this.room.getId());
statement.execute();
try (ResultSet set = statement.getGeneratedKeys())
{
if (set.next())
{
try (ResultSet set = statement.getGeneratedKeys()) {
if (set.next()) {
roomId = set.getInt(1);
}
}
@ -201,8 +169,7 @@ public class RoomBundleLayout extends SingleBundle
if (roomId == 0)
return;
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO items (user_id, room_id, item_id, wall_pos, x, y, z, rot, extra_data, wired_data, limited_data, guild_id) (SELECT ?, ?, item_id, wall_pos, x, y, z, rot, extra_data, wired_data, ?, ? FROM items WHERE room_id = ?)", Statement.RETURN_GENERATED_KEYS))
{
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO items (user_id, room_id, item_id, wall_pos, x, y, z, rot, extra_data, wired_data, limited_data, guild_id) (SELECT ?, ?, item_id, wall_pos, x, y, z, rot, extra_data, wired_data, ?, ? FROM items WHERE room_id = ?)", Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, userId);
statement.setInt(2, roomId);
statement.setString(3, "0:0");
@ -211,31 +178,23 @@ public class RoomBundleLayout extends SingleBundle
statement.execute();
}
if (this.room.hasCustomLayout())
{
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO room_models_custom (id, name, door_x, door_y, door_dir, heightmap) (SELECT ?, ?, door_x, door_y, door_dir, heightmap FROM room_models_custom WHERE id = ? LIMIT 1)", Statement.RETURN_GENERATED_KEYS))
{
if (this.room.hasCustomLayout()) {
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO room_models_custom (id, name, door_x, door_y, door_dir, heightmap) (SELECT ?, ?, door_x, door_y, door_dir, heightmap FROM room_models_custom WHERE id = ? LIMIT 1)", Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, roomId);
statement.setString(2, "custom_" + roomId);
statement.setInt(3, this.room.getId());
statement.execute();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
if (Emulator.getConfig().getBoolean("bundle.bots.enabled"))
{
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO bots (user_id, room_id, name, motto, figure, gender, x, y, z, chat_lines, chat_auto, chat_random, chat_delay, dance, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS))
{
synchronized (this.room.getCurrentBots())
{
if (Emulator.getConfig().getBoolean("bundle.bots.enabled")) {
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO bots (user_id, room_id, name, motto, figure, gender, x, y, z, chat_lines, chat_auto, chat_random, chat_delay, dance, type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
synchronized (this.room.getCurrentBots()) {
statement.setInt(1, userId);
statement.setInt(2, roomId);
for (Bot bot : this.room.getCurrentBots().valueCollection())
{
for (Bot bot : this.room.getCurrentBots().valueCollection()) {
statement.setString(3, bot.getName());
statement.setString(4, bot.getMotto());
statement.setString(5, bot.getFigure());
@ -244,8 +203,7 @@ public class RoomBundleLayout extends SingleBundle
statement.setInt(8, bot.getRoomUnit().getY());
statement.setDouble(9, bot.getRoomUnit().getZ());
StringBuilder text = new StringBuilder();
for (String s : bot.getChatLines())
{
for (String s : bot.getChatLines()) {
text.append(s).append("\r");
}
statement.setString(10, text.toString());
@ -260,9 +218,7 @@ public class RoomBundleLayout extends SingleBundle
statement.executeBatch();
}
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
@ -279,8 +235,7 @@ public class RoomBundleLayout extends SingleBundle
keys.put("OWNER", r.getOwnerName());
keys.put("image", "${image.library.url}/notifications/room_bundle_" + this.getId() + ".png");
if (habbo != null)
{
if (habbo != null) {
habbo.getClient().sendResponse(new BubbleAlertComposer(BubbleAlertKeys.PURCHASING_ROOM.key, keys));
}
}

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SingleBundle extends CatalogPage
{
public SingleBundle(ResultSet set) throws SQLException
{
public class SingleBundle extends CatalogPage {
public SingleBundle(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("single_bundle");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SoldLTDItemsLayout extends CatalogPage
{
public SoldLTDItemsLayout(ResultSet set) throws SQLException
{
public class SoldLTDItemsLayout extends CatalogPage {
public SoldLTDItemsLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("sold_ltd_items");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -8,14 +8,12 @@ import java.sql.SQLException;
public class SpacesLayout extends CatalogPage {
public SpacesLayout(ResultSet set) throws SQLException
{
public SpacesLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("spaces_new");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TraxLayout extends CatalogPage
{
public TraxLayout(ResultSet set) throws SQLException
{
public class TraxLayout extends CatalogPage {
public TraxLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("soundmachine");
message.appendInt(2);
message.appendString(super.getHeaderImage());

View File

@ -8,14 +8,12 @@ import java.sql.SQLException;
public class TrophiesLayout extends CatalogPage {
public TrophiesLayout(ResultSet set) throws SQLException
{
public TrophiesLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("trophies");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -6,16 +6,13 @@ import com.eu.habbo.messages.ServerMessage;
import java.sql.ResultSet;
import java.sql.SQLException;
public class VipBuyLayout extends CatalogPage
{
public VipBuyLayout(ResultSet set) throws SQLException
{
public class VipBuyLayout extends CatalogPage {
public VipBuyLayout(ResultSet set) throws SQLException {
super(set);
}
@Override
public void serialize(ServerMessage message)
{
public void serialize(ServerMessage message) {
message.appendString("vip_buy");
message.appendInt(3);
message.appendString(super.getHeaderImage());

View File

@ -25,8 +25,7 @@ import java.util.ArrayList;
import java.util.List;
public class MarketPlace
{
public class MarketPlace {
//Configuration. Loaded from database & updated accordingly.
public static boolean MARKETPLACE_ENABLED = true;
@ -34,22 +33,16 @@ public class MarketPlace
public static int MARKETPLACE_CURRENCY = 0;
public static THashSet<MarketPlaceOffer> getOwnOffers(Habbo habbo)
{
public static THashSet<MarketPlaceOffer> getOwnOffers(Habbo habbo) {
THashSet<MarketPlaceOffer> offers = new THashSet<>();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT items_base.type AS type, items.item_id AS base_item_id, items.limited_data AS ltd_data, marketplace_items.* FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE marketplace_items.user_id = ?"))
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT items_base.type AS type, items.item_id AS base_item_id, items.limited_data AS ltd_data, marketplace_items.* FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE marketplace_items.user_id = ?")) {
statement.setInt(1, habbo.getHabboInfo().getId());
try (ResultSet set = statement.executeQuery())
{
while (set.next())
{
try (ResultSet set = statement.executeQuery()) {
while (set.next()) {
offers.add(new MarketPlaceOffer(set, true));
}
}
}
catch(SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
@ -57,57 +50,43 @@ public class MarketPlace
}
public static void takeBackItem(Habbo habbo, int offerId)
{
public static void takeBackItem(Habbo habbo, int offerId) {
MarketPlaceOffer offer = habbo.getInventory().getOffer(offerId);
if (!Emulator.getPluginManager().fireEvent(new MarketPlaceItemCancelledEvent(offer)).isCancelled())
{
if (!Emulator.getPluginManager().fireEvent(new MarketPlaceItemCancelledEvent(offer)).isCancelled()) {
takeBackItem(habbo, offer);
}
}
private static void takeBackItem(Habbo habbo, MarketPlaceOffer offer)
{
if(offer != null && habbo.getInventory().getMarketplaceItems().contains(offer))
{
private static void takeBackItem(Habbo habbo, MarketPlaceOffer offer) {
if (offer != null && habbo.getInventory().getMarketplaceItems().contains(offer)) {
RequestOffersEvent.cachedResults.clear();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection())
{
try (PreparedStatement ownerCheck = connection.prepareStatement("SELECT user_id FROM marketplace_items WHERE id = ?"))
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
try (PreparedStatement ownerCheck = connection.prepareStatement("SELECT user_id FROM marketplace_items WHERE id = ?")) {
ownerCheck.setInt(1, offer.getOfferId());
try (ResultSet ownerSet = ownerCheck.executeQuery())
{
try (ResultSet ownerSet = ownerCheck.executeQuery()) {
ownerSet.last();
if (ownerSet.getRow() == 0)
{
if (ownerSet.getRow() == 0) {
return;
}
try (PreparedStatement statement = connection.prepareStatement("DELETE FROM marketplace_items WHERE id = ? AND state != 2"))
{
try (PreparedStatement statement = connection.prepareStatement("DELETE FROM marketplace_items WHERE id = ? AND state != 2")) {
statement.setInt(1, offer.getOfferId());
int count = statement.executeUpdate();
if (count != 0)
{
if (count != 0) {
habbo.getInventory().removeMarketplaceOffer(offer);
try (PreparedStatement updateItems = connection.prepareStatement("UPDATE items SET user_id = ? WHERE id = ? LIMIT 1"))
{
try (PreparedStatement updateItems = connection.prepareStatement("UPDATE items SET user_id = ? WHERE id = ? LIMIT 1")) {
updateItems.setInt(1, habbo.getHabboInfo().getId());
updateItems.setInt(2, offer.getSoldItemId());
updateItems.execute();
try (PreparedStatement selectItem = connection.prepareStatement("SELECT * FROM items WHERE id = ? LIMIT 1"))
{
try (PreparedStatement selectItem = connection.prepareStatement("SELECT * FROM items WHERE id = ? LIMIT 1")) {
selectItem.setInt(1, offer.getSoldItemId());
try (ResultSet set = selectItem.executeQuery())
{
while (set.next())
{
try (ResultSet set = selectItem.executeQuery()) {
while (set.next()) {
HabboItem item = Emulator.getGameEnvironment().getItemManager().loadHabboItem(set);
habbo.getInventory().getItemsComponent().addItem(item);
habbo.getClient().sendResponse(new MarketplaceCancelSaleComposer(offer, true));
@ -121,9 +100,7 @@ public class MarketPlace
}
}
}
}
catch(SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
habbo.getClient().sendResponse(new MarketplaceCancelSaleComposer(offer, false));
}
@ -134,23 +111,19 @@ public class MarketPlace
public static List<MarketPlaceOffer> getOffers(int minPrice, int maxPrice, String search, int sort) {
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 > ?";
if (minPrice > 0)
{
if (minPrice > 0) {
query += " AND CEIL(price + (price / 100)) >= " + minPrice;
}
if(maxPrice > 0 && maxPrice > minPrice)
{
if (maxPrice > 0 && maxPrice > minPrice) {
query += " AND CEIL(price + (price / 100)) <= " + maxPrice;
}
if(search.length() > 0)
{
if (search.length() > 0) {
query += " AND bi.public_name LIKE ?";
}
query += " GROUP BY base_item_id, ltd_data";
switch (sort)
{
switch (sort) {
case 6:
query += " ORDER BY number ASC";
break;
@ -178,23 +151,18 @@ public class MarketPlace
query += " LIMIT 100";
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(2, Emulator.getIntUnixTimestamp() - 172800);
if(search.length() > 0)
statement.setString(3, "%"+search+"%");
if (search.length() > 0)
statement.setString(3, "%" + search + "%");
try (ResultSet set = statement.executeQuery())
{
while (set.next())
{
try (ResultSet set = statement.executeQuery()) {
while (set.next()) {
offers.add(new MarketPlaceOffer(set, false));
}
}
}
catch(SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
@ -202,24 +170,20 @@ public class MarketPlace
}
public static void serializeItemInfo(int itemId, ServerMessage message)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT avg(price) as price, COUNT(*) as sold, (datediff(NOW(), DATE(from_unixtime(timestamp)))) as day FROM marketplace_items INNER JOIN items ON items.id = marketplace_items.item_id INNER JOIN items_base ON items.item_id = items_base.id WHERE items.limited_data = '0:0' AND state = 2 AND items_base.sprite_id = ? AND DATE(from_unixtime(timestamp)) >= NOW() - INTERVAL 30 DAY GROUP BY DATE(from_unixtime(timestamp))"))
{
public static void serializeItemInfo(int itemId, ServerMessage message) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT avg(price) as price, COUNT(*) as sold, (datediff(NOW(), DATE(from_unixtime(timestamp)))) as day FROM marketplace_items INNER JOIN items ON items.id = marketplace_items.item_id INNER JOIN items_base ON items.item_id = items_base.id WHERE items.limited_data = '0:0' AND state = 2 AND items_base.sprite_id = ? AND DATE(from_unixtime(timestamp)) >= NOW() - INTERVAL 30 DAY GROUP BY DATE(from_unixtime(timestamp))")) {
statement.setInt(1, itemId);
message.appendInt(avarageLastXDays(itemId, 7));
message.appendInt(itemsOnSale(itemId));
message.appendInt(30);
try (ResultSet set = statement.executeQuery())
{
try (ResultSet set = statement.executeQuery()) {
set.last();
message.appendInt(set.getRow());
set.beforeFirst();
while (set.next())
{
while (set.next()) {
message.appendInt(-set.getInt("day"));
message.appendInt(MarketPlace.calculateCommision(set.getInt("price")));
message.appendInt(set.getInt("sold"));
@ -228,29 +192,22 @@ public class MarketPlace
message.appendInt(1);
message.appendInt(itemId);
}
catch(SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
public static int itemsOnSale(int baseItemId)
{
public static int itemsOnSale(int baseItemId) {
int number = 0;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) as number, AVG(price) as avg FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE state = 1 AND timestamp >= ? AND items_base.sprite_id = ?"))
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT COUNT(*) as number, AVG(price) as avg FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE state = 1 AND timestamp >= ? AND items_base.sprite_id = ?")) {
statement.setInt(1, Emulator.getIntUnixTimestamp() - 172800);
statement.setInt(2, baseItemId);
try (ResultSet set = statement.executeQuery())
{
try (ResultSet set = statement.executeQuery()) {
set.first();
number = set.getInt("number");
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
@ -258,22 +215,17 @@ public class MarketPlace
}
private static int avarageLastXDays(int baseItemId, int days)
{
private static int avarageLastXDays(int baseItemId, int days) {
int avg = 0;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT AVG(price) as avg FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE state = 2 AND DATE(from_unixtime(timestamp)) >= NOW() - INTERVAL ? DAY AND items_base.sprite_id = ?"))
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT AVG(price) as avg FROM marketplace_items INNER JOIN items ON marketplace_items.item_id = items.id INNER JOIN items_base ON items.item_id = items_base.id WHERE state = 2 AND DATE(from_unixtime(timestamp)) >= NOW() - INTERVAL ? DAY AND items_base.sprite_id = ?")) {
statement.setInt(1, days);
statement.setInt(2, baseItemId);
try (ResultSet set = statement.executeQuery())
{
try (ResultSet set = statement.executeQuery()) {
set.first();
avg = set.getInt("avg");
}
}
catch(SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
@ -281,40 +233,26 @@ public class MarketPlace
}
public static void buyItem(int offerId, GameClient client)
{
public static void buyItem(int offerId, GameClient client) {
RequestOffersEvent.cachedResults.clear();
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection())
{
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM marketplace_items WHERE id = ? LIMIT 1"))
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM marketplace_items WHERE id = ? LIMIT 1")) {
statement.setInt(1, offerId);
try (ResultSet set = statement.executeQuery())
{
if (set.next())
{
try (PreparedStatement itemStatement = connection.prepareStatement("SELECT * FROM items WHERE id = ? LIMIT 1"))
{
try (ResultSet set = statement.executeQuery()) {
if (set.next()) {
try (PreparedStatement itemStatement = connection.prepareStatement("SELECT * FROM items WHERE id = ? LIMIT 1")) {
itemStatement.setInt(1, set.getInt("item_id"));
try (ResultSet itemSet = itemStatement.executeQuery())
{
try (ResultSet itemSet = itemStatement.executeQuery()) {
itemSet.first();
if (itemSet.getRow() > 0)
{
if (itemSet.getRow() > 0) {
int price = MarketPlace.calculateCommision(set.getInt("price"));
if (set.getInt("state") != 1)
{
if (set.getInt("state") != 1) {
sendErrorMessage(client, set.getInt("item_id"), offerId);
}
else if ((MARKETPLACE_CURRENCY == 0 && price > client.getHabbo().getHabboInfo().getCredits()) || (MARKETPLACE_CURRENCY > 0 && price > client.getHabbo().getHabboInfo().getCurrencyAmount(MARKETPLACE_CURRENCY)))
{
} else if ((MARKETPLACE_CURRENCY == 0 && price > client.getHabbo().getHabboInfo().getCredits()) || (MARKETPLACE_CURRENCY > 0 && price > client.getHabbo().getHabboInfo().getCurrencyAmount(MARKETPLACE_CURRENCY))) {
client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.NOT_ENOUGH_CREDITS, 0, offerId, price));
}
else
{
try (PreparedStatement updateOffer = connection.prepareStatement("UPDATE marketplace_items SET state = 2, sold_timestamp = ? WHERE id = ?"))
{
} else {
try (PreparedStatement updateOffer = connection.prepareStatement("UPDATE marketplace_items SET state = 2, sold_timestamp = ? WHERE id = ?")) {
updateOffer.setInt(1, Emulator.getIntUnixTimestamp());
updateOffer.setInt(2, offerId);
updateOffer.execute();
@ -323,8 +261,7 @@ public class MarketPlace
HabboItem item = Emulator.getGameEnvironment().getItemManager().loadHabboItem(itemSet);
MarketPlaceItemSoldEvent event = new MarketPlaceItemSoldEvent(habbo, client.getHabbo(), item, set.getInt("price"));
if (Emulator.getPluginManager().fireEvent(event).isCancelled())
{
if (Emulator.getPluginManager().fireEvent(event).isCancelled()) {
return;
}
event.price = calculateCommision(event.price);
@ -335,12 +272,9 @@ public class MarketPlace
client.getHabbo().getInventory().getItemsComponent().addItem(item);
if (MARKETPLACE_CURRENCY == 0)
{
if (MARKETPLACE_CURRENCY == 0) {
client.getHabbo().getHabboInfo().addCredits(-event.price);
}
else
{
} else {
client.getHabbo().givePoints(MARKETPLACE_CURRENCY, -event.price);
}
@ -349,8 +283,7 @@ public class MarketPlace
client.sendResponse(new InventoryRefreshComposer());
client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.REFRESH, 0, offerId, price));
if (habbo != null)
{
if (habbo != null) {
habbo.getInventory().getOffer(offerId).setState(MarketPlaceState.SOLD);
}
}
@ -360,16 +293,13 @@ public class MarketPlace
}
}
}
}
catch(SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
public static void sendErrorMessage(GameClient client, int baseItemId, int offerId) throws SQLException
{
public static void sendErrorMessage(GameClient client, int baseItemId, int offerId) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("SELECT marketplace_items.*, COUNT( * ) AS count\n" +
"FROM marketplace_items\n" +
"INNER JOIN items ON marketplace_items.item_id = items.id\n" +
@ -379,41 +309,37 @@ public class MarketPlace
"FROM items_base\n" +
"WHERE items_base.id = ? LIMIT 1)\n" +
"ORDER BY price ASC\n" +
"LIMIT 1"))
{
"LIMIT 1")) {
statement.setInt(1, baseItemId);
try (ResultSet countSet = statement.executeQuery())
{
try (ResultSet countSet = statement.executeQuery()) {
countSet.last();
if (countSet.getRow() == 0)
client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.SOLD_OUT, 0, offerId, 0));
else
{
else {
countSet.first();
client.sendResponse(new MarketplaceBuyErrorComposer(MarketplaceBuyErrorComposer.UPDATES, countSet.getInt("count"), countSet.getInt("id"), MarketPlace.calculateCommision(countSet.getInt("price"))));
}
}
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
public static boolean sellItem(GameClient client, HabboItem item, int price)
{
if(item == null || client == null)
public static boolean sellItem(GameClient client, HabboItem item, int price) {
if (item == null || client == null)
return false;
if (!item.getBaseItem().allowMarketplace() || price < 0)
return false;
MarketPlaceItemOfferedEvent event = new MarketPlaceItemOfferedEvent(client.getHabbo(), item, price);
if (Emulator.getPluginManager().fireEvent(event).isCancelled())
{
if (Emulator.getPluginManager().fireEvent(event).isCancelled()) {
return false;
}
RequestOffersEvent.cachedResults.clear();
try
{
client.sendResponse(new RemoveHabboItemComposer(event.item.getGiftAdjustedId()));
client.sendResponse(new InventoryRefreshComposer());
@ -425,27 +351,19 @@ public class MarketPlace
item.setUserId(-1);
item.needsUpdate(true);
Emulator.getThreading().run(item);
}
catch (SQLException e)
{
Emulator.getLogging().logSQLException(e);
}
return true;
}
public static void getCredits(GameClient client)
{
public static void getCredits(GameClient client) {
int credits = 0;
THashSet<MarketPlaceOffer> offers = new THashSet<>();
offers.addAll(client.getHabbo().getInventory().getMarketplaceItems());
for(MarketPlaceOffer offer : offers)
{
if(offer.getState().equals(MarketPlaceState.SOLD))
{
for (MarketPlaceOffer offer : offers) {
if (offer.getState().equals(MarketPlaceState.SOLD)) {
client.getHabbo().getInventory().removeMarketplaceOffer(offer);
credits += offer.getPrice();
removeUser(offer);
@ -456,34 +374,26 @@ public class MarketPlace
offers.clear();
if (MARKETPLACE_CURRENCY == 0)
{
if (MARKETPLACE_CURRENCY == 0) {
client.getHabbo().getHabboInfo().addCredits(credits);
}
else
{
} else {
client.getHabbo().givePoints(MARKETPLACE_CURRENCY, credits);
}
client.sendResponse(new UserCreditsComposer(client.getHabbo()));
}
private static void removeUser(MarketPlaceOffer offer)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE marketplace_items SET user_id = ? WHERE id = ?"))
{
private static void removeUser(MarketPlaceOffer offer) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE marketplace_items SET user_id = ? WHERE id = ?")) {
statement.setInt(1, -1);
statement.setInt(2, offer.getOfferId());
statement.execute();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
public static int calculateCommision(int price)
{
return price + (int)Math.ceil(price / 100.0);
public static int calculateCommision(int price) {
return price + (int) Math.ceil(price / 100.0);
}
}

View File

@ -8,8 +8,9 @@ import com.eu.habbo.habbohotel.users.HabboItem;
import java.sql.*;
public class MarketPlaceOffer implements Runnable
{
public class MarketPlaceOffer implements Runnable {
public int avarage;
public int count;
private int offerId;
private Item baseItem;
private int itemId;
@ -21,11 +22,7 @@ public class MarketPlaceOffer implements Runnable
private MarketPlaceState state = MarketPlaceState.OPEN;
private boolean needsUpdate = false;
public int avarage;
public int count;
public MarketPlaceOffer(ResultSet set, boolean privateOffer) throws SQLException
{
public MarketPlaceOffer(ResultSet set, boolean privateOffer) throws SQLException {
this.offerId = set.getInt("id");
this.price = set.getInt("price");
this.timestamp = set.getInt("timestamp");
@ -34,33 +31,28 @@ public class MarketPlaceOffer implements Runnable
this.state = MarketPlaceState.getType(set.getInt("state"));
this.itemId = set.getInt("item_id");
if(!set.getString("ltd_data").split(":")[1].equals("0"))
{
if (!set.getString("ltd_data").split(":")[1].equals("0")) {
this.limitedStack = Integer.valueOf(set.getString("ltd_data").split(":")[0]);
this.limitedNumber = Integer.valueOf(set.getString("ltd_data").split(":")[1]);
}
if(!privateOffer)
{
if (!privateOffer) {
this.avarage = set.getInt("avg");
this.count = set.getInt("number");
this.price = set.getInt("minPrice");
}
}
public MarketPlaceOffer(HabboItem item, int price, Habbo habbo) throws SQLException
{
public MarketPlaceOffer(HabboItem item, int price, Habbo habbo) {
this.price = price;
this.baseItem = item.getBaseItem();
this.itemId = item.getId();
if(item.getLimitedSells() > 0)
{
if (item.getLimitedSells() > 0) {
this.limitedNumber = item.getLimitedSells();
this.limitedStack = item.getLimitedStack();
}
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO marketplace_items (item_id, user_id, price, timestamp, state) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS))
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO marketplace_items (item_id, user_id, price, timestamp, state) VALUES (?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, item.getId());
statement.setInt(2, habbo.getHabboInfo().getId());
statement.setInt(3, this.price);
@ -68,115 +60,18 @@ public class MarketPlaceOffer implements Runnable
statement.setString(5, this.state.getState() + "");
statement.execute();
try (ResultSet id = statement.getGeneratedKeys())
{
while (id.next())
{
try (ResultSet id = statement.getGeneratedKeys()) {
while (id.next()) {
this.offerId = id.getInt(1);
}
}
}
}
public int getOfferId()
{
return this.offerId;
}
public void setOfferId(int offerId)
{
this.offerId = offerId;
}
public int getItemId()
{
return this.baseItem.getSpriteId();
}
public int getPrice()
{
return this.price;
}
public MarketPlaceState getState()
{
return this.state;
}
public void setState(MarketPlaceState state)
{
this.state = state;
}
public int getTimestamp()
{
return this.timestamp;
}
public int getSoldTimestamp()
{
return this.soldTimestamp;
}
public void setSoldTimestamp(int soldTimestamp)
{
this.soldTimestamp = soldTimestamp;
}
public int getLimitedStack()
{
return this.limitedStack;
}
public int getLimitedNumber()
{
return this.limitedNumber;
}
public int getSoldItemId()
{
return this.itemId;
}
public void needsUpdate(boolean value)
{
this.needsUpdate = value;
}
public int getType()
{
if (this.limitedStack > 0)
{
return 3;
}
return this.baseItem.getType().equals(FurnitureType.WALL) ? 2 : 1;
}
@Override
public void run()
{
if(this.needsUpdate)
{
this.needsUpdate = false;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE marketplace_items SET state = ?, sold_timestamp = ? WHERE id = ?"))
{
statement.setInt(1, this.state.getState());
statement.setInt(2, this.soldTimestamp);
statement.setInt(3, this.offerId);
statement.execute();
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
}
public static void insert(MarketPlaceOffer offer, Habbo habbo)
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO marketplace_items VALUES (?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS))
{
public static void insert(MarketPlaceOffer offer, Habbo habbo) {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO marketplace_items VALUES (?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
statement.setInt(1, offer.getItemId());
statement.setInt(2, habbo.getHabboInfo().getId());
statement.setInt(3, offer.getPrice());
@ -185,17 +80,88 @@ public class MarketPlaceOffer implements Runnable
statement.setString(6, offer.getState().getState() + "");
statement.execute();
try (ResultSet id = statement.getGeneratedKeys())
{
while (id.next())
{
try (ResultSet id = statement.getGeneratedKeys()) {
while (id.next()) {
offer.setOfferId(id.getInt(1));
}
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
public int getOfferId() {
return this.offerId;
}
public void setOfferId(int offerId) {
this.offerId = offerId;
}
public int getItemId() {
return this.baseItem.getSpriteId();
}
public int getPrice() {
return this.price;
}
public MarketPlaceState getState() {
return this.state;
}
public void setState(MarketPlaceState state) {
this.state = state;
}
public int getTimestamp() {
return this.timestamp;
}
public int getSoldTimestamp() {
return this.soldTimestamp;
}
public void setSoldTimestamp(int soldTimestamp) {
this.soldTimestamp = soldTimestamp;
}
public int getLimitedStack() {
return this.limitedStack;
}
public int getLimitedNumber() {
return this.limitedNumber;
}
public int getSoldItemId() {
return this.itemId;
}
public void needsUpdate(boolean value) {
this.needsUpdate = value;
}
public int getType() {
if (this.limitedStack > 0) {
return 3;
}
return this.baseItem.getType().equals(FurnitureType.WALL) ? 2 : 1;
}
@Override
public void run() {
if (this.needsUpdate) {
this.needsUpdate = false;
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("UPDATE marketplace_items SET state = ?, sold_timestamp = ? WHERE id = ?")) {
statement.setInt(1, this.state.getState());
statement.setInt(2, this.soldTimestamp);
statement.setInt(3, this.offerId);
statement.execute();
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}
}
}

View File

@ -1,7 +1,6 @@
package com.eu.habbo.habbohotel.catalog.marketplace;
public enum MarketPlaceState
{
public enum MarketPlaceState {
OPEN(1),
@ -13,27 +12,25 @@ public enum MarketPlaceState
private final int state;
MarketPlaceState(int state)
{
MarketPlaceState(int state) {
this.state = state;
}
public int getState()
{
return this.state;
}
public static MarketPlaceState getType(int type)
{
switch(type)
{
case 1: return OPEN;
case 2: return SOLD;
case 3: return CLOSED;
public static MarketPlaceState getType(int type) {
switch (type) {
case 1:
return OPEN;
case 2:
return SOLD;
case 3:
return CLOSED;
}
return CLOSED;
}
public int getState() {
return this.state;
}
}

View File

@ -3,16 +3,13 @@ package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.catalog.CatalogManager;
import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.messages.outgoing.generic.alerts.GenericAlertComposer;
import java.util.concurrent.TimeUnit;
public class AboutCommand extends Command
{
public AboutCommand()
{
super(null, new String[]{ "about", "info", "online", "server" });
public class AboutCommand extends Command {
public AboutCommand() {
super(null, new String[]{"about", "info", "online", "server"});
}
@Override
@ -20,15 +17,14 @@ public class AboutCommand extends Command
Emulator.getRuntime().gc();
int seconds = Emulator.getIntUnixTimestamp() - Emulator.getTimeStarted();
int day = (int)TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds) * 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) * 60);
String message = "<b>" + Emulator.version + "</b>\r\n";
if (Emulator.getConfig().getBoolean("info.shown", true))
{
if (Emulator.getConfig().getBoolean("info.shown", true)) {
message += "<b>Hotel Statistics</b>\r" +
"- Online Users: " + Emulator.getGameEnvironment().getHabboManager().getOnlineCount() + "\r" +
"- Active Rooms: " + Emulator.getGameEnvironment().getRoomManager().getActiveRooms().size() + "\r" +

View File

@ -0,0 +1,59 @@
package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.items.YoutubeManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class AddYoutubePlaylistCommand extends Command {
public AddYoutubePlaylistCommand() {
super("cmd_add_youtube_playlist", Emulator.getTexts().getValue("commands.keys.cmd_add_youtube_playlist").split(";"));
}
@Override
public boolean handle(GameClient gameClient, String[] params) throws Exception {
if (params.length < 3) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_add_youtube_playlist.usage"));
return true;
}
int itemId;
try {
itemId = Integer.valueOf(params[1]);
} catch (NumberFormatException e) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_add_youtube_playlist.no_base_item"));
return true;
}
if (Emulator.getGameEnvironment().getItemManager().getItem(itemId) == null) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_add_youtube_playlist.no_base_item"));
return true;
}
YoutubeManager.YoutubePlaylist playlist = Emulator.getGameEnvironment().getItemManager().getYoutubeManager().getPlaylistDataById(params[2]);
if (playlist == null) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_add_youtube_playlist.failed_playlist"));
return true;
}
Emulator.getGameEnvironment().getItemManager().getYoutubeManager().addPlaylistToItem(Integer.valueOf(params[1]), playlist);
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection(); PreparedStatement statement = connection.prepareStatement("INSERT INTO `youtube_playlists` (`item_id`, `playlist_id`) VALUES (?, ?)")) {
statement.setInt(1, itemId);
statement.setString(2, params[2]);
statement.execute();
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_add_youtube_playlist"));
return true;
}
}

View File

@ -4,25 +4,20 @@ import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.messages.outgoing.generic.alerts.GenericAlertComposer;
public class AlertCommand extends Command {
public AlertCommand()
{
public AlertCommand() {
super("cmd_alert", Emulator.getTexts().getValue("commands.keys.cmd_alert").split(";"));
}
@Override
public boolean handle(GameClient gameClient, String[] params)
{
if(params.length < 2)
{
public boolean handle(GameClient gameClient, String[] params) {
if (params.length < 2) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_alert.forgot_username"), RoomChatMessageBubbles.ALERT);
return true;
}
if(params.length < 3)
{
if (params.length < 3) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_alert.forgot_message"), RoomChatMessageBubbles.ALERT);
return true;
}
@ -30,8 +25,7 @@ public class AlertCommand extends Command {
String targetUsername = params[1];
StringBuilder message = new StringBuilder();
for(int i = 2; i < params.length; i++)
{
for (int i = 2; i < params.length; i++) {
message.append(params[i]).append(" ");
}

View File

@ -8,63 +8,50 @@ import com.eu.habbo.messages.outgoing.users.UserPerksComposer;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class AllowTradingCommand extends Command
{
public AllowTradingCommand()
{
public class AllowTradingCommand extends Command {
public AllowTradingCommand() {
super("cmd_allow_trading", Emulator.getTexts().getValue("commands.keys.cmd_allow_trading").split(";"));
}
@Override
public boolean handle(GameClient gameClient, String[] params) throws Exception
{
if (params.length == 1)
{
public boolean handle(GameClient gameClient, String[] params) throws Exception {
if (params.length == 1) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.forgot_username"));
return true;
}
if (params.length == 2)
{
if (params.length == 2) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.forgot_trade").replace("%username%", params[1]));
return true;
}
if (params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes")) || params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.no")))
{
if (params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes")) || params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.no"))) {
String username = params[1];
boolean enabled = params[2].equalsIgnoreCase(Emulator.getTexts().getValue("generic.yes"));
Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(username);
if (habbo != null)
{
if (habbo != null) {
habbo.getHabboStats().setAllowTrade(enabled);
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_allow_trading." + (enabled ? "enabled" : "disabled")).replace("%username%", params[1]));
habbo.getClient().sendResponse(new UserPerksComposer(habbo));
return true;
}
else
{
} else {
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.id SET can_trade = ? WHERE users.username LIKE ?")) {
statement.setString(1, enabled ? "1" : "0");
statement.setString(2, username);
found = statement.executeUpdate() > 0;
}
if (!found)
{
if (!found) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.user_not_found").replace("%username%", params[1]));
return true;
}
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_allow_trading." + (enabled ? "enabled" : "disabled")).replace("%username%", params[1]));
}
}
else
{
} else {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_allow_trading.incorrect_setting").replace("%enabled%", Emulator.getTexts().getValue("generic.yes")).replace("%disabled%", Emulator.getTexts().getValue("generic.no")));
}
return true;

View File

@ -3,17 +3,14 @@ package com.eu.habbo.habbohotel.commands;
import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
public class ArcturusCommand extends Command
{
public ArcturusCommand()
{
super(null, new String[]{ "arcturus", "emulator" });
public class ArcturusCommand extends Command {
public ArcturusCommand() {
super(null, new String[]{"arcturus", "emulator"});
}
@Override
public boolean handle(GameClient gameClient, String[] params) throws Exception
{
if(gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null)
{
public boolean handle(GameClient gameClient, String[] params) throws Exception {
if (gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null) {
gameClient.getHabbo().whisper("This hotel is powered by Arcturus Emulator! \r" +
"Cet hôtel est alimenté par Arcturus émulateur! \r" +
"Dit hotel draait op Arcturus Emulator! \r" +

View File

@ -10,69 +10,50 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BadgeCommand extends Command
{
public BadgeCommand()
{
public class BadgeCommand extends Command {
public BadgeCommand() {
super("cmd_badge", Emulator.getTexts().getValue("commands.keys.cmd_badge").split(";"));
}
@Override
public boolean handle(GameClient gameClient, String[] params) throws Exception
{
if(params.length == 1)
{
public boolean handle(GameClient gameClient, String[] params) throws Exception {
if (params.length == 1) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.forgot_username"), RoomChatMessageBubbles.ALERT);
return true;
}
if(params.length == 2)
{
if (params.length == 2) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.forgot_badge").replace("%user%", params[1]), RoomChatMessageBubbles.ALERT);
return true;
}
if(params.length == 3)
{
if (params.length == 3) {
Habbo habbo = Emulator.getGameEnvironment().getHabboManager().getHabbo(params[1]);
if(habbo != null)
{
if (habbo.addBadge(params[2]))
{
if (habbo != null) {
if (habbo.addBadge(params[2])) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_badge.given").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT);
}
else
{
} else {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.already_owned").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT);
}
return true;
}
else
{
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection())
{
} else {
try (Connection connection = Emulator.getDatabase().getDataSource().getConnection()) {
boolean found;
try (PreparedStatement statement = connection.prepareStatement("SELECT `badge_code` FROM `users_badges` INNER JOIN `users` ON `users`.`id` = `user_id` WHERE `users`.`username` = ? AND `badge_code` = ? LIMIT 1"))
{
try (PreparedStatement statement = connection.prepareStatement("SELECT `badge_code` FROM `users_badges` INNER JOIN `users` ON `users`.`id` = `user_id` WHERE `users`.`username` = ? AND `badge_code` = ? LIMIT 1")) {
statement.setString(1, params[1]);
statement.setString(2, params[2]);
try (ResultSet set = statement.executeQuery())
{
try (ResultSet set = statement.executeQuery()) {
found = set.next();
}
}
if(found)
{
if (found) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_badge.already_owns").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT);
return true;
}
else
{
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO users_badges (`id`, `user_id`, `slot_id`, `badge_code`) VALUES (null, (SELECT `id` FROM `users` WHERE `username` = ? LIMIT 1), 0, ?)"))
{
} else {
try (PreparedStatement statement = connection.prepareStatement("INSERT INTO users_badges (`id`, `user_id`, `slot_id`, `badge_code`) VALUES (null, (SELECT `id` FROM `users` WHERE `username` = ? LIMIT 1), 0, ?)")) {
statement.setString(1, params[1]);
statement.setString(2, params[2]);
statement.execute();
@ -81,9 +62,7 @@ public class BadgeCommand extends Command
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_badge.given").replace("%user%", params[1]).replace("%badge%", params[2]), RoomChatMessageBubbles.ALERT);
return true;
}
}
catch (SQLException e)
{
} catch (SQLException e) {
Emulator.getLogging().logSQLException(e);
}
}

View File

@ -9,47 +9,37 @@ import com.eu.habbo.habbohotel.users.Habbo;
import com.eu.habbo.habbohotel.users.HabboInfo;
import com.eu.habbo.habbohotel.users.HabboManager;
public class BanCommand extends Command
{
public BanCommand()
{
public class BanCommand extends Command {
public BanCommand() {
super("cmd_ban", Emulator.getTexts().getValue("commands.keys.cmd_ban").split(";"));
}
@Override
public boolean handle(GameClient gameClient, String[] params) throws Exception
{
if(params.length < 2)
{
public boolean handle(GameClient gameClient, String[] params) throws Exception {
if (params.length < 2) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.forgot_user"), RoomChatMessageBubbles.ALERT);
return true;
}
if(params.length < 3)
{
if (params.length < 3) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.forgot_time"), RoomChatMessageBubbles.ALERT);
return true;
}
int banTime;
try
{
try {
banTime = Integer.valueOf(params[2]);
}
catch (Exception e)
{
} catch (Exception e) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.invalid_time"), RoomChatMessageBubbles.ALERT);
return true;
}
if(banTime < 600)
{
if (banTime < 600) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.time_to_short"), RoomChatMessageBubbles.ALERT);
return true;
}
if(params[1].toLowerCase().equals(gameClient.getHabbo().getHabboInfo().getUsername().toLowerCase()))
{
if (params[1].toLowerCase().equals(gameClient.getHabbo().getHabboInfo().getUsername().toLowerCase())) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.ban_self"), RoomChatMessageBubbles.ALERT);
return true;
}
@ -57,23 +47,18 @@ public class BanCommand extends Command
Habbo t = Emulator.getGameEnvironment().getHabboManager().getHabbo(params[1]);
HabboInfo target;
if (t != null)
{
if (t != null) {
target = t.getHabboInfo();
}
else
{
} else {
target = HabboManager.getOfflineHabboInfo(params[1]);
}
if (target == null)
{
if (target == null) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.user_offline"), RoomChatMessageBubbles.ALERT);
return true;
}
if (target.getRank().getId() >= gameClient.getHabbo().getHabboInfo().getRank().getId())
{
if (target.getRank().getId() >= gameClient.getHabbo().getHabboInfo().getRank().getId()) {
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.error.cmd_ban.target_rank_higher"), RoomChatMessageBubbles.ALERT);
return true;
}
@ -81,10 +66,8 @@ public class BanCommand extends Command
StringBuilder reason = new StringBuilder();
if(params.length > 3)
{
for(int i = 3; i < params.length; i++)
{
if (params.length > 3) {
for (int i = 3; i < params.length; i++) {
reason.append(params[i]).append(" ");
}
}

View File

@ -4,18 +4,14 @@ import com.eu.habbo.Emulator;
import com.eu.habbo.habbohotel.gameclients.GameClient;
import com.eu.habbo.habbohotel.rooms.RoomChatMessageBubbles;
public class BlockAlertCommand extends Command
{
public BlockAlertCommand()
{
public class BlockAlertCommand extends Command {
public BlockAlertCommand() {
super("cmd_blockalert", Emulator.getTexts().getValue("commands.keys.cmd_blockalert").split(";"));
}
@Override
public boolean handle(GameClient gameClient, String[] params) throws Exception
{
if(gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null)
{
public boolean handle(GameClient gameClient, String[] params) throws Exception {
if (gameClient.getHabbo().getHabboInfo().getCurrentRoom() != null) {
gameClient.getHabbo().getHabboStats().blockStaffAlerts = !gameClient.getHabbo().getHabboStats().blockStaffAlerts;
gameClient.getHabbo().whisper(Emulator.getTexts().getValue("commands.succes.cmd_blockalert").replace("%state%", (gameClient.getHabbo().getHabboStats().blockStaffAlerts ? Emulator.getTexts().getValue("generic.on") : Emulator.getTexts().getValue("generic.off"))), RoomChatMessageBubbles.ALERT);

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