How to connent to Oracle database with SSH in IntelliJ IDEA - java

I'm trying to configure the data source using SSH to access the Database from IntelliJ off-campus. The configuration is as shown in the screenshots, and I got
[08006][17002] IO Error: Got minus one from a read call, connect lapse 30003 ms., Authentication lapse 0 ms. oracle.net.ns.NetException: Got minus one from a read call.
In fact, I've succeeded to connect to the DB with the loginProxy() and loginDB() in a Java program. From running the code, I knew that the jdbcPort should be dynamic, and I assume that's also what should be filled in the "Port" blank in the "General" tab in "Data Source and Drivers" configuration window.
So here comes the problem, how can I configure it if the Port to be filled in is DYNAMIC? Or did I get anything wrong so that actually there should be another approach?
An additional question: String URL = "jdbc:oracle:thin:#" + jdbcHost + ":" + jdbcPort + "/" + database; What URL format is used here? It doesn't look like SID, Service Name, or TNS, but it does work... and it's funny that when I substitute the "/" with ":", which matches the SID format, it doesn't work anymore...
/**
* Login the proxy. Do not change this function.
*
* #return boolean
*/
public boolean loginProxy() {
if (getYESorNO("Using ssh tunnel or not?")) { // if using ssh tunnel
String[] namePwd = getUsernamePassword("Login cs lab computer");
String sshUser = namePwd[0];
String sshPwd = namePwd[1];
try {
proxySession = new JSch().getSession(sshUser, proxyHost, proxyPort);
proxySession.setPassword(sshPwd);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
proxySession.setConfig(config);
proxySession.connect();
proxySession.setPortForwardingL(forwardHost, 0, databaseHost, databasePort);
forwardPort = Integer.parseInt(proxySession.getPortForwardingL()[0].split(":")[0]);
// 👆 forwardPort is set here, seems to be dynamic...
} catch (JSchException e) {
e.printStackTrace();
return false;
}
jdbcHost = forwardHost; // 👈 this is used in case of SSH connection, which is "localhost"
jdbcPort = forwardPort; // 👈 this is used in case of SSH connection
} else {
jdbcHost = databaseHost;
jdbcPort = databasePort;
}
return true;
}
/**
* Login the oracle system. Change this function under instruction.
*
* #return boolean
*/
public boolean loginDB() {
String username = "myDBUsername";
String password = "myDBPassword";
/* Do not change the code below */
String URL = "jdbc:oracle:thin:#" + jdbcHost + ":" + jdbcPort + "/" + database;
try {
System.out.println("Logging " + URL + " ...");
conn = DriverManager.getConnection(URL, username, password);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}

On general tab you need to specify real db server hostname and port, not localhost. With configured SSH tunnel on next tab all the things for connection will be done automatically.

Related

MongoClientURI connection string throwing error "com.mongodb.MongoSocketReadException: Prematurely reached end of stream"

public void MongoDBClient(String user, String pwd, String dbName, String collectionName) {
MongoClientURI uri = new MongoClientURI("mongodb+srv://" + user + ":" + pwd + "#cluster0.mff6p.mongodb.net/"
+ dbName + "?retryWrites=true&w=majority&connectTimeoutMS=30000&socketTimeoutMS=30000");
try (MongoClient mongoClient = new MongoClient(uri)) {
MongoDatabase database = mongoClient.getDatabase(dbName);
MongoCollection<Document> collection = database.getCollection(collectionName);
Document query = new Document("_id", new ObjectId("5f05e46281048f54ac98c455"));
Document result = collection.find(query).iterator().next();
System.out.println(result);
System.out.println("Test3: " + result.getString("Cluster"));
}
}
Getting exception in the above code -
INFO: Exception in monitor thread while connecting to server cluster0-shard-00-01.mff6p.mongodb.net:27017
com.mongodb.MongoSocketReadException: Prematurely reached end of stream
at com.mongodb.internal.connection.SocketStream.read(SocketStream.java:112)
at com.mongodb.internal.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:580)
at com.mongodb.internal.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:445)
at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:299)
at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:259)
at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)
at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:105)
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:62)
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:129)
at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117)
at java.base/java.lang.Thread.run(Thread.java:834)
Can anyone help me, i think there is an issue with the connection string url, MongoClientURI...
Its seems that your connection was terminated by the mongo server. It could have multiple reasons and best way to debug is to look at the server logs.
Usually the following is the issue:
From documentation:
For long running applications, it is often prudent to enable
"keepAlive" with a number of milliseconds. Without it, after some
period of time you may start to see "connection closed" errors for
what seems like no reason.
Try to enable to keepAlive property.
server: {
socketOptions: {
keepAlive: 100,
connectTimeoutMS: 30000
}
}
Try like this:
const MongoClient = require('mongodb').MongoClient;
const dburl = "mongodb+srv://" + user + ":" + pwd + "#cluster0.mff6p.mongodb.net/"
+ dbName + "?retryWrites=true&w=majority&connectTimeoutMS=30000&socketTimeoutMS=30000";
MongoClient.connect(dburl,{useNewUrlParser:true,useUnifiedTopology:true},(err,client) => {
if(err){
console.log("Error",err);
}
else{
console.log("Connected");
}
});

Redisson: Not able to set address in SingleServer mode

I am using the single server mode to configure the redis server and port, am I missing something here ?
Config config = new Config();
config.useSingleServer().setAddress("localhost:6379");
But below exception is encountered
Exception in thread "main" java.lang.IllegalArgumentException: Illegal character in scheme name at index 0: [localhost]:6379
at java.net.URI.create(URI.java:852)
at org.redisson.misc.URIBuilder.create(URIBuilder.java:38)
at org.redisson.config.SingleServerConfig.setAddress(SingleServerConfig.java:129)
Seems the below code in org.redisson.misc.URIBuilder has issue
public static URI create(String uri) {
URI u = URI.create(uri);
// Let's assuming most of the time it is OK.
if (u.getHost() != null) {
return u;
}
String s = uri.substring(0, uri.lastIndexOf(":")).replaceFirst("redis://", "").replaceFirst("rediss://", "");
// Assuming this is an IPv6 format, other situations will be handled by
// Netty at a later stage.
return URI.create(uri.replace(s, "[" + s + "]"));
}
Managed to get it working by using the following configuration
Config config = new Config();
config.useSingleServer().setAddress("redis://localhost:6379");

Python Server and Java Client: Weird behaviour receiving data

I am using python to create a server, and Java(Android) to create a client. The problem I am facing is getting the data correctly from one to the other.
I let the Java client attempt a login like this:
SettingsManager settingsman = SettingsManager.getInstance(params[0]);
int port = Integer.parseInt(settingsman.getPort());
String ip = settingsman.getIp();
server = new Socket(ip, port);
input = new DataInputStream(server.getInputStream());
output = new DataOutputStream(server.getOutputStream());
output.writeChars(LOGIN_REQ);
output.writeChars(settingsman.getUserName());
output.writeChars(settingsman.getPassword());
String token = Integer.toString(input.read());
//Check if the login has failed
if(token == "0"){
token = null;
}
return token;
And the Python server receives it like this:
opcode = c.recv(2)
opcode = opcode.decode('utf-8')
print("OPCODE:" + opcode + str(type(opcode)))
if(opcode == "0"):
"Login action"
print("STARTING TO RECV!")
login = c.recv(1024).decode('utf-8')
print("RECEIVED LOGIN: " + login)
password = c.recv(1024).decode('utf-8')
print("PASSWORD: " + password)
print("USERNAME: " + username)
setman = SettingsManager()
setuser = setman.seccam_user()
setpass = setman.seccam_password()
if login == setuser & password == setpass:
print("Login is good!")
"""Generate random token and save it to the settings file"""
elif(opcode == "1"):
pass
else:
print("OTHER!")
This is the output:
OPCODE:0<class 'str'>
OTHER!
Even though the Opcode seems to be a string and is the right value, the program doesn't enter the If statement correctly
Can anyone tell me what I am doing wrong?
Thanks
Alright, I fixed my issue. Using WriteBytes in my Java code is working better!

VPN connect using Java

Is there a way to connect and disconnect VPN in Forticlient programmatically?
I see that with Cisco VPN Client, there are options such as using the APIs they provide or executing connectivity commands from my Java code. Views and opinions on these ways of connecting to VPN are also most welcome.
I am looking for such options or any other that is possible, with Forticlient software.
Any directions from here would be of great help.
My trial so far :
private static final String COMMAND = "C:/Program Files/Cisco/Cisco AnyConnect Secure Mobility Client/vpncli";
private ExpectJ exp = new ExpectJ(10);
public void connectToVPNViaCLI(String server, String uname, String pwd)
{
try {
String command = COMMAND + " connect " + server;
Spawn sp = exp.spawn(command);
sp.expect("Username: ");
sp.send(uname + "\n");
sp.expect("Password: ");
sp.send(pwd + "\n");
sp.expect("accept? [y/n]: ");
sp.send("y" + "\n");
} catch(Exception e) {
LOGGER.severe(e.getMessage());
}
}

dokuwiki authentication from java

Here is the scenario:
I want to use docuwiki to show help and other content to users. The users are grouped by to organization. Each organization gets their own content that should be private to them. Enter ACL. I get how I can create a user and limit him to a certain subsection of the wiki.
Now the fun part begins. How can I authenticate these users from my server? I'm running a Tomcat/Java/MSSQL stack. I have full control of both servers.
I'd imagine if it is possible, I would imagine I can post the username/password to the wiki from the servlet, and get some kinda token back that the user can access the site with. But I don't see anything in the documentation about this. If anyone has any ideas, pointers or alternatives, I'd appreciate it.
I think the thing that you need is named Single Sign On (SSO). As a possible solution you could setup an SSO provider (there is vast variety of them, also with support of Tomcat and dokuwiki) and configure your dokuwiki and tomcat to use it. Here is a sample of such provider.
For googlers that come after me:
I ended up writing my own authenticator. TO use authenticator place it in *\inc\auth* with the name sqlsrv.class.php (sqlsrv will be the code you use to specify this authenticator.)
Basically what happens with this is I generate a token on my server that uniquely identifies a logged in user. I then POST or GET to the wiki with the token. The authenticator then queries the server to see if the user should be authenticated, as well as to get the name, email and which ACL groups the user should belong to.
Notes: make sure you change the config options in the php file. And you'll need sqlsrv installed and enabled for your apache/php.
<?php
/**
* sqlsrv authentication backend
*
* #license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* #author Yuriy Shikhanovich <yuriys#gmail.com>
*/
class auth_sqlsrv extends auth_basic {
/**
* Constructor
*
* Carry out sanity checks to ensure the object is
* able to operate. Set capabilities.
*
* #author Yuriy Shikhanovich <yuriys#gmail.com>
*/
function __construct() {
global $config_cascade;
global $connection;
$this->cando['external'] = true;
}
function trustExternal()
{
//$msgTxt = $_SESSION[DOKU_COOKIE]['auth']['info']['user']."x";
//msg($msgTxt);
//return true;
global $USERINFO;
global $conf;
global $connection;
//already logged in, no need to hit server
if (!empty($_SESSION[DOKU_COOKIE]['auth']['info']))
{
$USERINFO['name'] = $_SESSION[DOKU_COOKIE]['auth']['info']['user'];
$USERINFO['mail'] = $_SESSION[DOKU_COOKIE]['auth']['info']['mail'];
$USERINFO['grps'] = $_SESSION[DOKU_COOKIE]['auth']['info']['grps'];
$_SERVER['REMOTE_USER'] = $_SESSION[DOKU_COOKIE]['auth']['user'];
return true;
}
//check server based on token
try
{
$token = $_GET["token"];
if($token==null)
$token = $_POST["token"];
if($token==null)
$token = $_SESSION[DOKU_COOKIE]['auth']['token'];
if($token==null)
{
msg("Could not authenticate. Please contact your admin.");
return false;
}
//config //NOTE: replace with the appropriate values
$myServer = "1.1.1.1,1433";
$myUser = "sqlaccount";
$myPass = "sqlpassword";
$myDB = "dbName";
//end config
//get connection
$connectionInfo = array('UID' => $myUser, 'PWD' => $myPass, "Database"=>$myDB);
$link = sqlsrv_connect($myServer, $connectionInfo);
//check connection
if($link === FALSE)
{
msg("Could not get connection, contact your admin.");
return false;
}
//run token against proc
//NOTE: this needs to be implemented on your server, returns :
//"user" - Name of the user //this does not have to be setup in the wiki
//"email" - user's email //this does not have to be setup in the wiki
//"groups" - Which groups //this *does* have to be setup in the wiki to be used with ACL
$sql = "exec WikiLogin '".$token."'";
$stmt = sqlsrv_query( $link, $sql);
//check statement
if( $stmt === false)
{
msg("Could not get connection statement, contact your admin.");
return false;
}
//if returned results, set user and groups
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) )
{
// set the globals if authed
$USERINFO['name'] = $row['user'];
$USERINFO['mail'] = $row['email'];
$USERINFO['grps'] = split(" ",$row['groups']);
//msg(implode($row," "));
//msg(implode($USERINFO," "));
$_SERVER['REMOTE_USER'] = $row['user'];
//uncomment after testing
$_SESSION[DOKU_COOKIE]['auth']['user'] = $row['user'];
$_SESSION[DOKU_COOKIE]['auth']['mail'] = $row['email'];
$_SESSION[DOKU_COOKIE]['auth']['token'] = $token;
$_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
sqlsrv_free_stmt( $stmt);
sqlsrv_close($link);
return true;
}
return false;
if(isset($link))
sqlsrv_close($link);
else
msg("Could not get connection, contact your admin.");
if(isset($stmt))
sqlsrv_free_stmt($stmt);
else
msg("Could not get connection, contact your admin.");
}
catch (Exception $e)
{
if(isset($link))
sqlsrv_close($link);
else
msg("Could not get connection, contact your admin.");
if(isset($stmt))
sqlsrv_free_stmt($stmt);
else
msg("Could not get connection, contact your admin.");
}
}
}

Categories