qa: address PMD GuardLogStatement warnings (#5209)

address PMD GuardLogStatement warnings
---------

Co-authored-by: jdrueckert <jd.rueckert@googlemail.com>
This commit is contained in:
soloturn 2024-05-17 23:05:00 +02:00 committed by GitHub
parent 30bc83ab00
commit 0c00a0840a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
92 changed files with 273 additions and 249 deletions

View file

@ -52,6 +52,7 @@ public class OpenALManager implements AudioManager {
private final Map<SoundSource<?>, AudioEndListener> endListeners = Maps.newHashMap();
@SuppressWarnings("PMD.GuardLogStatement")
public OpenALManager(AudioConfig config) throws OpenALException {
logger.info("Initializing OpenAL audio manager");
@ -65,7 +66,6 @@ public OpenALManager(AudioConfig config) throws OpenALException {
AL.createCapabilities(alcCapabilities);
logger.info("OpenAL {} initialized!", AL10.alGetString(AL10.AL_VERSION));
logger.info("Using OpenAL: {} by {}", AL10.alGetString(AL10.AL_RENDERER), AL10.alGetString(AL10.AL_VENDOR));
logger.info("Using device: {}", ALC10.alcGetString(device, ALC10.ALC_DEVICE_SPECIFIER));
logger.info("Available AL extensions: {}", AL10.alGetString(AL10.AL_EXTENSIONS));
@ -260,7 +260,7 @@ private void notifyEndListeners(boolean interrupted) {
try {
entry.getValue().onAudioEnd(interrupted);
} catch (Exception e) {
logger.error("onAudioEnd() notification failed for {}", entry.getValue(), e);
logger.error("onAudioEnd() notification failed for {}", entry.getValue(), e); //NOPMD
}
}
}

View file

@ -104,7 +104,7 @@ protected void doReload(StaticSoundData newData) {
length = (float) size / channels / (bits / 8) / frequency;
});
} catch (InterruptedException e) {
logger.error("Failed to reload {}", getUrn(), e);
logger.error("Failed to reload {}", getUrn(), e); //NOPMD
}
}

View file

@ -123,7 +123,7 @@ protected void doReload(StreamingSoundData data) {
try {
GameThread.synch(this::initializeBuffers);
} catch (InterruptedException e) {
logger.error("Failed to reload {}", getUrn(), e);
logger.error("Failed to reload {}", getUrn(), e); //NOPMD
}
}

View file

@ -108,6 +108,6 @@ public void setRenderSkeletons(boolean renderSkeletons) {
@Override
public void propertyChange(PropertyChangeEvent evt) {
logger.debug("Set {} property to {}.", evt.getPropertyName().toUpperCase(), evt.getNewValue());
logger.atDebug().log("Set {} property to {}.", evt.getPropertyName().toUpperCase(), evt.getNewValue());
}
}

View file

@ -85,7 +85,7 @@ private <T extends AutoConfig> void loadSettingsFromDisk(Class<T> configClass, T
T loadedConfig = (T) serializer.deserialize(TypeInfo.of(configClass), inputStream).get();
mergeConfig(configClass, loadedConfig, config);
} catch (Exception e) {
logger.error("Error while loading config {} from disk", config.getId(), e);
logger.error("Error while loading config {} from disk", config.getId(), e); //NOPMD
}
}
@ -116,7 +116,7 @@ private void saveConfigToDisk(AutoConfig config) {
StandardOpenOption.CREATE)) {
serializer.serialize(config, TypeInfo.of((Class<AutoConfig>) config.getClass()), output);
} catch (IOException e) {
logger.error("Error while saving config {} to disk", config.getId(), e);
logger.error("Error while saving config {} to disk", config.getId(), e); //NOPMD
}
}

View file

@ -43,7 +43,7 @@ protected PersistedData serializeNonNull(AutoConfig value, PersistedDataSerializ
if (typeHandler.isPresent()) {
fields.put(field.getName(), typeHandler.get().serialize(setting.get(), serializer));
} else {
logger.error("Cannot serialize type [{}]", setting.getValueType());
logger.error("Cannot serialize type [{}]", setting.getValueType()); //NOPMD
}
}
} catch (IllegalAccessException e) {
@ -65,7 +65,7 @@ public Optional<AutoConfig> deserialize(PersistedData data) {
for (Map.Entry<String, PersistedData> entry : data.getAsValueMap().entrySet()) {
Field settingField = settingFields.get(entry.getKey());
if (settingField == null) {
logger.warn("Cannot to find setting field with name [{}]", entry.getKey());
logger.warn("Cannot to find setting field with name [{}]", entry.getKey()); //NOPMD
continue;
}
try {
@ -77,11 +77,10 @@ public Optional<AutoConfig> deserialize(PersistedData data) {
if (value.isPresent()) {
setting.set(value.get());
} else {
logger.error("Cannot deserialize value [{}] to type [{}]", entry.getValue(),
setting.getValueType());
logger.error("Cannot deserialize value [{}] to type [{}]", entry.getValue(), setting.getValueType()); //NOPMD
}
} else {
logger.error("Cannot deserialize type [{}]", setting.getValueType());
logger.error("Cannot deserialize type [{}]", setting.getValueType()); //NOPMD
}
} catch (IllegalAccessException e) {
// ignore, AutoConfig.getSettingsFieldsIn return public fields.

View file

@ -31,6 +31,7 @@ public boolean isSatisfiedBy(Locale value) {
}
@Override
@SuppressWarnings("PMD.GuardLogStatement")
public void warnUnsatisfiedBy(Locale value) {
logger.warn("Locale {} should be one of {}",
value,

View file

@ -96,8 +96,12 @@ public boolean isSatisfiedBy(T value) {
* {@inheritDoc}
*/
@Override
@SuppressWarnings("PMD.GuardLogStatement")
public void warnUnsatisfiedBy(T value) {
LOGGER.warn("Value {} is not in the range {}{}, {}{}", value, minInclusive ? "[" : "(",
min != null ? min : "UNBOUNDED", max != null ? max : "UNBOUNDED", maxInclusive ? "]" : ")");
LOGGER.warn("Value {} is not in the range {}{}, {}{}", value,
minInclusive ? "[" : "(",
min != null ? min : "UNBOUNDED",
max != null ? max : "UNBOUNDED",
maxInclusive ? "]" : ")");
}
}

View file

@ -49,6 +49,7 @@ public boolean isSatisfiedBy(String value) {
}
@Override
@SuppressWarnings("PMD.GuardLogStatement")
public void warnUnsatisfiedBy(String value) {
logger.warn("String [{}] does not match the conditions: {}", value,
predicates.stream()

View file

@ -46,7 +46,7 @@ public void initialise() {
if (widget.isPresent()) {
mainContainer.addWidget(widget.get());
} else {
logger.warn("Cannot create widget for config: {}", config.getId());
logger.warn("Cannot create widget for config: {}", config.getId()); //NOPMD
}
}
WidgetUtil.trySubscribe(this, "close", button -> triggerBackAnimation());

View file

@ -79,7 +79,7 @@ public UIWidget buildWidgetFor(AutoConfig config) {
Optional<UIWidget> settingWidget = settingWidgetFactory.createWidgetFor(setting);
if (!settingWidget.isPresent()) {
logger.error("Couldn't find a widget for the Setting [{}]", setting.getHumanReadableName());
logger.error("Couldn't find a widget for the Setting [{}]", setting.getHumanReadableName()); //NOPMD
continue;
}

View file

@ -68,7 +68,7 @@ public void loadSystems(ModuleEnvironment environment, NetworkMode netMode) {
ListMultimap<Name, Class<?>> systemsByModule = ArrayListMultimap.create();
for (Class<?> type : environment.getTypesAnnotatedWith(RegisterSystem.class)) {
if (!ComponentSystem.class.isAssignableFrom(type)) {
logger.error("Cannot load {}, must be a subclass of ComponentSystem", type.getSimpleName());
logger.error("Cannot load {}, must be a subclass of ComponentSystem", type.getSimpleName()); //NOPMD
continue;
}
Name moduleId = environment.getModuleProviding(type);
@ -177,7 +177,7 @@ public void register(ComponentSystem object) {
context.get(EntityManager.class).getEventSystem().registerEventHandler(object);
if (initialised) {
logger.warn("System {} registered post-init.", object.getClass().getName());
logger.atWarn().log("System {} registered post-init.", object.getClass().getName());
initialiseSystem(object);
}
}

View file

@ -78,7 +78,7 @@ private static Path findInstallPath() {
URI urlToSource = PathManager.class.getProtectionDomain().getCodeSource().getLocation().toURI();
Path codeLocation = Paths.get(urlToSource);
installationSearchPaths.add(codeLocation);
LOGGER.info("PathManager: Initial code location is " + codeLocation.toAbsolutePath());
LOGGER.atInfo().log("PathManager: Initial code location is " + codeLocation.toAbsolutePath());
} catch (URISyntaxException e) {
LOGGER.error("PathManager: Failed to convert code location to path.", e);
}
@ -90,7 +90,7 @@ private static Path findInstallPath() {
// Use the current directory as a fallback.
Path currentDirectory = Paths.get("").toAbsolutePath();
installationSearchPaths.add(currentDirectory);
LOGGER.info("PathManager: Working directory is " + currentDirectory);
LOGGER.info("PathManager: Working directory is {}", currentDirectory);
for (Path startPath : installationSearchPaths) {
Path installationPath = findNativesHome(startPath, 5);

View file

@ -253,7 +253,7 @@ public void initialize() {
}
double seconds = 0.001 * totalInitTime.elapsed(TimeUnit.MILLISECONDS);
logger.info("Initialization completed in {}sec.", String.format("%.2f", seconds));
logger.info("Initialization completed in {}sec.", String.format("%.2f", seconds)); //NOPMD
}
private void verifyInitialisation() {
@ -265,6 +265,7 @@ private void verifyInitialisation() {
/**
* Logs software, environment and hardware information.
*/
@SuppressWarnings("PMD.GuardLogStatement")
private void logEnvironmentInfo() {
logger.info("{}", TerasologyVersion.getInstance());
logger.info("Home path: {}", PathManager.getInstance().getHomePath());
@ -543,7 +544,7 @@ public void cleanup() {
try {
subsystem.preShutdown();
} catch (RuntimeException e) {
logger.error("Error preparing to shutdown {} subsystem", subsystem.getName(), e);
logger.error("Error preparing to shutdown {} subsystem", subsystem.getName(), e); //NOPMD
}
}
@ -553,7 +554,7 @@ public void cleanup() {
try {
subsystem.shutdown();
} catch (RuntimeException e) {
logger.error("Error shutting down {} subsystem", subsystem.getName(), e);
logger.error("Error shutting down {} subsystem", subsystem.getName(), e); //NOPMD
}
}
}

View file

@ -234,7 +234,7 @@ private void popStep() {
current = null;
if (!loadProcesses.isEmpty()) {
current = loadProcesses.remove();
logger.debug("{}", current.getMessage());
logger.debug("{}", current.getMessage()); //NOPMD
current.begin();
}
}

View file

@ -95,7 +95,7 @@ public boolean step() {
worldInfo.setSeed(random.nextString(16));
}
logger.info("World seed: \"{}\"", worldInfo.getSeed());
logger.info("World seed: \"{}\"", worldInfo.getSeed()); //NOPMD
// TODO: Separate WorldRenderer from world handling in general
WorldGeneratorManager worldGeneratorManager = context.get(WorldGeneratorManager.class);
@ -106,7 +106,7 @@ public boolean step() {
worldGenerator.setWorldSeed(worldInfo.getSeed());
context.put(WorldGenerator.class, worldGenerator);
} catch (UnresolvedWorldGeneratorException | UnresolvedDependencyException e) {
logger.error("Unable to load world generator {}. Available world generators: {}",
logger.atError().log("Unable to load world generator {}. Available world generators: {}",
worldInfo.getWorldGenerator(), worldGeneratorManager.getWorldGenerators());
context.get(GameEngine.class).changeState(new StateMainMenu("Failed to resolve world generator."));
return true; // We need to return true, otherwise the loading state will just call us again immediately

View file

@ -104,7 +104,7 @@ public boolean step() {
context.get(GameEngine.class).changeState(mainMenu);
return false;
} else {
logger.info("Activating module: {}:{}", moduleInfo.getName(), moduleInfo.getVersion());
logger.atInfo().log("Activating module: {}:{}", moduleInfo.getName(), moduleInfo.getVersion());
gameManifest.addModule(module.getId(), module.getVersion());
moduleSet.add(module);
}

View file

@ -34,7 +34,7 @@ public boolean step() {
boolean entityCreated = false;
for (EntityRef entity : em.getAllEntities()) {
entityCreated = true;
logger.error("Entity created before load: {}", entity.toFullDescription());
logger.atError().log("Entity created before load: {}", entity.toFullDescription());
}
if (entityCreated) {
throw new IllegalStateException("Entity creation detected during component system initialisation, game load aborting");

View file

@ -68,7 +68,7 @@ public boolean step() {
ModuleEnvironment env = moduleManager.loadEnvironment(result.getModules(), true);
for (Module moduleInfo : env.getModulesOrderedByDependencies()) {
logger.info("Activating module: {}:{}", moduleInfo.getId(), moduleInfo.getVersion());
logger.atInfo().log("Activating module: {}:{}", moduleInfo.getId(), moduleInfo.getVersion());
}
EnvironmentSwitchHandler environmentSwitchHandler = context.get(EnvironmentSwitchHandler.class);

View file

@ -38,7 +38,7 @@ public class ModuleInstaller implements Callable<List<Module>> {
@Override
public List<Module> call() throws Exception {
Map<URI, Path> filesToDownload = getDownloadUrls(moduleList);
logger.info("Started downloading {} modules", filesToDownload.size());
logger.info("Started downloading {} modules", filesToDownload.size()); //NOPMD
MultiFileDownloader downloader = new MultiFileDownloader(filesToDownload, downloadProgressListener);
List<Path> downloadedModulesPaths = downloader.call();
logger.info("Module download completed, loading the new modules...");
@ -48,7 +48,7 @@ public List<Module> call() throws Exception {
Module module = moduleManager.registerArchiveModule(filePath);
newInstalledModules.add(module);
} catch (IOException e) {
logger.warn("Could not load module {}", filePath.getFileName(), e);
logger.warn("Could not load module {}", filePath.getFileName(), e); //NOPMD
}
}
logger.info("Finished loading the downloaded modules");

View file

@ -59,13 +59,13 @@ public ModuleRegistry call() throws IOException {
String json = gson.toJson(jObject);
ModuleMetadata meta = metaReader.read(new StringReader(json));
logger.debug("Read module {} - {}", meta.getId(), meta.getVersion());
logger.debug("Read module {} - {}", meta.getId(), meta.getVersion()); //NOPMD
modules.add(new Module(meta, new EmptyFileSource(), Collections.emptyList(), new Reflections(),
(c) -> false));
}
int count = modules.size();
logger.info("Retrieved {} {}", count, (count == 1) ? "entry" : "entries");
logger.info("Retrieved {} {}", count, (count == 1) ? "entry" : "entries"); //NOPMD
}
return modules;
}

View file

@ -173,9 +173,9 @@ private void loadModulesFromClassPath() {
continue;
}
if (registry.add(module)) {
logger.info("Loaded {} from {}", module.getId(), path);
logger.info("Loaded {} from {}", module.getId(), path); //NOPMD
} else {
logger.info("Module {} from {} was a duplicate; not registering this copy.", module.getId(), path);
logger.info("Module {} from {} was a duplicate; not registering this copy.", module.getId(), path); //NOPMD
}
}
}

View file

@ -66,7 +66,7 @@ public void preInitialise(Context rootContext) {
checkServerIdentity();
// TODO: Move to display subsystem
logger.info("Video Settings: {}", config.renderConfigAsJson(config.getRendering()));
logger.info("Video Settings: {}", config.renderConfigAsJson(config.getRendering())); //NOPMD
rootContext.put(Config.class, config);
//add facades

View file

@ -251,11 +251,11 @@ private void registerAxisBinds(ModuleEnvironment environment) {
BindableButton positiveButton = getBindButton(new SimpleUri(info.positiveButton()));
BindableButton negativeButton = getBindButton(new SimpleUri(info.negativeButton()));
if (positiveButton == null) {
logger.warn("Failed to register axis \"{}\", missing positive button \"{}\"", id, info.positiveButton());
logger.atWarn().log("Failed to register axis \"{}\", missing positive button \"{}\"", id, info.positiveButton());
continue;
}
if (negativeButton == null) {
logger.warn("Failed to register axis \"{}\", missing negative button \"{}\"", id, info.negativeButton());
logger.atWarn().log("Failed to register axis \"{}\", missing negative button \"{}\"", id, info.negativeButton());
continue;
}
try {

View file

@ -14,6 +14,7 @@ public class GLFWErrorCallback implements GLFWErrorCallbackI {
private static final Logger logger = LoggerFactory.getLogger("GLFW");
@Override
@SuppressWarnings("PMD.GuardLogStatement")
public void invoke(int error, long description) {
logger.error("Received error. Code: {}, Description: {}", error, MemoryUtil.memASCII(description));
}

View file

@ -526,7 +526,7 @@ public <T extends Component> T addComponent(long entityId, T component) {
if (!oldComponent.isPresent()) {
notifyComponentAdded(getEntity(entityId), component.getClass());
} else {
logger.error("Adding a component ({}) over an existing component for entity {}", component.getClass(), entityId);
logger.error("Adding a component ({}) over an existing component for entity {}", component.getClass(), entityId); //NOPMD
notifyComponentChanged(getEntity(entityId), component.getClass());
}
@ -580,7 +580,7 @@ public void saveComponent(long entityId, Component component) {
.map(pool -> pool.getComponentStore().put(entityId, component));
if (!oldComponent.isPresent()) {
logger.error("Saving a component ({}) that doesn't belong to this entity {}", component.getClass(), entityId);
logger.error("Saving a component ({}) that doesn't belong to this entity {}", component.getClass(), entityId); //NOPMD
}
if (eventSystem != null) {
EntityRef entityRef = getEntity(entityId);

View file

@ -83,7 +83,7 @@ public void process() {
@Override
public void registerEvent(ResourceUrn uri, Class<? extends Event> eventType) {
eventIdMap.put(uri, eventType);
logger.debug("Registering event {}", eventType.getSimpleName());
logger.debug("Registering event {}", eventType.getSimpleName()); //NOPMD
for (Class parent : ReflectionUtils.getAllSuperTypes(eventType, Predicates.subtypeOf(Event.class))) {
if (!AbstractConsumableEvent.class.equals(parent) && !Event.class.equals(parent)) {
childEvents.put(parent, eventType);
@ -95,11 +95,11 @@ public void registerEvent(ResourceUrn uri, Class<? extends Event> eventType) {
public void registerEventHandler(ComponentSystem handler) {
Class handlerClass = handler.getClass();
if (!Modifier.isPublic(handlerClass.getModifiers())) {
logger.error("Cannot register handler {}, must be public", handlerClass.getName());
logger.error("Cannot register handler {}, must be public", handlerClass.getName()); //NOPMD
return;
}
logger.debug("Registering event handler {}", handlerClass.getName());
logger.debug("Registering event handler {}", handlerClass.getName()); //NOPMD
for (Method method : handlerClass.getMethods()) {
ReceiveEvent receiveEventAnnotation = method.getAnnotation(ReceiveEvent.class);
if (receiveEventAnnotation != null) {
@ -129,7 +129,7 @@ public void registerEventHandler(ComponentSystem handler) {
logger.debug("Found method: {}", method);
if (!Event.class.isAssignableFrom(types[0]) || !EntityRef.class.isAssignableFrom(types[1])) {
logger.error("Invalid event handler method: {}", method.getName());
logger.error("Invalid event handler method: {}", method.getName()); //NOPMD
return;
}
@ -138,7 +138,7 @@ public void registerEventHandler(ComponentSystem handler) {
for (int i = 2; i < types.length; ++i) {
if (!Component.class.isAssignableFrom(types[i])) {
logger.error("Invalid event handler method: {} - {} is not a component class",
method.getName(), types[i]);
method.getName(), types[i]); //NOPMD
return;
}
requiredComponents.add((Class<? extends Component>) types[i]);

View file

@ -46,11 +46,11 @@ public <T> ComponentLibrary createCopyUsingCopyStrategy(Class<T> type, CopyStrat
try {
info = new ComponentMetadata<>(uri, type, factory, copyStrategies);
} catch (NoSuchMethodException e) {
logger.error("Unable to register class {}: Default Constructor Required", type.getSimpleName(), e);
logger.atError().log("Unable to register class {}: Default Constructor Required", type.getSimpleName(), e);
return null;
} catch (NoClassDefFoundError e) {
// log what class was not found so that diagnosis is easier
logger.error("Class not found, {}", type.getSimpleName(), e);
logger.atError().log("Class not found, {}", type.getSimpleName(), e);
throw e;
}
return info;

View file

@ -30,7 +30,7 @@ public EventLibrary(ModuleEnvironment environment, ReflectFactory reflectFactory
try {
return new EventMetadata<>(type, copyStrategies, factory, uri);
} catch (NoSuchMethodException e) {
logger.error("Unable to register class {}: Default Constructor Required", type.getSimpleName(), e);
logger.error("Unable to register class {}: Default Constructor Required", type.getSimpleName(), e); //NOPMD
return null;
}
}

View file

@ -38,7 +38,7 @@ public EventMetadata(Class<T> simpleClass, CopyStrategyLibrary copyStrategies, R
skipInstigator = simpleClass.getAnnotation(BroadcastEvent.class).skipInstigator();
}
if (networkEventType != NetworkEventType.NONE && !isConstructable() && !Modifier.isAbstract(simpleClass.getModifiers())) {
logger.error("Event '{}' is a network event but lacks a default constructor - will not be replicated", this);
logger.error("Event '{}' is a network event but lacks a default constructor - will not be replicated", this); //NOPMD
}
}

View file

@ -71,10 +71,10 @@ private synchronized void performAction(Action action, StorageServiceWorkerStatu
throw new RuntimeException("StorageServiceWorker is not in the required status");
}
status = StorageServiceWorkerStatus.WORKING;
logger.info("Performing action {}", action.getClass().getSimpleName());
logger.atInfo().log("Performing action {}", action.getClass().getSimpleName());
new Thread(() -> {
action.perform(this);
logger.info("Completed action {}", action.getClass().getSimpleName());
logger.atInfo().log("Completed action {}", action.getClass().getSimpleName());
}).start();
}

View file

@ -107,20 +107,20 @@ private void onJoystickConnectDisconnect(int jid, int event) {
private void handleJoystickConnect(int jid) {
if (GLFW.glfwJoystickIsGamepad(jid)) {
gamepadIds.add(jid);
logger.info("JoyStick connected: {}", GLFW.glfwGetJoystickName(jid));
logger.atInfo().log("JoyStick connected: {}", GLFW.glfwGetJoystickName(jid));
} else {
joystickIds.add(jid);
logger.info("Gamepad connected: {}", GLFW.glfwGetGamepadName(jid));
logger.atInfo().log("Gamepad connected: {}", GLFW.glfwGetGamepadName(jid));
}
}
private void handleJoystickDisconnect(int jid) {
if (GLFW.glfwJoystickIsGamepad(jid)) {
gamepadIds.remove(jid);
logger.info("JoyStick disconnected: {}", GLFW.glfwGetJoystickName(jid));
logger.atInfo().log("JoyStick disconnected: {}", GLFW.glfwGetJoystickName(jid));
} else {
joystickIds.remove(jid);
logger.info("Gamepad disconnected: {}", GLFW.glfwGetGamepadName(jid));
logger.atInfo().log("Gamepad disconnected: {}", GLFW.glfwGetGamepadName(jid));
}
}
@ -186,7 +186,7 @@ public Queue<ControllerAction> getInputQueue() {
buttonIndex++;
}
} else {
logger.error("Cannot get states for {}", GLFW.glfwGetGamepadName(jid));
logger.atError().log("Cannot get states for {}", GLFW.glfwGetGamepadName(jid));
}
}

View file

@ -98,7 +98,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi
secondValue = "";
break;
default:
logger.error("Unsupported guard value type: {}", tokens[0]);
logger.error("Unsupported guard value type: {}", tokens[0]); //NOPMD
secondValue = "";
}
@ -115,7 +115,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi
passing = (Boolean) fieldValue != Boolean.parseBoolean(secondValue);
break;
default:
logger.error("Unsupported operation for boolean values: {}", tokens[2]);
logger.error("Unsupported operation for boolean values: {}", tokens[2]); //NOPMD
}
@ -142,7 +142,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi
passing = ((Number) fieldValue).doubleValue() < Double.parseDouble(secondValue);
break;
default:
logger.error("Unsupported operation for numeric values: {}", tokens[2]);
logger.error("Unsupported operation for numeric values: {}", tokens[2]); //NOPMD
}
@ -157,7 +157,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi
passing = !fieldValue.equals(secondValue);
break;
default:
logger.error("Unsupported operation for strings: {}", tokens[2]);
logger.error("Unsupported operation for strings: {}", tokens[2]); //NOPMD
}
} else {
@ -190,7 +190,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi
break;
default:
logger.error("Unknown field type or operation: {} {}", fieldValue.getClass(), tokens[2]);
logger.error("Unknown field type or operation: {} {}", fieldValue.getClass(), tokens[2]); //NOPMD
}
}
}

View file

@ -56,7 +56,7 @@ public void construct(Actor actor) {
try {
action.construct(actor);
} catch (Exception e) {
logger.debug("Exception while running construct() of action {} from entity {}: ", action, actor.getEntity(), e);
logger.debug("Exception while running construct() of action {} from entity {}: ", action, actor.getEntity(), e); //NOPMD
}
}
}
@ -67,7 +67,7 @@ public BehaviorState execute(Actor actor) {
try {
return action.modify(actor, BehaviorState.UNDEFINED);
} catch (Exception e) {
logger.debug("Exception while running action {} from entity {}: ", action, actor.getEntity(), e);
logger.debug("Exception while running action {} from entity {}: ", action, actor.getEntity(), e); //NOPMD
// TODO maybe returning UNDEFINED would be more fitting?
return BehaviorState.FAILURE;
}

View file

@ -48,7 +48,7 @@ public void construct(Actor actor) {
try {
action.construct(actor);
} catch (Exception e) {
logger.info("Exception while running construct() of action {} from entity {}:", action, actor.getEntity());
logger.info("Exception while running construct() of action {} from entity {}:", action, actor.getEntity()); //NOPMD
}
}
}
@ -80,7 +80,7 @@ public BehaviorState execute(Actor actor) {
try {
modifiedState = action.modify(actor, lastState);
} catch (Exception e) {
logger.info("Exception while running action {} from entity {}: {}", action, actor.getEntity(), e.getStackTrace());
logger.info("Exception while running action {} from entity {}: {}", action, actor.getEntity(), e.getStackTrace()); //NOPMD
// TODO maybe returning UNDEFINED would be more canonical?
return BehaviorState.FAILURE;
}

View file

@ -60,7 +60,7 @@ public void onFootstep(FootstepEvent event, EntityRef entity, LocationComponent
Block block = worldProvider.getBlock(blockPos);
if (block != null) {
if (block.getSounds() == null) {
logger.error("Block '{}' has no sounds", block.getURI());
logger.error("Block '{}' has no sounds", block.getURI()); //NOPMD
} else if (!block.getSounds().getStepSounds().isEmpty()) {
footstepSounds = block.getSounds().getStepSounds();
}

View file

@ -306,44 +306,41 @@ private boolean isPredictionOfEventCorrect(EntityRef character, ActivationReques
CharacterComponent characterComponent = character.getComponent(CharacterComponent.class);
EntityRef camera = GazeAuthoritySystem.getGazeEntityForCharacter(character);
LocationComponent location = camera.getComponent(LocationComponent.class);
Vector3f direction = location.getWorldDirection(new Vector3f());
if (!(event.getDirection().equals(direction, 0.0001f))) {
logger.error("Direction at client {} was different than direction at server {}", event.getDirection(), direction);
Vector3f worldDirection = location.getWorldDirection(new Vector3f());
Vector3f eventDirection = event.getDirection();
if (!(eventDirection.equals(worldDirection, 0.0001f))) {
logger.error("Direction at client {} was different than direction at server {}", eventDirection, worldDirection);
}
// Assume the exact same value in case there are rounding mistakes:
direction = event.getDirection();
String playerName = getPlayerNameFromCharacter(character);
Vector3f originPos = location.getWorldPosition(new Vector3f());
if (!(event.getOrigin().equals(originPos, 0.0001f))) {
logger.info("Player {} seems to have cheated: It stated that it performed an action from {} but the predicted position is {}",
getPlayerNameFromCharacter(character), event.getOrigin(), originPos);
Vector3f eventOrigin = event.getOrigin();
if (!(eventOrigin.equals(originPos, 0.0001f))) {
logger.info("Player {} seems to have cheated: It stated that it performed an action from {} " +
"but the predicted position is {}", playerName, eventOrigin, originPos);
return false;
}
if (event.isOwnedEntityUsage()) {
if (!event.getUsedOwnedEntity().exists()) {
logger.info("Denied activation attempt by {} since the used entity does not exist on the authority",
getPlayerNameFromCharacter(character));
logger.info("Denied activation attempt by {} since the used entity does not exist on the authority", playerName);
return false;
}
if (!networkSystem.getOwnerEntity(event.getUsedOwnedEntity()).equals(networkSystem.getOwnerEntity(character))) {
logger.info("Denied activation attempt by {} since it does not own the entity at the authority",
getPlayerNameFromCharacter(character));
logger.info("Denied activation attempt by {} since it does not own the entity at the authority", playerName);
return false;
}
} else {
// check for cheats so that data can later be trusted:
if (event.getUsedOwnedEntity().exists()) {
logger.info("Denied activation attempt by {} since it is not properly marked as owned entity usage",
getPlayerNameFromCharacter(character));
logger.info("Denied activation attempt by {} since it is not properly marked as owned entity usage", playerName);
return false;
}
}
if (event.isEventWithTarget()) {
if (!event.getTarget().exists()) {
logger.info("Denied activation attempt by {} since the target does not exist on the authority",
getPlayerNameFromCharacter(character));
logger.info("Denied activation attempt by {} since the target does not exist on the authority", playerName);
return false; // can happen if target existed on client
}
@ -357,45 +354,42 @@ private boolean isPredictionOfEventCorrect(EntityRef character, ActivationReques
interactionRange = characterComponent.interactionRange;
}
HitResult result = physics.rayTrace(originPos, direction, interactionRange, Sets.newHashSet(character),
HitResult result = physics.rayTrace(originPos, eventDirection, interactionRange, Sets.newHashSet(character),
DEFAULTPHYSICSFILTER);
if (!result.isHit()) {
logger.info("Denied activation attempt by {} since at the authority there was nothing to activate at that place",
getPlayerNameFromCharacter(character));
logger.info("Denied activation attempt by {} since at the authority there was nothing " +
"to activate at that place", playerName);
return false;
}
EntityRef hitEntity = result.getEntity();
if (!hitEntity.equals(event.getTarget())) {
/**
* Tip for debugging this issue: Obtain the network id of hit entity and search it in both client and
* server entity dump. When certain fields don't get replicated, then wrong entity might get hin in the
* hit test.
/*
Tip for debugging this issue: Obtain the network id of hit entity and search it in both client and
server entity dump. When certain fields don't get replicated, then wrong entity might get hin in the
hit test.
*/
logger.info("Denied activation attempt by {} since at the authority another entity would have been activated",
getPlayerNameFromCharacter(character));
logger.info("Denied activation attempt by {} since at the authority another entity would have been activated", playerName);
return false;
}
if (!(event.getHitPosition().equals(result.getHitPoint(), 0.0001f))) {
logger.info("Denied activation attempt by {} since at the authority the object got hit at a differnt position",
getPlayerNameFromCharacter(character));
logger.info("Denied activation attempt by {} since at the authority the object " +
"got hit at a different position", playerName);
return false;
}
} else {
// In order to trust the data later we need to verify it even if it should be correct if no one cheats:
if (event.getTarget().exists()) {
logger.info("Denied activation attempt by {} since the event was not properly labeled as having a target",
getPlayerNameFromCharacter(character));
logger.info("Denied activation attempt by {} since the event was not properly labeled as having a target", playerName);
return false;
}
if (event.getHitPosition() != null) {
logger.info("Denied activation attempt by {} since the event was not properly labeled as having a hit position",
getPlayerNameFromCharacter(character));
logger.info("Denied activation attempt by {} since the event was not properly labeled " +
"as having a hit position", playerName);
return false;
}
if (event.getHitNormal() != null) {
logger.info("Denied activation attempt by {} since the event was not properly labeled as having a hit delta",
getPlayerNameFromCharacter(character));
logger.info("Denied activation attempt by {} since the event was not properly labeled as having a hit delta", playerName);
return false;
}
}

View file

@ -84,7 +84,7 @@ public void onDestroy(final BeforeDeactivateComponent event, final EntityRef ent
@ReceiveEvent(components = {CharacterMovementComponent.class, LocationComponent.class, AliveCharacterComponent.class})
public void onCharacterStateReceived(CharacterStateEvent state, EntityRef entity) {
if (entity.equals(localPlayer.getCharacterEntity())) {
logger.trace("Received new state, sequence number: {}, buffered input size {}", state.getSequenceNumber(), inputs.size());
logger.trace("Received new state, sequence number: {}, buffered input size {}", state.getSequenceNumber(), inputs.size()); //NOPMD
playerStates.remove(entity);
authoritiveState = state;
@ -98,7 +98,7 @@ public void onCharacterStateReceived(CharacterStateEvent state, EntityRef entity
newState = stepState(input, newState, entity);
}
}
logger.trace("Resultant input size {}", inputs.size());
logger.trace("Resultant input size {}", inputs.size()); //NOPMD
characterMovementSystemUtility.setToState(entity, newState);
// TODO: soft correct predicted state
predictedState = newState;

View file

@ -59,12 +59,13 @@ public ConsoleImpl(Context context) {
* @param command The command to be registered
*/
@Override
@SuppressWarnings("PMD.GuardLogStatement")
public void registerCommand(ConsoleCommand command) {
Name commandName = command.getName();
if (commandRegistry.containsKey(commandName)) {
logger.warn("Command with name '{}' already registered by class '{}', skipping '{}'",
commandName, commandRegistry.get(commandName).getSource().getClass().getCanonicalName(),
logger.warn("Command with name '{}' already registered by class '{}', skipping '{}'", commandName,
commandRegistry.get(commandName).getSource().getClass().getCanonicalName(),
command.getSource().getClass().getCanonicalName());
} else {
commandRegistry.put(commandName, command);
@ -135,7 +136,7 @@ public void addMessage(String message, MessageType type, boolean newLine) {
@Override
public void addMessage(Message message) {
String uncoloredText = FontUnderline.strip(FontColor.stripColor(message.getMessage()));
logger.info("[{}] {}", message.getType(), uncoloredText);
logger.info("[{}] {}", message.getType(), uncoloredText); //NOPMD
messageHistory.add(message);
for (ConsoleSubscriber subscriber : messageSubscribers) {
subscriber.onNewConsoleMessage(message);

View file

@ -71,23 +71,24 @@ public static MethodCommand referringTo(SpecificAccessibleObject<Method> specifi
public static void registerAvailable(Object provider, Console console, Context context) {
Predicate<? super Method> predicate = Predicates.<Method>and(ReflectionUtils.withModifier(Modifier.PUBLIC),
ReflectionUtils.withAnnotation(Command.class));
Set<Method> commandMethods = ReflectionUtils.getAllMethods(provider.getClass(), predicate);
Class<?> providerClass = provider.getClass();
Set<Method> commandMethods = ReflectionUtils.getAllMethods(providerClass, predicate);
for (Method method : commandMethods) {
String methodName = method.getName();
String canonicalMethodName = method.getDeclaringClass().getCanonicalName();
if (!hasSenderAnnotation(method)) {
logger.error("Command {} provided by {} contains a EntityRef without @Sender annotation, may cause a " +
"NullPointerException", method.getName(), provider.getClass().getSimpleName());
logger.atError().log("Command {} provided by {} contains a EntityRef without @Sender annotation, may cause a " +
"NullPointerException", methodName, providerClass.getSimpleName());
}
logger.debug("Registering command method {} in class {}", method.getName(),
method.getDeclaringClass().getCanonicalName());
logger.debug("Registering command method {} in class {}", methodName, canonicalMethodName);
try {
SpecificAccessibleObject<Method> specificMethod = new SpecificAccessibleObject<>(method, provider);
MethodCommand command = referringTo(specificMethod, context);
console.registerCommand(command);
logger.debug("Registered command method {} in class {}", method.getName(),
method.getDeclaringClass().getCanonicalName());
logger.debug("Registered command method {} in class {}", methodName, canonicalMethodName);
} catch (RuntimeException t) {
logger.error("Failed to load command method {} in class {}", method.getName(),
method.getDeclaringClass().getCanonicalName(), t);
logger.error("Failed to load command method {} in class {}", methodName, canonicalMethodName, t);
}
}
}

View file

@ -68,7 +68,7 @@ public String shutdownServer(@Sender EntityRef sender) {
EntityRef clientInfo = sender.getComponent(ClientComponent.class).clientInfo;
DisplayNameComponent name = clientInfo.getComponent(DisplayNameComponent.class);
logger.info("Shutdown triggered by {}", name.name);
logger.info("Shutdown triggered by {}", name.name); //NOPMD
gameEngine.shutdown();
@ -165,7 +165,7 @@ private String kick(EntityRef clientEntity) {
EntityRef clientInfo = clientEntity.getComponent(ClientComponent.class).clientInfo;
DisplayNameComponent name = clientInfo.getComponent(DisplayNameComponent.class);
logger.info("Kicking user {}", name.name);
logger.info("Kicking user {}", name.name); //NOPMD
networkSystem.forceDisconnect(client);
return "User kick triggered for '" + name.name + "'";

View file

@ -25,14 +25,14 @@ public class ChunkEventErrorLogger extends BaseComponentSystem {
@ReceiveEvent(components = WorldComponent.class)
public void onNewChunk(OnChunkLoaded chunkAvailable, EntityRef worldEntity) {
if (!loadedChunks.add(chunkAvailable.getChunkPos())) {
logger.error("Multiple loads of chunk {}", chunkAvailable.getChunkPos());
logger.error("Multiple loads of chunk {}", chunkAvailable.getChunkPos()); //NOPMD
}
}
@ReceiveEvent(components = WorldComponent.class)
public void onRemoveChunk(BeforeChunkUnload chunkUnload, EntityRef worldEntity) {
if (!loadedChunks.remove(chunkUnload.getChunkPos())) {
logger.error("Unload event for not loaded chunk {}", chunkUnload.getChunkPos());
logger.error("Unload event for not loaded chunk {}", chunkUnload.getChunkPos()); //NOPMD
}
}
}

View file

@ -82,7 +82,7 @@ public void updateExtentsOnBlockItemBoxShape(OnAddedComponent event, EntityRef i
BlockFamily blockFamily = blockItemComponent.blockFamily;
if (blockFamily == null) {
LOGGER.warn("Prefab {} does not have a block family", itemEntity.getParentPrefab().getName());
LOGGER.warn("Prefab {} does not have a block family", itemEntity.getParentPrefab().getName()); //NOPMD
return;
}

View file

@ -155,7 +155,7 @@ public void onConnect(ConnectedEvent connected, EntityRef entity) {
private void restoreCharacter(EntityRef entity, EntityRef character) {
Client clientListener = networkSystem.getOwner(entity);
LOGGER.info(clientListener.toString());
LOGGER.info("{}", clientListener);
updateRelevanceEntity(entity, clientListener.getViewDistance().getChunkDistance());
ClientComponent client = entity.getComponent(ClientComponent.class);

View file

@ -151,17 +151,18 @@ private void receiveModuleStart(ChannelHandlerContext channelHandlerContext,
return;
}
String moduleId = moduleDataHeader.getId();
String moduleVersion = moduleDataHeader.getVersion();
if (missingModules.remove(moduleId.toLowerCase(Locale.ENGLISH))) {
if (moduleDataHeader.hasError()) {
joinStatus.setErrorMessage("Module download error: " + moduleDataHeader.getError());
channelHandlerContext.channel().close();
} else {
String sizeString = getSizeString(moduleDataHeader.getSize());
int numOfMissingModules = missingModules.size();
joinStatus.setCurrentActivity(
"Downloading " + moduleDataHeader.getId() + ":" + moduleDataHeader.getVersion() + " ("
+ sizeString + "," + missingModules.size() + " modules remain)");
logger.info("Downloading {}: {} ({}, {} modules remain)", moduleDataHeader.getId(), moduleDataHeader.getVersion(),
sizeString, missingModules.size());
"Downloading " + moduleDataHeader.getId() + ":" + moduleVersion
+ " (" + sizeString + "," + numOfMissingModules + " modules remain)");
logger.info("Downloading {}: {} ({}, {} modules remain)", moduleId, moduleVersion, sizeString, numOfMissingModules);
receivingModule = moduleDataHeader;
lengthReceived = 0;
try {
@ -176,7 +177,7 @@ private void receiveModuleStart(ChannelHandlerContext channelHandlerContext,
}
}
} else {
logger.error("Received unwanted module {}:{} from server", moduleDataHeader.getId(), moduleDataHeader.getVersion());
logger.error("Received unwanted module {}:{} from server", moduleId, moduleVersion);
joinStatus.setErrorMessage("Module download error");
channelHandlerContext.channel().close();
}

View file

@ -363,7 +363,8 @@ public boolean isLocal() {
}
void send(NetData.NetMessage data) {
logger.trace("Sending packet with size {}", data.getSerializedSize());
int dataSize = data.getSerializedSize();
logger.trace("Sending packet with size {}", dataSize);
sentMessages.incrementAndGet();
sentBytes.addAndGet(data.getSerializedSize());
channel.writeAndFlush(data);
@ -507,7 +508,7 @@ private void processEvents(NetData.NetMessage message) {
Event event = eventSerializer.deserialize(eventMessage.getEvent());
EventMetadata<?> metadata = eventLibrary.getMetadata(event.getClass());
if (metadata.getNetworkEventType() != NetworkEventType.SERVER) {
logger.warn("Received non-server event '{}' from client '{}'", metadata, getName());
logger.atWarn().log("Received non-server event '{}' from client '{}'", metadata, getName());
continue;
}
if (!lagCompensated && metadata.isLagCompensated()) {

View file

@ -183,7 +183,7 @@ public void host(int port, boolean dedicatedServer) throws HostingFailedExceptio
logger.info("Started server on port {}", port);
if (config.getServerMOTD() != null) {
logger.info("Server MOTD is \"{}\"", config.getServerMOTD());
logger.info("Server MOTD is \"{}\"", config.getServerMOTD()); //NOPMD
} else {
logger.info("No server MOTD is defined");
}
@ -239,11 +239,13 @@ public JoinStatus join(String address, int port) throws InterruptedException {
return connectionHandler.getJoinStatus();
}
} else {
logger.warn("Failed to connect to server", connectCheck.cause());
Throwable connectionFailureCause = connectCheck.cause();
logger.warn("Failed to connect to server", connectionFailureCause);
connectCheck.channel().closeFuture().awaitUninterruptibly();
clientGroup.shutdownGracefully(shutdownQuietMs, shutdownTimeoutMs, TimeUnit.MILLISECONDS)
.syncUninterruptibly();
return new JoinStatusImpl("Failed to connect to server - " + connectCheck.cause().getMessage());
return new JoinStatusImpl("Failed to connect to server - " + connectionFailureCause.getMessage());
}
}
connectCheck.channel().closeFuture().sync();
@ -538,11 +540,12 @@ public void unregisterNetworkEntity(EntityRef entity) {
if (mode != NetworkMode.CLIENT) {
NetworkComponent netComponent = entity.getComponent(NetworkComponent.class);
if (netComponent != null) {
logger.debug("Unregistering network entity: {} with netId {}", entity, netComponent.getNetworkId());
netIdToEntityId.remove(netComponent.getNetworkId());
int networkId = netComponent.getNetworkId();
logger.debug("Unregistering network entity: {} with netId {}", entity, networkId);
netIdToEntityId.remove(networkId);
if (mode.isServer()) {
for (NetClient client : netClientList) {
client.setNetRemoved(netComponent.getNetworkId());
client.setNetRemoved(networkId);
}
}
netComponent.setNetworkId(NULL_NET_ID);
@ -826,7 +829,7 @@ private void processRemovedClient(Client client) {
}
clientList.remove(client);
clientPlayerLookup.remove(client.getEntity());
logger.info("Client disconnected: {}", client.getName());
logger.info("Client disconnected: {}", client.getName()); //NOPMD
storageManager.deactivatePlayer(client);
client.getEntity().send(new DisconnectedEvent());
client.disconnect();
@ -855,7 +858,7 @@ private void processNewClient(NetClient client) {
connectClient(client);
// log after connect so that the name has been set:
logger.info("New client entity: {}", client.getEntity());
logger.info("New client entity: {}", client.getEntity()); //NOPMD
for (EntityRef netEntity : entityManager.getEntitiesWith(NetworkComponent.class)) {
NetworkComponent netComp = netEntity.getComponent(NetworkComponent.class);
if (netComp.getNetworkId() != NULL_NET_ID) {
@ -972,7 +975,7 @@ private <T> Map<Class<? extends T>, Integer> generateIds(ClassLibrary<T> classLi
int fieldId = 0;
for (FieldMetadata<?, ?> field : metadata.getFields()) {
if (fieldId >= 256) {
logger.error("Class {} has too many fields (>255), serialization will be incomplete", metadata.getId());
logger.error("Class {} has too many fields (>255), serialization will be incomplete", metadata.getId()); //NOPMD
break;
}
field.setId((byte) fieldId);
@ -992,19 +995,21 @@ private <T> Map<Class<? extends T>, Integer> applySerializationInfo(List<NetData
ClassLibrary<T> classLibrary) {
Map<Class<? extends T>, Integer> idTable = Maps.newHashMap();
for (NetData.SerializationInfo info : infoList) {
ClassMetadata<? extends T, ?> metadata = classLibrary.getMetadata(info.getName());
String infoName = info.getName();
ClassMetadata<? extends T, ?> metadata = classLibrary.getMetadata(infoName);
if (metadata != null) {
idTable.put(metadata.getType(), info.getId());
for (int i = 0; i < info.getFieldIds().size(); ++i) {
FieldMetadata<?, ?> field = metadata.getField(info.getFieldName(i));
String fieldName = info.getFieldName(i);
FieldMetadata<?, ?> field = metadata.getField(fieldName);
if (field != null) {
field.setId(info.getFieldIds().byteAt(i));
} else {
logger.error("Server has unknown field '{}' on '{}'", info.getFieldName(i), info.getName());
logger.error("Server has unknown field '{}' on '{}'", fieldName, infoName);
}
}
} else {
logger.error("Server has unknown class '{}'", info.getName());
logger.error("Server has unknown class '{}'", infoName);
}
}
return idTable;

View file

@ -193,7 +193,7 @@ private void processReceivedChunks() {
}
private void send(NetData.NetMessage data) {
logger.trace("Sending with size {}", data.getSerializedSize());
logger.atTrace().log("Sending with size {}", data.getSerializedSize());
channel.writeAndFlush(data);
}
@ -232,7 +232,7 @@ private void processEvent(NetData.EventMessage message) {
if (target.exists()) {
target.send(event);
} else {
logger.info("Dropping event {} for unavailable entity {}", event.getClass().getSimpleName(), target);
logger.atInfo().log("Dropping event {} for unavailable entity {}", event.getClass().getSimpleName(), target);
}
} catch (DeserializationException e) {
logger.error("Failed to deserialize event", e);
@ -346,21 +346,23 @@ private void processBlockRegistrations(NetData.NetMessage message) {
}
blockManager.receiveFamilyRegistration(family, registrationMap);
} catch (BlockUriParseException e) {
logger.error("Received invalid block uri {}", blockFamily.getBlockUri(0));
logger.error("Received invalid block uri {}", blockFamily.getBlockUri(0)); //NOPMD
}
}
}
}
private void updateEntity(NetData.UpdateEntityMessage updateEntity) {
EntityRef currentEntity = networkSystem.getEntity(updateEntity.getNetId());
int entityNetId = updateEntity.getNetId();
EntityRef currentEntity = networkSystem.getEntity(entityNetId);
if (currentEntity.exists()) {
NetworkComponent netComp = currentEntity.getComponent(NetworkComponent.class);
if (netComp == null) {
logger.error("Updating entity with no network component: {}, expected netId {}", currentEntity, updateEntity.getNetId());
logger.error("Updating entity with no network component: {}, expected netId {}", currentEntity, entityNetId);
return;
}
if (netComp.getNetworkId() != updateEntity.getNetId()) {
int networkId = netComp.getNetworkId();
if (networkId != entityNetId) {
logger.error("Network ID wrong before update");
}
boolean blockEntityBefore = currentEntity.hasComponent(BlockComponent.class);
@ -370,11 +372,11 @@ private void updateEntity(NetData.UpdateEntityMessage updateEntity) {
&& !blockEntityRegistry.getExistingBlockEntityAt(blockComponent.getPosition()).equals(currentEntity)) {
logger.error("Failed to associated new block entity");
}
if (netComp.getNetworkId() != updateEntity.getNetId()) {
logger.error("Network ID lost in update: {}, {} -> {}", currentEntity, updateEntity.getNetId(), netComp.getNetworkId());
if (networkId != entityNetId) {
logger.error("Network ID lost in update: {}, {} -> {}", currentEntity, entityNetId, networkId);
}
} else {
logger.warn("Received update for non-existent entity {}", updateEntity.getNetId());
logger.warn("Received update for non-existent entity {}", entityNetId);
}
}

View file

@ -125,7 +125,8 @@ public void initialize() {
for (Class<?> type : environment.getTypesAnnotatedWith(RegisterParticleSystemFunction.class)) {
if (!ParticleSystemFunction.class.isAssignableFrom(type)) {
logger.error("Cannot register particle system function {}, must be a subclass of ParticleSystemFunction", type.getSimpleName());
logger.atError().log("Cannot register particle system function {}, " +
"must be a subclass of ParticleSystemFunction", type.getSimpleName());
} else {
try {
ParticleSystemFunction function = (ParticleSystemFunction) type.newInstance();

View file

@ -93,7 +93,7 @@ private Prefab loadPrefab(EntityData.Prefab prefabData, Map<String, EntityData.P
try (ModuleContext.ContextSpan ignored = ModuleContext.setContext(module)) {
return createPrefab(prefabData);
} catch (Exception e) {
logger.error("Failed to load prefab {}", prefabData.getParentName(), e);
logger.error("Failed to load prefab {}", prefabData.getParentName(), e); //NOPMD
return null;
}
}
@ -108,11 +108,12 @@ private Prefab createPrefab(EntityData.Prefab prefabData) {
private void loadComponentMapping(EntityData.GlobalStore globalStore) {
Map<Class<? extends Component>, Integer> componentIdTable = Maps.newHashMap();
for (int index = 0; index < globalStore.getComponentClassCount(); ++index) {
ComponentMetadata<?> componentMetadata = componentLibrary.resolve(globalStore.getComponentClass(index));
String componentClass = globalStore.getComponentClass(index);
ComponentMetadata<?> componentMetadata = componentLibrary.resolve(componentClass);
if (componentMetadata != null) {
componentIdTable.put(componentMetadata.getType(), index);
} else {
logger.warn("Unable to resolve component '{}'", globalStore.getComponentClass(index));
logger.warn("Unable to resolve component '{}'", componentClass);
}
}

View file

@ -100,7 +100,7 @@ public Component deserialize(EntityData.Component componentData, Module context)
Component component = componentMetadata.newInstance();
return deserializeOnto(component, componentData, componentMetadata, FieldSerializeCheck.NullCheck.<Component>newInstance());
} else {
logger.warn("Unable to deserialize unknown component type: {}", componentData.getType());
logger.atWarn().log("Unable to deserialize unknown component type: {}", componentData.getType());
}
return null;
}
@ -159,7 +159,7 @@ public Component deserializeOnto(Component target, EntityData.Component componen
if (componentMetadata != null) {
return deserializeOnto(target, componentData, componentMetadata, fieldCheck);
} else {
logger.warn("Unable to deserialize unknown component type: {}", componentData.getType());
logger.atWarn().log("Unable to deserialize unknown component type: {}", componentData.getType());
}
return target;
}
@ -179,7 +179,7 @@ private <T extends Component> Component deserializeOnto(Component targetComponen
if (fieldInfo != null) {
dataMap.put(fieldInfo, new ProtobufPersistedData(field.getValue()));
} else if (field.hasName()) {
logger.warn("Cannot deserialize unknown field '{}' onto '{}'", field.getName(), componentMetadata.getId());
logger.atWarn().log("Cannot deserialize unknown field '{}' onto '{}'", field.getName(), componentMetadata.getId());
}
}
serializer.deserializeOnto(targetComponent, dataMap, fieldCheck);
@ -205,9 +205,10 @@ public EntityData.Component serialize(Component component) {
* @return The serialized component, or null if it could not be serialized.
*/
public EntityData.Component serialize(Component component, FieldSerializeCheck<Component> check) {
ComponentMetadata<?> componentMetadata = componentLibrary.getMetadata(component.getClass());
if (componentMetadata == null) {
logger.error("Unregistered component type: {}", component.getClass());
logger.atError().log("Unregistered component type: {}", component.getClass());
return null;
}
EntityData.Component.Builder componentMessage = EntityData.Component.newBuilder();
@ -262,7 +263,7 @@ public EntityData.Component serialize(Component base, Component delta) {
public EntityData.Component serialize(Component base, Component delta, FieldSerializeCheck<Component> check) {
ComponentMetadata<?> componentMetadata = componentLibrary.getMetadata(base.getClass());
if (componentMetadata == null) {
logger.error("Unregistered component type: {}", base.getClass());
logger.atError().log("Unregistered component type: {}", base.getClass());
return null;
}
@ -325,7 +326,7 @@ public ComponentMetadata<? extends Component> getComponentMetadata(EntityData.Co
}
}
if (metadata == null) {
logger.warn("Unable to deserialize unknown component with id: {}", componentData.getTypeIndex());
logger.atWarn().log("Unable to deserialize unknown component with id: {}", componentData.getTypeIndex());
return null;
}
return metadata;
@ -337,7 +338,7 @@ public ComponentMetadata<? extends Component> getComponentMetadata(EntityData.Co
metadata = componentLibrary.resolve(componentData.getType());
}
if (metadata == null) {
logger.warn("Unable to deserialize unknown component type: {}", componentData.getType());
logger.atWarn().log("Unable to deserialize unknown component type: {}", componentData.getType());
return null;
}
return metadata;

View file

@ -154,7 +154,7 @@ public Class<? extends Event> getEventClass(EntityData.Event eventData) {
}
}
if (metadata == null) {
logger.warn("Unable to deserialize unknown event with id: {}", eventData.getType());
logger.warn("Unable to deserialize unknown event with id: {}", eventData.getType()); //NOPMD
return null;
}
return metadata.getType();

View file

@ -130,7 +130,7 @@ private void serializeComponentDelta(Component oldComponent, Component newCompon
boolean componentInitial) {
ComponentMetadata<?> componentMetadata = componentLibrary.getMetadata(oldComponent.getClass());
if (componentMetadata == null) {
logger.error("Unregistered component type: {}", oldComponent.getClass());
logger.atError().log("Unregistered component type: {}", oldComponent.getClass());
return;
}
@ -165,7 +165,7 @@ private void serializeComponentFull(Component component, boolean ignoreIfNoField
boolean componentInitial) {
ComponentMetadata<?> componentMetadata = componentLibrary.getMetadata(component.getClass());
if (componentMetadata == null) {
logger.error("Unregistered component type: {}", component.getClass());
logger.atError().log("Unregistered component type: {}", component.getClass());
return;
}
@ -218,7 +218,8 @@ public void deserializeOnto(MutableComponentContainer entity, EntityData.PackedE
byte fieldId = entityData.getFieldIds().byteAt(fieldPos);
ReplicatedFieldMetadata fieldMetadata = metadata.getField(fieldId);
if (fieldMetadata != null && fieldCheck.shouldDeserialize(metadata, fieldMetadata)) {
logger.trace("Deserializing field {} of component {} as value {}", fieldMetadata, metadata, entityData.getFieldValue(fieldPos));
logger.atTrace().log("Deserializing field {} of component {} as value {}",
fieldMetadata, metadata, entityData.getFieldValue(fieldPos));
serializer.deserializeOnto(component, fieldMetadata, new ProtobufPersistedData(entityData.getFieldValue(fieldPos)));
}
fieldPos++;

View file

@ -155,7 +155,7 @@ private void applyComponentChanges(Module context, EntityData.Prefab prefabData,
}
}
} else if (componentData.hasType()) {
logger.warn("Prefab '{}' contains unknown component '{}'", prefabData.getName(), componentData.getType());
logger.warn("Prefab '{}' contains unknown component '{}'", prefabData.getName(), componentData.getType()); //NOPMD
}
}
}

View file

@ -157,7 +157,7 @@ private void createPrefab(EntityData.Prefab prefabData) {
PrefabData protoPrefab = prefabSerializer.deserialize(prefabData);
Assets.generateAsset(new ResourceUrn(prefabData.getName()), protoPrefab, Prefab.class);
} catch (Exception e) {
logger.error("Failed to create prefab {}", prefabData.getName());
logger.error("Failed to create prefab {}", prefabData.getName()); //NOPMD
}
}

View file

@ -241,7 +241,7 @@ public HitResult rayTrace(Vector3f from, Vector3f direction, float distance, Col
hitNormalWorld,
voxelPosition);
} else { //we hit something we don't understand, assume its nothing and log a warning
logger.warn("Unidentified object was hit in the physics engine: {}", collisionObject.userData);
logger.warn("Unidentified object was hit in the physics engine: {}", collisionObject.userData); //NOPMD
}
}
@ -305,7 +305,7 @@ public HitResult rayTrace(Vector3f from, Vector3f direction, float distance, Set
hitNormalWorld,
voxelPosition);
} else { //we hit something we don't understand, assume its nothing and log a warning
logger.warn("Unidentified object was hit in the physics engine: {}", collisionObject.userData);
logger.warn("Unidentified object was hit in the physics engine: {}", collisionObject.userData); //NOPMD
}
}
}

View file

@ -276,7 +276,7 @@ private EntityRef getEntityRef(RecordedEvent recordedEvent) {
@Override
public void registerEvent(ResourceUrn uri, Class<? extends Event> eventType) {
eventIdMap.put(uri, eventType);
logger.debug("Registering event {}", eventType.getSimpleName());
logger.debug("Registering event {}", eventType.getSimpleName()); //NOPMD
for (Class parent : ReflectionUtils.getAllSuperTypes(eventType, Predicates.subtypeOf(Event.class))) {
if (!AbstractConsumableEvent.class.equals(parent) && !Event.class.equals(parent)) {
childEvents.put(parent, eventType);
@ -303,11 +303,11 @@ private boolean shouldAddToLibrary(Class<? extends Event> eventType) {
public void registerEventHandler(ComponentSystem handler) {
Class handlerClass = handler.getClass();
if (!Modifier.isPublic(handlerClass.getModifiers())) {
logger.error("Cannot register handler {}, must be public", handlerClass.getName());
logger.error("Cannot register handler {}, must be public", handlerClass.getName()); //NOPMD
return;
}
logger.debug("Registering event handler {}", handlerClass.getName());
logger.debug("Registering event handler {}", handlerClass.getName()); //NOPMD
for (Method method : handlerClass.getMethods()) {
ReceiveEvent receiveEventAnnotation = method.getAnnotation(ReceiveEvent.class);
if (receiveEventAnnotation != null) {
@ -336,7 +336,7 @@ public void registerEventHandler(ComponentSystem handler) {
logger.debug("Found method: {}", method);
if (!Event.class.isAssignableFrom(types[0]) || !EntityRef.class.isAssignableFrom(types[1])) {
logger.error("Invalid event handler method: {}", method.getName());
logger.error("Invalid event handler method: {}", method.getName()); //NOPMD
return;
}
@ -344,7 +344,7 @@ public void registerEventHandler(ComponentSystem handler) {
List<Class<? extends Component>> componentParams = Lists.newArrayList();
for (int i = 2; i < types.length; ++i) {
if (!Component.class.isAssignableFrom(types[i])) {
logger.error("Invalid event handler method: {} - {} is not a component class", method.getName(), types[i]);
logger.error("Invalid event handler method: {} - {} is not a component class", method.getName(), types[i]); //NOPMD
return;
}
requiredComponents.add((Class<? extends Component>) types[i]);

View file

@ -73,7 +73,7 @@ public static void inject(final Object object) {
logger.error("Failed to inject value {} into field {} of {}", value, field, object, e);
}
} else {
logger.warn("{} wanted {} injected but CoreRegistry has none.",
logger.atWarn().log("{} wanted {} injected but CoreRegistry has none.",
object.getClass().getSimpleName(), field.getType().getSimpleName());
}
}

View file

@ -47,6 +47,7 @@ public void initShaders() {
addShaderProgram("particle");
}
@SuppressWarnings("PMD.GuardLogStatement")
private void logCapabilities() {
logger.info("Loading Terasology shader manager...");
logger.info("LWJGL: {} / {}", Version.getVersion(), Platform.get().getName());

View file

@ -472,7 +472,7 @@ public List<String> getOutputConnectionsList() {
}
public void disconnectInputFbo(int inputId) {
logger.info("Disconnecting {} input Fbo number {}", this.getUri(), inputId);
logger.info("Disconnecting {} input Fbo number {}", this.getUri(), inputId); //NOPMD
DependencyConnection connectionToDisconnect = this.inputConnections.get(FboConnection.getConnectionName(inputId, this.nodeUri));
if (connectionToDisconnect != null) {
// TODO make it reconnectInputFboToOutput
@ -547,7 +547,7 @@ public void dispose() {
*/
protected void addDesiredStateChange(StateChange stateChange) {
if (stateChange.isTheDefaultInstance()) {
logger.error("Attempted to add default state change {} to the set of desired state changes. (Node: {})",
logger.atError().log("Attempted to add default state change {} to the set of desired state changes. (Node: {})",
stateChange.getClass().getSimpleName(), this);
}
desiredStateChanges.add(stateChange);

View file

@ -118,9 +118,9 @@ protected FBO generateWithDimensions(FboConfig fboConfig, FBO.Dimensions dimensi
// At this stage it's unclear what should be done in this circumstances as I (manu3d) do not know what
// the effects of using an incomplete FrameBuffer are. Throw an exception? Live with visual artifacts?
if (fbo.getStatus() == FBO.Status.INCOMPLETE) {
logger.error("FBO {} is incomplete. Look earlier in the log for details.", fboConfig.getName());
logger.error("FBO {} is incomplete. Look earlier in the log for details.", fboConfig.getName()); //NOPMD
} else if (fbo.getStatus() == FBO.Status.UNEXPECTED) {
logger.error("FBO {} has generated an unexpected status code. Look earlier in the log for details.", fboConfig.getName());
logger.error("FBO {} has generated an unexpected status code. Look earlier in the log for details.", fboConfig.getName()); //NOPMD
}
return fbo;
}

View file

@ -52,7 +52,7 @@ public void addNode(Node node) {
}
if (akaNodeMap.containsKey(nodeAka)) {
Node aNode = akaNodeMap.get(nodeAka);
logger.info("Node {} also known as {} already matches existing node with uri {} - attempting replacing...",
logger.atInfo().log("Node {} also known as {} already matches existing node with uri {} - attempting replacing...",
nodeUri, nodeAka, aNode.getUri());
replaceNode(aNode, node);
} else {
@ -149,7 +149,7 @@ private void connect(Node... nodeList) {
if (!graph.hasEdgeConnecting(fromNode, toNode)) {
graph.putEdge(fromNode, toNode);
} else {
logger.warn("Trying to connect two already connected nodes, {} and {}", fromNode.getUri(), toNode.getUri());
logger.warn("Trying to connect two already connected nodes, {} and {}", fromNode.getUri(), toNode.getUri()); //NOPMD
}
}
@ -169,7 +169,7 @@ public void disconnect(Node fromNode, Node toNode) {
Preconditions.checkNotNull(toNode, "toNode cannot be null!");
if (!graph.hasEdgeConnecting(fromNode, toNode)) {
logger.warn("Trying to disconnect two nodes that aren't connected, {} and {}", fromNode.getUri(), toNode.getUri());
logger.warn("Trying to disconnect two nodes that aren't connected, {} and {}", fromNode.getUri(), toNode.getUri()); //NOPMD
}
graph.removeEdge(fromNode, toNode);
@ -275,7 +275,7 @@ private void connectFbo(Node toNode, int inputFboId, DependencyConnection fromCo
} else { // if adding new input failed, it already existed - check for connections
//TODO update
logger.info("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..",
logger.atInfo().log("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..",
toNode.getUri(), inputFboId, fromConnection.getName());
DependencyConnection localConnection = toNode.getInputFboConnection(inputFboId);
// DependencyConnection localConnectionConnectedTo = localConnection.getConnectedConnections();
@ -302,7 +302,7 @@ public void connectFbo(Node fromNode, int outputId, Node toNode, int inputId) {
// if (!areConnected(fromNode, toNode)) {
// connect(fromNode, toNode);
// }
logger.debug("Connected {} to {}.", fromNode.getOutputFboConnection(outputId), toNode);
logger.atDebug().log("Connected {} to {}.", fromNode.getOutputFboConnection(outputId), toNode);
}
public void reconnectFbo(Node fromNode, int outputId, Node toNode, int inputId) {
@ -339,7 +339,7 @@ private void connectBufferPair(Node toNode, int inputConnectionId, DependencyCon
} else { // if adding new input failed, it already existed - check for connections
//TODO update
logger.info("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..",
logger.atInfo().log("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..",
toNode.getUri(), inputConnectionId, fromConnection.getName());
DependencyConnection localConnection = toNode.getInputBufferPairConnection(inputConnectionId);
// DependencyConnection localConnectionConnectedTo = localConnection.getConnectedConnections();
@ -401,7 +401,7 @@ public void connectBufferPair(Node fromNode, int outputId, Node toNode, int inpu
// if (!areConnected(fromNode, toNode)) {
// connect(fromNode, toNode);
// }
logger.debug("Connected {} to {}.", fromNode.getOutputBufferPairConnection(outputId), toNode);
logger.atDebug().log("Connected {} to {}.", fromNode.getOutputBufferPairConnection(outputId), toNode);
}
/**
@ -529,12 +529,12 @@ public void reconnectInputToOutput(String fromNodeUri, int outputId, Node toNode
*/
private void reconnectInputToOutput(Node toNode, int inputId, DependencyConnection fromConnection,
ConnectionType connectionType, boolean disconnectPrevious) {
logger.debug("Attempting reconnection of {} to {}'s output.", toNode.getUri(), fromConnection.getParentNode());
logger.debug("Attempting reconnection of {} to {}'s output.", toNode.getUri(), fromConnection.getParentNode()); //NOPMD
Node fromNode;
fromNode = findNode(fromConnection.getParentNode());
if (!fromConnection.getConnectedConnections().isEmpty()) {
logger.warn("WARNING: destination connection ({}) is already connected to ({})",
logger.atWarn().log("WARNING: destination connection ({}) is already connected to ({})",
fromConnection, fromConnection.getConnectedConnections());
// TODO update the hashmap to string to be pretty
// throw new RuntimeException("Could not reconnect, destination connection (" + fromConnection + ") is already connected to ("

View file

@ -42,6 +42,7 @@ public RenderTaskListGenerator() {
taskList = Lists.newArrayList();
}
@SuppressWarnings("PMD.GuardLogStatement")
private void logIntermediateRendererListForDebugging(List<Node> orderedNodes) {
for (Node node : orderedNodes) {
@ -166,17 +167,17 @@ public List<RenderPipelineTask> generateFrom(List<Node> orderedNodes) {
long endTimeInNanoSeconds = System.nanoTime();
// if (logger.isDebugEnabled()) {
if (logger.isDebugEnabled()) {
logger.debug("===== INTERMEDIATE RENDERER LIST =========================");
logIntermediateRendererListForDebugging(orderedNodes);
logger.debug("===== RENDERER TASK LIST =================================");
logList(taskList);
logger.debug("----------------------------------------------------------");
logger.debug("Task list generated in {} ms", String.format("%.3f", (endTimeInNanoSeconds - startTimeInNanoSeconds) / 1000000f));
logger.debug("{} nodes, {} enabled - {} tasks (excluding marker tasks) out of {} potential tasks.",
nodeList.size(), enabledNodes, taskList.size() - enabledNodes, potentialTasks);
logger.debug(String.format("Task list generated in %.3f ms", (endTimeInNanoSeconds - startTimeInNanoSeconds) / 1000000f));
logger.debug(String.format("%s nodes, %s enabled - %s tasks (excluding marker tasks) out of %s potential tasks.",
nodeList.size(), enabledNodes, taskList.size() - enabledNodes, potentialTasks));
logger.debug("----------------------------------------------------------");
// }
}
return taskList;
}

View file

@ -77,7 +77,7 @@ private void render(Iterable<EntityRef> floatingTextEntities) {
LocationComponent location = entity.getComponent(LocationComponent.class);
if (location == null) {
logger.warn("location component is not defined can't render text: {}", floatingText.text);
logger.warn("location component is not defined can't render text: {}", floatingText.text); //NOPMD
continue;
}

View file

@ -307,7 +307,7 @@ public void renderOpaque() {
boneTransform.mul(bone.getInverseBindMatrix());
boneTransforms[bone.getIndex()] = boneTransform.transpose();
} else {
logger.warn("Unable to resolve bone \"{}\"", bone.getName());
logger.warn("Unable to resolve bone \"{}\"", bone.getName()); //NOPMD
boneTransforms[bone.getIndex()] = new Matrix4f();
}
}

View file

@ -47,7 +47,7 @@ public void apply(AssetDataFile input, UIData assetData) throws IOException {
if (skin.isPresent()) {
assetData.getRootWidget().setSkin(skin.get());
} else {
logger.warn("Failed to load skin {} for the delta file {}", skinUri, input.getFilename());
logger.atWarn().log("Failed to load skin {} for the delta file {}", skinUri, input.getFilename());
}
}
}

View file

@ -175,7 +175,7 @@ public UIWidget deserialize(JsonElement json, Type typeOfT, JsonDeserializationC
if (id != null) {
FieldMetadata<?, ?> fieldMetadata = elementMetadata.getField(ID_FIELD);
if (fieldMetadata == null) {
logger.warn("UIWidget type {} lacks id field", elementMetadata.getId());
logger.warn("UIWidget type {} lacks id field", elementMetadata.getId()); //NOPMD
} else {
fieldMetadata.setValue(element, id);
}
@ -218,7 +218,7 @@ public UIWidget deserialize(JsonElement json, Type typeOfT, JsonDeserializationC
field.setValue(element, context.deserialize(jsonObject.get(field.getSerializationName()), field.getType()));
}
} catch (RuntimeException e) {
logger.error("Failed to deserialize field {} of {}", field.getName(), type, e);
logger.error("Failed to deserialize field {} of {}", field.getName(), type, e); //NOPMD
}
}
}

View file

@ -259,7 +259,7 @@ private void populateContextMenu(JsonTree node, MenuTree addTree, boolean isSkin
}
}
} else {
logger.warn("Could not get class for node {}", node.getValue());
logger.warn("Could not get class for node {}", node.getValue()); //NOPMD
}
}

View file

@ -365,7 +365,7 @@ public <T extends CoreScreenLayer> T createScreen(ResourceUrn screenUri, Class<T
}
return screen;
} else {
logger.error("Screen '{}' is a '{}' and not a '{}'", screenUri, root.getClass(), expectedType);
logger.error("Screen '{}' is a '{}' and not a '{}'", screenUri, root.getClass(), expectedType); //NOPMD
}
}
return null;
@ -490,7 +490,7 @@ public <T extends ControlWidget> T addOverlay(ResourceUrn overlayUri, Class<T> e
addOverlay(overlay, overlayUri);
return overlay;
} else {
logger.error("Screen '{}' is a '{}' and not a '{}'", overlayUri, root.getClass(), expectedType);
logger.error("Screen '{}' is a '{}' and not a '{}'", overlayUri, root.getClass(), expectedType); //NOPMD
}
}
return null;

View file

@ -26,7 +26,9 @@
import org.terasology.gestalt.module.Module;
import org.terasology.gestalt.module.ModuleMetadata;
import org.terasology.gestalt.module.dependencyresolution.DependencyInfo;
import org.terasology.gestalt.naming.Name;
import org.terasology.gestalt.naming.NameVersion;
import org.terasology.gestalt.naming.Version;
import org.terasology.nui.Canvas;
import org.terasology.nui.databinding.Binding;
import org.terasology.nui.databinding.ReadOnlyBinding;
@ -350,22 +352,24 @@ private void loadGameModules() {
final List<ModuleSelectionInfo> sortedGameModules = gameInfo.getManifest().getModules().stream()
.sorted(Comparator.comparing(NameVersion::getName))
.map(nameVersion -> {
Module module = moduleManager.getRegistry().getModule(nameVersion.getName(), nameVersion.getVersion());
Name name = nameVersion.getName();
Version version = nameVersion.getVersion();
Module module = moduleManager.getRegistry().getModule(name, version);
if (module != null) {
return ModuleSelectionInfo.strictVersion(module);
} else {
logger.warn("Can't find module in your classpath - {}:{}", nameVersion.getName(), nameVersion.getVersion());
module = moduleManager.getRegistry().getLatestModuleVersion(nameVersion.getName());
logger.warn("Can't find module in your classpath - {}:{}", name, version);
module = moduleManager.getRegistry().getLatestModuleVersion(name);
if (module != null) {
logger.debug("Get the latest available version of module {} in your classpath", nameVersion.getName());
logger.debug("Get the latest available version of module {} in your classpath", name);
errors.add(String.format("Can't find module %s:%s in your classpath; " +
"loaded description for the latest available version.",
nameVersion.getName(), nameVersion.getVersion()));
name, version));
return ModuleSelectionInfo.latestVersion(module);
}
logger.error("Can't find any versions of module {} in your classpath!", nameVersion.getName());
errors.add(String.format("Can't find any versions of module %s in your classpath!", nameVersion.getName()));
return ModuleSelectionInfo.unavailableVersion(nameVersion.getName().toString(), nameVersion.getVersion().toString());
logger.error("Can't find any versions of module {} in your classpath!", name);
errors.add(String.format("Can't find any versions of module %s in your classpath!", name));
return ModuleSelectionInfo.unavailableVersion(name.toString(), version.toString());
}
})
.filter(Objects::nonNull)

View file

@ -355,7 +355,7 @@ public boolean onKeyEvent(NUIKeyEvent event) {
}
public void saveSettings() {
logger.info("Video Settings: {}", config.renderConfigAsJson(config.getRendering()));
logger.info("Video Settings: {}", config.renderConfigAsJson(config.getRendering())); //NOPMD
// TODO: add a dirty flag that checks if recompiling is needed
CoreRegistry.get(ShaderManager.class).recompileAllShaders();
triggerBackAnimation();

View file

@ -145,7 +145,7 @@ public void apply(UISkinBuilder builder) {
builder.setElementClass(metadata.getType());
entry.getValue().apply(builder);
} else {
logger.warn("Failed to resolve UIWidget class {}, skipping style information", entry.getKey());
logger.atWarn().log("Failed to resolve UIWidget class {}, skipping style information", entry.getKey());
}
}

View file

@ -68,7 +68,7 @@ public class UIButtonWebBrowser extends UIButton {
try {
desktop.browse(new URI(this.url));
} catch (IOException | URISyntaxException e) {
logger.warn("Can't open {} in default browser of your system.", this.url);
logger.warn("Can't open {} in default browser of your system.", this.url); //NOPMD
showErrorPopup("Can't open " + this.url + " in default browser of your system.");
}
} else {
@ -83,7 +83,7 @@ public class UIButtonWebBrowser extends UIButton {
runtime.exec(createCommand("xdg-open", this.url));
}
} catch (IOException e) {
logger.warn("Can't recognize your OS and open the url {}.", this.url);
logger.warn("Can't recognize your OS and open the url {}.", this.url); //NOPMD
showErrorPopup("Can't recognize your OS and open the url " + this.url);
}
}
@ -125,7 +125,7 @@ private void showConfirmationPopup() {
confirmUrlPopup.setCheckbox(webBrowserConfig, this.url);
}
} catch (MalformedURLException e) {
logger.error("{} is malformed", this.url, e);
logger.error("{} is malformed", this.url, e); //NOPMD
}
}

View file

@ -192,8 +192,8 @@ private void populateConstructorParameters(Binding<T> binding,
library.getBaseTypeWidget((Binding) argumentBinding, parameterType);
if (!optionalWidget.isPresent()) {
LOGGER.warn("Could not create widget for parameter of type {} of constructor {}",
parameter, selectedConstructor.get());
LOGGER.atWarn().log("Could not create widget for parameter of type {} of constructor {}",
parameter, selectedConstructor.get());
continue;
}

View file

@ -147,7 +147,7 @@ protected void onSet() {
.orElse(baseTypeWidgetBuilder);
if (builder == null) {
LOGGER.error("Could not find widget for type {}, editing as base type {}", get(), baseType);
LOGGER.atError().log("Could not find widget for type {}, editing as base type {}", get(), baseType);
return;
}

View file

@ -156,7 +156,7 @@ public final void doReload(MaterialData data) {
rebindVariables(data);
});
} catch (InterruptedException e) {
logger.error("Failed to reload {}", getUrn(), e);
logger.error("Failed to reload {}", getUrn(), e); //NOPMD
}
}
@ -228,7 +228,7 @@ public void activateFeature(ShaderProgramFeature feature) {
activeFeaturesMask = ShaderProgramFeature.getBitset(activeFeatures);
activeFeaturesChanged = true;
} else {
logger.error("Attempt to activate unsupported feature {} for material {} using shader {}", feature, getUrn(), shader.getUrn());
logger.error("Attempt to activate unsupported feature {} for material {} using shader {}", feature, getUrn(), shader.getUrn()); //NOPMD
}
}

View file

@ -278,7 +278,7 @@ private void registerAllShaderPermutations() {
disposalAction.vertexPrograms.put(featureHash, vertShaderId);
}
logger.debug("Compiled {} permutations for {}.", allPermutations.size(), getUrn());
logger.debug("Compiled {} permutations for {}.", allPermutations.size(), getUrn()); //NOPMD
}
private String assembleShader(int type, Set<ShaderProgramFeature> features) {
@ -364,7 +364,7 @@ private int compileShader(int type, Set<ShaderProgramFeature> features) {
protected void doReload(ShaderData data) {
try {
GameThread.synch(() -> {
logger.debug("Recompiling shader {}.", getUrn());
logger.debug("Recompiling shader {}.", getUrn()); //NOPMD
disposalAction.disposeData();
shaderProgramBase = data;
@ -376,11 +376,11 @@ protected void doReload(ShaderData data) {
try {
registerAllShaderPermutations();
} catch (RuntimeException e) {
logger.warn("{}", e.getMessage());
logger.warn("{}", e.getMessage()); //NOPMD
}
});
} catch (InterruptedException e) {
logger.error("Failed to reload {}", getUrn(), e);
logger.error("Failed to reload {}", getUrn(), e); //NOPMD
}
}

View file

@ -54,7 +54,7 @@ protected void doReload(MeshData newData) {
try {
GameThread.synch(() -> buildMesh(newData));
} catch (InterruptedException e) {
logger.error("Failed to reload {}", getUrn(), e);
logger.error("Failed to reload {}", getUrn(), e); //NOPMD
}
}
@ -86,7 +86,7 @@ public void render() {
}
GL30.glBindVertexArray(0);
} else {
logger.error("Attempted to render disposed mesh: {}", getUrn());
logger.error("Attempted to render disposed mesh: {}", getUrn()); //NOPMD
}
}

View file

@ -112,7 +112,7 @@ protected void doReload(SkeletalMeshData newData) {
GL30.glBindVertexArray(0);
});
} catch (InterruptedException e) {
logger.error("Failed to reload {}", getUrn(), e);
logger.error("Failed to reload {}", getUrn(), e); //NOPMD
}
}

View file

@ -82,7 +82,7 @@ protected void doReload(TextureData data) {
resources.graphicsManager.disposeTexture(newId);
} else {
resources.id = newId;
logger.debug("Bound texture '{}' - {}", getUrn(), resources.id);
logger.debug("Bound texture '{}' - {}", getUrn(), resources.id); //NOPMD
}
}
});
@ -104,7 +104,7 @@ protected void doReload(TextureData data) {
resources.graphicsManager.disposeTexture(newId);
} else {
resources.id = newId;
logger.debug("Bound texture '{}' - {}", getUrn(), resources.id);
logger.debug("Bound texture '{}' - {}", getUrn(), resources.id); //NOPMD
}
}
});

View file

@ -205,7 +205,7 @@ private void initRenderingModules() {
for (ModuleRendering moduleRenderingInstance : renderingModuleRegistry.getOrderedRenderingModules()) {
if (moduleRenderingInstance.isEnabled()) {
logger.info("\nInitialising rendering class {} from {} module.\n",
logger.atInfo().log("\nInitialising rendering class {} from {} module.\n",
moduleRenderingInstance.getClass().getSimpleName(),
moduleRenderingInstance.getProvidingModule());
moduleRenderingInstance.initialise();

View file

@ -28,12 +28,12 @@ public static void logClasspath(Logger aLogger) {
Matcher asMavenCache = MAVEN_CACHE.matcher(pathEntry);
if (asGradleCache.matches()) {
if (asGradleCache.group(1).contains(interestingGroup)) {
aLogger.debug("{}gradle:{}", indent, asGradleCache.group(2));
aLogger.atDebug().log("{}gradle:{}", indent, asGradleCache.group(2));
} else {
elidedCount++;
}
} else if (asMavenCache.matches()) {
aLogger.debug("{}maven:{}", indent, asMavenCache.group(1));
aLogger.atDebug().log("{}maven:{}", indent, asMavenCache.group(1));
} else {
String place = pathEntry;
if (pathEntry.startsWith(projectRoot)) {

View file

@ -42,7 +42,7 @@ public void run() {
logger.error("Thread interrupted", e);
} catch (RuntimeException e) {
ThreadMonitor.addError(e);
logger.error("Error in thread {}", Thread.currentThread().getName(), e);
logger.error("Error in thread {}", Thread.currentThread().getName(), e); //NOPMD
} catch (Error e) {
GameThread.asynch(() -> {
throw e; // re-throw on game thread to terminate the entire application

View file

@ -37,7 +37,7 @@ public BlockFamilyLibrary(ModuleEnvironment moduleEnvironment, Context context)
for (Class<?> entry : moduleEnvironment.getTypesAnnotatedWith(RegisterBlockFamily.class)) {
if (!BlockFamily.class.isAssignableFrom(entry)) {
logger.error("Cannot load {}, must be a subclass of BlockFamily", entry.getSimpleName());
logger.error("Cannot load {}, must be a subclass of BlockFamily", entry.getSimpleName()); //NOPMD
continue;
}
RegisterBlockFamily registerInfo = entry.getAnnotation(RegisterBlockFamily.class);
@ -96,7 +96,7 @@ public <T> Optional<T> get(Class<T> type) {
return result;
} catch (Exception e) {
logger.error("Failed to load blockFamily {}", blockFamily, e);
logger.error("Failed to load blockFamily {}", blockFamily, e); //NOPMD
}
return null;
}

View file

@ -95,7 +95,7 @@ public void initialise(List<String> registeredBlockFamilies,
if (id != null) {
block.setId(id);
} else {
logger.error("Missing id for block {} in provided family {}", block.getURI(), family.get().getURI());
logger.error("Missing id for block {} in provided family {}", block.getURI(), family.get().getURI()); //NOPMD
if (generateNewIds) {
block.setId(getNextId());
} else {
@ -156,7 +156,7 @@ public void receiveFamilyRegistration(BlockUri familyUri, Map<String, Integer> r
if (id != null) {
block.setId((short) id.intValue());
} else {
logger.error("Missing id for block {} in registered family {}", block.getURI(), familyUri);
logger.error("Missing id for block {} in registered family {}", block.getURI(), familyUri); //NOPMD
block.setId(UNKNOWN_ID);
}
}
@ -189,7 +189,7 @@ protected void registerFamily(BlockFamily family) {
private void registerBlock(Block block, RegisteredState newState) {
if (block.getId() != UNKNOWN_ID) {
logger.info("Registered Block {} with id {}", block, block.getId());
logger.info("Registered Block {} with id {}", block, block.getId()); //NOPMD
newState.blocksById.put(block.getId(), block);
newState.idByUri.put(block.getURI(), block.getId());
} else {

View file

@ -90,7 +90,7 @@ public ExtraBlockDataManager(Context context) {
loggingOutput.append(first ? " " : ", ").append(entry.getKey()).append(" -> ").append(entry.getValue());
first = false;
}
logger.info(loggingOutput.toString());
logger.info("{}", loggingOutput);
}
// Find requests for extensions and which blocks they apply to.
@ -107,7 +107,7 @@ private Map<Integer, Map<String, Set<Block>>> getFieldsFromAnnotations(Context c
if (registerAnnotation != null) {
String errorType = validRegistrationMethod(method, registerAnnotation);
if (errorType != null) {
logger.error("Unable to register extra block data: {} for {}.{}: should be \"public static"
logger.atError().log("Unable to register extra block data: {} for {}.{}: should be \"public static"
+ " boolean {}(Block block)\", and bitSize should be 4, 8 or 16.",
errorType, type.getName(), method.getName(), method.getName());
continue;

View file

@ -239,7 +239,7 @@ public void update() {
processReadyChunk(chunk);
long totalProcessingTime = System.currentTimeMillis() - processingStartTime;
if (!readyChunks.isEmpty() && totalProcessingTime > UPDATE_PROCESSING_DEADLINE_MS) {
logger.warn("Chunk processing took too long this tick ({}/{}ms). {} chunks remain.", totalProcessingTime,
logger.atWarn().log("Chunk processing took too long this tick ({}/{}ms). {} chunks remain.", totalProcessingTime,
UPDATE_PROCESSING_DEADLINE_MS, readyChunks.size());
break;
}
@ -301,7 +301,7 @@ private boolean unloadChunkInternal(Vector3ic pos) {
try {
unloadRequestTaskMaster.put(new ChunkUnloadRequest(chunk, this));
} catch (InterruptedException e) {
logger.error("Failed to enqueue unload request for {}", chunk.getPosition(), e);
logger.error("Failed to enqueue unload request for {}", chunk.getPosition(), e); //NOPMD
}
return true;
@ -311,7 +311,7 @@ void gatherBlockPositionsForDeactivate(Chunk chunk) {
try {
deactivateBlocksQueue.put(createBatchBlockEventMappings(chunk));
} catch (InterruptedException e) {
logger.error("Failed to queue deactivation of blocks for {}", chunk.getPosition());
logger.error("Failed to queue deactivation of blocks for {}", chunk.getPosition()); //NOPMD
}
}

View file

@ -116,7 +116,7 @@ private void onStageDone(PositionFuture<Chunk> future, ChunkProcessingInfo chunk
chunkProcessingInfo.getChunkTaskProvider() == null
? "Generation or Loading"
: chunkProcessingInfo.getChunkTaskProvider().getName();
logger.error("ChunkTask at position {} and stage [{}] catch error: ", chunkProcessingInfo.getPosition(), stageName, e);
logger.error("ChunkTask at position {} and stage [{}] catch error: ", chunkProcessingInfo.getPosition(), stageName, e); //NOPMD
chunkProcessingInfo.getExternalFuture().setException(e);
} catch (CancellationException ignored) {
}

View file

@ -30,7 +30,7 @@ public FacetedWorldConfigurator(List<ConfigurableFacetProvider> providersList) {
for (ConfigurableFacetProvider provider : providersList) {
Component old = properties.put(provider.getConfigurationName(), provider.getConfiguration());
if (old != null) {
logger.warn("Duplicate property key: {}", provider.getConfigurationName());
logger.atWarn().log("Duplicate property key: {}", provider.getConfigurationName());
}
}
this.providers = providersList;

View file

@ -175,22 +175,24 @@ private ListMultimap<Class<? extends WorldFacet>, FacetProvider> determineProvid
ListMultimap<Class<? extends WorldFacet>, FacetProvider> result = ArrayListMultimap.create();
Set<Class<? extends WorldFacet>> facets = new LinkedHashSet<>();
for (FacetProvider provider : providersList) {
Produces produces = provider.getClass().getAnnotation(Produces.class);
Class<? extends FacetProvider> providerClass = provider.getClass();
Produces produces = providerClass.getAnnotation(Produces.class);
if (produces != null) {
facets.addAll(Arrays.asList(produces.value()));
}
Requires requires = provider.getClass().getAnnotation(Requires.class);
Requires requires = providerClass.getAnnotation(Requires.class);
if (requires != null) {
for (Facet facet : requires.value()) {
if (!facets.contains(facet.value())) {
logger.error("Facet provider for {} is missing. It is required by {}", facet.value(), provider.getClass());
Class<? extends WorldFacet> facetValue = facet.value();
if (!facets.contains(facetValue)) {
logger.error("Facet provider for {} is missing. It is required by {}", facetValue, providerClass);
throw new IllegalStateException("Missing facet provider");
}
}
}
Updates updates = provider.getClass().getAnnotation(Updates.class);
Updates updates = providerClass.getAnnotation(Updates.class);
if (updates != null) {
for (Facet facet : updates.value()) {
facets.add(facet.value());

View file

@ -71,7 +71,7 @@ public void refresh() {
}
}
} catch (Exception e) {
logger.error("Error loading world generator in module {}, skipping", module.getId(), e);
logger.error("Error loading world generator in module {}, skipping", module.getId(), e); //NOPMD
}
} else {
logger.warn("Could not resolve dependencies for module: {}", module);

View file

@ -78,7 +78,7 @@ private static Collection<FacetLayer> createLayersFor(Class<? extends WorldFacet
}
if (result.isEmpty()) {
logger.warn("No layers found for facet {}", facetClass.getName());
logger.warn("No layers found for facet {}", facetClass.getName()); //NOPMD
}
return result;