diff --git a/PSWGCommon.jar b/PSWGCommon.jar deleted file mode 100644 index 9137fe7..0000000 Binary files a/PSWGCommon.jar and /dev/null differ diff --git a/build.gradle b/build.gradle index 4813b44..99e6d98 100644 --- a/build.gradle +++ b/build.gradle @@ -1,24 +1,19 @@ plugins { id 'java' - id 'idea' } sourceCompatibility = 1.8 targetCompatibility = 1.8 -jar { - from sourceSets.main.allSource - archiveName = "PSWGCommon.jar" -} - -task wrapper(type: Wrapper) { - gradleVersion = "4.4" -} - repositories { jcenter() } dependencies { + compile group: 'me.joshlarson', name: 'jlcommon', version: '1.6.1' testCompile 'junit:junit:4.12' } + +task wrapper(type: Wrapper) { + gradleVersion = "4.7" +} diff --git a/module-info.java b/module-info.java deleted file mode 100644 index 759f9c9..0000000 --- a/module-info.java +++ /dev/null @@ -1,3 +0,0 @@ -module com.projectswg.launcher { - requires java.base; -} \ No newline at end of file diff --git a/src/main/java/com/projectswg/common/callback/CallbackManager.java b/src/main/java/com/projectswg/common/callback/CallbackManager.java deleted file mode 100644 index 3af93bc..0000000 --- a/src/main/java/com/projectswg/common/callback/CallbackManager.java +++ /dev/null @@ -1,110 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.callback; - -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import com.projectswg.common.concurrency.PswgThreadPool; -import com.projectswg.common.debug.Log; - - -public class CallbackManager { - - private final PswgThreadPool executor; - private final List callbacks; - private final AtomicInteger runningTasks; - - public CallbackManager(String name) { - this(name, 1); - } - - public CallbackManager(String name, int threadCount) { - this.executor = new PswgThreadPool(threadCount, name); - this.callbacks = new CopyOnWriteArrayList<>(); - this.runningTasks = new AtomicInteger(0); - } - - public void addCallback(T callback) { - callbacks.add(callback); - } - - public void removeCallback(T callback) { - callbacks.remove(callback); - } - - public void setCallback(T callback) { - callbacks.clear(); - callbacks.add(callback); - } - - public void clearCallbacks() { - callbacks.clear(); - } - - public void start() { - executor.start(); - } - - public void stop() { - executor.stop(false); - } - - public boolean awaitTermination(long timeout, TimeUnit unit) { - return executor.awaitTermination(unit.toMillis(timeout)); - } - - public boolean isRunning() { - return executor.isRunning(); - } - - public boolean isQueueEmpty() { - return runningTasks.get() == 0; - } - - public boolean callOnEach(CallCallback call) { - runningTasks.incrementAndGet(); - return executor.execute(() -> { - for (T callback : callbacks) { - try { - call.run(callback); - } catch (Throwable t) { - Log.e(t); - } - } - runningTasks.decrementAndGet(); - }); - } - - - public interface CallCallback { - void run(T callback); - } -} diff --git a/src/main/java/com/projectswg/common/concurrency/Delay.java b/src/main/java/com/projectswg/common/concurrency/Delay.java deleted file mode 100644 index 509e93e..0000000 --- a/src/main/java/com/projectswg/common/concurrency/Delay.java +++ /dev/null @@ -1,98 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.LockSupport; - -public class Delay { - - /** - * Sleeps for the specified number of nanoseconds - * @param nanos the number of nanoseconds to sleep - * @return TRUE if this operation has been interrupted - */ - public static boolean sleepNano(long nanos) { - LockSupport.parkNanos(nanos); - return isInterrupted(); - } - - /** - * Sleeps for the specified number of microseconds - * @param micro the number of microseconds to sleep - * @return TRUE if this operation has been interrupted - */ - public static boolean sleepMicro(long micro) { - return sleepNano(micro * 1000); - } - - /** - * Sleeps for the specified number of milliseconds - * @param milli the number of milliseconds to sleep - * @return TRUE if this operation has been interrupted - */ - public static boolean sleepMilli(long milli) { - return sleepNano(milli * 1000000); - } - - /** - * Sleeps for the specified number of seconds - * @param sec the number of seconds to sleep - * @return TRUE if this operation has been interrupted - */ - public static boolean sleepSeconds(long sec) { - return sleepNano(sec * 1000000000); - } - - /** - * Sleeps for the specified amount of time - * @param time the amount of time to sleep - * @param unit the unit of time - * @return TRUE if this operation has been interrupted - */ - public static boolean sleep(long time, TimeUnit unit) { - return sleepNano(unit.toNanos(time)); - } - - /** - * Returns whether or not this thread has been interrupted - * @return TRUE if interrupted, FALSE otherwise - */ - public static boolean isInterrupted() { - return Thread.currentThread().isInterrupted(); - } - - /** - * Clears the interrupted flag so future calls to isInterrupted will return - * FALSE - */ - public static void clearInterrupted() { - Thread.interrupted(); - } - -} diff --git a/src/main/java/com/projectswg/common/concurrency/PswgBasicScheduledThread.java b/src/main/java/com/projectswg/common/concurrency/PswgBasicScheduledThread.java deleted file mode 100644 index f220973..0000000 --- a/src/main/java/com/projectswg/common/concurrency/PswgBasicScheduledThread.java +++ /dev/null @@ -1,71 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.concurrent.ScheduledFuture; - -public class PswgBasicScheduledThread extends PswgScheduledThreadPool { - - private final Runnable runnable; - - public PswgBasicScheduledThread(String name, Runnable runnable) { - super(1, name); - this.runnable = runnable; - } - - @Override - public void start() { - throw new UnsupportedOperationException("Cannot use this function. Must use startX(initialDelay, periodicDelay)"); - } - - public void startWithFixedRate(long initialDelay, long periodicDelay) { - super.start(); - super.executeWithFixedRate(initialDelay, periodicDelay, runnable); - } - - public void startWithFixedDelay(long initialDelay, long periodicDelay) { - super.start(); - super.executeWithFixedDelay(initialDelay, periodicDelay, runnable); - } - - @Override - public ScheduledFuture execute(long delay, Runnable runnable) { - throw new UnsupportedOperationException("Runnable is defined in the constructor!"); - } - - @Override - public ScheduledFuture executeWithFixedRate(long initialDelay, long periodicDelay, Runnable runnable) { - throw new UnsupportedOperationException("Runnable is defined in the constructor!"); - } - - @Override - public ScheduledFuture executeWithFixedDelay(long initialDelay, long periodicDelay, Runnable runnable) { - throw new UnsupportedOperationException("Runnable is defined in the constructor!"); - } - -} diff --git a/src/main/java/com/projectswg/common/concurrency/PswgBasicThread.java b/src/main/java/com/projectswg/common/concurrency/PswgBasicThread.java deleted file mode 100644 index 886f7fd..0000000 --- a/src/main/java/com/projectswg/common/concurrency/PswgBasicThread.java +++ /dev/null @@ -1,65 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.concurrent.atomic.AtomicBoolean; - -public class PswgBasicThread extends PswgThreadPool { - - private final AtomicBoolean executing; - private final Runnable runnable; - - public PswgBasicThread(String name, Runnable runnable) { - super(1, name); - this.executing = new AtomicBoolean(false); - this.runnable = runnable; - } - - @Override - public void start() { - super.start(); - super.execute(() -> { - executing.set(true); - try { - runnable.run(); - } finally { - executing.set(false); - } - }); - } - - public boolean isExecuting() { - return executing.get(); - } - - @Override - public boolean execute(Runnable runnable) { - throw new UnsupportedOperationException("Runnable is defined in the constructor!"); - } - -} diff --git a/src/main/java/com/projectswg/common/concurrency/PswgScheduledThreadPool.java b/src/main/java/com/projectswg/common/concurrency/PswgScheduledThreadPool.java deleted file mode 100644 index ed64bf0..0000000 --- a/src/main/java/com/projectswg/common/concurrency/PswgScheduledThreadPool.java +++ /dev/null @@ -1,128 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.projectswg.common.debug.Assert; -import com.projectswg.common.debug.Log; - -public class PswgScheduledThreadPool { - - private final AtomicBoolean running; - private final int nThreads; - private final ThreadFactory threadFactory; - private ScheduledExecutorService executor; - - public PswgScheduledThreadPool(int nThreads, String nameFormat) { - this.running = new AtomicBoolean(false); - this.nThreads = nThreads; - this.threadFactory = new CustomThreadFactory(nameFormat); - this.executor = null; - } - - public void start() { - Assert.test(!running.getAndSet(true)); - executor = Executors.newScheduledThreadPool(nThreads, threadFactory); - } - - public void stop() { - Assert.test(running.getAndSet(false)); - executor.shutdownNow(); - } - - public ScheduledFuture executeWithFixedRate(long initialDelay, long time, Runnable runnable) { - Assert.test(running.get()); - return executor.scheduleAtFixedRate(() -> { - try { - runnable.run(); - } catch (Throwable t) { - Log.e(t); - } - }, initialDelay, time, TimeUnit.MILLISECONDS); - } - - public ScheduledFuture executeWithFixedDelay(long initialDelay, long time, Runnable runnable) { - Assert.test(running.get()); - return executor.scheduleWithFixedDelay(() -> { - try { - runnable.run(); - } catch (Throwable t) { - Log.e(t); - } - }, initialDelay, time, TimeUnit.MILLISECONDS); - } - - public ScheduledFuture execute(long delay, Runnable runnable) { - Assert.test(running.get()); - return executor.schedule(() -> { - try { - runnable.run(); - } catch (Throwable t) { - Log.e(t); - } - }, delay, TimeUnit.MILLISECONDS); - } - - public boolean awaitTermination(long time) { - Assert.notNull(executor); - try { - return executor.awaitTermination(time, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - return false; - } - } - - private static class CustomThreadFactory implements ThreadFactory { - - private final String pattern; - private int counter; - - public CustomThreadFactory(String pattern) { - this.pattern = pattern; - this.counter = 0; - } - - @Override - public Thread newThread(Runnable r) { - String name; - if (pattern.contains("%d")) - name = String.format(pattern, counter++); - else - name = pattern; - return new Thread(r, name); - } - - } - -} diff --git a/src/main/java/com/projectswg/common/concurrency/PswgTaskThreadPool.java b/src/main/java/com/projectswg/common/concurrency/PswgTaskThreadPool.java deleted file mode 100644 index d2ca5fd..0000000 --- a/src/main/java/com/projectswg/common/concurrency/PswgTaskThreadPool.java +++ /dev/null @@ -1,71 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.ArrayDeque; -import java.util.Queue; - -public class PswgTaskThreadPool extends PswgThreadPool { - - private final Queue tasks; - private final Runnable runner; - - public PswgTaskThreadPool(int nThreads, String namePattern, TaskExecutor executor) { - super(nThreads, namePattern); - this.tasks = new ArrayDeque<>(); - this.runner = () -> { - T t = null; - synchronized (tasks) { - t = tasks.poll(); - } - if (t != null) - executor.run(t); - }; - } - - @Override - public boolean execute(Runnable runnable) { - throw new UnsupportedOperationException("Runnable are posted automatically by addTask!"); - } - - public void addTask(T t) { - synchronized (tasks) { - tasks.add(t); - } - super.execute(runner); - } - - public int getTaskCount() { - return tasks.size(); - } - - public interface TaskExecutor { - void run(T t); - } - -} diff --git a/src/main/java/com/projectswg/common/concurrency/PswgThreadPool.java b/src/main/java/com/projectswg/common/concurrency/PswgThreadPool.java deleted file mode 100644 index b93f03f..0000000 --- a/src/main/java/com/projectswg/common/concurrency/PswgThreadPool.java +++ /dev/null @@ -1,202 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.PriorityBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -import com.projectswg.common.debug.Assert; -import com.projectswg.common.debug.Log; -import com.projectswg.common.utilities.ThreadUtilities; - -public class PswgThreadPool { - - private static final Runnable END_OF_QUEUE = new EndOfQueueTask(); - - private final AtomicBoolean running; - private final boolean priorityScheduling; - private final int nThreads; - private final String nameFormat; - private final AtomicInteger priority; - private PswgThreadExecutor executor; - - public PswgThreadPool(int nThreads, String nameFormat) { - this(false, nThreads, nameFormat); - } - - public PswgThreadPool(boolean priorityScheduling, int nThreads, String nameFormat) { - this.running = new AtomicBoolean(false); - this.priorityScheduling = priorityScheduling; - this.nThreads = nThreads; - this.nameFormat = nameFormat; - this.executor = null; - this.priority = new AtomicInteger(Thread.NORM_PRIORITY); - } - - public void setPriority(int priority) { - this.priority.set(priority); - } - - public void start() { - Assert.test(!running.getAndSet(true), "PswgThreadPool has already been started!"); - executor = new PswgThreadExecutor(priorityScheduling, nThreads, ThreadUtilities.newThreadFactory(nameFormat, priority.get())); - executor.start(); - } - - public void stop(boolean interrupt) { - Assert.test(running.getAndSet(false), "PswgThreadPool has already been stopped!"); - executor.stop(interrupt); - } - - public boolean awaitTermination(long timeout) { - Assert.notNull(executor, "Executor hasn't been started yet!"); - return executor.awaitTermination(timeout); - } - - public int getQueuedTasks() { - return executor.getQueuedTasks(); - } - - public boolean execute(Runnable runnable) { - Assert.notNull(executor, "Executor hasn't been started yet!"); - return executor.execute(runnable); - } - - public boolean isRunning() { - return running.get(); - } - - private static class PswgThreadExecutor { - - private final AtomicInteger runningThreads; - private final BlockingQueue tasks; - private final List threads; - private final int nThreads; - - public PswgThreadExecutor(boolean priorityScheduling, int nThreads, ThreadFactory threadFactory) { - this.runningThreads = new AtomicInteger(0); - if (priorityScheduling) - this.tasks = new PriorityBlockingQueue<>(); - else - this.tasks = new LinkedBlockingQueue<>(); - this.threads = new ArrayList<>(nThreads); - this.nThreads = nThreads; - for (int i = 0; i < nThreads; i++) { - threads.add(threadFactory.newThread(this::threadExecutor)); - } - } - - public void start() { - runningThreads.set(nThreads); - for (Thread t : threads) { - t.start(); - } - } - - public void stop(boolean interrupt) { - for (int i = 0; i < nThreads; i++) { - tasks.add(END_OF_QUEUE); - } - if (interrupt) { - for (Thread t : threads) { - t.interrupt(); - } - } - } - - public int getQueuedTasks() { - return tasks.size(); - } - - public boolean execute(Runnable runnable) { - return tasks.offer(runnable); - } - - public boolean awaitTermination(long time) { - try { - synchronized (runningThreads) { - while (runningThreads.get() > 0 && time > 0) { - long startWait = System.nanoTime(); - runningThreads.wait(time); - time -= (long) ((System.nanoTime() - startWait) / 1E6 + 0.5); - } - } - } catch (InterruptedException e) { - return false; - } - return runningThreads.get() == 0; - } - - private void threadExecutor() { - try { - Runnable task = null; - while (task != END_OF_QUEUE) { - task = tasks.take(); - threadRun(task); - } - } catch (InterruptedException e) { - - } finally { - synchronized (runningThreads) { - runningThreads.decrementAndGet(); - runningThreads.notifyAll(); - } - } - } - - private void threadRun(Runnable r) { - try { - r.run(); - } catch (Throwable t) { - Log.e(t); - } - } - - } - - private static class EndOfQueueTask implements Runnable, Comparable { - - @Override - public void run() { - - } - - @Override - public int compareTo(EndOfQueueTask o) { - return 0; - } - - } - -} diff --git a/src/main/java/com/projectswg/common/concurrency/SmartLock.java b/src/main/java/com/projectswg/common/concurrency/SmartLock.java deleted file mode 100644 index 0eea30c..0000000 --- a/src/main/java/com/projectswg/common/concurrency/SmartLock.java +++ /dev/null @@ -1,129 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.Date; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -public class SmartLock { - - private final Lock lock; - private final Condition condition; - - public SmartLock() { - this.lock = new ReentrantLock(true); - this.condition = lock.newCondition(); - } - - public void lock() { - lock.lock(); - } - - public void lockInterruptibly() throws InterruptedException { - lock.lockInterruptibly(); - } - - public boolean tryLock() { - return lock.tryLock(); - } - - public boolean tryLock(long time, TimeUnit unit) throws InterruptedException { - return lock.tryLock(time, unit); - } - - public void unlock() { - lock.unlock(); - } - - public void await() throws InterruptedException { - lock(); - try { - condition.await(); - } finally { - unlock(); - } - } - - public void awaitUninterruptibly() { - lock(); - try { - condition.awaitUninterruptibly(); - } finally { - unlock(); - } - } - - public long awaitNanos(long nanosTimeout) throws InterruptedException { - lock(); - try { - return condition.awaitNanos(nanosTimeout); - } finally { - unlock(); - } - } - - public boolean await(long time, TimeUnit unit) throws InterruptedException { - lock(); - try { - return condition.await(time, unit); - } finally { - unlock(); - } - } - - public boolean awaitUntil(Date deadline) throws InterruptedException { - lock(); - try { - return condition.awaitUntil(deadline); - } finally { - unlock(); - } - } - - public void signal() { - lock(); - try { - condition.signal(); - } finally { - unlock(); - } - } - - public void signalAll() { - lock(); - try { - condition.signalAll(); - } finally { - unlock(); - } - } - -} diff --git a/src/main/java/com/projectswg/common/concurrency/SynchronizedList.java b/src/main/java/com/projectswg/common/concurrency/SynchronizedList.java deleted file mode 100644 index 6382c79..0000000 --- a/src/main/java/com/projectswg/common/concurrency/SynchronizedList.java +++ /dev/null @@ -1,182 +0,0 @@ -/************************************************************************************ - * Copyright (c) 2015 /// Project SWG /// www.projectswg.com * - * * - * ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * - * July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * - * Our goal is to create an emulator which will provide a server for players to * - * continue playing a game similar to the one they used to play. We are basing * - * it on the final publish of the game prior to end-game events. * - * * - * This file is part of Holocore. * - * * - * -------------------------------------------------------------------------------- * - * * - * Holocore is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General public synchronized License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * Holocore is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General public synchronized License for more details. * - * * - * You should have received a copy of the GNU Affero General public synchronized License * - * along with Holocore. If not, see . * - * * - ***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; -import java.util.Spliterator; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.function.UnaryOperator; -import java.util.stream.Stream; - -public class SynchronizedList implements List { - - private final List list; - - public SynchronizedList() { - this.list = new ArrayList<>(); - } - - public SynchronizedList(List list) { - this.list = list; - } - - public synchronized void forEach(Consumer action) { - list.forEach(action); - } - - public synchronized int size() { - return list.size(); - } - - public synchronized boolean isEmpty() { - return list.isEmpty(); - } - - public synchronized boolean contains(Object o) { - return list.contains(o); - } - - public synchronized Iterator iterator() { - return list.iterator(); - } - - public synchronized Object[] toArray() { - return list.toArray(); - } - - public synchronized T[] toArray(T[] a) { - return list.toArray(a); - } - - public synchronized boolean add(E e) { - return list.add(e); - } - - public synchronized boolean remove(Object o) { - return list.remove(o); - } - - public synchronized boolean containsAll(Collection c) { - return list.containsAll(c); - } - - public synchronized boolean addAll(Collection c) { - return list.addAll(c); - } - - public synchronized boolean addAll(int index, Collection c) { - return list.addAll(index, c); - } - - public synchronized boolean removeAll(Collection c) { - return list.removeAll(c); - } - - public synchronized boolean retainAll(Collection c) { - return list.retainAll(c); - } - - public synchronized void replaceAll(UnaryOperator operator) { - list.replaceAll(operator); - } - - public synchronized boolean removeIf(Predicate filter) { - return list.removeIf(filter); - } - - public synchronized void sort(Comparator c) { - list.sort(c); - } - - public synchronized void clear() { - list.clear(); - } - - public synchronized boolean equals(Object o) { - return list.equals(o); - } - - public synchronized int hashCode() { - return list.hashCode(); - } - - public synchronized E get(int index) { - return list.get(index); - } - - public synchronized E set(int index, E element) { - return list.set(index, element); - } - - public synchronized void add(int index, E element) { - list.add(index, element); - } - - public synchronized Stream stream() { - return list.stream(); - } - - public synchronized E remove(int index) { - return list.remove(index); - } - - public synchronized Stream parallelStream() { - return list.parallelStream(); - } - - public synchronized int indexOf(Object o) { - return list.indexOf(o); - } - - public synchronized int lastIndexOf(Object o) { - return list.lastIndexOf(o); - } - - public synchronized ListIterator listIterator() { - return list.listIterator(); - } - - public synchronized ListIterator listIterator(int index) { - return list.listIterator(index); - } - - public synchronized List subList(int fromIndex, int toIndex) { - return list.subList(fromIndex, toIndex); - } - - public synchronized Spliterator spliterator() { - return list.spliterator(); - } - -} diff --git a/src/main/java/com/projectswg/common/concurrency/SynchronizedMap.java b/src/main/java/com/projectswg/common/concurrency/SynchronizedMap.java deleted file mode 100644 index 7794429..0000000 --- a/src/main/java/com/projectswg/common/concurrency/SynchronizedMap.java +++ /dev/null @@ -1,111 +0,0 @@ -/************************************************************************************ - * Copyright (c) 2015 /// Project SWG /// www.projectswg.com * - * * - * ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * - * July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * - * Our goal is to create an emulator which will provide a server for players to * - * continue playing a game similar to the one they used to play. We are basing * - * it on the final publish of the game prior to end-game events. * - * * - * This file is part of Holocore. * - * * - * -------------------------------------------------------------------------------- * - * * - * Holocore is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General public synchronized License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * Holocore is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General public synchronized License for more details. * - * * - * You should have received a copy of the GNU Affero General public synchronized License * - * along with Holocore. If not, see . * - * * - ***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class SynchronizedMap implements Map { - - private final Map map; - - public SynchronizedMap() { - this.map = new HashMap<>(); - } - - public SynchronizedMap(Map map) { - this.map = map; - } - - public synchronized int hashCode() { - return map.hashCode(); - } - - public synchronized boolean equals(Object o) { - return map.equals(o); - } - - public synchronized String toString() { - return map.toString(); - } - - public synchronized int size() { - return map.size(); - } - - public synchronized boolean isEmpty() { - return map.isEmpty(); - } - - public synchronized V get(Object key) { - return map.get(key); - } - - public synchronized boolean containsKey(Object key) { - return map.containsKey(key); - } - - public synchronized V put(K key, V value) { - return map.put(key, value); - } - - public synchronized void putAll(Map m) { - map.putAll(m); - } - - public synchronized V remove(Object key) { - return map.remove(key); - } - - public synchronized void clear() { - map.clear(); - } - - public synchronized boolean containsValue(Object value) { - return map.containsValue(value); - } - - public synchronized Set keySet() { - return map.keySet(); - } - - public synchronized Collection values() { - return map.values(); - } - - public synchronized Set> entrySet() { - return map.entrySet(); - } - - public synchronized V replace(K key, V value) { - return map.replace(key, value); - } - -} diff --git a/src/main/java/com/projectswg/common/concurrency/SynchronizedQueue.java b/src/main/java/com/projectswg/common/concurrency/SynchronizedQueue.java deleted file mode 100644 index 30198b7..0000000 --- a/src/main/java/com/projectswg/common/concurrency/SynchronizedQueue.java +++ /dev/null @@ -1,151 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.ArrayDeque; -import java.util.Collection; -import java.util.Iterator; -import java.util.Queue; -import java.util.Spliterator; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.stream.Stream; - -public class SynchronizedQueue implements Queue { - - private final Queue queue; - - public SynchronizedQueue() { - this(new ArrayDeque<>()); - } - - public SynchronizedQueue(Queue queue) { - this.queue = queue; - } - - public synchronized void forEach(Consumer action) { - queue.forEach(action); - } - - public synchronized boolean add(T e) { - return queue.add(e); - } - - public synchronized boolean offer(T e) { - return queue.offer(e); - } - - public synchronized int size() { - return queue.size(); - } - - public synchronized boolean isEmpty() { - return queue.isEmpty(); - } - - public synchronized boolean contains(Object o) { - return queue.contains(o); - } - - public synchronized T remove() { - return queue.remove(); - } - - public synchronized T poll() { - return queue.poll(); - } - - public synchronized T element() { - return queue.element(); - } - - public synchronized Iterator iterator() { - return queue.iterator(); - } - - public synchronized T peek() { - return queue.peek(); - } - - public synchronized Object[] toArray() { - return queue.toArray(); - } - - public synchronized E[] toArray(E[] a) { - return queue.toArray(a); - } - - public synchronized boolean remove(Object o) { - return queue.remove(o); - } - - public synchronized boolean containsAll(Collection c) { - return queue.containsAll(c); - } - - public synchronized boolean addAll(Collection c) { - return queue.addAll(c); - } - - public synchronized boolean removeAll(Collection c) { - return queue.removeAll(c); - } - - public synchronized boolean removeIf(Predicate filter) { - return queue.removeIf(filter); - } - - public synchronized boolean retainAll(Collection c) { - return queue.retainAll(c); - } - - public synchronized void clear() { - queue.clear(); - } - - public synchronized boolean equals(Object o) { - return queue.equals(o); - } - - public synchronized int hashCode() { - return queue.hashCode(); - } - - public synchronized Spliterator spliterator() { - return queue.spliterator(); - } - - public synchronized Stream stream() { - return queue.stream(); - } - - public synchronized Stream parallelStream() { - return queue.parallelStream(); - } - -} diff --git a/src/main/java/com/projectswg/common/concurrency/SynchronizedSet.java b/src/main/java/com/projectswg/common/concurrency/SynchronizedSet.java deleted file mode 100644 index 2ddffec..0000000 --- a/src/main/java/com/projectswg/common/concurrency/SynchronizedSet.java +++ /dev/null @@ -1,131 +0,0 @@ -/************************************************************************************ - * Copyright (c) 2015 /// Project SWG /// www.projectswg.com * - * * - * ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * - * July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * - * Our goal is to create an emulator which will provide a server for players to * - * continue playing a game similar to the one they used to play. We are basing * - * it on the final publish of the game prior to end-game events. * - * * - * This file is part of Holocore. * - * * - * -------------------------------------------------------------------------------- * - * * - * Holocore is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General public synchronized License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * Holocore is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General public synchronized License for more details. * - * * - * You should have received a copy of the GNU Affero General public synchronized License * - * along with Holocore. If not, see . * - * * - ***********************************************************************************/ -package com.projectswg.common.concurrency; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.util.Spliterator; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.stream.Stream; - -public class SynchronizedSet implements Set { - - private final Set set; - - public SynchronizedSet() { - this.set = new HashSet<>(); - } - - public SynchronizedSet(Set set) { - this.set = set; - } - - public synchronized void forEach(Consumer action) { - set.forEach(action); - } - - public synchronized int size() { - return set.size(); - } - - public synchronized boolean isEmpty() { - return set.isEmpty(); - } - - public synchronized boolean contains(Object o) { - return set.contains(o); - } - - public synchronized Iterator iterator() { - return set.iterator(); - } - - public synchronized Object[] toArray() { - return set.toArray(); - } - - public synchronized T[] toArray(T[] a) { - return set.toArray(a); - } - - public synchronized boolean add(E e) { - return set.add(e); - } - - public synchronized boolean remove(Object o) { - return set.remove(o); - } - - public synchronized boolean containsAll(Collection c) { - return set.containsAll(c); - } - - public synchronized boolean addAll(Collection c) { - return set.addAll(c); - } - - public synchronized boolean retainAll(Collection c) { - return set.retainAll(c); - } - - public synchronized boolean removeAll(Collection c) { - return set.removeAll(c); - } - - public synchronized void clear() { - set.clear(); - } - - public synchronized boolean equals(Object o) { - return set.equals(o); - } - - public synchronized int hashCode() { - return set.hashCode(); - } - - public synchronized Spliterator spliterator() { - return set.spliterator(); - } - - public synchronized boolean removeIf(Predicate filter) { - return set.removeIf(filter); - } - - public synchronized Stream stream() { - return set.stream(); - } - - public synchronized Stream parallelStream() { - return set.parallelStream(); - } - -} diff --git a/src/main/java/com/projectswg/common/control/Intent.java b/src/main/java/com/projectswg/common/control/Intent.java deleted file mode 100644 index 1425cf1..0000000 --- a/src/main/java/com/projectswg/common/control/Intent.java +++ /dev/null @@ -1,182 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.control; - -import java.util.function.Consumer; - -public abstract class Intent { - - private boolean broadcasted; - private boolean complete; - private Intent parallel; - private Intent sequential; - private Consumer completedCallback; - - protected Intent() { - this.broadcasted = false; - this.complete = false; - this.parallel = null; - this.sequential = null; - this.completedCallback = null; - } - - /** - * Called when the intent has been completed - */ - protected synchronized void markAsComplete(IntentManager intentManager) { - this.complete = true; - if (sequential != null) - sequential.broadcast(intentManager); - sequential = null; - parallel = null; - } - - public Consumer getCompletedCallback() { - return completedCallback; - } - - public void setCompletedCallback(Consumer completedCallback) { - this.completedCallback = completedCallback; - } - - /** - * Determines whether or not the intent has been broadcasted and processed - * by the system - * @return TRUE if the intent has been broadcasted and processed, FALSE - * otherwise - */ - public synchronized boolean isComplete() { - return complete; - } - - /** - * Determines whether or not the intent has been broadcasted to the system - * @return TRUE if the intent has been broadcasted, FALSE otherwise - */ - public synchronized boolean isBroadcasted() { - return broadcasted; - } - - /** - * Waits for the intent as the parameter to finish before this intent - * starts - * @param i the intent to execute after - */ - public synchronized void broadcastAfterIntent(Intent i) { - broadcastAfterIntent(i, IntentManager.getInstance()); - } - - /** - * Waits for the intent as the parameter to finish before this intent - * starts - * @param i the intent to execute after - * @param intentManager the intent manager to broadcast this intent on - */ - public synchronized void broadcastAfterIntent(Intent i, IntentManager intentManager) { - if (i == null) { - broadcast(intentManager); - return; - } - synchronized (i) { - if (i.isComplete()) - broadcast(intentManager); - else - i.setAsSequential(this); - } - } - - /** - * Waits for the intent as the parameter to start before this intent starts - * @param i the intent to execute with - */ - public synchronized void broadcastWithIntent(Intent i) { - broadcastWithIntent(i, IntentManager.getInstance()); - } - - /** - * Waits for the intent as the parameter to start before this intent starts - * @param i the intent to execute with - * @param intentManager the intent manager to broadcast this intent on - */ - public synchronized void broadcastWithIntent(Intent i, IntentManager intentManager) { - if (i == null) { - broadcast(intentManager); - return; - } - synchronized (i) { - if (!isComplete()) { - setAsParallel(i); - } - broadcast(intentManager); - } - } - - /** - * Broadcasts this node to the system - */ - public synchronized void broadcast() { - broadcast(IntentManager.getInstance()); - } - - /** - * Broadcasts this node to the system with the specified intent manager - * - * @param intentManager the intent manager to broadcast this intent on - */ - public synchronized void broadcast(IntentManager intentManager) { - if (broadcasted) - throw new IllegalStateException("Intent has already been broadcasted!"); - if (intentManager == null) - return; - broadcasted = true; - intentManager.broadcastIntent(this); - if (parallel != null) - parallel.broadcast(intentManager); - parallel = null; - } - - @Override - public synchronized String toString() { - return getClass().getSimpleName(); - } - - private synchronized void setAsParallel(Intent i) { - if (parallel == null) - parallel = i; - else - parallel.setAsParallel(i); - } - - private synchronized void setAsSequential(Intent i) { - if (sequential == null) - sequential = i; - else - sequential.setAsParallel(i); - } - -} diff --git a/src/main/java/com/projectswg/common/control/IntentChain.java b/src/main/java/com/projectswg/common/control/IntentChain.java deleted file mode 100644 index 8251e26..0000000 --- a/src/main/java/com/projectswg/common/control/IntentChain.java +++ /dev/null @@ -1,72 +0,0 @@ -/************************************************************************************ - * Copyright (c) 2015 /// Project SWG /// www.projectswg.com * - * * - * ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * - * July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * - * Our goal is to create an emulator which will provide a server for players to * - * continue playing a game similar to the one they used to play. We are basing * - * it on the final publish of the game prior to end-game events. * - * * - * This file is part of Holocore. * - * * - * -------------------------------------------------------------------------------- * - * * - * Holocore is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * Holocore is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with Holocore. If not, see . * - * * - ***********************************************************************************/ -package com.projectswg.common.control; - -import com.projectswg.common.debug.Assert; - -import java.util.concurrent.atomic.AtomicReference; - -public class IntentChain { - - private final IntentManager intentManager; - private final AtomicReference previousIntent; - - public IntentChain() { - this(IntentManager.getInstance()); - } - - public IntentChain(IntentManager intentManager) { - this(intentManager, null); - } - - public IntentChain(Intent i) { - this(IntentManager.getInstance(), i); - } - - public IntentChain(IntentManager intentManager, Intent i) { - this.intentManager = intentManager; - this.previousIntent = new AtomicReference<>(i); - } - - public void reset() { - previousIntent.set(null); - } - - public void broadcastAfter(Intent i) { - i.broadcastAfterIntent(previousIntent.getAndSet(i), intentManager); - } - - public static void broadcastChain(Intent ... intents) { - Assert.test(intents.length > 0, "Intent length must be greater than 0!"); - for (int i = 1; i < intents.length; i++) { - intents[i].broadcastAfterIntent(intents[i-1]); - } - intents[0].broadcast(); - } - -} diff --git a/src/main/java/com/projectswg/common/control/IntentManager.java b/src/main/java/com/projectswg/common/control/IntentManager.java deleted file mode 100644 index d643d99..0000000 --- a/src/main/java/com/projectswg/common/control/IntentManager.java +++ /dev/null @@ -1,255 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.control; - -import com.projectswg.common.concurrency.PswgThreadPool; -import com.projectswg.common.debug.Log; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Consumer; - -public class IntentManager { - - private static final AtomicReference INSTANCE = new AtomicReference<>(null); - - private final Map , List>> intentRegistrations; - private final IntentSpeedRecorder speedRecorder; - private final PswgThreadPool processThreads; - private final AtomicBoolean initialized; - - public IntentManager(int threadCount) { - this.intentRegistrations = new ConcurrentHashMap<>(); - this.speedRecorder = new IntentSpeedRecorder(); - this.processThreads = new PswgThreadPool(true, threadCount, "intent-processor-%d"); - this.initialized = new AtomicBoolean(false); - - this.processThreads.setPriority(8); - } - - public void initialize() { - if (initialized.getAndSet(true)) - return; - processThreads.start(); - } - - public void terminate() { - if (!initialized.getAndSet(false)) - return; - processThreads.stop(true); - processThreads.awaitTermination(1000); - } - - public int getIntentCount() { - return processThreads.getQueuedTasks(); - } - - public IntentSpeedRecorder getSpeedRecorder() { - return speedRecorder; - } - - public void broadcastIntent(Intent i) { - Objects.requireNonNull(i, "Intent cannot be null!"); - List > receivers = intentRegistrations.get(i.getClass()); - if (receivers == null) - return; - - AtomicInteger remaining = new AtomicInteger(receivers.size()); - for (Consumer r : receivers) { -// processThreads.execute(() -> executeConsumer(r, i, remaining)); - processThreads.execute(new IntentRunner(r, i, remaining)); - } - } - - @SuppressWarnings("unchecked") - public void registerForIntent(Class c, Consumer r) { - if (r == null) - throw new NullPointerException("Cannot register a null consumer for an intent"); - List > intents = intentRegistrations.get(c); - if (intents == null) { - intents = new CopyOnWriteArrayList<>(); - List> replaced = intentRegistrations.putIfAbsent((Class) c, intents); - if (replaced != null) { - intents = replaced; - } - } - intents.add((Consumer) r); - } - - public void unregisterForIntent(Class c, Consumer r) { - if (r == null) - throw new NullPointerException("Cannot register a null consumer for an intent"); - List > intents = intentRegistrations.get(c); - if (intents == null) - return; - intents.remove(r); - } - - public static IntentManager getInstance() { - return INSTANCE.get(); - } - - public static void setInstance(IntentManager intentManager) { - IntentManager prev = INSTANCE.getAndSet(intentManager); - if (prev != null) - prev.terminate(); - } - - public static class IntentSpeedRecorder { - - private final Map, IntentSpeedRecord> times; - - public IntentSpeedRecorder() { - this.times = new ConcurrentHashMap<>(); - } - - private void addRecord(Class intent, Consumer consumer, long timeNanos) { - IntentSpeedRecord record = times.get(consumer); - if (record == null) { - record = new IntentSpeedRecord(intent, consumer); - IntentSpeedRecord replaced = times.putIfAbsent(consumer, record); - if (replaced != null) - record = replaced; - } - record.addTime(timeNanos); - } - - public IntentSpeedRecord getTime(Consumer consumer) { - return times.get(consumer); - } - - public List getAllTimes() { - return new ArrayList<>(times.values()); - } - - } - - public static class IntentSpeedRecord implements Comparable { - - private final Class intent; - private final Consumer consumer; - private final AtomicLong time; - private final AtomicLong count; - - public IntentSpeedRecord(Class intent, Consumer consumer) { - this.intent = intent; - this.consumer = consumer; - this.time = new AtomicLong(0); - this.count = new AtomicLong(0); - } - - public Class getIntent() { - return intent; - } - - public Consumer getConsumer() { - return consumer; - } - - public long getTime() { - return time.get(); - } - - public long getCount() { - return count.get(); - } - - public int getPriority() { - long time = getTime(); - long count = getCount(); - if (count == 0) - return 0; - return (int) (time / count / 1000); - } - - public void addTime(long timeNanos) { - time.addAndGet(timeNanos); - count.incrementAndGet(); - } - - @Override - public int compareTo(IntentSpeedRecord record) { - return Long.compare(record.getTime(), getTime()); - } - - } - - private class IntentRunner implements Comparable, Runnable { - - private final Consumer r; - private final Intent i; - private final AtomicInteger remaining; - private final int priority; - - public IntentRunner(Consumer r, Intent i, AtomicInteger remaining) { - this.r = r; - this.i = i; - this.remaining = remaining; - IntentSpeedRecord record = speedRecorder.getTime(r); - if (record == null) - this.priority = 0; - else - this.priority = record.getPriority(); - } - - @Override - public void run() { - try { - long start = System.nanoTime(); - r.accept(i); - long time = System.nanoTime() - start; - speedRecorder.addRecord(i.getClass(), r, time); - } catch (Throwable t) { - Log.e("Fatal Exception while processing intent: " + i); - Log.e(t); - } finally { - if (remaining.decrementAndGet() <= 0) { - i.markAsComplete(IntentManager.this); - Consumer completedCallback = i.getCompletedCallback(); - if (completedCallback != null) - completedCallback.accept(i); - } - } - } - - @Override - public int compareTo(IntentRunner r) { - return Integer.compare(priority, r.priority); - } - - } - -} diff --git a/src/main/java/com/projectswg/common/control/IntentQueue.java b/src/main/java/com/projectswg/common/control/IntentQueue.java deleted file mode 100644 index 515d1fa..0000000 --- a/src/main/java/com/projectswg/common/control/IntentQueue.java +++ /dev/null @@ -1,235 +0,0 @@ -/************************************************************************************ - * Copyright (c) 2015 /// Project SWG /// www.projectswg.com * - * * - * ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * - * July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * - * Our goal is to create an emulator which will provide a server for players to * - * continue playing a game similar to the one they used to play. We are basing * - * it on the final publish of the game prior to end-game events. * - * * - * This file is part of Holocore. * - * * - * -------------------------------------------------------------------------------- * - * * - * Holocore is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * Holocore is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with Holocore. If not, see . * - * * - ***********************************************************************************/ -package com.projectswg.common.control; - -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.NoSuchElementException; -import java.util.Queue; - -class IntentQueue implements Queue { - - private final Node head; - private int size; - private int modificationCount; - - public IntentQueue() { - head = new Node(null, null, null); // Left = Forward, Right = Reverse - head.left = head; - head.right = head; - modificationCount = 0; - } - - @Override - public int size() { - return size; - } - - @Override - public boolean isEmpty() { - return size == 0; - } - - @Override - public boolean contains(Object o) { - Node n = head; - while (n.left != head) { - if (n.left.value == o) - return true; - } - return false; - } - - @Override - public Iterator iterator() { - return new Iterator(); - } - - @Override - public Object [] toArray() { - return null; - } - - @Override - public T [] toArray(T [] a) { - return null; - } - - @Override - public boolean remove(Object o) { - modificationCount++; - Node n = head; - while (n.left != head) { - if (n.left.value == o) { - n.left = n.left.left; - n.left.right = n; - } - } - return false; - } - - @Override - public boolean containsAll(Collection c) { - for (Object o : c) - if (!contains(o)) - return false; - return true; - } - - @Override - public boolean addAll(Collection c) { - boolean added = false; - for (E i : c) - added = add(i) || added; - return added; - } - - @Override - public boolean removeAll(Collection c) { - boolean changed = false; - for (Object o : c) - changed = remove(o) || changed; - return changed; - } - - @Override - public boolean retainAll(Collection c) { - boolean changed = false; - Node n = head; - while (n.left != head) { - if (!c.contains(n.left.value)) { - n.left.left.right = n; - n.left = n.left.left; - } - } - return changed; - } - - @Override - public void clear() { - modificationCount++; - size = 0; - head.left = head; - head.right = head; - } - - @Override - public boolean add(E e) { - head.right.left = new Node(e, head, head.right); - head.right = head.right.left; - modificationCount++; - size++; - return true; - } - - @Override - public boolean offer(E e) { - return add(e); - } - - @Override - public E remove() { - if (isEmpty()) - throw new NoSuchElementException("Queue is empty!"); - modificationCount++; - E i = head.left.value; - head.left = head.left.left; - head.left.right = head; - size--; - return i; - } - - @Override - public E poll() { - if (isEmpty()) - return null; - modificationCount++; - E i = head.left.value; - head.left = head.left.left; - head.left.right = head; - size--; - return i; - } - - @Override - public E element() { - if (isEmpty()) - throw new NoSuchElementException("Queue is empty!"); - return head.left.value; - } - - @Override - public E peek() { - if (isEmpty()) - return null; - return head.left.value; - } - - private class Iterator implements java.util.Iterator { - - private final int modificationCount; - private Node currentNode; - - public Iterator() { - this.modificationCount = IntentQueue.this.modificationCount; - this.currentNode = IntentQueue.this.head; - } - - @Override - public boolean hasNext() { - if (this.modificationCount != IntentQueue.this.modificationCount) - throw new ConcurrentModificationException(); - return currentNode.left != IntentQueue.this.head; - } - - @Override - public E next() { - if (!hasNext()) - throw new NoSuchElementException("Iterator has reached the end of the queue!"); - E i = currentNode.left.value; - currentNode = currentNode.left; - return i; - } - - } - - private class Node { - - public final E value; - public Node left; - public Node right; - - public Node(E value, Node left, Node right) { - this.value = value; - this.left = left; - this.right = right; - } - - } - -} diff --git a/src/main/java/com/projectswg/common/control/IntentReceiver.java b/src/main/java/com/projectswg/common/control/IntentReceiver.java deleted file mode 100644 index 3839e4c..0000000 --- a/src/main/java/com/projectswg/common/control/IntentReceiver.java +++ /dev/null @@ -1,41 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.control; - - -public interface IntentReceiver { - - /** - * This function will be called if an intent is broadcasted and this - * manager is listening for it, or if this manager is specifically given - * this intent. - * @param i the intent received - */ - public void onIntentReceived(Intent i); - -} diff --git a/src/main/java/com/projectswg/common/control/Manager.java b/src/main/java/com/projectswg/common/control/Manager.java deleted file mode 100644 index afd1208..0000000 --- a/src/main/java/com/projectswg/common/control/Manager.java +++ /dev/null @@ -1,246 +0,0 @@ -/*********************************************************************************** - * Copyright (c) 2015 /// Project SWG /// www.projectswg.com * - * * - * ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * - * July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * - * Our goal is to create an emulator which will provide a server for players to * - * continue playing a game similar to the one they used to play. We are basing * - * it on the final publish of the game prior to end-game events. * - * * - * This file is part of Holocore. * - * * - * -------------------------------------------------------------------------------- * - * * - * Holocore is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * Holocore is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with Holocore. If not, see . * - * * - ***********************************************************************************/ -package com.projectswg.common.control; - -import com.projectswg.common.concurrency.Delay; -import com.projectswg.common.debug.Log; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.CopyOnWriteArrayList; - -/** - * A Manager is a class that will manage services, and generally controls the program as a whole - */ -public abstract class Manager extends Service { - - private final List initialized; - private final List started; - private final List children; - - public Manager() { - initialized = new CopyOnWriteArrayList<>(); - started = new CopyOnWriteArrayList<>(); - children = new CopyOnWriteArrayList<>(); - } - - /** - * Initializes this manager. If the manager returns false on this method then the initialization failed and may not work as intended. This will - * initialize all children automatically. - * - * @return TRUE if initialization was successful, FALSE otherwise - */ - @Override - public boolean initialize() { - boolean success = super.initialize(); - for (Service child : children) { - try { - if (!child.initialize()) { - Log.e("%s failed to initialize!", child.getClass().getSimpleName()); - success = false; - break; - } - initialized.add(child); - } catch (Throwable t) { - Log.e("%s failed to initialize!", child.getClass().getSimpleName()); - Log.e(t); - success = false; - break; - } - } - return success; - } - - /** - * Starts this manager. If the manager returns false on this method then the manger failed to start and may not work as intended. This will start - * all children automatically. - * - * @return TRUE if starting was successful, FALSE otherwise - */ - @Override - public boolean start() { - boolean success = super.start(); - for (Service child : children) { - try { - if (!child.start()) { - Log.e("%s failed to start!", child.getClass().getSimpleName()); - success = false; - break; - } - started.add(child); - } catch (Throwable t) { - Log.e("%s failed to start!", child.getClass().getSimpleName()); - Log.e(t); - success = false; - break; - } - } - return success; - } - - /** - * Stops this manager. If the manager returns false on this method then the manger failed to stop and may not have fully locked down. This will - * start all children automatically. - * - * @return TRUE if stopping was successful, FALSE otherwise - */ - @Override - public boolean stop() { - boolean success = super.stop(); - for (Service child : started) { - try { - if (!child.stop()) { - Log.e("%s failed to stop!", child.getClass().getSimpleName()); - success = false; - } - } catch (Throwable t) { - Log.e("%s failed to stop!", child.getClass().getSimpleName()); - Log.e(t); - success = false; - } - } - return success; - } - - /** - * Terminates this manager. If the manager returns false on this method then the manager failed to shut down and resources may not have been - * cleaned up. This will terminate all children automatically. - * - * @return TRUE if termination was successful, FALSE otherwise - */ - @Override - public boolean terminate() { - boolean success = super.terminate(); - for (Service child : initialized) { - try { - if (!child.terminate()) { - Log.e("%s failed to terminate!", child.getClass().getSimpleName()); - success = false; - } - } catch (Throwable t) { - Log.e("%s failed to terminate!", child.getClass().getSimpleName()); - Log.e(t); - success = false; - } - } - return success; - } - - /** - * Determines whether or not this manager is operational - * - * @return TRUE if this manager is operational, FALSE otherwise - */ - @Override - public boolean isOperational() { - for (Service child : children) { - if (!child.isOperational()) - return false; - } - return true; - } - - /** - * Adds a child to the manager's list of children. This creates a tree of managers that allows information to propogate freely through the network - * in an easy way. - * - * @param service the service to add as a child. - */ - public void addChildService(Service service) { - Objects.requireNonNull(service, "service"); - if (children.contains(service)) - return; - children.add(service); - IntentManager manager = getIntentManager(); - if (manager != null) - service.setIntentManager(manager); - } - - /** - * Removes the sub-manager from the list of children - * - * @param service the service to remove - */ - public void removeChildService(Service service) { - Objects.requireNonNull(service, "service"); - children.remove(service); - } - - /** - * Returns a copied ArrayList of the children of this manager - * - * @return a copied ArrayList of the children of this manager - */ - public List getManagerChildren() { - return new ArrayList<>(children); - } - - @Override - public void setIntentManager(IntentManager intentManager) { - super.setIntentManager(intentManager); - for (Service s : children) { - s.setIntentManager(intentManager); - } - } - - public static void startManager(Manager manager) { - Log.i("Initializing..."); - if (!manager.initialize()) { - Log.e("Failed to initialize!"); - terminateManager(manager); - return; - } - Log.i("Initialized."); - if (!manager.start()) { - Log.e("Failed to start!"); - stopManager(manager); - return; - } - Log.i("Started."); - while (manager.isOperational()) { - if (Delay.sleepMilli(50)) - break; - } - stopManager(manager); - } - - private static void stopManager(Manager manager) { - Log.i("Stopping..."); - manager.stop(); - Log.i("Stopped."); - terminateManager(manager); - } - - private static void terminateManager(Manager manager) { - Log.i("Terminating..."); - manager.terminate(); - Log.i("Terminated."); - } - -} diff --git a/src/main/java/com/projectswg/common/control/PrimaryManager.java b/src/main/java/com/projectswg/common/control/PrimaryManager.java deleted file mode 100644 index 5ee4a3e..0000000 --- a/src/main/java/com/projectswg/common/control/PrimaryManager.java +++ /dev/null @@ -1,73 +0,0 @@ -/*********************************************************************************** - * Copyright (c) 2018 /// Project SWG /// www.projectswg.com * - * * - * ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * - * July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * - * Our goal is to create an emulator which will provide a server for players to * - * continue playing a game similar to the one they used to play. We are basing * - * it on the final publish of the game prior to end-game events. * - * * - * This file is part of Holocore. * - * * - * --------------------------------------------------------------------------------* - * * - * Holocore is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * Holocore is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with Holocore. If not, see . * - * * - ***********************************************************************************/ -package com.projectswg.common.control; - -public class PrimaryManager { - - private final Manager manager; - - public PrimaryManager() { - this(new DefaultManager()); - } - - public PrimaryManager(Manager manager) { - this.manager = manager; - } - - public void addChildService(Service service) { - manager.addChildService(service); - } - - public boolean initialize() { - return manager.initialize(); - } - - public boolean start() { - boolean ret = manager.start(); - if (!ret) - terminate(); - return ret; - } - - public boolean isOperational() { - return manager.isOperational(); - } - - public boolean stop() { - return manager.stop(); - } - - public boolean terminate() { - return manager.terminate(); - } - - private static class DefaultManager extends Manager { - - } - -} diff --git a/src/main/java/com/projectswg/common/control/Service.java b/src/main/java/com/projectswg/common/control/Service.java deleted file mode 100644 index 0d15dc3..0000000 --- a/src/main/java/com/projectswg/common/control/Service.java +++ /dev/null @@ -1,119 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.control; - -import java.util.function.Consumer; - -/** - * A Service is a class that does a specific job for the application - */ -public abstract class Service { - - private IntentManager intentManager; - - public Service() { - this.intentManager = IntentManager.getInstance(); - } - - /** - * Initializes this service. If the service returns false on this method - * then the initialization failed and may not work as intended. - * @return TRUE if initialization was successful, FALSE otherwise - */ - public boolean initialize() { - return true; - } - - /** - * Starts this service. If the service returns false on this method then - * the service failed to start and may not work as intended. - * @return TRUE if starting was successful, FALSE otherwise - */ - public boolean start() { - return true; - } - - /** - * Stops the service. If the service returns false on this method then the - * service failed to stop and may not have fully locked down. - * @return TRUE if stopping was successful, FALSe otherwise - */ - public boolean stop() { - return true; - } - - /** - * Terminates this service. If the service returns false on this method - * then the service failed to shut down and resources may not have been - * cleaned up. - * @return TRUE if termination was successful, FALSE otherwise - */ - public boolean terminate() { - IntentManager im = IntentManager.getInstance(); - if (im != null) - im.terminate(); - return true; - } - - /** - * Determines whether or not this service is operational - * @return TRUE if this service is operational, FALSE otherwise - */ - public boolean isOperational() { - return true; - } - - /** - * Registers for the intent using the specified consumer - * @param c the class of intent to register for - * @param consumer the consumer to run when the intent is fired - */ - protected void registerForIntent(Class c, Consumer consumer) { - intentManager.registerForIntent(c, consumer); - } - - /** - * Unregisters for the intent using the specified consumer - * @param c the class of intent to unregister - * @param consumer the consumer that was previous registered - */ - protected void unregisterForIntent(Class c, Consumer consumer) { - intentManager.unregisterForIntent(c, consumer); - } - - public void setIntentManager(IntentManager intentManager) { - if (intentManager == null) - throw new NullPointerException("IntentManager cannot be null!"); - this.intentManager = intentManager; - } - - public IntentManager getIntentManager() { - return intentManager; - } - -} diff --git a/src/main/java/com/projectswg/common/data/CrcDatabase.java b/src/main/java/com/projectswg/common/data/CrcDatabase.java index 944c74c..9829d7e 100644 --- a/src/main/java/com/projectswg/common/data/CrcDatabase.java +++ b/src/main/java/com/projectswg/common/data/CrcDatabase.java @@ -37,7 +37,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; public class CrcDatabase { diff --git a/src/main/java/com/projectswg/common/data/Pair.java b/src/main/java/com/projectswg/common/data/Pair.java index 87ffe15..4430c4d 100644 --- a/src/main/java/com/projectswg/common/data/Pair.java +++ b/src/main/java/com/projectswg/common/data/Pair.java @@ -1,9 +1,5 @@ package com.projectswg.common.data; -import java.util.Objects; - -import com.projectswg.common.debug.Assert; -import com.projectswg.common.debug.Log; import com.projectswg.common.encoding.CachedEncode; import com.projectswg.common.encoding.Encodable; import com.projectswg.common.encoding.Encoder; @@ -11,6 +7,9 @@ import com.projectswg.common.encoding.StringType; import com.projectswg.common.network.NetBuffer; import com.projectswg.common.network.NetBufferStream; import com.projectswg.common.persistable.Persistable; +import me.joshlarson.jlcommon.log.Log; + +import java.util.Objects; public class Pair implements Encodable, Persistable { @@ -25,8 +24,10 @@ public class Pair implements Encodable, Persistable { private Pair(T left, S right, Class leftClass, Class rightClass, StringType leftType, StringType rightType) { // Final checks - has to be either one or the other. These ensure other assumptions in the class will succeed - Assert.test((leftType == null && !(left instanceof String) && !leftClass.equals(String.class)) ^ (leftType != null && (left instanceof String) && leftClass.equals(String.class))); - Assert.test((rightType == null && !(right instanceof String) && !rightClass.equals(String.class)) ^ (rightType != null && (right instanceof String) && rightClass.equals(String.class))); + if ((leftType == null && !(left instanceof String) && !leftClass.equals(String.class)) == (leftType != null && (left instanceof String) && leftClass.equals(String.class))) + throw new IllegalArgumentException("Invalid left arguments"); + if ((rightType == null && !(right instanceof String) && !rightClass.equals(String.class)) == (rightType != null && (right instanceof String) && rightClass.equals(String.class))) + throw new IllegalArgumentException("Invalid right arguments"); this.leftClass = leftClass; this.rightClass = rightClass; this.leftType = leftType; @@ -150,8 +151,10 @@ public class Pair implements Encodable, Persistable { } public static Pair createPair(T left, S right, Class leftClass, Class rightClass) { - Assert.test(!(left instanceof String)); - Assert.test(!(right instanceof String)); + if (!(left instanceof String)) + throw new IllegalArgumentException("Invalid left argument"); + if (!(right instanceof String)) + throw new IllegalArgumentException("Invalid right argument"); return new Pair<>(left, right, leftClass, rightClass, null, null); } @@ -162,7 +165,8 @@ public class Pair implements Encodable, Persistable { } public static Pair createPair(String left, T right, StringType type, Class rightClass) { - Assert.test(!(right instanceof String)); + if (!(right instanceof String)) + throw new IllegalArgumentException("Invalid right argument"); return new Pair<>(left, right, String.class, rightClass, type, null); } @@ -173,7 +177,8 @@ public class Pair implements Encodable, Persistable { } public static Pair createPair(T left, String right, Class leftClass, StringType type) { - Assert.test(!(left instanceof String)); + if (!(left instanceof String)) + throw new IllegalArgumentException("Invalid left argument"); return new Pair<>(left, right, leftClass, String.class, null, type); } diff --git a/src/main/java/com/projectswg/common/data/customization/CustomizationString.java b/src/main/java/com/projectswg/common/data/customization/CustomizationString.java index ab12dab..2930f43 100644 --- a/src/main/java/com/projectswg/common/data/customization/CustomizationString.java +++ b/src/main/java/com/projectswg/common/data/customization/CustomizationString.java @@ -27,18 +27,21 @@ ***********************************************************************************/ package com.projectswg.common.data.customization; -import com.projectswg.common.concurrency.SynchronizedMap; import com.projectswg.common.data.swgfile.ClientFactory; import com.projectswg.common.data.swgfile.visitors.CustomizationIDManagerData; -import com.projectswg.common.debug.Log; import com.projectswg.common.encoding.Encodable; import com.projectswg.common.network.NetBuffer; import com.projectswg.common.network.NetBufferStream; import com.projectswg.common.persistable.Persistable; +import me.joshlarson.jlcommon.log.Log; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.io.Writer; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.BiConsumer; @@ -54,7 +57,7 @@ public class CustomizationString implements Encodable, Persistable { private Map variables; public CustomizationString() { - variables = new SynchronizedMap<>(new LinkedHashMap<>()); // Ordered and synchronized + variables = Collections.synchronizedMap(new LinkedHashMap<>()); // Ordered and synchronized } boolean isEmpty() { diff --git a/src/main/java/com/projectswg/common/data/encodables/oob/OutOfBandPackage.java b/src/main/java/com/projectswg/common/data/encodables/oob/OutOfBandPackage.java index 959d399..366cb25 100644 --- a/src/main/java/com/projectswg/common/data/encodables/oob/OutOfBandPackage.java +++ b/src/main/java/com/projectswg/common/data/encodables/oob/OutOfBandPackage.java @@ -33,7 +33,7 @@ import java.util.List; import com.projectswg.common.data.EnumLookup; import com.projectswg.common.data.encodables.oob.waypoint.WaypointPackage; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import com.projectswg.common.encoding.Encodable; import com.projectswg.common.network.NetBuffer; import com.projectswg.common.network.NetBufferStream; diff --git a/src/main/java/com/projectswg/common/data/encodables/oob/ProsePackage.java b/src/main/java/com/projectswg/common/data/encodables/oob/ProsePackage.java index efe264a..ca9c61b 100644 --- a/src/main/java/com/projectswg/common/data/encodables/oob/ProsePackage.java +++ b/src/main/java/com/projectswg/common/data/encodables/oob/ProsePackage.java @@ -27,14 +27,14 @@ ***********************************************************************************/ package com.projectswg.common.data.encodables.oob; -import java.math.BigInteger; - -import com.projectswg.common.debug.Assert; -import com.projectswg.common.debug.Log; import com.projectswg.common.encoding.Encodable; import com.projectswg.common.network.NetBuffer; import com.projectswg.common.network.NetBufferStream; import com.projectswg.common.persistable.Persistable; +import me.joshlarson.jlcommon.log.Log; + +import java.math.BigInteger; +import java.util.Objects; public class ProsePackage implements OutOfBandData { @@ -194,7 +194,7 @@ public class ProsePackage implements OutOfBandData { @Override public byte[] encode() { - Assert.notNull(base, "There must be a StringId base!"); + Objects.requireNonNull(base, "There must be a StringId base!"); NetBuffer data = NetBuffer.allocate(getLength()); data.addEncodable(base); data.addEncodable(actor); @@ -291,12 +291,12 @@ public class ProsePackage implements OutOfBandData { } public void setStringId(StringId stringId) { - Assert.notNull(stringId, "StringId cannot be null!"); + Objects.requireNonNull(stringId, "StringId cannot be null!"); this.stringId = stringId; } public void setText(String text) { - Assert.notNull(text, "Text cannot be null!"); + Objects.requireNonNull(text, "Text cannot be null!"); this.text = text; } diff --git a/src/main/java/com/projectswg/common/data/encodables/oob/StringId.java b/src/main/java/com/projectswg/common/data/encodables/oob/StringId.java index 8328ffc..da51528 100644 --- a/src/main/java/com/projectswg/common/data/encodables/oob/StringId.java +++ b/src/main/java/com/projectswg/common/data/encodables/oob/StringId.java @@ -27,7 +27,7 @@ ***********************************************************************************/ package com.projectswg.common.data.encodables.oob; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import com.projectswg.common.network.NetBuffer; import com.projectswg.common.network.NetBufferStream; import com.projectswg.common.persistable.Persistable; diff --git a/src/main/java/com/projectswg/common/data/info/ConfigData.java b/src/main/java/com/projectswg/common/data/info/ConfigData.java index 4bf06f6..1c8d631 100644 --- a/src/main/java/com/projectswg/common/data/info/ConfigData.java +++ b/src/main/java/com/projectswg/common/data/info/ConfigData.java @@ -43,7 +43,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; class ConfigData { diff --git a/src/main/java/com/projectswg/common/data/info/RelationalDatabase.java b/src/main/java/com/projectswg/common/data/info/RelationalDatabase.java index f4fb888..9e95b27 100644 --- a/src/main/java/com/projectswg/common/data/info/RelationalDatabase.java +++ b/src/main/java/com/projectswg/common/data/info/RelationalDatabase.java @@ -37,7 +37,7 @@ import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.sql.Statement; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; public abstract class RelationalDatabase implements Closeable { diff --git a/src/main/java/com/projectswg/common/data/info/RelationalServerData.java b/src/main/java/com/projectswg/common/data/info/RelationalServerData.java index 2ceb235..47775a0 100644 --- a/src/main/java/com/projectswg/common/data/info/RelationalServerData.java +++ b/src/main/java/com/projectswg/common/data/info/RelationalServerData.java @@ -40,7 +40,7 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; public class RelationalServerData extends RelationalDatabase { diff --git a/src/main/java/com/projectswg/common/data/info/RelationalServerFactory.java b/src/main/java/com/projectswg/common/data/info/RelationalServerFactory.java index 25dc554..ecacc90 100644 --- a/src/main/java/com/projectswg/common/data/info/RelationalServerFactory.java +++ b/src/main/java/com/projectswg/common/data/info/RelationalServerFactory.java @@ -39,7 +39,7 @@ import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; public class RelationalServerFactory { diff --git a/src/main/java/com/projectswg/common/data/radial/RadialOptionList.java b/src/main/java/com/projectswg/common/data/radial/RadialOptionList.java index d687990..7c6bf8c 100644 --- a/src/main/java/com/projectswg/common/data/radial/RadialOptionList.java +++ b/src/main/java/com/projectswg/common/data/radial/RadialOptionList.java @@ -33,7 +33,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import com.projectswg.common.encoding.Encodable; import com.projectswg.common.network.NetBuffer; diff --git a/src/main/java/com/projectswg/common/data/sui/SuiBaseWindow.java b/src/main/java/com/projectswg/common/data/sui/SuiBaseWindow.java index 6fbacca..7972419 100644 --- a/src/main/java/com/projectswg/common/data/sui/SuiBaseWindow.java +++ b/src/main/java/com/projectswg/common/data/sui/SuiBaseWindow.java @@ -27,7 +27,7 @@ ***********************************************************************************/ package com.projectswg.common.data.sui; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import com.projectswg.common.encoding.Encodable; import com.projectswg.common.network.NetBuffer; diff --git a/src/main/java/com/projectswg/common/data/sui/SuiComponent.java b/src/main/java/com/projectswg/common/data/sui/SuiComponent.java index 92642f8..d502c4e 100644 --- a/src/main/java/com/projectswg/common/data/sui/SuiComponent.java +++ b/src/main/java/com/projectswg/common/data/sui/SuiComponent.java @@ -30,7 +30,7 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import com.projectswg.common.encoding.Encodable; import com.projectswg.common.encoding.StringType; import com.projectswg.common.network.NetBuffer; diff --git a/src/main/java/com/projectswg/common/data/swgfile/DataFactory.java b/src/main/java/com/projectswg/common/data/swgfile/DataFactory.java index 4fe7979..2b48e63 100644 --- a/src/main/java/com/projectswg/common/data/swgfile/DataFactory.java +++ b/src/main/java/com/projectswg/common/data/swgfile/DataFactory.java @@ -30,7 +30,7 @@ import java.io.File; import java.io.IOException; import java.nio.channels.ClosedChannelException; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; /** diff --git a/src/main/java/com/projectswg/common/data/swgfile/SWGFile.java b/src/main/java/com/projectswg/common/data/swgfile/SWGFile.java index ac927f0..2b48eb1 100644 --- a/src/main/java/com/projectswg/common/data/swgfile/SWGFile.java +++ b/src/main/java/com/projectswg/common/data/swgfile/SWGFile.java @@ -34,7 +34,7 @@ import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; /** diff --git a/src/main/java/com/projectswg/common/data/swgfile/visitors/CustomizationIDManagerData.java b/src/main/java/com/projectswg/common/data/swgfile/visitors/CustomizationIDManagerData.java index e138b52..9058ec3 100644 --- a/src/main/java/com/projectswg/common/data/swgfile/visitors/CustomizationIDManagerData.java +++ b/src/main/java/com/projectswg/common/data/swgfile/visitors/CustomizationIDManagerData.java @@ -30,7 +30,7 @@ package com.projectswg.common.data.swgfile.visitors; import com.projectswg.common.data.swgfile.ClientData; import com.projectswg.common.data.swgfile.IffNode; import com.projectswg.common.data.swgfile.SWGFile; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/com/projectswg/common/data/swgfile/visitors/DatatableData.java b/src/main/java/com/projectswg/common/data/swgfile/visitors/DatatableData.java index 1f59594..3e51063 100644 --- a/src/main/java/com/projectswg/common/data/swgfile/visitors/DatatableData.java +++ b/src/main/java/com/projectswg/common/data/swgfile/visitors/DatatableData.java @@ -34,7 +34,7 @@ import java.util.Map; import com.projectswg.common.data.swgfile.ClientData; import com.projectswg.common.data.swgfile.IffNode; import com.projectswg.common.data.swgfile.SWGFile; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; public class DatatableData extends ClientData { diff --git a/src/main/java/com/projectswg/common/data/swgfile/visitors/ObjectData.java b/src/main/java/com/projectswg/common/data/swgfile/visitors/ObjectData.java index 5353bc4..2ff057c 100644 --- a/src/main/java/com/projectswg/common/data/swgfile/visitors/ObjectData.java +++ b/src/main/java/com/projectswg/common/data/swgfile/visitors/ObjectData.java @@ -37,7 +37,7 @@ import com.projectswg.common.data.swgfile.ClientData; import com.projectswg.common.data.swgfile.ClientFactory; import com.projectswg.common.data.swgfile.IffNode; import com.projectswg.common.data.swgfile.SWGFile; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; public class ObjectData extends ClientData { diff --git a/src/main/java/com/projectswg/common/data/swgfile/visitors/appearance/AppearanceTemplateList.java b/src/main/java/com/projectswg/common/data/swgfile/visitors/appearance/AppearanceTemplateList.java index 011b58a..40e156e 100644 --- a/src/main/java/com/projectswg/common/data/swgfile/visitors/appearance/AppearanceTemplateList.java +++ b/src/main/java/com/projectswg/common/data/swgfile/visitors/appearance/AppearanceTemplateList.java @@ -35,7 +35,7 @@ import com.projectswg.common.data.swgfile.IffNode; import com.projectswg.common.data.swgfile.SWGFile; import com.projectswg.common.data.swgfile.visitors.appearance.render.RenderData; import com.projectswg.common.data.swgfile.visitors.appearance.render.RenderableData; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; public class AppearanceTemplateList extends ClientData implements RenderableData { diff --git a/src/main/java/com/projectswg/common/data/swgfile/visitors/appearance/DetailedAppearanceTemplateData.java b/src/main/java/com/projectswg/common/data/swgfile/visitors/appearance/DetailedAppearanceTemplateData.java index c4eb067..b013c08 100644 --- a/src/main/java/com/projectswg/common/data/swgfile/visitors/appearance/DetailedAppearanceTemplateData.java +++ b/src/main/java/com/projectswg/common/data/swgfile/visitors/appearance/DetailedAppearanceTemplateData.java @@ -37,7 +37,7 @@ import com.projectswg.common.data.swgfile.SWGFile; import com.projectswg.common.data.swgfile.visitors.appearance.render.RenderData; import com.projectswg.common.data.swgfile.visitors.appearance.render.RenderableData; import com.projectswg.common.data.swgfile.visitors.appearance.render.RenderableDataChild; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; public class DetailedAppearanceTemplateData extends ClientData implements RenderableData { diff --git a/src/main/java/com/projectswg/common/debug/Assert.java b/src/main/java/com/projectswg/common/debug/Assert.java deleted file mode 100644 index a52cba7..0000000 --- a/src/main/java/com/projectswg/common/debug/Assert.java +++ /dev/null @@ -1,112 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.debug; - -public class Assert { - - private static volatile AssertLevel level = AssertLevel.ASSERT; - - public static void setLevel(AssertLevel level) { - Assert.level = level; - } - - public static boolean debug() { - return level != AssertLevel.IGNORE; - } - - public static void notNull(Object o) { - notNull(o, ""); - } - - public static void notNull(Object o, String message) { - if (debug() && o == null) - handle(new NullPointerException(message)); - } - - public static void isNull(Object o) { - isNull(o, ""); - } - - public static void isNull(Object o, String message) { - if (debug() && o != null) - handle(new AssertionException(message)); - } - - public static void test(boolean expr) { - test(expr, ""); - } - - public static void test(boolean expr, String message) { - if (debug() && !expr) - handle(new AssertionException(message)); - } - - public static void fail() { - fail(""); - } - - public static void fail(String message) { - if (debug()) - handle(new AssertionException(message)); - } - - private static void handle(RuntimeException e) { - AssertLevel level = Assert.level; - switch (level) { - case WARN: - warn(e); - break; - case ASSERT: - throw e; - default: - break; - } - } - - private static void warn(Exception e) { - Log.e("Assert Warning:"); - Log.e(e); - } - - public static class AssertionException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public AssertionException(String message) { - super(message); - } - - } - - public enum AssertLevel { - IGNORE, - WARN, - ASSERT - } - -} diff --git a/src/main/java/com/projectswg/common/debug/Log.java b/src/main/java/com/projectswg/common/debug/Log.java deleted file mode 100644 index 130eafe..0000000 --- a/src/main/java/com/projectswg/common/debug/Log.java +++ /dev/null @@ -1,249 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.debug; - -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -public class Log { - - private static Log INSTANCE = null; - - private final List wrappers; - private final Lock logLock; - private final DateTimeFormatter timeFormat; - - private Log() { - this.wrappers = new ArrayList<>(); - this.logLock = new ReentrantLock(true); - this.timeFormat = DateTimeFormatter.ofPattern("dd-MM-yy HH:mm:ss.SSS").withZone(ZoneId.systemDefault()); - } - - private void logAddWrapper(LogWrapper wrapper) { - wrappers.add(wrapper); - } - - private void logClearWrappers() { - wrappers.clear(); - } - - private void logImplementation(LogLevel level, String str, Object ... args) { - String date = timeFormat.format(Instant.now()); - String logStr; - if (args.length == 0) - logStr = date + ' ' + level.getChar() + ": " + str; - else - logStr = date + ' ' + level.getChar() + ": " + String.format(str, args); - for (LogWrapper wrapper : wrappers) { - wrapper.onLog(level, logStr); - } - } - - private void lock() { - logLock.lock(); - } - - private void unlock() { - logLock.unlock(); - } - - private static synchronized final Log getInstance() { - if (INSTANCE == null) - INSTANCE = new Log(); - return INSTANCE; - } - - public static final void addWrapper(LogWrapper wrapper) { - getInstance().logAddWrapper(wrapper); - } - - public static final void clearWrappers() { - getInstance().logClearWrappers(); - } - - /** - * Logs the string to the server log file, formatted to display the log - * severity, time and message. - * @param level the log level of this message between VERBOSE and ASSERT - * @param tag the tag to use for the log - * @param str the format string for the log - * @param args the string format arguments, if specified - */ - public static final void log(LogLevel level, String str, Object ... args) { - try { - getInstance().lock(); - getInstance().logImplementation(level, str, args); - } finally { - getInstance().unlock(); - } - } - - /** - * Logs the string to the server log file, formatted to display the log - * severity as VERBOSE, as well as the time and message. - * @param message the format string for the log - * @param args the string format arguments, if specified - */ - public static final void v(String message, Object ... args) { - log(LogLevel.VERBOSE, message, args); - } - - /** - * Logs the string to the server log file, formatted to display the log - * severity as DEBUG, as well as the time and message. - * @param message the format string for the log - * @param args the string format arguments, if specified - */ - public static final void d(String message, Object ... args) { - log(LogLevel.DEBUG, message, args); - } - - /** - * Logs the string to the server log file, formatted to display the log - * severity as INFO, as well as the time and message. - * @param message the format string for the log - * @param args the string format arguments, if specified - */ - public static final void i(String message, Object ... args) { - log(LogLevel.INFO, message, args); - } - - /** - * Logs the string to the server log file, formatted to display the log - * severity as WARN, as well as the time and message. - * @param message the format string for the log - * @param args the string format arguments, if specified - */ - public static final void w(String message, Object ... args) { - log(LogLevel.WARN, message, args); - } - - - /** - * Logs the exception to the server log file, formatted to display the log - * severity as WARN, as well as the time, and tag. - * @param exception the exception to print - */ - public static final void w(Throwable exception) { - printException(LogLevel.WARN, exception); - } - - /** - * Logs the string to the server log file, formatted to display the log - * severity as ERROR, as well as the time and message. - * @param tag the tag to use for the log - * @param message the format string for the log - * @param args the string format arguments, if specified - */ - public static final void e(String message, Object ... args) { - log(LogLevel.ERROR, message, args); - } - - /** - * Logs the exception to the server log file, formatted to display the log - * severity as ERROR, as well as the time, and tag. - * @param exception the exception to print - */ - public static final void e(Throwable exception) { - printException(LogLevel.ERROR, exception); - } - - /** - * Logs the string to the server log file, formatted to display the log - * severity as ASSERT, as well as the time and message. - * @param message the format string for the log - * @param args the string format arguments, if specified - */ - public static final void a(String message, Object ... args) { - log(LogLevel.ASSERT, message, args); - } - - /** - * Logs the exception to the server log file, formatted to display the log - * severity as ASSERT, as well as the time, and tag. - * @param exception the exception to print - */ - public static final void a(Throwable exception) { - printException(LogLevel.ASSERT, exception); - } - - private static final void printException(LogLevel level, Throwable exception) { - Log instance = getInstance(); - try { - instance.lock(); - printException(level, exception, 0); - } finally { - instance.unlock(); - } - } - - private static final void printException(LogLevel level, Throwable exception, int depth) { - Log instance = getInstance(); - String depthString = createExceptionDepthString(depth); - String header1 = String.format("Exception in thread \"%s\" %s: %s", Thread.currentThread().getName(), exception.getClass().getName(), exception.getMessage()); - String header2 = String.format("Caused by: %s: %s", exception.getClass().getCanonicalName(), exception.getMessage()); - StackTraceElement [] elements = exception.getStackTrace(); - instance.logImplementation(level, depthString+header1); - instance.logImplementation(level, depthString+header2); - for (StackTraceElement e : elements) { - instance.logImplementation(level, depthString + " " + e.toString()); - } - if (exception.getCause() != null) - printException(level, exception.getCause(), depth+1); - } - - private static String createExceptionDepthString(int depth) { - StringBuilder str = new StringBuilder(depth*2); - for (int i = 0; i < depth; i++) - str.append(" "); - return str.toString(); - } - - public static enum LogLevel { - VERBOSE ('V'), - DEBUG ('D'), - INFO ('I'), - WARN ('W'), - ERROR ('E'), - ASSERT ('A'); - - private char c; - - LogLevel(char c) { - this.c = c; - } - - public char getChar() { return c; } - } - -} diff --git a/src/main/java/com/projectswg/common/debug/LogWrapper.java b/src/main/java/com/projectswg/common/debug/LogWrapper.java deleted file mode 100644 index 52d0328..0000000 --- a/src/main/java/com/projectswg/common/debug/LogWrapper.java +++ /dev/null @@ -1,36 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.debug; - -import com.projectswg.common.debug.Log.LogLevel; - -public interface LogWrapper { - - void onLog(LogLevel level, String str); - -} diff --git a/src/main/java/com/projectswg/common/debug/ThreadPrinter.java b/src/main/java/com/projectswg/common/debug/ThreadPrinter.java deleted file mode 100644 index c7397ff..0000000 --- a/src/main/java/com/projectswg/common/debug/ThreadPrinter.java +++ /dev/null @@ -1,61 +0,0 @@ -/*********************************************************************************** - * Copyright (c) 2018 /// Project SWG /// www.projectswg.com * - * * - * ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * - * July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * - * Our goal is to create an emulator which will provide a server for players to * - * continue playing a game similar to the one they used to play. We are basing * - * it on the final publish of the game prior to end-game events. * - * * - * This file is part of Holocore. * - * * - * --------------------------------------------------------------------------------* - * * - * Holocore is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * Holocore is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with Holocore. If not, see . * - * * - ***********************************************************************************/ -package com.projectswg.common.debug; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -public class ThreadPrinter { - - public static void printActiveThreads() { - ThreadGroup threadGroup = Thread.currentThread().getThreadGroup(); - int threadCount = threadGroup.activeCount(); - Thread[] threadsRaw = new Thread[threadCount]; - threadCount = threadGroup.enumerate(threadsRaw); - List threads = Arrays.stream(threadsRaw, 0, threadCount).filter(t -> t.getState() != Thread.State.TERMINATED).collect(Collectors.toList()); - int maxLength = threads.stream().mapToInt(t -> t.getName().length()).max().orElse(4); - if (maxLength < 4) - maxLength = 4; - - Log.w("Active Threads: %d", threads.size()); - Log.w("+-%s---%s-+", createRepeatingDash(maxLength), createRepeatingDash(13)); - Log.w("| %-" + maxLength + "s | %-13s |", "Name", "State"); - Log.w("+-%s-+-%s-+", createRepeatingDash(maxLength), createRepeatingDash(13)); - for (Thread t : threads) { - Log.w("| %-" + maxLength + "s | %-13s |", t.getName(), t.getState()); - } - Log.w("+-%s---%s-+", createRepeatingDash(maxLength), createRepeatingDash(13)); - } - - private static String createRepeatingDash(int count) { - return String.join("", Collections.nCopies(count, "-")); - } - -} diff --git a/src/main/java/com/projectswg/common/debug/log_wrapper/ConsoleLogWrapper.java b/src/main/java/com/projectswg/common/debug/log_wrapper/ConsoleLogWrapper.java deleted file mode 100644 index 596f7b4..0000000 --- a/src/main/java/com/projectswg/common/debug/log_wrapper/ConsoleLogWrapper.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.projectswg.common.debug.log_wrapper; - -import com.projectswg.common.debug.Log.LogLevel; -import com.projectswg.common.debug.LogWrapper; - -public class ConsoleLogWrapper implements LogWrapper { - - private final LogLevel level; - - public ConsoleLogWrapper(LogLevel level) { - this.level = level; - } - - @Override - public void onLog(LogLevel level, String str) { - if (this.level.compareTo(level) > 0) - return; - if (level.compareTo(LogLevel.WARN) >= 0) - System.err.println(str); - else - System.out.println(str); - } - -} diff --git a/src/main/java/com/projectswg/common/debug/log_wrapper/FileLogWrapper.java b/src/main/java/com/projectswg/common/debug/log_wrapper/FileLogWrapper.java deleted file mode 100644 index ae4686c..0000000 --- a/src/main/java/com/projectswg/common/debug/log_wrapper/FileLogWrapper.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.projectswg.common.debug.log_wrapper; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.StandardCharsets; - -import com.projectswg.common.debug.Log.LogLevel; -import com.projectswg.common.debug.LogWrapper; - -public class FileLogWrapper implements LogWrapper { - - private final BufferedWriter writer; - - public FileLogWrapper(File file) { - try { - writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8)); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public void onLog(LogLevel level, String str) { - try { - writer.write(str); - writer.newLine(); - writer.flush(); - } catch (IOException e) { - e.printStackTrace(); - } - } - -} diff --git a/src/main/java/com/projectswg/common/encoding/Encoder.java b/src/main/java/com/projectswg/common/encoding/Encoder.java index eb1263c..0c1c73c 100644 --- a/src/main/java/com/projectswg/common/encoding/Encoder.java +++ b/src/main/java/com/projectswg/common/encoding/Encoder.java @@ -31,7 +31,7 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.Charset; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; public class Encoder { diff --git a/src/main/java/com/projectswg/common/network/NetBuffer.java b/src/main/java/com/projectswg/common/network/NetBuffer.java index aa0d102..1199bfa 100644 --- a/src/main/java/com/projectswg/common/network/NetBuffer.java +++ b/src/main/java/com/projectswg/common/network/NetBuffer.java @@ -35,7 +35,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import com.projectswg.common.encoding.Encodable; import com.projectswg.common.encoding.StringType; @@ -415,4 +415,4 @@ public class NetBuffer { return ret; } -} \ No newline at end of file +} diff --git a/src/main/java/com/projectswg/common/network/NetworkProtocol.java b/src/main/java/com/projectswg/common/network/NetworkProtocol.java index b1f0cb6..789e090 100644 --- a/src/main/java/com/projectswg/common/network/NetworkProtocol.java +++ b/src/main/java/com/projectswg/common/network/NetworkProtocol.java @@ -27,7 +27,7 @@ ***********************************************************************************/ package com.projectswg.common.network; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import com.projectswg.common.network.packets.PacketType; import com.projectswg.common.network.packets.SWGPacket; import com.projectswg.common.network.packets.swg.zone.object_controller.ObjectController; diff --git a/src/main/java/com/projectswg/common/network/TCPSecureSocket.java b/src/main/java/com/projectswg/common/network/TCPSecureSocket.java deleted file mode 100644 index 1c816e8..0000000 --- a/src/main/java/com/projectswg/common/network/TCPSecureSocket.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.projectswg.common.network; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.UnrecoverableKeyException; -import java.security.cert.CertificateException; - -public class TCPSecureSocket extends TCPSocket { - - private final SecureSocketFactory socketFactory; - - public TCPSecureSocket(InetSocketAddress address, int bufferSize) { - super(address, bufferSize); - this.socketFactory = new SecureSocketFactory(); - } - - /** - * Sets up the encryption mechanism - * @param keystoreFile the keystore file - * @param password the password for the keystore - * @throws KeyStoreException if KeyManagerFactory.init or TrustManagerFactory.init fails - * @throws NoSuchAlgorithmException if the algorithm for the keystore or key manager could not be found - * @throws CertificateException if any of the certificates in the keystore could not be loaded - * @throws FileNotFoundException if the keystore file does not exist - * @throws IOException if there is an I/O or format problem with the keystore data, if a password is required but not given, or if the given password was incorrect. If the error is due to a wrong password, the cause of the IOException should be an UnrecoverableKeyException - * @throws KeyManagementException if SSLContext.init fails - * @throws UnrecoverableKeyException if the key cannot be recovered (e.g. the given password is wrong). - */ - public void setupEncryption(File keystoreFile, char [] password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException, KeyManagementException, UnrecoverableKeyException { - socketFactory.load(keystoreFile, password); - } - - @Override - public Socket createSocket() throws IOException { - return socketFactory.createSocket(); - } - -} diff --git a/src/main/java/com/projectswg/common/network/TCPServer.java b/src/main/java/com/projectswg/common/network/TCPServer.java deleted file mode 100644 index 3248e1c..0000000 --- a/src/main/java/com/projectswg/common/network/TCPServer.java +++ /dev/null @@ -1,306 +0,0 @@ -/*********************************************************************************** - * Copyright (c) 2017 /// Project SWG /// www.projectswg.com * - * * - * ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * - * July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * - * Our goal is to create an emulator which will provide a server for players to * - * continue playing a game similar to the one they used to play. We are basing * - * it on the final publish of the game prior to end-game events. * - * * - * This file is part of Holocore. * - * * - * --------------------------------------------------------------------------------* - * * - * Holocore is free software: you can redistribute it and/or modify * - * it under the terms of the GNU Affero General Public License as * - * published by the Free Software Foundation, either version 3 of the * - * License, or (at your option) any later version. * - * * - * Holocore is distributed in the hope that it will be useful, * - * but WITHOUT ANY WARRANTY; without even the implied warranty of * - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * - * GNU Affero General Public License for more details. * - * * - * You should have received a copy of the GNU Affero General Public License * - * along with Holocore. If not, see . * - * * - ***********************************************************************************/ -package com.projectswg.common.network; - -import com.projectswg.common.concurrency.PswgBasicThread; -import com.projectswg.common.concurrency.PswgThreadPool; -import com.projectswg.common.debug.Log; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.nio.Buffer; -import java.nio.ByteBuffer; -import java.nio.channels.*; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Function; - -public class TCPServer { - - private final PswgThreadPool callbackThread; - private final Map channels; - private final Map sessionIdToChannel; - - private final PswgBasicThread listener; - private final AtomicBoolean running; - private final InetSocketAddress addr; - private final Function sessionCreator; - private ServerSocketChannel channel; - - private final ByteBuffer buffer; - private final ByteArrayOutputStream bufferStream; - private final WritableByteChannel byteBufferChannel; - - public TCPServer(int port, int bufferSize, Function sessionCreator) { - this(new InetSocketAddress((InetAddress) null, port), bufferSize, sessionCreator); - } - - public TCPServer(InetSocketAddress addr, int bufferSize, Function sessionCreator) { - this.callbackThread = new PswgThreadPool(false, 1, "tcpserver-" + addr.getPort()); - this.channels = new ConcurrentHashMap<>(); - this.sessionIdToChannel = new ConcurrentHashMap<>(); - this.listener = new PswgBasicThread("tcpserver-listener-" + addr.getPort(), this::runListener); - this.running = new AtomicBoolean(false); - this.addr = addr; - this.channel = null; - this.sessionCreator = sessionCreator; - this.buffer = ByteBuffer.allocateDirect(bufferSize); - this.bufferStream = new ByteArrayOutputStream(bufferSize); - this.byteBufferChannel = Channels.newChannel(bufferStream); - } - - public int getPort() { - return channel.socket().getLocalPort(); - } - - public void bind() throws IOException { - assert !running.get() : "TCPServer is already running"; - if (running.getAndSet(true)) - return; - callbackThread.start(); - channel = ServerSocketChannel.open(); - channel.bind(addr, 50); - channel.configureBlocking(false); - listener.start(); - } - - public void disconnect(long sessionId) { - T session = sessionIdToChannel.remove(sessionId); - if (session == null) { - Log.w("TCPServer - unknown session id in disconnect: %d", sessionId); - return; - } - - disconnect(session.getChannel()); - } - - public void disconnect(T session) { - disconnect(Objects.requireNonNull(session, "session").getChannel()); - } - - public void disconnect(SocketChannel sc) { - T session = channels.remove(sc); - if (session == null) { - Log.w("TCPServer - unknown channel in disconnect: %d", sc); - return; - } - sessionIdToChannel.remove(session.getSessionId()); - - session.close(); - callbackThread.execute(session::onDisconnected); - } - - public T getSession(long sessionId) { - return sessionIdToChannel.get(sessionId); - } - - public T getSession(SocketChannel sc) { - return channels.get(sc); - } - - public void close() { - assert running.get() : "TCPServer isn't running"; - if (!running.getAndSet(false)) - return; - callbackThread.stop(false); - listener.stop(true); - safeClose(channel); - } - - private void runListener() { - try (Selector selector = Selector.open()) { - channel.register(selector, SelectionKey.OP_ACCEPT); - while (running.get()) { - selector.select(); - accept(selector); - selector.selectedKeys().forEach(this::read); - } - } catch (IOException e) { - Log.e(e); - } - } - - private void accept(Selector selector) { - try { - while (channel.isOpen()) { - SocketChannel sc = channel.accept(); - if (sc == null) - return; - sc.configureBlocking(false); - sc.register(selector, SelectionKey.OP_READ); - acceptConnection(sc); - } - } catch (ClosedChannelException e) { - // Ignored - } catch (Throwable t) { - Log.w("TCPServer - IOException in accept(): %s", t.getMessage()); - } - } - - private void acceptConnection(SocketChannel sc) { - T session = sessionCreator.apply(sc); - if (session == null) { - Log.w("Session creator for TCPServer-%d created a null session!", addr.getPort()); - safeClose(sc); - return; - } - if (session.getChannel() != sc) { - Log.w("Session creator for TCPServer-%d created a session with an invalid channel!", addr.getPort()); - safeClose(sc); - return; - } - channels.put(sc, session); - sessionIdToChannel.put(session.getSessionId(), session); - callbackThread.execute(session::onConnected); - } - - private void read(SelectionKey key) { - SelectableChannel selectableChannel = key.channel(); - if (selectableChannel == channel) - return; - SocketChannel sc = (SocketChannel) selectableChannel; - T session = getSession(sc); - if (session == null || !sc.isConnected()) { - invalidate(sc, key); - return; - } - try { - bufferStream.reset(); - int n = 1; - while (n > 0) { - ((Buffer) buffer).clear(); - n = sc.read(buffer); - ((Buffer) buffer).flip(); - byteBufferChannel.write(buffer); - } - if (bufferStream.size() > 0) { - byte[] data = bufferStream.toByteArray(); - callbackThread.execute(() -> session.onIncomingData(data)); - } - if (n < 0) { - invalidate(sc, key); - } - } catch (ClosedChannelException e) { - // Ignored - } catch (Throwable t) { - Log.w("TCPServer - %s in read(): %s", t.getClass(), t.getMessage()); - invalidate(sc, key); - } - } - - private void invalidate(SocketChannel sc, SelectionKey key) { - key.cancel(); - disconnect(sc); - } - - private static void safeClose(Channel c) { - try { - c.close(); - } catch (IOException e) { - // Ignored - as long as it's closed - } - } - - public abstract static class TCPSession { - - private static final AtomicLong GLOBAL_SESSION_ID = new AtomicLong(0); - - private final SocketChannel sc; - private final SocketAddress addr; - private final long sessionId; - - protected TCPSession(SocketChannel sc) { - this.sc = Objects.requireNonNull(sc, "socket"); - this.sessionId = GLOBAL_SESSION_ID.incrementAndGet(); - - SocketAddress addr; - try { - addr = sc.getRemoteAddress(); - } catch (IOException e) { - addr = null; - } - this.addr = addr; - } - - protected void onConnected() { - - } - - protected void onDisconnected() { - - } - - /** - * Returns a globally unique session id for this particular connection - * @return the unique session id - */ - protected final long getSessionId() { - return sessionId; - } - - /** - * Returns the socket channel associated with this session - * @return the socket channel - */ - protected final SocketChannel getChannel() { - return sc; - } - - /** - * Returns the remote address that this socket is/was connected to - * @return the remote socket address - */ - @SuppressWarnings("unused") // open for subclass to use - protected final SocketAddress getRemoteAddress() { - return addr; - } - - @SuppressWarnings("unused") // open for subclass to use - protected void writeToChannel(ByteBuffer data) throws IOException { - sc.write(data); - } - - @SuppressWarnings("unused") // open for subclass to use - protected void writeToChannel(byte [] data) throws IOException { - sc.write(ByteBuffer.wrap(data)); - } - - protected void close() { - safeClose(sc); - } - - protected abstract void onIncomingData(byte[] data); - } - -} diff --git a/src/main/java/com/projectswg/common/network/TCPSocket.java b/src/main/java/com/projectswg/common/network/TCPSocket.java deleted file mode 100644 index 359021e..0000000 --- a/src/main/java/com/projectswg/common/network/TCPSocket.java +++ /dev/null @@ -1,309 +0,0 @@ -/*********************************************************************************** -* Copyright (c) 2015 /// Project SWG /// www.projectswg.com * -* * -* ProjectSWG is the first NGE emulator for Star Wars Galaxies founded on * -* July 7th, 2011 after SOE announced the official shutdown of Star Wars Galaxies. * -* Our goal is to create an emulator which will provide a server for players to * -* continue playing a game similar to the one they used to play. We are basing * -* it on the final publish of the game prior to end-game events. * -* * -* This file is part of Holocore. * -* * -* -------------------------------------------------------------------------------- * -* * -* Holocore is free software: you can redistribute it and/or modify * -* it under the terms of the GNU Affero General Public License as * -* published by the Free Software Foundation, either version 3 of the * -* License, or (at your option) any later version. * -* * -* Holocore is distributed in the hope that it will be useful, * -* but WITHOUT ANY WARRANTY; without even the implied warranty of * -* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * -* GNU Affero General Public License for more details. * -* * -* You should have received a copy of the GNU Affero General Public License * -* along with Holocore. If not, see . * -* * -***********************************************************************************/ -package com.projectswg.common.network; - -import java.io.EOFException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.nio.ByteBuffer; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import com.projectswg.common.callback.CallbackManager; -import com.projectswg.common.concurrency.Delay; -import com.projectswg.common.debug.Assert; -import com.projectswg.common.debug.Log; - -public class TCPSocket { - - private final CallbackManager callbackManager; - private final TCPSocketListener listener; - private final AtomicReference address; - private final AtomicReference state; - private final Object stateMutex; - private final int bufferSize; - private Socket socket; - private InputStream socketInputStream; - private OutputStream socketOutputStream; - - public TCPSocket(InetSocketAddress address, int bufferSize) { - this.callbackManager = new CallbackManager<>("tcpsocket-"+address, 1); - this.listener = new TCPSocketListener(); - this.address = new AtomicReference<>(address); - this.state = new AtomicReference<>(SocketState.CLOSED); - this.stateMutex = new Object(); - this.bufferSize = bufferSize; - - this.socket = null; - this.socketInputStream = null; - this.socketOutputStream = null; - } - - public TCPSocket(int bufferSize) { - this(null, bufferSize); - } - - public TCPSocket() { - this(1024); - } - - public int getBufferSize() { - return bufferSize; - } - - public InetSocketAddress getRemoteAddress() { - return address.get(); - } - - public void setRemoteAddress(InetSocketAddress address) { - this.address.set(address); - } - - public Socket getSocket() { - return socket; - } - - public boolean isAlive() { - synchronized (stateLock()) { - return socket != null && listener.isAlive(); - } - } - - public boolean isConnected() { - synchronized (stateLock()) { - return socket != null && socket.isConnected(); - } - } - - public void setCallback(TCPSocketCallback callback) { - callbackManager.setCallback(callback); - } - - public void removeCallback() { - callbackManager.clearCallbacks(); - } - - public void createConnection() throws IOException { - synchronized (stateLock()) { - checkAndSetState(SocketState.CLOSED, SocketState.CREATED); - socket = createSocket(); - } - } - - public void startConnection() throws IOException { - synchronized (stateLock()) { - try { - checkAndSetState(SocketState.CREATED, SocketState.CONNECTING); - socket.connect(getRemoteAddress()); - socketInputStream = socket.getInputStream(); - socketOutputStream = socket.getOutputStream(); - } catch (IOException e) { - checkAndSetState(SocketState.CONNECTING, SocketState.CLOSED); - socket = null; - socketInputStream = null; - socketOutputStream = null; - throw e; - } - - callbackManager.start(); - listener.start(); - checkAndSetState(SocketState.CONNECTING, SocketState.CONNECTED); - callbackManager.callOnEach((callback) -> callback.onConnected(this)); - } - } - - public void connect() throws IOException { - createConnection(); - startConnection(); - } - - public boolean disconnect() { - synchronized (stateLock()) { - if (socket == null) - return true; - try { - checkAndSetState(SocketState.CONNECTED, SocketState.CLOSED); - socket.close(); - socket = null; - socketInputStream = null; - socketOutputStream = null; - - if (listener.isAlive()) { - listener.stop(); - listener.awaitTermination(); - } - - if (callbackManager.isRunning()) { - callbackManager.callOnEach((callback) -> callback.onDisconnected(this)); - callbackManager.stop(); - } - return true; - } catch (IOException e) { - Log.e(e); - } - return false; - } - } - - public boolean send(NetBuffer data) { - return send(data.array(), data.position(), data.remaining()); - } - - public boolean send(ByteBuffer data) { - return send(data.array(), data.position(), data.remaining()); - } - - public boolean send(byte [] data) { - return send(data, 0, data.length); - } - - public boolean send(byte [] data, int offset, int length) { - synchronized (stateLock()) { - try { - if (socket == null) - return false; - - if (length > 0) - socketOutputStream.write(data, offset, length); - - return true; - } catch (IOException e) { - Log.e(e); - } - return false; - } - } - - protected Socket createSocket() throws IOException { - return new Socket(); - } - - protected final Object stateLock() { - return stateMutex; - } - - /** - * Checks the current state to see if it matches the expected, and if so, changes it to the new state. If not, it fails the assertion - * @param expected the expected state - * @param state the new state - */ - private void checkAndSetState(SocketState expected, SocketState state) { - Assert.notNull(expected, "Expected state cannot be null!"); - Assert.notNull(state, "New state cannot be null!"); - Assert.test(this.state.compareAndSet(expected, state), "Failed to set state! Was: " + this.state.get() + " Expected: " + expected + " Update: " + state); - } - - public interface TCPSocketCallback { - void onConnected(TCPSocket socket); - void onDisconnected(TCPSocket socket); - void onIncomingData(TCPSocket socket, byte [] data); - } - - private enum SocketState { - CLOSED, - CREATED, - CONNECTING, - CONNECTED - } - - private class TCPSocketListener implements Runnable { - - private final AtomicBoolean running; - private final AtomicBoolean alive; - - private Thread thread; - - public TCPSocketListener() { - this.running = new AtomicBoolean(false); - this.alive = new AtomicBoolean(false); - this.thread = null; - } - - public void start() { - Assert.test(!running.get(), "Cannot start listener! Already started!"); - Assert.isNull(thread, "Cannot start listener! Already started!"); - thread = new Thread(this, "TCPServer Port#" + getRemoteAddress().getPort()); - running.set(true); - thread.start(); - } - - public void stop() { - Assert.test(running.get(), "Cannot stop listener! Already stopped!"); - Assert.notNull(thread, "Cannot stop listener! Already stopped!"); - running.set(false); - if (thread != null) - thread.interrupt(); - thread = null; - } - - public void awaitTermination() { - while (isAlive()) { - if (!Delay.sleepMicro(5)) - break; - } - } - - public boolean isAlive() { - return alive.get(); - } - - @Override - public void run() { - try { - alive.set(true); - InputStream input = TCPSocket.this.socketInputStream; - byte [] buffer = new byte[TCPSocket.this.bufferSize]; - while (running.get()) { - waitIncoming(input, buffer); - } - } catch (Throwable t) { - - } finally { - running.set(false); - alive.set(false); - thread = null; - disconnect(); - } - } - - private void waitIncoming(InputStream input, byte [] buffer) throws IOException { - int n = input.read(buffer); - if (n == 0) - return; - if (n < 0) - throw new EOFException(); - byte [] data = new byte[n]; - System.arraycopy(buffer, 0, data, 0, n); - callbackManager.callOnEach((callback) -> callback.onIncomingData(TCPSocket.this, data)); - } - - } -} diff --git a/src/main/java/com/projectswg/common/network/packets/PacketSerializationException.java b/src/main/java/com/projectswg/common/network/packets/PacketSerializationException.java new file mode 100644 index 0000000..6bd5b58 --- /dev/null +++ b/src/main/java/com/projectswg/common/network/packets/PacketSerializationException.java @@ -0,0 +1,37 @@ +/*********************************************************************************** + * Copyright (C) 2018 /// Project SWG /// www.projectswg.com * + * * + * This file is part of the ProjectSWG Launcher. * + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU Affero General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU Affero General Public License for more details. * + * * + * You should have received a copy of the GNU Affero General Public License * + * along with this program. If not, see . * + * * + ***********************************************************************************/ + +package com.projectswg.common.network.packets; + +public class PacketSerializationException extends RuntimeException { + + public PacketSerializationException() { + + } + + public PacketSerializationException(String message) { + super(message); + } + + public PacketSerializationException(Object packet, String constraint) { + this("Packet " + packet.getClass().getName() + " violated constraint [" + constraint + "]"); + } + +} diff --git a/src/main/java/com/projectswg/common/network/packets/PacketType.java b/src/main/java/com/projectswg/common/network/packets/PacketType.java index 6d86423..decbfce 100644 --- a/src/main/java/com/projectswg/common/network/packets/PacketType.java +++ b/src/main/java/com/projectswg/common/network/packets/PacketType.java @@ -28,7 +28,7 @@ package com.projectswg.common.network.packets; import com.projectswg.common.data.EnumLookup; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import com.projectswg.common.network.packets.swg.ErrorMessage; import com.projectswg.common.network.packets.swg.ServerUnixEpochTime; import com.projectswg.common.network.packets.swg.admin.AdminShutdownServer; diff --git a/src/main/java/com/projectswg/common/network/packets/SWGPacket.java b/src/main/java/com/projectswg/common/network/packets/SWGPacket.java index eec62fb..388da72 100644 --- a/src/main/java/com/projectswg/common/network/packets/SWGPacket.java +++ b/src/main/java/com/projectswg/common/network/packets/SWGPacket.java @@ -3,7 +3,7 @@ package com.projectswg.common.network.packets; import java.net.SocketAddress; import com.projectswg.common.data.CRC; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import com.projectswg.common.network.NetBuffer; public abstract class SWGPacket { @@ -52,6 +52,11 @@ public abstract class SWGPacket { public abstract void decode(NetBuffer data); public abstract NetBuffer encode(); + protected void packetAssert(boolean condition, String constraint) { + if (!condition) + throw new PacketSerializationException(this, constraint); + } + public static int getCrc(String string) { return CRC.getCrc(string); } diff --git a/src/main/java/com/projectswg/common/network/packets/swg/zone/SceneCreateObjectByCrc.java b/src/main/java/com/projectswg/common/network/packets/swg/zone/SceneCreateObjectByCrc.java index 06d1ee7..81ed0f1 100644 --- a/src/main/java/com/projectswg/common/network/packets/swg/zone/SceneCreateObjectByCrc.java +++ b/src/main/java/com/projectswg/common/network/packets/swg/zone/SceneCreateObjectByCrc.java @@ -28,7 +28,6 @@ package com.projectswg.common.network.packets.swg.zone; import com.projectswg.common.data.location.Location; -import com.projectswg.common.debug.Assert; import com.projectswg.common.network.NetBuffer; import com.projectswg.common.network.packets.SWGPacket; @@ -60,12 +59,12 @@ public class SceneCreateObjectByCrc extends SWGPacket { location = data.getEncodable(Location.class); objCrc = data.getInt(); hyperspace = data.getBoolean(); + verifyInternals(); } @Override public NetBuffer encode() { - verifyObjectId(); - verifyLocation(); + verifyInternals(); NetBuffer data = NetBuffer.allocate(47); data.addShort(5); data.addInt(CRC); @@ -77,13 +76,14 @@ public class SceneCreateObjectByCrc extends SWGPacket { } public void setObjectId(long objId) { + if (objId == 0) + throw new IllegalArgumentException("Object ID cannot be 0!"); this.objId = objId; - verifyObjectId(); } public void setLocation(Location l) { this.location = new Location(l); - verifyLocation(); + verifyInternals(); } public void setObjectCrc(int objCrc) { @@ -110,19 +110,16 @@ public class SceneCreateObjectByCrc extends SWGPacket { return hyperspace; } - private void verifyObjectId() { - Assert.test(objId != 0, "Object ID cannot be 0!"); - } - - private void verifyLocation() { - Assert.notNull(location); - Assert.test(!Double.isNaN(location.getX()), "X Coordinate is NaN!"); - Assert.test(!Double.isNaN(location.getY()), "Y Coordinate is NaN!"); - Assert.test(!Double.isNaN(location.getZ()), "Z Coordinate is NaN!"); - Assert.test(!Double.isNaN(location.getOrientationX()), "X Orientation is NaN!"); - Assert.test(!Double.isNaN(location.getOrientationY()), "Y Orientation is NaN!"); - Assert.test(!Double.isNaN(location.getOrientationZ()), "Z Orientation is NaN!"); - Assert.test(!Double.isNaN(location.getOrientationW()), "W Orientation is NaN!"); + private void verifyInternals() { + packetAssert(objId != 0, "Object ID cannot be 0!"); + packetAssert(location != null, "location cannot be null"); + packetAssert(!Double.isNaN(location.getX()), "X Coordinate is NaN!"); + packetAssert(!Double.isNaN(location.getY()), "Y Coordinate is NaN!"); + packetAssert(!Double.isNaN(location.getZ()), "Z Coordinate is NaN!"); + packetAssert(!Double.isNaN(location.getOrientationX()), "X Orientation is NaN!"); + packetAssert(!Double.isNaN(location.getOrientationY()), "Y Orientation is NaN!"); + packetAssert(!Double.isNaN(location.getOrientationZ()), "Z Orientation is NaN!"); + packetAssert(!Double.isNaN(location.getOrientationW()), "W Orientation is NaN!"); } } diff --git a/src/main/java/com/projectswg/common/network/packets/swg/zone/object_controller/ObjectController.java b/src/main/java/com/projectswg/common/network/packets/swg/zone/object_controller/ObjectController.java index c2e5353..fb05f27 100644 --- a/src/main/java/com/projectswg/common/network/packets/swg/zone/object_controller/ObjectController.java +++ b/src/main/java/com/projectswg/common/network/packets/swg/zone/object_controller/ObjectController.java @@ -27,7 +27,7 @@ ***********************************************************************************/ package com.projectswg.common.network.packets.swg.zone.object_controller; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import com.projectswg.common.network.NetBuffer; import com.projectswg.common.network.packets.SWGPacket; import com.projectswg.common.network.packets.swg.zone.object_controller.combat.CombatAction; diff --git a/src/main/java/com/projectswg/common/network/packets/swg/zone/resource/ResourceWeight.java b/src/main/java/com/projectswg/common/network/packets/swg/zone/resource/ResourceWeight.java index f82ee3b..adb32cf 100644 --- a/src/main/java/com/projectswg/common/network/packets/swg/zone/resource/ResourceWeight.java +++ b/src/main/java/com/projectswg/common/network/packets/swg/zone/resource/ResourceWeight.java @@ -27,16 +27,15 @@ ***********************************************************************************/ package com.projectswg.common.network.packets.swg.zone.resource; +import com.projectswg.common.network.NetBuffer; +import com.projectswg.common.network.packets.swg.zone.object_controller.ObjectController; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import com.projectswg.common.debug.Assert; -import com.projectswg.common.network.NetBuffer; -import com.projectswg.common.network.packets.swg.zone.object_controller.ObjectController; - public class ResourceWeight extends ObjectController { public static final int CRC = 0x0207; @@ -60,7 +59,7 @@ public class ResourceWeight extends ObjectController { int count = data.getByte(); decodeWeights(data, attributes, count); decodeWeights(data, resourceMaxWeights, count); - Assert.test(attributes.size() == resourceMaxWeights.size()); + packetAssert(attributes.size() == resourceMaxWeights.size(), "attributes must equal resource weight size"); } @Override @@ -70,7 +69,7 @@ public class ResourceWeight extends ObjectController { len += 3 + weights.size(); for (List weights : resourceMaxWeights.values()) len += 3 + weights.size(); - Assert.test(attributes.size() == resourceMaxWeights.size()); + packetAssert(attributes.size() == resourceMaxWeights.size(), "attributes must equal resource weight size"); NetBuffer data = NetBuffer.allocate(len); encodeHeader(data); encodeWeights(data, attributes); diff --git a/src/main/java/com/projectswg/common/process/ArgumentParser.java b/src/main/java/com/projectswg/common/process/ArgumentParser.java index 21928d7..0df8c68 100644 --- a/src/main/java/com/projectswg/common/process/ArgumentParser.java +++ b/src/main/java/com/projectswg/common/process/ArgumentParser.java @@ -1,6 +1,6 @@ package com.projectswg.common.process; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/com/projectswg/common/process/JarProcessBuilder.java b/src/main/java/com/projectswg/common/process/JarProcessBuilder.java index 1cbcf23..064130d 100644 --- a/src/main/java/com/projectswg/common/process/JarProcessBuilder.java +++ b/src/main/java/com/projectswg/common/process/JarProcessBuilder.java @@ -1,7 +1,5 @@ package com.projectswg.common.process; -import com.projectswg.common.debug.Assert; - import java.io.File; import java.io.IOException; import java.lang.ProcessBuilder.Redirect; @@ -40,19 +38,22 @@ public class JarProcessBuilder { } public JarProcessBuilder setMinMemory(long minMemory, MemoryUnit unit) { - Assert.test(unit == MemoryUnit.KILOBYTES || unit == MemoryUnit.MEGABYTES || unit == MemoryUnit.GIGABYTES, "Unsupported memory unit!"); + if (unit != MemoryUnit.KILOBYTES && unit != MemoryUnit.MEGABYTES && unit != MemoryUnit.GIGABYTES) + throw new IllegalArgumentException("Unsupported memory unit!"); this.minMemory = unit.getBytes(minMemory); return this; } public JarProcessBuilder setMaxMemory(long maxMemory, MemoryUnit unit) { - Assert.test(unit == MemoryUnit.KILOBYTES || unit == MemoryUnit.MEGABYTES || unit == MemoryUnit.GIGABYTES, "Unsupported memory unit!"); + if (unit != MemoryUnit.KILOBYTES && unit != MemoryUnit.MEGABYTES && unit != MemoryUnit.GIGABYTES) + throw new IllegalArgumentException("Unsupported memory unit!"); this.maxMemory = unit.getBytes(maxMemory); return this; } public JarProcessBuilder setMemory(long minMemory, long maxMemory, MemoryUnit unit) { - Assert.test(unit == MemoryUnit.KILOBYTES || unit == MemoryUnit.MEGABYTES || unit == MemoryUnit.GIGABYTES, "Unsupported memory unit!"); + if (unit != MemoryUnit.KILOBYTES && unit != MemoryUnit.MEGABYTES && unit != MemoryUnit.GIGABYTES) + throw new IllegalArgumentException("Unsupported memory unit!"); this.minMemory = unit.getBytes(minMemory); this.maxMemory = unit.getBytes(maxMemory); return this; diff --git a/src/main/java/com/projectswg/common/utilities/TimeUtilities.java b/src/main/java/com/projectswg/common/utilities/TimeUtilities.java index 791df54..bf5ce86 100644 --- a/src/main/java/com/projectswg/common/utilities/TimeUtilities.java +++ b/src/main/java/com/projectswg/common/utilities/TimeUtilities.java @@ -34,7 +34,7 @@ import java.util.Locale; import java.util.TimeZone; import java.util.concurrent.TimeUnit; -import com.projectswg.common.debug.Log; +import me.joshlarson.jlcommon.log.Log; public class TimeUtilities {