Connect to RServe from JAVA using authentication - java

I am running RServe from Server machine using cmd
Rserve.exe --RS-conf Rserv.conf --RS-port 12306
Rserv.conf file has following content:
pwdfile RserveAuth.txt
auth required
remote enable
plaintext disable
RserveAuth.txt has following contents:
Admin 123456
I am connecting to R Server from JAVA
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.*;
public class ConnecttoR
{
...
...
public void connectR()
{
try
{
RConnection connection = new RConnection("172.16.33.242",12306); // Works if authentication is not required in Rserv.conf
}
catch (RserveException e) {
e.printStackTrace();
}
catch(REXPMismatchException e){
e.printStackTrace();
}
catch(REngineException e){
e.printStackTrace();
}
}
}
Connection to Rserve is open to all without username & Password. How shall I add security and allow connection only with valid credentials to access Rserve

As you have enabled the authentification after creating the connection as a first command you need to execute the login command. The Java library has a special wrapper for it.
See code below for example use case.
RConnection connection = new RConnection("127.0.0.1",12306);
connection.login("Admin", "123456");
REXP x = connection.eval("R.version.string");
System.out.println(x.asString());
Also, I would recommend using full path as the pwdfile value.

Related

How to connect to Apache Hive Using SSL certificate from Java JDBC?

I am currently trying to make a simple connection between a Java class and an Apache Hive server.
However, I have not been able to do it due to a javax.net.ssl.SSLPeerUnverifiedException error.
This is the Java code that I am executing:
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
Connection con = null;
try {
String conStr = "jdbc:hive2://{{domain}}:{{port}}/default;ssl=true;sslTrustStore=C:/DBVisualization/gateway.jks;trustStorePassword=Password1;transportMode=http;httpPath=/gateway/default/hive";
Class.forName("org.apache.hive.jdbc.HiveDriver");
con = DriverManager.getConnection(conStr, "user", "password");
if(con != null)
System.out.println("Connected");
} catch (Exception ex) {
Logger.getAnonymousLogger().severe("There was an error while connecting to Hive");
}
}
}
And this is the error I am getting:
Could not open client transport with JDBC Uri: jdbc:hive2:{{url}}:{{port}}/default;ssl=true;sslTrustStore=C:/DBVisualization/cacerts;trustStorePassword=changeit;transportMode=http;httpPath=/gateway/default/hive: Could not establish connection to jdbc:hive2://{{url}}:{{port}}/default;ssl=true;sslTrustStore=C:/DBVisualization/cacerts;trustStorePassword=changeit;transportMode=http;httpPath=/gateway/default/hive: javax.net.ssl.SSLPeerUnverifiedException: Certificate for <IP> doesn't match any of the subject alternative names: []
As you can see I am pointing to the file where the certificate is, I used that same certificate for set up a DB visualizer connection and it worked. I am just do not know if for Java a different certificate is required. What am I doing wrong?

Connect to SQL server from Java

I'm trying to connect from SSMS(SQL Server Management Studio) to Eclipse(Java), but I keep getting this error message:
com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host localhost, named instance sqlexpress failed. Error: "java.net.SocketTimeoutException: Receive timed out". Verify the server and instance names and check that no firewall is blocking UDP traffic to port 1434. For SQL Server 2005 or later, verify that the SQL Server Browser Service is running on the host.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:234)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.getInstancePort(SQLServerConnection.java:6132)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.primaryPermissionCheck(SQLServerConnection.java:2609)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2346)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:2213)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1276)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:861)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at net.codejava.sql.JavaConnect2SQL.main(JavaConnect2SQL.java:16)
The code I do have is:
import java.sql.DriverManager;
import java.sql.SQLException;
//import com.sun.jdi.connect.spi.Connection;
public class JavaConnect2SQL {
public static void main(String[] args) {
// TODO Auto-generated method stub
String url = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=students"; // This is where I think the error is
String user = "sa";
String password = "123";
try {
java.sql.Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Succesfully connected to Microsoft SQL Server");
}catch (SQLException e) {
System.out.println("Oops! There was an error: ");
e.printStackTrace();
}
}
}
I think the problem is in the connection URL, but I don't know the host name/instance name. If you can tell me how to get my host name/instance name, that would be appreciated. But if the problem is something else, please tell me!
Edit: I have changed the code, and I'm now getting a different. Here is the new code:
package net.codejava.sql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JavaConnect2SQL {
public static void main(String[] args) {
// Create a variable for the connection string.
String url = " jdbc:sqlserver://LAPTOP-5697KK36:1433;databaseName=students";
String user= "sa";
String password = "123";
try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("Connection succesful!");
}
// Handle any errors that may have occurred.
catch (SQLException e) {
System.out.println("Here is your error message: ");
e.printStackTrace();
}
}
}
The new error message is this:
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://LAPTOP-5697KK36:1433;databaseName=students
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:702)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:228)
at net.codejava.sql.JavaConnect2SQL.main(JavaConnect2SQL.java:40)
I think the problem is that I installed the wrong version of JDBC Driver. My JRE version is 12.0.1. What is the correct JDBC Driver to install.
You can check in SQL server configuration manager and Microsoft SQL server management studio. The state must be running in server configuration manager and you can try to connect your database in Microsoft SQL server management with your password.
if you connect successfully then there is another problem but it looks like the database is stopped.

Shell commands are not running using jsch and expcetit library in java

I am following below steps for running commands on ssh server.
Connecting to ssh server
Using devpush command again logging to server (using expectit library for user input prompt).
Finally running remote commands using jsch library.
The issue I am facing is that, my code is going in infinite loop it is able to login to ssh server but not able to run the commands.
Can any one please help me on this as I am using both the libraries for first time.
package com.dmotorworks.cdk;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import net.sf.expectit.*;
import net.sf.expectit.matcher.Matchers;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class ShellClient {
public void loginToPabloServer() throws IOException, JSchException{
String hostname="pablo.dmotorworks.com";
String username="gaikwasu";
String password="Nexus#80900";
final String endLineStr=" # ";
JSch jsch = new JSch();
Session session = jsch.getSession(username, hostname, 22);
session.setPassword(password);
jsch.setKnownHosts("C://Users//gaikwasu//.ssh//known_hosts");
session.connect();
System.out.println("Connected");
Channel channel=session.openChannel("shell");
channel.connect();
Expect expect=new ExpectBuilder()
.withOutput(channel.getOutputStream())
.withInputs(channel.getInputStream(), channel.getExtInputStream())
.withEchoOutput(System.out)
.withEchoInput(System.err)
.withExceptionOnFailure()
.build();
expect.expect(Matchers.contains("-bash-4.1$"));
expect.send("devpush\n");
expect.expect(Matchers.contains("[sudo] password for"));
expect.send(password+"\n");
DataInputStream dataIn = new DataInputStream(channel.getInputStream());
DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
BufferedReader bufferReader= new BufferedReader(new InputStreamReader(dataIn));
dataOut.writeBytes("cd custom\n");
dataOut.writeBytes("ls -lrt\n");
dataOut.flush();
String line=bufferReader.readLine();
while(!line.endsWith(endLineStr)) {
System.out.println(line);
}
channel.disconnect();
session.disconnect();
expect.close();
}
public static void main(String[] args) {
ShellClient shellClient=new ShellClient();
try {
shellClient.loginToPabloServer();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Most probably the cause of the infinitive loop is because the Expect instance reads the input data in a separate thread at the same time while you are trying to same data in the main thread.
Try to close the Expect instance before reading the data. It may help.
However, I strongly recommend to keep using the Expect instance after the sending password. ExpectIt can help with extracting the information from the remote command output. For example:
expect.sendLine(password);
expect.expect(Matchers.contains("-bash-4.1$"));
expect.sendLine("cd custom");
expect.expect(Matchers.contains("-bash-4.1$"));
expect.sendLine("ls -lrt");
// the lsResult variable should contain the result of the 'ls -l' command
String lsResult = expect.expect(Matchers.contains("-bash-4.1$")).getBefore();
System.out.println(lsResult);
Please take a look at this example.

Google Cloud Connection Server and smack

I'm trying to get a java server set up for communicating to Google's Cloud Connection Server using the smack library. I have set up an app ID and API key through Google APIs and am trying to use the following code:
import javax.net.ssl.SSLSocketFactory;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Packet;
public class CloudMessager {
public CloudMessager(){
ConnectionConfiguration config = new ConnectionConfiguration("gcm.googleapis.com", 5235);
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
config.setSASLAuthenticationEnabled(true);
config.setSocketFactory(SSLSocketFactory.getDefault());
Connection connection = new XMPPConnection(config);
// Connect to the server
try {
connection.connect();
connection.login("SENDERID#gcm.googleapis.com", "APIKEY");
PacketListener myListener = new PacketListener() {
public void processPacket(Packet packet) {
}
};
// Register the listener.
connection.addPacketListener(myListener,null);
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
Which gives me the following error:
SASL authentication PLAIN failed: text:
at org.jivesoftware.smack.SASLAuthentication.authenticate(SASLAuthentication.java:342)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:221)
at org.jivesoftware.smack.Connection.login(Connection.java:366)
at org.umptyfratz.strongbox.CloudMessager.<init>(CloudMessager.java:25)
I'm at a bit of a loss to figure out where to go from here. Has anyone else successfully connected to CCS using the Java smack library?
Try to debug the connection with this option:
config.setDebuggerEnabled(true);
This'll open a new window with the data sent and received.
If you find something like "Project SENDERID not whitelisted." you have to register your project here.
(This is in the documentation's note too! http://developer.android.com/google/gcm/ccs.html )

Create WebSphere administrative client program for java

I am using IBM WebSphere server. I need to Create WebSphere administrative client program for java using WebSphere Administrative API's. I am using this code for creating admin client
...
adminClient = AdminClientFactory.createAdminClient(connectProps);
...
but it gives exception.
The system cannot create a SOAP connector to connect to host localhost at port 8881.
After creating client I want to configure WASADMIN through this API. Am I on right track?
I need to get shared library through this API.
check if you have this server SOAP connector port set to 8881.
In Dmgr click the server name than Ports to check it. If not using 8881 than change it to the correct port being used by the server you're trying to connect to.
Update:
I did a test in my environment(Linux) and the following code worked( I had to add WebSphere_ND8.5/AppServer/runtimes/com.ibm.ws.admin.client_8.5.0.jarto classpath to run it without getting a ClassNotFoundException):
import java.util.Properties;
import java.util.logging.Logger;
import com.ibm.websphere.management.AdminClient;
import com.ibm.websphere.management.AdminClientFactory;
import com.ibm.websphere.management.exception.ConnectorException;
public class AdminConnect {
private static Logger logger = Logger.getLogger(AdminConnect.class.getName());
/**
* #param args
*/
public static void main(String[] args) {
Properties connectProps = new Properties();
connectProps.setProperty(
AdminClient.CONNECTOR_TYPE, AdminClient.CONNECTOR_TYPE_SOAP);
connectProps.setProperty(AdminClient.CONNECTOR_HOST, "localhost");
connectProps.setProperty(AdminClient.CONNECTOR_PORT, "8880");
// connectProps.setProperty(AdminClient.USERNAME, "test2");
// connectProps.setProperty(AdminClient.PASSWORD, "user24test");
AdminClient adminClient = null;
try
{
adminClient = AdminClientFactory.createAdminClient(connectProps);
logger.info("Connected successfuly with WebSphere :) ");
}
catch (ConnectorException e)
{
logger.severe("Exception creating admin client: " + e);
e.printStackTrace();
}
}
}

Categories

Resources