2019-07-11 16:59:21 +00:00
From 5b14068add26b91b006e51d745d5de6118e4c154 Mon Sep 17 00:00:00 2001
2016-01-09 06:32:38 +00:00
From: Aikar <aikar@aikar.co>
2016-02-29 23:09:49 +00:00
Date: Mon, 29 Feb 2016 18:48:17 -0600
2016-01-09 06:32:38 +00:00
Subject: [PATCH] Timings v2
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/FullServerTickHandler.java b/src/main/java/co/aikar/timings/FullServerTickHandler.java
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..64531fcc
2016-01-10 07:33:27 +00:00
--- /dev/null
+++ b/src/main/java/co/aikar/timings/FullServerTickHandler.java
2019-03-24 21:47:23 +00:00
@@ -0,0 +1,84 @@
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
+
+import static co.aikar.timings.TimingsManager.*;
+
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+
2016-01-10 07:33:27 +00:00
+public class FullServerTickHandler extends TimingHandler {
2018-08-31 00:43:15 +00:00
+ private static final TimingIdentifier IDENTITY = new TimingIdentifier("Minecraft", "Full Server Tick", null);
2016-01-10 07:33:27 +00:00
+ final TimingData minuteData;
+ double avgFreeMemory = -1D;
+ double avgUsedMemory = -1D;
+ FullServerTickHandler() {
+ super(IDENTITY);
+ minuteData = new TimingData(id);
+
+ TIMING_MAP.put(IDENTITY, this);
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-10 07:33:27 +00:00
+ @Override
2016-05-15 21:34:26 +00:00
+ public Timing startTiming() {
2016-01-10 07:33:27 +00:00
+ if (TimingsManager.needsFullReset) {
+ TimingsManager.resetTimings();
+ } else if (TimingsManager.needsRecheckEnabled) {
+ TimingsManager.recheckEnabled();
2016-01-09 06:32:38 +00:00
+ }
2016-05-15 21:34:26 +00:00
+ return super.startTiming();
2016-01-10 07:33:27 +00:00
+ }
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+ @Override
+ public void stopTiming() {
+ super.stopTiming();
2016-06-30 05:31:00 +00:00
+ if (!isEnabled()) {
2016-01-10 07:33:27 +00:00
+ return;
2016-01-09 06:32:38 +00:00
+ }
2016-01-10 07:33:27 +00:00
+ if (TimingHistory.timedTicks % 20 == 0) {
+ final Runtime runtime = Runtime.getRuntime();
+ double usedMemory = runtime.totalMemory() - runtime.freeMemory();
+ double freeMemory = runtime.maxMemory() - usedMemory;
+ if (this.avgFreeMemory == -1) {
+ this.avgFreeMemory = freeMemory;
+ } else {
+ this.avgFreeMemory = (this.avgFreeMemory * (59 / 60D)) + (freeMemory * (1 / 60D));
+ }
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+ if (this.avgUsedMemory == -1) {
+ this.avgUsedMemory = usedMemory;
+ } else {
+ this.avgUsedMemory = (this.avgUsedMemory * (59 / 60D)) + (usedMemory * (1 / 60D));
+ }
2016-01-09 06:32:38 +00:00
+ }
+
2016-01-10 07:33:27 +00:00
+ long start = System.nanoTime();
+ TimingsManager.tick();
+ long diff = System.nanoTime() - start;
2019-03-24 21:47:23 +00:00
+ TIMINGS_TICK.addDiff(diff, null);
2016-01-10 07:33:27 +00:00
+ // addDiff for TIMINGS_TICK incremented this, bring it back down to 1 per tick.
2016-06-30 05:31:00 +00:00
+ record.setCurTickCount(record.getCurTickCount()-1);
+
+ minuteData.setCurTickTotal(record.getCurTickTotal());
+ minuteData.setCurTickCount(1);
+
2016-01-10 07:33:27 +00:00
+ boolean violated = isViolated();
+ minuteData.processTick(violated);
+ TIMINGS_TICK.processTick(violated);
+ processTick(violated);
2016-01-09 06:32:38 +00:00
+
+
2016-01-10 07:33:27 +00:00
+ if (TimingHistory.timedTicks % 1200 == 0) {
+ MINUTE_REPORTS.add(new TimingHistory.MinuteReport());
+ TimingHistory.resetTicks(false);
+ minuteData.reset();
2016-01-09 06:32:38 +00:00
+ }
2016-01-10 07:33:27 +00:00
+ if (TimingHistory.timedTicks % Timings.getHistoryInterval() == 0) {
+ TimingsManager.HISTORY.add(new TimingHistory());
+ TimingsManager.resetTimings();
+ }
2017-02-05 01:46:27 +00:00
+ TimingsExport.reportTimings();
2016-01-10 07:33:27 +00:00
+ }
+
+ boolean isViolated() {
2016-06-30 05:31:00 +00:00
+ return record.getCurTickTotal() > 50000000;
2016-01-10 07:33:27 +00:00
+ }
2016-01-09 06:32:38 +00:00
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/NullTimingHandler.java b/src/main/java/co/aikar/timings/NullTimingHandler.java
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..9b45ce88
2016-01-10 07:33:27 +00:00
--- /dev/null
+++ b/src/main/java/co/aikar/timings/NullTimingHandler.java
2019-03-26 05:31:59 +00:00
@@ -0,0 +1,68 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
2016-01-10 07:33:27 +00:00
+public final class NullTimingHandler implements Timing {
2019-03-26 05:31:59 +00:00
+ public static final Timing NULL = new NullTimingHandler();
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-10 07:33:27 +00:00
+ @Override
2016-05-15 21:34:26 +00:00
+ public Timing startTiming() {
+ return this;
2016-01-10 07:33:27 +00:00
+ }
+
+ @Override
+ public void stopTiming() {
2016-01-09 06:32:38 +00:00
+
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
2016-05-15 21:34:26 +00:00
+ public Timing startTimingIfSync() {
+ return this;
2016-01-09 06:32:38 +00:00
+ }
+
+ @Override
2016-01-10 07:33:27 +00:00
+ public void stopTimingIfSync() {
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+ }
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+ @Override
+ public void abort() {
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+ }
2016-01-09 06:32:38 +00:00
+
2019-03-20 00:28:15 +00:00
+ @Nullable
2016-01-10 07:33:27 +00:00
+ @Override
+ public TimingHandler getTimingHandler() {
+ return null;
2016-01-09 06:32:38 +00:00
+ }
+
2016-01-10 07:33:27 +00:00
+ @Override
+ public void close() {
+
2016-01-09 06:32:38 +00:00
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/TimedEventExecutor.java b/src/main/java/co/aikar/timings/TimedEventExecutor.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..933ecf9b
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/TimedEventExecutor.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,83 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+import org.bukkit.Bukkit;
+import org.bukkit.event.Event;
+import org.bukkit.event.EventException;
+import org.bukkit.event.Listener;
+import org.bukkit.plugin.EventExecutor;
+import org.bukkit.plugin.Plugin;
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+import java.lang.reflect.Method;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+public class TimedEventExecutor implements EventExecutor {
2016-01-09 06:32:38 +00:00
+
+ private final EventExecutor executor;
+ private final Timing timings;
+
+ /**
+ * Wraps an event executor and associates a timing handler to it.
+ *
2017-06-10 22:11:10 +00:00
+ * @param executor Executor to wrap
+ * @param plugin Owning plugin
+ * @param method EventHandler method
+ * @param eventClass Owning class
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ public TimedEventExecutor(@NotNull EventExecutor executor, @NotNull Plugin plugin, @Nullable Method method, @NotNull Class<? extends Event> eventClass) {
2016-01-09 06:32:38 +00:00
+ this.executor = executor;
+ String id;
+
+ if (method == null) {
2016-01-10 00:43:35 +00:00
+ if (executor.getClass().getEnclosingClass() != null) { // Oh Skript, how we love you
+ method = executor.getClass().getEnclosingMethod();
+ }
2016-01-09 06:32:38 +00:00
+ }
2016-01-10 00:43:35 +00:00
+
+ if (method != null) {
+ id = method.getDeclaringClass().getName();
+ } else {
2016-01-10 06:40:46 +00:00
+ id = executor.getClass().getName();
2016-01-10 00:43:35 +00:00
+ }
+
2016-01-09 06:32:38 +00:00
+
+ final String eventName = eventClass.getSimpleName();
2016-03-29 01:41:17 +00:00
+ boolean verbose = "BlockPhysicsEvent".equals(eventName);
2016-01-09 06:32:38 +00:00
+ this.timings = Timings.ofSafe(plugin.getName(), (verbose ? "## " : "") +
+ "Event: " + id + " (" + eventName + ")", null);
+ }
+
+ @Override
2019-03-20 00:28:15 +00:00
+ public void execute(@NotNull Listener listener, @NotNull Event event) throws EventException {
2016-01-09 06:32:38 +00:00
+ if (event.isAsynchronous() || !Timings.timingsEnabled || !Bukkit.isPrimaryThread()) {
+ executor.execute(listener, event);
+ return;
+ }
2019-03-26 00:55:29 +00:00
+ try (Timing ignored = timings.startTiming()){
+ executor.execute(listener, event);
+ }
2016-01-09 06:32:38 +00:00
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/Timing.java b/src/main/java/co/aikar/timings/Timing.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..a21e5ead
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/Timing.java
2019-03-24 21:47:23 +00:00
@@ -0,0 +1,83 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
2016-01-09 06:32:38 +00:00
+/**
+ * Provides an ability to time sections of code within the Minecraft Server
+ */
+public interface Timing extends AutoCloseable {
+ /**
+ * Starts timing the execution until {@link #stopTiming()} is called.
2017-06-10 22:11:10 +00:00
+ *
+ * @return Timing
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-05-15 21:34:26 +00:00
+ Timing startTiming();
2016-01-09 06:32:38 +00:00
+
+ /**
2016-01-21 23:30:05 +00:00
+ * <p>Stops timing and records the data. Propagates the data up to group handlers.</p>
+ *
2016-01-09 06:32:38 +00:00
+ * Will automatically be called when this Timing is used with try-with-resources
+ */
2016-05-15 21:34:26 +00:00
+ void stopTiming();
2016-01-09 06:32:38 +00:00
+
+ /**
+ * Starts timing the execution until {@link #stopTiming()} is called.
+ *
+ * But only if we are on the primary thread.
2017-06-10 22:11:10 +00:00
+ *
+ * @return Timing
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-05-15 21:34:26 +00:00
+ Timing startTimingIfSync();
2016-01-09 06:32:38 +00:00
+
+ /**
2016-01-21 23:30:05 +00:00
+ * <p>Stops timing and records the data. Propagates the data up to group handlers.</p>
+ *
+ * <p>Will automatically be called when this Timing is used with try-with-resources</p>
2016-01-09 06:32:38 +00:00
+ *
+ * But only if we are on the primary thread.
+ */
2016-05-15 21:34:26 +00:00
+ void stopTimingIfSync();
2016-01-09 06:32:38 +00:00
+
+ /**
2019-03-24 21:47:23 +00:00
+ * @deprecated Doesn't do anything - Removed
2016-01-09 06:32:38 +00:00
+ */
2019-03-24 21:47:23 +00:00
+ @Deprecated
2016-05-15 21:34:26 +00:00
+ void abort();
2016-01-09 06:32:38 +00:00
+
+ /**
+ * Used internally to get the actual backing Handler in the case of delegated Handlers
+ *
+ * @return TimingHandler
+ */
2019-03-20 00:28:15 +00:00
+ @Nullable
2016-01-09 06:32:38 +00:00
+ TimingHandler getTimingHandler();
+
+ @Override
+ void close();
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/TimingData.java b/src/main/java/co/aikar/timings/TimingData.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..a5d13a1e
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/TimingData.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,122 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
+import java.util.List;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+import static co.aikar.util.JSONUtil.toArray;
2016-01-09 06:32:38 +00:00
+
+/**
2016-01-21 23:30:05 +00:00
+ * <p>Lightweight object for tracking timing data</p>
+ *
2016-01-09 06:32:38 +00:00
+ * This is broken out to reduce memory usage
+ */
+class TimingData {
2016-06-30 05:31:00 +00:00
+ private final int id;
+ private int count = 0;
+ private int lagCount = 0;
+ private long totalTime = 0;
+ private long lagTotalTime = 0;
+ private int curTickCount = 0;
+ private long curTickTotal = 0;
2016-01-09 06:32:38 +00:00
+
+ TimingData(int id) {
+ this.id = id;
+ }
+
2016-06-30 05:31:00 +00:00
+ private TimingData(TimingData data) {
2016-01-09 06:32:38 +00:00
+ this.id = data.id;
+ this.totalTime = data.totalTime;
+ this.lagTotalTime = data.lagTotalTime;
+ this.count = data.count;
+ this.lagCount = data.lagCount;
+ }
+
+ void add(long diff) {
+ ++curTickCount;
+ curTickTotal += diff;
+ }
+
+ void processTick(boolean violated) {
+ totalTime += curTickTotal;
+ count += curTickCount;
+ if (violated) {
+ lagTotalTime += curTickTotal;
+ lagCount += curTickCount;
+ }
+ curTickTotal = 0;
+ curTickCount = 0;
+ }
+
+ void reset() {
+ count = 0;
+ lagCount = 0;
+ curTickTotal = 0;
+ curTickCount = 0;
+ totalTime = 0;
+ lagTotalTime = 0;
+ }
+
+ protected TimingData clone() {
+ return new TimingData(this);
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-06-30 05:31:00 +00:00
+ List<Object> export() {
+ List<Object> list = toArray(
2016-01-09 06:32:38 +00:00
+ id,
+ count,
+ totalTime);
+ if (lagCount > 0) {
+ list.add(lagCount);
+ list.add(lagTotalTime);
+ }
+ return list;
+ }
2016-06-30 05:31:00 +00:00
+
+ boolean hasData() {
+ return count > 0;
+ }
+
+ long getTotalTime() {
+ return totalTime;
+ }
+
+ int getCurTickCount() {
+ return curTickCount;
+ }
+
+ void setCurTickCount(int curTickCount) {
+ this.curTickCount = curTickCount;
+ }
+
+ long getCurTickTotal() {
+ return curTickTotal;
+ }
+
+ void setCurTickTotal(long curTickTotal) {
+ this.curTickTotal = curTickTotal;
+ }
2016-01-09 06:32:38 +00:00
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/TimingHandler.java b/src/main/java/co/aikar/timings/TimingHandler.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..cc0390c0
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/TimingHandler.java
2019-04-03 02:56:32 +00:00
@@ -0,0 +1,227 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+import co.aikar.util.LoadingIntMap;
2016-03-30 05:59:47 +00:00
+import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
2019-03-24 21:47:23 +00:00
+
+import java.util.ArrayDeque;
+import java.util.Deque;
2018-08-31 00:43:15 +00:00
+import java.util.concurrent.atomic.AtomicInteger;
2019-03-24 21:47:23 +00:00
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
2019-03-20 00:28:15 +00:00
+import org.bukkit.Bukkit;
+import org.jetbrains.annotations.NotNull;
2019-03-24 22:32:08 +00:00
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+
+class TimingHandler implements Timing {
+
2018-08-31 00:43:15 +00:00
+ private static AtomicInteger idPool = new AtomicInteger(1);
2019-03-26 04:31:34 +00:00
+ private static Deque<TimingHandler> TIMING_STACK = new ArrayDeque<>();
2018-08-31 00:43:15 +00:00
+ final int id = idPool.getAndIncrement();
2016-01-09 06:32:38 +00:00
+
2019-03-24 21:47:23 +00:00
+ final TimingIdentifier identifier;
2016-06-30 05:31:00 +00:00
+ private final boolean verbose;
2016-01-09 06:32:38 +00:00
+
2016-06-30 05:31:00 +00:00
+ private final Int2ObjectOpenHashMap<TimingData> children = new LoadingIntMap<>(TimingData::new);
2016-01-09 06:32:38 +00:00
+
+ final TimingData record;
2019-04-03 02:56:32 +00:00
+ private TimingHandler startParent;
2016-06-30 05:31:00 +00:00
+ private final TimingHandler groupHandler;
2016-01-09 06:32:38 +00:00
+
2016-06-30 05:31:00 +00:00
+ private long start = 0;
+ private int timingDepth = 0;
+ private boolean added;
+ private boolean timed;
+ private boolean enabled;
2016-01-09 06:32:38 +00:00
+
2019-03-20 00:28:15 +00:00
+ TimingHandler(@NotNull TimingIdentifier id) {
2019-03-24 21:47:23 +00:00
+ this.identifier = id;
+ this.verbose = id.name.startsWith("##");
2016-01-09 06:32:38 +00:00
+ this.record = new TimingData(this.id);
+ this.groupHandler = id.groupHandler;
+
+ TimingIdentifier.getGroup(id.group).handlers.add(this);
+ checkEnabled();
+ }
+
+ final void checkEnabled() {
+ enabled = Timings.timingsEnabled && (!verbose || Timings.verboseEnabled);
+ }
+
+ void processTick(boolean violated) {
2016-06-30 05:31:00 +00:00
+ if (timingDepth != 0 || record.getCurTickCount() == 0) {
2016-01-09 06:32:38 +00:00
+ timingDepth = 0;
+ start = 0;
+ return;
+ }
+
+ record.processTick(violated);
2016-03-30 05:59:47 +00:00
+ for (TimingData handler : children.values()) {
2016-01-09 06:32:38 +00:00
+ handler.processTick(violated);
+ }
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
2016-05-15 21:34:26 +00:00
+ public Timing startTimingIfSync() {
2018-08-31 00:43:15 +00:00
+ startTiming();
2016-05-15 21:34:26 +00:00
+ return this;
2016-01-09 06:32:38 +00:00
+ }
+
+ @Override
+ public void stopTimingIfSync() {
2018-08-31 00:43:15 +00:00
+ stopTiming();
2016-01-09 06:32:38 +00:00
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-05-15 21:34:26 +00:00
+ public Timing startTiming() {
2019-04-03 02:56:32 +00:00
+ if (!enabled || !Bukkit.isPrimaryThread()) {
+ return this;
+ }
+ if (++timingDepth == 1) {
+ startParent = TIMING_STACK.peekLast();
2016-01-09 06:32:38 +00:00
+ start = System.nanoTime();
+ }
2019-04-03 02:56:32 +00:00
+ TIMING_STACK.addLast(this);
2016-05-15 21:34:26 +00:00
+ return this;
2016-01-09 06:32:38 +00:00
+ }
+
+ public void stopTiming() {
2019-04-03 02:56:32 +00:00
+ if (!enabled || timingDepth <= 0 || start == 0 || !Bukkit.isPrimaryThread()) {
+ return;
+ }
2019-03-24 21:47:23 +00:00
+
2019-04-03 02:56:32 +00:00
+ popTimingStack();
+ if (--timingDepth == 0) {
+ addDiff(System.nanoTime() - start, startParent);
+ startParent = null;
2016-01-09 06:32:38 +00:00
+ start = 0;
+ }
+ }
+
2019-04-03 02:56:32 +00:00
+ private void popTimingStack() {
+ TimingHandler last;
+ while ((last = TIMING_STACK.removeLast()) != this) {
+ last.timingDepth = 0;
+ String reportTo;
+ if ("Minecraft".equalsIgnoreCase(last.identifier.group)) {
+ reportTo = "Paper! This is a potential bug in Paper";
+ } else {
+ reportTo = "the plugin " + last.identifier.group + "(Look for errors above this in the logs)";
+ }
+ Logger.getGlobal().log(Level.SEVERE, "TIMING_STACK_CORRUPTION - Report this to " + reportTo + " (" + last.identifier + " did not stopTiming)", new Throwable());
+ boolean found = TIMING_STACK.contains(this);
+ if (!found) {
+ // We aren't even in the stack... Don't pop everything
+ TIMING_STACK.addLast(last);
+ break;
+ }
+ }
+ }
+
2016-01-09 06:32:38 +00:00
+ @Override
2019-03-24 21:47:23 +00:00
+ public final void abort() {
+
2016-01-09 06:32:38 +00:00
+ }
+
2019-03-24 22:32:08 +00:00
+ void addDiff(long diff, @Nullable TimingHandler parent) {
2019-03-24 21:47:23 +00:00
+ if (parent != null) {
+ parent.children.get(id).add(diff);
2016-01-09 06:32:38 +00:00
+ }
2019-03-24 21:47:23 +00:00
+
2016-01-09 06:32:38 +00:00
+ record.add(diff);
+ if (!added) {
+ added = true;
+ timed = true;
+ TimingsManager.HANDLERS.add(this);
+ }
+ if (groupHandler != null) {
2019-03-24 21:47:23 +00:00
+ groupHandler.addDiff(diff, parent);
2016-01-09 06:32:38 +00:00
+ groupHandler.children.get(id).add(diff);
+ }
+ }
+
+ /**
+ * Reset this timer, setting all values to zero.
+ */
+ void reset(boolean full) {
+ record.reset();
+ if (full) {
+ timed = false;
+ }
+ start = 0;
+ timingDepth = 0;
+ added = false;
+ children.clear();
+ checkEnabled();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
+ public TimingHandler getTimingHandler() {
+ return this;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return (this == o);
+ }
+
+ @Override
+ public int hashCode() {
+ return id;
+ }
+
+ /**
2019-03-20 00:28:15 +00:00
+ * This is simply for the Closeable interface so it can be used with try-with-resources ()
2016-01-09 06:32:38 +00:00
+ */
+ @Override
+ public void close() {
+ stopTimingIfSync();
+ }
+
+ public boolean isSpecial() {
+ return this == TimingsManager.FULL_SERVER_TICK || this == TimingsManager.TIMINGS_TICK;
+ }
2016-06-30 05:31:00 +00:00
+
+ boolean isTimed() {
+ return timed;
+ }
+
+ public boolean isEnabled() {
+ return enabled;
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-06-30 05:31:00 +00:00
+ TimingData[] cloneChildren() {
+ final TimingData[] clonedChildren = new TimingData[children.size()];
+ int i = 0;
+ for (TimingData child : children.values()) {
+ clonedChildren[i++] = child.clone();
+ }
+ return clonedChildren;
+ }
2016-01-09 06:32:38 +00:00
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/TimingHistory.java b/src/main/java/co/aikar/timings/TimingHistory.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..ddaed812
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/TimingHistory.java
2019-03-24 21:47:23 +00:00
@@ -0,0 +1,354 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
2016-04-05 05:20:25 +00:00
+import co.aikar.timings.TimingHistory.RegionData.RegionId;
2016-01-09 06:32:38 +00:00
+import com.google.common.base.Function;
+import com.google.common.collect.Sets;
+import org.bukkit.Bukkit;
+import org.bukkit.Chunk;
+import org.bukkit.Material;
+import org.bukkit.World;
+import org.bukkit.block.BlockState;
+import org.bukkit.entity.Entity;
+import org.bukkit.entity.EntityType;
+import org.bukkit.entity.Player;
2016-01-10 07:33:27 +00:00
+import co.aikar.util.LoadingMap;
+import co.aikar.util.MRUMapCache;
2016-01-09 06:32:38 +00:00
+
+import java.lang.management.ManagementFactory;
+import java.util.Collection;
+import java.util.EnumMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+import static co.aikar.timings.TimingsManager.FULL_SERVER_TICK;
+import static co.aikar.timings.TimingsManager.MINUTE_REPORTS;
+import static co.aikar.util.JSONUtil.*;
2016-01-09 06:32:38 +00:00
+
2016-04-05 05:20:25 +00:00
+@SuppressWarnings({"deprecation", "SuppressionAnnotation", "Convert2Lambda", "Anonymous2MethodRef"})
2016-01-09 06:32:38 +00:00
+public class TimingHistory {
+ public static long lastMinuteTime;
+ public static long timedTicks;
+ public static long playerTicks;
+ public static long entityTicks;
+ public static long tileEntityTicks;
+ public static long activatedEntityTicks;
2016-04-05 05:20:25 +00:00
+ private static int worldIdPool = 1;
2016-01-09 06:32:38 +00:00
+ static Map<String, Integer> worldMap = LoadingMap.newHashMap(new Function<String, Integer>() {
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ public Integer apply(@Nullable String input) {
2016-01-09 06:32:38 +00:00
+ return worldIdPool++;
+ }
+ });
2016-04-05 05:20:25 +00:00
+ private final long endTime;
+ private final long startTime;
+ private final long totalTicks;
+ private final long totalTime; // Represents all time spent running the server this history
+ private final MinuteReport[] minuteReports;
2016-01-09 06:32:38 +00:00
+
2016-04-05 05:20:25 +00:00
+ private final TimingHistoryEntry[] entries;
2016-01-09 06:32:38 +00:00
+ final Set<Material> tileEntityTypeSet = Sets.newHashSet();
+ final Set<EntityType> entityTypeSet = Sets.newHashSet();
2016-04-05 05:20:25 +00:00
+ private final Map<Object, Object> worlds;
2016-01-09 06:32:38 +00:00
+
+ TimingHistory() {
+ this.endTime = System.currentTimeMillis() / 1000;
+ this.startTime = TimingsManager.historyStart / 1000;
+ if (timedTicks % 1200 != 0 || MINUTE_REPORTS.isEmpty()) {
+ this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size() + 1]);
+ this.minuteReports[this.minuteReports.length - 1] = new MinuteReport();
+ } else {
+ this.minuteReports = MINUTE_REPORTS.toArray(new MinuteReport[MINUTE_REPORTS.size()]);
+ }
+ long ticks = 0;
+ for (MinuteReport mp : this.minuteReports) {
+ ticks += mp.ticksRecord.timed;
+ }
+ this.totalTicks = ticks;
2016-06-30 05:31:00 +00:00
+ this.totalTime = FULL_SERVER_TICK.record.getTotalTime();
2019-03-24 21:47:23 +00:00
+ this.entries = new TimingHistoryEntry[TimingsManager.HANDLERS.size()];
2016-01-09 06:32:38 +00:00
+
2019-03-24 21:47:23 +00:00
+ int i = 0;
+ for (TimingHandler handler : TimingsManager.HANDLERS) {
+ entries[i++] = new TimingHistoryEntry(handler);
2016-01-09 06:32:38 +00:00
+ }
+
+ // Information about all loaded chunks/entities
2016-04-05 05:20:25 +00:00
+ //noinspection unchecked
2016-01-09 06:32:38 +00:00
+ this.worlds = toObjectMapper(Bukkit.getWorlds(), new Function<World, JSONPair>() {
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-04-05 05:20:25 +00:00
+ @Override
+ public JSONPair apply(World world) {
+ Map<RegionId, RegionData> regions = LoadingMap.newHashMap(RegionData.LOADER);
2016-01-09 06:32:38 +00:00
+
2016-04-05 05:20:25 +00:00
+ for (Chunk chunk : world.getLoadedChunks()) {
+ RegionData data = regions.get(new RegionId(chunk.getX(), chunk.getZ()));
2016-01-09 06:32:38 +00:00
+
2016-04-05 05:20:25 +00:00
+ for (Entity entity : chunk.getEntities()) {
2017-07-03 01:54:29 +00:00
+ if (entity == null) {
+ Bukkit.getLogger().warning("Null entity detected in chunk at position x: " + chunk.getX() + ", z: " + chunk.getZ());
+ continue;
+ }
+
2016-04-05 05:20:25 +00:00
+ data.entityCounts.get(entity.getType()).increment();
+ }
2016-01-09 06:32:38 +00:00
+
2016-04-05 05:20:25 +00:00
+ for (BlockState tileEntity : chunk.getTileEntities()) {
2017-07-03 01:54:29 +00:00
+ if (tileEntity == null) {
+ Bukkit.getLogger().warning("Null tileentity detected in chunk at position x: " + chunk.getX() + ", z: " + chunk.getZ());
+ continue;
+ }
+
2016-04-05 05:20:25 +00:00
+ data.tileEntityCounts.get(tileEntity.getBlock().getType()).increment();
+ }
+ }
+ return pair(
+ worldMap.get(world.getName()),
+ toArrayMapper(regions.values(),new Function<RegionData, Object>() {
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-04-05 05:20:25 +00:00
+ @Override
+ public Object apply(RegionData input) {
+ return toArray(
+ input.regionId.x,
+ input.regionId.z,
+ toObjectMapper(input.entityCounts.entrySet(),
+ new Function<Map.Entry<EntityType, Counter>, JSONPair>() {
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-04-05 05:20:25 +00:00
+ @Override
+ public JSONPair apply(Map.Entry<EntityType, Counter> entry) {
+ entityTypeSet.add(entry.getKey());
+ return pair(
2019-05-07 00:05:41 +00:00
+ String.valueOf(entry.getKey().ordinal()),
2016-04-05 05:20:25 +00:00
+ entry.getValue().count()
+ );
+ }
2016-01-09 06:32:38 +00:00
+ }
2016-04-05 05:20:25 +00:00
+ ),
+ toObjectMapper(input.tileEntityCounts.entrySet(),
+ new Function<Map.Entry<Material, Counter>, JSONPair>() {
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-04-05 05:20:25 +00:00
+ @Override
+ public JSONPair apply(Map.Entry<Material, Counter> entry) {
+ tileEntityTypeSet.add(entry.getKey());
+ return pair(
2019-05-07 00:05:41 +00:00
+ String.valueOf(entry.getKey().ordinal()),
2016-04-05 05:20:25 +00:00
+ entry.getValue().count()
+ );
+ }
2016-01-09 06:32:38 +00:00
+ }
2016-04-05 05:20:25 +00:00
+ )
+ );
2016-01-09 06:32:38 +00:00
+ }
+ })
+ );
+ }
+ });
+ }
2016-04-05 05:20:25 +00:00
+ static class RegionData {
2016-06-30 05:31:00 +00:00
+ final RegionId regionId;
2016-04-05 05:20:25 +00:00
+ @SuppressWarnings("Guava")
+ static Function<RegionId, RegionData> LOADER = new Function<RegionId, RegionData>() {
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-04-05 05:20:25 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ public RegionData apply(@NotNull RegionId id) {
2016-04-05 05:20:25 +00:00
+ return new RegionData(id);
+ }
+ };
2019-03-20 00:28:15 +00:00
+ RegionData(@NotNull RegionId id) {
2016-04-05 05:20:25 +00:00
+ this.regionId = id;
+ }
+
+ @Override
+ public boolean equals(Object o) {
2016-06-30 05:31:00 +00:00
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
2016-01-09 06:32:38 +00:00
+
2016-04-05 05:20:25 +00:00
+ RegionData that = (RegionData) o;
+
+ return regionId.equals(that.regionId);
+
+ }
+
+ @Override
+ public int hashCode() {
+ return regionId.hashCode();
+ }
+
+ @SuppressWarnings("unchecked")
+ final Map<EntityType, Counter> entityCounts = MRUMapCache.of(LoadingMap.of(
2018-10-18 01:59:35 +00:00
+ new EnumMap<EntityType, Counter>(EntityType.class), k -> new Counter()
2016-04-05 05:20:25 +00:00
+ ));
+ @SuppressWarnings("unchecked")
+ final Map<Material, Counter> tileEntityCounts = MRUMapCache.of(LoadingMap.of(
2018-10-18 01:59:35 +00:00
+ new EnumMap<Material, Counter>(Material.class), k -> new Counter()
2016-04-05 05:20:25 +00:00
+ ));
+
+ static class RegionId {
+ final int x, z;
+ final long regionId;
+ RegionId(int x, int z) {
+ this.x = x >> 5 << 5;
+ this.z = z >> 5 << 5;
+ this.regionId = ((long) (this.x) << 32) + (this.z >> 5 << 5) - Integer.MIN_VALUE;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ RegionId regionId1 = (RegionId) o;
+
+ return regionId == regionId1.regionId;
+
+ }
+
+ @Override
+ public int hashCode() {
+ return (int) (regionId ^ (regionId >>> 32));
+ }
+ }
+ }
+ static void resetTicks(boolean fullReset) {
2016-01-09 06:32:38 +00:00
+ if (fullReset) {
+ // Non full is simply for 1 minute reports
+ timedTicks = 0;
+ }
+ lastMinuteTime = System.nanoTime();
+ playerTicks = 0;
+ tileEntityTicks = 0;
+ entityTicks = 0;
+ activatedEntityTicks = 0;
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ Object export() {
+ return createObject(
+ pair("s", startTime),
+ pair("e", endTime),
+ pair("tk", totalTicks),
+ pair("tm", totalTime),
+ pair("w", worlds),
+ pair("h", toArrayMapper(entries, new Function<TimingHistoryEntry, Object>() {
2019-03-20 00:28:15 +00:00
+ @Nullable
2016-01-09 06:32:38 +00:00
+ @Override
+ public Object apply(TimingHistoryEntry entry) {
+ TimingData record = entry.data;
2016-06-30 05:31:00 +00:00
+ if (!record.hasData()) {
2016-01-09 06:32:38 +00:00
+ return null;
+ }
+ return entry.export();
+ }
+ })),
+ pair("mp", toArrayMapper(minuteReports, new Function<MinuteReport, Object>() {
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
+ public Object apply(MinuteReport input) {
+ return input.export();
+ }
+ }))
+ );
+ }
+
+ static class MinuteReport {
+ final long time = System.currentTimeMillis() / 1000;
+
+ final TicksRecord ticksRecord = new TicksRecord();
+ final PingRecord pingRecord = new PingRecord();
+ final TimingData fst = TimingsManager.FULL_SERVER_TICK.minuteData.clone();
+ final double tps = 1E9 / ( System.nanoTime() - lastMinuteTime ) * ticksRecord.timed;
+ final double usedMemory = TimingsManager.FULL_SERVER_TICK.avgUsedMemory;
+ final double freeMemory = TimingsManager.FULL_SERVER_TICK.avgFreeMemory;
+ final double loadAvg = ManagementFactory.getOperatingSystemMXBean().getSystemLoadAverage();
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-06-30 05:31:00 +00:00
+ List<Object> export() {
2016-01-09 06:32:38 +00:00
+ return toArray(
+ time,
+ Math.round(tps * 100D) / 100D,
+ Math.round(pingRecord.avg * 100D) / 100D,
+ fst.export(),
+ toArray(ticksRecord.timed,
+ ticksRecord.player,
+ ticksRecord.entity,
+ ticksRecord.activatedEntity,
+ ticksRecord.tileEntity
+ ),
+ usedMemory,
+ freeMemory,
+ loadAvg
+ );
+ }
+ }
+
2016-04-05 05:20:25 +00:00
+ private static class TicksRecord {
2016-01-09 06:32:38 +00:00
+ final long timed;
+ final long player;
+ final long entity;
+ final long tileEntity;
+ final long activatedEntity;
+
+ TicksRecord() {
+ timed = timedTicks - (TimingsManager.MINUTE_REPORTS.size() * 1200);
+ player = playerTicks;
+ entity = entityTicks;
+ tileEntity = tileEntityTicks;
+ activatedEntity = activatedEntityTicks;
+ }
+
+ }
+
2016-04-05 05:20:25 +00:00
+ private static class PingRecord {
2016-01-09 06:32:38 +00:00
+ final double avg;
+
+ PingRecord() {
+ final Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
+ int totalPing = 0;
+ for (Player player : onlinePlayers) {
+ totalPing += player.spigot().getPing();
+ }
+ avg = onlinePlayers.isEmpty() ? 0 : totalPing / onlinePlayers.size();
+ }
+ }
+
2016-06-30 05:31:00 +00:00
+
+ private static class Counter {
+ private int count = 0;
2016-01-09 06:32:38 +00:00
+ public int increment() {
+ return ++count;
+ }
+ public int count() {
+ return count;
+ }
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/TimingHistoryEntry.java b/src/main/java/co/aikar/timings/TimingHistoryEntry.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..86d5ac6b
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/TimingHistoryEntry.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,58 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
+import com.google.common.base.Function;
+
+import java.util.List;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+import static co.aikar.util.JSONUtil.toArrayMapper;
2016-01-09 06:32:38 +00:00
+
+class TimingHistoryEntry {
+ final TimingData data;
2016-06-30 05:31:00 +00:00
+ private final TimingData[] children;
2016-01-09 06:32:38 +00:00
+
2019-03-20 00:28:15 +00:00
+ TimingHistoryEntry(@NotNull TimingHandler handler) {
2016-01-09 06:32:38 +00:00
+ this.data = handler.record.clone();
2016-06-30 05:31:00 +00:00
+ children = handler.cloneChildren();
2016-01-09 06:32:38 +00:00
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-06-30 05:31:00 +00:00
+ List<Object> export() {
+ List<Object> result = data.export();
2016-01-09 06:32:38 +00:00
+ if (children.length > 0) {
+ result.add(
+ toArrayMapper(children, new Function<TimingData, Object>() {
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
+ public Object apply(TimingData child) {
+ return child.export();
+ }
+ })
+ );
+ }
+ return result;
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/TimingIdentifier.java b/src/main/java/co/aikar/timings/TimingIdentifier.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..df142a89
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/TimingIdentifier.java
2019-03-24 21:47:23 +00:00
@@ -0,0 +1,116 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
2016-01-10 07:33:27 +00:00
+import co.aikar.util.LoadingMap;
2016-01-09 06:32:38 +00:00
+
2019-02-23 19:22:43 +00:00
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
2016-01-09 06:32:38 +00:00
+import java.util.Map;
2018-10-18 01:59:35 +00:00
+import java.util.Objects;
+import java.util.concurrent.ConcurrentHashMap;
2018-08-31 00:43:15 +00:00
+import java.util.concurrent.atomic.AtomicInteger;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+
+/**
2016-01-21 23:30:05 +00:00
+ * <p>Used as a basis for fast HashMap key comparisons for the Timing Map.</p>
+ *
2016-01-09 06:32:38 +00:00
+ * This class uses interned strings giving us the ability to do an identity check instead of equals() on the strings
+ */
+final class TimingIdentifier {
+ /**
+ * Holds all groups. Autoloads on request for a group by name.
+ */
2018-10-18 01:59:35 +00:00
+ static final Map<String, TimingGroup> GROUP_MAP = LoadingMap.of(new ConcurrentHashMap<>(64, .5F), TimingGroup::new);
2018-08-31 00:43:15 +00:00
+ private static final TimingGroup DEFAULT_GROUP = getGroup("Minecraft");
2016-01-09 06:32:38 +00:00
+ final String group;
+ final String name;
+ final TimingHandler groupHandler;
+ private final int hashCode;
+
2019-03-20 00:28:15 +00:00
+ TimingIdentifier(@Nullable String group, @NotNull String name, @Nullable Timing groupHandler) {
2018-10-18 01:59:35 +00:00
+ this.group = group != null ? group: DEFAULT_GROUP.name;
+ this.name = name;
2016-01-09 06:32:38 +00:00
+ this.groupHandler = groupHandler != null ? groupHandler.getTimingHandler() : null;
+ this.hashCode = (31 * this.group.hashCode()) + this.name.hashCode();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
+ static TimingGroup getGroup(@Nullable String groupName) {
2016-01-09 06:32:38 +00:00
+ if (groupName == null) {
2019-03-20 00:28:15 +00:00
+ //noinspection ConstantConditions
2016-01-09 06:32:38 +00:00
+ return DEFAULT_GROUP;
+ }
+
2018-10-18 01:59:35 +00:00
+ return GROUP_MAP.get(groupName);
2016-01-09 06:32:38 +00:00
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null) {
+ return false;
+ }
+
+ TimingIdentifier that = (TimingIdentifier) o;
2018-10-18 01:59:35 +00:00
+ return Objects.equals(group, that.group) && Objects.equals(name, that.name);
2016-01-09 06:32:38 +00:00
+ }
+
+ @Override
+ public int hashCode() {
+ return hashCode;
+ }
+
2019-03-24 21:47:23 +00:00
+ @Override
+ public String toString() {
+ return "TimingIdentifier{id=" + group + ":" + name +'}';
+ }
+
2016-01-09 06:32:38 +00:00
+ static class TimingGroup {
+
2018-08-31 00:43:15 +00:00
+ private static AtomicInteger idPool = new AtomicInteger(1);
+ final int id = idPool.getAndIncrement();
2016-01-09 06:32:38 +00:00
+
+ final String name;
2019-02-23 19:22:43 +00:00
+ final List<TimingHandler> handlers = Collections.synchronizedList(new ArrayList<>(64));
2016-01-09 06:32:38 +00:00
+
+ private TimingGroup(String name) {
+ this.name = name;
+ }
2018-08-31 00:43:15 +00:00
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ TimingGroup that = (TimingGroup) o;
+ return id == that.id;
+ }
+
+ @Override
+ public int hashCode() {
+ return id;
+ }
2016-01-09 06:32:38 +00:00
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/Timings.java b/src/main/java/co/aikar/timings/Timings.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..0b34e0d0
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/Timings.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,293 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.EvictingQueue;
2017-02-05 03:47:39 +00:00
+import org.apache.commons.lang.Validate;
2016-01-09 06:32:38 +00:00
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+import org.bukkit.plugin.Plugin;
+
+import java.util.Queue;
+import java.util.logging.Level;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+
2017-02-05 01:46:27 +00:00
+@SuppressWarnings({"UnusedDeclaration", "WeakerAccess", "SameParameterValue"})
2016-01-09 06:32:38 +00:00
+public final class Timings {
+
+ private static final int MAX_HISTORY_FRAMES = 12;
+ public static final Timing NULL_HANDLER = new NullTimingHandler();
+ static boolean timingsEnabled = false;
+ static boolean verboseEnabled = false;
+ private static int historyInterval = -1;
+ private static int historyLength = -1;
+
+ private Timings() {}
+
+ /**
+ * Returns a Timing for a plugin corresponding to a name.
+ *
+ * @param plugin Plugin to own the Timing
+ * @param name Name of Timing
+ * @return Handler
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static Timing of(@NotNull Plugin plugin, @NotNull String name) {
2016-01-09 06:32:38 +00:00
+ Timing pluginHandler = null;
+ if (plugin != null) {
+ pluginHandler = ofSafe(plugin.getName(), "Combined Total", TimingsManager.PLUGIN_GROUP_HANDLER);
+ }
+ return of(plugin, name, pluginHandler);
+ }
+
+ /**
2016-01-21 23:30:05 +00:00
+ * <p>Returns a handler that has a groupHandler timer handler. Parent timers should not have their
+ * start/stop methods called directly, as the children will call it for you.</p>
+ *
+ * Parent Timers are used to group multiple subsections together and get a summary of them combined
2016-01-09 06:32:38 +00:00
+ * Parent Handler can not be changed after first call
+ *
+ * @param plugin Plugin to own the Timing
+ * @param name Name of Timing
+ * @param groupHandler Parent handler to mirror .start/stop calls to
+ * @return Timing Handler
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static Timing of(@NotNull Plugin plugin, @NotNull String name, @Nullable Timing groupHandler) {
2016-01-09 06:32:38 +00:00
+ Preconditions.checkNotNull(plugin, "Plugin can not be null");
2018-08-31 00:43:15 +00:00
+ return TimingsManager.getHandler(plugin.getName(), name, groupHandler);
2016-01-09 06:32:38 +00:00
+ }
+
+ /**
+ * Returns a Timing object after starting it, useful for Java7 try-with-resources.
+ *
+ * try (Timing ignored = Timings.ofStart(plugin, someName)) {
+ * // timed section
+ * }
+ *
+ * @param plugin Plugin to own the Timing
+ * @param name Name of Timing
+ * @return Timing Handler
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static Timing ofStart(@NotNull Plugin plugin, @NotNull String name) {
2016-01-09 06:32:38 +00:00
+ return ofStart(plugin, name, null);
+ }
+
+ /**
+ * Returns a Timing object after starting it, useful for Java7 try-with-resources.
+ *
+ * try (Timing ignored = Timings.ofStart(plugin, someName, groupHandler)) {
+ * // timed section
+ * }
+ *
+ * @param plugin Plugin to own the Timing
+ * @param name Name of Timing
+ * @param groupHandler Parent handler to mirror .start/stop calls to
+ * @return Timing Handler
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static Timing ofStart(@NotNull Plugin plugin, @NotNull String name, @Nullable Timing groupHandler) {
2016-01-09 06:32:38 +00:00
+ Timing timing = of(plugin, name, groupHandler);
2018-08-31 00:43:15 +00:00
+ timing.startTiming();
2016-01-09 06:32:38 +00:00
+ return timing;
+ }
+
+ /**
+ * Gets whether or not the Spigot Timings system is enabled
+ *
+ * @return Enabled or not
+ */
+ public static boolean isTimingsEnabled() {
+ return timingsEnabled;
+ }
+
+ /**
2016-01-21 23:30:05 +00:00
+ * <p>Sets whether or not the Spigot Timings system should be enabled</p>
+ *
2016-01-09 06:32:38 +00:00
+ * Calling this will reset timing data.
+ *
+ * @param enabled Should timings be reported
+ */
+ public static void setTimingsEnabled(boolean enabled) {
+ timingsEnabled = enabled;
+ reset();
+ }
+
+ /**
2016-01-21 23:30:05 +00:00
+ * <p>Sets whether or not the Timings should monitor at Verbose level.</p>
+ *
+ * <p>When Verbose is disabled, high-frequency timings will not be available.</p>
2016-01-09 06:32:38 +00:00
+ *
+ * @return Enabled or not
+ */
+ public static boolean isVerboseTimingsEnabled() {
2016-09-23 23:18:36 +00:00
+ return verboseEnabled;
2016-01-09 06:32:38 +00:00
+ }
+
+ /**
2017-06-10 22:11:10 +00:00
+ * <p>Sets whether or not the Timings should monitor at Verbose level.</p>
+ *
2016-01-09 06:32:38 +00:00
+ * When Verbose is disabled, high-frequency timings will not be available.
+ * Calling this will reset timing data.
+ *
+ * @param enabled Should high-frequency timings be reported
+ */
+ public static void setVerboseTimingsEnabled(boolean enabled) {
+ verboseEnabled = enabled;
+ TimingsManager.needsRecheckEnabled = true;
+ }
+
+ /**
2016-01-21 23:30:05 +00:00
+ * <p>Gets the interval between Timing History report generation.</p>
+ *
2016-01-09 06:32:38 +00:00
+ * Defaults to 5 minutes (6000 ticks)
+ *
+ * @return Interval in ticks
+ */
+ public static int getHistoryInterval() {
+ return historyInterval;
+ }
+
+ /**
2016-01-21 23:30:05 +00:00
+ * <p>Sets the interval between Timing History report generations.</p>
+ *
+ * <p>Defaults to 5 minutes (6000 ticks)</p>
2016-01-09 06:32:38 +00:00
+ *
+ * This will recheck your history length, so lowering this value will lower your
+ * history length if you need more than 60 history windows.
+ *
+ * @param interval Interval in ticks
+ */
+ public static void setHistoryInterval(int interval) {
+ historyInterval = Math.max(20*60, interval);
+ // Recheck the history length with the new Interval
+ if (historyLength != -1) {
+ setHistoryLength(historyLength);
+ }
+ }
+
+ /**
+ * Gets how long in ticks Timings history is kept for the server.
+ *
+ * Defaults to 1 hour (72000 ticks)
+ *
+ * @return Duration in Ticks
+ */
+ public static int getHistoryLength() {
+ return historyLength;
+ }
+
+ /**
+ * Sets how long Timing History reports are kept for the server.
+ *
+ * Defaults to 1 hours(72000 ticks)
+ *
+ * This value is capped at a maximum of getHistoryInterval() * MAX_HISTORY_FRAMES (12)
+ *
+ * Will not reset Timing Data but may truncate old history if the new length is less than old length.
+ *
+ * @param length Duration in ticks
+ */
+ public static void setHistoryLength(int length) {
+ // Cap at 12 History Frames, 1 hour at 5 minute frames.
+ int maxLength = historyInterval * MAX_HISTORY_FRAMES;
+ // For special cases of servers with special permission to bypass the max.
+ // This max helps keep data file sizes reasonable for processing on Aikar's Timing parser side.
+ // Setting this will not help you bypass the max unless Aikar has added an exception on the API side.
+ if (System.getProperty("timings.bypassMax") != null) {
+ maxLength = Integer.MAX_VALUE;
+ }
+ historyLength = Math.max(Math.min(maxLength, length), historyInterval);
+ Queue<TimingHistory> oldQueue = TimingsManager.HISTORY;
+ int frames = (getHistoryLength() / getHistoryInterval());
+ if (length > maxLength) {
+ Bukkit.getLogger().log(Level.WARNING, "Timings Length too high. Requested " + length + ", max is " + maxLength + ". To get longer history, you must increase your interval. Set Interval to " + Math.ceil(length / MAX_HISTORY_FRAMES) + " to achieve this length.");
+ }
+ TimingsManager.HISTORY = EvictingQueue.create(frames);
+ TimingsManager.HISTORY.addAll(oldQueue);
+ }
+
+ /**
+ * Resets all Timing Data
+ */
+ public static void reset() {
+ TimingsManager.reset();
+ }
+
+ /**
+ * Generates a report and sends it to the specified command sender.
+ *
+ * If sender is null, ConsoleCommandSender will be used.
2016-01-21 23:30:05 +00:00
+ * @param sender The sender to send to, or null to use the ConsoleCommandSender
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ public static void generateReport(@Nullable CommandSender sender) {
2016-01-09 06:32:38 +00:00
+ if (sender == null) {
+ sender = Bukkit.getConsoleSender();
+ }
2017-02-05 03:47:39 +00:00
+ TimingsExport.requestingReport.add(sender);
+ }
+
+ /**
+ * Generates a report and sends it to the specified listener.
+ * Use with {@link org.bukkit.command.BufferedCommandSender} to get full response when done!
+ * @param sender The listener to send responses too.
+ */
2019-03-20 00:28:15 +00:00
+ public static void generateReport(@NotNull TimingsReportListener sender) {
2017-02-05 03:47:39 +00:00
+ Validate.notNull(sender);
2017-02-05 01:46:27 +00:00
+ TimingsExport.requestingReport.add(sender);
2016-01-09 06:32:38 +00:00
+ }
+
+ /*
+ =================
+ Protected API: These are for internal use only in Bukkit/CraftBukkit
+ These do not have isPrimaryThread() checks in the startTiming/stopTiming
+ =================
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ static TimingHandler ofSafe(@NotNull String name) {
2016-01-09 06:32:38 +00:00
+ return ofSafe(null, name, null);
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
+ static Timing ofSafe(@Nullable Plugin plugin, @NotNull String name) {
2016-01-09 06:32:38 +00:00
+ Timing pluginHandler = null;
+ if (plugin != null) {
+ pluginHandler = ofSafe(plugin.getName(), "Combined Total", TimingsManager.PLUGIN_GROUP_HANDLER);
+ }
+ return ofSafe(plugin != null ? plugin.getName() : "Minecraft - Invalid Plugin", name, pluginHandler);
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
+ static TimingHandler ofSafe(@NotNull String name, @Nullable Timing groupHandler) {
2016-01-09 06:32:38 +00:00
+ return ofSafe(null, name, groupHandler);
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
+ static TimingHandler ofSafe(@Nullable String groupName, @NotNull String name, @Nullable Timing groupHandler) {
2018-08-31 00:43:15 +00:00
+ return TimingsManager.getHandler(groupName, name, groupHandler);
2016-01-09 06:32:38 +00:00
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/TimingsCommand.java b/src/main/java/co/aikar/timings/TimingsCommand.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..c0d8f201
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/TimingsCommand.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,122 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
+import com.google.common.collect.ImmutableList;
+import org.apache.commons.lang.Validate;
+import org.bukkit.ChatColor;
+import org.bukkit.command.CommandSender;
+import org.bukkit.command.defaults.BukkitCommand;
+import org.bukkit.util.StringUtil;
+
+import java.util.ArrayList;
+import java.util.List;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+
+
+public class TimingsCommand extends BukkitCommand {
2016-08-20 03:42:38 +00:00
+ private static final List<String> TIMINGS_SUBCOMMANDS = ImmutableList.of("report", "reset", "on", "off", "paste", "verbon", "verboff");
+ private long lastResetAttempt = 0;
2016-01-09 06:32:38 +00:00
+
2019-03-20 00:28:15 +00:00
+ public TimingsCommand(@NotNull String name) {
2016-01-09 06:32:38 +00:00
+ super(name);
+ this.description = "Manages Spigot Timings data to see performance of the server.";
+ this.usageMessage = "/timings <reset|report|on|off|verbon|verboff>";
+ this.setPermission("bukkit.command.timings");
+ }
+
+ @Override
2019-03-20 00:28:15 +00:00
+ public boolean execute(@NotNull CommandSender sender, @NotNull String currentAlias, @NotNull String[] args) {
2016-01-09 06:32:38 +00:00
+ if (!testPermission(sender)) {
+ return true;
+ }
+ if (args.length < 1) {
+ sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
+ return true;
+ }
+ final String arg = args[0];
+ if ("on".equalsIgnoreCase(arg)) {
+ Timings.setTimingsEnabled(true);
+ sender.sendMessage("Enabled Timings & Reset");
+ return true;
+ } else if ("off".equalsIgnoreCase(arg)) {
+ Timings.setTimingsEnabled(false);
+ sender.sendMessage("Disabled Timings");
+ return true;
+ }
+
+ if (!Timings.isTimingsEnabled()) {
+ sender.sendMessage("Please enable timings by typing /timings on");
+ return true;
+ }
2016-08-20 03:42:38 +00:00
+
+ long now = System.currentTimeMillis();
2016-01-09 06:32:38 +00:00
+ if ("verbon".equalsIgnoreCase(arg)) {
+ Timings.setVerboseTimingsEnabled(true);
+ sender.sendMessage("Enabled Verbose Timings");
+ return true;
+ } else if ("verboff".equalsIgnoreCase(arg)) {
+ Timings.setVerboseTimingsEnabled(false);
+ sender.sendMessage("Disabled Verbose Timings");
+ return true;
+ } else if ("reset".equalsIgnoreCase(arg)) {
2016-08-20 03:42:38 +00:00
+ if (now - lastResetAttempt < 30000) {
+ TimingsManager.reset();
+ sender.sendMessage(ChatColor.RED + "Timings reset. Please wait 5-10 minutes before using /timings report.");
+ } else {
+ lastResetAttempt = now;
+ sender.sendMessage(ChatColor.RED + "WARNING: Timings v2 should not be reset. If you are encountering lag, please wait 3 minutes and then issue a report. The best timings will include 10+ minutes, with data before and after your lag period. If you really want to reset, run this command again within 30 seconds.");
+ }
+
2016-01-09 06:32:38 +00:00
+ } else if ("cost".equals(arg)) {
+ sender.sendMessage("Timings cost: " + TimingsExport.getCost());
+ } else if (
+ "paste".equalsIgnoreCase(arg) ||
+ "report".equalsIgnoreCase(arg) ||
+ "get".equalsIgnoreCase(arg) ||
+ "merged".equalsIgnoreCase(arg) ||
+ "separate".equalsIgnoreCase(arg)
+ ) {
2017-02-05 01:46:27 +00:00
+ Timings.generateReport(sender);
2016-01-09 06:32:38 +00:00
+ } else {
+ sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
+ }
+ return true;
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) {
2016-01-09 06:32:38 +00:00
+ Validate.notNull(sender, "Sender cannot be null");
+ Validate.notNull(args, "Arguments cannot be null");
+ Validate.notNull(alias, "Alias cannot be null");
+
+ if (args.length == 1) {
+ return StringUtil.copyPartialMatches(args[0], TIMINGS_SUBCOMMANDS,
+ new ArrayList<String>(TIMINGS_SUBCOMMANDS.size()));
+ }
+ return ImmutableList.of();
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/TimingsExport.java b/src/main/java/co/aikar/timings/TimingsExport.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..23eb8c65
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/TimingsExport.java
2019-03-24 21:47:23 +00:00
@@ -0,0 +1,355 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
2017-02-05 01:46:27 +00:00
+import com.google.common.collect.Lists;
2016-01-09 06:32:38 +00:00
+import com.google.common.collect.Sets;
+import org.apache.commons.lang.StringUtils;
+import org.bukkit.Bukkit;
+import org.bukkit.ChatColor;
+import org.bukkit.Material;
+import org.bukkit.command.CommandSender;
+import org.bukkit.configuration.ConfigurationSection;
+import org.bukkit.configuration.MemorySection;
+import org.bukkit.entity.EntityType;
+import org.json.simple.JSONObject;
+import org.json.simple.JSONValue;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.management.ManagementFactory;
+import java.lang.management.RuntimeMXBean;
+import java.net.HttpURLConnection;
+import java.net.InetAddress;
+import java.net.URL;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Level;
+import java.util.zip.GZIPOutputStream;
+
2016-01-10 07:33:27 +00:00
+import static co.aikar.timings.TimingsManager.HISTORY;
2017-02-05 03:47:39 +00:00
+import static co.aikar.util.JSONUtil.appendObjectData;
+import static co.aikar.util.JSONUtil.createObject;
+import static co.aikar.util.JSONUtil.pair;
+import static co.aikar.util.JSONUtil.toArray;
+import static co.aikar.util.JSONUtil.toArrayMapper;
+import static co.aikar.util.JSONUtil.toObjectMapper;
2016-01-09 06:32:38 +00:00
+
+@SuppressWarnings({"rawtypes", "SuppressionAnnotation"})
+class TimingsExport extends Thread {
+
2017-02-05 03:47:39 +00:00
+ private final TimingsReportListener listeners;
2016-01-09 06:32:38 +00:00
+ private final Map out;
+ private final TimingHistory[] history;
2016-08-20 03:42:38 +00:00
+ private static long lastReport = 0;
2017-02-05 01:46:27 +00:00
+ final static List<CommandSender> requestingReport = Lists.newArrayList();
2016-01-09 06:32:38 +00:00
+
2017-02-05 03:47:39 +00:00
+ private TimingsExport(TimingsReportListener listeners, Map out, TimingHistory[] history) {
2016-01-09 06:32:38 +00:00
+ super("Timings paste thread");
2017-02-05 03:47:39 +00:00
+ this.listeners = listeners;
2016-01-09 06:32:38 +00:00
+ this.out = out;
+ this.history = history;
+ }
+
+ /**
2017-02-05 01:46:27 +00:00
+ * Checks if any pending reports are being requested, and builds one if needed.
2016-01-09 06:32:38 +00:00
+ */
2017-02-05 01:46:27 +00:00
+ static void reportTimings() {
+ if (requestingReport.isEmpty()) {
+ return;
+ }
2017-02-05 03:47:39 +00:00
+ TimingsReportListener listeners = new TimingsReportListener(requestingReport);
+ listeners.addConsoleIfNeeded();
+
2017-02-05 01:46:27 +00:00
+ requestingReport.clear();
2016-08-20 03:42:38 +00:00
+ long now = System.currentTimeMillis();
+ final long lastReportDiff = now - lastReport;
+ if (lastReportDiff < 60000) {
2017-02-05 03:47:39 +00:00
+ listeners.sendMessage(ChatColor.RED + "Please wait at least 1 minute in between Timings reports. (" + (int)((60000 - lastReportDiff) / 1000) + " seconds)");
+ listeners.done();
2016-08-20 03:42:38 +00:00
+ return;
+ }
+ final long lastStartDiff = now - TimingsManager.timingStart;
+ if (lastStartDiff < 180000) {
2017-02-05 03:47:39 +00:00
+ listeners.sendMessage(ChatColor.RED + "Please wait at least 3 minutes before generating a Timings report. Unlike Timings v1, v2 benefits from longer timings and is not as useful with short timings. (" + (int)((180000 - lastStartDiff) / 1000) + " seconds)");
+ listeners.done();
2016-08-20 03:42:38 +00:00
+ return;
+ }
2017-02-05 03:47:39 +00:00
+ listeners.sendMessage(ChatColor.GREEN + "Preparing Timings Report...");
2016-08-20 03:42:38 +00:00
+ lastReport = now;
2016-01-09 06:32:38 +00:00
+ Map parent = createObject(
+ // Get some basic system details about the server
+ pair("version", Bukkit.getVersion()),
+ pair("maxplayers", Bukkit.getMaxPlayers()),
+ pair("start", TimingsManager.timingStart / 1000),
+ pair("end", System.currentTimeMillis() / 1000),
+ pair("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000)
+ );
+ if (!TimingsManager.privacy) {
+ appendObjectData(parent,
2019-05-06 07:20:16 +00:00
+ pair("server", Bukkit.getUnsafe().getTimingsServerName()),
2016-01-09 06:32:38 +00:00
+ pair("motd", Bukkit.getServer().getMotd()),
+ pair("online-mode", Bukkit.getServer().getOnlineMode()),
+ pair("icon", Bukkit.getServer().getServerIcon().getData())
+ );
+ }
+
+ final Runtime runtime = Runtime.getRuntime();
+ RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();
+
+ parent.put("system", createObject(
+ pair("timingcost", getCost()),
+ pair("name", System.getProperty("os.name")),
+ pair("version", System.getProperty("os.version")),
+ pair("jvmversion", System.getProperty("java.version")),
+ pair("arch", System.getProperty("os.arch")),
+ pair("maxmem", runtime.maxMemory()),
+ pair("cpu", runtime.availableProcessors()),
+ pair("runtime", ManagementFactory.getRuntimeMXBean().getUptime()),
+ pair("flags", StringUtils.join(runtimeBean.getInputArguments(), " ")),
2017-02-05 03:47:39 +00:00
+ pair("gc", toObjectMapper(ManagementFactory.getGarbageCollectorMXBeans(), input -> pair(input.getName(), toArray(input.getCollectionCount(), input.getCollectionTime()))))
2016-01-09 06:32:38 +00:00
+ )
+ );
+
+ Set<Material> tileEntityTypeSet = Sets.newHashSet();
+ Set<EntityType> entityTypeSet = Sets.newHashSet();
+
+ int size = HISTORY.size();
+ TimingHistory[] history = new TimingHistory[size + 1];
+ int i = 0;
+ for (TimingHistory timingHistory : HISTORY) {
+ tileEntityTypeSet.addAll(timingHistory.tileEntityTypeSet);
+ entityTypeSet.addAll(timingHistory.entityTypeSet);
+ history[i++] = timingHistory;
+ }
+
+ history[i] = new TimingHistory(); // Current snapshot
+ tileEntityTypeSet.addAll(history[i].tileEntityTypeSet);
+ entityTypeSet.addAll(history[i].entityTypeSet);
+
+
+ Map handlers = createObject();
2019-02-23 19:22:43 +00:00
+ Map groupData;
+ synchronized (TimingIdentifier.GROUP_MAP) {
+ for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
+ synchronized (group.handlers) {
+ for (TimingHandler id : group.handlers) {
+
+ if (!id.isTimed() && !id.isSpecial()) {
+ continue;
+ }
2019-03-24 21:47:23 +00:00
+
+ String name = id.identifier.name;
+ if (name.startsWith("##")) {
+ name = name.substring(3);
+ }
2019-02-23 19:22:43 +00:00
+ handlers.put(id.id, toArray(
+ group.id,
2019-03-24 21:47:23 +00:00
+ name
2019-02-23 19:22:43 +00:00
+ ));
+ }
2016-01-09 06:32:38 +00:00
+ }
+ }
2019-02-23 19:22:43 +00:00
+
+ groupData = toObjectMapper(
+ TimingIdentifier.GROUP_MAP.values(), group -> pair(group.id, group.name));
2016-01-09 06:32:38 +00:00
+ }
+
+ parent.put("idmap", createObject(
2019-02-23 19:22:43 +00:00
+ pair("groups", groupData),
2016-01-09 06:32:38 +00:00
+ pair("handlers", handlers),
2017-02-05 03:47:39 +00:00
+ pair("worlds", toObjectMapper(TimingHistory.worldMap.entrySet(), input -> pair(input.getValue(), input.getKey()))),
2016-01-09 06:32:38 +00:00
+ pair("tileentity",
2019-05-07 17:13:52 +00:00
+ toObjectMapper(tileEntityTypeSet, input -> pair(input.ordinal(), input.name()))),
2016-01-09 06:32:38 +00:00
+ pair("entity",
2019-07-08 02:54:40 +00:00
+ toObjectMapper(entityTypeSet, input -> pair(input.ordinal(), input.name())))
2016-01-09 06:32:38 +00:00
+ ));
+
+ // Information about loaded plugins
+
+ parent.put("plugins", toObjectMapper(Bukkit.getPluginManager().getPlugins(),
2017-02-05 03:47:39 +00:00
+ plugin -> pair(plugin.getName(), createObject(
+ pair("version", plugin.getDescription().getVersion()),
+ pair("description", String.valueOf(plugin.getDescription().getDescription()).trim()),
+ pair("website", plugin.getDescription().getWebsite()),
+ pair("authors", StringUtils.join(plugin.getDescription().getAuthors(), ", "))
+ ))));
2016-01-09 06:32:38 +00:00
+
+
+
+ // Information on the users Config
+
+ parent.put("config", createObject(
+ pair("spigot", mapAsJSON(Bukkit.spigot().getSpigotConfig(), null)),
+ pair("bukkit", mapAsJSON(Bukkit.spigot().getBukkitConfig(), null)),
2016-04-06 04:27:53 +00:00
+ pair("paper", mapAsJSON(Bukkit.spigot().getPaperConfig(), null))
2016-01-09 06:32:38 +00:00
+ ));
+
2017-02-05 03:47:39 +00:00
+ new TimingsExport(listeners, parent, history).start();
2016-01-09 06:32:38 +00:00
+ }
+
+ static long getCost() {
+ // Benchmark the users System.nanotime() for cost basis
2016-02-24 03:31:01 +00:00
+ int passes = 100;
2016-01-09 06:32:38 +00:00
+ TimingHandler SAMPLER1 = Timings.ofSafe("Timings Sampler 1");
+ TimingHandler SAMPLER2 = Timings.ofSafe("Timings Sampler 2");
+ TimingHandler SAMPLER3 = Timings.ofSafe("Timings Sampler 3");
+ TimingHandler SAMPLER4 = Timings.ofSafe("Timings Sampler 4");
+ TimingHandler SAMPLER5 = Timings.ofSafe("Timings Sampler 5");
+ TimingHandler SAMPLER6 = Timings.ofSafe("Timings Sampler 6");
+
+ long start = System.nanoTime();
+ for (int i = 0; i < passes; i++) {
+ SAMPLER1.startTiming();
+ SAMPLER2.startTiming();
+ SAMPLER3.startTiming();
+ SAMPLER3.stopTiming();
+ SAMPLER4.startTiming();
+ SAMPLER5.startTiming();
+ SAMPLER6.startTiming();
+ SAMPLER6.stopTiming();
+ SAMPLER5.stopTiming();
+ SAMPLER4.stopTiming();
+ SAMPLER2.stopTiming();
+ SAMPLER1.stopTiming();
+ }
+ long timingsCost = (System.nanoTime() - start) / passes / 6;
+ SAMPLER1.reset(true);
+ SAMPLER2.reset(true);
+ SAMPLER3.reset(true);
+ SAMPLER4.reset(true);
+ SAMPLER5.reset(true);
+ SAMPLER6.reset(true);
+ return timingsCost;
+ }
+
+ private static JSONObject mapAsJSON(ConfigurationSection config, String parentKey) {
+
+ JSONObject object = new JSONObject();
+ for (String key : config.getKeys(false)) {
+ String fullKey = (parentKey != null ? parentKey + "." + key : key);
+ if (fullKey.equals("database") || fullKey.equals("settings.bungeecord-addresses") || TimingsManager.hiddenConfigs.contains(fullKey)) {
+ continue;
+ }
+ final Object val = config.get(key);
+
+ object.put(key, valAsJSON(val, fullKey));
+ }
+ return object;
+ }
+
+ private static Object valAsJSON(Object val, final String parentKey) {
+ if (!(val instanceof MemorySection)) {
+ if (val instanceof List) {
+ Iterable<Object> v = (Iterable<Object>) val;
2017-02-05 03:47:39 +00:00
+ return toArrayMapper(v, input -> valAsJSON(input, parentKey));
2016-01-09 06:32:38 +00:00
+ } else {
+ return val.toString();
+ }
+ } else {
+ return mapAsJSON((ConfigurationSection) val, parentKey);
+ }
+ }
+
+ @Override
+ public void run() {
2017-02-05 03:47:39 +00:00
+ out.put("data", toArrayMapper(history, TimingHistory::export));
2016-01-09 06:32:38 +00:00
+
+
+ String response = null;
2017-02-05 04:07:09 +00:00
+ String timingsURL = null;
2016-01-09 06:32:38 +00:00
+ try {
+ HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection();
+ con.setDoOutput(true);
2016-06-30 05:31:00 +00:00
+ String hostName = "BrokenHost";
+ try {
+ hostName = InetAddress.getLocalHost().getHostName();
2019-05-06 07:20:16 +00:00
+ } catch (Exception ignored) {}
+ con.setRequestProperty("User-Agent", "Paper/" + Bukkit.getUnsafe().getTimingsServerName() + "/" + hostName);
2016-01-09 06:32:38 +00:00
+ con.setRequestMethod("POST");
+ con.setInstanceFollowRedirects(false);
+
+ OutputStream request = new GZIPOutputStream(con.getOutputStream()) {{
+ this.def.setLevel(7);
+ }};
+
+ request.write(JSONValue.toJSONString(out).getBytes("UTF-8"));
+ request.close();
+
+ response = getResponse(con);
+
+ if (con.getResponseCode() != 302) {
2017-02-05 03:47:39 +00:00
+ listeners.sendMessage(
2016-01-09 06:32:38 +00:00
+ ChatColor.RED + "Upload Error: " + con.getResponseCode() + ": " + con.getResponseMessage());
2017-02-05 03:47:39 +00:00
+ listeners.sendMessage(ChatColor.RED + "Check your logs for more information");
2016-01-09 06:32:38 +00:00
+ if (response != null) {
+ Bukkit.getLogger().log(Level.SEVERE, response);
+ }
+ return;
+ }
+
2017-02-05 04:07:09 +00:00
+ timingsURL = con.getHeaderField("Location");
+ listeners.sendMessage(ChatColor.GREEN + "View Timings Report: " + timingsURL);
2016-01-09 06:32:38 +00:00
+
+ if (response != null && !response.isEmpty()) {
+ Bukkit.getLogger().log(Level.INFO, "Timing Response: " + response);
+ }
+ } catch (IOException ex) {
2017-02-05 03:47:39 +00:00
+ listeners.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information");
2016-01-09 06:32:38 +00:00
+ if (response != null) {
+ Bukkit.getLogger().log(Level.SEVERE, response);
+ }
+ Bukkit.getLogger().log(Level.SEVERE, "Could not paste timings", ex);
2017-02-05 03:47:39 +00:00
+ } finally {
2017-02-05 04:07:09 +00:00
+ this.listeners.done(timingsURL);
2016-01-09 06:32:38 +00:00
+ }
+ }
+
+ private String getResponse(HttpURLConnection con) throws IOException {
+ InputStream is = null;
+ try {
+ is = con.getInputStream();
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+
+ byte[] b = new byte[1024];
+ int bytesRead;
+ while ((bytesRead = is.read(b)) != -1) {
+ bos.write(b, 0, bytesRead);
+ }
+ return bos.toString();
+
+ } catch (IOException ex) {
2017-02-05 03:47:39 +00:00
+ listeners.sendMessage(ChatColor.RED + "Error uploading timings, check your logs for more information");
2016-01-09 06:32:38 +00:00
+ Bukkit.getLogger().log(Level.WARNING, con.getResponseMessage(), ex);
+ return null;
+ } finally {
+ if (is != null) {
+ is.close();
+ }
+ }
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/TimingsManager.java b/src/main/java/co/aikar/timings/TimingsManager.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..ef824d70
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/TimingsManager.java
2019-03-24 21:47:23 +00:00
@@ -0,0 +1,188 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
2019-02-23 19:22:43 +00:00
+import co.aikar.util.LoadingMap;
2016-01-09 06:32:38 +00:00
+import com.google.common.collect.EvictingQueue;
+import org.bukkit.Bukkit;
+import org.bukkit.Server;
+import org.bukkit.command.Command;
+import org.bukkit.plugin.Plugin;
+import org.bukkit.plugin.java.PluginClassLoader;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
2018-10-18 01:59:35 +00:00
+import java.util.concurrent.ConcurrentHashMap;
2016-01-09 06:32:38 +00:00
+import java.util.logging.Level;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+
+public final class TimingsManager {
2018-10-18 01:59:35 +00:00
+ static final Map<TimingIdentifier, TimingHandler> TIMING_MAP = LoadingMap.of(
+ new ConcurrentHashMap<>(4096, .5F), TimingHandler::new
+ );
2016-01-09 06:32:38 +00:00
+ public static final FullServerTickHandler FULL_SERVER_TICK = new FullServerTickHandler();
+ public static final TimingHandler TIMINGS_TICK = Timings.ofSafe("Timings Tick", FULL_SERVER_TICK);
+ public static final Timing PLUGIN_GROUP_HANDLER = Timings.ofSafe("Plugins");
+ public static List<String> hiddenConfigs = new ArrayList<String>();
+ public static boolean privacy = false;
+
2019-03-24 21:47:23 +00:00
+ static final List<TimingHandler> HANDLERS = new ArrayList<>(1024);
2018-10-18 01:59:35 +00:00
+ static final List<TimingHistory.MinuteReport> MINUTE_REPORTS = new ArrayList<>(64);
2016-01-09 06:32:38 +00:00
+
+ static EvictingQueue<TimingHistory> HISTORY = EvictingQueue.create(12);
+ static long timingStart = 0;
+ static long historyStart = 0;
+ static boolean needsFullReset = false;
+ static boolean needsRecheckEnabled = false;
+
+ private TimingsManager() {}
+
+ /**
+ * Resets all timing data on the next tick
+ */
+ static void reset() {
+ needsFullReset = true;
+ }
+
+ /**
+ * Ticked every tick by CraftBukkit to count the number of times a timer
+ * caused TPS loss.
+ */
+ static void tick() {
+ if (Timings.timingsEnabled) {
+ boolean violated = FULL_SERVER_TICK.isViolated();
+
2019-03-24 21:47:23 +00:00
+ for (TimingHandler handler : HANDLERS) {
+ if (handler.isSpecial()) {
+ // We manually call this
+ continue;
2016-01-09 06:32:38 +00:00
+ }
2019-03-24 21:47:23 +00:00
+ handler.processTick(violated);
2016-01-09 06:32:38 +00:00
+ }
+
+ TimingHistory.playerTicks += Bukkit.getOnlinePlayers().size();
+ TimingHistory.timedTicks++;
+ // Generate TPS/Ping/Tick reports every minute
+ }
+ }
+ static void stopServer() {
+ Timings.timingsEnabled = false;
+ recheckEnabled();
+ }
+ static void recheckEnabled() {
+ synchronized (TIMING_MAP) {
+ for (TimingHandler timings : TIMING_MAP.values()) {
+ timings.checkEnabled();
+ }
+ }
+ needsRecheckEnabled = false;
+ }
+ static void resetTimings() {
+ if (needsFullReset) {
+ // Full resets need to re-check every handlers enabled state
+ // Timing map can be modified from async so we must sync on it.
+ synchronized (TIMING_MAP) {
+ for (TimingHandler timings : TIMING_MAP.values()) {
+ timings.reset(true);
+ }
+ }
+ Bukkit.getLogger().log(Level.INFO, "Timings Reset");
+ HISTORY.clear();
+ needsFullReset = false;
+ needsRecheckEnabled = false;
+ timingStart = System.currentTimeMillis();
+ } else {
+ // Soft resets only need to act on timings that have done something
+ // Handlers can only be modified on main thread.
2019-03-24 21:47:23 +00:00
+ for (TimingHandler timings : HANDLERS) {
+ timings.reset(false);
2016-01-09 06:32:38 +00:00
+ }
+ }
+
+ HANDLERS.clear();
+ MINUTE_REPORTS.clear();
+
+ TimingHistory.resetTicks(true);
+ historyStart = System.currentTimeMillis();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
+ static TimingHandler getHandler(@Nullable String group, @NotNull String name, @Nullable Timing parent) {
2018-08-31 00:43:15 +00:00
+ return TIMING_MAP.get(new TimingIdentifier(group, name, parent));
2016-01-09 06:32:38 +00:00
+ }
+
+
+ /**
2016-01-21 23:30:05 +00:00
+ * <p>Due to access restrictions, we need a helper method to get a Command TimingHandler with String group</p>
+ *
2016-01-09 06:32:38 +00:00
+ * Plugins should never call this
+ *
+ * @param pluginName Plugin this command is associated with
+ * @param command Command to get timings for
+ * @return TimingHandler
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static Timing getCommandTiming(@Nullable String pluginName, @NotNull Command command) {
2016-01-09 06:32:38 +00:00
+ Plugin plugin = null;
+ final Server server = Bukkit.getServer();
2016-04-30 16:53:20 +00:00
+ if (!( server == null || pluginName == null ||
+ "minecraft".equals(pluginName) || "bukkit".equals(pluginName) ||
+ "spigot".equalsIgnoreCase(pluginName) || "paper".equals(pluginName)
+ )) {
2016-01-09 06:32:38 +00:00
+ plugin = server.getPluginManager().getPlugin(pluginName);
2016-04-30 16:53:20 +00:00
+ }
+ if (plugin == null) {
+ // Plugin is passing custom fallback prefix, try to look up by class loader
+ plugin = getPluginByClassloader(command.getClass());
2016-01-09 06:32:38 +00:00
+ }
+ if (plugin == null) {
+ return Timings.ofSafe("Command: " + pluginName + ":" + command.getTimingName());
+ }
+
+ return Timings.ofSafe(plugin, "Command: " + pluginName + ":" + command.getTimingName());
+ }
+
+ /**
+ * Looks up the class loader for the specified class, and if it is a PluginClassLoader, return the
+ * Plugin that created this class.
+ *
+ * @param clazz Class to check
+ * @return Plugin if created by a plugin
+ */
2019-03-20 00:28:15 +00:00
+ @Nullable
2018-09-29 18:05:24 +00:00
+ public static Plugin getPluginByClassloader(@Nullable Class<?> clazz) {
2016-01-09 06:32:38 +00:00
+ if (clazz == null) {
+ return null;
+ }
+ final ClassLoader classLoader = clazz.getClassLoader();
+ if (classLoader instanceof PluginClassLoader) {
+ PluginClassLoader pluginClassLoader = (PluginClassLoader) classLoader;
+ return pluginClassLoader.getPlugin();
+ }
+ return null;
+ }
+}
2017-02-05 03:47:39 +00:00
diff --git a/src/main/java/co/aikar/timings/TimingsReportListener.java b/src/main/java/co/aikar/timings/TimingsReportListener.java
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..bf3e059f
2017-02-05 03:47:39 +00:00
--- /dev/null
+++ b/src/main/java/co/aikar/timings/TimingsReportListener.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,75 @@
2017-02-05 03:47:39 +00:00
+package co.aikar.timings;
+
+import com.google.common.collect.Lists;
+import org.apache.commons.lang.Validate;
+import org.bukkit.Bukkit;
+import org.bukkit.command.CommandSender;
+import org.bukkit.command.ConsoleCommandSender;
+import org.bukkit.command.MessageCommandSender;
+import org.bukkit.command.RemoteConsoleCommandSender;
+
+import java.util.List;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2017-02-05 03:47:39 +00:00
+
+@SuppressWarnings("WeakerAccess")
+public class TimingsReportListener implements MessageCommandSender {
+ private final List<CommandSender> senders;
+ private final Runnable onDone;
2017-02-05 04:07:09 +00:00
+ private String timingsURL;
2017-02-05 03:47:39 +00:00
+
2019-03-20 00:28:15 +00:00
+ public TimingsReportListener(@NotNull CommandSender senders) {
2017-02-05 03:47:39 +00:00
+ this(senders, null);
+ }
2019-03-20 00:28:15 +00:00
+ public TimingsReportListener(@NotNull CommandSender sender, @Nullable Runnable onDone) {
2017-02-05 03:47:39 +00:00
+ this(Lists.newArrayList(sender), onDone);
+ }
2019-03-20 00:28:15 +00:00
+ public TimingsReportListener(@NotNull List<CommandSender> senders) {
2017-02-05 03:47:39 +00:00
+ this(senders, null);
+ }
2019-03-20 00:28:15 +00:00
+ public TimingsReportListener(@NotNull List<CommandSender> senders, @Nullable Runnable onDone) {
2017-02-05 03:47:39 +00:00
+ Validate.notNull(senders);
+ Validate.notEmpty(senders);
+
+ this.senders = Lists.newArrayList(senders);
+ this.onDone = onDone;
+ }
+
2019-03-20 00:28:15 +00:00
+ @Nullable
2017-02-05 04:07:09 +00:00
+ public String getTimingsURL() {
+ return timingsURL;
+ }
+
2017-02-05 03:47:39 +00:00
+ public void done() {
2017-02-05 04:07:09 +00:00
+ done(null);
+ }
+
2019-03-20 00:28:15 +00:00
+ public void done(@Nullable String url) {
2017-02-05 04:07:09 +00:00
+ this.timingsURL = url;
2017-02-05 03:47:39 +00:00
+ if (onDone != null) {
+ onDone.run();
+ }
+ for (CommandSender sender : senders) {
+ if (sender instanceof TimingsReportListener) {
+ ((TimingsReportListener) sender).done();
+ }
+ }
+ }
+
+ @Override
2019-03-20 00:28:15 +00:00
+ public void sendMessage(@NotNull String message) {
2017-02-05 03:47:39 +00:00
+ senders.forEach((sender) -> sender.sendMessage(message));
+ }
+
+ public void addConsoleIfNeeded() {
+ boolean hasConsole = false;
+ for (CommandSender sender : this.senders) {
+ if (sender instanceof ConsoleCommandSender || sender instanceof RemoteConsoleCommandSender) {
+ hasConsole = true;
+ }
+ }
+ if (!hasConsole) {
+ this.senders.add(Bukkit.getConsoleSender());
+ }
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/timings/UnsafeTimingHandler.java b/src/main/java/co/aikar/timings/UnsafeTimingHandler.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..632c4961
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/timings/UnsafeTimingHandler.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,53 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.timings;
2016-01-09 06:32:38 +00:00
+
+import org.bukkit.Bukkit;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
2016-01-09 06:32:38 +00:00
+
+class UnsafeTimingHandler extends TimingHandler {
+
2019-03-20 00:28:15 +00:00
+ UnsafeTimingHandler(@NotNull TimingIdentifier id) {
2016-01-09 06:32:38 +00:00
+ super(id);
+ }
+
+ private static void checkThread() {
+ if (!Bukkit.isPrimaryThread()) {
+ throw new IllegalStateException("Calling Timings from Async Operation");
+ }
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
2016-05-15 21:34:26 +00:00
+ public Timing startTiming() {
2016-01-09 06:32:38 +00:00
+ checkThread();
2016-05-15 21:34:26 +00:00
+ return super.startTiming();
2016-01-09 06:32:38 +00:00
+ }
+
+ @Override
+ public void stopTiming() {
+ checkThread();
+ super.stopTiming();
+ }
+}
2018-07-04 07:55:24 +00:00
diff --git a/src/main/java/co/aikar/util/Counter.java b/src/main/java/co/aikar/util/Counter.java
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..80155072
2018-07-04 07:55:24 +00:00
--- /dev/null
+++ b/src/main/java/co/aikar/util/Counter.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,38 @@
2018-07-04 07:55:24 +00:00
+package co.aikar.util;
+
+import com.google.common.collect.ForwardingMap;
+
+import java.util.HashMap;
+import java.util.Map;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2018-07-04 07:55:24 +00:00
+
+public class Counter <T> extends ForwardingMap<T, Long> {
+ private final Map<T, Long> counts = new HashMap<>();
+
2019-03-20 00:28:15 +00:00
+ public long decrement(@Nullable T key) {
2018-07-04 07:55:24 +00:00
+ return increment(key, -1);
+ }
2019-03-20 00:28:15 +00:00
+ public long increment(@Nullable T key) {
2018-07-04 07:55:24 +00:00
+ return increment(key, 1);
+ }
2019-03-20 00:28:15 +00:00
+ public long decrement(@Nullable T key, long amount) {
2018-07-04 07:55:24 +00:00
+ return decrement(key, -amount);
+ }
2019-03-20 00:28:15 +00:00
+ public long increment(@Nullable T key, long amount) {
2018-07-04 07:55:24 +00:00
+ Long count = this.getCount(key);
+ count += amount;
+ this.counts.put(key, count);
+ return count;
+ }
+
2019-03-20 00:28:15 +00:00
+ public long getCount(@Nullable T key) {
2018-07-04 07:55:24 +00:00
+ return this.counts.getOrDefault(key, 0L);
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2018-07-04 07:55:24 +00:00
+ @Override
+ protected Map<T, Long> delegate() {
+ return this.counts;
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/util/JSONUtil.java b/src/main/java/co/aikar/util/JSONUtil.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..190bf059
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/util/JSONUtil.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,140 @@
2016-01-10 07:33:27 +00:00
+package co.aikar.util;
2016-01-09 06:32:38 +00:00
+
+import com.google.common.base.Function;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+import org.json.simple.JSONArray;
+import org.json.simple.JSONObject;
+
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Provides Utility methods that assist with generating JSON Objects
+ */
+@SuppressWarnings({"rawtypes", "SuppressionAnnotation"})
+public final class JSONUtil {
+ private JSONUtil() {}
+
+ /**
+ * Creates a key/value "JSONPair" object
2017-06-10 22:11:10 +00:00
+ *
+ * @param key Key to use
+ * @param obj Value to use
+ * @return JSONPair
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static JSONPair pair(@NotNull String key, @Nullable Object obj) {
2016-01-09 06:32:38 +00:00
+ return new JSONPair(key, obj);
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static JSONPair pair(long key, @Nullable Object obj) {
2016-01-09 06:32:38 +00:00
+ return new JSONPair(String.valueOf(key), obj);
+ }
+
+ /**
2017-06-10 22:11:10 +00:00
+ * Creates a new JSON object from multiple JSONPair key/value pairs
+ *
+ * @param data JSONPairs
+ * @return Map
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
2019-03-24 21:47:23 +00:00
+ public static Map<String, Object> createObject(@NotNull JSONPair... data) {
2016-01-09 06:32:38 +00:00
+ return appendObjectData(new LinkedHashMap(), data);
+ }
+
+ /**
+ * This appends multiple key/value Obj pairs into a JSON Object
2017-06-10 22:11:10 +00:00
+ *
+ * @param parent Map to be appended to
+ * @param data Data to append
+ * @return Map
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
2019-03-24 21:47:23 +00:00
+ public static Map<String, Object> appendObjectData(@NotNull Map parent, @NotNull JSONPair... data) {
2016-01-09 06:32:38 +00:00
+ for (JSONPair JSONPair : data) {
+ parent.put(JSONPair.key, JSONPair.val);
+ }
+ return parent;
+ }
+
+ /**
+ * This builds a JSON array from a set of data
2017-06-10 22:11:10 +00:00
+ *
+ * @param data Data to build JSON array from
+ * @return List
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static List toArray(@NotNull Object... data) {
2016-01-09 06:32:38 +00:00
+ return Lists.newArrayList(data);
+ }
+
+ /**
+ * These help build a single JSON array using a mapper function
2017-06-10 22:11:10 +00:00
+ *
+ * @param collection Collection to apply to
+ * @param mapper Mapper to apply
+ * @param <E> Element Type
+ * @return List
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <E> List toArrayMapper(@NotNull E[] collection, @NotNull Function<E, Object> mapper) {
2016-01-09 06:32:38 +00:00
+ return toArrayMapper(Lists.newArrayList(collection), mapper);
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <E> List toArrayMapper(@NotNull Iterable<E> collection, @NotNull Function<E, Object> mapper) {
2016-01-09 06:32:38 +00:00
+ List array = Lists.newArrayList();
+ for (E e : collection) {
+ Object object = mapper.apply(e);
+ if (object != null) {
+ array.add(object);
+ }
+ }
+ return array;
+ }
+
+ /**
+ * These help build a single JSON Object from a collection, using a mapper function
2017-06-10 22:11:10 +00:00
+ *
+ * @param collection Collection to apply to
+ * @param mapper Mapper to apply
+ * @param <E> Element Type
+ * @return Map
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <E> Map toObjectMapper(@NotNull E[] collection, @NotNull Function<E, JSONPair> mapper) {
2016-01-09 06:32:38 +00:00
+ return toObjectMapper(Lists.newArrayList(collection), mapper);
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <E> Map toObjectMapper(@NotNull Iterable<E> collection, @NotNull Function<E, JSONPair> mapper) {
2016-01-09 06:32:38 +00:00
+ Map object = Maps.newLinkedHashMap();
+ for (E e : collection) {
+ JSONPair JSONPair = mapper.apply(e);
+ if (JSONPair != null) {
+ object.put(JSONPair.key, JSONPair.val);
+ }
+ }
+ return object;
+ }
+
+ /**
+ * Simply stores a key and a value, used internally by many methods below.
+ */
+ @SuppressWarnings("PublicInnerClass")
+ public static class JSONPair {
+ final String key;
+ final Object val;
+
2019-03-20 00:28:15 +00:00
+ JSONPair(@NotNull String key, @NotNull Object val) {
2016-01-09 06:32:38 +00:00
+ this.key = key;
+ this.val = val;
+ }
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/util/LoadingIntMap.java b/src/main/java/co/aikar/util/LoadingIntMap.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..63a899c7
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/util/LoadingIntMap.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,76 @@
2016-01-09 06:32:38 +00:00
+/*
+ * Copyright (c) 2015. Starlis LLC / dba Empire Minecraft
+ *
+ * This source code is proprietary software and must not be redistributed without Starlis LLC's approval
+ *
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.util;
2016-01-09 06:32:38 +00:00
+
+
+import com.google.common.base.Function;
2016-03-30 05:59:47 +00:00
+import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+
+/**
2016-01-21 23:30:05 +00:00
+ * Allows you to pass a Loader function that when a key is accessed that doesn't exist,
2016-01-09 06:32:38 +00:00
+ * automatically loads the entry into the map by calling the loader Function.
+ *
+ * .get() Will only return null if the Loader can return null.
+ *
+ * You may pass any backing Map to use.
+ *
+ * This class is not thread safe and should be wrapped with Collections.synchronizedMap on the OUTSIDE of the LoadingMap if needed.
+ *
+ * Do not wrap the backing map with Collections.synchronizedMap.
+ *
+ * @param <V> Value
+ */
2016-03-30 05:59:47 +00:00
+public class LoadingIntMap<V> extends Int2ObjectOpenHashMap<V> {
2016-01-09 06:32:38 +00:00
+ private final Function<Integer, V> loader;
+
2019-03-20 00:28:15 +00:00
+ public LoadingIntMap(@NotNull Function<Integer, V> loader) {
2016-03-30 05:59:47 +00:00
+ super();
+ this.loader = loader;
+ }
+
2019-03-20 00:28:15 +00:00
+ public LoadingIntMap(int expectedSize, @NotNull Function<Integer, V> loader) {
2016-03-30 05:59:47 +00:00
+ super(expectedSize);
+ this.loader = loader;
+ }
+
2019-03-20 00:28:15 +00:00
+ public LoadingIntMap(int expectedSize, float loadFactor, @NotNull Function<Integer, V> loader) {
2016-03-30 05:59:47 +00:00
+ super(expectedSize, loadFactor);
2016-01-09 06:32:38 +00:00
+ this.loader = loader;
+ }
+
+
2019-03-20 00:28:15 +00:00
+ @Nullable
2016-01-09 06:32:38 +00:00
+ @Override
+ public V get(int key) {
+ V res = super.get(key);
+ if (res == null) {
+ res = loader.apply(key);
+ if (res != null) {
+ put(key, res);
+ }
+ }
+ return res;
+ }
+
+ /**
+ * Due to java stuff, you will need to cast it to (Function) for some cases
2017-06-10 22:11:10 +00:00
+ *
+ * @param <T> Type
2016-01-09 06:32:38 +00:00
+ */
+ public abstract static class Feeder <T> implements Function<T, T> {
2019-03-20 00:28:15 +00:00
+ @Nullable
2016-01-09 06:32:38 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ public T apply(@Nullable Object input) {
2016-01-09 06:32:38 +00:00
+ return apply();
+ }
+
2019-03-20 00:28:15 +00:00
+ @Nullable
2016-01-09 06:32:38 +00:00
+ public abstract T apply();
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/util/LoadingMap.java b/src/main/java/co/aikar/util/LoadingMap.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..aedbb033
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/util/LoadingMap.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,368 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.util;
2016-01-09 06:32:38 +00:00
+
2019-03-20 00:28:15 +00:00
+import com.google.common.base.Preconditions;
2016-01-09 06:32:38 +00:00
+import java.lang.reflect.Constructor;
+import java.util.AbstractMap;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.IdentityHashMap;
+import java.util.Map;
+import java.util.Set;
2018-10-18 01:59:35 +00:00
+import java.util.function.Function;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+
+/**
+ * Allows you to pass a Loader function that when a key is accessed that doesn't exists,
+ * automatically loads the entry into the map by calling the loader Function.
+ *
+ * .get() Will only return null if the Loader can return null.
+ *
+ * You may pass any backing Map to use.
+ *
+ * This class is not thread safe and should be wrapped with Collections.synchronizedMap on the OUTSIDE of the LoadingMap if needed.
+ *
+ * Do not wrap the backing map with Collections.synchronizedMap.
+ *
+ * @param <K> Key
+ * @param <V> Value
+ */
2018-10-18 01:59:35 +00:00
+public class LoadingMap <K, V> extends AbstractMap<K, V> {
2016-01-09 06:32:38 +00:00
+ private final Map<K, V> backingMap;
2018-10-18 01:59:35 +00:00
+ private final java.util.function.Function<K, V> loader;
2016-01-09 06:32:38 +00:00
+
+ /**
+ * Initializes an auto loading map using specified loader and backing map
2017-06-10 22:11:10 +00:00
+ * @param backingMap Map to wrap
+ * @param loader Loader
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ public LoadingMap(@NotNull Map<K, V> backingMap, @NotNull java.util.function.Function<K, V> loader) {
2016-01-09 06:32:38 +00:00
+ this.backingMap = backingMap;
+ this.loader = loader;
+ }
+
+ /**
+ * Creates a new LoadingMap with the specified map and loader
2017-06-10 22:11:10 +00:00
+ *
+ * @param backingMap Actual map being used.
+ * @param loader Loader to use
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> of(@NotNull Map<K, V> backingMap, @NotNull Function<K, V> loader) {
2018-10-18 01:59:35 +00:00
+ return new LoadingMap<>(backingMap, loader);
2016-01-09 06:32:38 +00:00
+ }
+
+ /**
+ * Creates a LoadingMap with an auto instantiating loader.
+ *
+ * Will auto construct class of of Value when not found
+ *
+ * Since this uses Reflection, It is more effecient to define your own static loader
+ * than using this helper, but if performance is not critical, this is easier.
+ *
+ * @param backingMap Actual map being used.
+ * @param keyClass Class used for the K generic
+ * @param valueClass Class used for the V generic
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map that auto instantiates on .get()
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newAutoMap(@NotNull Map<K, V> backingMap, @Nullable final Class<? extends K> keyClass,
+ @NotNull final Class<? extends V> valueClass) {
2018-10-18 01:59:35 +00:00
+ return new LoadingMap<>(backingMap, new AutoInstantiatingLoader<>(keyClass, valueClass));
2016-01-09 06:32:38 +00:00
+ }
+ /**
+ * Creates a LoadingMap with an auto instantiating loader.
+ *
+ * Will auto construct class of of Value when not found
+ *
+ * Since this uses Reflection, It is more effecient to define your own static loader
+ * than using this helper, but if performance is not critical, this is easier.
+ *
+ * @param backingMap Actual map being used.
+ * @param valueClass Class used for the V generic
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map that auto instantiates on .get()
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newAutoMap(@NotNull Map<K, V> backingMap,
+ @NotNull final Class<? extends V> valueClass) {
2016-01-09 06:32:38 +00:00
+ return newAutoMap(backingMap, null, valueClass);
+ }
+
+ /**
+ * @see #newAutoMap
+ *
+ * new Auto initializing map using a HashMap.
2017-06-10 22:11:10 +00:00
+ *
+ * @param keyClass Class used for the K generic
+ * @param valueClass Class used for the V generic
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map that auto instantiates on .get()
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newHashAutoMap(@Nullable final Class<? extends K> keyClass, @NotNull final Class<? extends V> valueClass) {
2018-10-18 01:59:35 +00:00
+ return newAutoMap(new HashMap<>(), keyClass, valueClass);
2016-01-09 06:32:38 +00:00
+ }
+
+ /**
+ * @see #newAutoMap
+ *
+ * new Auto initializing map using a HashMap.
2017-06-10 22:11:10 +00:00
+ *
+ * @param valueClass Class used for the V generic
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map that auto instantiates on .get()
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newHashAutoMap(@NotNull final Class<? extends V> valueClass) {
2016-01-09 06:32:38 +00:00
+ return newHashAutoMap(null, valueClass);
+ }
+
+ /**
+ * @see #newAutoMap
+ *
+ * new Auto initializing map using a HashMap.
+ *
2017-06-10 22:11:10 +00:00
+ * @param keyClass Class used for the K generic
+ * @param valueClass Class used for the V generic
+ * @param initialCapacity Initial capacity to use
+ * @param loadFactor Load factor to use
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map that auto instantiates on .get()
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newHashAutoMap(@Nullable final Class<? extends K> keyClass, @NotNull final Class<? extends V> valueClass, int initialCapacity, float loadFactor) {
2018-10-18 01:59:35 +00:00
+ return newAutoMap(new HashMap<>(initialCapacity, loadFactor), keyClass, valueClass);
2016-01-09 06:32:38 +00:00
+ }
+
+ /**
+ * @see #newAutoMap
+ *
+ * new Auto initializing map using a HashMap.
+ *
2017-06-10 22:11:10 +00:00
+ * @param valueClass Class used for the V generic
+ * @param initialCapacity Initial capacity to use
+ * @param loadFactor Load factor to use
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map that auto instantiates on .get()
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newHashAutoMap(@NotNull final Class<? extends V> valueClass, int initialCapacity, float loadFactor) {
2016-01-09 06:32:38 +00:00
+ return newHashAutoMap(null, valueClass, initialCapacity, loadFactor);
+ }
+
+ /**
+ * Initializes an auto loading map using a HashMap
2017-06-10 22:11:10 +00:00
+ *
+ * @param loader Loader to use
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newHashMap(@NotNull Function<K, V> loader) {
2018-10-18 01:59:35 +00:00
+ return new LoadingMap<>(new HashMap<>(), loader);
2016-01-09 06:32:38 +00:00
+ }
+
+ /**
+ * Initializes an auto loading map using a HashMap
2017-06-10 22:11:10 +00:00
+ *
+ * @param loader Loader to use
+ * @param initialCapacity Initial capacity to use
2018-10-18 01:59:35 +00:00
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newHashMap(@NotNull Function<K, V> loader, int initialCapacity) {
2018-10-18 01:59:35 +00:00
+ return new LoadingMap<>(new HashMap<>(initialCapacity), loader);
+ }
+ /**
+ * Initializes an auto loading map using a HashMap
+ *
+ * @param loader Loader to use
+ * @param initialCapacity Initial capacity to use
2017-06-10 22:11:10 +00:00
+ * @param loadFactor Load factor to use
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newHashMap(@NotNull Function<K, V> loader, int initialCapacity, float loadFactor) {
2018-10-18 01:59:35 +00:00
+ return new LoadingMap<>(new HashMap<>(initialCapacity, loadFactor), loader);
2016-01-09 06:32:38 +00:00
+ }
+
+ /**
+ * Initializes an auto loading map using an Identity HashMap
2017-06-10 22:11:10 +00:00
+ *
+ * @param loader Loader to use
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newIdentityHashMap(@NotNull Function<K, V> loader) {
2018-10-18 01:59:35 +00:00
+ return new LoadingMap<>(new IdentityHashMap<>(), loader);
2016-01-09 06:32:38 +00:00
+ }
+
+ /**
+ * Initializes an auto loading map using an Identity HashMap
2017-06-10 22:11:10 +00:00
+ *
+ * @param loader Loader to use
+ * @param initialCapacity Initial capacity to use
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> newIdentityHashMap(@NotNull Function<K, V> loader, int initialCapacity) {
2018-10-18 01:59:35 +00:00
+ return new LoadingMap<>(new IdentityHashMap<>(initialCapacity), loader);
2016-01-09 06:32:38 +00:00
+ }
+
+ @Override
+ public int size() {return backingMap.size();}
+
+ @Override
+ public boolean isEmpty() {return backingMap.isEmpty();}
+
+ @Override
2019-03-20 00:28:15 +00:00
+ public boolean containsKey(@Nullable Object key) {return backingMap.containsKey(key);}
2016-01-09 06:32:38 +00:00
+
+ @Override
2019-03-20 00:28:15 +00:00
+ public boolean containsValue(@Nullable Object value) {return backingMap.containsValue(value);}
2016-01-09 06:32:38 +00:00
+
2019-03-20 00:28:15 +00:00
+ @Nullable
2016-01-09 06:32:38 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ public V get(@Nullable Object key) {
2019-02-23 19:22:43 +00:00
+ V v = backingMap.get(key);
+ if (v != null) {
+ return v;
+ }
2018-10-18 01:59:35 +00:00
+ return backingMap.computeIfAbsent((K) key, loader);
2016-01-09 06:32:38 +00:00
+ }
+
2019-03-20 00:28:15 +00:00
+ @Nullable
+ public V put(@Nullable K key, @Nullable V value) {return backingMap.put(key, value);}
2016-01-09 06:32:38 +00:00
+
2019-03-20 00:28:15 +00:00
+ @Nullable
2016-01-09 06:32:38 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ public V remove(@Nullable Object key) {return backingMap.remove(key);}
2016-01-09 06:32:38 +00:00
+
2019-03-20 00:28:15 +00:00
+ public void putAll(@NotNull Map<? extends K, ? extends V> m) {backingMap.putAll(m);}
2016-01-09 06:32:38 +00:00
+
+ @Override
+ public void clear() {backingMap.clear();}
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
+ public Set<K> keySet() {return backingMap.keySet();}
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
+ public Collection<V> values() {return backingMap.values();}
+
+ @Override
2019-03-20 00:28:15 +00:00
+ public boolean equals(@Nullable Object o) {return backingMap.equals(o);}
2016-01-09 06:32:38 +00:00
+
+ @Override
+ public int hashCode() {return backingMap.hashCode();}
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
+ public Set<Entry<K, V>> entrySet() {
+ return backingMap.entrySet();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ public LoadingMap<K, V> clone() {
2018-10-18 01:59:35 +00:00
+ return new LoadingMap<>(backingMap, loader);
2016-01-09 06:32:38 +00:00
+ }
+
+ private static class AutoInstantiatingLoader<K, V> implements Function<K, V> {
+ final Constructor<? extends V> constructor;
+ private final Class<? extends V> valueClass;
+
2019-03-20 00:28:15 +00:00
+ AutoInstantiatingLoader(@Nullable Class<? extends K> keyClass, @NotNull Class<? extends V> valueClass) {
2016-01-09 06:32:38 +00:00
+ try {
+ this.valueClass = valueClass;
+ if (keyClass != null) {
+ constructor = valueClass.getConstructor(keyClass);
+ } else {
+ constructor = null;
+ }
+ } catch (NoSuchMethodException e) {
+ throw new IllegalStateException(
+ valueClass.getName() + " does not have a constructor for " + (keyClass != null ? keyClass.getName() : null));
+ }
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ public V apply(@Nullable K input) {
2016-01-09 06:32:38 +00:00
+ try {
+ return (constructor != null ? constructor.newInstance(input) : valueClass.newInstance());
+ } catch (Exception e) {
+ throw new ExceptionInInitializerError(e);
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ return super.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object object) {
+ return false;
+ }
+ }
+
+ /**
+ * Due to java stuff, you will need to cast it to (Function) for some cases
2017-06-10 22:11:10 +00:00
+ *
+ * @param <T> Type
2016-01-09 06:32:38 +00:00
+ */
+ public abstract static class Feeder <T> implements Function<T, T> {
2019-03-20 00:28:15 +00:00
+ @Nullable
2016-01-09 06:32:38 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ public T apply(@Nullable Object input) {
2016-01-09 06:32:38 +00:00
+ return apply();
+ }
+
2019-03-20 00:28:15 +00:00
+ @Nullable
2016-01-09 06:32:38 +00:00
+ public abstract T apply();
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/co/aikar/util/MRUMapCache.java b/src/main/java/co/aikar/util/MRUMapCache.java
2016-01-09 06:32:38 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..5989ee21
2016-01-09 06:32:38 +00:00
--- /dev/null
2016-01-10 07:33:27 +00:00
+++ b/src/main/java/co/aikar/util/MRUMapCache.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,111 @@
2016-01-09 06:32:38 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
2016-01-10 07:33:27 +00:00
+package co.aikar.util;
2016-01-09 06:32:38 +00:00
+
+import java.util.AbstractMap;
+import java.util.Collection;
+import java.util.Map;
+import java.util.Set;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
2016-01-09 06:32:38 +00:00
+
+/**
+ * Implements a Most Recently Used cache in front of a backing map, to quickly access the last accessed result.
2017-06-10 22:11:10 +00:00
+ *
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
2016-01-09 06:32:38 +00:00
+ */
+public class MRUMapCache<K, V> extends AbstractMap<K, V> {
+ final Map<K, V> backingMap;
+ Object cacheKey;
+ V cacheValue;
2019-03-20 00:28:15 +00:00
+ public MRUMapCache(@NotNull final Map<K, V> backingMap) {
2016-01-09 06:32:38 +00:00
+ this.backingMap = backingMap;
+ }
+
+ public int size() {return backingMap.size();}
+
+ public boolean isEmpty() {return backingMap.isEmpty();}
+
2019-03-20 00:28:15 +00:00
+ public boolean containsKey(@Nullable Object key) {
2016-01-09 06:32:38 +00:00
+ return key != null && key.equals(cacheKey) || backingMap.containsKey(key);
+ }
+
2019-03-20 00:28:15 +00:00
+ public boolean containsValue(@Nullable Object value) {
2016-01-09 06:32:38 +00:00
+ return value != null && value == cacheValue || backingMap.containsValue(value);
+ }
+
2019-03-20 00:28:15 +00:00
+ @Nullable
+ public V get(@Nullable Object key) {
2016-01-09 06:32:38 +00:00
+ if (cacheKey != null && cacheKey.equals(key)) {
+ return cacheValue;
+ }
+ cacheKey = key;
+ return cacheValue = backingMap.get(key);
+ }
+
2019-03-20 00:28:15 +00:00
+ @Nullable
+ public V put(@Nullable K key, @Nullable V value) {
2016-01-09 06:32:38 +00:00
+ cacheKey = key;
+ return cacheValue = backingMap.put(key, value);
+ }
+
2019-03-20 00:28:15 +00:00
+ @Nullable
+ public V remove(@Nullable Object key) {
2016-01-09 06:32:38 +00:00
+ if (key != null && key.equals(cacheKey)) {
+ cacheKey = null;
+ }
+ return backingMap.remove(key);
+ }
+
2019-03-20 00:28:15 +00:00
+ public void putAll(@NotNull Map<? extends K, ? extends V> m) {backingMap.putAll(m);}
2016-01-09 06:32:38 +00:00
+
+ public void clear() {
+ cacheKey = null;
+ cacheValue = null;
+ backingMap.clear();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ public Set<K> keySet() {return backingMap.keySet();}
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ public Collection<V> values() {return backingMap.values();}
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-09 06:32:38 +00:00
+ public Set<Map.Entry<K, V>> entrySet() {return backingMap.entrySet();}
+
+ /**
+ * Wraps the specified map with a most recently used cache
2017-06-10 22:11:10 +00:00
+ *
+ * @param map Map to be wrapped
+ * @param <K> Key Type of the Map
+ * @param <V> Value Type of the Map
+ * @return Map
2016-01-09 06:32:38 +00:00
+ */
2019-03-20 00:28:15 +00:00
+ @NotNull
+ public static <K, V> Map<K, V> of(@NotNull Map<K, V> map) {
2016-01-09 06:32:38 +00:00
+ return new MRUMapCache<K, V>(map);
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/org/bukkit/Bukkit.java b/src/main/java/org/bukkit/Bukkit.java
2019-07-11 16:59:21 +00:00
index 0822b8e5..940c643d 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/Bukkit.java
+++ b/src/main/java/org/bukkit/Bukkit.java
2019-05-06 07:20:16 +00:00
@@ -574,7 +574,6 @@ public final class Bukkit {
2016-01-10 07:33:27 +00:00
*/
public static void reload() {
server.reload();
- org.spigotmc.CustomTimingsHandler.reload(); // Spigot
}
/**
diff --git a/src/main/java/org/bukkit/Server.java b/src/main/java/org/bukkit/Server.java
2019-07-11 16:59:21 +00:00
index 11c5c205..c197e381 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/Server.java
+++ b/src/main/java/org/bukkit/Server.java
2019-05-14 02:20:58 +00:00
@@ -1250,6 +1250,26 @@ public interface Server extends PluginMessageRecipient {
2016-01-10 07:33:27 +00:00
throw new UnsupportedOperationException( "Not supported yet." );
}
2019-03-20 00:28:15 +00:00
+ // Paper start
+ @NotNull
2016-01-10 07:33:27 +00:00
+ public org.bukkit.configuration.file.YamlConfiguration getBukkitConfig()
+ {
+ throw new UnsupportedOperationException( "Not supported yet." );
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-01-10 07:33:27 +00:00
+ public org.bukkit.configuration.file.YamlConfiguration getSpigotConfig()
+ {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2016-02-29 23:09:49 +00:00
+ public org.bukkit.configuration.file.YamlConfiguration getPaperConfig()
2016-01-10 07:33:27 +00:00
+ {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
2019-03-20 00:28:15 +00:00
+ // Paper end
2016-01-10 07:33:27 +00:00
+
/**
* Sends the component to the player
*
2019-05-06 07:20:16 +00:00
diff --git a/src/main/java/org/bukkit/UnsafeValues.java b/src/main/java/org/bukkit/UnsafeValues.java
2019-07-11 16:59:21 +00:00
index 247d194f..72c5501e 100644
2019-05-06 07:20:16 +00:00
--- a/src/main/java/org/bukkit/UnsafeValues.java
+++ b/src/main/java/org/bukkit/UnsafeValues.java
@@ -69,4 +69,12 @@ public interface UnsafeValues {
* @return true if a file matching this key was found and deleted
*/
boolean removeAdvancement(NamespacedKey key);
+
+ // Paper start
+ /**
+ * Server name to report to timings v2
+ * @return name
+ */
+ String getTimingsServerName();
+ // Paper end
}
2017-02-05 03:47:39 +00:00
diff --git a/src/main/java/org/bukkit/command/BufferedCommandSender.java b/src/main/java/org/bukkit/command/BufferedCommandSender.java
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..f9a00aec
2017-02-05 03:47:39 +00:00
--- /dev/null
+++ b/src/main/java/org/bukkit/command/BufferedCommandSender.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,21 @@
2017-02-05 03:47:39 +00:00
+package org.bukkit.command;
+
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
+
2017-02-05 03:47:39 +00:00
+public class BufferedCommandSender implements MessageCommandSender {
+ private final StringBuffer buffer = new StringBuffer();
+ @Override
2019-03-20 00:28:15 +00:00
+ public void sendMessage(@NotNull String message) {
2017-02-05 03:47:39 +00:00
+ buffer.append(message);
+ buffer.append("\n");
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2017-02-05 03:47:39 +00:00
+ public String getBuffer() {
+ return buffer.toString();
+ }
+
+ public void reset() {
+ this.buffer.setLength(0);
+ }
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/org/bukkit/command/Command.java b/src/main/java/org/bukkit/command/Command.java
2019-07-11 16:59:21 +00:00
index 4bfc2146..03bdc162 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/command/Command.java
+++ b/src/main/java/org/bukkit/command/Command.java
2019-04-23 04:47:07 +00:00
@@ -33,7 +33,8 @@ public abstract class Command {
2016-01-10 07:33:27 +00:00
protected String usageMessage;
private String permission;
private String permissionMessage;
- public org.spigotmc.CustomTimingsHandler timings; // Spigot
2019-03-20 00:28:15 +00:00
+ public co.aikar.timings.Timing timings; // Paper
+ @NotNull public String getTimingName() {return getName();} // Paper
2016-01-10 07:33:27 +00:00
2019-03-20 00:28:15 +00:00
protected Command(@NotNull String name) {
2016-01-10 07:33:27 +00:00
this(name, "", "/" + name, new ArrayList<String>());
2019-04-23 04:47:07 +00:00
@@ -47,7 +48,6 @@ public abstract class Command {
2019-03-20 00:28:15 +00:00
this.usageMessage = (usageMessage == null) ? "/" + name : usageMessage;
2016-01-10 07:33:27 +00:00
this.aliases = aliases;
this.activeAliases = new ArrayList<String>(aliases);
- this.timings = new org.spigotmc.CustomTimingsHandler("** Command: " + name); // Spigot
}
/**
2019-04-23 04:47:07 +00:00
@@ -245,7 +245,6 @@ public abstract class Command {
2019-03-20 00:28:15 +00:00
}
2016-01-10 07:33:27 +00:00
this.nextLabel = name;
if (!isRegistered()) {
- this.timings = new org.spigotmc.CustomTimingsHandler("** Command: " + name); // Spigot
this.label = name;
return true;
}
diff --git a/src/main/java/org/bukkit/command/FormattedCommandAlias.java b/src/main/java/org/bukkit/command/FormattedCommandAlias.java
2019-07-11 16:59:21 +00:00
index d6c8938b..a6ad94ef 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/command/FormattedCommandAlias.java
+++ b/src/main/java/org/bukkit/command/FormattedCommandAlias.java
2019-04-23 04:47:07 +00:00
@@ -9,6 +9,7 @@ public class FormattedCommandAlias extends Command {
2016-01-10 07:33:27 +00:00
2019-03-20 00:28:15 +00:00
public FormattedCommandAlias(@NotNull String alias, @NotNull String[] formatStrings) {
2016-01-10 07:33:27 +00:00
super(alias);
+ timings = co.aikar.timings.TimingsManager.getCommandTiming("minecraft", this); // Spigot
this.formatStrings = formatStrings;
}
2019-04-23 04:47:07 +00:00
@@ -113,6 +114,10 @@ public class FormattedCommandAlias extends Command {
2016-01-10 07:33:27 +00:00
return formatString;
}
2019-03-20 00:28:15 +00:00
+ @NotNull
+ @Override // Paper
+ public String getTimingName() {return "Command Forwarder - " + super.getTimingName();} // Paper
2016-01-10 07:33:27 +00:00
+
private static boolean inRange(int i, int j, int k) {
return i >= j && i <= k;
}
2017-02-05 03:47:39 +00:00
diff --git a/src/main/java/org/bukkit/command/MessageCommandSender.java b/src/main/java/org/bukkit/command/MessageCommandSender.java
2017-02-05 01:46:27 +00:00
new file mode 100644
2019-07-11 16:59:21 +00:00
index 00000000..ca1893e9
2017-02-05 01:46:27 +00:00
--- /dev/null
2017-02-05 03:47:39 +00:00
+++ b/src/main/java/org/bukkit/command/MessageCommandSender.java
2019-03-20 00:28:15 +00:00
@@ -0,0 +1,114 @@
2017-02-05 01:46:27 +00:00
+package org.bukkit.command;
+
+import org.apache.commons.lang.NotImplementedException;
+import org.bukkit.Bukkit;
+import org.bukkit.Server;
+import org.bukkit.permissions.Permission;
+import org.bukkit.permissions.PermissionAttachment;
+import org.bukkit.permissions.PermissionAttachmentInfo;
+import org.bukkit.plugin.Plugin;
+
+import java.util.Set;
2019-03-20 00:28:15 +00:00
+import org.jetbrains.annotations.NotNull;
2017-02-05 01:46:27 +00:00
+
+/**
2017-02-05 03:47:39 +00:00
+ * For when all you care about is just messaging
2017-02-05 01:46:27 +00:00
+ */
2017-02-05 03:47:39 +00:00
+public interface MessageCommandSender extends CommandSender {
2017-02-05 01:46:27 +00:00
+
+ @Override
2019-03-20 00:28:15 +00:00
+ default void sendMessage(@NotNull String[] messages) {
2017-02-05 03:47:39 +00:00
+ for (String message : messages) {
+ sendMessage(message);
+ }
2017-02-05 01:46:27 +00:00
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2017-02-05 01:46:27 +00:00
+ @Override
2017-02-05 03:47:39 +00:00
+ default Server getServer() {
2017-02-05 01:46:27 +00:00
+ return Bukkit.getServer();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2017-02-05 01:46:27 +00:00
+ @Override
2017-02-05 03:47:39 +00:00
+ default String getName() {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
+ @Override
2017-02-05 03:47:39 +00:00
+ default boolean isOp() {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
+ @Override
2017-02-05 03:47:39 +00:00
+ default void setOp(boolean value) {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
+ @Override
2019-03-20 00:28:15 +00:00
+ default boolean isPermissionSet(@NotNull String name) {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
+ @Override
2019-03-20 00:28:15 +00:00
+ default boolean isPermissionSet(@NotNull Permission perm) {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
+ @Override
2019-03-20 00:28:15 +00:00
+ default boolean hasPermission(@NotNull String name) {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
+ @Override
2019-03-20 00:28:15 +00:00
+ default boolean hasPermission(@NotNull Permission perm) {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2017-02-05 01:46:27 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ default PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value) {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2017-02-05 01:46:27 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ default PermissionAttachment addAttachment(@NotNull Plugin plugin) {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2017-02-05 01:46:27 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ default PermissionAttachment addAttachment(@NotNull Plugin plugin, @NotNull String name, boolean value, int ticks) {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2017-02-05 01:46:27 +00:00
+ @Override
2019-03-20 00:28:15 +00:00
+ default PermissionAttachment addAttachment(@NotNull Plugin plugin, int ticks) {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
+ @Override
2019-03-20 00:28:15 +00:00
+ default void removeAttachment(@NotNull PermissionAttachment attachment) {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
+ @Override
2017-02-05 03:47:39 +00:00
+ default void recalculatePermissions() {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2017-02-05 01:46:27 +00:00
+ @Override
2017-02-05 03:47:39 +00:00
+ default Set<PermissionAttachmentInfo> getEffectivePermissions() {
2017-02-05 01:46:27 +00:00
+ throw new NotImplementedException();
+ }
2017-05-15 16:25:20 +00:00
+
2019-03-20 00:28:15 +00:00
+ @NotNull
2017-05-15 16:25:20 +00:00
+ @Override
+ default Spigot spigot() {
+ throw new NotImplementedException();
+ }
+
2017-02-05 01:46:27 +00:00
+}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/org/bukkit/command/SimpleCommandMap.java b/src/main/java/org/bukkit/command/SimpleCommandMap.java
2019-07-11 16:59:21 +00:00
index 81e4fa57..f020cb04 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/command/SimpleCommandMap.java
+++ b/src/main/java/org/bukkit/command/SimpleCommandMap.java
2019-04-23 04:47:07 +00:00
@@ -15,7 +15,6 @@ import org.bukkit.command.defaults.BukkitCommand;
import org.bukkit.command.defaults.HelpCommand;
import org.bukkit.command.defaults.PluginsCommand;
import org.bukkit.command.defaults.ReloadCommand;
-import org.bukkit.command.defaults.TimingsCommand;
import org.bukkit.command.defaults.VersionCommand;
import org.bukkit.entity.Player;
import org.bukkit.util.StringUtil;
@@ -35,7 +34,7 @@ public class SimpleCommandMap implements CommandMap {
2016-01-10 07:33:27 +00:00
register("bukkit", new VersionCommand("version"));
register("bukkit", new ReloadCommand("reload"));
register("bukkit", new PluginsCommand("plugins"));
- register("bukkit", new TimingsCommand("timings"));
2019-03-20 00:28:15 +00:00
+ register("bukkit", new co.aikar.timings.TimingsCommand("timings")); // Paper
2016-01-10 07:33:27 +00:00
}
public void setFallbackCommands() {
2019-05-06 02:58:04 +00:00
@@ -67,6 +66,7 @@ public class SimpleCommandMap implements CommandMap {
2016-01-10 07:33:27 +00:00
*/
2019-05-06 02:58:04 +00:00
@Override
2019-03-20 00:28:15 +00:00
public boolean register(@NotNull String label, @NotNull String fallbackPrefix, @NotNull Command command) {
+ command.timings = co.aikar.timings.TimingsManager.getCommandTiming(fallbackPrefix, command); // Paper
2016-06-26 19:13:00 +00:00
label = label.toLowerCase(java.util.Locale.ENGLISH).trim();
fallbackPrefix = fallbackPrefix.toLowerCase(java.util.Locale.ENGLISH).trim();
2016-01-10 07:33:27 +00:00
boolean registered = register(label, command, false, fallbackPrefix);
2019-05-06 02:58:04 +00:00
@@ -143,16 +143,22 @@ public class SimpleCommandMap implements CommandMap {
2016-05-13 05:13:38 +00:00
return false;
}
+ // Paper start - Plugins do weird things to workaround normal registration
+ if (target.timings == null) {
+ target.timings = co.aikar.timings.TimingsManager.getCommandTiming(null, target);
+ }
+ // Paper end
+
try {
2019-03-26 04:31:34 +00:00
- target.timings.startTiming(); // Spigot
+ try (co.aikar.timings.Timing ignored = target.timings.startTiming()) { // Paper - use try with resources
2016-05-13 05:13:38 +00:00
// Note: we don't return the result of target.execute as thats success / failure, we return handled (true) or not handled (false)
2019-03-26 04:31:34 +00:00
target.execute(sender, sentCommandLabel, Arrays.copyOfRange(args, 1, args.length));
- target.timings.stopTiming(); // Spigot
+ } // target.timings.stopTiming(); // Spigot // Paper
} catch (CommandException ex) {
- target.timings.stopTiming(); // Spigot
+ //target.timings.stopTiming(); // Spigot // Paper
throw ex;
} catch (Throwable ex) {
- target.timings.stopTiming(); // Spigot
+ //target.timings.stopTiming(); // Spigot // Paper
throw new CommandException("Unhandled exception executing '" + commandLine + "' in " + target, ex);
}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/org/bukkit/command/defaults/TimingsCommand.java b/src/main/java/org/bukkit/command/defaults/TimingsCommand.java
2016-02-29 23:09:49 +00:00
deleted file mode 100644
2019-07-11 16:59:21 +00:00
index 6023e4f6..00000000
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/command/defaults/TimingsCommand.java
2016-02-29 23:09:49 +00:00
+++ /dev/null
2019-04-23 04:47:07 +00:00
@@ -1,253 +0,0 @@
2016-02-29 23:09:49 +00:00
-package org.bukkit.command.defaults;
-
2019-04-23 04:47:07 +00:00
-import com.google.common.collect.ImmutableList;
2016-02-29 23:09:49 +00:00
-import java.io.File;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.List;
-import org.apache.commons.lang.Validate;
-import org.bukkit.Bukkit;
-import org.bukkit.ChatColor;
-import org.bukkit.command.CommandSender;
-import org.bukkit.event.Event;
-import org.bukkit.event.HandlerList;
-import org.bukkit.plugin.Plugin;
-import org.bukkit.plugin.RegisteredListener;
-import org.bukkit.plugin.TimedRegisteredListener;
-import org.bukkit.util.StringUtil;
2019-03-20 00:28:15 +00:00
-import org.jetbrains.annotations.NotNull;
2016-02-29 23:09:49 +00:00
-
-// Spigot start
2019-04-23 04:47:07 +00:00
-// CHECKSTYLE:OFF
2016-02-29 23:09:49 +00:00
-import java.io.ByteArrayOutputStream;
-import java.io.OutputStream;
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.util.logging.Level;
-import org.bukkit.command.RemoteConsoleCommandSender;
-import org.bukkit.plugin.SimplePluginManager;
-import org.spigotmc.CustomTimingsHandler;
2019-04-23 04:47:07 +00:00
-// CHECKSTYLE:ON
2016-02-29 23:09:49 +00:00
-// Spigot end
-
-public class TimingsCommand extends BukkitCommand {
2016-01-10 07:33:27 +00:00
- private static final List<String> TIMINGS_SUBCOMMANDS = ImmutableList.of("report", "reset", "on", "off", "paste"); // Spigot
- public static long timingStart = 0; // Spigot
2016-02-29 23:09:49 +00:00
-
2019-03-20 00:28:15 +00:00
- public TimingsCommand(@NotNull String name) {
2016-02-29 23:09:49 +00:00
- super(name);
2016-01-10 07:33:27 +00:00
- this.description = "Manages Spigot Timings data to see performance of the server."; // Spigot
- this.usageMessage = "/timings <reset|report|on|off|paste>"; // Spigot
2016-02-29 23:09:49 +00:00
- this.setPermission("bukkit.command.timings");
- }
-
2016-01-10 07:33:27 +00:00
- // Spigot start - redesigned Timings Command
2019-03-20 00:28:15 +00:00
- public void executeSpigotTimings(@NotNull CommandSender sender, @NotNull String[] args) {
2016-01-10 07:33:27 +00:00
- if ( "on".equals( args[0] ) )
- {
- ( (SimplePluginManager) Bukkit.getPluginManager() ).useTimings( true );
- CustomTimingsHandler.reload();
- sender.sendMessage( "Enabled Timings & Reset" );
- return;
- } else if ( "off".equals( args[0] ) )
- {
- ( (SimplePluginManager) Bukkit.getPluginManager() ).useTimings( false );
- sender.sendMessage( "Disabled Timings" );
- return;
- }
-
- if ( !Bukkit.getPluginManager().useTimings() )
- {
- sender.sendMessage( "Please enable timings by typing /timings on" );
- return;
- }
-
- boolean paste = "paste".equals( args[0] );
- if ("reset".equals(args[0])) {
- CustomTimingsHandler.reload();
- sender.sendMessage("Timings reset");
- } else if ("merged".equals(args[0]) || "report".equals(args[0]) || paste) {
- long sampleTime = System.nanoTime() - timingStart;
- int index = 0;
- File timingFolder = new File("timings");
- timingFolder.mkdirs();
- File timings = new File(timingFolder, "timings.txt");
- ByteArrayOutputStream bout = ( paste ) ? new ByteArrayOutputStream() : null;
- while (timings.exists()) timings = new File(timingFolder, "timings" + (++index) + ".txt");
- PrintStream fileTimings = null;
- try {
- fileTimings = ( paste ) ? new PrintStream( bout ) : new PrintStream( timings );
-
- CustomTimingsHandler.printTimings(fileTimings);
- fileTimings.println( "Sample time " + sampleTime + " (" + sampleTime / 1E9 + "s)" );
-
- fileTimings.println( "<spigotConfig>" );
- fileTimings.println( Bukkit.spigot().getConfig().saveToString() );
- fileTimings.println( "</spigotConfig>" );
-
- if ( paste )
- {
- new PasteThread( sender, bout ).start();
- return;
- }
-
- sender.sendMessage("Timings written to " + timings.getPath());
2016-02-29 23:09:49 +00:00
- sender.sendMessage( "Paste contents of file into form at http://www.spigotmc.org/go/timings to read results." );
2016-01-10 07:33:27 +00:00
-
- } catch (IOException e) {
- } finally {
- if (fileTimings != null) {
- fileTimings.close();
- }
- }
- }
- }
- // Spigot end
-
2016-02-29 23:09:49 +00:00
- @Override
2019-03-20 00:28:15 +00:00
- public boolean execute(@NotNull CommandSender sender, @NotNull String currentAlias, @NotNull String[] args) {
2016-02-29 23:09:49 +00:00
- if (!testPermission(sender)) return true;
2016-01-10 07:33:27 +00:00
- if (args.length < 1) { // Spigot
2016-02-29 23:09:49 +00:00
- sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
- return false;
- }
2016-01-10 07:33:27 +00:00
- if (true) { executeSpigotTimings(sender, args); return true; } // Spigot
2016-02-29 23:09:49 +00:00
- if (!sender.getServer().getPluginManager().useTimings()) {
- sender.sendMessage("Please enable timings by setting \"settings.plugin-profiling\" to true in bukkit.yml");
- return true;
- }
-
- boolean separate = "separate".equalsIgnoreCase(args[0]);
- if ("reset".equalsIgnoreCase(args[0])) {
- for (HandlerList handlerList : HandlerList.getHandlerLists()) {
- for (RegisteredListener listener : handlerList.getRegisteredListeners()) {
- if (listener instanceof TimedRegisteredListener) {
2017-08-08 03:05:16 +00:00
- ((TimedRegisteredListener) listener).reset();
2016-02-29 23:09:49 +00:00
- }
- }
- }
- sender.sendMessage("Timings reset");
- } else if ("merged".equalsIgnoreCase(args[0]) || separate) {
-
- int index = 0;
- int pluginIdx = 0;
- File timingFolder = new File("timings");
- timingFolder.mkdirs();
- File timings = new File(timingFolder, "timings.txt");
- File names = null;
- while (timings.exists()) timings = new File(timingFolder, "timings" + (++index) + ".txt");
- PrintStream fileTimings = null;
- PrintStream fileNames = null;
- try {
- fileTimings = new PrintStream(timings);
- if (separate) {
- names = new File(timingFolder, "names" + index + ".txt");
- fileNames = new PrintStream(names);
- }
- for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {
- pluginIdx++;
- long totalTime = 0;
- if (separate) {
- fileNames.println(pluginIdx + " " + plugin.getDescription().getFullName());
- fileTimings.println("Plugin " + pluginIdx);
- }
- else fileTimings.println(plugin.getDescription().getFullName());
- for (RegisteredListener listener : HandlerList.getRegisteredListeners(plugin)) {
- if (listener instanceof TimedRegisteredListener) {
- TimedRegisteredListener trl = (TimedRegisteredListener) listener;
- long time = trl.getTotalTime();
- int count = trl.getCount();
- if (count == 0) continue;
- long avg = time / count;
- totalTime += time;
- Class<? extends Event> eventClass = trl.getEventClass();
- if (count > 0 && eventClass != null) {
- fileTimings.println(" " + eventClass.getSimpleName() + (trl.hasMultiple() ? " (and sub-classes)" : "") + " Time: " + time + " Count: " + count + " Avg: " + avg);
- }
- }
- }
- fileTimings.println(" Total time " + totalTime + " (" + totalTime / 1000000000 + "s)");
- }
- sender.sendMessage("Timings written to " + timings.getPath());
- if (separate) sender.sendMessage("Names written to " + names.getPath());
- } catch (IOException e) {
- } finally {
- if (fileTimings != null) {
- fileTimings.close();
- }
- if (fileNames != null) {
- fileNames.close();
- }
- }
- } else {
- sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
- return false;
- }
- return true;
- }
-
2019-03-20 00:28:15 +00:00
- @NotNull
2016-02-29 23:09:49 +00:00
- @Override
2019-03-20 00:28:15 +00:00
- public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) {
2016-02-29 23:09:49 +00:00
- Validate.notNull(sender, "Sender cannot be null");
- Validate.notNull(args, "Arguments cannot be null");
- Validate.notNull(alias, "Alias cannot be null");
-
- if (args.length == 1) {
- return StringUtil.copyPartialMatches(args[0], TIMINGS_SUBCOMMANDS, new ArrayList<String>(TIMINGS_SUBCOMMANDS.size()));
- }
- return ImmutableList.of();
- }
2016-01-10 07:33:27 +00:00
-
- // Spigot start
- private static class PasteThread extends Thread
- {
-
- private final CommandSender sender;
- private final ByteArrayOutputStream bout;
-
2019-03-20 00:28:15 +00:00
- public PasteThread(@NotNull CommandSender sender, @NotNull ByteArrayOutputStream bout)
2016-01-10 07:33:27 +00:00
- {
- super( "Timings paste thread" );
- this.sender = sender;
- this.bout = bout;
- }
-
- @Override
- public synchronized void start() {
- if (sender instanceof RemoteConsoleCommandSender) {
- run();
- } else {
- super.start();
- }
- }
-
- @Override
- public void run()
- {
- try
- {
2016-08-16 00:22:10 +00:00
- HttpURLConnection con = (HttpURLConnection) new URL( "https://timings.spigotmc.org/paste" ).openConnection();
2016-01-10 07:33:27 +00:00
- con.setDoOutput( true );
- con.setRequestMethod( "POST" );
- con.setInstanceFollowRedirects( false );
-
- OutputStream out = con.getOutputStream();
2016-08-16 00:22:10 +00:00
- out.write( bout.toByteArray() );
2016-01-10 07:33:27 +00:00
- out.close();
2016-08-16 00:22:10 +00:00
-
- com.google.gson.JsonObject location = new com.google.gson.Gson().fromJson(new java.io.InputStreamReader(con.getInputStream()), com.google.gson.JsonObject.class);
2016-01-10 07:33:27 +00:00
- con.getInputStream().close();
-
2016-08-16 00:22:10 +00:00
- String pasteID = location.get( "key" ).getAsString();
- sender.sendMessage( ChatColor.GREEN + "Timings results can be viewed at https://www.spigotmc.org/go/timings?url=" + pasteID );
2016-01-10 07:33:27 +00:00
- } catch ( IOException ex )
- {
- sender.sendMessage( ChatColor.RED + "Error pasting timings, check your console for more information" );
- Bukkit.getServer().getLogger().log( Level.WARNING, "Could not paste timings", ex );
- }
- }
- }
- // Spigot end
2016-02-29 23:09:49 +00:00
-}
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/org/bukkit/entity/Player.java b/src/main/java/org/bukkit/entity/Player.java
2019-07-11 16:59:21 +00:00
index ae6274d7..bf0b8bf1 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/entity/Player.java
+++ b/src/main/java/org/bukkit/entity/Player.java
2019-06-25 01:47:58 +00:00
@@ -1601,6 +1601,11 @@ public interface Player extends HumanEntity, Conversable, OfflinePlayer, PluginM
2019-03-20 00:28:15 +00:00
public void sendMessage(@NotNull net.md_5.bungee.api.ChatMessageType position, @NotNull net.md_5.bungee.api.chat.BaseComponent... components) {
2016-02-29 23:09:49 +00:00
throw new UnsupportedOperationException("Not supported yet.");
2016-01-10 07:33:27 +00:00
}
+
+ public int getPing()
+ {
+ throw new UnsupportedOperationException( "Not supported yet." );
+ }
}
2019-03-20 00:28:15 +00:00
@NotNull
2016-01-10 07:33:27 +00:00
diff --git a/src/main/java/org/bukkit/plugin/SimplePluginManager.java b/src/main/java/org/bukkit/plugin/SimplePluginManager.java
2019-07-11 16:59:21 +00:00
index 2dfb8529..53e5045f 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/plugin/SimplePluginManager.java
+++ b/src/main/java/org/bukkit/plugin/SimplePluginManager.java
2019-07-11 16:59:21 +00:00
@@ -298,7 +298,6 @@ public final class SimplePluginManager implements PluginManager {
2016-01-10 07:33:27 +00:00
}
}
- org.bukkit.command.defaults.TimingsCommand.timingStart = System.nanoTime(); // Spigot
return result.toArray(new Plugin[result.size()]);
}
2019-07-11 16:59:21 +00:00
@@ -337,7 +336,7 @@ public final class SimplePluginManager implements PluginManager {
2016-01-10 07:33:27 +00:00
if (result != null) {
plugins.add(result);
- lookupNames.put(result.getDescription().getName(), result);
2019-03-20 00:28:15 +00:00
+ lookupNames.put(result.getDescription().getName().toLowerCase(java.util.Locale.ENGLISH), result); // Paper
2016-01-10 07:33:27 +00:00
}
return result;
2019-07-11 16:59:21 +00:00
@@ -365,7 +364,7 @@ public final class SimplePluginManager implements PluginManager {
2019-05-06 02:58:04 +00:00
@Override
2019-03-20 00:28:15 +00:00
@Nullable
public synchronized Plugin getPlugin(@NotNull String name) {
2016-01-10 07:33:27 +00:00
- return lookupNames.get(name.replace(' ', '_'));
2019-03-20 00:28:15 +00:00
+ return lookupNames.get(name.replace(' ', '_').toLowerCase(java.util.Locale.ENGLISH)); // Paper
2016-01-10 07:33:27 +00:00
}
2019-05-06 02:58:04 +00:00
@Override
2019-07-11 16:59:21 +00:00
@@ -586,7 +585,8 @@ public final class SimplePluginManager implements PluginManager {
2016-01-10 07:33:27 +00:00
throw new IllegalPluginAccessException("Plugin attempted to register " + event + " while not enabled");
}
- if (useTimings) {
2019-03-20 00:28:15 +00:00
+ executor = new co.aikar.timings.TimedEventExecutor(executor, plugin, null, event); // Paper
+ if (false) { // Spigot - RL handles useTimings check now // Paper
2016-01-10 07:33:27 +00:00
getEventListeners(event).register(new TimedRegisteredListener(listener, executor, priority, plugin, ignoreCancelled));
} else {
getEventListeners(event).register(new RegisteredListener(listener, executor, priority, plugin, ignoreCancelled));
2019-07-11 16:59:21 +00:00
@@ -783,7 +783,7 @@ public final class SimplePluginManager implements PluginManager {
2016-01-10 07:33:27 +00:00
2019-05-06 02:58:04 +00:00
@Override
2016-01-10 07:33:27 +00:00
public boolean useTimings() {
- return useTimings;
+ return co.aikar.timings.Timings.isTimingsEnabled(); // Spigot
}
/**
2019-07-11 16:59:21 +00:00
@@ -792,6 +792,6 @@ public final class SimplePluginManager implements PluginManager {
2016-01-10 07:33:27 +00:00
* @param use True if per event timing code should be used
*/
public void useTimings(boolean use) {
- useTimings = use;
2019-03-20 00:28:15 +00:00
+ co.aikar.timings.Timings.setTimingsEnabled(use); // Paper
2016-01-10 07:33:27 +00:00
}
}
diff --git a/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java b/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java
2019-07-11 16:59:21 +00:00
index 1173e433..82e379d1 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java
+++ b/src/main/java/org/bukkit/plugin/java/JavaPluginLoader.java
2019-04-23 04:47:07 +00:00
@@ -53,7 +53,6 @@ public final class JavaPluginLoader implements PluginLoader {
2016-01-10 07:33:27 +00:00
private final Pattern[] fileFilters = new Pattern[] { Pattern.compile("\\.jar$"), };
2019-01-01 03:15:55 +00:00
private final Map<String, Class<?>> classes = new ConcurrentHashMap<String, Class<?>>();
2016-09-03 03:44:52 +00:00
private final List<PluginClassLoader> loaders = new CopyOnWriteArrayList<PluginClassLoader>();
2016-01-10 07:33:27 +00:00
- public static final CustomTimingsHandler pluginParentTimer = new CustomTimingsHandler("** Plugins"); // Spigot
/**
* This class was not meant to be constructed explicitly
2019-05-06 02:58:04 +00:00
@@ -302,27 +301,21 @@ public final class JavaPluginLoader implements PluginLoader {
2016-01-10 07:33:27 +00:00
}
}
- final CustomTimingsHandler timings = new CustomTimingsHandler("Plugin: " + plugin.getDescription().getFullName() + " Event: " + listener.getClass().getName() + "::" + method.getName()+"("+eventClass.getSimpleName()+")", pluginParentTimer); // Spigot
- EventExecutor executor = new EventExecutor() {
2019-03-20 00:28:15 +00:00
+ EventExecutor executor = new co.aikar.timings.TimedEventExecutor(new EventExecutor() { // Paper
2019-05-06 02:58:04 +00:00
@Override
- public void execute(@NotNull Listener listener, @NotNull Event event) throws EventException {
2019-03-20 00:28:15 +00:00
+ public void execute(@NotNull Listener listener, @NotNull Event event) throws EventException { // Paper
2016-01-10 07:33:27 +00:00
try {
if (!eventClass.isAssignableFrom(event.getClass())) {
return;
}
- // Spigot start
- boolean isAsync = event.isAsynchronous();
- if (!isAsync) timings.startTiming();
method.invoke(listener, event);
- if (!isAsync) timings.stopTiming();
- // Spigot end
} catch (InvocationTargetException ex) {
throw new EventException(ex.getCause());
} catch (Throwable t) {
throw new EventException(t);
}
}
- };
2019-03-20 00:28:15 +00:00
+ }, plugin, method, eventClass); // Paper
2016-01-10 07:33:27 +00:00
if (false) { // Spigot - RL handles useTimings check now
eventSet.add(new TimedRegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled()));
} else {
diff --git a/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java b/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java
2019-07-11 16:59:21 +00:00
index 0ffc1dfd..b859796b 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java
+++ b/src/main/java/org/bukkit/plugin/java/PluginClassLoader.java
2019-04-23 04:47:07 +00:00
@@ -24,7 +24,8 @@ import org.jetbrains.annotations.Nullable;
2016-01-10 07:33:27 +00:00
/**
* A ClassLoader for plugins, to allow shared classes across multiple plugins
*/
-final class PluginClassLoader extends URLClassLoader {
+public final class PluginClassLoader extends URLClassLoader { // Spigot
+ public JavaPlugin getPlugin() { return plugin; } // Spigot
private final JavaPluginLoader loader;
2019-01-01 03:15:55 +00:00
private final Map<String, Class<?>> classes = new ConcurrentHashMap<String, Class<?>>();
2016-01-10 07:33:27 +00:00
private final PluginDescriptionFile description;
diff --git a/src/main/java/org/bukkit/util/CachedServerIcon.java b/src/main/java/org/bukkit/util/CachedServerIcon.java
2019-07-11 16:59:21 +00:00
index 5ca863b3..612958a3 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/bukkit/util/CachedServerIcon.java
+++ b/src/main/java/org/bukkit/util/CachedServerIcon.java
2019-03-20 00:28:15 +00:00
@@ -2,6 +2,7 @@ package org.bukkit.util;
import org.bukkit.Server;
import org.bukkit.event.server.ServerListPingEvent;
+import org.jetbrains.annotations.Nullable;
/**
* This is a cached version of a server-icon. It's internal representation
@@ -12,4 +13,9 @@ import org.bukkit.event.server.ServerListPingEvent;
2016-01-10 07:33:27 +00:00
* @see Server#loadServerIcon(java.io.File)
* @see ServerListPingEvent#setServerIcon(CachedServerIcon)
*/
-public interface CachedServerIcon {}
+public interface CachedServerIcon {
2019-03-20 00:28:15 +00:00
+
+ @Nullable
+ public String getData(); // Paper
+
2016-01-10 07:33:27 +00:00
+}
diff --git a/src/main/java/org/spigotmc/CustomTimingsHandler.java b/src/main/java/org/spigotmc/CustomTimingsHandler.java
2019-07-11 16:59:21 +00:00
index b71235f6..3cbe5c2b 100644
2016-01-10 07:33:27 +00:00
--- a/src/main/java/org/spigotmc/CustomTimingsHandler.java
+++ b/src/main/java/org/spigotmc/CustomTimingsHandler.java
2019-03-20 00:28:15 +00:00
@@ -1,3 +1,26 @@
2016-01-10 07:33:27 +00:00
+/*
+ * This file is licensed under the MIT License (MIT).
+ *
+ * Copyright (c) 2014 Daniel Ennis <http://aikar.co>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
package org.spigotmc;
2019-03-20 00:28:15 +00:00
import java.io.PrintStream;
@@ -5,155 +28,84 @@ import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.bukkit.Bukkit;
import org.bukkit.World;
2016-01-10 07:33:27 +00:00
-import org.bukkit.command.defaults.TimingsCommand;
2019-03-20 00:28:15 +00:00
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
2016-01-10 07:33:27 +00:00
+import org.bukkit.plugin.AuthorNagException;
2019-03-20 00:28:15 +00:00
+import org.bukkit.plugin.Plugin;
2016-01-10 07:33:27 +00:00
+import co.aikar.timings.Timing;
+import co.aikar.timings.Timings;
+import co.aikar.timings.TimingsManager;
2019-03-20 00:28:15 +00:00
+
2018-09-29 18:05:24 +00:00
+import java.lang.reflect.InvocationTargetException;
2016-01-10 07:33:27 +00:00
+import java.lang.reflect.Method;
+import java.util.logging.Level;
/**
- * Provides custom timing sections for /timings merged.
+ * This is here for legacy purposes incase any plugin used it.
+ *
+ * If you use this, migrate ASAP as this will be removed in the future!
+ *
+ * @deprecated
+ * @see co.aikar.timings.Timings#of
*/
-public class CustomTimingsHandler
-{
+@Deprecated
+public final class CustomTimingsHandler {
+ private final Timing handler;
2018-09-29 18:05:24 +00:00
+ private static Boolean sunReflectAvailable;
+ private static Method getCallerClass;
2016-01-10 07:33:27 +00:00
- private static Queue<CustomTimingsHandler> HANDLERS = new ConcurrentLinkedQueue<CustomTimingsHandler>();
- /*========================================================================*/
- private final String name;
- private final CustomTimingsHandler parent;
- private long count = 0;
- private long start = 0;
- private long timingDepth = 0;
- private long totalTime = 0;
- private long curTickTotal = 0;
- private long violations = 0;
2019-03-20 00:28:15 +00:00
+ public CustomTimingsHandler(@NotNull String name) {
2018-09-29 18:05:24 +00:00
+ if (sunReflectAvailable == null) {
+ String javaVer = System.getProperty("java.version");
+ String[] elements = javaVer.split("\\.");
2016-01-10 07:33:27 +00:00
2019-03-20 00:28:15 +00:00
- public CustomTimingsHandler(@NotNull String name)
2016-01-10 07:33:27 +00:00
- {
- this( name, null );
- }
2018-09-29 18:05:24 +00:00
-
2019-03-20 00:28:15 +00:00
- public CustomTimingsHandler(@NotNull String name, @Nullable CustomTimingsHandler parent)
2016-01-10 07:33:27 +00:00
- {
- this.name = name;
- this.parent = parent;
- HANDLERS.add( this );
- }
2018-09-29 18:05:24 +00:00
+ int major = Integer.parseInt(elements.length >= 2 ? elements[1] : javaVer);
+ if (major <= 8) {
+ sunReflectAvailable = true;
2016-01-10 07:33:27 +00:00
- /**
- * Prints the timings and extra data to the given stream.
- *
2019-05-22 04:14:56 +00:00
- * @param printStream output stream
2016-01-10 07:33:27 +00:00
- */
2019-03-20 00:28:15 +00:00
- public static void printTimings(@NotNull PrintStream printStream)
2016-01-10 07:33:27 +00:00
- {
- printStream.println( "Minecraft" );
- for ( CustomTimingsHandler timings : HANDLERS )
- {
- long time = timings.totalTime;
- long count = timings.count;
- if ( count == 0 )
- {
- continue;
2018-09-29 18:05:24 +00:00
+ try {
+ Class<?> reflection = Class.forName("sun.reflect.Reflection");
+ getCallerClass = reflection.getMethod("getCallerClass", int.class);
+ } catch (ClassNotFoundException | NoSuchMethodException ignored) {
+ }
+ } else {
+ sunReflectAvailable = false;
2016-01-10 07:33:27 +00:00
}
- long avg = time / count;
-
- printStream.println( " " + timings.name + " Time: " + time + " Count: " + count + " Avg: " + avg + " Violations: " + timings.violations );
2018-09-29 18:05:24 +00:00
- }
2016-01-10 07:33:27 +00:00
- printStream.println( "# Version " + Bukkit.getVersion() );
- int entities = 0;
- int livingEntities = 0;
- for ( World world : Bukkit.getWorlds() )
- {
- entities += world.getEntities().size();
- livingEntities += world.getLivingEntities().size();
2018-09-29 18:05:24 +00:00
}
2016-01-10 07:33:27 +00:00
- printStream.println( "# Entities " + entities );
- printStream.println( "# LivingEntities " + livingEntities );
2018-09-29 18:05:24 +00:00
- }
2016-01-10 07:33:27 +00:00
- /**
- * Resets all timings.
- */
- public static void reload()
- {
- if ( Bukkit.getPluginManager().useTimings() )
- {
- for ( CustomTimingsHandler timings : HANDLERS )
- {
- timings.reset();
2018-09-29 18:05:24 +00:00
+ Class calling = null;
+ if (sunReflectAvailable) {
+ try {
+ calling = (Class) getCallerClass.invoke(null, 2);
+ } catch (IllegalAccessException | InvocationTargetException ignored) {
}
}
2016-01-10 07:33:27 +00:00
- TimingsCommand.timingStart = System.nanoTime();
- }
- /**
- * Ticked every tick by CraftBukkit to count the number of times a timer
- * caused TPS loss.
- */
- public static void tick()
- {
- if ( Bukkit.getPluginManager().useTimings() )
- {
- for ( CustomTimingsHandler timings : HANDLERS )
- {
- if ( timings.curTickTotal > 50000000 )
- {
- timings.violations += Math.ceil( timings.curTickTotal / 50000000 );
- }
- timings.curTickTotal = 0;
- timings.timingDepth = 0; // incase reset messes this up
- }
- }
- }
2018-09-29 18:05:24 +00:00
+ Timing timing;
2016-01-10 07:33:27 +00:00
- /**
- * Starts timing to track a section of code.
- */
- public void startTiming()
- {
- // If second condtion fails we are already timing
- if ( Bukkit.getPluginManager().useTimings() && ++timingDepth == 1 )
- {
- start = System.nanoTime();
- if ( parent != null && ++parent.timingDepth == 1 )
- {
- parent.start = start;
- }
- }
- }
2018-09-29 18:05:24 +00:00
+ Plugin plugin = null;
+ try {
+ plugin = TimingsManager.getPluginByClassloader(calling);
+ } catch (Exception ignored) {}
2016-01-10 07:33:27 +00:00
- /**
- * Stops timing a section of code.
- */
- public void stopTiming()
- {
- if ( Bukkit.getPluginManager().useTimings() )
- {
- if ( --timingDepth != 0 || start == 0 )
- {
- return;
- }
- long diff = System.nanoTime() - start;
- totalTime += diff;
- curTickTotal += diff;
- count++;
- start = 0;
- if ( parent != null )
- {
- parent.stopTiming();
2018-09-29 18:05:24 +00:00
+ new AuthorNagException("Deprecated use of CustomTimingsHandler. Please Switch to Timings.of ASAP").printStackTrace();
+ if (plugin != null) {
+ timing = Timings.of(plugin, "(Deprecated API) " + name);
+ } else {
+ try {
+ final Method ofSafe = TimingsManager.class.getDeclaredMethod("getHandler", String.class, String.class, Timing.class);
+ ofSafe.setAccessible(true);
+ timing = (Timing) ofSafe.invoke(null,"Minecraft", "(Deprecated API) " + name, null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ Bukkit.getLogger().log(Level.SEVERE, "This handler could not be registered");
+ timing = Timings.NULL_HANDLER;
}
}
+ handler = timing;
}
2016-01-10 07:33:27 +00:00
- /**
- * Reset this timer, setting all values to zero.
- */
- public void reset()
- {
- count = 0;
- violations = 0;
- curTickTotal = 0;
- totalTime = 0;
- start = 0;
- timingDepth = 0;
- }
2018-09-29 18:05:24 +00:00
+ public void startTiming() { handler.startTiming(); }
+ public void stopTiming() { handler.stopTiming(); }
+
2016-01-10 07:33:27 +00:00
}
2016-01-09 06:32:38 +00:00
--
2019-06-25 01:47:58 +00:00
2.22.0
2016-01-09 06:32:38 +00:00