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;
}
}
Related
Project details:
| mysql-connector-java version : 8.0.27 |
| JDK version : 15.0.1 |
I am unable to make a connection to the MySQL database hosted on docker using Java. I have attached my code below for reference.
Note : I am able to make a connection to the database using python instead of java while making no changes to the connection details whatsoever. This problem only persists with java.
`
import java.sql.*;
public class TestJDBCMySQL
{ public static void main(String[] args)
{ String url = "jdbc:mysql://localhost/workson";
String uid = "retracted";
String pw = "retracted";
try ( Connection con = DriverManager.getConnection(url, uid, pw);
Statement stmt = con.createStatement();)
{
ResultSet rst = stmt.executeQuery("SELECT ename,salary FROM emp");
System.out.println("Employee Name,Salary");
while (rst.next())
{ System.out.println(rst.getString("ename")+","+rst.getDouble("salary"));
}
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex);
}
}
}
`
What I've done so far :
Creating a new user and granting all privileges using MySQL workbench
Verifying credentials. I was able to connect to the database using the docker cli with the exact same credentials.
Ensuring the database exists ( it does )
Add the mysql-connector-java to the reference library in VsCode
Specifying the port in the connection URL
Question has been updated (The DriverManager is no longer loaded manually and instead the getConnection() method is used):
package guii;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* This program demonstrates how to establish database connection to Microsoft
* SQL Server.
* #author www.codejava.net
*
*/
public class JdbcSQLServerConnection {
public static void main(String[] args) {
Connection conn = null;
try {
String dbURL = "jdbc:sqlserver://ASUS\\YES:1433";
String user = "TestingUser";
String pass = "12345";
conn = DriverManager.getConnection(dbURL, user, pass);
if (conn != null) {
DatabaseMetaData dm = (DatabaseMetaData) conn.getMetaData();
System.out.println("Driver name: " + dm.getDriverName());
System.out.println("Driver version: " + dm.getDriverVersion());
System.out.println("Product name: " + dm.getDatabaseProductName());
System.out.println("Product version: " + dm.getDatabaseProductVersion());
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
The problem is the resulting Exception of this code. I can't find out know the reason why that particular exception is thrown.
The username, password and servername were double checked and they are definitively correct.
Currently this exception is thrown:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'TestingUser'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:196)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:83)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2532)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:1929)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:1917)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4026)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1416)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1061)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:833)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:716)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:841)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at guii.JdbcSQLServerConnection.main(JdbcSQLServerConnection.java:25)
Trouble Shooting Notes
Use integratedSecurity=true again
Check if you have the sqljdbc_auch.dll in your system32 folder
Check out this link
Make sure you use the correct one (32 vs 64 bit)
Make sure the sqljdbc_auch.dll is in the Windows system path
Check if the properties of your Server instance are set correctly: access rights, make sure it actually listens in the port 1433, ...
check out this link and don't just look at the accepted answer but the other two as well.
make sure your firewall does not prevent any connections
check out if your Java Version matches the jdbc Version you use sqljdbc4.2 needs Java 1.8, jdbc4.1 needs java 1.7. look here
previously i using this code to connect my database there is non error occur.
but comes to this DA files, its unable to connect to database.
i had go through most of the post but some of it i don't understand.[i'm just new to java]
i had try to use jdbc:derby://localhost:1527/societydb;create=true
but the same error occur again.
here's the code and <<< is the line the error point to.
private String host = "jdbc:derby://localhost:1527/societydb";
private String user = "nbuser";
private String password = "nbuser";
private String tableName = "MEMBER";
private void createConnection() {
try {
conn = DriverManager.getConnection(host, user, password);
System.out.println("*** Successfully established the connection to database. ***");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
public ArrayList<Member> getMember() {
ArrayList<Member> memArray = new ArrayList<>();
try {
stmt = conn.prepareStatement("SELECT * FROM " + tableName);//<<< error pointing to here
ResultSet rs = stmt.executeQuery();
while (rs.next()){
Member m = new Member(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5), rs.getString(6), rs.getString(7), rs.getString(8), rs.getInt(9), rs.getString(10), rs.getString(11));
memArray.add(m);}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), "Error Message", JOptionPane.ERROR_MESSAGE);
}
return memArray;
}
From Java documentation the drivers you need are org.apache.derby.jdbc.EmbeddedDriver and org.apache.derby.jdbc.ClientDriver.
Also it clearly states
Any JDBC 4.0 drivers that are found in your class path are automatically loaded.(However,
you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)
Note : JDBC 4.0 comes as a default package from Java 7 onwards.
As for your problem search for the classes mentioned above in your class path(Ctrl + N in Intellij Idea or Ctrl + R in Eclipse). If these classes are not present google them, download and add the jar files to your class path.
Just add these external jars:
derby.jar
derbyclient.jar
How to do it:
right click your project > Properties > Java Build Path > Libraries
click 'Add external jar'
go to C:\Program Files\Java\jdk1.8.0_65\db\lib
add the derby.jar and derbyclient.jar
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.
I'm currently working on a SalesForce.com tutorial entitled Force.com for Google App Engine for Java: Getting Started
I've installed the Google Eclipse Plugin, downloaded the libraries, and entered the "Hello World App" (as seen on the tutorial page):
package com.force;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.*;
import java.util.logging.*;
import com.sforce.ws.*;
import com.sforce.soap.partner.*;
import com.sforce.soap.partner.sobject.SObject;
#SuppressWarnings("serial")
public class HelloWorldServlet extends HttpServlet {
private static final Logger log = Logger.getLogger(HelloWorldServlet.class.getName());
private String username = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private String password = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private PartnerConnection connection;
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html");
resp.getWriter().println("Hello, world. this is a test2");
PrintWriter t = resp.getWriter();
getConnection( t, req);
if ( connection == null ) { return; }
QueryResult result = null;
try {
result = connection.query( "select id, name, phone from Account order by LastModifiedDate desc limit 10 ");
} catch (ConnectionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (SObject account : result.getRecords()) {
t.println("<li>"+ (String)account.getField("Name") + "</li>");
}
}
void getConnection(PrintWriter out, HttpServletRequest req) {
try {
// build up a ConnectorConfig from a sid
String sessionid = req.getParameter("sid");
String serverurl = req.getParameter("srv");
if ( connection == null ) {
out.println("<p>new connection needed</p>");
// login to the Force.com Platform
ConnectorConfig config = new ConnectorConfig();
if ( sessionid != null && serverurl != null) {
config.setServiceEndpoint(serverurl);
config.setSessionId(sessionid);
config.setManualLogin(false);
out.println("using session from query string");
} else {
config.setUsername(username);
config.setPassword(password);
}
connection = Connector.newConnection(config);
out.println( connection.getConfig().getSessionId() );
out.println( connection.getConfig().getServiceEndpoint() );
} else {
out.println("<p> reuse existing connection");
out.println( connection.getConfig().getSessionId() );
}
log.warning("Connection SID " +connection.getConfig().getSessionId());
} catch ( ConnectionException ce) {
log.warning("ConnectionException " +ce.getMessage());
out.println( ce.getMessage() + " s " + ce.getClass() );
}
}
}
When I run the application as a "Web Application" I get the following in the console:
Initializing AppEngine server
Logging to JettyLogger(null) via com.google.apphosting.utils.jetty.JettyLogger
Successfully processed D:\education\java\HelloWorldOriginal\war\WEB-INF/appengine-web.xml
Successfully processed D:\education\java\HelloWorldOriginal\war\WEB-INF/web.xml
The server is running at http://localhost:8888/
Warning: default mime table not found: C:\devtool\Java\jre6\lib\content-types.properties
When I try to visit http://localhost:8080/ , I see:
Oops! Google Chrome could not connect to localhost:8080
Did you mean: localhost-8080.com
Additional suggestions:
Try reloading: localhost:8080
Search on Google:
Google Chrome Help - Why am I seeing this page?
©2011 Google - Google Home
But when I visit http://localhost:8888/ , I get:
Web Application Starter Project
Please enter your name:
Send
(Which, also isn't the desired or expected outcome.)
What is this content-type.properties that I'm missing and how can I fix it? Or is that just a symptom of a greater problem?
Have you checked that your web.xml directs requests for / to the appropriate handler class? Just writing the class isn't enough - you have to make sure that incoming requests are directed to it.