Move prefixes to loggers.

This commit is contained in:
asofold 2015-11-15 02:15:20 +01:00
parent 528410f6f3
commit af5fbd900a
48 changed files with 615 additions and 630 deletions

View File

@ -4,6 +4,7 @@ import java.util.logging.Level;
/**
* Central access point log manager with a bias towards String messages.
*
* @author dev1mc
*
*/
@ -11,33 +12,41 @@ public interface LogManager {
/**
* A stream that skips all messages. It's not registered officially.
*
* @return
*/
public StreamID getVoidStreamID();
/**
* This should be a fail-safe direct String-logger, that has the highest probability of working
* within the default context and rather skips messages instead of failing or scheduling tasks,
* typically the main application primary thread.
* This should be a fail-safe direct String-logger, that has the highest
* probability of working within the default context and rather skips
* messages instead of failing or scheduling tasks, typically the main
* application primary thread.
*
* @return
*/
public StreamID getInitStreamID();
/**
* Don't use this prefix for custom registrations with StreamID and LoggerID.
* Prefix for the names of the default streams. Don't use this prefix for
* custom registrations with StreamID and LoggerID.
*
* @return
*/
public String getDefaultPrefix();
/**
* Case-insensitive lookup.
*
* @param name
* @return
*/
public boolean hasLogger(String name);
/**
* A newly created id can be used here (case-insensitive comparison by name). For logging use existing ids always.
* A newly created id can be used here (case-insensitive comparison by
* name). For logging use existing ids always.
*
* @param loggerID
* @return
*/
@ -45,6 +54,7 @@ public interface LogManager {
/**
* Case-insensitive lookup.
*
* @param name
* @return Returns the registered StreamID or null, if not registered.
*/
@ -52,13 +62,16 @@ public interface LogManager {
/**
* Case-insensitive lookup.
*
* @param name
* @return
*/
public boolean hasStream(String name);
/**
* A newly created id can be used here (case-insensitive comparison by name). For logging use existing ids always.
* A newly created id can be used here (case-insensitive comparison by
* name). For logging use existing ids always.
*
* @param streamID
* @return
*/
@ -66,6 +79,7 @@ public interface LogManager {
/**
* Case-insensitive lookup.
*
* @param name
* @return Returns the registered StreamID or null, if not registered.
*/

View File

@ -18,53 +18,53 @@ import fr.neatmonster.nocheatplus.utilities.StringUtil;
*
*/
public abstract class AbstractLogManager implements LogManager {
// TODO: Visibility of methods.
// TODO: Add option for per stream prefixes.
// TODO: Concept for adding in the time at the point of call/scheduling.
// TODO: Re-register with other options: Add methods for LoggerID + StreamID + options.
// TODO: Hierarchical LogNode relations, to ensure other log nodes with the same logger are removed too [necessary to allow removing individual loggers].
// TODO: Temporary streams, e.g. for players, unregistering with command and/or logout.
// TODO: Mechanics of removing temporary streams (flush stream, remove entries from queues, wait with removal until tasks have run once more).
// TODO: Consider generalizing the (internal) implementation right away (sub registry by content class).
// TODO: Consider adding a global cache (good for re-mapping, contra: reload is not intended to happen on a regular basis).
private final LogNodeDispatcher dispatcher;
private final String defaultPrefix;
/**
* Fast streamID access map (runtime). Copy on write with registryLock.
*/
private Map<StreamID, ContentStream<String>> idStreamMap = new IdentityHashMap<StreamID, ContentStream<String>>();
/**
* Map name to Stream. Copy on write with registryLock.
*/
private Map<String, ContentStream<String>> nameStreamMap = new HashMap<String, ContentStream<String>>();
/**
* Lower-case name to StreamID.
*/
private Map<String, StreamID> nameStreamIDMap = new HashMap<String, StreamID>();
/**
* LogNode registry by LoggerID. Copy on write with registryLock.
*/
private Map<LoggerID, LogNode<String>> idNodeMap = new IdentityHashMap<LoggerID, LogNode<String>>();
/**
* LogNode registry by lower-case name. Copy on write with registryLock.
*/
private Map<String, LogNode<String>> nameNodeMap = new HashMap<String, LogNode<String>>();
/**
* Lower-case name to LoggerID.
*/
private Map<String, LoggerID> nameLoggerIDMap = new HashMap<String, LoggerID>();
/** Registry changes have to be done under this lock (copy on write) */
protected final Object registryCOWLock = new Object();
// TODO: Future: Only an init string stream or (later) always "the init stream" for all content types.
@ -76,7 +76,7 @@ public abstract class AbstractLogManager implements LogManager {
* fail.
*/
private StreamID fallBackStreamID = voidStreamID;
/**
* Wrapping logging to the init stream.
*/
@ -86,7 +86,7 @@ public abstract class AbstractLogManager implements LogManager {
AbstractLogManager.this.log(getInitStreamID(), level, content);
}
};
/**
*
* @param dispatcher
@ -101,9 +101,10 @@ public abstract class AbstractLogManager implements LogManager {
registerInitLogger();
dispatcher.setInitLogger(initLogger);
}
/**
* Create stream if it does not exist.
* Create INIT stream for strings, if it does not exist. Does not set a
* prefix.
*/
protected void createInitStream() {
synchronized (registryCOWLock) {
@ -112,61 +113,61 @@ public abstract class AbstractLogManager implements LogManager {
}
}
}
/**
* Create the minimal init logger(s). Synchronize over registryCOWLock. It's preferable not to duplicate loggers. Prefer LoggerID("init...").
*/
protected abstract void registerInitLogger();
protected LogNodeDispatcher getLogNodeDispatcher() {
return dispatcher;
}
@Override
public String getDefaultPrefix() {
return defaultPrefix;
}
@Override
public StreamID getInitStreamID() {
return initStreamID;
}
@Override
public StreamID getVoidStreamID() {
return voidStreamID;
}
@Override
public StreamID getStreamID(String name) {
return nameStreamIDMap.get(name.toLowerCase());
}
@Override
public LoggerID getLoggerID(String name) {
return nameLoggerIDMap.get(name.toLowerCase());
}
@Override
public void debug(final StreamID streamID, final String message) {
log(streamID, Level.FINE, message); // TODO: Not sure what happens with FINE and provided Logger instances.
}
@Override
public void info(final StreamID streamID, final String message) {
log(streamID, Level.INFO, message);
}
@Override
public void warning(final StreamID streamID, final String message) {
log(streamID, Level.WARNING, message);
}
@Override
public void severe(final StreamID streamID, final String message) {
log(streamID, Level.SEVERE, message);
}
@Override
public void log(final StreamID streamID, final Level level, final String message) {
if (streamID != voidStreamID) {
@ -178,7 +179,7 @@ public abstract class AbstractLogManager implements LogManager {
}
}
}
private void handleFallBack(final StreamID streamID, final Level level, final String message) {
if (fallBackStreamID != null && streamID != fallBackStreamID) {
log(fallBackStreamID, level, message);
@ -186,22 +187,22 @@ public abstract class AbstractLogManager implements LogManager {
throw new RuntimeException("Stream not registered: " + streamID);
}
}
@Override
public void debug(final StreamID streamID, final Throwable t) {
log(streamID, Level.FINE, t); // TODO: Not sure what happens with FINE and provided Logger instances.
}
@Override
public void info(final StreamID streamID, final Throwable t) {
log(streamID, Level.INFO, t);
}
@Override
public void warning(final StreamID streamID, final Throwable t) {
log(streamID, Level.WARNING, t);
}
@Override
public void severe(final StreamID streamID, final Throwable t) {
log(streamID, Level.SEVERE, t);
@ -212,17 +213,17 @@ public abstract class AbstractLogManager implements LogManager {
// Not sure adding streams for Throwable would be better.
log(streamID, level, StringUtil.throwableToString(t));
}
@Override
public boolean hasStream(final StreamID streamID) {
return this.idStreamMap.containsKey(streamID) || this.nameStreamMap.containsKey(streamID.name.toLowerCase());
}
@Override
public boolean hasStream(String name) {
return getStreamID(name) != null;
}
/**
* Call under lock.
* @param streamID
@ -241,7 +242,7 @@ public abstract class AbstractLogManager implements LogManager {
throw new IllegalArgumentException("Stream already registered: " + streamID.name.toLowerCase());
}
}
protected ContentStream<String> createStringStream(final StreamID streamID) {
ContentStream<String> stream;
synchronized (registryCOWLock) {
@ -256,21 +257,21 @@ public abstract class AbstractLogManager implements LogManager {
this.idStreamMap = idStreamMap;
this.nameStreamMap = nameStreamMap;
this.nameStreamIDMap = nameStreamIDMap;
}
return stream;
}
@Override
public boolean hasLogger(final LoggerID loggerID) {
return this.idNodeMap.containsKey(loggerID) || this.nameNodeMap.containsKey(loggerID.name.toLowerCase());
}
@Override
public boolean hasLogger(String name) {
return getLoggerID(name) != null;
}
/**
* Call under lock.
* @param loggerID
@ -286,7 +287,7 @@ public abstract class AbstractLogManager implements LogManager {
throw new IllegalArgumentException("Logger already registered: " + loggerID.name.toLowerCase());
}
}
/**
* Convenience method.
* @param logger
@ -298,7 +299,7 @@ public abstract class AbstractLogManager implements LogManager {
registerStringLogger(loggerID, logger, options);
return loggerID;
}
/**
* Convenience method.
* @param logger
@ -310,7 +311,7 @@ public abstract class AbstractLogManager implements LogManager {
registerStringLogger(loggerID, logger, options);
return loggerID;
}
/**
* Convenience method.
* @param logger
@ -318,11 +319,22 @@ public abstract class AbstractLogManager implements LogManager {
* @return
*/
protected LoggerID registerStringLogger(final File file, final LogOptions options) {
return registerStringLogger(file, null, options);
}
/**
* Convenience method.
* @param logger
* @param prefix Prefix for all log messages.
* @param options
* @return
*/
protected LoggerID registerStringLogger(final File file, final String prefix, final LogOptions options) {
LoggerID loggerID = new LoggerID(options.name);
registerStringLogger(loggerID, file, options);
registerStringLogger(loggerID, file, prefix, options);
return loggerID;
}
protected LogNode<String> registerStringLogger(final LoggerID loggerID, final ContentLogger<String> logger, final LogOptions options) {
LogNode<String> node;
synchronized (registryCOWLock) {
@ -340,7 +352,7 @@ public abstract class AbstractLogManager implements LogManager {
}
return node;
}
protected LogNode<String> registerStringLogger(LoggerID loggerID, Logger logger, LogOptions options) {
LogNode<String> node;
synchronized (registryCOWLock) {
@ -350,13 +362,17 @@ public abstract class AbstractLogManager implements LogManager {
}
return node;
}
protected LogNode<String> registerStringLogger(LoggerID loggerID, File file, LogOptions options) {
return registerStringLogger(loggerID, file, null, options);
}
protected LogNode<String> registerStringLogger(LoggerID loggerID, File file, String prefix, LogOptions options) {
LogNode<String> node;
synchronized (registryCOWLock) {
testRegisterLogger(loggerID); // Redundant checking, because file loggers are expensive.
// TODO: Detect duplicate loggers (register same logger with given id and options).
FileLoggerAdapter adapter = new FileLoggerAdapter(file);
FileLoggerAdapter adapter = new FileLoggerAdapter(file, prefix);
if (adapter.isInoperable()) {
adapter.detachLogger();
throw new RuntimeException("Failed to set up file logger for id '" + loggerID + "': " + file);
@ -371,7 +387,7 @@ public abstract class AbstractLogManager implements LogManager {
}
return node;
}
/**
* Attach a logger to a stream. Redundant attaching will mean no changes.
* @param loggerID Must exist.
@ -401,13 +417,13 @@ public abstract class AbstractLogManager implements LogManager {
idStreamMap.get(streamID).addNode(node);
}
}
// TODO: Methods to replace options for loggers (+ loggers themselves)
// TODO: Later: attach streams to streams ? [few loggers: attach loggers rather]
// TODO: logger/stream: allow id lookup logger, file, etc. ?
/**
* Remove all loggers and streams including init, resulting in roughly the
* same state as is after calling the AbstractLogger constructor. Call from
@ -451,14 +467,14 @@ public abstract class AbstractLogManager implements LogManager {
}
}
}
// /**
// * Remove all registered streams and loggers, recreates init logger (and stream).
// */
// public void clear(final long msWaitFlush) {
// clear(msWaitFlush, true);
// }
// /**
// * Remove all registered streams and loggers, recreates init logger (and stream).
// */
// public void clear(final long msWaitFlush) {
// clear(msWaitFlush, true);
// }
/**
* Rather a graceful shutdown, including waiting for the asynchronous task, if necessary. Clear the registry. Also removes the init logger [subject to change].
* Call from the primary thread (policy pending).
@ -466,5 +482,5 @@ public abstract class AbstractLogManager implements LogManager {
public void shutdown() {
clear(500, false); // TODO: Policy / making sense.
}
}

View File

@ -4,23 +4,35 @@ import java.io.File;
import java.util.logging.Level;
public class FileLoggerAdapter extends FileLogger implements ContentLogger<String> {
// TODO: Store path/file either here or on FileLogger.
// TODO: Do store the string path (directory / direct file path), to reference correctly.
private final String prefix;
/**
* See FileLogger(File).
* @param file Path to log file or existing directory.
*/
public FileLoggerAdapter(File file) {
this(file, null);
}
/**
* See FileLogger(File).
* @param file Path to log file or existing directory.
* @param prefix Prefix for all log messages.
*/
public FileLoggerAdapter(File file, String prefix) {
super(file);
this.prefix = (prefix == null || prefix.isEmpty()) ? null : prefix;
}
@Override
public void log(Level level, String content) {
// TODO: Check loggerisInoperable() ?
logger.log(level, content);
logger.log(level, prefix == null ? content : (prefix + content));
}
}

View File

@ -1,7 +1,7 @@
package fr.neatmonster.nocheatplus.logging.details;
public class LogOptions {
/**
* Describe the context in which the log method may be used.<br>
* Policies:
@ -28,24 +28,24 @@ public class LogOptions {
ASYNCHRONOUS_TASK,
/** Only log if it is not the primary thread. */
ASYNCHRONOUS_ONLY,
// CUSTOM_THREAD_DIRECT|TASK // Needs a variable (Thread, methods to sync into a specific thread would have to be registered in LogManager).
;
// TODO: Can distinguish further: Call from where, log from where directly, schedule from where (allow to skip certain contexts).
}
public final String name; // TODO: Name necessary ?
public final String name;
public final CallContext callContext;
public LogOptions(LogOptions options) {
this(options.name, options.callContext);
}
public LogOptions(String name, CallContext callContext) {
this.name = name;
this.callContext = callContext;
// TODO: shutdown policy (clear, log), rather with per-world threads.
}
}

View File

@ -44,7 +44,7 @@ public class FastConsume extends Check implements Listener{
super(CheckType.INVENTORY_FASTCONSUME);
// Overrides the instant-eat check.
ConfigManager.setForAllConfigs(ConfPaths.INVENTORY_INSTANTEAT_CHECK, false);
StaticLog.logInfo("[NoCheatPlus] Inventory checks: FastConsume is available, disabled InstantEat.");
StaticLog.logInfo("Inventory checks: FastConsume is available, disabled InstantEat.");
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)

View File

@ -28,16 +28,16 @@ public class MCAccessCBReflect extends MCAccessBukkitBase {
// Version Envelope tests (1.4.5-R1.0 ... 1.8.x is considered to be ok).
final String mcVersion = ServerVersion.getMinecraftVersion();
if (mcVersion == ServerVersion.UNKNOWN_VERSION) {
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.INIT, "[NoCheatPlus] The Minecraft version could not be detected, Compat-CB-Reflect might or might not work.");
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.INIT, "The Minecraft version could not be detected, Compat-CB-Reflect might or might not work.");
this.knownSupportedVersion = false;
}
else if (ServerVersion.compareVersions(mcVersion, "1.4.5") < 0) {
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.INIT, "[NoCheatPlus] The Minecraft version seems to be older than what Compat-CB-Reflect can support.");
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.INIT, "The Minecraft version seems to be older than what Compat-CB-Reflect can support.");
this.knownSupportedVersion = false;
}
else if (ServerVersion.compareVersions(mcVersion, "1.9") >= 0) {
this.knownSupportedVersion = false;
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.INIT, "[NoCheatPlus] The Minecraft version seems to be more recent than the one Compat-CB-Reflect has been built with - this might work, but there could be incompatibilities.");
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.INIT, "The Minecraft version seems to be more recent than the one Compat-CB-Reflect has been built with - this might work, but there could be incompatibilities.");
} else {
this.knownSupportedVersion = true;
}

View File

@ -75,7 +75,7 @@ public class ReflectBlock {
// TODO: Test which is which [ALLOW to configure and also save used ones to config, by mc version].
// TODO: Dynamically test these ? [needs an extra world/space to place blocks inside of...]
if (ConfigManager.getConfigFile().getBoolean(ConfPaths.LOGGING_EXTENDED_STATUS)) {
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.INIT, "[NoCheatPlus] ReflectBlock: Use methods for shape: " + StringUtil.join(Arrays.asList(names), ", "));
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.INIT, "ReflectBlock: Use methods for shape: " + StringUtil.join(Arrays.asList(names), ", "));
}
this.nmsGetMinX = methods[0];
this.nmsGetMaxX = methods[1];

View File

@ -124,7 +124,7 @@ public class ReflectHelper {
}
}
if (!parts.isEmpty()) {
parts.add(0, "[NoCheatPlus] CompatCBReflect: The following properties could not be set:");
parts.add(0, "CompatCBReflect: The following properties could not be set:");
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.INIT, StringUtil.join(parts, "\n"));
}
}

View File

@ -293,7 +293,7 @@ public class FlyingFrequency extends BaseAdapter {
*/
private void packetMismatch() {
packetMismatch = true;
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.STATUS, "[NoCheatPlus] Data mismatch: disable interpretation of flying packets.");
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().warning(Streams.STATUS, "Data mismatch: disable interpretation of flying packets.");
}
}

View File

@ -56,10 +56,16 @@ public class ProtocolLibComponent implements DisableListener, INotifyReload, Joi
private void register(Plugin plugin) {
StaticLog.logInfo("Adding packet level hooks for ProtocolLib (MC " + ProtocolLibrary.getProtocolManager().getMinecraftVersion().getVersion() + ")...");
//Special purpose.
if (ConfigManager.isTrueForAnyConfig(ConfPaths.NET + ConfPaths.SUB_DEBUG) || ConfigManager.isTrueForAnyConfig(ConfPaths.CHECKS_DEBUG) ) {
// (Debug logging. Only activates if debug is set for checks or checks.net, not on the fly.)
register("fr.neatmonster.nocheatplus.checks.net.protocollib.DebugAdapter", plugin);
}
// Actual checks.
// if (ConfigManager.isTrueForAnyConfig(ConfPaths.NET_ATTACKFREQUENCY_ACTIVE)) {
// // (Also sets lastKeepAliveTime, if enabled.)
// register("fr.neatmonster.nocheatplus.checks.net.protocollib.UseEntityAdapter", plugin);
// }
if (ConfigManager.isTrueForAnyConfig(ConfPaths.NET_FLYINGFREQUENCY_ACTIVE)) {
// (Also sets lastKeepAliveTime, if enabled.)
register("fr.neatmonster.nocheatplus.checks.net.protocollib.FlyingFrequency", plugin);
@ -77,10 +83,10 @@ public class ProtocolLibComponent implements DisableListener, INotifyReload, Joi
for (PacketAdapter adapter : registeredPacketAdapters) {
names.add(adapter.getClass().getSimpleName());
}
StaticLog.logInfo("[NoCheatPlus] Available (and activated) packet level hooks: " + StringUtil.join(names, " | "));
StaticLog.logInfo("Available (and activated) packet level hooks: " + StringUtil.join(names, " | "));
NCPAPIProvider.getNoCheatPlusAPI().addFeatureTags("checks", names);
} else {
StaticLog.logInfo("[NoCheatPlus] No packet level hooks activated.");
StaticLog.logInfo("No packet level hooks activated.");
}
}
@ -96,7 +102,7 @@ public class ProtocolLibComponent implements DisableListener, INotifyReload, Joi
} catch (ClassCastException e) {
t = e;
}
StaticLog.logWarning("[NoCheatPlus] Could not register packet level hook: " + name);
StaticLog.logWarning("Could not register packet level hook: " + name);
StaticLog.logWarning(t);
}
@ -107,7 +113,7 @@ public class ProtocolLibComponent implements DisableListener, INotifyReload, Joi
ProtocolLibrary.getProtocolManager().addPacketListener(adapter);
registeredPacketAdapters.add(adapter);
} catch (Throwable t) {
StaticLog.logWarning("[NoCheatPlus] Could not register packet level hook: " + clazz.getSimpleName());
StaticLog.logWarning("Could not register packet level hook: " + clazz.getSimpleName());
StaticLog.logWarning(t);
}
}
@ -132,7 +138,7 @@ public class ProtocolLibComponent implements DisableListener, INotifyReload, Joi
protocolManager.removePacketListener(adapter);
api.removeComponent(adapter); // Bit heavy, but consistent.
} catch (Throwable t) {
StaticLog.logWarning("[NoCheatPlus] Failed to unregister packet level hook: " + adapter.getClass().getName());
StaticLog.logWarning("Failed to unregister packet level hook: " + adapter.getClass().getName());
}// TODO Auto-generated method stub
}

View File

@ -11,10 +11,10 @@ import fr.neatmonster.nocheatplus.actions.types.DummyAction;
import fr.neatmonster.nocheatplus.logging.StaticLog;
public abstract class AbstractActionFactory <D extends ActionData, L extends AbstractActionList<D, L>>{
// TODO: static ?
// TODO: static ?
protected static final Map<String, Object> lib = new HashMap<String, Object>();
protected final ActionListFactory<D, L> listFactory;
protected final ActionListFactory<D, L> listFactory;
/**
* Instantiates a new action factory.
@ -23,14 +23,14 @@ public abstract class AbstractActionFactory <D extends ActionData, L extends Abs
* the library
*/
public AbstractActionFactory(final Map<String, Object> library, final ActionListFactory<D, L> listFactory) {
this.listFactory = listFactory;
this.listFactory = listFactory;
lib.putAll(library);
}
public abstract Action<D, L> createAction(String actionDefinition);
public abstract Action<D, L> createAction(String actionDefinition);
/**
* Creates a new Action object.
*
@ -42,7 +42,7 @@ public abstract class AbstractActionFactory <D extends ActionData, L extends Abs
*/
public L createActionList(final String definition, final String permission) {
final L list = listFactory.getNewActionList(permission);
// Do check for null, to allow removing default actions, for better robustness.
if (definition == null) return list;
@ -70,13 +70,13 @@ public abstract class AbstractActionFactory <D extends ActionData, L extends Abs
}
list.setActions(vl, createActions(def.split("\\s+")));
} catch (final Exception e) {
StaticLog.logWarning("[NoCheatPlus] Couldn't parse action definition 'vl:" + s + "'.");
StaticLog.logWarning("Couldn't parse action definition 'vl:" + s + "'.");
}
}
return list;
}
/**
* Creates a new Action object.
*
@ -84,8 +84,8 @@ public abstract class AbstractActionFactory <D extends ActionData, L extends Abs
* the definitions
* @return the action[]
*/
@SuppressWarnings("unchecked")
public Action<D, L>[] createActions(final String... definitions) {
@SuppressWarnings("unchecked")
public Action<D, L>[] createActions(final String... definitions) {
final List<Action<D, L>> actions = new ArrayList<Action<D, L>>();
for (final String def : definitions) {
@ -94,14 +94,14 @@ public abstract class AbstractActionFactory <D extends ActionData, L extends Abs
try {
actions.add(createAction(def));
} catch (final IllegalArgumentException e) {
StaticLog.logWarning("[NoCheatPlus] Failed to create action: " + e.getMessage());
StaticLog.logWarning("Failed to create action: " + e.getMessage());
actions.add(new DummyAction<D, L>(def));
}
}
return (Action<D, L>[]) actions.toArray(new Action<?, ?>[actions.size()]);
}
/**
* Parses the cmd action.
*
@ -125,7 +125,7 @@ public abstract class AbstractActionFactory <D extends ActionData, L extends Abs
delay = Integer.parseInt(parts[1]);
repeat = Integer.parseInt(parts[2]);
} catch (final Exception e) {
StaticLog.logWarning("[NoCheatPlus] Couldn't parse details of command '" + definition
StaticLog.logWarning("Couldn't parse details of command '" + definition
+ "', will use default values instead.");
delay = 0;
repeat = 0;

View File

@ -29,12 +29,12 @@ public class ActionFactory extends AbstractActionFactory<ViolationData, ActionLi
* the action definition
* @return the action
*/
public Action<ViolationData, ActionList> createAction(String actionDefinition) {
public Action<ViolationData, ActionList> createAction(String actionDefinition) {
actionDefinition = actionDefinition.toLowerCase();
if (actionDefinition.equals("cancel"))
return new CancelAction<ViolationData, ActionList>();
if (actionDefinition.startsWith("cmd:"))
return parseCmdAction(actionDefinition.split(":", 2)[1]);
@ -65,9 +65,9 @@ public class ActionFactory extends AbstractActionFactory<ViolationData, ActionLi
boolean toFile = true;
boolean toChat = true;
if (message == null)
throw new IllegalArgumentException("NoCheatPlus doesn't know log message '" + name
+ "'. Have you forgotten to define it?");
if (message == null) {
throw new IllegalArgumentException("Can't log, due to entry missing in strings: '" + name);
}
try {
delay = Integer.parseInt(parts[1]);
@ -76,9 +76,9 @@ public class ActionFactory extends AbstractActionFactory<ViolationData, ActionLi
toChat = parts[3].contains("i");
toFile = parts[3].contains("f");
} catch (final Exception e) {
StaticLog.logWarning("[NoCheatPlus] Couldn't parse details of log action '" + definition
StaticLog.logWarning("Couldn't parse details of log action '" + definition
+ "', will use default values instead.");
StaticLog.logWarning(e);
StaticLog.logWarning(e);
delay = 0;
repeat = 1;
toConsole = true;

View File

@ -38,7 +38,7 @@ public class CommandAction<D extends ParameterHolder, L extends AbstractActionLi
try {
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);
} catch (final CommandException e) {
StaticLog.logWarning("[NoCheatPlus] Failed to execute the command '" + command + "': " + e.getMessage()
StaticLog.logWarning("Failed to execute the command '" + command + "': " + e.getMessage()
+ ", please check if everything is setup correct.");
} catch (final Exception e) {
// I don't care in this case, your problem if your command fails.

View File

@ -1,7 +1,5 @@
package fr.neatmonster.nocheatplus.actions.types;
import org.bukkit.ChatColor;
import fr.neatmonster.nocheatplus.NCPAPIProvider;
import fr.neatmonster.nocheatplus.actions.Action;
import fr.neatmonster.nocheatplus.actions.ActionList;
@ -17,12 +15,6 @@ import fr.neatmonster.nocheatplus.utilities.ColorUtil;
*/
public class LogAction extends ActionWithParameters<ViolationData, ActionList> {
private static final String PREFIX_CHAT = ChatColor.RED + "NCP: "+ ChatColor.WHITE ;
private static final String PREFIX_CONSOLE= "[NoCheatPlus] ";
private static final String PREFIX_FILE = "";
// TODO: pull down to providers for (console), !chat!, (file) - then move to NCPCompat.
// Some flags to decide where the log message should show up, based on the configuration file.
/** Log to chat? */
public final boolean toChat;
@ -33,9 +25,6 @@ public class LogAction extends ActionWithParameters<ViolationData, ActionList> {
/** Log to file? */
public final boolean toFile;
/** Message prefixes. */
public final String prefixChat, prefixConsole, prefixFile;
/**
* Instantiates a new log action.
*
@ -61,33 +50,16 @@ public class LogAction extends ActionWithParameters<ViolationData, ActionList> {
this.toChat = toChat;
this.toConsole = toConsole;
this.toFile = toFile;
prefixChat = PREFIX_CHAT;
prefixConsole = PREFIX_CONSOLE;
prefixFile = PREFIX_FILE;
}
/**
* Constructor for optimized actions.
* @param name
* @param delay
* @param repeat
* @param prefixChat Prefixes set to null means deactivated.
* @param prefixConsole
* @param prefixFile
* @param message
*/
protected LogAction(final String name, final int delay, final int repeat, final String prefixChat,
final String prefixConsole, final String prefixFile, final String message) {
super(name, delay, repeat, message);
this.prefixChat = prefixChat;
this.prefixConsole = prefixConsole;
this.prefixFile = prefixFile;
toChat = prefixChat != null;
toConsole = prefixConsole != null;
toFile = prefixFile != null;
@Override
public Action<ViolationData, ActionList> getOptimizedCopy(final ConfigFileWithActions<ViolationData, ActionList> config, final Integer threshold) {
if (!config.getBoolean(ConfPaths.LOGGING_ACTIVE)) {
return null;
}
return this;
}
/*
* (non-Javadoc)
*
@ -101,13 +73,13 @@ public class LogAction extends ActionWithParameters<ViolationData, ActionList> {
final String message = super.getMessage(violationData);
final LogManager logManager = NCPAPIProvider.getNoCheatPlusAPI().getLogManager();
if (toChat) {
logManager.info(Streams.NOTIFY_INGAME, ColorUtil.replaceColors(prefixChat + message));
logManager.info(Streams.NOTIFY_INGAME, ColorUtil.replaceColors(message));
}
if (toConsole) {
logManager.info(Streams.SERVER_LOGGER, ColorUtil.removeColors(prefixConsole + message));
logManager.info(Streams.SERVER_LOGGER, ColorUtil.removeColors(message));
}
if (toFile) {
logManager.info(Streams.DEFAULT_FILE, ColorUtil.removeColors(prefixFile + message));
logManager.info(Streams.DEFAULT_FILE, ColorUtil.removeColors(message));
}
}
return false;
@ -124,35 +96,4 @@ public class LogAction extends ActionWithParameters<ViolationData, ActionList> {
+ (toFile ? "f" : "");
}
@Override
public Action<ViolationData, ActionList> getOptimizedCopy(final ConfigFileWithActions<ViolationData, ActionList> config, final Integer threshold) {
if (!config.getBoolean(ConfPaths.LOGGING_ACTIVE)) {
return null;
}
final String prefixChat = filterPrefix(config, ConfPaths.LOGGING_BACKEND_INGAMECHAT_PREFIX, PREFIX_CHAT, this.toChat && config.getBoolean(ConfPaths.LOGGING_BACKEND_INGAMECHAT_ACTIVE));
final String prefixConsole = filterPrefix(config, ConfPaths.LOGGING_BACKEND_CONSOLE_PREFIX, PREFIX_CONSOLE, this.toConsole && config.getBoolean(ConfPaths.LOGGING_BACKEND_CONSOLE_ACTIVE));
final String prefixFile = filterPrefix(config, ConfPaths.LOGGING_BACKEND_FILE_PREFIX, PREFIX_FILE, this.toFile && config.getBoolean(ConfPaths.LOGGING_BACKEND_FILE_ACTIVE));
if (allNull(prefixChat, prefixConsole, prefixFile)) {
return null;
}
return new LogAction(name, delay, repeat, prefixChat, prefixConsole, prefixFile, message);
}
private static boolean allNull(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (objects[i] != null) {
return false;
}
}
return true;
}
private static final String filterPrefix(final ConfigFileWithActions<ViolationData, ActionList> config, final String path, final String defaultValue, final boolean use) {
if (!use) {
return null;
}
final String prefix = config.getString(path);
return prefix == null ? defaultValue : prefix;
}
}

View File

@ -120,7 +120,7 @@ public class Text extends Check implements INotifyReload {
final List<String> debugParts;
if (debug) {
debugParts = new LinkedList<String>();
debugParts.add("[NoCheatPlus][chat.text] Message ("+player.getName()+"/"+message.length()+"): ");
debugParts.add("[chat.text] Message ("+player.getName()+"/"+message.length()+"): ");
}
else debugParts = null;

View File

@ -33,109 +33,109 @@ import fr.neatmonster.nocheatplus.logging.StaticLog;
*
*/
public class LetterEngine implements IRemoveData, IHaveCheckType, ConsistencyChecker{
/** Global processors */
protected final List<WordProcessor> processors = new ArrayList<WordProcessor>();
/**
* Mapping players to data.
*/
protected final EnginePlayerDataMap dataMap;
public LetterEngine(ConfigFile config){
// Add word processors.
// NOTE: These settings should be compared to the per player settings done in the EnginePlayerConfig constructor.
if (config.getBoolean(ConfPaths.CHAT_TEXT_GL_WORDS_CHECK, false)){
FlatWordsSettings settings = new FlatWordsSettings();
settings.maxSize = 1000;
settings.applyConfig(config, ConfPaths.CHAT_TEXT_GL_WORDS);
processors.add(new FlatWords("glWords",settings));
}
if (config.getBoolean(ConfPaths.CHAT_TEXT_GL_PREFIXES_CHECK , false)){
WordPrefixesSettings settings = new WordPrefixesSettings();
settings.maxAdd = 2000;
settings.applyConfig(config, ConfPaths.CHAT_TEXT_GL_PREFIXES);
processors.add(new WordPrefixes("glPrefixes", settings));
}
if (config.getBoolean(ConfPaths.CHAT_TEXT_GL_SIMILARITY_CHECK , false)){
SimilarWordsBKLSettings settings = new SimilarWordsBKLSettings();
settings.maxSize = 1000;
settings.applyConfig(config, ConfPaths.CHAT_TEXT_GL_SIMILARITY);
processors.add(new SimilarWordsBKL("glSimilarity", settings));
}
// TODO: At least expiration duration configurable? (Entries expire after 10 minutes.)
dataMap = new EnginePlayerDataMap(600000L, 100, 0.75f);
}
public Map<String, Float> process(final MessageLetterCount letterCount, final String playerName, final ChatConfig cc, final ChatData data){
final Map<String, Float> result = new HashMap<String, Float>();
// Global processors.
if (cc.textGlobalCheck){
for (final WordProcessor processor : processors){
try{
result.put(processor.getProcessorName(), processor.process(letterCount) * cc.textGlobalWeight);
}
catch( final Exception e){
StaticLog.logSevere("[NoCheatPlus] chat.text: processor("+processor.getProcessorName()+") generated an exception: " + e.getClass().getSimpleName() + ": " + e.getMessage());
StaticLog.logSevere(e);
continue;
}
}
}
// Per player processors.
if (cc.textPlayerCheck){
final EnginePlayerData engineData = dataMap.get(playerName, cc);
for (final WordProcessor processor : engineData.processors){
try{
result.put(processor.getProcessorName(), processor.process(letterCount) * cc.textPlayerWeight);
}
catch( final Exception e){
StaticLog.logSevere("[NoCheatPlus] chat.text: processor("+processor.getProcessorName()+") generated an exception: " + e.getClass().getSimpleName() + ": " + e.getMessage());
StaticLog.logSevere(e);
continue;
}
}
}
return result;
}
public void clear() {
for (WordProcessor processor : processors){
processor.clear();
}
processors.clear();
dataMap.clear();
}
/** Global processors */
protected final List<WordProcessor> processors = new ArrayList<WordProcessor>();
@Override
public IData removeData(final String playerName) {
return dataMap.remove(playerName);
}
/**
* Mapping players to data.
*/
protected final EnginePlayerDataMap dataMap;
@Override
public void removeAllData() {
dataMap.clear();
}
public LetterEngine(ConfigFile config){
// Add word processors.
// NOTE: These settings should be compared to the per player settings done in the EnginePlayerConfig constructor.
if (config.getBoolean(ConfPaths.CHAT_TEXT_GL_WORDS_CHECK, false)){
FlatWordsSettings settings = new FlatWordsSettings();
settings.maxSize = 1000;
settings.applyConfig(config, ConfPaths.CHAT_TEXT_GL_WORDS);
processors.add(new FlatWords("glWords",settings));
}
if (config.getBoolean(ConfPaths.CHAT_TEXT_GL_PREFIXES_CHECK , false)){
WordPrefixesSettings settings = new WordPrefixesSettings();
settings.maxAdd = 2000;
settings.applyConfig(config, ConfPaths.CHAT_TEXT_GL_PREFIXES);
processors.add(new WordPrefixes("glPrefixes", settings));
}
if (config.getBoolean(ConfPaths.CHAT_TEXT_GL_SIMILARITY_CHECK , false)){
SimilarWordsBKLSettings settings = new SimilarWordsBKLSettings();
settings.maxSize = 1000;
settings.applyConfig(config, ConfPaths.CHAT_TEXT_GL_SIMILARITY);
processors.add(new SimilarWordsBKL("glSimilarity", settings));
}
// TODO: At least expiration duration configurable? (Entries expire after 10 minutes.)
dataMap = new EnginePlayerDataMap(600000L, 100, 0.75f);
}
@Override
public final CheckType getCheckType() {
return CheckType.CHAT_TEXT;
}
public Map<String, Float> process(final MessageLetterCount letterCount, final String playerName, final ChatConfig cc, final ChatData data){
@Override
public void checkConsistency(final Player[] onlinePlayers) {
// Use consistency checking to release some memory.
final long now = System.currentTimeMillis();
if (now < dataMap.lastExpired){
dataMap.clear();
return;
}
if (now - dataMap.lastExpired > dataMap.durExpire){
dataMap.expire(now - dataMap.durExpire);
}
}
final Map<String, Float> result = new HashMap<String, Float>();
// Global processors.
if (cc.textGlobalCheck){
for (final WordProcessor processor : processors){
try{
result.put(processor.getProcessorName(), processor.process(letterCount) * cc.textGlobalWeight);
}
catch( final Exception e){
StaticLog.logSevere("chat.text: processor("+processor.getProcessorName()+") generated an exception: " + e.getClass().getSimpleName() + ": " + e.getMessage());
StaticLog.logSevere(e);
continue;
}
}
}
// Per player processors.
if (cc.textPlayerCheck){
final EnginePlayerData engineData = dataMap.get(playerName, cc);
for (final WordProcessor processor : engineData.processors){
try{
result.put(processor.getProcessorName(), processor.process(letterCount) * cc.textPlayerWeight);
}
catch( final Exception e){
StaticLog.logSevere("chat.text: processor("+processor.getProcessorName()+") generated an exception: " + e.getClass().getSimpleName() + ": " + e.getMessage());
StaticLog.logSevere(e);
continue;
}
}
}
return result;
}
public void clear() {
for (WordProcessor processor : processors){
processor.clear();
}
processors.clear();
dataMap.clear();
}
@Override
public IData removeData(final String playerName) {
return dataMap.remove(playerName);
}
@Override
public void removeAllData() {
dataMap.clear();
}
@Override
public final CheckType getCheckType() {
return CheckType.CHAT_TEXT;
}
@Override
public void checkConsistency(final Player[] onlinePlayers) {
// Use consistency checking to release some memory.
final long now = System.currentTimeMillis();
if (now < dataMap.lastExpired){
dataMap.clear();
return;
}
if (now - dataMap.lastExpired > dataMap.durExpire){
dataMap.expire(now - dataMap.durExpire);
}
}
}

View File

@ -107,7 +107,7 @@ public class CombinedConfig extends ACheckConfig {
}
catch (final Exception e){
error = true;
StaticLog.logWarning("[NoCheatPlus] Bad damage cause (combined.invulnerable.ignore): " + input);
StaticLog.logWarning("Bad damage cause (combined.invulnerable.ignore): " + input);
}
}
// Read modifiers for causes.
@ -125,11 +125,11 @@ public class CombinedConfig extends ACheckConfig {
}
catch (final Exception e){
error = true;
StaticLog.logWarning("[NoCheatPlus] Bad damage cause (combined.invulnerable.modifiers): " + input);
StaticLog.logWarning("Bad damage cause (combined.invulnerable.modifiers): " + input);
}
}
invulnerableModifierDefault = defaultMod;
if (error) StaticLog.logInfo("[NoCheatPlus] Damage causes can be: " + StringUtil.join(Arrays.asList(DamageCause.values()), ", "));
if (error) StaticLog.logInfo("Damage causes can be: " + StringUtil.join(Arrays.asList(DamageCause.values()), ", "));
invulnerableTriggerAlways = config.getBoolean(ConfPaths.COMBINED_INVULNERABLE_TRIGGERS_ALWAYS);
invulnerableTriggerFallDistance = config.getBoolean(ConfPaths.COMBINED_INVULNERABLE_TRIGGERS_FALLDISTANCE);

View File

@ -864,7 +864,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
*/
private void onVehicleLeaveMiss(final Player player, final MovingData data, final MovingConfig cc) {
if (data.debug) {
StaticLog.logWarning("[NoCheatPlus] VehicleExitEvent missing for: " + player.getName());
StaticLog.logWarning("VehicleExitEvent missing for: " + player.getName());
}
onPlayerVehicleLeave(player, null);
// if (BlockProperties.isRails(pFrom.getTypeId())) {
@ -1220,7 +1220,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
// A little extra sweep to check for debug flags.
normalVehicles.add(entityType);
if (MovingConfig.getConfig(vehicle.getWorld().getName()).debug) {
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, "[NoCheatPlus] VehicleMoveEvent fired for: " + entityType);
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().debug(Streams.TRACE_FILE, "VehicleMoveEvent fired for: " + entityType);
}
}
// TODO: Might account for the case of a player letting the vehicle move but not themselves (do mind latency).
@ -1424,7 +1424,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
final int loaded = BlockCache.ensureChunksLoaded(loc.getWorld(), loc.getX(), loc.getZ(), 3.0);
if (loaded > 0 && data.debug && BuildParameters.debugLevel > 0) {
// DEBUG
StaticLog.logInfo("[NoCheatPlus] Player " + tag + ": Loaded " + loaded + " chunk" + (loaded == 1 ? "" : "s") + " for the world " + loc.getWorld().getName() + " for player: " + player.getName());
StaticLog.logInfo("Player " + tag + ": Loaded " + loaded + " chunk" + (loaded == 1 ? "" : "s") + " for the world " + loc.getWorld().getName() + " for player: " + player.getName());
}
}
@ -1504,7 +1504,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
final Location loc = player.getLocation(useLoc);
// Debug logout.
if (data.debug) {
StaticLog.logInfo("[NoCheatPlus] Player " + player.getName() + " leaves at location: " + loc.toString());
StaticLog.logInfo("Player " + player.getName() + " leaves at location: " + loc.toString());
}
if (!player.isSleeping() && !player.isDead()) {
// Check for missed moves.
@ -1517,15 +1517,15 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
// TODO: Consider to always set back here. Might skip on big distances.
if (TrigUtil.manhattan(loc, refLoc) > 0 || BlockProperties.isPassable(refLoc)) {
if (passable.isEnabled(player)) {
StaticLog.logWarning("[NoCheatPlus] Potential exploit: Player " + player.getName() + " leaves, having moved into a block (not tracked by moving checks): " + player.getWorld().getName() + " / " + DebugUtil.formatMove(refLoc, loc));
StaticLog.logWarning("Potential exploit: Player " + player.getName() + " leaves, having moved into a block (not tracked by moving checks): " + player.getWorld().getName() + " / " + DebugUtil.formatMove(refLoc, loc));
// TODO: Actually trigger a passable violation (+tag).
if (d > 1.25) {
StaticLog.logWarning("[NoCheatPlus] SKIP set-back for " + player.getName() + ", because distance is too high (risk of false positives): " + d);
StaticLog.logWarning("SKIP set-back for " + player.getName() + ", because distance is too high (risk of false positives): " + d);
} else {
StaticLog.logInfo("[NoCheatPlus] Set back player " + player.getName() + ": " + DebugUtil.formatLocation(refLoc));
StaticLog.logInfo("Set back player " + player.getName() + ": " + DebugUtil.formatLocation(refLoc));
data.prepareSetBack(refLoc);
if (!player.teleport(refLoc)) {
StaticLog.logWarning("[NoCheatPlus] FAILED to set back player " + player.getName());
StaticLog.logWarning("FAILED to set back player " + player.getName());
}
}
}
@ -1806,7 +1806,7 @@ public class MovingListener extends CheckListener implements TickListener, IRemo
final int loaded = info.from.ensureChunksLoaded();
if (loaded > 0 && data.debug && BuildParameters.debugLevel > 0) {
// DEBUG
StaticLog.logInfo("[NoCheatPlus] Hover check: Needed to load " + loaded + " chunk" + (loaded == 1 ? "" : "s") + " for the world " + loc.getWorld().getName() + " around " + loc.getBlockX() + "," + loc.getBlockZ() + " in order to check player: " + player.getName());
StaticLog.logInfo("Hover check: Needed to load " + loaded + " chunk" + (loaded == 1 ? "" : "s") + " for the world " + loc.getWorld().getName() + " around " + loc.getBlockX() + "," + loc.getBlockZ() + " in order to check player: " + player.getName());
}
if (info.from.isOnGroundOrResetCond() || info.from.isAboveLadder() || info.from.isAboveStairs()) {
res = true;

View File

@ -15,6 +15,8 @@ import fr.neatmonster.nocheatplus.permissions.Permissions;
*/
public class NetConfig extends ACheckConfig {
public final boolean attackFrequencyActive;
public final boolean flyingFrequencyActive;
public final int flyingFrequencySeconds;
public final double flyingFrequencyPPS;
@ -33,10 +35,16 @@ public class NetConfig extends ACheckConfig {
public NetConfig(final ConfigFile config) {
super(config, ConfPaths.NET, new String[] {
Permissions.NET_FLYINGFREQUENCY, Permissions.NET_KEEPALIVEFREQUENCY
Permissions.NET_ATTACKFREQUENCY,
Permissions.NET_FLYINGFREQUENCY,
Permissions.NET_KEEPALIVEFREQUENCY,
});
final ConfigFile globalConfig = ConfigManager.getConfigFile();
attackFrequencyActive = config.getBoolean(ConfPaths.NET_ATTACKFREQUENCY_ACTIVE);
// TODO: Others.
flyingFrequencyActive = config.getBoolean(ConfPaths.NET_FLYINGFREQUENCY_ACTIVE);
flyingFrequencySeconds = Math.max(1, globalConfig.getInt(ConfPaths.NET_FLYINGFREQUENCY_SECONDS));
flyingFrequencyPPS = Math.max(1.0, globalConfig.getDouble(ConfPaths.NET_FLYINGFREQUENCY_PACKETSPERSECOND));
@ -59,6 +67,8 @@ public class NetConfig extends ACheckConfig {
@Override
public boolean isEnabled(final CheckType checkType) {
switch(checkType) {
case NET_ATTACKFREQUENCY:
return attackFrequencyActive;
case NET_FLYINGFREQUENCY:
return flyingFrequencyActive;
case NET_SOUNDDISTANCE:

View File

@ -61,7 +61,7 @@ public abstract class AbstractCommand<A> implements TabExecutor{
if (sender instanceof Player) {
return true;
} else {
sender.sendMessage("[NoCheatPlus] A player is required to run this command.");
sender.sendMessage("A player is required to run this command.");
return false;
}
}
@ -75,7 +75,7 @@ public abstract class AbstractCommand<A> implements TabExecutor{
if (sender instanceof ConsoleCommandSender) {
return true;
} else {
sender.sendMessage("[NoCheatPlus] This command can only be run from the console.");
sender.sendMessage("This command can only be run from the console.");
return false;
}
}

View File

@ -19,71 +19,71 @@ import fr.neatmonster.nocheatplus.utilities.IdUtil;
public class BanCommand extends BaseCommand {
public BanCommand(JavaPlugin plugin) {
super(plugin, "ban", Permissions.COMMAND_BAN);
}
public BanCommand(JavaPlugin plugin) {
super(plugin, "ban", Permissions.COMMAND_BAN);
}
@Override
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) {
if (!demandConsoleCommandSender(sender)) {
return true;
}
// TODO: Consider supporting vanilla syntax or removing this command :p.
// Args contains "ban" as first arg.
if (args.length < 2) {
return false;
}
final String name = args[1].trim();
final String reason;
if (args.length > 2) {
reason = AbstractCommand.join(args, 2);
}
else {
reason = "";
}
ban(sender, name, reason);
return true;
}
/**
*
* @param sender
* @param name Trimmed name.
* @param reason
*/
void ban(CommandSender sender, String name, String reason) {
final Server server = Bukkit.getServer();
Player player = DataManager.getPlayer(name);
// Pro logic below.
if (player == null && !IdUtil.isValidMinecraftUserName(name)) {
UUID id = IdUtil.UUIDFromStringSafe(name);
if (id != null) {
StaticLog.logWarning("Banning by UUID might not work (" + id.toString()+"), relay to the vanilla command.");
} else {
StaticLog.logWarning("Might not be a valid user name: " + name);
}
}
if (player != null){
player.kickPlayer(reason);
}
// Relay to the server command for compatibility reasons.
server.dispatchCommand(server.getConsoleSender(), "ban " + name);
logBan(sender, player, name, reason);
}
private void logBan(CommandSender sender, Player player, String name, String reason) {
StaticLog.logInfo("[NoCheatPlus] (" + sender.getName() + ") Banned " + name + (player != null ? ("/" + player.getName()) : "") + " : " + reason);
}
@Override
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) {
if (!demandConsoleCommandSender(sender)) {
return true;
}
// TODO: Consider supporting vanilla syntax or removing this command :p.
/* (non-Javadoc)
* @see fr.neatmonster.nocheatplus.command.AbstractCommand#onTabComplete(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
// TODO: Consider adding player names and other.
return null;
}
// Args contains "ban" as first arg.
if (args.length < 2) {
return false;
}
final String name = args[1].trim();
final String reason;
if (args.length > 2) {
reason = AbstractCommand.join(args, 2);
}
else {
reason = "";
}
ban(sender, name, reason);
return true;
}
/**
*
* @param sender
* @param name Trimmed name.
* @param reason
*/
void ban(CommandSender sender, String name, String reason) {
final Server server = Bukkit.getServer();
Player player = DataManager.getPlayer(name);
// Pro logic below.
if (player == null && !IdUtil.isValidMinecraftUserName(name)) {
UUID id = IdUtil.UUIDFromStringSafe(name);
if (id != null) {
StaticLog.logWarning("Banning by UUID might not work (" + id.toString()+"), relay to the vanilla command.");
} else {
StaticLog.logWarning("Might not be a valid user name: " + name);
}
}
if (player != null){
player.kickPlayer(reason);
}
// Relay to the server command for compatibility reasons.
server.dispatchCommand(server.getConsoleSender(), "ban " + name);
logBan(sender, player, name, reason);
}
private void logBan(CommandSender sender, Player player, String name, String reason) {
StaticLog.logInfo("(" + sender.getName() + ") Banned " + name + (player != null ? ("/" + player.getName()) : "") + " : " + reason);
}
/* (non-Javadoc)
* @see fr.neatmonster.nocheatplus.command.AbstractCommand#onTabComplete(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
// TODO: Consider adding player names and other.
return null;
}
}

View File

@ -16,48 +16,48 @@ import fr.neatmonster.nocheatplus.players.DataManager;
public class DenyLoginCommand extends BaseCommand {
public DenyLoginCommand(JavaPlugin plugin) {
super(plugin, "denylogin", Permissions.COMMAND_DENYLOGIN,
new String[]{"tempkick", "tkick", "tempban", "tban",});
}
public DenyLoginCommand(JavaPlugin plugin) {
super(plugin, "denylogin", Permissions.COMMAND_DENYLOGIN,
new String[]{"tempkick", "tkick", "tempban", "tban",});
}
@Override
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) {
// Args contains sub command label as first arg.
if (args.length < 3) return false;
long base = 60000; // minutes (!)
final String name = args[1];
long duration = -1;
try{
// TODO: parse for abbreviations like 30s 30m 30h 30d, and set base...
duration = Integer.parseInt(args[2]);
}
catch( NumberFormatException e){};
if (duration <= 0) return false;
final long finalDuration = duration * base;
final String reason;
if (args.length > 3) reason = AbstractCommand.join(args, 3);
else reason = "";
denyLogin(sender, name, finalDuration, reason);
return true;
}
@Override
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) {
// Args contains sub command label as first arg.
if (args.length < 3) return false;
long base = 60000; // minutes (!)
final String name = args[1];
long duration = -1;
try{
// TODO: parse for abbreviations like 30s 30m 30h 30d, and set base...
duration = Integer.parseInt(args[2]);
}
catch( NumberFormatException e){};
if (duration <= 0) return false;
final long finalDuration = duration * base;
final String reason;
if (args.length > 3) reason = AbstractCommand.join(args, 3);
else reason = "";
denyLogin(sender, name, finalDuration, reason);
return true;
}
protected void denyLogin(CommandSender sender, String name, long duration, String reason){
Player player = DataManager.getPlayer(name);
NCPAPIProvider.getNoCheatPlusAPI().denyLogin(name, duration);
if (player == null) return;
player.kickPlayer(reason);
StaticLog.logInfo("[NoCheatPlus] (" + sender.getName() + ") Kicked " + player.getName() + " for " + duration/60000 +" minutes: " + reason);
}
/* (non-Javadoc)
* @see fr.neatmonster.nocheatplus.command.AbstractCommand#onTabComplete(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public List<String> onTabComplete(CommandSender sender, Command command,
String alias, String[] args) {
return null;
}
protected void denyLogin(CommandSender sender, String name, long duration, String reason){
Player player = DataManager.getPlayer(name);
NCPAPIProvider.getNoCheatPlusAPI().denyLogin(name, duration);
if (player == null) return;
player.kickPlayer(reason);
StaticLog.logInfo("(" + sender.getName() + ") Kicked " + player.getName() + " for " + duration/60000 +" minutes: " + reason);
}
/* (non-Javadoc)
* @see fr.neatmonster.nocheatplus.command.AbstractCommand#onTabComplete(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public List<String> onTabComplete(CommandSender sender, Command command,
String alias, String[] args) {
return null;
}
}

View File

@ -15,39 +15,39 @@ import fr.neatmonster.nocheatplus.players.DataManager;
public class KickCommand extends BaseCommand {
public KickCommand(JavaPlugin plugin) {
super(plugin, "kick", Permissions.COMMAND_KICK);
}
public KickCommand(JavaPlugin plugin) {
super(plugin, "kick", Permissions.COMMAND_KICK);
}
@Override
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) {
if (!demandConsoleCommandSender(sender)) {
return true;
}
// Args contains "kick" as first arg.
if (args.length < 2) return false;
final String name = args[1];
final String reason;
if (args.length > 2) reason = AbstractCommand.join(args, 2);
else reason = "";
kick(sender, name, reason);
return true;
}
void kick(CommandSender sender, String name, String reason) {
Player player = DataManager.getPlayer(name);
if (player == null) return;
player.kickPlayer(reason);
StaticLog.logInfo("[NoCheatPlus] (" + sender.getName() + ") Kicked " + player.getName() + " : " + reason);
}
@Override
public boolean onCommand(final CommandSender sender, Command command, String label, String[] args) {
if (!demandConsoleCommandSender(sender)) {
return true;
}
// Args contains "kick" as first arg.
if (args.length < 2) return false;
final String name = args[1];
final String reason;
if (args.length > 2) reason = AbstractCommand.join(args, 2);
else reason = "";
kick(sender, name, reason);
return true;
}
void kick(CommandSender sender, String name, String reason) {
Player player = DataManager.getPlayer(name);
if (player == null) return;
player.kickPlayer(reason);
StaticLog.logInfo("(" + sender.getName() + ") Kicked " + player.getName() + " : " + reason);
}
/* (non-Javadoc)
* @see fr.neatmonster.nocheatplus.command.AbstractCommand#onTabComplete(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public List<String> onTabComplete(CommandSender sender, Command command,
String alias, String[] args) {
return null;
}
/* (non-Javadoc)
* @see fr.neatmonster.nocheatplus.command.AbstractCommand#onTabComplete(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public List<String> onTabComplete(CommandSender sender, Command command,
String alias, String[] args) {
return null;
}
}

View File

@ -34,7 +34,7 @@ public class InspectCommand extends BaseCommand {
if (sender instanceof Player) {
args = new String[]{args[0], sender.getName()};
} else {
sender.sendMessage("[NoCheatPlus] Please specify a player to inspect.");
sender.sendMessage(TAG + "Please specify a player to inspect.");
return true;
}
}

View File

@ -22,23 +22,23 @@ import fr.neatmonster.nocheatplus.players.DataManager;
import fr.neatmonster.nocheatplus.utilities.StringUtil;
public class ReloadCommand extends BaseCommand {
/** Components that need to be notified on reload */
private final List<INotifyReload> notifyReload;
public ReloadCommand(JavaPlugin plugin, List<INotifyReload> notifyReload) {
super(plugin, "reload", Permissions.COMMAND_RELOAD);
this.notifyReload = notifyReload;
}
/** Components that need to be notified on reload */
private final List<INotifyReload> notifyReload;
@Override
public boolean onCommand(CommandSender sender, Command command, String label,
String[] args) {
if (args.length != 1) return false;
public ReloadCommand(JavaPlugin plugin, List<INotifyReload> notifyReload) {
super(plugin, "reload", Permissions.COMMAND_RELOAD);
this.notifyReload = notifyReload;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label,
String[] args) {
if (args.length != 1) return false;
handleReloadCommand(sender);
return true;
}
}
/**
* Handle the '/nocheatplus reload' command.
*
@ -51,7 +51,7 @@ public class ReloadCommand extends BaseCommand {
if (!sender.equals(Bukkit.getConsoleSender())) {
sender.sendMessage(TAG + "Reloading configuration...");
}
logManager.info(Streams.INIT, "[NoCheatPlus] Reloading configuration...");
logManager.info(Streams.INIT, TAG + "Reloading configuration...");
// Do the actual reload.
ConfigManager.cleanup();
@ -59,35 +59,35 @@ public class ReloadCommand extends BaseCommand {
if (logManager instanceof INotifyReload) { // TODO: This is a band-aid.
((INotifyReload) logManager).onReload();
}
// Remove all cached configs.
DataManager.clearConfigs(); // There you have to add XConfig.clear() form now on.
// Remove some checks data.
// TODO: Better concept (INotifyReload).
for (final CheckType checkType : new CheckType[]{
CheckType.BLOCKBREAK, CheckType.FIGHT,
CheckType.BLOCKBREAK, CheckType.FIGHT,
}){
DataManager.clearData(checkType);
DataManager.clearData(checkType);
}
// Reset debug flags to default (temp, heavy).
DataManager.restoreDefaultDebugFlags();
// Tell the registered listeners to adapt to new config, first sort them (!).
Collections.sort(notifyReload, Order.cmpSetupOrder);
for (final INotifyReload component : notifyReload){
component.onReload();
component.onReload();
}
// Say to the other plugins that we've reloaded the configuration.
Bukkit.getPluginManager().callEvent(new NCPReloadEvent());
// Log reloading done.
if (!sender.equals(Bukkit.getConsoleSender())) {
sender.sendMessage(TAG + "Configuration reloaded!");
}
logManager.info(Streams.INIT, "[NoCheatPlus] Configuration reloaded.");
logManager.info(Streams.INIT, TAG + "Configuration reloaded.");
logManager.info(Streams.DEFAULT_FILE, StringUtil.join(VersionCommand.getVersionInfo(), "\n")); // Queued (!).
}

View File

@ -11,26 +11,26 @@ import fr.neatmonster.nocheatplus.players.DataManager;
public class NotifyOffCommand extends BaseCommand {
public NotifyOffCommand(JavaPlugin plugin) {
super(plugin, "off", null, new String[]{"0", "-"});
}
public NotifyOffCommand(JavaPlugin plugin) {
super(plugin, "off", null, new String[]{"0", "-"});
}
/* (non-Javadoc)
* @see fr.neatmonster.nocheatplus.command.AbstractCommand#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if (args.length != 2){
return false;
}
if (!(sender instanceof Player)){
// TODO: Might implement if upvoted a lot.
sender.sendMessage("[NoCheatPlus] Toggling notifications is only available for online players.");
return true;
}
DataManager.getPlayerData(sender.getName(), true).setNotifyOff(true);
sender.sendMessage(TAG + "Notifications are now turned " + ChatColor.RED + "off" + ChatColor.WHITE + ".");
return true;
}
/* (non-Javadoc)
* @see fr.neatmonster.nocheatplus.command.AbstractCommand#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if (args.length != 2){
return false;
}
if (!(sender instanceof Player)){
// TODO: Might implement if upvoted a lot.
sender.sendMessage(TAG + "Toggling notifications is only available for online players.");
return true;
}
DataManager.getPlayerData(sender.getName(), true).setNotifyOff(true);
sender.sendMessage(TAG + "Notifications are now turned " + ChatColor.RED + "off" + ChatColor.WHITE + ".");
return true;
}
}

View File

@ -11,26 +11,26 @@ import fr.neatmonster.nocheatplus.players.DataManager;
public class NotifyOnCommand extends BaseCommand {
public NotifyOnCommand(JavaPlugin plugin) {
super(plugin, "on", null, new String[]{"1", "+"});
}
/* (non-Javadoc)
* @see fr.neatmonster.nocheatplus.command.AbstractCommand#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if (args.length != 2){
return false;
}
if (!(sender instanceof Player)){
// TODO: Might implement if upvoted a lot.
sender.sendMessage("[NoCheatPlus] Toggling notifications is only available for online players.");
return true;
}
DataManager.getPlayerData(sender.getName(), true).setNotifyOff(false);
sender.sendMessage(TAG + "Notifications are now turned " + ChatColor.YELLOW + "on" + ChatColor.WHITE + ".");
return true;
}
public NotifyOnCommand(JavaPlugin plugin) {
super(plugin, "on", null, new String[]{"1", "+"});
}
/* (non-Javadoc)
* @see fr.neatmonster.nocheatplus.command.AbstractCommand#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if (args.length != 2){
return false;
}
if (!(sender instanceof Player)){
// TODO: Might implement if upvoted a lot.
sender.sendMessage(TAG + "Toggling notifications is only available for online players.");
return true;
}
DataManager.getPlayerData(sender.getName(), true).setNotifyOff(false);
sender.sendMessage(TAG + "Notifications are now turned " + ChatColor.YELLOW + "on" + ChatColor.WHITE + ".");
return true;
}
}

View File

@ -222,7 +222,7 @@ public class BridgeHealth {
private static void checkLogEntry(final String tag) {
// New entry.
if (ConfigManager.getConfigFile().getBoolean(ConfPaths.LOGGING_EXTENDED_STATUS)){
StaticLog.logInfo("[NoCheatPlus] Try old health API: " + tag);
StaticLog.logInfo("Try old health API: " + tag);
}
}

View File

@ -87,7 +87,7 @@ public class BlocksMC1_5 implements BlockPropertiesSetup {
// 95 Locked chest
BlockProperties.setBlockProps(95, BlockProperties.instantType);
StaticLog.logInfo("[NoCheatPlus] Added block-info for Minecraft 1.5 blocks.");
StaticLog.logInfo("Added block-info for Minecraft 1.5 blocks.");
}
}

View File

@ -38,7 +38,7 @@ public class BlocksMC1_6_1 implements BlockPropertiesSetup{
BlockProperties.setBlockProps(171, new BlockProps(BlockProperties.noTool, 0.1f, BlockProperties.secToMs(0.15)));
BlockProperties.setBlockFlags(171, BlockProperties.F_GROUND|BlockProperties.F_IGN_PASSABLE|BlockProperties.F_GROUND_HEIGHT);
StaticLog.logInfo("[NoCheatPlus] Added block-info for Minecraft 1.6.1 blocks.");
StaticLog.logInfo("Added block-info for Minecraft 1.6.1 blocks.");
}
}

View File

@ -56,7 +56,7 @@ public class BlocksMC1_7_2 implements BlockPropertiesSetup{
BlockProperties.setBlockProps(BlockProperties.getId(mat), diamondType);
}
StaticLog.logInfo("[NoCheatPlus] Added block-info for Minecraft 1.7.2 blocks.");
StaticLog.logInfo("Added block-info for Minecraft 1.7.2 blocks.");
}
}

View File

@ -131,7 +131,7 @@ public class BlocksMC1_8 implements BlockPropertiesSetup {
// 197(DARK_OAK_DOOR
BlockInit.setAs(197, Material.WOODEN_DOOR);
StaticLog.logInfo("[NoCheatPlus] Added block-info for Minecraft 1.8 blocks.");
StaticLog.logInfo("Added block-info for Minecraft 1.8 blocks.");
}
}

View File

@ -29,7 +29,7 @@ public class VanillaBlocksFactory {
// TODO: Do logging from here ?
}
catch(Throwable t){
StaticLog.logSevere("[NoCheatPlus] " + setup.getClass().getSimpleName() + ".setupBlockProperties could not execute properly: " + t.getClass().getSimpleName() + " - " + t.getMessage());
StaticLog.logSevere(setup.getClass().getSimpleName() + ".setupBlockProperties could not execute properly: " + t.getClass().getSimpleName() + " - " + t.getMessage());
StaticLog.logSevere(t);
// Abort further processing.
break;

View File

@ -38,7 +38,6 @@ public abstract class ConfPaths {
private static final String LOGGING_BACKEND = LOGGING + "backend.";
private static final String LOGGING_BACKEND_CONSOLE = LOGGING_BACKEND + "console.";
public static final String LOGGING_BACKEND_CONSOLE_ACTIVE = LOGGING_BACKEND_CONSOLE + "active";
public static final String LOGGING_BACKEND_CONSOLE_PREFIX = LOGGING_BACKEND_CONSOLE + "prefix";
public static final String LOGGING_BACKEND_CONSOLE_ASYNCHRONOUS = LOGGING_BACKEND_CONSOLE + "asynchronous";
private static final String LOGGING_BACKEND_FILE = LOGGING_BACKEND + "file.";
public static final String LOGGING_BACKEND_FILE_ACTIVE = LOGGING_BACKEND_FILE + "active";
@ -613,6 +612,10 @@ public abstract class ConfPaths {
public static final String NET = CHECKS + "net.";
private static final String NET_ATTACKFREQUENCY = NET + "attackfrequency.";
public static final String NET_ATTACKFREQUENCY_ACTIVE = NET_ATTACKFREQUENCY + "active";
// TODO: Parameters / concept.
private static final String NET_FLYINGFREQUENCY = NET + "flyingfrequency.";
public static final String NET_FLYINGFREQUENCY_ACTIVE = NET_FLYINGFREQUENCY + "active";
@GlobalConfig
@ -717,5 +720,7 @@ public abstract class ConfPaths {
public static final String COMPATIBILITY_BUKKITONLY = "compatibility.bukkitapionly";
@Deprecated
public static final String MOVING_SURVIVALFLY_BEDSTEP ="checks.moving.survivalfly.bedstep";
@Deprecated
public static final String LOGGING_BACKEND_CONSOLE_PREFIX = "logging.backend.console.prefix";
}

View File

@ -207,11 +207,11 @@ public class ConfigManager {
globalConfig.save(globalFile);
}
} catch (final Exception e) {
StaticLog.logSevere("[NoCheatPlus] Could not save back config.yml (see exception below).");
StaticLog.logSevere("Could not save back config.yml (see exception below).");
StaticLog.logSevere(e);
}
} catch (final Exception e) {
StaticLog.logSevere("[NoCheatPlus] Could not load config.yml (see exception below). Continue with default settings...");
StaticLog.logSevere("Could not load config.yml (see exception below). Continue with default settings...");
StaticLog.logSevere(e);
}
}
@ -257,11 +257,11 @@ public class ConfigManager {
try{
if (worldConfig.getBoolean(ConfPaths.SAVEBACKCONFIG)) worldConfig.save(worldFile);
} catch (final Exception e){
StaticLog.logSevere("[NoCheatPlus] Couldn't save back world-specific configuration for " + worldEntry.getKey() + " (see exception below).");
StaticLog.logSevere("Couldn't save back world-specific configuration for " + worldEntry.getKey() + " (see exception below).");
StaticLog.logSevere(e);
}
} catch (final Exception e) {
StaticLog.logSevere("[NoCheatPlus] Couldn't load world-specific configuration for " + worldEntry.getKey() + " (see exception below). Continue with global default settings...");
StaticLog.logSevere("Couldn't load world-specific configuration for " + worldEntry.getKey() + " (see exception below). Continue with global default settings...");
StaticLog.logSevere(e);
}
worldConfig.setDefaults(globalConfig);

View File

@ -44,7 +44,6 @@ public class DefaultConfig extends ConfigFile {
set(ConfPaths.LOGGING_EXTENDED_ALLVIOLATIONS_BACKEND_TRACE, false);
set(ConfPaths.LOGGING_EXTENDED_ALLVIOLATIONS_BACKEND_NOTIFY, false);
set(ConfPaths.LOGGING_BACKEND_CONSOLE_ACTIVE, true);
set(ConfPaths.LOGGING_BACKEND_CONSOLE_PREFIX, "[NoCheatPlus] ");
set(ConfPaths.LOGGING_BACKEND_CONSOLE_ASYNCHRONOUS, true);
set(ConfPaths.LOGGING_BACKEND_FILE_ACTIVE, true);
set(ConfPaths.LOGGING_BACKEND_FILE_PREFIX, "");
@ -446,6 +445,9 @@ public class DefaultConfig extends ConfigFile {
// NET
// AttackFrequency
set(ConfPaths.NET_ATTACKFREQUENCY_ACTIVE, true);
// FlyingFrequency
set(ConfPaths.NET_FLYINGFREQUENCY_ACTIVE, true);
set(ConfPaths.NET_FLYINGFREQUENCY_SECONDS, 5);

View File

@ -110,7 +110,7 @@ public class PathUtils {
protected static void warnPaths(final ConfigurationSection config, final CharPrefixTree<?, ?> paths, final String msgPrefix, final Set<String> warnedPaths) {
for (final String path : config.getKeys(true)) {
if (paths.hasPrefix(path)) {
StaticLog.logWarning("[NoCheatPlus] Config path '" + path + "'" + msgPrefix);
StaticLog.logWarning("Config path '" + path + "'" + msgPrefix);
if (warnedPaths != null) {
warnedPaths.add(path);
}
@ -135,7 +135,7 @@ public class PathUtils {
}
catch(Throwable t) {
// Do log this one.
StaticLog.logSevere("[NoCheatPlus] Failed to save configuration (" + configName + ") with changes: " + t.getClass().getSimpleName());
StaticLog.logSevere("Failed to save configuration (" + configName + ") with changes: " + t.getClass().getSimpleName());
StaticLog.logSevere(t);
}
}
@ -266,7 +266,7 @@ public class PathUtils {
addPaths.put(newPath, value);
removePaths.add(path);
}
StaticLog.logWarning("[NoCheatPlus] Config path '" + path + "' (" + configName + ") has been moved" + to);
StaticLog.logWarning("Config path '" + path + "' (" + configName + ") has been moved" + to);
}
}
}

View File

@ -172,7 +172,7 @@ public class RawConfigFile extends YamlConfiguration{
for (final String entry : content){
final Integer id = parseTypeId(entry);
if (id == null){
StaticLog.logWarning("[NoCheatPlus] Bad material entry (" + path +"): " + entry);
StaticLog.logWarning("Bad material entry (" + path +"): " + entry);
}
else{
target.add(id);
@ -196,7 +196,7 @@ public class RawConfigFile extends YamlConfiguration{
for (final String entry : content){
final Material mat = parseMaterial(entry);
if (mat == null){
StaticLog.logWarning("[NoCheatPlus] Bad material entry (" + path +"): " + entry);
StaticLog.logWarning("Bad material entry (" + path +"): " + entry);
}
else{
target.add(mat);

View File

@ -260,7 +260,7 @@ public final class NCPHookManager {
* the hook
*/
private static final void logHookAdded(final NCPHook hook) {
Bukkit.getLogger().info("[NoCheatPlus] Added hook: " + getHookDescription(hook) + ".");
Bukkit.getLogger().info("Added hook: " + getHookDescription(hook) + ".");
}
/**
@ -280,7 +280,7 @@ public final class NCPHookManager {
// TODO: might accumulate failure rate and only log every so and so seconds or disable hook if spamming (leads
// to NCP spam though)?
final StringBuilder builder = new StringBuilder(1024);
builder.append("[NoCheatPlus] Hook " + getHookDescription(hook) + " encountered an unexpected exception:\n");
builder.append("Hook " + getHookDescription(hook) + " encountered an unexpected exception:\n");
builder.append("Processing: ");
if (checkType.getParent() != null)
builder.append("Prent " + checkType.getParent() + " ");
@ -301,7 +301,7 @@ public final class NCPHookManager {
* the hook
*/
private static final void logHookRemoved(final NCPHook hook) {
Bukkit.getLogger().info("[NoCheatPlus] Removed hook: " + getHookDescription(hook) + ".");
Bukkit.getLogger().info("Removed hook: " + getHookDescription(hook) + ".");
}
/**

View File

@ -39,6 +39,15 @@ public class BukkitLogManager extends AbstractLogManager implements INotifyReloa
// TODO: ingame logging [ingame needs api to keep track of players who receive notifications.].
// TODO: Later: Custom loggers (file, other), per-player-streams (debug per player), custom ingame loggers (one or more players).
private static ContentLogger<String> serverLogger = new ContentLogger<String>() {
@Override
public void log(Level level, String content) {
try {
Bukkit.getLogger().log(level, "[NoCheatPlus] " + content);
} catch (Throwable t) {}
}
};
protected final Plugin plugin;
/**
@ -65,16 +74,7 @@ public class BukkitLogManager extends AbstractLogManager implements INotifyReloa
}
// Attach a new restrictive init logger.
boolean bukkitLoggerAsynchronous = ConfigManager.getConfigFile().getBoolean(ConfPaths.LOGGING_BACKEND_CONSOLE_ASYNCHRONOUS);
LoggerID initLoggerID = registerStringLogger(new ContentLogger<String>() {
@Override
public void log(Level level, String content) {
try {
Bukkit.getLogger().log(level, content);
} catch (Throwable t) {}
}
}, new LogOptions(Streams.INIT.name, bukkitLoggerAsynchronous ? CallContext.ANY_THREAD_DIRECT : CallContext.PRIMARY_THREAD_ONLY));
LoggerID initLoggerID = registerStringLogger(serverLogger, new LogOptions(Streams.INIT.name, bukkitLoggerAsynchronous ? CallContext.ANY_THREAD_DIRECT : CallContext.PRIMARY_THREAD_ONLY));
attachStringLogger(initLoggerID, Streams.INIT);
}
}
@ -83,6 +83,7 @@ public class BukkitLogManager extends AbstractLogManager implements INotifyReloa
* Create default loggers and streams.
*/
protected void createDefaultLoggers(ConfigFile config) {
// Default streams.
for (StreamID streamID : new StreamID[] {
Streams.STATUS,
@ -94,6 +95,10 @@ public class BukkitLogManager extends AbstractLogManager implements INotifyReloa
createStringStream(streamID);
}
// Default prefixes.
final String prefixIngame = config.getString(ConfPaths.LOGGING_BACKEND_INGAMECHAT_PREFIX);
final String prefixFile = config.getString(ConfPaths.LOGGING_BACKEND_FILE_PREFIX);
// Variables for temporary use.
LoggerID tempID;
@ -105,7 +110,7 @@ public class BukkitLogManager extends AbstractLogManager implements INotifyReloa
CallContext defaultAsynchronousContext = CallContext.ASYNCHRONOUS_TASK; // Plugin runtime + asynchronous.
// Server logger.
tempID = registerStringLogger(Bukkit.getLogger(), new LogOptions(Streams.SERVER_LOGGER.name, bukkitLoggerAsynchronous ? defaultAsynchronousContext : CallContext.PRIMARY_THREAD_TASK));
tempID = registerStringLogger(serverLogger, new LogOptions(Streams.SERVER_LOGGER.name, bukkitLoggerAsynchronous ? defaultAsynchronousContext : CallContext.PRIMARY_THREAD_TASK));
attachStringLogger(tempID, Streams.SERVER_LOGGER);
// Plugin logger.
@ -114,15 +119,16 @@ public class BukkitLogManager extends AbstractLogManager implements INotifyReloa
// Ingame logger (assume not thread-safe at first).
// TODO: Thread-safe ProtocolLib-based implementation?
// TODO: Consider using a task.
tempID = registerStringLogger(new ContentLogger<String>() {
@Override
public void log(Level level, String content) {
// Ignore level for now.
NCPAPIProvider.getNoCheatPlusAPI().sendAdminNotifyMessage(content);
NCPAPIProvider.getNoCheatPlusAPI().sendAdminNotifyMessage(prefixIngame == null ? content : (prefixIngame + content));
}
}, new LogOptions(Streams.NOTIFY_INGAME.name, CallContext.PRIMARY_THREAD_DIRECT)); // TODO: Consider task.
}, new LogOptions(Streams.NOTIFY_INGAME.name, CallContext.PRIMARY_THREAD_DIRECT));
attachStringLogger(tempID, Streams.NOTIFY_INGAME);
// Abstract STATUS stream (efficient version of INIT during plugin runtime).
@ -132,7 +138,7 @@ public class BukkitLogManager extends AbstractLogManager implements INotifyReloa
String fileName = config.getString(ConfPaths.LOGGING_BACKEND_FILE_FILENAME).trim();
ContentLogger<String> defaultFileLogger = null;
if (!fileName.isEmpty() && !fileName.equalsIgnoreCase("none")) {
defaultFileLogger = newFileLogger(fileName, plugin.getDataFolder());
defaultFileLogger = newFileLogger(fileName, plugin.getDataFolder(), prefixFile);
}
ContentLogger<String> traceFileLogger = null;
@ -169,17 +175,20 @@ public class BukkitLogManager extends AbstractLogManager implements INotifyReloa
* @param defaultDir
* This is used as a base, if fileName represents a relative
* path.
* @param prefix
* A prefix to use for each message (can be null).
* @return
*/
protected ContentLogger<String> newFileLogger(String fileName, File defaultDir) {
protected ContentLogger<String> newFileLogger(String fileName, File defaultDir, String prefix) {
File file = new File(fileName);
if (!file.isAbsolute()) {
file = new File(defaultDir, file.getPath());
}
// TODO: Sanity check file+extensions and fall-back if not valid [make an auxiliary method doing all this at once]!
try {
FileLoggerAdapter logger = new FileLoggerAdapter(file); // TODO: Method to get-or-create these (store logger by canonical abs paths).
FileLoggerAdapter logger = new FileLoggerAdapter(file, prefix); // TODO: Method to get-or-create these (store logger by canonical abs paths).
if (logger.isInoperable()) {
// TODO: Might want to log this?
logger.detachLogger();
return null;
} else {

View File

@ -64,7 +64,7 @@ public class StaticLog {
if (useLogManager) {
NCPAPIProvider.getNoCheatPlusAPI().getLogManager().log(streamID, level, msg);
} else {
System.out.println("[" + level + "] " + new Date());
System.out.println("[" + level + "][NoCheatPlus] " + new Date());
System.out.println(msg);
}
}

View File

@ -513,7 +513,7 @@ public class DataManager implements Listener, INotifyReload, INeedConfig, Compon
playerMap.clear();
// Finally alert (summary) if inconsistencies found.
if (foundInconsistencies > 0) {
StaticLog.logWarning("[NoCheatPlus] DataMan found " + foundInconsistencies + " inconsistencies (warnings suppressed).");
StaticLog.logWarning("DataMan found " + foundInconsistencies + " inconsistencies (warnings suppressed).");
foundInconsistencies = 0;
}
}
@ -564,7 +564,7 @@ public class DataManager implements Listener, INotifyReload, INeedConfig, Compon
details.add("changed player instances (" + changed + ")");
}
StaticLog.logWarning("[NoCheatPlus] DataMan inconsistencies: " + StringUtil.join(details, " | "));
StaticLog.logWarning("DataMan inconsistencies: " + StringUtil.join(details, " | "));
}
}
}

View File

@ -425,7 +425,7 @@ public class BlockProperties {
blocksFeatures.addAll(new VanillaBlocksFactory().setupVanillaBlocks(worldConfigProvider));
}
catch(Throwable t) {
StaticLog.logSevere("[NoCheatPlus] Could not initialize vanilla blocks: " + t.getClass().getSimpleName() + " - " + t.getMessage());
StaticLog.logSevere("Could not initialize vanilla blocks: " + t.getClass().getSimpleName() + " - " + t.getMessage());
StaticLog.logSevere(t);
}
// Allow mcAccess to setup block properties.
@ -435,7 +435,7 @@ public class BlockProperties {
blocksFeatures.add(mcAccess.getClass().getSimpleName());
}
catch(Throwable t) {
StaticLog.logSevere("[NoCheatPlus] McAccess.setupBlockProperties (" + mcAccess.getClass().getSimpleName() + ") could not execute properly: " + t.getClass().getSimpleName() + " - " + t.getMessage());
StaticLog.logSevere("McAccess.setupBlockProperties (" + mcAccess.getClass().getSimpleName() + ") could not execute properly: " + t.getClass().getSimpleName() + " - " + t.getMessage());
StaticLog.logSevere(t);
}
}
@ -803,7 +803,7 @@ public class BlockProperties {
List<String> missing = new LinkedList<String>();
List<String> allBlocks = new LinkedList<String>();
if (all) {
allBlocks.add("[NoCheatPlus] Dump block properties for fastbreak check:");
allBlocks.add("Dump block properties for fastbreak check:");
allBlocks.add("--- Present entries -------------------------------");
}
List<String> tags = new ArrayList<String>();
@ -839,7 +839,7 @@ public class BlockProperties {
}
if (!missing.isEmpty()) {
missing.add(0, "--- Missing entries -------------------------------");
missing.add(0, "[NoCheatPlus] The block breaking data is incomplete, default to allow instant breaking:");
missing.add(0, "The block breaking data is incomplete, default to allow instant breaking:");
logManager.warning(Streams.INIT, StringUtil.join(missing, "\n"));
}
}
@ -1999,7 +1999,7 @@ public class BlockProperties {
for (final String input : config.getStringList(pathPrefix + ConfPaths.SUB_IGNOREPASSABLE)) {
final Integer id = RawConfigFile.parseTypeId(input);
if (id == null || id < 0 || id >= 4096) {
StaticLog.logWarning("[NoCheatplus] Bad block id (" + pathPrefix + ConfPaths.SUB_IGNOREPASSABLE + "): " + input);
StaticLog.logWarning("Bad block id (" + pathPrefix + ConfPaths.SUB_IGNOREPASSABLE + "): " + input);
}
else {
blockFlags[id] |= F_IGN_PASSABLE;
@ -2010,7 +2010,7 @@ public class BlockProperties {
for (final String input : config.getStringList(pathPrefix + ConfPaths.SUB_ALLOWINSTANTBREAK)) {
final Integer id = RawConfigFile.parseTypeId(input);
if (id == null || id < 0 || id >= 4096) {
StaticLog.logWarning("[NoCheatplus] Bad block id (" + pathPrefix + ConfPaths.SUB_ALLOWINSTANTBREAK + "): " + input);
StaticLog.logWarning("Bad block id (" + pathPrefix + ConfPaths.SUB_ALLOWINSTANTBREAK + "): " + input);
}
else {
setBlockProps(id, instantType);
@ -2026,12 +2026,12 @@ public class BlockProperties {
final String key = entry.getKey();
final Integer id = RawConfigFile.parseTypeId(key);
if (id == null || id < 0 || id >= 4096) {
StaticLog.logWarning("[NoCheatplus] Bad block id (" + pathPrefix + ConfPaths.SUB_OVERRIDEFLAGS + "): " + key);
StaticLog.logWarning("Bad block id (" + pathPrefix + ConfPaths.SUB_OVERRIDEFLAGS + "): " + key);
continue;
}
final Object obj = entry.getValue();
if (!(obj instanceof String)) {
StaticLog.logWarning("[NoCheatplus] Bad flags at " + pathPrefix + ConfPaths.SUB_OVERRIDEFLAGS + " for key: " + key);
StaticLog.logWarning("Bad flags at " + pathPrefix + ConfPaths.SUB_OVERRIDEFLAGS + " for key: " + key);
hasErrors = true;
continue;
}
@ -2050,7 +2050,7 @@ public class BlockProperties {
try{
flags |= parseFlag(input);
} catch(InputMismatchException e) {
StaticLog.logWarning("[NoCheatplus] Bad flag at " + pathPrefix + ConfPaths.SUB_OVERRIDEFLAGS + " for key " + key + " (skip setting flags for this block): " + input);
StaticLog.logWarning("Bad flag at " + pathPrefix + ConfPaths.SUB_OVERRIDEFLAGS + " for key " + key + " (skip setting flags for this block): " + input);
error = true;
hasErrors = true;
break;
@ -2062,7 +2062,7 @@ public class BlockProperties {
blockFlags[id] = flags;
}
if (hasErrors) {
StaticLog.logInfo("[NoCheatPlus] Overriding block-flags was not entirely successful, all available flags: \n" + StringUtil.join(flagNameMap.values(), "|"));
StaticLog.logInfo("Overriding block-flags was not entirely successful, all available flags: \n" + StringUtil.join(flagNameMap.values(), "|"));
}
}
}

View File

@ -238,7 +238,7 @@ public class TickTask implements Runnable {
}
catch(Throwable t) {
// Unlikely.
StaticLog.logWarning("[NoCheatPlus] Failed to set OnDemandTickListener to unregistered state: " + t.getClass().getSimpleName());
StaticLog.logWarning("Failed to set OnDemandTickListener to unregistered state: " + t.getClass().getSimpleName());
StaticLog.logWarning(t);
}
}
@ -477,7 +477,7 @@ public class TickTask implements Runnable {
listener.onTick(tick, timeLast);
}
catch(Throwable t) {
StaticLog.logSevere("[NoCheatPlus] (TickTask) TickListener generated an exception:");
StaticLog.logSevere("(TickTask) TickListener generated an exception:");
StaticLog.logSevere(t);
}
}
@ -498,7 +498,7 @@ public class TickTask implements Runnable {
// Time running backwards check (not only players can!).
if (timeLast > time) {
StaticLog.logWarning("[NoCheatPlus] System time ran backwards (" + timeLast + "->" + time + "), clear all data and history...");
StaticLog.logWarning("System time ran backwards (" + timeLast + "->" + time + "), clear all data and history...");
DataManager.clearData(CheckType.ALL);
lastDur = 50;
for (int i = 0; i < spikeDurations.length; i++) {

View File

@ -509,7 +509,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
if (listener instanceof IHaveMethodOrder){
// TODO: Might log the order too, might prevent registration ?
// TODO: Alternative: queue listeners and register after startup (!)
logManager.warning(Streams.INIT, "[NoCheatPlus] Listener demands registration order, but listeners are not managed: " + listener.getClass().getName());
logManager.warning(Streams.INIT, "Listener demands registration order, but listeners are not managed: " + listener.getClass().getName());
}
}
}
@ -570,10 +570,10 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Remove listener references.
if (verbose){
if (listenerManager.hasListenerMethods()) {
logManager.info(Streams.INIT, "[NoCheatPlus] Cleanup ListenerManager...");
logManager.info(Streams.INIT, "Cleanup ListenerManager...");
}
else {
logManager.info(Streams.INIT, "[NoCheatPlus] (ListenerManager not in use, prevent registering...)");
logManager.info(Streams.INIT, "(ListenerManager not in use, prevent registering...)");
}
}
listenerManager.setRegisterDirectly(false);
@ -589,7 +589,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Stop the tickTask.
if (verbose) {
logManager.info(Streams.INIT, "[NoCheatPlus] Stop TickTask...");
logManager.info(Streams.INIT, "Stop TickTask...");
}
TickTask.setLocked(true);
TickTask.purge();
@ -605,7 +605,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Just to be sure nothing gets left out.
if (verbose) {
logManager.info(Streams.INIT, "[NoCheatPlus] Stop all remaining tasks...");
logManager.info(Streams.INIT, "Stop all remaining tasks...");
}
sched.cancelTasks(this);
@ -615,13 +615,13 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Exemptions cleanup.
if (verbose) {
logManager.info(Streams.INIT, "[NoCheatPlus] Reset ExemptionManager...");
logManager.info(Streams.INIT, "Reset ExemptionManager...");
}
NCPExemptionManager.clear();
// Data cleanup.
if (verbose) {
logManager.info(Streams.INIT, "[NoCheatPlus] onDisable calls (include DataManager cleanup)...");
logManager.info(Streams.INIT, "onDisable calls (include DataManager cleanup)...");
}
for (final DisableListener dl : disableListeners) {
try {
@ -649,7 +649,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Unregister all added components explicitly.
if (verbose) {
logManager.info(Streams.INIT, "[NoCheatPlus] Unregister all registered components...");
logManager.info(Streams.INIT, "Unregister all registered components...");
}
final ArrayList<Object> allComponents = new ArrayList<Object>(this.allComponents);
for (int i = allComponents.size() - 1; i >= 0; i--){
@ -658,12 +658,12 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Cleanup BlockProperties.
if (verbose) {
logManager.info(Streams.INIT, "[NoCheatPlus] Cleanup BlockProperties...");
logManager.info(Streams.INIT, "Cleanup BlockProperties...");
}
BlockProperties.cleanup();
if (verbose) {
logManager.info(Streams.INIT, "[NoCheatPlus] Cleanup some mappings...");
logManager.info(Streams.INIT, "Cleanup some mappings...");
}
// Remove listeners.
listeners.clear();
@ -686,18 +686,18 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
changedCommands = null;
}
// // Restore changed commands.
// if (verbose) LogUtil.logInfo("[NoCheatPlus] Undo command changes...");
// if (verbose) LogUtil.logInfo("Undo command changes...");
// undoCommandChanges();
// Cleanup the configuration manager.
if (verbose) {
logManager.info(Streams.INIT, "[NoCheatPlus] Cleanup ConfigManager...");
logManager.info(Streams.INIT, "Cleanup ConfigManager...");
}
ConfigManager.cleanup();
// Cleanup file logger.
if (verbose) {
logManager.info(Streams.INIT, "[NoCheatPlus] Shutdown LogManager...");
logManager.info(Streams.INIT, "Shutdown LogManager...");
}
StaticLog.setUseLogManager(false);
StaticLog.setStreamID(Streams.INIT);
@ -705,10 +705,10 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Tell the server administrator that we finished unloading NoCheatPlus.
if (verbose) {
Bukkit.getLogger().info("[NoCheatPlus] All cleanup done.");
Bukkit.getLogger().info("All cleanup done.");
}
final PluginDescriptionFile pdfFile = getDescription();
Bukkit.getLogger().info("[NoCheatPlus] Version " + pdfFile.getVersion() + " is disabled.");
Bukkit.getLogger().info("Version " + pdfFile.getVersion() + " is disabled.");
}
/**
@ -758,7 +758,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
*/
@Override
public void onLoad() {
Bukkit.getLogger().info("[NoCheatPlus] onLoad: Early set up of static API, configuration, logging.");
Bukkit.getLogger().info("onLoad: Early set up of static API, configuration, logging.");
setupBasics();
}
@ -779,8 +779,8 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
logManager = new BukkitLogManager(this);
StaticLog.setStreamID(Streams.INIT);
StaticLog.setUseLogManager(true);
logManager.info(Streams.INIT, "[NoCheatPlus] Logging system initialized.");
logManager.info(Streams.INIT, "[NoCheatPlus] Detected Minecraft version: " + ServerVersion.getMinecraftVersion());
logManager.info(Streams.INIT, "Logging system initialized.");
logManager.info(Streams.INIT, "Detected Minecraft version: " + ServerVersion.getMinecraftVersion());
}
}
@ -920,7 +920,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Is the version the configuration was created with consistent with the current one?
if (configProblems != null && config.getBoolean(ConfPaths.CONFIGVERSION_NOTIFY)){
// Could use custom prefix from logging, however ncp should be mentioned then.
logManager.warning(Streams.INIT, "[NoCheatPlus] " + configProblems);
logManager.warning(Streams.INIT, "" + configProblems);
}
// Care for already online players.
@ -933,19 +933,19 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
// Set StaticLog to more efficient output.
StaticLog.setStreamID(Streams.STATUS);
// Tell the server administrator that we finished loading NoCheatPlus now.
logManager.info(Streams.INIT, "[NoCheatPlus] Version " + getDescription().getVersion() + " is enabled.");
logManager.info(Streams.INIT, "Version " + getDescription().getVersion() + " is enabled.");
}
/**
* Actions to be done after enable of all plugins. This aims at reloading mainly.
*/
protected void postEnable(final NoCheatPlusCommand commandHandler, final Player[] onlinePlayers){
logManager.info(Streams.INIT, "[NoCheatPlus] Post-enable running...");
logManager.info(Streams.INIT, "Post-enable running...");
try {
// Set child permissions for commands for faster checking.
PermissionUtil.addChildPermission(commandHandler.getAllSubCommandPermissions(), Permissions.FILTER_COMMAND_NOCHEATPLUS, PermissionDefault.OP);
} catch (Throwable t) {
logManager.severe(Streams.INIT, "[NoCheatPlus] Failed to complement permissions: " + t.getClass().getSimpleName());
logManager.severe(Streams.INIT, "Failed to complement permissions: " + t.getClass().getSimpleName());
logManager.severe(Streams.INIT, t);
}
try {
@ -954,7 +954,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
setupCommandProtection();
}
} catch (Throwable t) {
logManager.severe(Streams.INIT, "[NoCheatPlus] Failed to apply command protection: " + t.getClass().getSimpleName());
logManager.severe(Streams.INIT, "Failed to apply command protection: " + t.getClass().getSimpleName());
logManager.severe(Streams.INIT, t);
}
for (final Player player : onlinePlayers){
@ -964,7 +964,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
}
}
// TODO: if (online.lenght > 0) LogUtils.logInfo("[NCP] Updated " + online.length + "players (post-enable).")
logManager.info(Streams.INIT, "[NoCheatPlus] Post-enable finished.");
logManager.info(Streams.INIT, "Post-enable finished.");
logManager.info(Streams.DEFAULT_FILE, StringUtil.join(VersionCommand.getVersionInfo(), "\n")); // Queued (!).
}
@ -1067,12 +1067,12 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
try{
((MCAccessHolder) obj).setMCAccess(mcAccess);
} catch(Throwable t){
logManager.severe(Streams.INIT, "[NoCheatPlus] MCAccessHolder(" + obj.getClass().getName() + ") failed to set MCAccess: " + t.getClass().getSimpleName());
logManager.severe(Streams.INIT, "MCAccessHolder(" + obj.getClass().getName() + ") failed to set MCAccess: " + t.getClass().getSimpleName());
logManager.severe(Streams.INIT, t);
}
}
}
logManager.info(Streams.INIT, "[NoCheatPlus] McAccess set to: " + mcAccess.getMCVersion() + " / " + mcAccess.getServerVersionTag());
logManager.info(Streams.INIT, "McAccess set to: " + mcAccess.getMCVersion() + " / " + mcAccess.getServerVersionTag());
}
/**
@ -1174,7 +1174,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
jlListener.playerJoins(player);
}
catch(Throwable t){
logManager.severe(Streams.INIT, "[NoCheatPlus] JoinLeaveListener(" + jlListener.getClass().getName() + ") generated an exception (join): " + t.getClass().getSimpleName());
logManager.severe(Streams.INIT, "JoinLeaveListener(" + jlListener.getClass().getName() + ") generated an exception (join): " + t.getClass().getSimpleName());
logManager.severe(Streams.INIT, t);
}
}
@ -1191,7 +1191,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
jlListener.playerLeaves(player);
}
catch(Throwable t){
logManager.severe(Streams.INIT, "[NoCheatPlus] JoinLeaveListener(" + jlListener.getClass().getName() + ") generated an exception (leave): " + t.getClass().getSimpleName());
logManager.severe(Streams.INIT, "JoinLeaveListener(" + jlListener.getClass().getName() + ") generated an exception (leave): " + t.getClass().getSimpleName());
logManager.severe(Streams.INIT, t);
}
}
@ -1252,7 +1252,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
checker.checkConsistency(onlinePlayers);
}
catch (Throwable t){
logManager.severe(Streams.INIT, "[NoCheatPlus] ConsistencyChecker(" + checker.getClass().getName() + ") encountered an exception:");
logManager.severe(Streams.INIT, "ConsistencyChecker(" + checker.getClass().getName() + ") encountered an exception:");
logManager.severe(Streams.INIT, t);
}
consistencyCheckerIndex ++; // Do not remove :).
@ -1274,7 +1274,7 @@ public class NoCheatPlus extends JavaPlugin implements NoCheatPlusAPI {
}
});
if (debug){
logManager.info(Streams.STATUS, "[NoCheatPlus] Interrupted consistency checking until next tick.");
logManager.info(Streams.STATUS, "Interrupted consistency checking until next tick.");
}
}
}

View File

@ -31,7 +31,7 @@ public class DefaultComponentFactory {
// Add components (try-catch).
// TODO: catch ClassNotFound, incompatibleXY rather !?
// Check: inventory.fastconsume.
try{
// TODO: Static test methods !?
@ -42,9 +42,9 @@ public class DefaultComponentFactory {
}
}
catch (Throwable t){
StaticLog.logInfo("[NoCheatPlus] Inventory checks: FastConsume is not available.");
StaticLog.logInfo("Inventory checks: FastConsume is not available.");
}
// Check: inventory.gutenberg.
try {
Gutenberg.testAvailability();
@ -53,14 +53,14 @@ public class DefaultComponentFactory {
NCPAPIProvider.getNoCheatPlusAPI().addFeatureTags("checks", Arrays.asList(Gutenberg.class.getSimpleName()));
}
} catch (Throwable t) {
StaticLog.logInfo("[NoCheatPlus] Inventory checks: Gutenberg is not available.");
StaticLog.logInfo("Inventory checks: Gutenberg is not available.");
}
// ProtocolLib dependencies.
try {
available.add(new ProtocolLibComponent(plugin));
} catch (Throwable t){
StaticLog.logInfo("[NoCheatPlus] Packet level access: ProtocolLib is not available.");
StaticLog.logInfo("Packet level access: ProtocolLib is not available.");
}
return available;

View File

@ -19,8 +19,8 @@ import fr.neatmonster.nocheatplus.logging.StaticLog;
public class MCAccessFactory {
private final String[] updateLocs = new String[]{
"[NoCheatPlus] Check for updates and support at BukkitDev: http://dev.bukkit.org/server-mods/nocheatplus/",
"[NoCheatPlus] Development builds (unsupported by the Bukkit Staff, use at your own risk): http://ci.md-5.net/job/NoCheatPlus/changes",
" Check for updates and support at BukkitDev: http://dev.bukkit.org/server-mods/nocheatplus/",
" Development builds (unsupported by the Bukkit Staff, use at your own risk): http://ci.md-5.net/job/NoCheatPlus/changes",
};
/**
@ -63,7 +63,7 @@ public class MCAccessFactory {
try {
mcAccess = new MCAccessBukkit();
final String msg;
msg = "[NoCheatPlus] Running in Bukkit-API-only mode (" + Bukkit.getServer().getVersion() + "). If this is not intended, please check for updates and consider to request support.";
msg = "Running in Bukkit-API-only mode (" + Bukkit.getServer().getVersion() + "). If this is not intended, please check for updates and consider to request support.";
StaticLog.logWarning(msg);
for (String uMsg : updateLocs) {
StaticLog.logWarning(uMsg);
@ -71,7 +71,7 @@ public class MCAccessFactory {
// if (ConfigManager.getConfigFile().getBoolean(ConfPaths.LOGGING_EXTENDED_STATUS)) {
// log(throwables); // Maybe later activate with TRACE explicitly set
// }
StaticLog.logWarning("[NoCheatPlus] Bukkit-API-only mode: Some features will likely not function properly, performance might suffer.");
StaticLog.logWarning("Bukkit-API-only mode: Some features will likely not function properly, performance might suffer.");
return mcAccess;
}
catch(Throwable t) {
@ -80,11 +80,11 @@ public class MCAccessFactory {
// All went wrong.
// TODO: Fall-back solution (disable plugin, disable checks).
StaticLog.logSevere("[NoCheatPlus] Your version of NoCheatPlus is not compatible with the version of the server-mod (" + Bukkit.getServer().getVersion() + "). Please check for updates and consider to request support.");
StaticLog.logSevere("Your version of NoCheatPlus is not compatible with the version of the server-mod (" + Bukkit.getServer().getVersion() + "). Please check for updates and consider to request support.");
for (String msg : updateLocs) {
StaticLog.logSevere(msg);
}
StaticLog.logSevere("[NoCheatPlus] >>> Failed to set up MCAccess <<<");
StaticLog.logSevere(">>> Failed to set up MCAccess <<<");
log(throwables);
// TODO: Schedule disabling the plugin or running in circles.
throw new RuntimeException("Could not set up native access to the server mod, neither to the Bukkit-API.");

View File

@ -6,43 +6,13 @@ import org.junit.Test;
import fr.neatmonster.nocheatplus.actions.Action;
import fr.neatmonster.nocheatplus.actions.ActionList;
import fr.neatmonster.nocheatplus.actions.types.LogAction;
import fr.neatmonster.nocheatplus.checks.ViolationData;
import fr.neatmonster.nocheatplus.config.ConfPaths;
import fr.neatmonster.nocheatplus.config.ConfigFile;
import fr.neatmonster.nocheatplus.config.DefaultConfig;
public class TestActions {
@Test
public void testOptimizedLogActionPrefixes() {
final ConfigFile config = new DefaultConfig();
config.set("actions", "log:dummy:0:0:icf");
config.set("strings.dummy", "dummy");
config.set(ConfPaths.LOGGING_BACKEND_CONSOLE_PREFIX, "console_dummy");
config.set(ConfPaths.LOGGING_BACKEND_FILE_PREFIX, "file_dummy");
config.set(ConfPaths.LOGGING_BACKEND_INGAMECHAT_PREFIX, "ingame_dummy");
ActionList actionList = config.getOptimizedActionList("actions", "dummy");
Action<ViolationData, ActionList>[] actions = actionList.getActions(0.0);
if (actions.length != 1) {
fail("Wrong number of actions.");
}
if (actions[0] instanceof LogAction) {
LogAction action = (LogAction) actions[0];
testString(action.prefixChat, "ingame_dummy");
testString(action.prefixFile, "file_dummy");
testString(action.prefixConsole, "console_dummy");
} else {
fail("Expect log action.");
}
}
private static void testString(String value, String match) {
if (!match.equals(value)) {
fail("Expect '" + match + "', got instead: '" + value + "'");
}
}
@Test
public void testOptimizedLogActionEmpty() {
final ConfigFile config = new DefaultConfig();
@ -55,5 +25,5 @@ public class TestActions {
fail("Wrong number of actions.");
}
}
}