Minecraft One Player Per Config - java

I'm going to try to make this quick basically i'm trying to make ONE config per player.
So basically when ever I call user.CreateUser(); if the user doesn't exist it registers there own config with there unique id as the name of the yml
My problem is that when ever I try to call user.CreateUser(); on the PlayerJoinEvent it shows a error and i'm not sure the UUID u shouldn't be returning null because it's inside a constructor or the other variables.
Error
[23:57:52 ERROR]: Could not pass event PlayerJoinEvent to MCEnhanced v1.0
org.bukkit.event.EventException
at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.ja
va:310) ~[spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.jav
a:62) ~[spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.j
ava:502) [spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.j
ava:487) [spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at net.minecraft.server.v1_8_R3.PlayerList.onPlayerJoin(PlayerList.java:
296) [spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at net.minecraft.server.v1_8_R3.PlayerList.a(PlayerList.java:156) [spigo
t-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at net.minecraft.server.v1_8_R3.LoginListener.b(LoginListener.java:144)
[spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at net.minecraft.server.v1_8_R3.LoginListener.c(LoginListener.java:54) [
spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at net.minecraft.server.v1_8_R3.NetworkManager.a(NetworkManager.java:231
) [spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at net.minecraft.server.v1_8_R3.ServerConnection.c(ServerConnection.java
:148) [spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:8
17) [spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:3
67) [spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:6
57) [spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java
:560) [spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_45]
Caused by: java.lang.NullPointerException
at crypted.mcenhanced.Handlers.UserDataHandler.CreateUser(UserDataHandle
r.java:46) ~[?:?]
at crypted.mcenhanced.Mechanics.ConfigMechanics.CreateUser.CreateUser(Cr
eateUser.java:19) ~[?:?]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0
_45]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0
_45]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1
.8.0_45]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_45]
at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.ja
va:306) ~[spigot-1.8.7-R0.1-SNAPSHOT-latest.jar:git-Spigot-f928e7a-e91aed8]
... 14 more
CreateUser Listener Class
public class CreateUser implements Listener {
#EventHandler
public void CreateUser(PlayerJoinEvent event){
Player player = event.getPlayer();
UserDataHandler user = new UserDataHandler(player.getUniqueId());
user.CreateUser();
}
}
UserDataHandler Class
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.event.Listener;
import java.io.File;
import java.util.UUID;
public class UserDataHandler implements Listener {
UUID u;
File UserFile;
FileConfiguration UserConfig;
//UserDataHandler user = new UserDataHandler(player.getUniqueId()); // Make sure that you have the player.getUniqueId()
public UserDataHandler(UUID u){
this.u = u;
File UserFile = new File("plugins/MCEnhanced/data/" + u + ".yml");
YamlConfiguration UserConfig = YamlConfiguration.loadConfiguration(UserFile);
}
public void CreateUser(){
if ( !(UserFile.exists()) ) {
try {
//Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[MCEnhanced] Created a new File for " + player.getName() + "(" + player.getUniqueId() + ")");
YamlConfiguration UserConfig = YamlConfiguration.loadConfiguration(UserFile);
UserConfig.save(UserFile);
} catch (Exception e) {
e.printStackTrace();
// Bukkit.getConsoleSender().sendMessage(ChatColor.RED + "[MCEnhanced] Could not create a new File for " + player.getName() + "(" + player.getUniqueId() + ")");
//u.kickPlayer(ChatColor.RED + "We could not create a file for your account!"); // THE PLAYERS CONFIG NEEDS TO BE CREATED!!!!!!!!
}
}
}
public FileConfiguration getUserFile(){
return UserConfig;
}
public void setDefaultUserFile(){
getUserFile().set("MCEnhanced.Info.IsInfected", false);
}
public void saveUserFile(){
try {
getUserFile().save(UserFile);
} catch(Exception e) {
e.printStackTrace();
}
}
}

In the CreateUser method, you are referencing the UserFile field or instance variable of the current UserDataHandler object which is by default null. Your constructor for the UserDataHandler class does not instantiate this UserFile field and instead creates a local File variable inside that constructor which is then never used. The line...
File UserFile = new File("plugins/MCEnhanced/data/" + u + ".yml");
should be...
UserFile = new File("plugins/MCEnhanced/data/" + u + ".yml");
so that the File field is instantiated for that instance.
I would recommend using the lowerCamelCase naming convention to name your variables, fields and methods as well.

Related

Including Python Script in Spring Boot Application with Jython fails - module not found

I am trying to get used to python+java interaction and so I wrote a little python-script that I wanted to execute that script from my Spring Boot Application. That script is located in the (relative from the .java-file) path /scripts_py/getStockPrice.py that contains the getStockPrice-method (see code below). So I integrated jython and tried to execute the following CronJob:
#Component
public class CronService {
private PythonScriptSingleton pss = PythonScriptSingleton.getInstance();
private final Logger logger = LoggerFactory.getLogger(CronService.class);
//call every 5 sec
#Scheduled(fixedRate = 5000)
public void initStockPriceAPICall() {
this.getStockPrice("NFLX");
}
public void getStockPrice(String ticker) {
String result = (String) (Object) this.pss.getFunc_getPriceForTicker().__call__(new PyString(ticker));
try {
logger.info("Price is " + result);
} catch (NullPointerException e) {
logger.info("Catched NPE");
}
}
}
The PythongScriptSingleton (the idea was, that I probably need to execute that script a lot of times - so I tried to go for a singleton instance of this class that holds the script so I do not need to recompile it every time:
public class PythonScriptSingleton {
private static PythonScriptSingleton ps;
public static PythonScriptSingleton getInstance() {
if (ps == null) {
ps = new PythonScriptSingleton();
ps.initScript();
}
return ps;
}
private PyObject func_getPriceForTicker;
private PythonScriptSingleton() {
}
private void initScript() {
PythonInterpreter interpreter = new PythonInterpreter();
String fileUrlPath = "/scripts_py";
String scriptName = "getStockPrice.py";
interpreter.exec("import sys\n" + "import os \n" + "sys.path.append('" + fileUrlPath + "')\n" + "from "
+ scriptName + " import * \n");
String funcName = "getStockPrice";
PyObject someFunc = interpreter.get(funcName);
this.func_getPriceForTicker = someFunc;
interpreter.close();
}
public PyObject getFunc_getPriceForTicker() {
return func_getPriceForTicker;
}
}
The Python Script:
from yahoo_fin import stock_info as si
def getStockPrice(ticker):
price = si.get_live_price(ticker)
return price
I am using the embedded tomcat with Spring Boot (executable JAR-File) and jython-standalone 2.7.2:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.2</version>
</dependency>
The error i keep running into says, that the script is not defined - I tried defining it with and without the file ending (.py), both did not change anything:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.fr.stockticker.pythoninteraction.CronService]: Constructor threw exception; nested exception is Traceback (most recent call last):
File "<string>", line 4, in <module>
ImportError: No module named getStockPrice
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:217) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:87) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1312) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
... 81 common frames omitted
Caused by: org.python.core.PyException: ImportError: No module named getStockPrice
at org.python.core.Py.ImportError(Py.java:329) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.import_first(imp.java:1230) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.import_module_level(imp.java:1361) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.importName(imp.java:1528) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.ImportFunction.__call__(__builtin__.java:1285) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.PyObject.__call__(PyObject.java:433) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.__builtin__.__import__(__builtin__.java:1232) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.imp.importAll(imp.java:1647) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.pycode._pyx0.f$0(<string>:4) ~[na:na]
at org.python.pycode._pyx0.call_function(<string>) ~[na:na]
at org.python.core.PyTableCode.call(PyTableCode.java:173) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.PyCode.call(PyCode.java:18) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.Py.runCode(Py.java:1687) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.core.Py.exec(Py.java:1731) ~[jython-standalone-2.7.2.jar:2.7.2]
at org.python.util.PythonInterpreter.exec(PythonInterpreter.java:268) ~[jython-standalone-2.7.2.jar:2.7.2]
at de.fr.stockticker.pythoninteraction.PythonScriptSingleton.initScript(PythonScriptSingleton.java:28) ~[classes/:na]
at de.fr.stockticker.pythoninteraction.PythonScriptSingleton.getInstance(PythonScriptSingleton.java:13) ~[classes/:na]
at de.fr.stockticker.pythoninteraction.CronService.<init>(CronService.java:12) ~[classes/:na]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_251]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_251]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_251]
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_251]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:204) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
... 83 common frames omitted
I was able to run your program partially using Jython - I couldn't get the stock process from yahoo which is internally depends on numpy and looks like Jython doesn't support numpy as it being cpython library.
private void initScript() {
PythonInterpreter interpreter = new PythonInterpreter();
String fileUrlPath = "/users/sagar/demo/src/main/resources/python";
interpreter.exec("import sys");
interpreter.exec("sys.path.append('" + fileUrlPath + "')");
interpreter.exec("from getStockPrice import *"); this.func_getPriceForTicker =
interpreter.get("getStockPrice", PyFunction.class);
interpreter.close();
}
You will be able to get past your error but you will see error
Missing required dependencies ['numpy']
So I tried using another java python library jep and made changes as follow
#SpringBootApplication
#EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
private final Logger logger = LoggerFactory.getLogger(DemoApplication.class);
//call every 5 sec
#Scheduled(fixedRate = 5000)
public void initStockPriceAPICall() throws JepException {
this.getStockPrice("NFLX");
}
private void getStockPrice(String ticker) throws JepException {
try (Interpreter interp = new SharedInterpreter()) {
String fileUrlPath = "/users/sagar/demo/src/main/resources/python";
interp.exec("import sys");
interp.exec("sys.path.append('" + fileUrlPath + "')");
interp.exec("from getStockPrice import *");
interp.set("ticker", ticker);
interp.exec("price = getStockPrice(ticker)");
Object result = interp.getValue("price");
logger.info("Price is " + result);
}
}
}
pom.xml
<dependency>
<groupId>black.ninia</groupId>
<artifactId>jep</artifactId>
<version>3.9.0</version>
</dependency>
Make sure to install jep module - it has native library
pip install jeb
Add java library path to load native library
-Djava.library.path=/usr/local/lib/python2.7/site-packages/jep
Reference - https://github.com/ninia/jep/wiki/Getting-Started

Bukkit - NPE using VaultAPI (Chat)

When trying to set the player suffix/prefix from the GUI I am getting a null pointer exception for setting the said prefix/suffix. (I get the 'You applied the x tag' message, and it does close the inventory.)
Main class (Where the chat is defined and setup, not the entire class)
public static Chat chat = null;
#SuppressWarnings("unused")
private TagsCommands tCmd;
public void onEnable() {
if (Bukkit.getPluginManager().getPlugin("Vault") != null) {
setupChat();
createFolders();
Message.console("&fPlugin successfully loaded");
Bukkit.getPluginManager().registerEvents(new TagsGUI(), this);
tCmd = new TagsCommands(this);
} else {
Message.console("&dCouldn't enable plugin as &aVault&c was not found");
Bukkit.getPluginManager().disablePlugin(this);
return;
}
}
private boolean setupChat() {
RegisteredServiceProvider<Chat> chatProvider = getServer().getServicesManager()
.getRegistration(net.milkbowl.vault.chat.Chat.class);
if (chatProvider != null) {
chat = chatProvider.getProvider();
}
return (chat != null);
}
GUI class (Again, not the entire thing. The error lies in this class at line 55.)
#EventHandler
public void inventoryClick(InventoryClickEvent event) {
Player player = (Player) event.getWhoClicked();
ItemStack click = event.getCurrentItem();
if (opened.contains(player)) {
event.setCancelled(true);
File tags = new File("plugins/Tags/Pages", "One.yml");
FileConfiguration tagsC = YamlConfiguration.loadConfiguration(tags);
for (String title : tagsC.getConfigurationSection("Tags").getKeys(false)) {
String tag = tagsC.getString("Tags." + title + ".Display");
if (click.getItemMeta().getDisplayName().equals(Format.color(tag))) {
if (player.hasPermission(tagsC.getString("Tags." + title + ".Permission"))) {
if (tagsC.getString("Tags." + title + ".Type").equalsIgnoreCase("prefix")) {
player.closeInventory();
Message.player("&fYou applied the '" + tag + "&f' tag", player);
Main.chat.setPlayerPrefix(player, Format.color(tag));
break;
} else if (tagsC.getString("Tags." + title + ".Type").equalsIgnoreCase("suffix")) {
player.closeInventory();
Message.player("&fYou applied the '" + tag + "&f' tag", player);
Main.chat.setPlayerSuffix(player, Format.color(tag));
break;
}
} else {
Message.player("&fSorry, but you do not have permission to do this", player);
break;
}
}
}
return;
}
}
Line 55:
Main.chat.setPlayerSuffix(player, Format.color(tag));
Console error message:
[11:13:05 INFO]: BearToothh issued server command: /tags
[11:13:12 ERROR]: Could not pass event InventoryClickEvent to Tags v1.0
org.bukkit.event.EventException: null
at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:306) ~[spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at org.bukkit.plugin.RegisteredListener.callEvent(RegisteredListener.java:62) ~[spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at org.bukkit.plugin.SimplePluginManager.fireEvent(SimplePluginManager.java:500) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at org.bukkit.plugin.SimplePluginManager.callEvent(SimplePluginManager.java:485) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at net.minecraft.server.v1_12_R1.PlayerConnection.a(PlayerConnection.java:1889) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at net.minecraft.server.v1_12_R1.PacketPlayInWindowClick.a(SourceFile:33) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at net.minecraft.server.v1_12_R1.PacketPlayInWindowClick.a(SourceFile:10) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at net.minecraft.server.v1_12_R1.PlayerConnectionUtils$1.run(SourceFile:13) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [?:?]
at java.util.concurrent.FutureTask.run(Unknown Source) [?:?]
at net.minecraft.server.v1_12_R1.SystemUtils.a(SourceFile:46) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at net.minecraft.server.v1_12_R1.MinecraftServer.D(MinecraftServer.java:748) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at net.minecraft.server.v1_12_R1.DedicatedServer.D(DedicatedServer.java:406) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at net.minecraft.server.v1_12_R1.MinecraftServer.C(MinecraftServer.java:679) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:577) [spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
at java.lang.Thread.run(Unknown Source) [?:?]
Caused by: java.lang.NullPointerException
at me.askingg.tags.TagsGUI.inventoryClick(TagsGUI.java:55) ~[?:?]
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?]
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:?]
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:?]
at java.lang.reflect.Method.invoke(Unknown Source) ~[?:?]
at org.bukkit.plugin.java.JavaPluginLoader$1.execute(JavaPluginLoader.java:302) ~[spigot-1.12.2.jar:git-Spigot-2cf50f0-2b93d83]
... 15 more
public static Chat chat = null; is null so it returns a NullPointerException.
You cannot define a chat thats null and set prefixes and stuff on a chat that dont exist ^^
You have to define the Chat chat variable to an existing chat.

Error "Exception in thread "main" java.lang.ExceptionInInitializerError" while working with log4j

Error is :
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.agile.pc.cmserver.base.CMLogger.setLogClass(CMLogger.java:39)
at com.agile.util.log.CMLogFactory.getLogger(CMLogFactory.java:77)
at com.agile.util.exception.AppException.<clinit>(AppException.java:28)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.sun.proxy.$Proxy23.<clinit>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.reflect.Proxy.newProxyInstance(Unknown Source)
at com.agile.api.pc.EJBRemoteProxy.createRemoteProxy(EJBRemoteProxy.java:60)
at com.agile.api.pc.EJBLookup.getRemoteInterface(EJBLookup.java:1012)
at com.agile.api.pc.EJBLookup.getRemoteInterface(EJBLookup.java:959)
at com.agile.api.pc.EJBLookup.getChangeSession(EJBLookup.java:309)
at com.agile.api.pc.change.Change.getBean(Change.java:106)
at com.agile.api.pc.RouteObject$GetStatusAction.doSdkAction(RouteObject.java:2926)
at com.agile.api.common.SDKAction.run(SDKAction.java:23)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:368)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:163)
at weblogic.security.Security.runAs(Security.java:61)
at com.agile.api.common.WebLogicAuthenticator.doAs(WebLogicAuthenticator.java:111)
at com.agile.api.common.Security.doAs(Security.java:54)
at com.agile.api.common.Security.doAs(Security.java:109)
at com.agile.api.pc.RouteObject.getStatus(RouteObject.java:1206)
at com.gehc.extensions.px.CreateChildSCN.doAction(CreateChildSCN.java:39)
at com.gehc.extensions.px.CreateChildSCN.main(CreateChildSCN.java:124)
Caused by: java.lang.NullPointerException
at org.apache.logging.log4j.util.ProviderUtil.validVersion(ProviderUtil.java:142)
at org.apache.logging.log4j.util.ProviderUtil.loadProvider(ProviderUtil.java:80)
at org.apache.logging.log4j.util.ProviderUtil.<init>(ProviderUtil.java:66)
at org.apache.logging.log4j.util.ProviderUtil.lazyInit(ProviderUtil.java:124)
at org.apache.logging.log4j.util.ProviderUtil.hasProviders(ProviderUtil.java:108)
at org.apache.logging.log4j.LogManager.<clinit>(LogManager.java:89)
... 27 more
Javafile:
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import com.agile.api.APIException;
import com.agile.api.IAgileSession;
import com.agile.api.IChange;
import com.agile.api.IDataObject;
import com.agile.api.INode;
import com.agile.px.ActionResult;
import com.agile.px.ICustomAction;
import com.gehc.common.core.CreateChildSCN_BO;
import com.gehc.common.pxconstants.GEHC_SCNConstants;
import com.gehc.common.pxutil.SDKUtil;
import com.gehc.common.pxutil.Util;
public class CreateChildSCN implements ICustomAction {
private static ResourceBundle objResourceBundle = ResourceBundle.getBundle("GEHCCreateChildSCN");
private static Logger objLogger = Logger.getLogger(CreateChildSCN.class);
public ActionResult doAction(IAgileSession aSession, INode actionNode,
IDataObject currentObject){
Util.initAppLogger(CreateChildSCN.class, Util.getLogFileName());
StringBuffer pxMessage = new StringBuffer();
try
{
IChange objChange = (IChange)currentObject;
String strChangeStatus = objChange.getStatus().toString();
IAgileSession objAgileSession = null;
String strUser = aSession.getCurrentUser().toString();
objLogger.info("Session with Logged on User..::"+aSession.getCurrentUser().toString());
objAgileSession = SDKUtil.getAgileSession(objResourceBundle
.getString("AGILE_USER"), objResourceBundle
.getString("AGILE_PASSWORD"), objResourceBundle
.getString("AGILE_URL"));
if(!(strUser.equals(objResourceBundle.getString("CURRENT_USER")))){
if(strChangeStatus.equals(objResourceBundle.getString("ECO_WORKFLOW_STATUS"))
|| strChangeStatus.equals(objResourceBundle.getString(("ECR_WORKFLOW_STATUS")))){
String suppliers = objChange.getValue(GEHC_SCNConstants.SCN_SUPPLIER_NAME).toString();
String supplierGroup = objChange.getValue(GEHC_SCNConstants.SCN_SUPPLIER_USER_GROUPS).toString();
//Checking for the suppliers presence
if("".equals(suppliers) && "".equals(supplierGroup)){
CreateChildSCN_BO objChildSCNBO = new CreateChildSCN_BO();
pxMessage.append(objChildSCNBO.createSCNs(objAgileSession, objChange));
}else{
pxMessage.append(objResourceBundle.getString("MESSAGE_ERROR_SUPPLIER_NAME_VALUE"));
objLogger.info(objResourceBundle.getString("MESSAGE_ERROR_SUPPLIER_NAME_VALUE"));
System.out.println(objResourceBundle.getString("MESSAGE_ERROR_SUPPLIER_NAME_VALUE"));
}
}else{
//System.out.println(objResourceBundle.getString("MESSAGE_ERROR_WORKFLOW_CRITERIA"));
pxMessage.append(objResourceBundle.getString("MESSAGE_ERROR_WORKFLOW_CRITERIA"));
} objLogger.info(objResourceBundle.getString("MESSAGE_ERROR_WORKFLOW_CRITERIA"));
}else{
//System.out.println(objResourceBundle.getString("MESSAGE_ERROR_INVALID_USER_LOGIN"));
pxMessage.append(objResourceBundle.getString("MESSAGE_ERROR_INVALID_USER_LOGIN"));
objLogger.info(objResourceBundle.getString("MESSAGE_ERROR_INVALID_USER_LOGIN"));
}
}catch (Exception apiEx){
apiEx.printStackTrace();
System.out.println(objResourceBundle.getString("MESSAGE_ERROR_UNABLE_TO_DO ") + apiEx);
pxMessage.append(objResourceBundle.getString("MESSAGE_ERROR_UNABLE_TO_DO"));
objLogger.error(objResourceBundle.getString("MESSAGE_ERROR_UNABLE_TO_DO"));
}
return new ActionResult(ActionResult.STRING, pxMessage.toString());
}
/**
* For Stand alone Only
* Invokes the doAction method
*/
public static void main(String[] args) {
CreateChildSCN objSCRValidation = null;
String strNumber = null;
IAgileSession objAgileSession = null;
IChange objChange = null;
ResourceBundle objResources = ResourceBundle.getBundle("GEHCCreateChildSCN");
Logger objLogger = Logger.getLogger(CreateChildSCN.class);
try {
objSCRValidation = new CreateChildSCN();
Util.initAppLogger(CreateChildSCN.class, Util.getLogFileName());
strNumber = "SCN-0043018";
// Establish session
/*objAgileSession = SDKUtil.getAgileSession(objResources
.getString("AGILE_USER"), objResources
.getString("AGILE_PASSWORD"), objResources
.getString("AGILE_URL"));*/
objAgileSession = SDKUtil.getAgileSession("xxx","xxxx","xxxxxxxxx");
System.out.println("created session");
// Load the objChange
//System.out.println(" Object:: " + objChange.getName());
objChange = (IChange) objAgileSession
.getObject(IChange.OBJECT_TYPE, strNumber);
objSCRValidation
.doAction(objAgileSession, null, objChange);
} catch (APIException e) {
System.out.println("Error log from main thread ::: " + e);
objLogger.error(objResources.getString("SESSION_FAILED") + Util.exception2String(e));
}
}
}
And also it contains properties files where we defined logger details like path and file name of log file and logger initialization like log4j.category.com.xxx.common.util.SDKUtil = debug, XLogger
Here we are using Log4.jar api initialized in classpath.
Any help here is highly appreciated.
Thanks,
Himachandra.
if you look at the code for at org.apache.logging.log4j.util.ProviderUtil.validVersion(ProviderUtil.java:142), it looks like a bug in Log4J:
private static boolean validVersion(final String version) {
for (final String v : COMPATIBLE_API_VERSIONS) {
if (version.startsWith(v)) {
return true;
}
}
return false;
}
In that library, if (version.startsWith(v)) should be if (v.startsWith(version)) since version is nullable but v is never null.
Try using a newer version of log4j that does not have this bug.
I did not see this issue in version:
2.11.2
I saw this issue in versions:
2.6.2 (java.lang.NullPointerException at org.apache.logging.log4j.util.ProviderUtil.validVersion(ProviderUtil.java:142))
2.8.2 (java.lang.NullPointerException at org.apache.logging.log4j.util.ProviderUtil.validVersion(ProviderUtil.java:142))
2.10.0 (java.lang.NoClassDefFoundError: Could not initialize class org.apache.logging.log4j.util.PropertiesUtil)
Changing the version was a quick fix for me. However, it does not fix the underlying root cause. For me, I think it was some strange interaction between junit-log4j-jmockit that allowed the version to be null. If I ran tests in a different order, I had no issue.

instance is null after renaming project

I'm working in IntelliJ and I attempted to rename my Project! After doing so, and renaming everything, which I believe I did correctly, I'm unable to actually start my application.
Error:
org.bukkit.plugin.InvalidPluginException: java.lang.NullPointerException
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:133) ~[spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at org.bukkit.plugin.SimplePluginManager.loadPlugin(SimplePluginManager.java:326) ~[spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at org.bukkit.plugin.SimplePluginManager.loadPlugins(SimplePluginManager.java:248) [spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at org.bukkit.craftbukkit.v1_12_R1.CraftServer.loadPlugins(CraftServer.java:302) [spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at net.minecraft.server.v1_12_R1.DedicatedServer.init(DedicatedServer.java:205) [spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at net.minecraft.server.v1_12_R1.MinecraftServer.run(MinecraftServer.java:544) [spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_121]
Caused by: java.lang.NullPointerException
at me.craftblock.MochaMessages.Config.<init>(Config.java:7) ~[?:?]
at me.craftblock.MochaMessages.MochaMessages.<init>(MochaMessages.java:18) ~[?:?]
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[?:1.8.0_121]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_121]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[?:1.8.0_121]
at java.lang.reflect.Constructor.newInstance(Unknown Source) ~[?:1.8.0_121]
at java.lang.Class.newInstance(Unknown Source) ~[?:1.8.0_121]
at org.bukkit.plugin.java.PluginClassLoader.<init>(PluginClassLoader.java:76) ~[spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
at org.bukkit.plugin.java.JavaPluginLoader.loadPlugin(JavaPluginLoader.java:129) ~[spigot-latest.jar:git-Spigot-4df3c0c-03f1e37]
... 6 more
The error points to my Config class, however I'm not sure why:
public class Config {
private MochaMessages instance = MochaMessages.getInstance();
private FileConfiguration config = instance.getConfig();
public Config() {
}
public String get(String node) {
System.out.println("Fetching: " + node);
return config.getString(node);
}
public void set(String node, String value) {
config.set(node, value);
}
public boolean getBoolean(String node) {
System.out.println("Fetching: " + node);
return config.getBoolean(node);
}
}
Which is being called via my MochaMessages class:
Here's the related method:
private static MochaMessages instance;
private Config config = new Config();
public void onEnable() {
instance = this;
createConfig();
te = getTokenEnchant();
if (!config.getBoolean("database.enabled")) {
disablePlugin("Enable MySQL!");
} else if (config.get("mocha.currency").equalsIgnoreCase("TokenEnchant")) {
if (te == null) {
disablePlugin("Unable to access TokenEnchant. Disabling Plugin!");
}
} else {
Bukkit.getServer().getPluginManager().registerEvents(new MochaListener(), this);
new MochaModel().createTable();
new CommandHandler();
}
}
I believe it's because instance is returning null even though it shouldn't be. This worked perfectly before the rename!
What's going on?

RuntimeException: Unexpected global[] in Drools

I'm facing a problem using Spring with Drools. My main problem is that in the unit tests do not occur the error. Follows below the exception
java.lang.RuntimeException: Unexpected global [premioService]
This error occurs when I try to set a global variable in KieSession
Seeing the method StatefulKnowledgeSessionImpl#setGlobal(String, Object) seems that I should set the
globals before create a newInstance. Follows the StatefulKnowledgeSessionImpl#setGlobal code:
public void setGlobal(final String identifier,
final Object value) {
// Cannot set null values
if ( value == null ) {
return;
}
try {
this.kBase.readLock();
startOperation();
// Make sure the global has been declared in the RuleBase
final Map globalDefintions = this.kBase.getGlobals();
final Class type = (Class) globalDefintions.get( identifier );
if ( (type == null) ) {
throw new RuntimeException( "Unexpected global [" + identifier + "]" );
} else if ( !type.isInstance( value ) ) {
throw new RuntimeException( "Illegal class for global. " + "Expected [" + type.getName() + "], " + "found [" + value.getClass().getName() + "]." );
} else {
this.globalResolver.setGlobal( identifier,
value );
}
} finally {
endOperation();
this.kBase.readUnlock();
}
}
Follows my code:
#Inject
protected PremioVisaoService premioVisaoService;
protected final KieSession createSession() {
return this.kieBase.newKieSession();
}
protected final int process() {
final KieSession kieSession = this.createSession();
Object rulesFired = 0;
try {
//here occurs the error
kieSession.execute(CommandFactory.newSetGlobal(PREMIO_SERVICE_GLOBAL_ID, premioVisaoService));
} catch(Exception e) {
e.printStackTrace();
}
}
package br.com.company.brms.model.rules;
import br.com.company.brms.model.*;
import br.com.company.brms.model.premios.*;
import br.com.company.brms.model.tarifas.*;
import function br.com.company.brms.helpers.DomainUtils.getPais;
import function br.com.company.brms.helpers.DomainUtils.getUF;
import function br.com.company.brms.helpers.PremioFactory.novoPremioVisaoPercursoPadrao;
import function br.com.company.brms.helpers.CalculoTarifaHelper.calculaTaxaBasica;
global br.com.company.brms.services.PremioVisaoService premioService;
rule "Rule Example"
ruleflow-group "calculo"
salience -1
when
$averbacao : Averbacao( indicadorAvaria == Constantes.STATUS_SIM )
$taxa : TarifaPercursoVigencia( tipoTarifa == TipoTarifa.AVARIA)
then
PremioVisaoPercursoPadrao premio = novoPremioVisaoPercursoPadrao($taxa, $averbacao);
premio.setValor( calculaTaxaBasica($taxa, $averbacao) );
//insert ( premio );
premioService.inserirPremioCalculado( premio );
//System.out.println( $averbacao + " calculada com o premio: " + premio );
end
Follows below the stacktrace:
java.lang.RuntimeException: Unexpected global [premioService]
at org.drools.core.impl.StatefulKnowledgeSessionImpl.setGlobal(StatefulKnowledgeSessionImpl.java:1124)
at org.drools.core.command.runtime.SetGlobalCommand.execute(SetGlobalCommand.java:65)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.execute(StatefulKnowledgeSessionImpl.java:665)
at org.drools.core.impl.StatefulKnowledgeSessionImpl.execute(StatefulKnowledgeSessionImpl.java:648)
at br.com.company.brms.services.impl.BilhetagemBpmnRunnerServiceImpl.processar(BilhetagemBpmnRunnerServiceImpl.java:87)
at br.com.company.brms.services.impl.BilhetagemBpmnRunnerServiceImpl.processarRegrasMercado(BilhetagemBpmnRunnerServiceImpl.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy68.processarRegrasMercado(Unknown Source)
at br.com.company.brms.services.impl.BilhetagemProcessManagerServiceImpl.processar(BilhetagemProcessManagerServiceImpl.java:111)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy69.processar(Unknown Source)
at br.com.company.brms.spi.impl.BilhetagemServiceAsyncImpl.processarPorCliente(BilhetagemServiceAsyncImpl.java:88)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.interceptor.AsyncExecutionInterceptor$1.call(AsyncExecutionInterceptor.java:95)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Tks in advance
My problem was that I were looking for the DRL files in different jars. I don't know yet how I'll do this in the right way. But the problem definitely was solved.
I finally tracked down what the root cause of this is:
If you have a rule and you want to setGlobal for that rule, you must have the global defined in that rule (the .drl file), such as;
global net.mikeski.ProviderImpl provider
Then, kSession.setGlobal("provider", myProviderImpl); will work.
I discovered this by looking at the Drools setGlobal method in StatefulKnowledgeSessionImpl.java:
...
final Class type = (Class) globalDefintions.get( identifier );
if ( (type == null) ) {
throw new RuntimeException( "Unexpected global [" + identifier + "]" );
} else if ( !type.isInstance( value ) ) {
throw new RuntimeException( "Illegal class for global. " + "Expected [" + type.getName() + "], " + "found [" + value.getClass().getName() + "]." );
} else {
this.globalResolver.setGlobal( identifier,
value );
}
...

Categories