diff --git a/.gitignore b/.gitignore index b9cbf8fe..11eef07b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,221 +1,224 @@ -################# -## Eclipse -################# - -*.pydevproject -.metadata -bin/ -tmp/ -*.tmp -*.bak -*.pkc -*.swp -*~.nib -local.properties -.settings/ -.loadpath -*.ltn -*.pln -*.lsb -pt_sword_glint -*.lod -*.msh -*.mesh -*.iff -*.pob -*.ws -*.trn -*.tga -*.lmg -*.sat -*.lay -*.flr -*.apt -*.prt -*.cfg -*.spr -*.swh -*.jdb -*.lck -*.mgn -*.0 -cachedir/ -appearance/ -clientdata/ -*.class - -# SWG Client Folders -footprint/ -interiorlayout/ -clientdata/quest/ - -# PSWG Object Databases -odb/building/je.info.* -odb/creature/je.info.* -odb/doids/je.info.* -odb/guild/je.info.* -odb/mails/je.info.* -odb/oids/je.info.* -odb/chatRooms/je.info.* -odb/resourcehistory/je.info.* -odb/resourceroots/je.info.* -odb/resources/je.info.* -odb/auction/je.info.* -odb/swgobjects/je.info.* -odb/bounties/je.info.* -odb/cities/je.info.* - -# External tool builders -.externalToolBuilders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# CDT-specific -.cproject - -# PDT-specific -.buildpath - -# Log files +################# +## Eclipse +################# + +*.pydevproject +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.pkc +*.swp +*~.nib +local.properties +.settings/ +.loadpath +*.ltn +*.pln +*.lsb +pt_sword_glint +*.lod +*.msh +*.mesh +*.iff +*.pob +*.ws +*.trn +*.tga +*.lmg +*.sat +*.lay +*.flr +*.apt +*.prt +*.cfg +*.spr +*.swh +*.jdb +*.lck +*.mgn +*.0 +cachedir/ +appearance/ +clientdata/ +*.class + +# SWG Client Folders +footprint/ +interiorlayout/ +clientdata/quest/ + +# PSWG Object Databases +odb/building/je.info.* +odb/creature/je.info.* +odb/doids/je.info.* +odb/guild/je.info.* +odb/mails/je.info.* +odb/oids/je.info.* +odb/chatRooms/je.info.* +odb/resourcehistory/je.info.* +odb/resourceroots/je.info.* +odb/resources/je.info.* +odb/auction/je.info.* +odb/swgobjects/je.info.* +odb/bounties/je.info.* +odb/cities/je.info.* + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + +# Log files debuglogs/ -logs/ - -################# -## Visual Studio -################# - -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. - -# User-specific files -*.suo -*.user -*.sln.docstates - -# Build results -[Dd]ebug/ -[Rr]elease/ -*_i.c -*_p.c -*.ilk -*.meta -*.obj -*.pch -*.pdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.vspscc -.builds -*.dotCover - -## TODO: If you have NuGet Package Restore enabled, uncomment this -#packages/ - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opensdf -*.sdf - -# Visual Studio profiler -*.psess -*.vsp - -# ReSharper is a .NET coding add-in -_ReSharper* - -# Installshield output folder -[Ee]xpress - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish - -# Others -[Bb]in -[Oo]bj -sql -TestResults -*.Cache -ClientBin -stylecop.* -~$* -*.dbmdl -Generated_Code #added for RIA/Silverlight projects - -# Backup & report files from converting an old project file to a newer -# Visual Studio version. Backup files are not needed, because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML - - - -############ -## Windows -############ - -# Windows image file caches -Thumbs.db - -# Folder config file -Desktop.ini - - -############# -## Python -############# - -*.py[co] - -# Packages -*.egg -*.egg-info -dist -build -eggs -parts -bin -var -sdist -develop-eggs -.installed.cfg - -# Installer logs -pip-log.txt - -# Unit test / coverage reports -.coverage -.tox - -#Translations -*.mo - -#Mr Developer -.mr.developer.cfg - -# Mac crap -.DS_Store - - -############# -## PyCharm -############# -.idea +logs/ + +################# +## Visual Studio +################# + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results +[Dd]ebug/ +[Rr]elease/ +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.vspscc +.builds +*.dotCover + +## TODO: If you have NuGet Package Restore enabled, uncomment this +#packages/ + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf + +# Visual Studio profiler +*.psess +*.vsp + +# ReSharper is a .NET coding add-in +_ReSharper* + +# Installshield output folder +[Ee]xpress + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish + +# Others +[Bb]in +[Oo]bj +sql +TestResults +*.Cache +ClientBin +stylecop.* +~$* +*.dbmdl +Generated_Code #added for RIA/Silverlight projects + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML + + + +############ +## Windows +############ + +# Windows image file caches +Thumbs.db + +# Folder config file +Desktop.ini + + +############# +## Python +############# + +*.py[co] + +# Packages +*.egg +*.egg-info +dist +build +eggs +parts +bin +var +sdist +develop-eggs +.installed.cfg + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox + +#Translations +*.mo + +#Mr Developer +.mr.developer.cfg + +# Mac crap +.DS_Store + + +############# +## PyCharm +############# +.idea + +# The config should be example only +nge.cfg diff --git a/README.md b/README.md index 1523c7a5..e1874751 100644 --- a/README.md +++ b/README.md @@ -1,66 +1,65 @@ -NGECore2 -======== +# NGECore2 The ProjectSWG Open Source Project's aim is to create a server emulator for the sandbox MMO Star Wars Galaxies at its final publish before shutdown on 15/12/2011. The Open Source Version of ProjectSWG is restricted to 30 minutes uptime and upto 5 connections to ensure that the community -is not split between several small servers. This restriction will not be lifted, it is also not legal to remove this restriction for anyone(see the engine's license for more legal information). +is not split between several small servers. This restriction will not be lifted. It is not legal to remove this restriction, per the license. -The Engine(NGEngine) is a closed source library and is only licensed for use with this project. The Core(NGECore2) is licensed under the L-GPL License. +The Engine (NGEngine) is a closed source library and is only licensed for use with this project. The Core (NGECore2) is licensed under the L-GPL License. By using NGECore2, you agree to the terms of both licenses. -Requirements for Building the Core: -======== +## Requirements for Building the Core: -- JDK 8 -- A Java 8 compatible IDE like Eclipse Kepler (https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler) -- A valid Star Wars Galaxies Installation with the final patch -- Postgresql server (www.postgresql.org) -- TRE Explorer(http://forum.modsource.org/index.php?PHPSESSID=bf02fd8244123807f4716c1686abb59f&action=dlattach;topic=33.0;attach=49) -- Github account -- (optional for windows) Github for Windows(http://windows.github.com/) +* JDK 8 +* A Java 8 compatible IDE like Eclipse Kepler + * https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler +* A valid Star Wars Galaxies Installation with the final patch +* Postgresql server + * http://www.postgresql.org +* PGAdmin (optional, but makes managing the database easier) + * http://www.pgadmin.org/ +* TRE Explorer + * http://forum.modsource.org/index.php?PHPSESSID=bf02fd8244123807f4716c1686abb59f&action=dlattach;topic=33.0;attach=49 +* Github account +* Github for Windows (optional) + * http://windows.github.com/ -Once you have met the requirements, fork the project(click on the fork button) and then clone your forked repository. -If you are using Windows then you can clone the repository with Github for Windows, otherwise you can use the following git command: +### Setting up the core - git clone https://github.com/your_account_name/ngecore2.git +A video tutorial of this process can be viewed at http://www.projectswg.com/showthread.php?t=40304 -Then you can import the project to Eclipse. +1. Once you have met the requirements, fork the project and then proceed to clone your copy of the repository to your computer. +2. Import the project to Eclipse. +3. Create a postgres DB and restore the nge.backup file. Depending on each update, you may or may not have to repeat this process. Once restored, create an account for yourself in the accounts table of your database, and update the connectionServers table with the appropriate IP address of your server, in the address field. +4. Copy nge.cfg.example to nge.cfg, and add your DB credentials and name. +5. Create a directory named "clientdata" inside your NGECore2 git repo. +5. Open TRE Explorer and proceed open the sku0_client.toc in your SWG directory. Export the following directories to your clientdata directory: -Next you need to create a postgres DB and restore the nge.backup file. Once you have done that, edit your nge.cfg with your DB information and create an account for yourself in the accounts table of your database. +* abstract +* appearance +* creation +* customization +* datatables +* footprint +* interiorlayout +* misc +* object +* quest +* snapshot +* string +* terrain -Once you've done that open TRE Explorer and open the sku0_client.toc in your SWG folder with it. +Repeat the above extraction process with the sku1_client.toc, sku2_client.toc and sku3_client.toc files to avoid errors with kashyyyk. -Then export the following folders to your clientdata folder(should be located in your project folder): -- abstract -- appearance -- creation -- customization -- datatables -- footprint -- interiorlayout -- misc -- object -- quest -- snapshot -- string -- terrain +You are now ready to run the core! -Export the same folders from sku1_client.toc, sku2_client.toc and sku3_client.toc to avoid errors with kashyyyk. +## Contributing and Submitting patches -Now you're ready to run the core! - -Contributing and Submitting patches -======== - -To contribute, simply commit your changes to your fork of the project and then submit a pull request here: - - https://github.com/ProjectSWGCore/NGECore2/compare/ - -Now your changes will be reviewed by other developers and once the changes are approved your code will be merged into the main repository. - -For more information please visit the wiki: https://github.com/ProjectSWGCore/NGECore2/wiki - -Documentation can be found here: http://projectswg.com/doc/ +To contribute, commit your changes to your fork of the project and then submit a pull request. + +Your changes will be reviewed by other developers. Once the changes are approved, your pull request will be merged into the main repository. Please prefix all commits with Added, Changed, Removed or Fixed. If you don't have enough room for multiple changes, use the extended description. Try not to bundle multiple changes into one vague line (ie. "Changed various combat things"). Try to make all commit messages understandable by non-programmers. + +* For more information please visit the wiki at https://github.com/ProjectSWGCore/NGECore2/wiki +* Documentation can be found at http://projectswg.com/doc/ diff --git a/nge.cfg b/nge.cfg.example similarity index 100% rename from nge.cfg rename to nge.cfg.example diff --git a/src/main/NGECore.java b/src/main/NGECore.java index 1cc1d7e3..3a2c1121 100644 --- a/src/main/NGECore.java +++ b/src/main/NGECore.java @@ -134,30 +134,29 @@ import engine.servers.InteractiveJythonServer; import engine.servers.MINAServer; import engine.servers.PingServer; - @SuppressWarnings("unused") public class NGECore { - + private static boolean logUnhandledExceptions = true; - + public static boolean didServerCrash = false; - + private static NGECore instance; - + private Config config = null; private Config options = null; private String motd = ""; private volatile boolean isShuttingDown = false; private long galacticTime = System.currentTimeMillis(); private int galaxyStatus = -1; - + private ConcurrentHashMap clients = new ConcurrentHashMap(); - + // Database - + private DatabaseConnection databaseConnection = null; private DatabaseConnection databaseConnection2 = null; - + // Services public LoginService loginService; public RetroService retroService; @@ -206,18 +205,18 @@ public class NGECore { public ReverseEngineeringService reverseEngineeringService; public PetService petService; public BrowserService browserService; - //public BattlefieldService battlefieldService; + // public BattlefieldService battlefieldService; public InvasionService invasionService; public AdminService adminService; - + // Login Server public NetworkDispatch loginDispatch; private MINAServer loginServer; - + // Zone Server public NetworkDispatch zoneDispatch; private MINAServer zoneServer; - + // Interactive Jython Console public InteractiveJythonAcceptor jythonAcceptor; private InteractiveJythonServer jythonServer; @@ -227,26 +226,54 @@ public class NGECore { private ObjectDatabase objectIdODB; private ObjectDatabase duplicateIdODB; private ObjectDatabase chatRoomODB; - - private BusConfiguration eventBusConfig = BusConfiguration.Default(1, new ThreadPoolExecutor(1, 4, 1, TimeUnit.MINUTES, new LinkedBlockingQueue())); + + private BusConfiguration eventBusConfig = BusConfiguration.Default(1, + new ThreadPoolExecutor(1, 4, 1, TimeUnit.MINUTES, + new LinkedBlockingQueue())); private ObjectDatabase auctionODB; private ObjectDatabase resourceHistoryODB; private ObjectDatabase swgObjectODB; private ObjectDatabase bountiesODB; private ObjectDatabase cityODB; - + public static boolean PACKET_DEBUG = false; - + public NGECore() { instance = this; } - + + // our entry point + public static void main(String[] args) { + // With this class, we are overwriting the JVM's way of handling + // exceptions that are never caught. Very handy so no try/catch spam for + // every method. + if (logUnhandledExceptions) + Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionLogger( + "./logs/uncaught")); + + NGECore core = new NGECore(); + + core.start(); + + do { + if (didServerCrash) { + core.restart(); + } + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + + } + } while (true); + + } + public void start() { - + instance = this; - + final ThreadMonitor deadlockDetector = new ThreadMonitor(); Thread deadlockMonitor = new Thread(new Runnable() { @Override @@ -265,7 +292,7 @@ public class NGECore { if (!(config.loadConfigFile())) { config = DefaultConfig.getConfig(); } - + DevLogQueuer devLogQueuer = new DevLogQueuer(); CharonPacketLogger packetLogger; @@ -279,60 +306,83 @@ public class NGECore { options = DefaultConfig.getConfig(); } - if (options.getInt("CLEAN.ODB.FOLDERS") > 0){ + if (options.getInt("CLEAN.ODB.FOLDERS") > 0) { File baseFolder = new File("./odb"); - + if (baseFolder.isDirectory()) { for (File odbFolder : baseFolder.listFiles()) { if (odbFolder.isDirectory()) { for (File file : odbFolder.listFiles()) { - if (!file.isDirectory() && !file.getName().equals("placeholder.txt")) { file.delete(); } + if (!file.isDirectory() + && !file.getName() + .equals("placeholder.txt")) { + file.delete(); + } } } } } - - + System.out.println("Cleaned ODB Folders."); } - - try(BufferedReader br = new BufferedReader(new FileReader("./motd.txt"))) { - for(String line; (line = br.readLine()) != null;) { + + try (BufferedReader br = new BufferedReader( + new FileReader("./motd.txt"))) { + for (String line; (line = br.readLine()) != null;) { motd += line; } - } catch (IOException e1) { e1.printStackTrace(); } + } catch (IOException e1) { + e1.printStackTrace(); + } // Database databaseConnection = new DatabaseConnection(); - databaseConnection.connect(config.getString("DB.URL"), config.getString("DB.NAME"), config.getString("DB.USER"), config.getString("DB.PASS"), "postgresql"); + databaseConnection.connect(config.getString("DB.URL"), + config.getString("DB.NAME"), config.getString("DB.USER"), + config.getString("DB.PASS"), "postgresql"); String db2Url = config.getString("DB2.URL"); if (db2Url == null || db2Url.matches("^\\s*$")) { databaseConnection2 = null; } else { databaseConnection2 = new DatabaseConnection(); - databaseConnection2.connect(config.getString("DB2.URL"), config.getString("DB2.NAME"), config.getString("DB2.USER"), config.getString("DB2.PASS"), "mysql"); + databaseConnection2.connect(config.getString("DB2.URL"), + config.getString("DB2.NAME"), config.getString("DB2.USER"), + config.getString("DB2.PASS"), "mysql"); } - + setGalaxyStatus(GalaxyStatus.Loading); - + if (options.getInt("CLEAN.CHARACTERS.TABLE") > 0) { - try { databaseConnection.preparedStatement("DELETE FROM characters").execute(); } - catch (SQLException e) {e.printStackTrace(); } + try { + databaseConnection.preparedStatement("DELETE FROM characters") + .execute(); + } catch (SQLException e) { + e.printStackTrace(); + } System.out.println("Cleared characters table."); } - - swgObjectODB = new ObjectDatabase("swgobjects", true, true, true, SWGObject.class); + + swgObjectODB = new ObjectDatabase("swgobjects", true, true, true, + SWGObject.class); mailODB = new ObjectDatabase("mails", true, true, true, Mail.class); - guildODB = new ObjectDatabase("guild", true, true, true, GuildObject.class); - objectIdODB = new ObjectDatabase("oids", true, true, true, ObjectId.class); - duplicateIdODB = new ObjectDatabase("doids", true, true, true, DuplicateId.class); - chatRoomODB = new ObjectDatabase("chatRooms", true, true, true, ChatRoom.class); - resourceHistoryODB = new ObjectDatabase("resourcehistory", true, true, true, GalacticResource.class); - auctionODB = new ObjectDatabase("auction", true, true, true, AuctionItem.class); - bountiesODB = new ObjectDatabase("bounties", true, true, true, BountyListItem.class); - cityODB = new ObjectDatabase("cities", true, true, true, PlayerCity.class); - + guildODB = new ObjectDatabase("guild", true, true, true, + GuildObject.class); + objectIdODB = new ObjectDatabase("oids", true, true, true, + ObjectId.class); + duplicateIdODB = new ObjectDatabase("doids", true, true, true, + DuplicateId.class); + chatRoomODB = new ObjectDatabase("chatRooms", true, true, true, + ChatRoom.class); + resourceHistoryODB = new ObjectDatabase("resourcehistory", true, true, + true, GalacticResource.class); + auctionODB = new ObjectDatabase("auction", true, true, true, + AuctionItem.class); + bountiesODB = new ObjectDatabase("bounties", true, true, true, + BountyListItem.class); + cityODB = new ObjectDatabase("cities", true, true, true, + PlayerCity.class); + // Services loginService = new LoginService(this); retroService = new RetroService(this); @@ -340,7 +390,7 @@ public class NGECore { characterService = new CharacterService(this); mapService = new MapService(this); travelService = new TravelService(this); - + factionService = new FactionService(this); objectService = new ObjectService(this); terrainService = new TerrainService(this); @@ -368,19 +418,21 @@ public class NGECore { staticService = new StaticService(this); reverseEngineeringService = new ReverseEngineeringService(this); petService = new PetService(this); - + if (options.getInt("LOAD.RESOURCE.SYSTEM") == 1) { surveyService = new SurveyService(this); resourceService = new ResourceService(this); } - + if (config.keyExists("JYTHONCONSOLE.PORT")) { int jythonPort = config.getInt("JYTHONCONSOLE.PORT"); if (jythonPort > 0) { - - System.out.println("Starting InteractiveJythonServer on Port " + jythonPort); + + System.out.println("Starting InteractiveJythonServer on Port " + + jythonPort); jythonAcceptor = new InteractiveJythonAcceptor(); - jythonServer = new InteractiveJythonServer((IoHandler) jythonAcceptor, jythonPort, this); + jythonServer = new InteractiveJythonServer( + (IoHandler) jythonAcceptor, jythonPort, this); jythonAcceptor.setServer(jythonServer); jythonServer.start(); } @@ -390,36 +442,40 @@ public class NGECore { missionService = new MissionService(this); questService = new QuestService(this); invasionService = new InvasionService(this); - + // Ping Server - - if(config.keyExists("PING.PORT")) + if (config.keyExists("PING.PORT")) if (config.getInt("PING.PORT") != 0) { try { - PingServer pingServer = new PingServer(config.getInt("PING.PORT")); + PingServer pingServer = new PingServer( + config.getInt("PING.PORT")); pingServer.bind(); } catch (IOException e) { e.printStackTrace(); } } else - System.out.println("Warning: pingServer was not launched. Port equals 0."); + System.out + .println("Warning: pingServer was not launched. Port equals 0."); else - System.out.println("Warning: pingServer was not launched. Port not specified."); - - + System.out + .println("Warning: pingServer was not launched. Port not specified."); + // Login Server loginDispatch = new NetworkDispatch(this, false); loginDispatch.addService(loginService); - - if(config.keyExists("LOGIN.PORT")) + + if (config.keyExists("LOGIN.PORT")) if (config.getInt("LOGIN.PORT") != 0) { - loginServer = new MINAServer(loginDispatch, config.getInt("LOGIN.PORT")); + loginServer = new MINAServer(loginDispatch, + config.getInt("LOGIN.PORT")); loginServer.start(); } else - System.out.println("Warning: loginServer was not launched. Port equals 0."); + System.out + .println("Warning: loginServer was not launched. Port equals 0."); else - System.out.println("Warning: loginServer was not launched. Port not specified."); - + System.out + .println("Warning: loginServer was not launched. Port not specified."); + // Zone Server zoneDispatch = new NetworkDispatch(this, true); zoneDispatch.addService(retroService); @@ -446,22 +502,26 @@ public class NGECore { zoneDispatch.addService(reverseEngineeringService); zoneDispatch.addService(petService); zoneDispatch.addService(invasionService); - + if (options.getInt("LOAD.RESOURCE.SYSTEM") == 1) { zoneDispatch.addService(surveyService); zoneDispatch.addService(resourceService); } - - if(config.keyExists("ZONE.PORT")) + + if (config.keyExists("ZONE.PORT")) if (config.getInt("ZONE.PORT") != 0) { - zoneServer = new MINAServer(zoneDispatch, config.getInt("ZONE.PORT")); + zoneServer = new MINAServer(zoneDispatch, + config.getInt("ZONE.PORT")); zoneServer.start(); } else - System.out.println("Warning: zoneServer was not launched. Port equals 0."); + System.out + .println("Warning: zoneServer was not launched. Port equals 0."); else - System.out.println("Warning: zoneServer was not launched. Port not specified."); - - //Start terrainList + System.out + .println("Warning: zoneServer was not launched. Port not specified."); + + // Start terrainList + // Original Planets terrainService.addPlanet(1, "tatooine", "terrain/tatooine.trn", true); terrainService.addPlanet(2, "naboo", "terrain/naboo.trn", true); @@ -474,139 +534,152 @@ public class NGECore { terrainService.addPlanet(9, "endor", "terrain/endor.trn", true); terrainService.addPlanet(10, "dathomir", "terrain/dathomir.trn", true); terrainService.addPlanet(11, "mustafar", "terrain/mustafar.trn", true); - terrainService.addPlanet(12, "kashyyyk_main", "terrain/kashyyyk_main.trn", true); - //Dungeon Terrains + terrainService.addPlanet(12, "kashyyyk_main", + "terrain/kashyyyk_main.trn", true); + + // Dungeon Terrains // TODO: Fix BufferUnderFlow Errors on loaded of dungeon instances. - terrainService.addPlanet(13, "kashyyyk_dead_forest", "terrain/kashyyyk_dead_forest.trn", false); - terrainService.addPlanet(14, "kashyyyk_hunting", "terrain/kashyyyk_hunting.trn", false); - terrainService.addPlanet(15, "kashyyyk_north_dungeons", "terrain/kashyyyk_north_dungeons.trn", false); - terrainService.addPlanet(16, "kashyyyk_rryatt_trail", "terrain/kashyyyk_rryatt_trail.trn", false); - terrainService.addPlanet(17, "kashyyyk_south_dungeons", "terrain/kashyyyk_south_dungeons.trn", false); - terrainService.addPlanet(18, "adventure1", "terrain/adventure1.trn", false); - terrainService.addPlanet(19, "adventure2", "terrain/adventure2.trn", false); + terrainService.addPlanet(13, "kashyyyk_dead_forest", + "terrain/kashyyyk_dead_forest.trn", false); + terrainService.addPlanet(14, "kashyyyk_hunting", + "terrain/kashyyyk_hunting.trn", false); + terrainService.addPlanet(15, "kashyyyk_north_dungeons", + "terrain/kashyyyk_north_dungeons.trn", false); + terrainService.addPlanet(16, "kashyyyk_rryatt_trail", + "terrain/kashyyyk_rryatt_trail.trn", false); + terrainService.addPlanet(17, "kashyyyk_south_dungeons", + "terrain/kashyyyk_south_dungeons.trn", false); + terrainService.addPlanet(18, "adventure1", "terrain/adventure1.trn", + false); + terrainService.addPlanet(19, "adventure2", "terrain/adventure2.trn", + false); + // Tutorial Terrains terrainService.addPlanet(20, "dungeon1", "terrain/dungeon1.trn", true); - terrainService.addPlanet(21, "tutorial", "terrain/tutorial.trn", false); // 21B droid scene - //terrainService.addPlanet(22, "space_npe_falcon_3", "terrain/space_npe_falcon_3.trn", false); - - //Space Zones - // NOTE: Commented out for now until space is implemented. No need to be loaded into memory when space is not implemented. - /*terrainService.addPlanet(21, "space_corellia", "terrain/space_corellia.trn", true); - terrainService.addPlanet(22, "space_corellia_2", "terrain/space_corellia_2.trn", true); - terrainService.addPlanet(23, "space_dantooine", "terrain/space_dantooine.trn", true); - terrainService.addPlanet(24, "space_dathomir", "terrain/space_dathomir.trn", true); - terrainService.addPlanet(25, "space_endor", "terrain/space_endor.trn", true); - terrainService.addPlanet(26, "space_env", "terrain/space_env.trn", true); - terrainService.addPlanet(27, "space_halos", "terrain/space_halos.trn", true); - terrainService.addPlanet(28, "space_heavy1", "terrain/space_heavy1.trn", true); - terrainService.addPlanet(29, "space_kashyyyk", "terrain/space_kashyyyk.trn", true); - terrainService.addPlanet(30, "space_light1", "terrain/space_light1.trn", true); - terrainService.addPlanet(31, "space_lok", "terrain/space_lok.trn", true); - terrainService.addPlanet(32, "space_naboo", "terrain/space_naboo.trn", true); - terrainService.addPlanet(33, "space_naboo_2", "terrain/space_naboo_2.trn", true); - terrainService.addPlanet(34, "space_nova_orion", "terrain/space_nova_orion.trn", true); - terrainService.addPlanet(35, "space_npe_falcon", "terrain/space_npe_falcon.trn", true); // Only space_npe_falce_3 is used - terrainService.addPlanet(36, "space_npe_falcon_2", "terrain/space_npe_falcon_2.trn", true); // Only space_npe_falce_3 is used - terrainService.addPlanet(37, "space_ord_mantell", "terrain/space_ord_mantell.trn", true); - terrainService.addPlanet(38, "space_ord_mantell_2", "terrain/space_ord_mantell_2.trn", true); - terrainService.addPlanet(39, "space_ord_mantell_3", "terrain/space_ord_mantell_3.trn", true); - terrainService.addPlanet(40, "space_ord_mantell_4", "terrain/space_ord_mantell_4.trn", true); - terrainService.addPlanet(41, "space_ord_mantell_5", "terrain/space_ord_mantell_5.trn", true); - terrainService.addPlanet(42, "space_ord_mantell_6", "terrain/space_ord_mantell_6.trn", true); - terrainService.addPlanet(43, "space_tatooine", "terrain/space_tatooine.trn", true); - terrainService.addPlanet(44, "space_tatooine_2", "terrain/space_tatooine_2.trn", true); - terrainService.addPlanet(45, "space_yavin4", "terrain/space_yavin4.trn", true);*/ - - //end terrainList - + terrainService.addPlanet(21, "tutorial", "terrain/tutorial.trn", false); // 21B + // droid + // scene + // terrainService.addPlanet(22, "space_npe_falcon_3", + // "terrain/space_npe_falcon_3.trn", false); + + // Space Zones + // NOTE: Commented out for now until space is implemented. No need to be + // loaded into memory when space is not implemented. + /* + * terrainService.addPlanet(21, "space_corellia", + * "terrain/space_corellia.trn", true); terrainService.addPlanet(22, + * "space_corellia_2", "terrain/space_corellia_2.trn", true); + * terrainService.addPlanet(23, "space_dantooine", + * "terrain/space_dantooine.trn", true); terrainService.addPlanet(24, + * "space_dathomir", "terrain/space_dathomir.trn", true); + * terrainService.addPlanet(25, "space_endor", + * "terrain/space_endor.trn", true); terrainService.addPlanet(26, + * "space_env", "terrain/space_env.trn", true); + * terrainService.addPlanet(27, "space_halos", + * "terrain/space_halos.trn", true); terrainService.addPlanet(28, + * "space_heavy1", "terrain/space_heavy1.trn", true); + * terrainService.addPlanet(29, "space_kashyyyk", + * "terrain/space_kashyyyk.trn", true); terrainService.addPlanet(30, + * "space_light1", "terrain/space_light1.trn", true); + * terrainService.addPlanet(31, "space_lok", "terrain/space_lok.trn", + * true); terrainService.addPlanet(32, "space_naboo", + * "terrain/space_naboo.trn", true); terrainService.addPlanet(33, + * "space_naboo_2", "terrain/space_naboo_2.trn", true); + * terrainService.addPlanet(34, "space_nova_orion", + * "terrain/space_nova_orion.trn", true); terrainService.addPlanet(35, + * "space_npe_falcon", "terrain/space_npe_falcon.trn", true); // Only + * space_npe_falce_3 is used terrainService.addPlanet(36, + * "space_npe_falcon_2", "terrain/space_npe_falcon_2.trn", true); // + * Only space_npe_falce_3 is used terrainService.addPlanet(37, + * "space_ord_mantell", "terrain/space_ord_mantell.trn", true); + * terrainService.addPlanet(38, "space_ord_mantell_2", + * "terrain/space_ord_mantell_2.trn", true); + * terrainService.addPlanet(39, "space_ord_mantell_3", + * "terrain/space_ord_mantell_3.trn", true); + * terrainService.addPlanet(40, "space_ord_mantell_4", + * "terrain/space_ord_mantell_4.trn", true); + * terrainService.addPlanet(41, "space_ord_mantell_5", + * "terrain/space_ord_mantell_5.trn", true); + * terrainService.addPlanet(42, "space_ord_mantell_6", + * "terrain/space_ord_mantell_6.trn", true); + * terrainService.addPlanet(43, "space_tatooine", + * "terrain/space_tatooine.trn", true); terrainService.addPlanet(44, + * "space_tatooine_2", "terrain/space_tatooine_2.trn", true); + * terrainService.addPlanet(45, "space_yavin4", + * "terrain/space_yavin4.trn", true); + */ + + // end terrainList + if (options.getInt("LOAD.RESOURCE.SYSTEM") > 0) { resourceService.loadResources(); } - + chatService.loadChatRooms(); - + spawnService = new SpawnService(this); terrainService.loadClientPois(); + // Travel Points travelService.loadTravelPoints(); simulationService = new SimulationService(this); - - + terrainService.loadSnapShotObjects(); - objectService.loadServerTemplates(); + objectService.loadServerTemplates(); objectService.loadObjects(); harvesterService.loadHarvesters(); simulationService.insertSnapShotObjects(); simulationService.insertPersistentBuildings(); + // Zone services that need to be loaded after the above zoneDispatch.addService(simulationService); - + guildService = new GuildService(this); zoneDispatch.addService(guildService); - + gcwService = new GCWService(this); zoneDispatch.addService(gcwService); - + collectionService = new CollectionService(this); zoneDispatch.addService(collectionService); tradeService = new TradeService(this); zoneDispatch.addService(tradeService); - + zoneDispatch.addService(skillService); - + instanceService = new InstanceService(this); zoneDispatch.addService(instanceService); - + weatherService = new WeatherService(this); weatherService.loadPlanetSettings(); - + spawnService.loadMobileTemplates(); spawnService.loadLairTemplates(); spawnService.loadLairGroups(); - spawnService.loadDynamicGroups();; + spawnService.loadDynamicGroups(); + ; spawnService.loadSpawnAreas(); - + staticService.spawnStatics(); - + equipmentService.loadBonusSets(); playerCityService.loadCityRankCaps(); playerCityService.loadCities(); retroService.run(); - - browserService = new BrowserService(this); - //battlefieldService = new BattlefieldService(this); - adminService = new AdminService(this); - - didServerCrash = false; - System.out.println("Started Server."); - cleanupCreatureODB(); - setGalaxyStatus(GalaxyStatus.Online); - - } - private void cleanupCreatureODB() { - ODBCursor cursor = swgObjectODB.getCursor(); - - List deletedObjects = new ArrayList(); - - while(cursor.hasNext()) { - Object next = cursor.next(); - if (next == null) continue; - SWGObject creature = (SWGObject) next; - if(!characterService.playerExists(creature.getObjectID()) && creature instanceof CreatureObject) - deletedObjects.add((CreatureObject) creature); - } - cursor.close(); - - for(CreatureObject creature : deletedObjects) { - swgObjectODB.remove(creature.getObjectID()); - } - - System.out.println("Deleted " + deletedObjects.size() + " creatures."); + browserService = new BrowserService(this); + // battlefieldService = new BattlefieldService(this); + adminService = new AdminService(this); + + didServerCrash = false; + cleanupCreatureODB(); //just in case we crashed previously... + System.out.println("Started Server."); + setGalaxyStatus(GalaxyStatus.Online); + } public void stop() { @@ -614,134 +687,115 @@ public class NGECore { databaseConnection.close(); databaseConnection2.close(); } - - public void cleanUp() { - System.out.println("Cleaning Up..."); - long memoryUsed = Runtime.getRuntime().freeMemory(); - System.out.println("Using " + memoryUsed + " bytes of memory."); - - config = null; - databaseConnection = null; - databaseConnection2 = null; - Runtime.getRuntime().gc(); - System.out.println("Cleaned Up " + (Runtime.getRuntime().freeMemory() - memoryUsed) + " bytes of memory."); - } - + public void restart() { stop(); cleanUp(); try { Thread.sleep(30000); } catch (InterruptedException e) { - + } start(); } - - public static void main(String[] args) { - //With this class, we are overwriting the JVM's way of handling exceptions that are never caught. Very handy so no try/catch spam for every method. - if (logUnhandledExceptions) Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionLogger("./logs/uncaught")); - NGECore core = new NGECore(); - - core.start(); - - do { - if (didServerCrash) { - core.restart(); + public void initiateShutdown() { + if (isShuttingDown) + return; + try { + + for (int minutes = 15; minutes > 1; minutes--) { + chatService + .broadcastGalaxy("The server will be shutting down soon. Please find a safe place to logout. (" + + minutes + " minutes left)"); + Thread.sleep(60000); } - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - + setGalaxyStatus(GalaxyStatus.Locked); + chatService + .broadcastGalaxy("The server will be shutting down soon. Please find a safe place to logout. (" + + 1 + " minutes left)"); + Thread.sleep(30000); + chatService + .broadcastGalaxy("You will be disconnected in 30 seconds so the server can perform a final save before shutting down. Please find a safe place to logout now."); + Thread.sleep(20000); + chatService + .broadcastGalaxy("You will be disconnected in 10 seconds so the server can perform a final save before shutting down. Please find a safe place to logout now."); + Thread.sleep(10000); + chatService + .broadcastGalaxy("You will now be disconnected so the server can perform a final save before shutting down."); + + synchronized (getActiveConnectionsMap()) { + for (Client client : getActiveConnectionsMap().values()) { + client.getSession().close(true); + connectionService.disconnect(client); + } } - } while (true); - + + System.exit(0); + + } catch (InterruptedException e) { + e.printStackTrace(); + } } - + + public void initiateStop() { + if (isShuttingDown) + return; + try { + chatService + .broadcastGalaxy("You will now be disconnected so the server can perform a final save before shutting down."); + Thread.sleep(10000); + synchronized (getActiveConnectionsMap()) { + for (Client client : getActiveConnectionsMap().values()) { + client.getSession().close(true); + connectionService.disconnect(client); + } + } + + System.exit(0); + + } catch (InterruptedException e) { + e.printStackTrace(); + } + + } + + public void cleanUp() { + System.out.println("Cleaning Up..."); + long memoryUsed = Runtime.getRuntime().freeMemory(); + System.out.println("Using " + memoryUsed + " bytes of memory."); + + config = null; + databaseConnection = null; + databaseConnection2 = null; + cleanupCreatureODB(); + Runtime.getRuntime().gc(); + System.out.println("Cleaned Up " + + (Runtime.getRuntime().freeMemory() - memoryUsed) + + " bytes of memory."); + } + public void setGalaxyStatus(int statusId) { - + galaxyStatus = statusId; int galaxyId = config.getInt("GALAXY_ID"); - + try { - PreparedStatement ps = databaseConnection.preparedStatement("UPDATE \"connectionServers\" SET \"statusId\"=? WHERE \"galaxyId\"=?"); + PreparedStatement ps = databaseConnection + .preparedStatement("UPDATE \"connectionServers\" SET \"statusId\"=? WHERE \"galaxyId\"=?"); ps.setInt(1, statusId); ps.setInt(2, galaxyId); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } - - } - - public int getGalaxyStatus() { - return galaxyStatus; - } - - /* - * ---------- Getter methods for NGECore ---------- - */ - public Config getConfig() { - return config; - } - - public String getGalaxyName() { - return config.getString("GALAXY_NAME"); - } - - public DatabaseConnection getDatabase1() { - return databaseConnection; - } - - public DatabaseConnection getDatabase2() { - return databaseConnection2; - } - - public ObjectDatabase getSWGObjectODB() { - return swgObjectODB; - } - - public ObjectDatabase getMailODB() { - return mailODB; - } - - public ObjectDatabase getGuildODB() { - return guildODB; - } - - public ObjectDatabase getObjectIdODB() { - return objectIdODB; - } - - public ObjectDatabase getDuplicateIdODB() { - return duplicateIdODB; - } - - public ObjectDatabase getChatRoomODB() { - return chatRoomODB; - } - - public ObjectDatabase getBountiesODB() { - return bountiesODB; - } - - public ObjectDatabase getResourceHistoryODB() { - return resourceHistoryODB; - } - - public ObjectDatabase getAuctionODB() { - return auctionODB; - } - public ObjectDatabase getCityODB() { - return cityODB; } public int getActiveClients() { int connections = 0; for (Map.Entry c : clients.entrySet()) { - if(c.getValue().getSession() != null) { + if (c.getValue().getSession() != null) { if (c.getValue().getSession().isConnected()) { connections++; } @@ -749,12 +803,13 @@ public class NGECore { } return connections; } - + public int getActiveZoneClients() { int connections = 0; for (Map.Entry c : clients.entrySet()) { - if(c.getValue().getSession() != null) { - if (c.getValue().getSession().isConnected() && c.getValue().getParent() != null) { + if (c.getValue().getSession() != null) { + if (c.getValue().getSession().isConnected() + && c.getValue().getParent() != null) { connections++; } } @@ -762,96 +817,6 @@ public class NGECore { return connections; } - - public Client getClient(IoSession session) { - return clients.get(session); - } - - public ConcurrentHashMap getActiveConnectionsMap() { - return clients; - } - - /* - * --------------- Other methods for services --------------- - */ - public void addClient(IoSession session, Client client) { - clients.put(session, client); - } - - public void removeClient(IoSession session) { - clients.remove(session); - } - - // for python scripts - public Thread getCurrentThread() { - return Thread.currentThread(); - } - - public static NGECore getInstance() { - return instance; - } - - public BusConfiguration getEventBusConfig() { - return eventBusConfig; - } - - public void initiateShutdown() { - if(isShuttingDown) - return; - try { - - for(int minutes = 15; minutes > 1; minutes--) { - chatService.broadcastGalaxy("The server will be shutting down soon. Please find a safe place to logout. (" + minutes + " minutes left)"); - Thread.sleep(60000); - } - setGalaxyStatus(GalaxyStatus.Locked); - chatService.broadcastGalaxy("The server will be shutting down soon. Please find a safe place to logout. (" + 1 + " minutes left)"); - Thread.sleep(30000); - chatService.broadcastGalaxy("You will be disconnected in 30 seconds so the server can perform a final save before shutting down. Please find a safe place to logout now."); - Thread.sleep(20000); - chatService.broadcastGalaxy("You will be disconnected in 10 seconds so the server can perform a final save before shutting down. Please find a safe place to logout now."); - Thread.sleep(10000); - chatService.broadcastGalaxy("You will now be disconnected so the server can perform a final save before shutting down."); - - synchronized(getActiveConnectionsMap()) { - for(Client client : getActiveConnectionsMap().values()) { - client.getSession().close(true); - connectionService.disconnect(client); - } - } - - System.exit(0); - - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - public void initiateStop() { - if(isShuttingDown) - return; - try { - chatService.broadcastGalaxy("You will now be disconnected so the server can perform a final save before shutting down."); - Thread.sleep(10000); - synchronized(getActiveConnectionsMap()) { - for(Client client : getActiveConnectionsMap().values()) { - client.getSession().close(true); - connectionService.disconnect(client); - } - } - - System.exit(0); - - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - public long getGalacticTime() { - return System.currentTimeMillis() - galacticTime; - } - public void closeODBs() { swgObjectODB.close(); mailODB.close(); @@ -864,6 +829,137 @@ public class NGECore { cityODB.close(); } + public Vector getExcludedDevelopers() { + Vector excludedDevelopers = new Vector(); + // excludedDevelopers.add("Charon"); + // Feel free to add your OS user account name here to exclude yourself + // from loading buildouts and snapshots + // without having to change options.cfg all the time + return excludedDevelopers; + } + + //our lone private function + //TODO: we could speed this up if we put all the creature object id's into a list + //and then replace the call to playerExists with a function that selects object id's + //that are not in the list of object id's - those would be returned and deleted all at once + private void cleanupCreatureODB() { + ODBCursor cursor = swgObjectODB.getCursor(); + + int deleteCount = 0; + + while (cursor.hasNext()) { + Object next = cursor.next(); + if (next == null) + continue; + SWGObject creature = (SWGObject) next; + if (!characterService.playerExists(creature.getObjectID()) + && creature instanceof CreatureObject) { + swgObjectODB.remove(creature.getObjectID()); + deleteCount++; + } + } + cursor.close(); + + System.out.println("Deleted " + Integer.toString(deleteCount) + " creatures."); + } + + /* + * ---------- Getter methods for NGECore ---------- + */ + + public int getGalaxyStatus() { + return galaxyStatus; + } + + public Config getConfig() { + return config; + } + + public String getGalaxyName() { + return config.getString("GALAXY_NAME"); + } + + public DatabaseConnection getDatabase1() { + return databaseConnection; + } + + public DatabaseConnection getDatabase2() { + return databaseConnection2; + } + + public ObjectDatabase getSWGObjectODB() { + return swgObjectODB; + } + + public ObjectDatabase getMailODB() { + return mailODB; + } + + public ObjectDatabase getGuildODB() { + return guildODB; + } + + public ObjectDatabase getObjectIdODB() { + return objectIdODB; + } + + public ObjectDatabase getDuplicateIdODB() { + return duplicateIdODB; + } + + public ObjectDatabase getChatRoomODB() { + return chatRoomODB; + } + + public ObjectDatabase getBountiesODB() { + return bountiesODB; + } + + public ObjectDatabase getResourceHistoryODB() { + return resourceHistoryODB; + } + + public ObjectDatabase getAuctionODB() { + return auctionODB; + } + + public ObjectDatabase getCityODB() { + return cityODB; + } + + public Client getClient(IoSession session) { + return clients.get(session); + } + + public ConcurrentHashMap getActiveConnectionsMap() { + return clients; + } + + public void addClient(IoSession session, Client client) { + clients.put(session, client); + } + + public void removeClient(IoSession session) { + clients.remove(session); + } + + // for python scripts + public Thread getCurrentThread() { + return Thread.currentThread(); + } + + public static NGECore getInstance() { + return instance; + } + + public BusConfiguration getEventBusConfig() { + return eventBusConfig; + } + + public long getGalacticTime() { + return System.currentTimeMillis() - galacticTime; + } + public String getMotd() { return motd; } @@ -871,17 +967,8 @@ public class NGECore { public void setMotd(String motd) { this.motd = motd; } - - public Vector getExcludedDevelopers(){ - Vector excludedDevelopers = new Vector(); - //excludedDevelopers.add("Charon"); - // Feel free to add your OS user account name here to exclude yourself from loading buildouts and snapshots - // without having to change options.cfg all the time - return excludedDevelopers; - } - + public Config getOptions() { return options; } } - diff --git a/src/protocol/Message.java b/src/protocol/Message.java index 9792eaec..c852b2f3 100644 --- a/src/protocol/Message.java +++ b/src/protocol/Message.java @@ -28,132 +28,128 @@ import java.nio.ByteOrder; import org.apache.mina.core.buffer.IoBuffer; public abstract class Message { - + protected byte[] data; protected int opcode; protected short sequence; protected IoBuffer result; - + public Message() { - + } - - public Message(byte[] data) { - this.data = data; + + public Message(byte[] data) { + this.data = data; } - + public int getOpcode() { return opcode; } - + public int getSize() { return (data == null) ? 0 : data.length; } - + public byte[] getData() { - return data == null ? new byte[] { } : data.clone(); - } - - public abstract void deserialize(IoBuffer data); - public abstract IoBuffer serialize(); - - protected String getAsciiString(IoBuffer buffer) - { - return getString(buffer, "US-ASCII"); - } - - protected String getUnicodeString(IoBuffer buffer) - { - return getString(buffer, "UTF-16LE"); - } - - protected byte[] getAsciiString(String string) - { - return getString(string, "US-ASCII"); - } - - protected byte[] getUnicodeString(String string) - { - return getString(string, "UTF-16LE"); - } - - protected String getString(IoBuffer buffer, String charFormat) - { - - String result; - - int length; - - if (charFormat == "UTF-16LE") length = buffer.order(ByteOrder.LITTLE_ENDIAN).getInt(); - else length = buffer.order(ByteOrder.LITTLE_ENDIAN).getShort(); - - int bufferPosition = buffer.position(); - - try - { - - result = new String(buffer.array(), bufferPosition, length, charFormat); - - } - catch (UnsupportedEncodingException e) - { - - e.printStackTrace(); - return ""; - - } - - //TODO: Verify if character position is set correctly after reading a UTF-16 string - buffer.position(bufferPosition + length); - - return result; - - } - private byte[] getString(String string, String charFormat) - { - - ByteBuffer result; - int length = 2 + string.length(); - - if (charFormat == "UTF-16LE") - { - - result = ByteBuffer.allocate(length * 2).order(ByteOrder.LITTLE_ENDIAN); - result.putInt(string.length()); - - } - else - { - - result = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); - result.putShort((short) string.length()); - - } - - try - { - - result.put(string.getBytes(charFormat)); - - } - catch (UnsupportedEncodingException e) - { - - e.printStackTrace(); - return new byte[] {}; - - } - - return result.array(); - + return data == null ? new byte[] {} : data.clone(); } - //FIXME: this is redundant and was also bugged. At some point, get rid of the redundant functions. + public abstract void deserialize(IoBuffer data); + + public abstract IoBuffer serialize(); + + protected String getAsciiString(IoBuffer buffer) { + return getString(buffer, "US-ASCII"); + } + + protected String getUnicodeString(IoBuffer buffer) { + return getString(buffer, "UTF-16LE"); + } + + protected byte[] getAsciiString(String string) { + return getString(string, "US-ASCII"); + } + + protected byte[] getUnicodeString(String string) { + return getString(string, "UTF-16LE"); + } + + protected String getString(IoBuffer buffer, String charFormat) { + + String result; + + int length; + + if (charFormat == "UTF-16LE") + length = buffer.order(ByteOrder.LITTLE_ENDIAN).getInt(); + else + length = buffer.order(ByteOrder.LITTLE_ENDIAN).getShort(); + + int bufferPosition = buffer.position(); + + try { + + result = new String(buffer.array(), bufferPosition, length, + charFormat); + + } catch (UnsupportedEncodingException e) { + + e.printStackTrace(); + return ""; + + } + + // TODO: Verify if character position is set correctly after reading a + // UTF-16 string + buffer.position(bufferPosition + length); + + return result; + + } + + private byte[] getString(String string, String charFormat) { + + ByteBuffer result; + int length = 2 + string.length(); + + if (charFormat == "UTF-16LE") { + + result = ByteBuffer.allocate(length * 2).order( + ByteOrder.LITTLE_ENDIAN); + result.putInt(string.length()); + + } else { + + result = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); + result.putShort((short) string.length()); + + } + + try { + + result.put(string.getBytes(charFormat)); + + } catch (UnsupportedEncodingException e) { + + e.printStackTrace(); + return new byte[] {}; + + } + + return result.array(); + + } + + // FIXME: this is redundant and was also bugged. At some point, get rid of + // the redundant functions. /** - * Reads the next string in. It gets the length of the - * string from the short/int at the beginning of it - * @param bb The ByteBuffer to read from - * @param charset Charset of the string + * Reads the next string in. It gets the length of the string from the + * short/int at the beginning of it + * + * @param bb + * The ByteBuffer to read from + * @param charset + * Charset of the string * @return The read string. Returns "" if exception is thrown */ protected String getNextString(IoBuffer bb, String charset) { @@ -166,7 +162,7 @@ public abstract class Message { } if (length > bb.remaining()) return ""; - byte [] data = new byte[length]; + byte[] data = new byte[length]; bb.get(data); return new String(data, charset); } catch (Exception e) { @@ -174,18 +170,21 @@ public abstract class Message { } return ""; } - + /** * Reads the next array with specified size and returns it - * @param bb The ByteBuffer to read from - * @param size Size of the array + * + * @param bb + * The ByteBuffer to read from + * @param size + * Size of the array * @return The array that has been read, or an empty array if an exception */ - protected byte [] getNextArray(IoBuffer bb, int size) { + protected byte[] getNextArray(IoBuffer bb, int size) { try { if (bb.remaining() < size) return new byte[0]; - byte [] tmp = new byte[size]; + byte[] tmp = new byte[size]; bb.get(tmp); return tmp; } catch (Exception e) { @@ -193,13 +192,13 @@ public abstract class Message { } return new byte[0]; } - - + protected String getNextAsciiString(IoBuffer buffer) { return getNextString(buffer, "US-ASCII"); } + protected String getNextUnicodeString(IoBuffer buffer) { return getNextString(buffer, "UTF-16LE"); } -} +} diff --git a/src/protocol/UnitTest.java b/src/protocol/UnitTest.java index dbe94365..1a7fa908 100644 --- a/src/protocol/UnitTest.java +++ b/src/protocol/UnitTest.java @@ -34,107 +34,110 @@ import engine.resources.common.Stf; import engine.resources.objects.SWGObject; public abstract class UnitTest extends AbstractUnitTest { - + protected NGECore core; - + protected IoBuffer buffer = null; - + private static CrcStringTableVisitor crcTable = null; - + public UnitTest() { super(); core = NGECore.getInstance(); - + if (crcTable == null) { try { - crcTable = ClientFileManager.loadFile("misc/object_template_crc_string_table.iff", CrcStringTableVisitor.class); + crcTable = ClientFileManager.loadFile( + "misc/object_template_crc_string_table.iff", + CrcStringTableVisitor.class); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } } - + public boolean checkObjectId(long objectId) { Map map = UnitTests.getObjectIdMap(); - + if (objectId == 0) { return false; } - + SWGObject object = core.objectService.getObject(objectId); - + if (object == null) { return false; } - + if (map.containsKey(objectId)) { if (map.get(objectId) == null) { return false; } - + if (!object.getClass().getSimpleName().equals(map.get(objectId))) { return false; } } else { map.put(object.getObjectID(), object.getClass().getSimpleName()); } - + return true; } - + public boolean checkString(String string) { if (string == null) { return false; } - + return true; } - + public boolean checkCrc(int crc) { if (crcTable != null) { String template = crcTable.getTemplateString(buffer.getInt()); - + if (template == null || template.length() == 0) { return false; } } - + return true; } - + public boolean checkStf(IoBuffer buffer, boolean failEmpty) { Stf stf = new Stf(); String string; - + string = getAsciiString(buffer); - + if (!checkString(string)) { return false; } - + stf.setStfFilename(string); - + if (buffer.getInt() > 0) { return false; } - + string = getAsciiString(buffer); - + if (!checkString(string)) { return false; } - + stf.setStfName(string); - - if (stf.getStfFilename().length() == 0 || stf.getStfName().length() == 0) { + + if (stf.getStfFilename().length() == 0 + || stf.getStfName().length() == 0) { return !failEmpty; } - + if (stf.getStfValue() == null) { return false; } - + return true; } - + } diff --git a/src/resources/common/BuffBuilder.java b/src/resources/common/BuffBuilder.java index cd3c48a4..7bf1edbe 100644 --- a/src/resources/common/BuffBuilder.java +++ b/src/resources/common/BuffBuilder.java @@ -77,22 +77,22 @@ public class BuffBuilder { public void setCategory(String category) { - this.catId=BuffCategory.MISC; - if(category.equals("attributes")) - { - this.catId=BuffCategory.ATTRIBUTES; - } - else if(category.equals("trade")) - { - this.catId=BuffCategory.TRADE; - } - else if(category.equals("resistances")) - { - this.catId=BuffCategory.RESISTANCES; - } - else if(category.equals("combat")) - { - this.catId=BuffCategory.COMBAT; + + switch (category) { + case "attributes": + this.catId=BuffCategory.ATTRIBUTES; + break; + case "trade": + this.catId=BuffCategory.TRADE; + break; + case "resistances": + this.catId=BuffCategory.RESISTANCES; + break; + case "combat": + this.catId=BuffCategory.COMBAT; + break; + default: + this.catId=BuffCategory.MISC; } this.category = category; diff --git a/src/resources/common/Forager.java b/src/resources/common/Forager.java index 492537e0..7ce9852f 100644 --- a/src/resources/common/Forager.java +++ b/src/resources/common/Forager.java @@ -39,478 +39,546 @@ import resources.objects.group.GroupObject; import resources.objects.tangible.TangibleObject; import services.ai.AIActor; -/** - * @author Charon +/** + * @author Charon */ public class Forager { - - public static final int LYASE_ENZYME = 0; - public static final int RARE_COMPONENT = 1; - public static final int INSECT_BAIT = 2; - public static final int GRUB_BAIT = 3; - public static final int WORM_BAIT = 4; + + public static final int LYASE_ENZYME = 0; + public static final int RARE_COMPONENT = 1; + public static final int INSECT_BAIT = 2; + public static final int GRUB_BAIT = 3; + public static final int WORM_BAIT = 4; public static final int MYSTERIOUS_DATA_DISC = 5; - - public static final String[] RARE_COMPONENTS_CORELLIA = new String[]{"object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_charbote.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_goldfruit.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_kavasa_fruit.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_salthia.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_sunfruit.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_vweilu.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_yam.iff" - }; - - public static final String[] RARE_COMPONENTS_DANTOOINE = new String[]{"object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_barabel.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_celonslay.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_dorian.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_kibla_greens.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_shefna_fruit.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_tritacale.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_yot_beans.iff" - }; - - public static final String[] RARE_COMPONENTS_DATHOMIR = new String[]{"object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_beebleberry.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_driblis.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_dricklefruit.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_grape.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_hwotha.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_plaitfruit.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_qana.iff" - }; - - public static final String[] RARE_COMPONENTS_ENDOR = new String[]{"object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_acorns.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_blumfruit.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_burr_ball.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_gin_jang_berry.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_honey_melon.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_sunberries.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_yubnut.iff" - }; - - public static final String[] RARE_COMPONENTS_NABOO = new String[]{"object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_cligs.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_cracknut.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_denta.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_muja.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_ootoowergs.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_phraig.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_stinkmelon.iff" - }; - - public static final String[] RARE_COMPONENTS_TATOOINE = new String[]{"object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_banthaweed.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_bestinnian.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_bloddle.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_bristlemelon.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_tatoes.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_wyykmelons.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_zog.iff" - }; - - public static final String[] RARE_COMPONENTS_YAVIN = new String[]{"object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_blueleaf_shrub.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_celto.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_farrberries.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_sweetmelon.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_topatoes.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_trig_berries.iff", - "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_wuli_nuts.iff" - }; - - private static final HashMap rareComponentHash= new HashMap(); - - private int[] mapPlanetIDs = new int[]{6,7,8}; - - // consider foraged food food/foraged + + public static final String[] RARE_COMPONENTS_CORELLIA = new String[] { + "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_charbote.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_goldfruit.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_kavasa_fruit.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_salthia.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_sunfruit.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_vweilu.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/corellia/shared_yam.iff" }; + + public static final String[] RARE_COMPONENTS_DANTOOINE = new String[] { + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_barabel.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_celonslay.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_dorian.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_kibla_greens.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_shefna_fruit.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_tritacale.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dantooine/shared_yot_beans.iff" }; + + public static final String[] RARE_COMPONENTS_DATHOMIR = new String[] { + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_beebleberry.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_driblis.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_dricklefruit.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_grape.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_hwotha.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_plaitfruit.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/dathomir/shared_qana.iff" }; + + public static final String[] RARE_COMPONENTS_ENDOR = new String[] { + "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_acorns.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_blumfruit.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_burr_ball.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_gin_jang_berry.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_honey_melon.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_sunberries.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/endor/shared_yubnut.iff" }; + + public static final String[] RARE_COMPONENTS_NABOO = new String[] { + "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_cligs.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_cracknut.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_denta.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_muja.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_ootoowergs.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_phraig.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/naboo/shared_stinkmelon.iff" }; + + public static final String[] RARE_COMPONENTS_TATOOINE = new String[] { + "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_banthaweed.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_bestinnian.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_bloddle.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_bristlemelon.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_tatoes.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_wyykmelons.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/tatooine/shared_zog.iff" }; + + public static final String[] RARE_COMPONENTS_YAVIN = new String[] { + "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_blueleaf_shrub.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_celto.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_farrberries.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_sweetmelon.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_topatoes.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_trig_berries.iff", + "object/tangible/loot/creature_loot/collections/fried_icecream_components/yavin/shared_wuli_nuts.iff" }; + + private static final HashMap rareComponentHash = new HashMap(); + + private int[] mapPlanetIDs = new int[] { 6, 7, 8 }; + + // consider foraged food food/foraged // tangible/item/treasure_map/shared_relic_buff_s01.iff - - public Forager(){ - + + public Forager() { + } - + @SuppressWarnings("unused") - public boolean handleForageResults(CreatureObject forager){ + public boolean handleForageResults(CreatureObject forager) { // determine foraged object SWGObject foragerInventory = forager.getSlottedObject("inventory"); - - - // you can use Kommerken Steak food which increases your - // foraging chance by 12% and gives you a - // 5% bonus chance of finding a treasure map. - - int randomForageRoll = new Random().nextInt(100); + + // you can use Kommerken Steak food which increases your + // foraging chance by 12% and gives you a + // 5% bonus chance of finding a treasure map. + + int randomForageRoll = new Random().nextInt(100); int randomForageObjectRoll = new Random().nextInt(100); - int remainder = 0; + int remainder = 0; int forageResultChance = 100; int kommerkenBonus = 0; - int[] forageChances = new int[]{10,10,25,25,25,5}; - int[] forageChances2 = new int[]{12,10,21,23,24,10}; // Kommerken Steak - int[] forageChances3 = new int[]{20,9,22,22,22,5}; // if you got the pig - - rareComponentHash.put(1,RARE_COMPONENTS_TATOOINE); - rareComponentHash.put(2,RARE_COMPONENTS_NABOO); - rareComponentHash.put(3,RARE_COMPONENTS_CORELLIA); - rareComponentHash.put(6,RARE_COMPONENTS_DANTOOINE); - rareComponentHash.put(8,RARE_COMPONENTS_YAVIN); - rareComponentHash.put(9,RARE_COMPONENTS_ENDOR); - rareComponentHash.put(10,RARE_COMPONENTS_DATHOMIR); - + int[] forageChances = new int[] { 10, 10, 25, 25, 25, 5 }; + int[] forageChances2 = new int[] { 12, 10, 21, 23, 24, 10 }; // Kommerken + // Steak + int[] forageChances3 = new int[] { 20, 9, 22, 22, 22, 5 }; // if you got + // the pig + + rareComponentHash.put(1, RARE_COMPONENTS_TATOOINE); + rareComponentHash.put(2, RARE_COMPONENTS_NABOO); + rareComponentHash.put(3, RARE_COMPONENTS_CORELLIA); + rareComponentHash.put(6, RARE_COMPONENTS_DANTOOINE); + rareComponentHash.put(8, RARE_COMPONENTS_YAVIN); + rareComponentHash.put(9, RARE_COMPONENTS_ENDOR); + rareComponentHash.put(10, RARE_COMPONENTS_DATHOMIR); + int chosenObject = 0; - -// if (forager.hasChuckedIn(KommerkenSteak)){ -// kommerkenBonus = 12; -// forageChances = forageChances2; -// } - -// if (forager.gotThePig(pig)){ -// forageChances = forageChances3; -//} - //forager.sendSystemMessage("randomForageRoll " + randomForageRoll,(byte) 0); - if (randomForageRoll=80){ + + if (forager.getInventoryItemCount() >= 80) { chosenObject = 6; - forager.sendSystemMessage("@skl_use:sys_forage_noroom",(byte) 0); + forager.sendSystemMessage("@skl_use:sys_forage_noroom", + (byte) 0); } - + // chosenObject = 5; // To test TMs - if(!(NGECore.getInstance().adminService.getAccessLevelFromDB(forager.getClient().getAccountId()) == null)) // Always yield a TM for testing + if (!(NGECore.getInstance().adminService + .getAccessLevelFromDB(forager.getClient().getAccountId()) == null)) // Always + // yield + // a + // TM + // for + // testing chosenObject = 5; - - //forager.sendSystemMessage("chosenObject " + chosenObject,(byte) 0); + + // forager.sendSystemMessage("chosenObject " + chosenObject,(byte) + // 0); switch (chosenObject) { - - case LYASE_ENZYME: String template = "object/tangible/loot/beast/shared_enzyme_2.iff"; - TangibleObject foragedObject = (TangibleObject) NGECore.getInstance().objectService.createObject(template, forager.getPlanet()); - // determine color here - foragedObject.setCustomizationVariable("/private/index_color_1", (byte) new Random().nextInt(10)); // edb_vial.pal - foragerInventory.add(foragedObject); - forager.sendSystemMessage("",(byte) 0); - break; - - case RARE_COMPONENT: template = ""; - String[] componentArray = rareComponentHash.get(forager.getPlanetId()); - int componentRoll = new Random().nextInt(componentArray.length); - template = componentArray[componentRoll]; - foragedObject = (TangibleObject) NGECore.getInstance().objectService.createObject(template, forager.getPlanet()); - foragerInventory.add(foragedObject); - forager.sendSystemMessage("",(byte) 0); - break; - - case INSECT_BAIT: template = "object/tangible/fishing/bait/shared_bait_insect.iff"; - foragedObject = (TangibleObject) NGECore.getInstance().objectService.createObject(template, forager.getPlanet()); - foragerInventory.add(foragedObject); - forager.sendSystemMessage("",(byte) 0); - break; - - case GRUB_BAIT: template = "object/tangible/fishing/bait/shared_bait_grub.iff"; - foragedObject = (TangibleObject) NGECore.getInstance().objectService.createObject(template, forager.getPlanet()); - foragerInventory.add(foragedObject); - forager.sendSystemMessage("",(byte) 0); - break; - - case WORM_BAIT: template = "object/tangible/fishing/bait/shared_bait_worm.iff"; - foragedObject = (TangibleObject) NGECore.getInstance().objectService.createObject(template, forager.getPlanet()); - foragerInventory.add(foragedObject); - forager.sendSystemMessage("",(byte) 0); - break; - - case MYSTERIOUS_DATA_DISC: template = "object/tangible/loot/generic_usable/shared_datadisk_generic.iff"; - foragedObject = (TangibleObject) NGECore.getInstance().objectService.createObject(template, forager.getPlanet()); - foragedObject.setCustomName(getLevelDependentMapName(forager.getLevel())); - foragedObject.setAttachment("MapLevel", forager.getLevel()); - foragedObject.setAttachment("MapSTFName", getLevelDependentSTFName(forager.getLevel())); - int mapPlanetID = new Random().nextInt(mapPlanetIDs.length-1); - foragedObject.setAttachment("MapPlanet", mapPlanetIDs[mapPlanetID]); - //System.out.println("mapPlanetID " + mapPlanetIDs[mapPlanetID]); - foragedObject.setAttachment("radial_filename", "object/treasuremap"); - //foragedObject.setAttachment("radial_filename", "object/treasuremapExtract"); - foragerInventory.add(foragedObject); - forager.sendSystemMessage("",(byte) 0); - break; - - default: break; - ///object/tangible/treasure_map/shared_treasure_map_base.iff shared_treasure_map_quest.iff + + case LYASE_ENZYME: + String template = "object/tangible/loot/beast/shared_enzyme_2.iff"; + TangibleObject foragedObject = (TangibleObject) NGECore + .getInstance().objectService.createObject(template, + forager.getPlanet()); + // determine color here + foragedObject.setCustomizationVariable( + "/private/index_color_1", + (byte) new Random().nextInt(10)); // edb_vial.pal + foragerInventory.add(foragedObject); + forager.sendSystemMessage("", (byte) 0); + break; + + case RARE_COMPONENT: + template = ""; + String[] componentArray = rareComponentHash.get(forager + .getPlanetId()); + int componentRoll = new Random().nextInt(componentArray.length); + template = componentArray[componentRoll]; + foragedObject = (TangibleObject) NGECore.getInstance().objectService + .createObject(template, forager.getPlanet()); + foragerInventory.add(foragedObject); + forager.sendSystemMessage("", (byte) 0); + break; + + case INSECT_BAIT: + template = "object/tangible/fishing/bait/shared_bait_insect.iff"; + foragedObject = (TangibleObject) NGECore.getInstance().objectService + .createObject(template, forager.getPlanet()); + foragerInventory.add(foragedObject); + forager.sendSystemMessage("", (byte) 0); + break; + + case GRUB_BAIT: + template = "object/tangible/fishing/bait/shared_bait_grub.iff"; + foragedObject = (TangibleObject) NGECore.getInstance().objectService + .createObject(template, forager.getPlanet()); + foragerInventory.add(foragedObject); + forager.sendSystemMessage("", (byte) 0); + break; + + case WORM_BAIT: + template = "object/tangible/fishing/bait/shared_bait_worm.iff"; + foragedObject = (TangibleObject) NGECore.getInstance().objectService + .createObject(template, forager.getPlanet()); + foragerInventory.add(foragedObject); + forager.sendSystemMessage("", (byte) 0); + break; + + case MYSTERIOUS_DATA_DISC: + template = "object/tangible/loot/generic_usable/shared_datadisk_generic.iff"; + foragedObject = (TangibleObject) NGECore.getInstance().objectService + .createObject(template, forager.getPlanet()); + foragedObject.setCustomName(getLevelDependentMapName(forager + .getLevel())); + foragedObject.setAttachment("MapLevel", forager.getLevel()); + foragedObject.setAttachment("MapSTFName", + getLevelDependentSTFName(forager.getLevel())); + int mapPlanetID = new Random().nextInt(mapPlanetIDs.length - 1); + foragedObject.setAttachment("MapPlanet", + mapPlanetIDs[mapPlanetID]); + // System.out.println("mapPlanetID " + + // mapPlanetIDs[mapPlanetID]); + foragedObject.setAttachment("radial_filename", + "object/treasuremap"); + // foragedObject.setAttachment("radial_filename", + // "object/treasuremapExtract"); + foragerInventory.add(foragedObject); + forager.sendSystemMessage("", (byte) 0); + break; + + default: + break; + // /object/tangible/treasure_map/shared_treasure_map_base.iff + // shared_treasure_map_quest.iff } - - if (chosenObject<6) - forager.sendSystemMessage("@skl_use:sys_forage_success",(byte) 0); - + + if (chosenObject < 6) + forager.sendSystemMessage("@skl_use:sys_forage_success", + (byte) 0); + // spawn adversaries int adversaryRoll = new Random().nextInt(100); - // A new buff is imaginable that would decrease the chance of running into adversaries here, just an idea - - if (chosenObject>6) - adversaryRoll=999; - + // A new buff is imaginable that would decrease the chance of + // running into adversaries here, just an idea + + if (chosenObject > 6) + adversaryRoll = 999; + // adversaryRoll=999; // To test TMs - if (adversaryRoll<14) { // 14 100 // To test TMs + if (adversaryRoll < 14) { // 14 100 // To test TMs int adversaryTypeRoll = new Random().nextInt(100); - if (adversaryTypeRoll<50){ + if (adversaryTypeRoll < 50) { // wormie spawnWormie(forager); } else { // goon spawnGoon(forager); - } + } } - + } else { - forager.sendSystemMessage("@skl_use:sys_forage_fail",(byte) 0); - - } - + forager.sendSystemMessage("@skl_use:sys_forage_fail", (byte) 0); + + } + return true; } - - private String getLevelDependentMapName(int level){ - if (level>=1 && level<=10) + + private String getLevelDependentMapName(int level) { + if (level >= 1 && level <= 10) return "Mysterious Data Disk (Adventurer's Treasure)"; - if (level>=11 && level<=20) + if (level >= 11 && level <= 20) return "Mysterious Data Disk (Villager's Hidden Savings)"; - if (level>=21 && level<=30) + if (level >= 21 && level <= 30) return "A map to a Trader's Hidden Treasure"; - if (level>=31 && level<=40) + if (level >= 31 && level <= 40) return "A map to a Bounty Hunter's Hidden Stash"; - if (level>=41 && level<=50) + if (level >= 41 && level <= 50) return "A droid's data disk with map coordinates"; - if (level>=51 && level<=60) + if (level >= 51 && level <= 60) return "A map to a Jedi Knight's body"; - if (level>=61 && level<=70) + if (level >= 61 && level <= 70) return "A map to Jedi Artifacts"; - if (level>=71 && level<=80) + if (level >= 71 && level <= 80) return "A map to a cursed item"; - if (level>=81 && level<=90) + if (level >= 81 && level <= 90) return "Mysterious Data Disk (Mysterious Container) "; return ""; } - - private String getLevelDependentSTFName(int level){ - if (level>=1 && level<=10) + + private String getLevelDependentSTFName(int level) { + if (level >= 1 && level <= 10) return "treasure_guard_adventurer"; - if (level>=11 && level<=20) + if (level >= 11 && level <= 20) return "treasure_guard_villager"; - if (level>=21 && level<=30) + if (level >= 21 && level <= 30) return "treasure_guard_trader"; - if (level>=31 && level<=40) + if (level >= 31 && level <= 40) return "treasure_guard_bounty_hunter"; - if (level>=41 && level<=50) + if (level >= 41 && level <= 50) return "treasure_guard_droid"; - if (level>=51 && level<=60) + if (level >= 51 && level <= 60) return "treasure_guard_padawan"; - if (level>=61 && level<=70) + if (level >= 61 && level <= 70) return "treasure_guard_jedi"; - if (level>=71 && level<=80) + if (level >= 71 && level <= 80) return "treasure_guard_jedi_elder"; - if (level>=81 && level<=90) + if (level >= 81 && level <= 90) return "treasure_guard_jedi_elite"; return ""; } - - - - - - - public void spawnWormie(CreatureObject forager){ + + public void spawnWormie(CreatureObject forager) { int level = forager.getLevel(); - String name = ""; - Point3D wormiePosition = SpawnPoint.getRandomPosition(forager.getPosition(), 1, 6, forager.getPlanetId()); - CreatureObject wormie = NGECore.getInstance().spawnService.spawnCreature("forage_worm", forager.getPlanet().getName(), 0L, wormiePosition.x, wormiePosition.y, wormiePosition.z, (short)level); + String name = ""; + Point3D wormiePosition = SpawnPoint.getRandomPosition( + forager.getPosition(), 1, 6, forager.getPlanetId()); + CreatureObject wormie = NGECore.getInstance().spawnService + .spawnCreature("forage_worm", forager.getPlanet().getName(), + 0L, wormiePosition.x, wormiePosition.y, + wormiePosition.z, (short) level); switch (wormie.getTemplate()) { - case "object/mobile/shared_col_forage_aggravated_worm.iff": - name = "An Aggravated Worm"; - break; - + name = "An Aggravated Worm"; + break; + case "object/mobile/shared_col_forage_angry_worm.iff": - name = "An Angry Worm"; - break; - + name = "An Angry Worm"; + break; + case "object/mobile/shared_col_forage_brutal_worm.iff": - name = "A Brutal Worm"; - break; - + name = "A Brutal Worm"; + break; + case "object/mobile/shared_col_forage_carnivorous_worm.iff": - name = "A Carnivorous Worm"; - break; - + name = "A Carnivorous Worm"; + break; + case "object/mobile/shared_col_forage_ferocious_worm.iff": - name = "A Ferocious Worm"; - break; - + name = "A Ferocious Worm"; + break; + case "object/mobile/shared_col_forage_fierce_worm.iff": - name = "A Fierce Worm"; - break; - + name = "A Fierce Worm"; + break; + case "object/mobile/shared_col_forage_hungry_worm.iff": - name = "A Hungry Worm"; - break; - + name = "A Hungry Worm"; + break; + case "object/mobile/shared_col_forage_oozing_worm.iff": - name = "An Oozing Worm"; - break; - + name = "An Oozing Worm"; + break; + case "object/mobile/shared_col_forage_savage_worm.iff": - name = "A Savage Worm"; - break; - + name = "A Savage Worm"; + break; + case "object/mobile/shared_col_forage_territorial_worm.iff": - name = "A Territorial Worm"; - break; + name = "A Territorial Worm"; + break; } wormie.setCustomName(name); wormie.setLevel(forager.getLevel()); wormie.setOptions(Options.AGGRESSIVE, true); wormie.setOptions(Options.ATTACKABLE, true); AIActor actor = (AIActor) wormie.getAttachment("AI"); - actor.addDefender(forager); + actor.addDefender(forager); } - - public void spawnGoon(CreatureObject forager){ + + public void spawnGoon(CreatureObject forager) { System.out.println("GOON"); int level = forager.getLevel(); - String name = ""; - Point3D wormiePosition = SpawnPoint.getRandomPosition(forager.getPosition(), 1, 6, forager.getPlanetId()); - CreatureObject goon = NGECore.getInstance().spawnService.spawnCreature("forage_goon", forager.getPlanet().getName(), 0L, wormiePosition.x, wormiePosition.y, wormiePosition.z, (short)level); + String name = ""; + Point3D wormiePosition = SpawnPoint.getRandomPosition( + forager.getPosition(), 1, 6, forager.getPlanetId()); + CreatureObject goon = NGECore.getInstance().spawnService.spawnCreature( + "forage_goon", forager.getPlanet().getName(), 0L, + wormiePosition.x, wormiePosition.y, wormiePosition.z, + (short) level); // thief wookie criminal scavenger @forage_enemy:bark_thief String barkString = ""; - + switch (goon.getTemplate()) { - + case "object/mobile/shared_dressed_criminal_assassin_human_female_01.iff": - name = "A criminal"; - barkString = "bark_criminal"; - break; - + name = "A criminal"; + barkString = "bark_criminal"; + break; + case "object/mobile/shared_dressed_criminal_assassin_human_male_01.iff": - name = "A Scavenger"; - barkString = "bark_scavenger"; - break; - + name = "A Scavenger"; + barkString = "bark_scavenger"; + break; + case "object/mobile/shared_twilek_male.iff": - name = "A Thief"; - barkString = "bark_thief"; - break; - + name = "A Thief"; + barkString = "bark_thief"; + break; + case "object/mobile/shared_dressed_binayre_pirate_zabrak_male_01.iff": - name = "A Pirate"; - barkString = "bark_thief"; - break; - + name = "A Pirate"; + barkString = "bark_thief"; + break; + case "object/mobile/shared_dressed_borvos_thug.iff": - name = "A Thug"; - barkString = "bark_criminal"; - break; - + name = "A Thug"; + barkString = "bark_criminal"; + break; + case "object/mobile/shared_wookiee_male.iff": - name = "A Thug"; - barkString = "bark_wookiee"; - break; - + name = "A Thug"; + barkString = "bark_wookiee"; + break; + } - -// goon.addObserver(forager); + + // goon.addObserver(forager); goon.setCustomName(name); goon.setLevel(forager.getLevel()); -// goon.setOptions(Options.AGGRESSIVE, true); -// goon.setOptions(Options.ATTACKABLE, true); + // goon.setOptions(Options.AGGRESSIVE, true); + // goon.setOptions(Options.ATTACKABLE, true); AIActor actor = (AIActor) goon.getAttachment("AI"); actor.addDefender(forager); - forager.sendSystemMessage("@foraging/forage_enemy:" + barkString, DisplayType.Broadcast); - OutOfBand oob = OutOfBand.ProsePackage("@foraging/forage_enemy:" + barkString); + forager.sendSystemMessage("@foraging/forage_enemy:" + barkString, + DisplayType.Broadcast); + OutOfBand oob = OutOfBand.ProsePackage("@foraging/forage_enemy:" + + barkString); Stf stf = new Stf("@foraging/forage_enemy:" + barkString); - NGECore.getInstance().chatService.spatialChat(goon, forager, stf.getStfValue(), (short)0x0, (short)0x0, 1, oob); + NGECore.getInstance().chatService.spatialChat(goon, forager, + stf.getStfValue(), (short) 0x0, (short) 0x0, 1, oob); } - - public void handleGuardSpawn(CreatureObject owner, TangibleObject map){ + + public void handleGuardSpawn(CreatureObject owner, TangibleObject map) { System.err.println("handleGuardSpawn"); short spawnLevel = (short) map.getAttachment("MapLevel"); - //Point3D exactTreasureLocation = (Point3D) map.getAttachment("MapExactLocation"); + // Point3D exactTreasureLocation = (Point3D) + // map.getAttachment("MapExactLocation"); Point3D exactTreasureLocation = owner.getPosition(); - + GroupObject extractorGroup = null; - if (owner.getGroupId()!=0) - extractorGroup = (GroupObject) NGECore.getInstance().objectService.getObject(owner.getGroupId()); - + if (owner.getGroupId() != 0) + extractorGroup = (GroupObject) NGECore.getInstance().objectService + .getObject(owner.getGroupId()); + int extractorGroupSize = 1; - if (extractorGroup!=null) + if (extractorGroup != null) extractorGroupSize = extractorGroup.getMemberList().size(); - + int guardSpawnNumber = 2 + extractorGroupSize; Vector guardList = new Vector(); - for (int i=0;i0){ - Thread.sleep(1000); - if (owner.getPosture()==14) - Thread.currentThread().interrupt(); - } - treasureContainer.setAttachment("radial_filename", "object/treasureContainer"); - owner.sendSystemMessage("@treasure_map/treasure_map:unlock_chest",(byte)0); - Thread.currentThread().interrupt(); - - } catch(InterruptedException va) { - System.out.println(va); - Thread.currentThread().interrupt(); // very important - } - } + public void run() { + try { + while (countAliveGuards(treasureContainer) > 0) { + Thread.sleep(1000); + if (owner.getPosture() == 14) + Thread.currentThread().interrupt(); + } + treasureContainer.setAttachment("radial_filename", + "object/treasureContainer"); + owner.sendSystemMessage( + "@treasure_map/treasure_map:unlock_chest", (byte) 0); + Thread.currentThread().interrupt(); + + } catch (InterruptedException va) { + System.out.println(va); + Thread.currentThread().interrupt(); // very important + } + } }; guardsThread.start(); - - // all down: owner.sendSystemMessage("@treasure_map/treasure_map:unlock_chest",(byte)0); + + // all down: + // owner.sendSystemMessage("@treasure_map/treasure_map:unlock_chest",(byte)0); } - - public CreatureObject spawnGuard(Point3D exactTreasureLocation, CreatureObject owner, TangibleObject map, short spawnLevel){ - - String name = ""; -// System.out.println("exactTreasureLocation.x + " +exactTreasureLocation.x); -// System.out.println("exactTreasureLocation.y + " +exactTreasureLocation.y); -// System.out.println("exactTreasureLocation.z + " +exactTreasureLocation.z); - - Point3D guardPosition = SpawnPoint.getRandomPosition(exactTreasureLocation, 5, 12, owner.getPlanetId()); - CreatureObject guard = NGECore.getInstance().spawnService.spawnCreature("treasure_guard", owner.getPlanet().getName(), 0L, guardPosition.x, guardPosition.y, guardPosition.z, spawnLevel); - + + public CreatureObject spawnGuard(Point3D exactTreasureLocation, + CreatureObject owner, TangibleObject map, short spawnLevel) { + + String name = ""; + // System.out.println("exactTreasureLocation.x + " + // +exactTreasureLocation.x); + // System.out.println("exactTreasureLocation.y + " + // +exactTreasureLocation.y); + // System.out.println("exactTreasureLocation.z + " + // +exactTreasureLocation.z); + + Point3D guardPosition = SpawnPoint.getRandomPosition( + exactTreasureLocation, 5, 12, owner.getPlanetId()); + CreatureObject guard = NGECore.getInstance().spawnService + .spawnCreature("treasure_guard", owner.getPlanet().getName(), + 0L, guardPosition.x, guardPosition.y, guardPosition.z, + spawnLevel); + String barkString = ""; name = "Treasure Protector"; - + guard.addObserver(owner); // ToDo: add any players in aggro range!!! guard.setCustomName(name); guard.setLevel(owner.getLevel()); @@ -518,94 +586,112 @@ public class Forager { guard.setOptions(Options.ATTACKABLE, true); AIActor actor = (AIActor) guard.getAttachment("AI"); actor.addDefender(owner); - - barkString = "bark_"+map.getAttachment("MapSTFName"); - owner.sendSystemMessage("@treasure_map/treasure_map:" + barkString, DisplayType.Broadcast); - OutOfBand oob = OutOfBand.ProsePackage("@treasure_map/treasure_map:" + barkString); - NGECore.getInstance().chatService.spatialChat(guard, owner, "", (short)0x0, (short)0x0, 1, oob); + + barkString = "bark_" + map.getAttachment("MapSTFName"); + owner.sendSystemMessage("@treasure_map/treasure_map:" + barkString, + DisplayType.Broadcast); + OutOfBand oob = OutOfBand.ProsePackage("@treasure_map/treasure_map:" + + barkString); + NGECore.getInstance().chatService.spatialChat(guard, owner, "", + (short) 0x0, (short) 0x0, 1, oob); return guard; } - - public CreatureObject spawnBoss(Point3D exactTreasureLocation, CreatureObject owner, TangibleObject map, short spawnLevel){ - - //Point3D treasureLocation = resources.common.SpawnPoint.getRandomPosition(exactTreasureLocation, 1, 10, owner.getPlanetId()); + + public CreatureObject spawnBoss(Point3D exactTreasureLocation, + CreatureObject owner, TangibleObject map, short spawnLevel) { + + // Point3D treasureLocation = + // resources.common.SpawnPoint.getRandomPosition(exactTreasureLocation, + // 1, 10, owner.getPlanetId()); return new CreatureObject(); // FIXME on paper this looks bad } - + @SuppressWarnings("unchecked") - public int countAliveGuards(SWGObject treasureContainer){ - Vector guardList = (Vector) treasureContainer.getAttachment("TreasureGuards"); + public int countAliveGuards(SWGObject treasureContainer) { + Vector guardList = (Vector) treasureContainer + .getAttachment("TreasureGuards"); int aliveCount = 0; - for (CreatureObject guard:guardList){ - if (guard.getPosture()!=14 && guard.getPosture()!=15) + for (CreatureObject guard : guardList) { + if (guard.getPosture() != 14 && guard.getPosture() != 15) aliveCount++; } return aliveCount; } - - - - public void configureTreasureLoot(TangibleObject treasureContainer, CreatureObject owner, short spawnLevel){ - @SuppressWarnings("unused") List lootgroups = new ArrayList(); - + + public void configureTreasureLoot(TangibleObject treasureContainer, + CreatureObject owner, short spawnLevel) { + @SuppressWarnings("unused") + List lootgroups = new ArrayList(); + String levelRange = "61"; - if (spawnLevel>60 && spawnLevel<=70){ + if (spawnLevel > 60 && spawnLevel <= 70) { levelRange = "61"; } - if (spawnLevel>70 && spawnLevel<=80){ + if (spawnLevel > 70 && spawnLevel <= 80) { levelRange = "75"; } - if (spawnLevel>80 && spawnLevel<=90){ + if (spawnLevel > 80 && spawnLevel <= 90) { levelRange = "85"; } - - - // PROFESSION BRACELETS HOUSE FURNITURE WEARABLE BACKPACKS -// String[] lootPoolNames = new String[]{"profession_bracelets_"+levelRange,"house_furniture","wearable_backpacks"}; -// double[] lootPoolChances = new double[]{60,30,10}; - String[] lootPoolNames = new String[]{"profession_bracelets_"+levelRange}; - double[] lootPoolChances = new double[]{100}; + + // PROFESSION BRACELETS HOUSE FURNITURE WEARABLE BACKPACKS + // String[] lootPoolNames = new + // String[]{"profession_bracelets_"+levelRange,"house_furniture","wearable_backpacks"}; + // double[] lootPoolChances = new double[]{60,30,10}; + String[] lootPoolNames = new String[] { "profession_bracelets_" + + levelRange }; + double[] lootPoolChances = new double[] { 100 }; double lootGroupChance = 80; - treasureContainer.addToLootGroups(lootPoolNames, lootPoolChances, lootGroupChance); - - // WEAPONSMITH COMPONENTS JEDI COMPONENTS GEM COLLECTION ITEMS TREASURE HUNTER COLLECTION ITEMS - //lootPoolNames = new String[]{"weaponsmith_components","jedi_components","gem_collection_items","treasure_hunter_collection_items"}; - //lootPoolChances = new double[]{15,25,30,30}; - lootPoolNames = new String[]{"jedi_components_treasure"}; - lootPoolChances = new double[]{100}; + treasureContainer.addToLootGroups(lootPoolNames, lootPoolChances, + lootGroupChance); + + // WEAPONSMITH COMPONENTS JEDI COMPONENTS GEM COLLECTION ITEMS TREASURE + // HUNTER COLLECTION ITEMS + // lootPoolNames = new + // String[]{"weaponsmith_components","jedi_components","gem_collection_items","treasure_hunter_collection_items"}; + // lootPoolChances = new double[]{15,25,30,30}; + lootPoolNames = new String[] { "jedi_components_treasure" }; + lootPoolChances = new double[] { 100 }; lootGroupChance = 80; - treasureContainer.addToLootGroups(lootPoolNames, lootPoolChances, lootGroupChance); - - // COMMON LOOTS: -// Looted non-wearable Bounty Hunter armor pieces (Used to make Mandalorian armor at the Death Watch Bunker) -// Looted clothing (usually 20+) -// Looted armors (usually 20+) -// Looted weapons (700-800 DPS(Sometimes less, now includes the Nak'tra Crystal Rifle)) -// Advanced Agility Stim (CL80) -// Advanced Power Stim (CL80) -// Loot kits adhesives -// Various Schematics -// lootPoolNames = new String[]{"bh_armor_for_mando","advanced_stims_80","loot_kits_adhesives","various_schematics"}; -// lootPoolChances = new double[]{15,25,30,30}; -// lootGroupChance = 80; -// treasureContainer.addToLootGroups(lootPoolNames, lootPoolChances, lootGroupChance); -// - - //GEM COLLECTION ITEMS CONSUMABLE BUFF ITEMS - + treasureContainer.addToLootGroups(lootPoolNames, lootPoolChances, + lootGroupChance); + + // COMMON LOOTS: + // Looted non-wearable Bounty Hunter armor pieces (Used to make + // Mandalorian armor at the Death Watch Bunker) + // Looted clothing (usually 20+) + // Looted armors (usually 20+) + // Looted weapons (700-800 DPS(Sometimes less, now includes the Nak'tra + // Crystal Rifle)) + // Advanced Agility Stim (CL80) + // Advanced Power Stim (CL80) + // Loot kits adhesives + // Various Schematics + // lootPoolNames = new + // String[]{"bh_armor_for_mando","advanced_stims_80","loot_kits_adhesives","various_schematics"}; + // lootPoolChances = new double[]{15,25,30,30}; + // lootGroupChance = 80; + // treasureContainer.addToLootGroups(lootPoolNames, lootPoolChances, + // lootGroupChance); + // + + // GEM COLLECTION ITEMS CONSUMABLE BUFF ITEMS + // VERY RARE BUFF ITEMS - lootPoolNames = new String[]{"rare_buff_items"}; - lootPoolChances = new double[]{100}; + lootPoolNames = new String[] { "rare_buff_items" }; + lootPoolChances = new double[] { 100 }; lootGroupChance = 0.1; - treasureContainer.addToLootGroups(lootPoolNames, lootPoolChances, lootGroupChance); - + treasureContainer.addToLootGroups(lootPoolNames, lootPoolChances, + lootGroupChance); + // EXTRA - lootPoolNames = new String[]{"treasure_extra"}; - lootPoolChances = new double[]{100}; + lootPoolNames = new String[] { "treasure_extra" }; + lootPoolChances = new double[] { 100 }; lootGroupChance = 50; - treasureContainer.addToLootGroups(lootPoolNames, lootPoolChances, lootGroupChance); - + treasureContainer.addToLootGroups(lootPoolNames, lootPoolChances, + lootGroupChance); + } } diff --git a/src/services/AdminService.java b/src/services/AdminService.java index 79462bb8..f6558217 100644 --- a/src/services/AdminService.java +++ b/src/services/AdminService.java @@ -44,7 +44,7 @@ public class AdminService implements INetworkDispatch { PreparedStatement preparedStatement; try { - preparedStatement = core.getDatabase1().preparedStatement("SELECT * FROM accounts WHERE id=" + id + ""); + preparedStatement = core.getDatabase1().preparedStatement("SELECT accessLevel FROM accounts WHERE id=" + id); ResultSet resultSet = preparedStatement.executeQuery(); if(resultSet.next()) accessLevel = resultSet.getString("accessLevel"); @@ -60,7 +60,7 @@ public class AdminService implements INetworkDispatch { PreparedStatement preparedStatement; try { - preparedStatement = core.getDatabase1().preparedStatement("SELECT * FROM accounts WHERE id=" + id + ""); + preparedStatement = core.getDatabase1().preparedStatement("SELECT user FROM accounts WHERE id=" + id); ResultSet resultSet = preparedStatement.executeQuery(); if(resultSet.next()) accountName = resultSet.getString("user"); diff --git a/src/services/CharacterService.java b/src/services/CharacterService.java index bba03b1a..0c02f0ba 100644 --- a/src/services/CharacterService.java +++ b/src/services/CharacterService.java @@ -422,7 +422,7 @@ public class CharacterService implements INetworkDispatch { if (isDuplicate) { return true; } //FIXME: this is a bit lazy... but it's only temporary :p - PreparedStatement psc = databaseConnection.preparedStatement("SELECT * FROM pg_tables WHERE \"tablename\"=?"); + PreparedStatement psc = databaseConnection.preparedStatement("SELECT COUNT(*) FROM pg_tables WHERE \"tablename\"=?"); psc.setString(1, "temp_reserved_char_names"); ResultSet resultSetC = psc.executeQuery(); boolean tableExists = resultSetC.next(); @@ -467,7 +467,7 @@ public class CharacterService implements INetworkDispatch { private String checkForReservedName(String firstName, String lastName) throws SQLException { - PreparedStatement psc = databaseConnection.preparedStatement("SELECT * FROM pg_tables WHERE \"tablename\"=?"); + PreparedStatement psc = databaseConnection.preparedStatement("SELECT COUNT(*) FROM pg_tables WHERE \"tablename\"=?"); psc.setString(1, "reservednames"); ResultSet rsc = psc.executeQuery(); if (!rsc.next()) { @@ -485,6 +485,7 @@ public class CharacterService implements INetworkDispatch { String combinedName = firstName + " " + lastName; combinedName.replaceAll("\\s*$", ""); + //we could consider using LIKE here, or some form of regex. either way it doesn't work right at the moment -ilikenwf String query = "SELECT \"type\" FROM \"reservednames\" WHERE (\"match_firstname\" = TRUE AND ? ~ \"pattern\") OR (\"match_both_names\" = TRUE and ? ~ \"pattern\") "; if (lastName != "") { @@ -522,10 +523,12 @@ public class CharacterService implements INetworkDispatch { PreparedStatement preparedStatement; int characters = 0; try { - preparedStatement = databaseConnection.preparedStatement("SELECT * FROM characters WHERE \"accountId\"=" + accountId + ""); + preparedStatement = databaseConnection.preparedStatement("SELECT COUNT(*) AS charCount FROM characters WHERE \"accountId\"=" + accountId); ResultSet resultSet = preparedStatement.executeQuery(); - while(resultSet.next() && !resultSet.isClosed()) - characters++; + + characters = 0; + if (!resultSet.isClosed() && resultSet.next()) + characters = resultSet.getInt("charCount"); } catch (SQLException e) { e.printStackTrace(); } @@ -575,10 +578,10 @@ public class CharacterService implements INetworkDispatch { name = name.toLowerCase(); long oid = 0L; try { - PreparedStatement ps = databaseConnection.preparedStatement("SELECT * FROM characters WHERE LOWER(\"firstName\")=?"); + PreparedStatement ps = databaseConnection.preparedStatement("SELECT COUNT(*) AS charCount FROM characters WHERE LOWER(\"firstName\")=?"); ps.setString(1, name); ResultSet resultSet = ps.executeQuery(); - while (resultSet.next()) { + if (!resultSet.isClosed() && resultSet.next()) { oid = resultSet.getLong("id"); } return oid; @@ -598,7 +601,7 @@ public class CharacterService implements INetworkDispatch { String name = ""; try { - PreparedStatement ps = databaseConnection.preparedStatement("SELECT * FROM characters WHERE \"id\"=?"); + PreparedStatement ps = databaseConnection.preparedStatement("SELECT firstName FROM characters WHERE \"id\"=?"); ps.setLong(1, oid); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { @@ -609,7 +612,7 @@ public class CharacterService implements INetworkDispatch { } name = name.toLowerCase(); - } + } return name; } @@ -648,11 +651,11 @@ public class CharacterService implements INetworkDispatch { */ public int getAccountId(long objectId) { try { - PreparedStatement ps = databaseConnection.preparedStatement("SELECT * FROM characters WHERE id=?"); + PreparedStatement ps = databaseConnection.preparedStatement("SELECT accountId FROM characters WHERE id=?"); ps.setLong(1, objectId); ResultSet resultSet = ps.executeQuery(); - resultSet.next(); - return resultSet.getInt("accountId"); + if (resultSet.next()) + return resultSet.getInt("accountId"); } catch (SQLException e) { e.printStackTrace(); } diff --git a/src/services/ConnectionService.java b/src/services/ConnectionService.java index 15f12267..7177d03c 100644 --- a/src/services/ConnectionService.java +++ b/src/services/ConnectionService.java @@ -84,14 +84,12 @@ public class ConnectionService implements INetworkDispatch { try { synchronized(core.getActiveConnectionsMap()) { for(Client c : core.getActiveConnectionsMap().values()) { - if(c.getParent() != null) { - if ((System.currentTimeMillis() - c.getSession().getLastReadTime()) > 300000) { - try { - disconnect(c); - } catch (Exception e) { - System.err.println("ConnectionService:disconnect(): Error disconnecting client."); - e.printStackTrace(); - } + if ((c.getParent() != null) && (System.currentTimeMillis() - c.getSession().getLastReadTime()) > 300000) { + try { + disconnect(c); + } catch (Exception e) { + System.err.println("ConnectionService:disconnect(): Error disconnecting client."); + e.printStackTrace(); } } } @@ -130,15 +128,17 @@ public class ConnectionService implements INetworkDispatch { try { - preparedStatement = databaseConnection.preparedStatement("SELECT * FROM sessions WHERE key=?"); + preparedStatement = databaseConnection.preparedStatement("SELECT accountId FROM sessions WHERE key=?"); preparedStatement.setBytes(1, clientIdMsg.getSessionKey()); resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { - client.setAccountId(resultSet.getLong("accountId")); + long accountId = resultSet.getLong("accountID"); + + client.setAccountId(accountId); client.setSessionKey(clientIdMsg.getSessionKey()); AccountFeatureBits accountFeatureBits = new AccountFeatureBits(); - ClientPermissionsMessage clientPermissionsMessage = new ClientPermissionsMessage(maxNumberOfCharacters - core.characterService.getNumberOfCharacters((int) resultSet.getLong("accountId"))); + ClientPermissionsMessage clientPermissionsMessage = new ClientPermissionsMessage(maxNumberOfCharacters - core.characterService.getNumberOfCharacters((int) accountId)); session.write(new HeartBeatMessage().serialize()); session.write(accountFeatureBits.serialize()); session.write(clientPermissionsMessage.serialize()); diff --git a/src/services/LoginService.java b/src/services/LoginService.java index ac16029e..1d67a22e 100644 --- a/src/services/LoginService.java +++ b/src/services/LoginService.java @@ -312,11 +312,13 @@ public class LoginService implements INetworkDispatch{ PreparedStatement preparedStatement; try { - preparedStatement = databaseConnection1.preparedStatement("SELECT * FROM characters WHERE \"accountId\"=" + id + ""); + preparedStatement = databaseConnection1.preparedStatement("SELECT firstName, lastName, appaearance, id, galaxyId, statusID" + + " FROM characters WHERE \"accountId\"= " + id); resultSet = preparedStatement.executeQuery(); while (resultSet.next() && !resultSet.isClosed()) { + //TODO: on creation just don't allow spaces in first or last name maybe? String characterName = resultSet.getString("firstName").replaceAll("\\s",""); ; String lastName = resultSet.getString("lastName").replaceAll("\\s",""); @@ -344,7 +346,7 @@ public class LoginService implements INetworkDispatch{ LoginEnumCluster servers = new LoginEnumCluster(9); PreparedStatement preparedStatement; try { - preparedStatement = databaseConnection1.preparedStatement("SELECT * FROM galaxies"); + preparedStatement = databaseConnection1.preparedStatement("SELECT id, name FROM galaxies"); ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next() && !resultSet.isClosed()) servers.addServer(resultSet.getInt("id"), resultSet.getString("name")); @@ -363,7 +365,8 @@ public class LoginService implements INetworkDispatch{ LoginClusterStatus clusterStatus = new LoginClusterStatus(); ResultSet resultSet; try { - PreparedStatement preparedStatement = databaseConnection1.preparedStatement("SELECT * FROM \"connectionServers\""); + PreparedStatement preparedStatement = databaseConnection1.preparedStatement("SELECT id, address, port, pingPort, statusID" + + " FROM \"connectionServers\""); resultSet = preparedStatement.executeQuery(); while (resultSet.next() && !resultSet.isClosed()) clusterStatus.addServer( diff --git a/src/services/object/ObjectService.java b/src/services/object/ObjectService.java index 02a25339..2af17e5d 100644 --- a/src/services/object/ObjectService.java +++ b/src/services/object/ObjectService.java @@ -719,7 +719,7 @@ public class ObjectService implements INetworkDispatch { customName = customName.split(" ")[0]; try { - PreparedStatement ps = core.getDatabase1().preparedStatement("SELECT * FROM characters WHERE \"firstName\" ILIKE ?"); + PreparedStatement ps = core.getDatabase1().preparedStatement("SELECT id FROM characters WHERE \"firstName\" ILIKE ?"); ps.setString(1, customName); ResultSet resultSet = ps.executeQuery();