h2 mixed mode connection problem - h2

I start h2 database in a servlet context listener:
public void contextInitialized(ServletContextEvent sce) {
org.h2.Driver.load();
String apprealPath = sce.getServletContext().getRealPath("\\");
String h2Url = "jdbc:h2:file:" + apprealPath + "DB\\cdb;AUTO_SERVER=true";
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
StatusPrinter.print(lc);
logger.debug("h2 url : " + h2Url);
try {
conn = DriverManager.getConnection(h2Url, "sa", "sa");
} catch (SQLException e) {
e.printStackTrace();
}
logger.debug("h2 database started in embedded mode");
sce.getServletContext().setAttribute("connection", conn);
}
then I try to use dbvisualizer to connect to h2 using following url :
jdbc:h2:tcp://localhost/~/cdb
but get these error messages:
An error occurred while establishing the connection:
Type: org.h2.jdbc.JdbcSQLException Error Code: 90067 SQL State: 90067
Message:
Connection is broken: "Connection refused: connect" [90067-148]
I tried to replace localhost with "172.17.33.181:58524" (I found it in cdb.lock.db)
reconnect with user "sa" password "sa" ,then server response changed to :
wrong username or password !

In the Automatic Mixed Mode, you don't need to (and you can't) use jdbc:h2:tcp://localhost. Just use the same URL everywhere, that means jdbc:h2:file:...DB\\cdb;AUTO_SERVER=true.
You can use the same database URL independent of whether the database is already open or not. Explicit client/server connections (using jdbc:h2:tcp:// or ssl://) are not supported.

Related

Can't seem to send email with jhipster application

I'm trying to make a simple form that when submited sends and email to a fixed email.
I'm using spring and i've searched on how to configure the application.yml and i'm using the mailsend method that seems to have been generated with my jhipster application.
I've built my FE service to connect to the back end :
sendForm(): Observable<any>{
return this.http.post(SERVER_API_URL + 'api/sendForm', "");
}
i've built the onsubmit method to make the subscribe to the method above:
onSubmit() {
this.auth.sendForm().subscribe( data => {
console.log(data);
})
}
i've hard coded the mail resource just to mock an email to make sure its working:
#PostMapping("/sendForm")
public void sendForm() {
this.mailService.sendEmail("mymail#gmail.com","Header","texto",false,true);
}
the sendMail method that im sending the information for the mail submition is autogenerated and I believe it should be working
#Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart, isHtml, to, subject, content);
// Prepare message using a Spring helper
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
message.setTo(to);
message.setFrom(jHipsterProperties.getMail().getFrom());
message.setSubject(subject);
message.setText(content, isHtml);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.warn("Email could not be sent to user '{}'", to, e);
} else {
log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
}
}
}
and heres my application-dev.yml (i'm still on dev)
spring:
profiles:
active: dev
mail:
host: smtp.gmail.com
port: 587
username: gmailuserid#gmail.com #Replace this field with your Gmail username.
password: ************ #Replace this field with your Gmail password.
protocol: smtp
tls: true
properties.mail.smtp:
auth: true
starttls.enable: true
ssl.trust: smtp.gmail.com
the errors im getting goes as follows:
org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localh
ost, 25; timeout -1;
nested exception is:
java.net.ConnectException: Connection refused: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeo
ut -1;
All I expect is a mail with the mock i've used and I cant seem to be able to put this working.
I hope i've not made the post to long and that everything is well explained.
Thank you in advance for anyone willing to help
Apparently somewhy the properties-prod.yml wasnt being loaded to the server. I had to create a config file with all the configurations for it to work

Unable to get oracle database connection

1.JAVA_HOME is set to IBM JAVA SDK.
2.Unable to get oracle database connection. Where as tried running the same on machine having Oracle java set as JAVA_HOME
3.Placed ojdbc14.jar under AppServer/lib.
try {
connection = DriverManager.getConnection(
"jdbc:oracle:thin:#[server-ip]:[server-port]/[dbname]", "[uname]", "[pass]");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
Is there any setting i need to do.Below is the error
Oracle JDBC Driver Registered! Connection Failed! Check output console
java.sql.SQLRecoverableException: IO Error: The Network Adapter could
not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:517)
at oracle.jdbc.driver.PhysicalConnection.(PhysicalConnection.java:557)
at oracle.jdbc.driver.T4CConnection.(T4CConnection.java:233)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:29)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:556)
at java.sql.DriverManager.getConnection(DriverManager.java:583)
at java.sql.DriverManager.getConnection(DriverManager.java:227)
at OracleJDBCExample.main(OracleJDBCExample.java:29) Caused by: oracle.net.ns.NetException: The Network Adapter could not
establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:389)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:431)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:882)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:267)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1625)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:365)
... 7 more Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:370)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:231)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:213)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:404)
at java.net.Socket.connect(Socket.java:643)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:147)
at oracle.net.nt.ConnOption.connect(ConnOption.java:130)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:367)
Thanks,
Kusuma
Here's a couple of things to check:
can you connect to port [server-port] on [server-ip] ? (try telnet, netcat or something similar)
does the listener accept connections? i.e. does sqlplus username/pw#[server-ip]:[server-port]/[dbname] work?
is the SID correct (dbname) ?
have you tried connecting with the service name instead of the SID:
jdbc:oracle:thin:#//<server-ip>:<server-port>/<dbname> ?
see also
Java JDBC - How to connect to Oracle using Service Name instead of SID

FTPSClient file upload and download always size 0 and exception

Installed the filezilla server and enabled the FTP over TLS Settings in Settings and started the server.
Through eclipse java client i tried to connect to server for upload and download the file using the below code
using commons-net apache library.
FTPSClient ftpClient = new FTPSClient(false);
// Connect to host
ftpClient.connect(mServer, mPort);
int reply = ftpClient.getReplyCode();
System.out.println("The reply code is "+reply);
if (FTPReply.isPositiveCompletion(reply)) {
// Login
if (ftpClient.login("******", "*******")) {
// Set protection buffer size
ftpClient.execPBSZ(0);
// Set data channel protection to private
ftpClient.execPROT("P");
// Enter local passive mode
ftpClient.enterLocalPassiveMode();
// Upload File using storeFile
File firstLocalFile = new File("e:/Test.txt");
String firstRemoteFile = "hello.txt";
InputStream is = new FileInputStream(firstLocalFile);
String result = getStringFromInputStream(is);
System.out.println(result);
Object output = ftpClient.storeFile(firstRemoteFile, is);
System.out.println(output);
is.close();
// Download File using retrieveFile(String, OutputStream)
String remoteFile1 = "/settings.xml";
File downloadFile1 = new File("e:/testOutput.xml");
OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(downloadFile1));
boolean success = ftpClient.retrieveFile(remoteFile1, outputStream1);
outputStream1.close();
if (success) {
System.out.println("File #1 has been downloaded successfully.");
}
// Logout
ftpClient.logout();
// Disconnect
ftpClient.disconnect();
} else {
System.out.println("FTP login failed");
}
// Disconnect
ftpClient.disconnect();
} else {
System.out.println("FTP connect to host failed");
}
} catch (IOException ioe) {
System.out.println("FTP client received network error");
ioe.printStackTrace();
} catch (Exception nsae) {
System.out.println("FTP client could not use SSL algorithm");
nsae.printStackTrace();
}
It creates a file hello.txt on the server but size is of 0kb (source file size is 10 kb) and ended up the following error. Please help me to resolve this
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at org.apache.commons.net.ftp.FTPSClient._openDataConnection_(FTPSClient.java:619)
at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:633)
at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:624)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1976)
at com.test.ftps.TestClass.main(TestClass.java:88)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(Unknown Source)
... 9 more
just un-tick
"Require TLC session resumption on data connection..." in the filezilla server -> settings -> FTP over TLS Settings -> un-tick the Require TLC session resumption on data connection when using PROT P
In addition to user2750213's answer ( Filezilla's TLS session resumption ) beware to have the required protocols enabled. You can verify them running this code or this other on the jvm connecting to the FTPS server. Recent versions of Filezilla server use TLSv1.2.
If this works for you, you may get a java.net.SocketException: Unconnected sockets not implemented. In this case you need to write your own class which extends DefaultSocketFactory class and then set it to your FTPS client via method ftpsClient.setSocketFactory(yourSocketFactory) overriding the createSocket() method which must returns a new Socket()

How to find the h2 database server is running or not from java code

I need to find whether h2 database server is running or not from java code. I have tried getStatus().isRunning(args) methods but it always shows that server is not running even if the server is running. Below is my code:
Server server = Server.createTcpServer(args);
// Find whether is server is on or not using "isRunning()" method
if (server.isRunning(false)) {
System.out.println("server is running");
} else {
System.out.println("server is not running");
}
// Find whether is server is on or not using "getStatus()" method
String statVariable = server.getStatus();
System.out.println("STATUS=" + statVariable);
System.out.println("SERVER GONNA START");
server.start();
perhaps you can send a request off to the port in question, assuming it is either WebServer or TCP server (the default ports being 8082 or 9092 respectively). You know that the call
drewmac:bin drewpierce$ java -cp h2*.jar org.h2.tools.Server
creates 3 servers and spits out something like:
TCP server running at tcp://192.168.1.3:9092 (only local connections)
PG server running at pg://192.168.1.3:5435 (only local connections)
Web Console server running at http://192.168.1.3:8082 (only local connections)
then if you call the routine to show ports on your server with listening sockets
and my call would be
drewmac:~ drewpierce$ sudo lsof -i -P | grep -i "listen"
java 81339 drewpierce 19u IPv6 0xffffff800b782ac0 0t0 TCP *:9092 (LISTEN)
java 81339 drewpierce 22u IPv6 0xffffff800b781bc0 0t0 TCP *:5435 (LISTEN)
java 81339 drewpierce 24u IPv6 0xffffff8015620800 0t0 TCP *:8082 (LISTEN)
now if you want to test the web server (http and html streams to port 80, 8082, whatever you make it, you can issue Chunk A. If you want to test the TCP server you can issue Chunk B.
Call Chunk A like java GreetingClient localhost 8082
or like java GreetingClient ec2-1-2-3-4-amaz-aws-ec2.amazon.com 8082
don't forget the 2 parameters in this test or it will barf
Chunk A:
import java.io.*;
import java.net.*;
public class GreetingClient {
public static void main(String[] args) {
// declaration section:
// mySocket: our client socket pretending to be a browser
// os: output stream
// is: input stream
Socket mySocket = null;
DataOutputStream os = null;
DataInputStream is = null;
String serverName = args[0];
int port = Integer.parseInt(args[1]);
// Initialization section:
// btw make sure parameters are passed noting that this quick code is NOT
// Try to open input and output streams
System.out.println("*1");
try {
mySocket = new Socket(serverName,port);
os = new DataOutputStream(mySocket.getOutputStream());
is = new DataInputStream(mySocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Don't know about host: hostname");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: hostname");
}
System.out.println("*2");
// If everything has been initialized then we want to write some data
// to the socket we have opened a connection to on port 80, 8082, whatever
// (what the server is listening on)
if (mySocket != null && os != null && is != null) {
try {
// pretend to be a browser and do a GET against a resource
System.out.println("*3");
os.writeBytes("GET /index.html HTTP/1.0\r\n\r\n");
System.out.println("*4");
// wait for response from webserver, dump out response for sanity check
String responseLine;
while ((responseLine = is.readLine()) != null) {
System.out.println("Server: " + responseLine);
if (responseLine.indexOf("Ok") != -1) {
break;
}
}
// clean up:
// close the output stream
// close the input stream
// close the socket
System.out.println("*5");
os.close();
is.close();
mySocket.close();
} catch (UnknownHostException e) {
System.err.println("Trying to connect to unknown host: " + e);
} catch (IOException e) {
System.err.println("IOException: " + e);
}
}
System.out.println("*6");
}
}
Chunk A output (for me at least):
*1
*2
*3
*4
Server: HTTP/1.1 200 OK
Server: Content-Type: text/html
Server: Cache-Control: no-cache
Server: Content-Length: 937
Server:
Server: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
Server: <!--
Server: Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
Server: and the EPL 1.0 (http://h2database.com/html/license.html).
Server: Initial Developer: H2 Group
Server: -->
Server: <html><head>
Server: <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
Server: <title>H2 Console</title>
Server: <link rel="stylesheet" type="text/css" href="stylesheet.css" />
Server: <script type="text/javascript">
Server: location.href = 'login.jsp?jsessionid=f3d05d9b68f4c5407054628f096ffccb';
Server: </script>
Server: </head>
Server: <body style="margin: 20px;">
Server:
Server: <h1>Welcome to H2</h1>
Server: <h2>No Javascript</h2>
Server: If you are not automatically redirected to the login page, then
Server: Javascript is currently disabled or your browser does not support Javascript.
Server: For this application to work, Javascript is essential.
Server: Please enable Javascript now, or use another web browser that supports it.
Server:
Server: </body></html>
*5
*6
A few things, clearly this is H2 output. Chunk A source code could be whittled down to about 10 lines.
Chunk B (talk jdbc to TCP jdbc server)
//STEP 1. Import required packages
import java.sql.*;
import org.h2.Driver;
public class JdbcTrial {
// JDBC driver name and database URL
//static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
//static final String DB_URL = "jdbc:mysql://127.0.0.1/test";
static final String JDBC_DRIVER = "org.h2.Driver";
static final String DB_URL = "jdbc:h2:tcp://localhost/~/test";
// Database credentials
static final String USER = "sa";
static final String PASS = "";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
System.out.println("***** 1");
Class.forName(JDBC_DRIVER);
System.out.println("***** 2");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, FirstName, LastName from people";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String first = rs.getString("FirstName");
String last = rs.getString("LastName");
//Display values
System.out.print("ID: " + id);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Chunk B output:
drewmac:~ drewpierce$ java JdbcTrial
***** 1
***** 2
Connecting to database...
Creating statement...
ID: 1, First: joan, Last: london
ID: 2, First: Sgt., Last: Corholio
Goodbye!
worked fine against mysql, mariadb, and H2, just by messing with the jdbc_driver and db_url
You could just do socket connects and not issue off data retrieval calls and really prune it down.
As far as how to do this with the H2 getStatus, I have no clue. Good luck.

SFTP error : com.jcraft.jsch.JSchException: invalid server's version string

I have the below code to SFTP to a location
public static void putFile(String username, String host, String password, String remotefile, String localfile){
JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(username, host, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.put(localfile, remotefile);
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();
}
}
I am able to SFTP the document from my local machine using the above code. However when I am trying from a different environment to SFTP to the same location I am getting the follow error.
com.jcraft.jsch.JSchException: invalid server's version string at
com.jcraft.jsch.Session.connect(Session.java:253)
Note : I am using jsch-0.1.31.jar file.
on printing out session.getClientVersion() I am getting "SSH-2.0-JSCH-0.1.31".
I tried to upgrade the jar file to jsch-0.1.51.jar then session.getClientVersion() = "SSH-1.5-JSCH-0.1.51" and I am getting the following error
com.jcraft.jsch.JSchException: Session.connect: java.net.SocketException: Connection reset at com.jcraft.jsch.Session.connect(Session.java:558)
Please can you help me on what parameters should I be looking into and what is causing it to run from my local machine and upload to the same SFTP location and not from other environment?
As noted by #Kenster, the exception is about server's version string, not client's. The "invalid server's version string" exception is thrown by following code in Session.connect:
if(i==buf.buffer.length ||
i<7 || // SSH-1.99 or SSH-2.0
(buf.buffer[4]=='1' && buf.buffer[6]!='9') // SSH-1.5
){
throw new JSchException("invalid server's version string");
}
First, I would try to connect with some client that logs the version string and see yourself. For example with WinSCP, search its log for a pattern like:
. 2014-09-03 17:01:20.596 Server version: SSH-2.0-OpenSSH_5.3
(I'm the author of WinSCP)
Though possibly it's not about version string at all. I would rather believe the error raised by the new version, the Connection reset. The old version may fail to detect that the connection was aborted prematurely and tries to validate some random or incomplete data.
The Connection reset may indicate wide variety of different errors
Server refusing a connection from the other location
Some firewall or proxy not allowing the connection to pass through

Resources