NullpointerException allthough reference is passed - nullpointerexception

Irc client which can make multiple connections to different irc servers.
Each tab represents a server connection. I want a connection closed when its tab is closed.
When i start a connection using the menuitembutton event i construct a serverConnection object, passing it to the main controller (serverConnection con) before i launch the communication method in a new thread.
Now the problem is that when onTabClose event is fired i get a nullpointerexception when i use the reference from the main controller to change a flag so that the method running in the thread will return and eventually stop instead of using the deprecated thread.stop() method. (Keep in mind that a thread using that object is already running)
Why do i get that exception when i have already passed a reference? (garbage collector can't have touched the object since it's used in the thread and main controller reference)
serverConnection class
package jircclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.function.Consumer;
public class serverConnection
{
//VARIABLES
public clientInfo client;
private String server_to_connect;
private String channel_to_connect;
private String serv_resp;
private int port;
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private ArrayList<channel> channels;
public boolean threadExitFlag = false;
//DEFAULT CONSTRUCTOR
public serverConnection() {}
//FULL CONSTRUCTOR
public serverConnection(clientInfo clientInfo, String server_to_connect, int port, String channel_to_connect) throws IOException
{
this.client = clientInfo;
this.server_to_connect = server_to_connect;
this.port = port;
this.channel_to_connect = channel_to_connect;
try
{
//Creating socket connection
this.socket = new Socket(this.server_to_connect,port);
//Socket output writer
writer = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
//Socket input writer
reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
serv_resp = null;
System.out.println("Connection established.");
}
catch(UnknownHostException exc)
{
System.out.println("ERROR: "+ exc.toString());
}
catch(IOException exc)
{
System.out.println("ERROR: "+ exc.toString());
}
finally
{
System.out.println("Closing connection.");
socket.close();
}
}
public Consumer<String> messageCallback ;
public void setMessageCallback(Consumer<String> messageCallback) {
this.messageCallback = messageCallback ;
}
//server response getter
public String getServerResponse()
{
return serv_resp;
}
public void exitThread()
{
this.threadExitFlag = true;
}
//Introduction to server and listen
public void startCommunication() throws IOException
{
//
this.socket = new Socket(this.server_to_connect,port);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
serv_resp = null;
//
writer.write("NICK " + client.getClientNickname() + "\r\n");
writer.write("USER " + client.getClientLogin() + " 0 * : " + client.getClientRealName() + "\r\n");
writer.flush();
while ((serv_resp = reader.readLine()) != null)
{
System.out.println(serv_resp);
if (messageCallback != null)
messageCallback.accept(serv_resp);
if (serv_resp.indexOf("004") >= 0)
{
break;
}
else if (serv_resp.indexOf("433") >= 0)
{
System.out.println("Nickname is already in use.");
return;
}
}
//Get channel list
writer.write("LIST \r\n");
writer.flush();
//Join desired client
writer.write("JOIN " + channel_to_connect + "\r\n");
writer.flush();
//keep listening
while ((serv_resp = reader.readLine()) != null)
{
//check if running thread should terminate
if(threadExitFlag)
{
System.out.println("THREAD FLAG POINT");
writer.write("QUIT :Bye..");
socket.close();
return;
}
if (messageCallback != null)
messageCallback.accept(serv_resp);
if (serv_resp.startsWith("PING "))
{
this.pingPong();
} else
{
System.out.println(serv_resp);
}
}
}
//Ping respond
public void pingPong() throws IOException
{
writer.write("PONG " + serv_resp.substring(5) + "\r\n");
writer.flush();
}
mainController class
package jircclient.FXML;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import jircclient.serverConnection;
public class FXMLmainController implements Initializable
{
//VARIABLES
private connectionThreadFactory connectionThreadFactory;
private ExecutorService executor;
private int tabCounter = 0;
public serverConnection con;
//CONTROLLER VARIABLES
#FXML
TextArea txt;
#FXML
TabPane tabPane;
#FXML
private void connectServerMenuButtonAction(ActionEvent event)
{
System.out.println("You clicked connectServerButtonAction!");
FXMLLoader loader = new FXMLLoader(getClass().getResource("/jircclient/FXML/FXMLserver.fxml"));
try
{
Parent root = (Parent) loader.load();
Scene scene = new Scene(root, 320, 200);
Stage stage = new Stage();
stage.setTitle("Server Info");
stage.setResizable(false);
stage.setScene(scene);
stage.show();
FXMLserverController controller = loader.getController();
controller.initData(stage, this);
}
catch (IOException ex)
{
Logger.getLogger(FXMLserverController.class.getName()).log(Level.SEVERE, null, ex);
}
}
#FXML
private void onTabCloseEvent(Event event)
{
//Event type instead of ActionEvent because the latter didnt work
//i must be able to get a reference to the serverConnection object of the associated tab
//i have to keep a list of the tab ids and the thread objects so i can set the threadExitFlag to TRUE
System.out.println("CLOSE");
System.out.println("FLAG: "+ con.threadExitFlag);
con.exitThread();
}
#Override
public void initialize(URL url, ResourceBundle rb)
{
System.out.println("Initialize in controller!");
connectionThreadFactory = new connectionThreadFactory("Server Connection");
executor = Executors.newFixedThreadPool(5, connectionThreadFactory);
}
//setters - getters
public connectionThreadFactory getConnectionThreadFactory()
{
return connectionThreadFactory;
}
public ExecutorService getExecutorService()
{
return executor;
}
public int getTabCounter()
{
return tabCounter;
}
public void setTabCounter(int tabCounter)
{
this.tabCounter = tabCounter;
}
public void increaseTabCounter()
{
tabCounter++;
}
}
serverController class - starts when connectServerMenuButtonAction is fired and opens new window-stage
package jircclient.FXML;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import jircclient.clientInfo;
import jircclient.serverConnection;
public class FXMLserverController extends AnchorPane implements Initializable
{
//PARENT VARIABLES - REFERENCES
Stage stage;
FXMLmainController parentController;
//CONTROLLER VARIABLES
#FXML
TextField ircServerField, port, nicknameField, loginField, realNameField;
#FXML
PasswordField passwordField;
public void initData(Stage stage, FXMLmainController parentController)
{
this.stage = stage;
this.parentController = parentController;
}
#Override
public void initialize(URL url, ResourceBundle rb)
{
System.out.println("serverController reporting in!");
}
#FXML
private void connectButtonAction(ActionEvent event) throws IOException
{
//get info from text fields - initialize serverConnection
clientInfo clientInfo = new clientInfo(this.realNameField.getText(), this.nicknameField.getText(), this.loginField.getText());
serverConnection serverConnection = new serverConnection(clientInfo, ircServerField.getText(), Integer.parseInt(port.getText()), "#linux");
serverConnection.setMessageCallback(message ->
Platform.runLater(() -> ((TextArea) parentController.tabPane.lookup("#txt")).appendText(message+"\n")));
//prepare thread
Thread serverThread = parentController.getConnectionThreadFactory().newThread(() -> {
try
{
serverConnection.startCommunication();
System.out.println("Terminating Thread...");
}
catch(IOException ex)
{
Logger.getLogger(FXMLmainController.class.getName()).log(Level.SEVERE, null, ex);
}
});
//add server tab
parentController.tabPane.getTabs().add(FXMLLoader.load(getClass().getResource("/jircclient/FXML/FXMLtab.fxml")));
parentController.tabPane.getTabs().get(parentController.getTabCounter()).setText(ircServerField.getText());
parentController.increaseTabCounter();
//start thread-communication
serverThread.setDaemon(true);
parentController.getExecutorService().execute(serverThread);
parentController.con = serverConnection;
System.out.println("CON IFNO"+ parentController.con.threadExitFlag);
//close window
stage.close();
}
#FXML
private void cancelButtonAction(ActionEvent event)
{
//close window
stage.close();
}
}
fxml snippet for the #onTabCloseEvent event
<Tab xmlns:fx="http://javafx.com/fxml/1" fx:controller="jircclient.FXML.FXMLmainController" onClosed="#onTabCloseEvent">
stack trace:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1762)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1645)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at com.sun.javafx.scene.control.behavior.TabPaneBehavior.canCloseTab(TabPaneBehavior.java:152)
at com.sun.javafx.scene.control.skin.TabPaneSkin$TabHeaderSkin$5.handle(TabPaneSkin.java:1291)
at com.sun.javafx.scene.control.skin.TabPaneSkin$TabHeaderSkin$5.handle(TabPaneSkin.java:1282)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3724)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3452)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1728)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2461)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:348)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:273)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:382)
at com.sun.glass.ui.View.handleMouseEvent(View.java:553)
at com.sun.glass.ui.View.notifyMouse(View.java:925)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(WinApplication.java:102)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/96639997.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1757)
... 43 more
Caused by: java.lang.NullPointerException
at jircclient.FXML.FXMLmainController.onTabCloseEvent(FXMLmainController.java:69)
... 53 more
line 69 and 70 FXMLmainController:
System.out.println("FLAG: "+ con.threadExitFlag);
con.exitThread();

Related

RedissonClient is throwing StringIndexOutOfBoundsException: begin 8, end 5, length 22

I have below code for Redis Configuration, i need to use RedissonClient to flush cache after regular intervals.Using timerTask to run flush code. CacheManager and Proxy Manager is used because it is connected to bucket4j Ratelimiting code.
Connection to Docker Redis Image is successful as well. Using redisson version 3.12.5.
Following this doc: https://www.freecodecamp.org/news/rate-limiting-with-bucket4j-and-redis/
import io.github.bucket4j.distributed.proxy.ProxyManager;
import io.github.bucket4j.grid.jcache.JCacheProxyManager;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
import lombok.extern.log4j.Log4j2;
import org.ehcache.jsr107.EhcacheCachingProvider;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.jcache.configuration.RedissonConfiguration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.utility.DockerImageName;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
#Log4j2
#Configuration
public class RedisConfig {
private static GenericContainer redis = null;
private RedissonClient redisson;
private final Timer timer = new Timer("RedisConfig", true);
private final CleanupRedis clean = new CleanupRedis(this);
public RedisConfig(){
timer.scheduleAtFixedRate(clean, SECONDS.toMillis(2), MINUTES.toMillis(2));
}
#Bean(name = "client")
public RedissonClient client() {
Config config = new Config();
if (redis == null) {
redis = new GenericContainer<>(redisImageName()).withExposedPorts(6379);
redis.start();
}
System.setProperty("spring.redis.host", redis.getHost());
System.setProperty("spring.redis.port", redis.getMappedPort(6379).toString());
config
.useSingleServer()
.setAddress("redis://" + redis.getHost() + redis.getMappedPort(6379));
RedissonClient rdson = Redisson.create(config);
return rdson;
}
#Bean
public CacheManager cacheManager(#Qualifier("client") RedissonClient redissonClient) {
Iterator<CachingProvider> iterator =
Caching.getCachingProviders(Caching.getDefaultClassLoader()).iterator();
while (iterator.hasNext()) {
CachingProvider provider = iterator.next();
if (!(provider instanceof EhcacheCachingProvider)) {
iterator.remove();
}
}
CacheManager manager = Caching.getCachingProvider().getCacheManager();
manager.createCache("cache", RedissonConfiguration.fromConfig(redissonClient.getConfig()));
return manager;
}
private static DockerImageName redisImageName() {
return DockerImageName.parse("docker.io/redis:5.0.3-alpine")
.asCompatibleSubstituteFor("redis:5.0.3-alpine");
}
#Bean
ProxyManager<String> proxyManager(CacheManager cacheManager) {
return new JCacheProxyManager<>(cacheManager.getCache("cache"));
}
protected class CleanupRedis extends TimerTask {
private RedisConfig redisConfig;
CleanupRedis(RedisConfig redisConfig) {
this.redisConfig = redisConfig;
}
#Override
public void run() {
try {
System.out.println("Redisson client call is being made");
RedissonClient redisson = Redisson.create(client().getConfig());
System.out.println("Redisson client is not working");
redisson.getKeys().flushdb();
log.debug("Successfully cleared the Redis Cache");
redisson.shutdown();
} catch (Exception e) {
log.debug("caught exception cleanup availability: {}", e.getMessage());
}
}
}
}

Refreshing RedisTemplate

I am using spring quartz job to connect to Redis to perform a operation. I have configured the RedisTemplate to connect to only the master node.
When failover happens in Redis and new master is elected I am notified via client-reconfig-script in sentinel.conf. After this I am trying to rewire my RedisTemplate to talk to the new master. This rewire part is not working.
Spring boot config for quartz job and RedisTemplate:
package com.XXX.XXX;
import org.quartz.JobDetail;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;
import de.chandre.quartz.spring.AutowiringSpringBeanJobFactory;
import de.chandre.quartz.spring.QuartzSchedulerAutoConfiguration;
#SpringBootApplication(exclude = { QuartzSchedulerAutoConfiguration.class })
public class OrderProcessorApplication {
public static void main(String[] args) {
SpringApplication.run(OrderProcessorApplication.class, args);
}
#Bean
public JobDetailFactoryBean jobDetail() {
JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
jobDetailFactory.setJobClass(OrderProcessorJob.class);
jobDetailFactory.setDurability(true);
return jobDetailFactory;
}
#Value("${job.interval}")
private int interval;
#Bean
public SimpleTriggerFactoryBean trigger(JobDetail job) {
SimpleTriggerFactoryBean trigger = new SimpleTriggerFactoryBean();
trigger.setJobDetail(job);
trigger.setRepeatInterval(interval);
trigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
return trigger;
}
#Bean
public SchedulerFactoryBean scheduler(Trigger trigger, JobDetail job) {
SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
schedulerFactory.setConfigLocation(new ClassPathResource("quartz.properties"));
schedulerFactory.setJobFactory(springBeanJobFactory());
schedulerFactory.setJobDetails(job);
schedulerFactory.setTriggers(trigger);
return schedulerFactory;
}
#Autowired
private ApplicationContext ap;
#Bean
#Primary
public SpringBeanJobFactory springBeanJobFactory() {
AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
jobFactory.setApplicationContext(ap);
return jobFactory;
}
// #Bean
// #Qualifier("sentinel")
// public RedisTemplate<String, Object> createRedisTemplate() {
// RedisSentinelConfiguration sc = new RedisSentinelConfiguration()
// .master("redis-cluster")
// .sentinel("127.0.0.1", 26179)
// .sentinel("127.0.0.1", 26381);
//
// JedisConnectionFactory jcf = new JedisConnectionFactory(sc);
// jcf.setUsePool(true);
// jcf.afterPropertiesSet();
//
// RedisTemplate rt = new RedisTemplate();
// rt.setConnectionFactory(jcf);
// rt.afterPropertiesSet();
// return rt;
// }
#Bean
#Primary
public RedisTemplate<String, Object> createMasterOnlyRedisTemplate() {
JedisConnectionFactory jcf = new JedisConnectionFactory();
jcf.setHostName("127.0.0.1");
jcf.setPort(6379);
jcf.setUsePool(true);
jcf.afterPropertiesSet();
RedisTemplate rt = new RedisTemplate();
rt.setConnectionFactory(jcf);
rt.afterPropertiesSet();
return rt;
}
}
Refresh REST service invoked by sentinel:
package com.store.platform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.kohls.store.platform.common.model.ui.UpdateRedisMaster;
#RestController
#RequestMapping(path = "/refresh", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public class Test {
#Autowired
private RedisTemplate<String, Object> rt;
#RequestMapping(method = RequestMethod.POST)
public void refresh(#RequestBody UpdateRedisMaster um) {
JedisConnectionFactory jcf = (JedisConnectionFactory) rt.getConnectionFactory();
jcf.setHostName(um.getIp());
jcf.setPort(um.getPort());
jcf.setShardInfo(null);
jcf.afterPropertiesSet();
}
}
After successfully invoking refresh, next the quartz job tries to connect to Redis I get following exception:
org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:204) ~[spring-data-redis-1.8.4.RELEASE.jar:na]
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:348) ~[spring-data-redis-1.8.4.RELEASE.jar:na]
at org.springframework.data.redis.core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:129) ~[spring-data-redis-1.8.4.RELEASE.jar:na]
at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:92) ~[spring-data-redis-1.8.4.RELEASE.jar:na]
at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:79) ~[spring-data-redis-1.8.4.RELEASE.jar:na]
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:194) ~[spring-data-redis-1.8.4.RELEASE.jar:na]
at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:169) ~[spring-data-redis-1.8.4.RELEASE.jar:na]
at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:91) ~[spring-data-redis-1.8.4.RELEASE.jar:na]
at org.springframework.data.redis.core.DefaultValueOperations.set(DefaultValueOperations.java:182) ~[spring-data-redis-1.8.4.RELEASE.jar:na]
at com.XXX.platform.OrderProcessorJob.execute(OrderProcessorJob.java:32) ~[classes/:na]
at org.quartz.core.JobRunShell.run(JobRunShell.java:202) ~[quartz-2.3.0.jar:na]
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:573) [quartz-2.3.0.jar:na]
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool
at redis.clients.util.Pool.getResource(Pool.java:53) ~[jedis-2.9.0.jar:na]
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:226) ~[jedis-2.9.0.jar:na]
at redis.clients.jedis.JedisPool.getResource(JedisPool.java:16) ~[jedis-2.9.0.jar:na]
at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:194) ~[spring-data-redis-1.8.4.RELEASE.jar:na]
... 11 common frames omitted
Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused (Connection refused)
at redis.clients.jedis.Connection.connect(Connection.java:207) ~[jedis-2.9.0.jar:na]
at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:93) ~[jedis-2.9.0.jar:na]
at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1767) ~[jedis-2.9.0.jar:na]
at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:106) ~[jedis-2.9.0.jar:na]
at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:868) ~[commons-pool2-2.4.2.jar:2.4.2]
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:435) ~[commons-pool2-2.4.2.jar:2.4.2]
at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363) ~[commons-pool2-2.4.2.jar:2.4.2]
at redis.clients.util.Pool.getResource(Pool.java:49) ~[jedis-2.9.0.jar:na]
... 14 common frames omitted
Caused by: java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.8.0_121]
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_121]
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_121]
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_121]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_121]
at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_121]
at redis.clients.jedis.Connection.connect(Connection.java:184) ~[jedis-2.9.0.jar:na]
... 21 common frames omitted
I want to get consistent data, thats why I want to use master for read and write, and slave for redundancy and failover.
I am struck on this issue for two days. Any help is highly appreciated.
I was able to resolve my issue by creating my own RedisConnectionFactory.
public class SPRedisConnectionFactory implements InitializingBean, RedisConnectionFactory, DisposableBean {
private Jedis jedis;
private String[] nodes;
private Map<String, String[]> nodeMap;
#Value("${master.node}")
private String masterNode;
#Override
public void afterPropertiesSet() throws Exception {
nodeMap = Arrays.stream(this.nodes)
.map(n -> n.split(":"))
.collect(toMap(n -> n[0] + ":" + n[1], n -> n));
System.out.println(nodeMap);
}
#Override
public RedisConnection getConnection() {
String[] master = nodeMap.get(masterNode);
jedis = new Jedis(master[0], parseInt(master[1]), 2000);
jedis.connect();
JedisConnection c = new JedisConnection(jedis);
return c;
}
#Override
public RedisClusterConnection getClusterConnection() {
throw new UnsupportedOperationException();
}
#Override
public boolean getConvertPipelineAndTxResults() {
return false;
}
#Override
public RedisSentinelConnection getSentinelConnection() {
throw new UnsupportedOperationException();
}
#Override
public DataAccessException translateExceptionIfPossible(RuntimeException e) {
return null;
}
#Override
public void destroy() throws Exception {
jedis.disconnect();
}
}
Got this idea from Connections to multiple Redis servers with Spring Data Redis.

NullPointer with sWakeLock in my GCMIntentService when receiving notification

WI have implemented push notification in my Android App.
I send notification from my server and when a notification arrived on Androide device, i get a null pointer on my sWakeLock object.
Moreover, I never called runIntentInService because i don't how to do it !
Here is the call stack :
10-26 13:31:55.410: E/AndroidRuntime(15351): FATAL EXCEPTION: IntentService[71715548489]
10-26 13:31:55.410: E/AndroidRuntime(15351): java.lang.NullPointerException
10-26 13:31:55.410: E/AndroidRuntime(15351): at com.example.android.stackwidget.GCMIntentService.onHandleIntent(GCMIntentService.java:42)
10-26 13:31:55.410: E/AndroidRuntime(15351): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
10-26 13:31:55.410: E/AndroidRuntime(15351): at android.os.Handler.dispatchMessage(Handler.java:99)
10-26 13:31:55.410: E/AndroidRuntime(15351): at android.os.Looper.loop(Looper.java:137)
10-26 13:31:55.410: E/AndroidRuntime(15351): at android.os.HandlerThread.run(HandlerThread.java:60)
Here is also the source code of my GCMIntentService class :
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
public class GCMIntentService extends IntentService {
public GCMIntentService() {
super(Utils.GCMSenderId);
}
private static PowerManager.WakeLock sWakeLock;
private static final Object LOCK = GCMIntentService.class;
public String regIdtoSend = "";
#Override
protected void onHandleIntent(Intent intent) {
try {
String action = intent.getAction();
if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {
handleRegistration(intent);
} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(intent);
}
}
finally {
synchronized(LOCK) {
sWakeLock.release(); //Null pointer here on sWakeLock
}
}
}
private void handleRegistration(Intent intent) {
String regId = intent.getStringExtra("registration_id");
Utils.registrationId = regId;
regIdtoSend = regId;
new LongOperation().execute("");
Log.e("", "registration id : "+regId);
}
private void handleMessage(Intent intent) {
Utils.notiMsg = intent.getStringExtra("message");
Context context = getApplicationContext();
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
int icon = R.drawable.ic_action_lab_white;
CharSequence tickerText = Utils.notiMsg;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
CharSequence contentTitle = "New notification";
CharSequence contentText = Utils.notiMsg;
Intent notificationIntent = new Intent();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1, notification);
Utils.notificationReceived=true;
}
static void runIntentInService(Context context,Intent intent){
synchronized(LOCK) {
if (sWakeLock == null) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "my_wakelock");
}
}
sWakeLock.acquire();
intent.setClassName(context, GCMIntentService.class.getName());
context.startService(intent);
}
}

SQL Query to JTable NullPointerException

This runs perfectly:
package sledmonitor;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class GetList3 {
private Connection conn;
private String ConnectURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=." + File.separator + "db" + File.separator + "sledprod.mdb";
private String user = "";
private String pw = "";
String offer;
GetList3(String sql){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
conn = DriverManager.getConnection(ConnectURL, user, pw);
Statement stmt = conn.createStatement();
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
offer = rs.getString("offernumber");
System.out.println(offer);
}
rs.close();
stmt.close();
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(conn!=null){
try{
conn.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
Now I would like to show the Results in a JTable. So I make this, what normaly should work:
while(rs.next()){
offer = rs.getString("offernumber");
List.tablemodel.addRow(new String[]{offer});
}
But this somehow throws following NullPointerException:
SELECT o.offernumber, o.TotalMPL
FROM sled_offers o left join sled_changes c on o.offerguid = c.objectid
WHERE (c.nextsequencenr is null or c.nextsequencenr=99999) AND TotalMPL='0'
AND (o.offerstate=2 or o.offerstate=4 or o.offerstate=5)
java.lang.NullPointerException
at sledmonitor.GetList3.<init>(GetList3.java:28)
at sledmonitor.GetList.<init>(GetList.java:45)
at sledmonitor.Monitor$4.mouseClicked(Monitor.java:99)
at java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:270)
at java.awt.Component.processMouseEvent(Component.java:6508)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4501)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:703)
at java.awt.EventQueue.access$000(EventQueue.java:102)
at java.awt.EventQueue$3.run(EventQueue.java:662)
at java.awt.EventQueue$3.run(EventQueue.java:660)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:676)
at java.awt.EventQueue$4.run(EventQueue.java:674)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:673)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
The class List looks like this:
package sledmonitor;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class List extends JFrame {
private JPanel contentPane;
private JTable table;
static DefaultTableModel tablemodel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
List frame = new List();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public List() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
tablemodel = new DefaultTableModel();
tablemodel.addColumn("OfferNumber");
table = new JTable(tablemodel);
scrollPane.setViewportView(table);
}
}
Any idea?
You seem to be accessing the static field List.tablemodel without instanciating first the List object, so you aren't calling List() which doesn't instanciate your tablemodel object.
You should then use a static constructor:
static {
tablemodel = new DefaultTableModel();
tablemodel.addColumn("OfferNumber");
}
And remove those 2 lines of code from the List() constructor.
use this
DefaultTableModel myData = new DefaultTableModel();
JTable table = new JTable(myData);
// initialize the table with model type constructor
while(rs.next()){
String offer = rs.getString("offernumber");
Object [] rowData=new Object[]{offer,null};
myData.addRow(rowData);
}
//use addRow(Object[] rowData) method of defaulttablemodel class

Is there any way to configure jms transport for axis2 client programatically?

I know how to configure jms transport within axis2.xml, but i need to configure it with my specific application properties that could be changed in runtime.
I found solution, hope it will be helpful
package com.mycompany.client.config;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import javax.naming.Context;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNode;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.description.Parameter;
import org.apache.axis2.description.ParameterInclude;
import org.apache.axis2.description.TransportInDescription;
import org.apache.axis2.description.TransportOutDescription;
import org.apache.axis2.engine.AxisConfiguration;
import org.apache.axis2.transport.TransportListener;
import org.apache.axis2.transport.TransportSender;
import org.apache.axis2.transport.jms.JMSConstants;
import org.apache.axis2.transport.jms.JMSListener;
import org.apache.axis2.transport.jms.JMSSender;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.mycompany.client.config.exceptions.ConfigurationException;
import com.mycompany.client.jms.JMSWebServiceClient;
import com.mycompany.stub.FtthRequestStub;
public class ConfigurationManager {
static Log log = LogFactory.getLog(ConfigurationManager.class);
private static final String DEFAULT_TRANSPORT_PARAMETER_NAME = "default";
public JMSWebServiceClient configureJMSClient() throws Exception {
FtthRequestStub stub;
ConfigurationContext ctx;
boolean isAuthenticationEnabled = false;
Map<String,String> jmsTransportProps = getAxisTransportConfiguration(isAuthenticationEnabled);
String url = buildUrlFromMap(jmsTransportProps);
ctx = ConfigurationContextFactory.createDefaultConfigurationContext();
//transport in
TransportListener tl = new JMSListener();
TransportInDescription transportIn = new TransportInDescription("jms");
addParameterToTransport(jmsTransportProps,transportIn);
transportIn.setReceiver(tl);
// transport out
TransportSender transportSender = new JMSSender();
TransportOutDescription transportOut = new TransportOutDescription("jms");
addParameterToTransport(jmsTransportProps, transportOut);
transportOut.setSender(transportSender);
transportSender.init(ctx, transportOut); //very important call because transport senders are not initialized during createDefaultConfigurationContext() invocation.
AxisConfiguration axisConfiguration = ctx.getAxisConfiguration();
axisConfiguration.addTransportIn(transportIn);
axisConfiguration.addTransportOut(transportOut);
stub = new FtthRequestStub(ctx,url);
String replyTo = getReplyDestination();
if(StringUtils.isNotEmpty(replyTo)) {
stub._getServiceClient().getServiceContext().setProperty(JMSConstants.JMS_REPLY_TO, replyTo);
}
JMSWebServiceClient client = new JMSWebServiceClient(stub);
return client;
}
private void addParameterToTransport(Map<String,String> jmsTransportProps,
ParameterInclude transportInOut) throws ConfigurationException {
try {
Parameter parameter = new Parameter();
parameter.setName(DEFAULT_TRANSPORT_PARAMETER_NAME);
parameter.setValue(buildParameterOMElementFromMap(DEFAULT_TRANSPORT_PARAMETER_NAME, jmsTransportProps, false));
transportInOut.addParameter(parameter);
} catch (AxisFault e) {
throw new ConfigurationException(e.getMessage());
}
}
private static OMElement createRootParameterOMElement(String name) {
OMFactory omFactory = OMAbstractFactory.getOMFactory();
OMElement defaultReceiverParameter = omFactory.createOMElement(new javax.xml.namespace.QName("parameter"));
OMAttribute nameAttribute = omFactory.createOMAttribute("name", null, name);
defaultReceiverParameter.addAttribute(nameAttribute);
return defaultReceiverParameter;
}
private static OMElement buildParameterOMElementFromMap(String rootElementName, Map<String,String> properties, boolean rootIsLocked) {
OMFactory omFactory = OMAbstractFactory.getOMFactory();
//creating root <parameter>
OMElement root = omFactory.createOMElement(new javax.xml.namespace.QName("parameter"));
OMAttribute attribute = omFactory.createOMAttribute("name", null, rootElementName);
root.addAttribute(attribute);
attribute = omFactory.createOMAttribute("locked", null, String.valueOf(rootIsLocked));
root.addAttribute(attribute);
//creating child <parameter> elements
for(String key : properties.keySet())
{
OMElement child = omFactory.createOMElement(new javax.xml.namespace.QName("parameter"));
attribute = omFactory.createOMAttribute("name", null, key);
child.addAttribute(attribute);
attribute = omFactory.createOMAttribute("locked", null, Boolean.FALSE.toString());
child.addAttribute(attribute);
OMNode text = omFactory.createOMText(properties.get(key));
child.addChild(text);
root.addChild(child);
}
return root;
}
private static String buildUrlFromMap(Map<String,String> properties) {
StringBuffer url = new StringBuffer();
url.append(JMSConstants.JMS_PREFIX);
url.append(getDestination()).append("?"); //send destination
for(String key : properties.keySet()) {
url.append(key).append("=").append(properties.get(key)).append("&");
}
return StringUtils.chop(url.toString());
}
private static String getDestination() {
return "testQueue";
}
private static String getReplyDestination() {
return "replyQueue";
}
private Map<String,String> getAxisTransportConfiguration(boolean authenticationEnabled) {
Map<String,String> properties = new HashMap<String,String>();
properties.put(JMSConstants.PARAM_CONFAC_JNDI_NAME, "QueueConnectionFactory");
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
properties.put(Context.PROVIDER_URL, "tcp://localhost:61616");
if(authenticationEnabled) {
properties.put(JMSConstants.PARAM_JMS_USERNAME, "username");
properties.put(JMSConstants.PARAM_JMS_PASSWORD, "password");
}
return properties;
}
}