JDBC node module not working in other systems - java

I have used npm install jdbc to install the jdbc node module in my 32 bit Linux OS. I've written a node code :
var jdbc = new ( require('jdbc') );
var config = {
libpath: __dirname + 'path/to/jdbc.jar',
drivername: 'cs.jdbc.driver.CompositeDriver',
url: connectionurl,
// optionally
user: username,
password: password,
};
app.get('/jdbctry', function (req, res) {
jdbc.initialize(config, function(err, res) {
if (err) {
console.log(err);
}
});
var genericQueryHandler = function(err, results) {
if (err) {
console.log(err);
} else if (results) {
console.log(results);
}
jdbc.close(function(err) {
if(err) {
console.log(err);
} else {
console.log("Connection closed successfully!");
}
});
};
jdbc.open(function(err, conn) {
if (conn) {
// SELECT statements are called with executeQuery
jdbc.executeQuery("SELECT * FROM table", genericQueryHandler);
}
});
});
I've run it in my local system and it works perfectly fine.
But my requirement is to run it in another 32 bit Linux machine with no access to the Internet. I moved the code and the jdbc module to the other system, and tried running it, I get the following error :
Module._extensions[extension](this, filename);
^
Error: libjvm.so: cannot open shared object file: No such file or directory
at Error (native)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous (/common/node_modules/jdbc/node_modules/java/lib/nodeJavaBridge.js:10:16)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)

Related

How to Connect to Databricks Delta table using JDBC driver

How can I connect to Databricks Delta table using JDBC?
I have tried connecting simba driver but im getting hard time for driver class name and url configuration.
Any solution is appreciated.
I cannot paste code here as its company code.
Thanks in advance.
Check this link below. This has steps to configure delta using JDBC
http://sedeks.blogspot.com/2019/05/how-to-connect-to-databricks-delta.html
code provided in this link:
import java.sql.DriverManager
import java.sql.Driver
import java.sql.Connection
import javax.sql.DataSource
object ScalaJdbcConnectSelect {
def main(args: Array[String]) {
val driver = "com.simba.spark.jdbc41.Driver" //attach the Spark jar to the Classpath.
val url = "jdbc:spark://field-eng.cloud.databricks.com:443/default;transportMode=http;ssl=true;httpPath=sql/protocolvl/o/0/0911-153027-hopes19";
val username = "token"
val password = "<token-value>" //Token generated from databricks profile page.
var connection:Connection = null
try {
// Create the connection
Class.forName(driver)
connection = DriverManager.getConnection(url, username, password)
if(connection != null){
println("Connection Established");
}
else {
println("Connection Failed");
}
// create the statement
val statement = connection.createStatement()
val resultSet = statement.executeQuery("<<Query>") // Profile your query here.
while ( resultSet.next() ) {
// Iterate through Result set
}
catch {
case e => e.printStackTrace
}
connection.close()
}
}

IONIC 3 : UnhandledPromiseRejectionWarning when generating APK File

I'm facing problems when generating apk file. I get the following error.
Command : ionic cordova build android
Output :
> cordova build android
Android Studio project detected
ANDROID_HOME=C:\Users\****\AppData\Local\Android\Sdk
JAVA_HOME=C:\Program Files\Java\jdk-9.0.4
(node:17504) UnhandledPromiseRejectionWarning: Unhandled promise rejection (reje
ction id: 1): CordovaError: Requirements check failed for JDK 1.8 or greater
(node:17504) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate th
e Node.js process with a non-zero exit code.
[13:47:49] lint finished in 8.47 s
This is the content of my rest file rest.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class RestProvider {
private baseUrl = 'http://localhost/project/web/rest/mobile/v1/';
private nomsvillesUrl = this.baseUrl + 'ville/nomsvilles/1';
constructor(public http: HttpClient) {
console.log('Hello RestProvider Provider');
}
getNomvilles(): Observable<string[]> {
return this.http.get(this.nomsvillesUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res;
return body || { };
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const err = error || '';
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
This is the content of my main class main.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { RestProvider } from '../../providers/rest/rest';
#Component({
selector: 'page-main',
templateUrl: 'main.html',
})
export class MainPage {
villes: string[]
errorMessage: string
constructor(public navCtrl: NavController, public navParams: NavParams, public rest: RestProvider) {
}
ionViewDidLoad() {
this.getVilles();
}
getVilles() {
this.rest.getNomvilles().subscribe(
villes => this.villes = villes,
error => this.errorMessage = <any>error
);
}
}
Please help me ! I want to know how to handle Promise in order to prevent promise rejection.
Thank you .
The error has nothing related to your code. It's asking for jdk 1.8 or higher you can download it from this link. But first uninstall jdk 1.9 you're using because it's not compatible with android.
Then create a environment variable JAVA_HOME=C:\path\to\jdk\bin

wowza authontication using external jar

I am using Wowza streaming engine in my project. I successfully started wowza with basic authentication. I need to authenticate wowza with my database because I am creating a java project. It will handle the authentication process after I add the jar to the Wowza engine lib folder.
This is the source code of jar:
public class WowzaTesting {
boolean authStatus = false;
public boolean authenticationTest(String username, String password) {
System.out.println("Authentication Process started");
// authentication code here
// if authentication is done authStatus=true; else authStatus=false;
if (authStatus) {
return true;
} else {
return false;
}
}
}
And I have added to conf file:
<Module>
<Name>TestWowza</Name>
<Description>Java code for testing wowza</Description>
<Class>com.test.wowza.WowzaTesting</Class>
</Module>
Then restarted wowza server engine.
I have some questions:
Have I missed any steps?
How to call method in the jar file in the time of Wowza authentication?
Currently I am using this command for live streaming"
ffmpeg -i "rtsp://localhost:port/livetest" -vcodec copy -acodec copy -f rtsp "rtsp://username:password#localhost:port/live/livetest
How to get the username and password from the above command to my method?
Have I missed any steps?
Wowza API has the AuthenticateUsernamePasswordProviderBase class that you would need to extend in order to integrate database authentication.
How to call method in the jar file in the time of Wowza authentication?
The way that RTSP authentication currently works in Wowza is that you specify the authentication method to be used in the Application configuration (in the Root/Application/RTP/Authentication/PublishMethod section of the file). These publish methods are defined in the Authentication configuration. To intercept this with your custom authentication module, you would need to add your Java class to this Authentication.xml file as a property. In version 3 of Wowza, the Authentication.xml file is in the conf/ directory and can be easily edited, but in version 4, this has been bundled into the com.wowza.wms.conf package (you can grab a copy from the package and copy it to your conf/ folder and it will override the one in the package). Wowza will thus use the method defined in your class instead of the built-in ones.
How to get the username and password from the above command to my method?
When Wowza receives the incoming RTSP connection, it should query the username/password from the connection and pass these to your Java class to handle authentication.
An example code that integrates a database for authentication is below:
package com.wowza.wms.example.authenticate;
import com.wowza.wms.authentication.*;
import com.wowza.wms.logging.WMSLoggerFactory;
import java.sql.*;
public class AuthenticateUsernamePasswordProviderExample extends AuthenticateUsernamePasswordProviderBase
{
public String getPassword(String username)
{
// return password for given username
String pwd = null;
WMSLoggerFactory.getLogger(null).info("Authenticate getPassword username: " + username);
Connection conn = null;
try
{
conn = DriverManager.getConnection("jdbc:mysql://localhost/wowza?user=root&password=mypassword");
Statement stmt = null;
ResultSet rs = null;
try
{
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT pwd FROM users where username = '"+username+"'");
while (rs.next())
{
pwd = rs.getString("pwd");
}
}
catch (SQLException sqlEx)
{
WMSLoggerFactory.getLogger(null).error("sqlexecuteException: " + sqlEx.toString());
}
finally
{
if (rs != null)
{
try
{
rs.close();
}
catch (SQLException sqlEx)
{
rs = null;
}
}
if (stmt != null)
{
try
{
stmt.close();
}
catch (SQLException sqlEx)
{
stmt = null;
}
}
}
conn.close();
}
catch (SQLException ex)
{
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
return pwd;
}
public boolean userExists(String username)
{
// return true is user exists
return false;
}
}

Java running in Oracle - the imported jars

I am trying to get a small java class to load into Oracle 11g so I can run it and call it from PL/SQL. I coded and compiled the class on my local machine in eclipse and it compiles fine. I packaged it up into a jar (with the other jar files it depends on in the jar). They I tried loading my jar into Oracle 11g. Everything loads in, unfortunately when it loads my custom java class, it stays invalid and when I try to compile it within Oracle it says it can't find references to the classes (the ones I had packaged in my jar with my class).
Is there some other sort of setting I need to configure?
Here is what my custom classes code looks like:
import com.flashline.registry.openapi.base.OpenAPIException;
import com.flashline.registry.openapi.entity.*;
import com.flashline.registry.openapi.service.v300.FlashlineRegistry;
import com.flashline.registry.openapi.service.v300.FlashlineRegistryServiceLocator;
import javax.xml.rpc.ServiceException;
import java.net.URL;
import java.rmi.RemoteException;
import org.apache.log4j.Logger;
import java.net.MalformedURLException;
public class AssetExtractor {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
static Logger LOG;
static AuthToken authToken = null;
static FlashlineRegistry repository = null;
static URL repoURL;
public static FlashlineRegistry getRepository()
{
if(repository == null)
try
{
try{
repoURL = new URL("https://myserver/oer/services/FlashlineRegistry");
}catch(MalformedURLException mue)
{
LOG.error(mue);
}
repository = (new FlashlineRegistryServiceLocator()).getFlashlineRegistry(repoURL);
LOG.debug((new StringBuilder()).append("Created repository at URL=").append(repoURL.toString()).toString());
}
catch(ServiceException e)
{
LOG.error(e, e);
}
return repository;
}
public static AuthToken getAuthToken()
{
if(authToken == null)
try
{
authToken = getRepository().authTokenCreate("user", "password");
LOG.debug("Created auth token.");
}
catch(OpenAPIException e)
{
LOG.error(e, e);
}
catch(RemoteException e)
{
LOG.error(e, e);
}
else
try
{
getRepository().authTokenValidate(authToken);
}
catch(OpenAPIException e)
{
LOG.info("Auth token was invalid. Recreating auth token");
authToken = null;
return getAuthToken();
}
catch(RemoteException re)
{
LOG.error("Remote exception occured during creation of suth token after determined to be invalid", re);
re.printStackTrace();
authToken = null;
}
return authToken;
}
public static String getAssetXML(String strAssetID)
{
String strAsset = null;
try
{
strAsset = getRepository().assetReadXml(getAuthToken(), Long.parseLong(strAssetID));
}
catch(OpenAPIException e)
{
e.printStackTrace();
}
catch(RemoteException e)
{
e.printStackTrace();
}
return strAsset;
}
}
And all the *.jar files for the imports are inside my AssetExtractor.jar
The command I've been using to load the jar into oracle is:
loadjava -v -f -resolve -resolver "((* OER) (* PUBLIC))" -user oer/***** AssetExtractor.jar
Any ideas would be helpful!
So it appears that if I do the following it solves nearly all my problems:
Edit the Oracle users' .profile to SET and EXPORT the CLASSPATH, PATH, LD_LIBRARY_PATH, ORACLE_HOME, JAVA_HOME with the correct paths
SQLPlus as sys as sysdba
EXEC dbms_java.grant_permission( 'OER', 'SYS:java.util.PropertyPermission', 'java.class.path', 'write' );
OS Commandline as oracle user:
loadjava –v –grant PUBLIC <jar> -user oer/****** for all jars
SQLPlus as OER user
DECLARE
v_classpath VARCHAR2(4000);
v_path VARCHAR2(4000);
BEGIN
v_classpath := DBMS_JAVA.set_property('java.class.path', '/opt/oracle/102/jdk/lib:/mnt/hgfs/vmshare/rex_lib/aler-axis- 1.2.1.jar:/mnt/hgfs/vmshare/rex_lib/aler-axis-jaxrpc-1.2.1.jar:/mnt/hgfs/vmshare/rex_lib/client.rex- 11.1.1.5.0.jar:/mnt/hgfs/vmshare/rex_lib/commons-httpclient-3.0rc2- flashline.jar:/mnt/hgfs/vmshare/rex_lib/log4j-1.2.8.jar');
v_path := DBMS_JAVA.set_property('java.path', '/opt/oracle/102/jdk/bin');
END;
/
alter java source "AssetExtractor" compile;
show errors
The only outstanding issue is that for some reason it still can't locate/resolve some of the Oracle OER classes (which should all be in the client.rex*.jar, I opened and saw them there. If I can solve this part then I'm good to go.

JDBC Lotus-Oracle error: Java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -1

I am using jdbc to connect to an Oracle 10g database. Building the connection in Eclipse/Java works fine. However when I move the code to a Lotus 8.5.2 agent I end up with the following error(s):
Java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -1
at oracle.jdbc.driver.T4CTTIoauthenticate.setSessionFields(T4CTTIoauthenticate.java:1019)
at oracle.jdbc.driver.T4CTTIoauthenticate.<init>(T4CTTIoauthenticate.java:186)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:354)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:454)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:802)
at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection(OracleDataSource.java:298)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:222)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:166)
at JavaAgent.NotesMain(Unknown Source)
at lotus.domino.AgentBase.runNotes(Unknown Source)
at lotus.domino.NotesThread.run(Unknown Source)
This is the code used to connect:
Class.forName("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:#:xx.xx.xx.xx:1521:xx", "xx", "xx");
I have tried to solve this in different ways:
- use the Lotus JVM in eclipse
- use different jdbc jars in eclipse
- use different ways to build the connection in Lotus
- use different jdbc jars jars in lotus
Finally I moved the ojdbc14.jar file Lotus\Notes\jvm\lib\ext directory and it works fine now.
This solution will work, but obviously I prefer to distribute this jar along with the nsf. Is there a way I can make this happen?
As suggested by leyrer. I tried adding the following line to the "/jvm/lib/security/java.policy" file
permission java.security.AllPermission;
This does results in the same error message.
For now I will stick with placing the ojdbc5.jar in the /ext directory.
If you are using the ojdbc jar unpacked, be sure you are not excluding the oracle/sql/converter_xcharset/*.glb files. I was getting this same error when my executable jar was built using Maven, but was not including these files. The block below explicitly includes them.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>unpack-dependencies</goal>
</goals>
<configuration>
<excludeTypes>pom</excludeTypes>
<includes>**/*.class,**/*.glb</includes>
<outputDirectory>${project.build.directory}/classes</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>true</overWriteSnapshots>
</configuration>
</execution>
</executions>
</plugin>
I would guess, that the JVM's Security Manager is not allowing access to the network because the security policy does not specify to allow this action.
See Flying Saucer in Lotus Notes for more details.
Long time ago this issue arise... But I had to discover it for a customer this month. And nowhere I found a solution but some false pretences and incomplete analyses. Therefore and for all of you run into it, I will share my findings, the root cause of the issue and your opportunities to get it solved. I have tested it with the version 11.2.0.4 of the driver (ojdbc6.jar). Further, if your database uses UTF-8 encoding, it seems to work just with the java.policy adjustments. In my case, it was a database with windows 1252 encoding.
First of all, the oracle jdbc driver needs some security adjustments... it's better to set them explicitly and not by permission java.security.AllPermission;. Use this permissions, taken from the ocacle jdbc driver download page (ojdbc.policy file):
permission java.util.PropertyPermission "user.name", "read";
permission java.util.PropertyPermission "oracle.jdbc.*", "read";
permission java.util.PropertyPermission "oracle.net.wallet_location", "read";
permission java.util.PropertyPermission "oracle.net.tns_admin", "read";
permission javax.management.MBeanServerPermission "createMBeanServer";
permission javax.management.MBeanPermission "oracle.jdbc.driver.OracleDiagnosabilityMBean#[com.oracle.jdbc:type=diagnosability,*]", "registerMBean";
permission javax.management.MBeanTrustPermission "register";
After this settings are in place, you will run into the Java.lang.ArrayIndexOutOfBoundsException: Array index out of range: -1 issue. The root cause of that is, the the class loader of java agents (lotus.domino.AgentLoader) does not implement getResource(String name) and that leads to always returning null to the calling method. Since the orcale jdbc driver needs the glb files from the oracle.sql.converter_xcharset folder within the jar to work properly and they were loaded by the getRousource method mentioned above, this will not work! The result is the ArrayIndexOutOfBoundsException.
So the only solutions are either to use the driver from the file system (and use a jvm default class loader) or you change the class loading process as follows:
create a custom class loader:
public class CustomLoader extends ClassLoader {
private final AgentLoader loader;
public CustomLoader(AgentLoader agentLoader, ClassLoader parent) {
super(parent);
loader = agentLoader;
}
#Override
public URL getResource(String name) {
InputStream is = loader.getResourceAsStream(name);
if (is == null) {
return super.getResource(name);
}
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
try {
URL url = new URL("dominoinmemory", "", -1, name, new DominoInMemoryStreamHandler(name));
System.out.println(url);
return url;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
private class DominoInMemoryStreamHandler extends URLStreamHandler {
private String resName;
byte[] content = null;
public DominoInMemoryStreamHandler(String resName) {
this.resName = resName;
}
#Override
protected URLConnection openConnection(final URL u) throws IOException {
if (!u.getProtocol().equals("dominoinmemory"))
throw new IOException("Cannot handle protocol: " + u.getProtocol());
InputStream is = loader.getResourceAsStream(resName);
content = toByteArray(is);
return new URLConnection(u) {
#Override
public int getContentLength() {
if (content != null) {
return content.length;
} else {
return super.getContentLength();
}
}
#Override
public void connect() throws IOException {
if (content != null) {
connected = true;
} else {
throw new IOException("The resource '" + resName + "' was not found");
}
}
#Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(content);
}
};
}
}
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
long count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return output.toByteArray();
}
In the domino agent, before any other operation occurs, change the parent class loader of the AgentLoader with reflection
public void NotesMain() {
try {
AgentLoader agentLoader = (AgentLoader) getClass().getClassLoader();
Field f1 = agentLoader.getClass().getSuperclass().getDeclaredField("parent");
f1.setAccessible(true);
ClassLoader parent = (ClassLoader) f1.get(agentLoader);
f1.set(agentLoader, new CustomLoader(agentLoader, parent));
...
Attention:
Use this at your own risk!
This code required two additional entries in the policy file:
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
permission java.net.NetPermission "specifyStreamHandler";

Categories

Resources