Here is my code,why the connection not close in "doFinally":
public class TestR2DBC {
static ConnectionFactory connectionFactory = ConnectionFactories.get(
"r2dbcs:mysql://root:1234qwer#localhost:3306/testdb?useSSL=false&characterEncoding=utf-8");
public static Flux<Customer> findCustomerByAge(int age) {
Publisher<? extends Connection> conn = connectionFactory.create();
return Mono.from(conn)
.flatMap((c) -> Mono.from(c.createStatement("SELECT custno,firstname,age FROM customer WHERE age > ?")
.bind(0, age)
.execute())
.doFinally(st->c.close())
)
.flatMapMany(result -> Flux.from(result.map((row, meta) -> {
Customer cust = new Customer();
cust.setFirstname(row.get("firstname", String.class));
cust.setCustno(row.get("custno", Long.class));
cust.setAge(row.get("age",Integer.class));
return cust;
}))
.doOnNext(System.out::println))
;
}
public static void main(String[] args) throws InterruptedException {
findCustomerByAge(1).subscribe();
Thread.sleep(100000);
}
}
If i use connection pool,pool close connection automatically for us,but manually can not?
Related
i'm newbie to netbeans and doing my schoolwork
i'm trying to connect to derby database but the public static void showing error i don't know what to do here is my code:
import java.sql.;
import javax.swing.;
public class addcriminal extends javax.swing.JFrame {
public addcriminal() {
initComponents();
}
#SuppressWarnings("unchecked")
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String url="jdbc:derby://localhost:1527/criminal records ";
String username ="naim";
String password = "12345";
Connection con = DriverManager.getConnection(url,username,password);
Statement stmt = con.createStatement ();
String Query;
Query = "INSERT INTO CRIMINAL RECORDS (ID, NAME, AGE, ICNO, SEX, CRIME, PERIODS)VALUES ('"+txtno.getText()+"' , '"+txtname.getText()+"', '"+txtage.getText()+"', '"+txtic.getText()+"','"+txtic.getText()+"', '"+combosex.getSelectedItem()+"', '"+txtcrime.getText()+"', '"+txtperiods.getText()+"')";
stmt.execute(Query);
JOptionPane.showMessageDialog(null, "criminal recorded");
txtno.setText(null);
txtname.setText(null);
txtage.setText(null);
txtic.setText(null);
combosex.setSelectedItem(null);
txtcrime.setText(null);
txtperiods.setText(null);
}
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
public static void main(String args[]) { <<ERROR HERE
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new addcriminal().setVisible(true);
}
});
}
Looks to me like you forgot the closing curly bracket in your catch statement.
catch(SQLException ex) {
JOptionPane.showMessageDialog(null, ex.toString());
}
I am getting the below exception:
Could not find PortableFactory for factory-id: 1
com.hazelcast.nio.serialization.HazelcastSerializationException: Could
not find PortableFactory for factory-id: 1
On the client side I have the following code:
public class ClientTest {
public static void main(String[] args) {
List<String> nodes = new ArrayList<String>();
nodes.add("localhost:5701");
ClientConfig clientConfig = new ClientConfig();
ClientNetworkConfig networkConfig = new ClientNetworkConfig();
networkConfig.setAddresses(nodes);
clientConfig.setNetworkConfig(networkConfig);
SerializationConfig serCong = clientConfig.getSerializationConfig();
serCong.addPortableFactory(1, new UserFactoryImpl());
serCong.setPortableVersion(1);
HazelcastInstance hzClient1 = HazelcastClient.newHazelcastClient(clientConfig);
IMap<String, User> map = hzClient1.getMap("user");
System.out.println(map.size() + "hiten");
User user1 = new User();
user1.setFirstName("hiten");
user1.setLastName("singh");
map.put("1", user1);
//hz1.getLifecycleService().terminate();
System.out.println(map.size() + "after");
User user2 = new User();
user2.setFirstName("hiten1");
user2.setLastName("singh1");
map.put("2", user2);
UserEntryProcessor entryProc = new UserEntryProcessor();
User userRes = (User)map.executeOnKey("1", entryProc);
}
static class UserEntryProcessor implements EntryProcessor<String, User>, HazelcastInstanceAware {
private transient HazelcastInstance hazelcastInstance;
#Override
public Object process(Entry<String, User> entry) {
User user = entry.getValue();
if(user != null) {
System.out.println(user.getFirstName());
}
return user;
}
#Override
public EntryBackupProcessor<String, User> getBackupProcessor() {
return null;
}
#Override
public void setHazelcastInstance(HazelcastInstance hazelcastInstance) {
this.hazelcastInstance = hazelcastInstance;
}
}
static class UserFactoryImpl implements PortableFactory{
public final static int USER_PORTABLE_ID = 1;
public final static int FACTORY_ID = 1;
public Portable create(int classId) {
switch (classId) {
case USER_PORTABLE_ID:
return new User();
}
return null;
}
}
static class User implements Portable {
private String firstName;
private String lastName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Override
public int getFactoryId() {
return UserFactoryImpl.FACTORY_ID;
}
#Override
public int getClassId() {
return UserFactoryImpl.USER_PORTABLE_ID;
}
#Override
public void writePortable(PortableWriter writer) throws IOException {
writer.writeUTF("first_name", firstName);
writer.writeUTF("last_name", lastName);
}
#Override
public void readPortable(PortableReader reader) throws IOException {
firstName = reader.readUTF("first_name");
lastName = reader.readUTF("last_name");
}
}
}
Yes it does, just as you figured out the factory and the classes need to be available. Currently there is no built-in solution to not share classes for more sophisticated use cases than simple gets / puts. I have JSON support and some other ideas cooking but nothing really done yet.
I'm a beginner in java and i'm practicing Singleton.
I'm trying to figure out how to convert my Database class to Singleton.
Also, part of my issue is how to use the Database class without passing the properties in the constructor.
public class Database {
public static final String DB_DRIVER_KEY = "db.driver";
public static final String DB_URL_KEY = "db.url";
public static final String DB_USER_KEY = "db.user";
public static final String DB_PASSWORD_KEY = "db.password";
private static Logger LOG = Logger.getLogger(Database.class.getName());
private static final Database theInstance = new Database();
private static Connection connection;
private static Properties properties;
private Database() {
}
public static void init(Properties properties) {
if (Database.properties == null) {
LOG.debug("Loading database properties from db.properties");
Database.properties = properties;
}
}
public static Connection getConnection() throws SQLException {
if (connection != null) {
return connection;
}
try {
connect();
} catch (ClassNotFoundException e) {
throw new SQLException(e);
}
return connection;
}
private static void connect() throws ClassNotFoundException, SQLException {
String dbDriver = properties.getProperty(DB_DRIVER_KEY);
LOG.debug(dbDriver);
Class.forName(dbDriver);
System.out.println("Driver loaded");
connection = DriverManager.getConnection(properties.getProperty(DB_URL_KEY),
properties.getProperty(DB_USER_KEY), properties.getProperty(DB_PASSWORD_KEY));
LOG.debug("Database connected");
}
/**
* Close the connections to the database
*/
public void shutdown() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
LOG.error(e.getMessage());
}
}
}
/**
* Determine if the database table exists.
*
* #param tableName
* #return true is the table exists, false otherwise
* #throws SQLException
*/
public static boolean tableExists(String tableName) throws SQLException {
DatabaseMetaData databaseMetaData = getConnection().getMetaData();
ResultSet resultSet = null;
String rsTableName = null;
try {
resultSet = databaseMetaData.getTables(connection.getCatalog(), "%", "%", null);
while (resultSet.next()) {
rsTableName = resultSet.getString("TABLE_NAME");
if (rsTableName.equalsIgnoreCase(tableName)) {
return true;
}
}
} finally {
resultSet.close();
}
return false;
}
/**
* #return the theinstance
*/
public static Database getTheinstance() {
return theInstance;
}
}
Well this little bit change into your existing class to make you understand.
public class Database {
public static final String DB_DRIVER_KEY = "db.driver";
public static final String DB_URL_KEY = "db.url";
public static final String DB_USER_KEY = "db.user";
public static final String DB_PASSWORD_KEY = "db.password";
private static Logger LOG = Logger.getLogger(Database.class.getName());
private static Database theInstance;
private static Connection connection;
private static Properties properties;
private Database() {
}
public static void init(Properties properties) {
if (Database.properties == null) {
LOG.debug("Loading database properties from db.properties");
Database.properties = properties;
}
}
public static Connection getConnection() throws SQLException {
if (connection != null) {
return connection;
}
try {
connect();
} catch (ClassNotFoundException e) {
throw new SQLException(e);
}
return connection;
}
private static void connect() throws ClassNotFoundException, SQLException {
String dbDriver = properties.getProperty(DB_DRIVER_KEY);
LOG.debug(dbDriver);
Class.forName(dbDriver);
System.out.println("Driver loaded");
connection = DriverManager.getConnection(
properties.getProperty(DB_URL_KEY),
properties.getProperty(DB_USER_KEY),
properties.getProperty(DB_PASSWORD_KEY));
LOG.debug("Database connected");
}
/**
* Close the connections to the database
*/
public void shutdown() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
LOG.error(e.getMessage());
}
}
}
/**
* Determine if the database table exists.
*
* #param tableName
* #return true is the table exists, false otherwise
* #throws SQLException
*/
public static boolean tableExists(String tableName) throws SQLException {
DatabaseMetaData databaseMetaData = getConnection().getMetaData();
ResultSet resultSet = null;
String rsTableName = null;
try {
resultSet = databaseMetaData.getTables(connection.getCatalog(),
"%", "%", null);
while (resultSet.next()) {
rsTableName = resultSet.getString("TABLE_NAME");
if (rsTableName.equalsIgnoreCase(tableName)) {
return true;
}
}
} finally {
resultSet.close();
}
return false;
}
/**
* #return the theinstance
*/
public static Database getInstance() {
if(theInstance == null){
theInstance = new Database();
}
return theInstance;
}
}
I get following error when I try to load data into JTable.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.tfc.cheque.handle.dao.impl.ChequeDAOImpl.getCheques(ChequeDAOImpl.java:23)
at com.tfc.cheque.handle.ui.ChequeGUI.(ChequeGUI.java:38)
at TestChequeDAO$1.run(TestChequeDAO.java:30)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
this is my main class:
public class TestChequeDAO {
public static void main(String[] args) throws SQLException{
DBConnection connection = new DBConnection();
connection.setUser("");
connection.setPswd("");
ChequeDAOImpl dao = new ChequeDAOImpl();
dao.setConnection(connection);
List<Cheque> cheques = dao.getCheques();
EventQueue.invokeLater(new Runnable() {
public void run() {
ChequeGUI cgui;
try {
cgui = new ChequeGUI();
cgui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
cgui.pack();
cgui.setVisible(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
}
this is my gui class:
public class ChequeGUI extends JFrame {
JTable guiTable = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][]{},new String[]{"Name","Amount","Date"});
public ChequeGUI() throws SQLException {
guiTable.setModel(model);
add(new JScrollPane(guiTable));
//Populate Table
ChequeDAOImpl chqdi = new ChequeDAOImpl();
List<Cheque> cheques = chqdi.getCheques();
for(Cheque cq : cheques){
model.addRow(new Object[]{cq.getName(),cq.getAmount(),cq.getDate()});
}
}
}
this is where i have written the query:
public class ChequeDAOImpl implements ChequeDAO{
//DB2 connection
private DBConnection dbConnection;
public List<Cheque> getCheques() throws SQLException{
List<Cheque> cheques = new ArrayList<Cheque>();
Connection connection = dbConnection.getConnection();
try{
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery("select * from LIB.DATA");
while(result.next()) {
Cheque cheque = new Cheque();
cheque.setAmount(result.getDouble("AMOUNT"));
cheque.setDate(result.getDate("DATE"));
cheque.setName(result.getString("NAME"));
cheques.add(cheque);
for(Cheque chq : cheques){
System.out.println("Name: " + result.getString("NAME"));
System.out.println("Amount: " + result.getDouble("AMOUNT"));
System.out.println("Date: " + result.getDate("DATE"));
}
}
}catch(Exception exception){
exception.printStackTrace();
}finally{
connection.close();
}
return cheques;
}
public DBConnection getConnection() {
return dbConnection;
}
public void setConnection(DBConnection connection) {
this.dbConnection = connection;
}
}
You need to initialize DBConnection dbConnection, and that much depends on a way how your application works
I am just trying to create a simple MINA server and client to evaluate. Here is my code.
public class Server {
private static final int PORT = 8080;
static class ServerHandler extends IoHandlerAdapter {
#Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
cause.printStackTrace();
}
#Override
public void sessionCreated(IoSession session) {
System.out.println("session is created");
session.write("Thank you");
}
#Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("session is closed.");
}
#Override
public void messageReceived(IoSession session, Object message) {
System.out.println("message=" + message);
session.write("Reply="+message);
}
}
/**
* #param args
*/
public static void main(String[] args) throws Exception {
SocketAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );
acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
acceptor.setHandler(new Server.ServerHandler());
acceptor.getSessionConfig().setReadBufferSize( 2048 );
acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
acceptor.bind(new InetSocketAddress(PORT));
System.out.println("Listening on port " + PORT);
for (;;) {
Thread.sleep(3000);
}
}
}
public class Client {
private static final int PORT = 8080;
private IoSession session;
private ClientHandler handler;
public Client() {
super();
}
public void initialize() throws Exception {
handler = new ClientHandler();
NioSocketConnector connector = new NioSocketConnector();
connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
connector.getFilterChain().addLast("logger", new LoggingFilter());
connector.setHandler(handler);
for (;;) {
try {
ConnectFuture future = connector.connect(new InetSocketAddress(PORT));
future.awaitUninterruptibly();
session = future.getSession();
break;
} catch (RuntimeIoException e) {
System.err.println("Failed to connect.");
e.printStackTrace();
Thread.sleep(5000);
}
}
if (session == null) {
throw new Exception("Unable to get session");
}
Sender sender = new Sender();
sender.start();
session.getCloseFuture().awaitUninterruptibly();
connector.dispose();
System.out.println("client is done.");
}
/**
* #param args
*/
public static void main(String[] args) throws Exception {
Client client = new Client();
client.initialize();
}
class Sender extends Thread {
#Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.messageSent(session, "message");
}
}
class ClientHandler extends IoHandlerAdapter {
#Override
public void sessionOpened(IoSession session) {
}
#Override
public void messageSent(IoSession session, Object message) {
System.out.println("message sending=" + message);
session.write(message);
}
#Override
public void messageReceived(IoSession session, Object message) {
System.out.println("message receiving "+ message);
}
#Override
public void exceptionCaught(IoSession session, Throwable cause) {
cause.printStackTrace();
}
}
}
When I execute this code, the Client seems to keep sending a message instead of stopping after it sends. It looks to me that there is a recursive call in underlying MINA code. I know that I am doing something wrong.
Can somebody tell me how to fix this?
Thanks.
Try to initialize and start your sender and use the session within sessionOpened (ClientHandler)