Jsp Connection Error - apache

When im trying to run this code to establish a connection ...... this error is coming
Im using Apache-tomcat-7.0.8
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 1 in the jsp file: /test_conn.jsp
Connection cannot be resolved to a type
1: <% Connection connection = null; try { // Load the JDBC driver String driverName = "oracle.jdbc.driver.OracleDriver"; Class.forName(driverName);
2:
3: // Create a connection to the database
4: String serverName = "URL";
Code I've tried:
<%#page import="java.sql.*,java.io.*,java.text.*,java.util.*" %>
<%#page import="java.util.*" %>
<%
Connection connection = null;
out.println("Before try");
try {
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
out.println("Entered try");
String url = "jdbc:oracle:thin:#:URL:port:sid";
String username = "usr";
String password = "pass";
connection = DriverManager.getConnection(url, username, password);
out.println("Successfully Connected");
}catch (SQLException e) {
out.println("Not Connected: "+ e.getMessage());
}
%>

You should have to use Servlet to write database code however you may import the java.sql package or use the Connection interface with fully qualified package name.
java.sql.Connection connection = null;
EDIT:
You need to copy the .jar (eg. for oracle 10g - ojdbc14.jar) into the WEB-INF/lib folder.

In JSP you forgot to include
<%#page import="java.sql.Connection"%>
Though, this is not good practice. You should write Servlet and DAO class to do this. JSP's are to write HTML.

Related

Connecting to Amazon ActiveMQ with username & password

I'm trying to connect to ActiveMQ Amazon broker via SSL. My application is written in C#.
Previously, I connected via TCP to localhost ActiveMQ broker, which worked:
using Apache.NMS;
using Apache.NMS.ActiveMQ;
using Apache.NMS.ActiveMQ.Commands;
void Connect()
{
String brokerUri = "activemq:tcp://" + host + ":" + port + "? transport.useLogging=true&wireFormat.maxInactivityDuration=0&userName=myUsername&password=myPassword";
NMSConnectionFactory factory = new NMSConnectionFactory(brokerUri);
IConnection connection = factory.CreateConnection();
connection.Start();
}
To connect to ActiveMQ Amazon broker via SSL, I have modified the code in the following way:
void Connect()
{
String brokerUri = "ssl://" + host + ":" + port + "? transport.useLogging=true&wireFormat.maxInactivityDuration=0&userName=myUsername&password=myPassword";
SslTransportFactory transportFactory = new SslTransportFactory();
Uri uri = new Uri(brokerUri);
ITransport transport = transportFactory.CreateTransport(uri);
transport.Command = Command;
transport.Exception = Exception;
transport.Start();
ConnectionFactory factory = new ConnectionFactory(brokerUri);
IConnection connection = factory.CreateConnection();
Connection con = (Connection)connection;
con.ITransport = transport;
con.Start(); => Here the exception is thrown: User name [null] or password is invalid.
}
private void Exception(ITransport sender, Exception command)
{
}
private void Command(ITransport sender, Command command)
{
}
However, upon starting the connection, User name [null] or password is invalid. Exception is thrown.
Please advise.
You're currently passing user credentials via the URI. However, I don't see any reference to username or password in the URI reference documentation. Also, the fact that the exception indicates the user name is null indicates the user credentials in your URI are simply being ignored.
Instead you should pass the user credentials in the CreateConnection method as documented here, e.g.:
IConnection connection = factory.CreateConnection("myUsername", "myPassword");

Access remote git repo via ssh, using libgit2sharp

I'm trying to get a simple working example for cloning or accessing a remote git repository via ssh.
After adding nuget package LibGit2Sharp-SSH v1.0.22, got a .Net Framework v4.6.1 console application like this:
using LibGit2Sharp;
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string localPath = Path.Combine(Path.GetTempPath(), "Example");
string repoPath = "git#example.server.com:Projects/Project1.git";
Repository.Clone(repoPath, localPath, new CloneOptions() { CredentialsProvider = CredentialsHandler });
}
private static Credentials CredentialsHandler(string url, string username, SupportedCredentialTypes types)
{
var sshDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh");
return new SshUserKeyCredentials()
{
Username = username,
Passphrase = string.Empty,
PublicKey = Path.Combine(sshDir, "id_rsa.pub"),
PrivateKey = Path.Combine(sshDir, "id_rsa")
};
}
}
This returns 'Failed to start SSH session: Unable to exchange encryption keys'.
If I use instead
repoPath = "ssh://git#example.server.com:Projects/Project1.git";
Then it throws Malformed URL 'ssh://git#example.server.com:Projects/Project1.git'.
Try to use '/' instead of second ':', to fix 'Malformed URL'
repoPath = "ssh://git#example.server.com/Projects/Project1.git";
As for 'Failed to start SSH session', that's a problem with libgit not LibGit2Sharp, should be tuned on OS level.

Aws-java-sdk from xagent

I'm developing an application in which much of the work interacts with aws S3.
Initial situation:
Domino: Release 9.0.1FP6.
Application on xpages with aws utilities working perfectly with the typical functionalities of readBucket, downloadFile, createBucket etc.
For application needs, due to its weight, I need to separate the logic of the same and try three methods for their separation.
In another database, an agent receives a docID from the main application and executes the order of the requested operations for S3. The mechanism works perfectly, but the memory consumption is unacceptable so it is discarded.
In another new database with the same libraries and classes needed to focus with XAgent based on How to schedule an Xagent from a Domino Java agent? Agent but with the access not ssl that points Per Henrik Lausten. It works fine, but if we load s3 it gives errors.
Console Java:
Starting http://localhost/proves\s3.nsf/demo.xsp
java.lang.NullPointerException --> at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:727)
Console Domino
HTTP JVM: demo.xsp --> beforePageLoad ---> Hello Word
HTTP JVM: CLFAD0211E: Exception thrown. please consult error-log-0.xml
Error-log-0.xml
Exception occurred servicing request for: /proves/s3.nsf/demo.xsp - HTTP Code: 500
IBM_TECHNICAL_SUPPORT\ xpages_exc.log
java.lang.NoClassDefFoundError: com.amazonaws.auth.AWSCredentials
I think the problem may be in using this mechanism because it is not secure, if it is accessed from the browser to demo.xsp it will be running the entire load of aws xon the default credentials.
I test with another SSL-based xagent according to Devin Olson's blog post, Scheduled Xagents, but throw error:
Console Java:
Exception:javax.net.ssl.SSLHandshakeException: com.ibm.jsse2.util.j: No trusted certificate found
Is the separation approach of the logic of the application correct?
Any suggestions as to why the third procedure for SSL is failing?
Thanks in advance
Edit: Hello, the code XAgent (Agent properties security tab=3)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import javax.net.ssl.SSLSocketFactory;
import lotus.domino.AgentBase;
public class JavaAgent extends AgentBase {
// Change these settings below to your setup as required.
static final String hostName = "localhost";
static final String urlFilepath = "/proves/s3.nsf/demo.xsp";
static final int sslPort = 443;
public void NotesMain() {
try {
final SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
final Socket socket = factory.createSocket(JavaAgent.hostName, JavaAgent.sslPort);
final BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
final BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
final StringBuilder sb = new StringBuilder();
sb.append("GET ");
sb.append(JavaAgent.urlFilepath);
sb.append(" HTTP/1.1\n");
final String command = sb.toString();
sb.setLength(0);
sb.append("Host: ");
sb.append(JavaAgent.hostName);
sb.append("\n\n");
final String hostinfo = sb.toString();
out.write(command);
out.write(hostinfo);
out.flush();
in.close();
out.close();
socket.close();
} catch (final Exception e) {
// YOUR_EXCEPTION_HANDLING_CODE
System.out.println("Exception:" + e);
}
}
}
Code demo.xsp
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.beforePageLoad><![CDATA[#{javascript:
print("demo.xsp --> beforePageLoad ---> Hello Word");
var a = new Array();
a[0] = "mybucket-proves";
a[1] = #UserName();
var s3 = new S3();
var vector:java.util.Vector = s3.mainReadBucket(a);
var i=0;
for ( i = 0; i < vector.size(); i++) {
print("Value:" + vector.get(i));
}
}]]></xp:this.beforePageLoad>
<xp:label value="Demo" id="label1"></xp:label>
</xp:view>
New test:
Although the two bd's reside on the same server, I have an SSL Certificate Authority in the JVM in case this is the fault, but it still gives the same error. SSLHandshakeException: com.ibm.jsse2.util.j: No trusted certificate.
Note: I have tested in the main application, where the aws libraries work properly, this agent and demo.xsp page and follow the same error.
Thank you

AbstractMethodError with jTDS JDBC Driver on Tomcat 8

I am deploying a web app (WAR) to a Tomcat 8 web container.
The WAR includes in the '/WEB-INF/lib' directory the following jTDS JDBC driver:
<dependency org="net.sourceforge.jtds" name="jtds" rev="1.3.1" />
(file is: jtds-1.3.1.jar).
This is how the resource is defined in META-INF/context.xml:
<Resource name="jdbc/jtds/sybase/somedb"
auth="Container"
type="javax.sql.DataSource"
driverClassName="net.sourceforge.jtds.jdbc.Driver"
url="jdbc:jtds:sybase://localhost:2501/somedb"
username="someuser" password="somepassword"
/>
In my code I obtain the javax.sql.DataSource the normal way:
InitialContext cxt = new InitialContext();
if ( cxt == null ) {
throw new RuntimeException("Uh oh -- no context!");
}
DataSource ds = (DataSource) cxt.lookup( lookupName );
I further verify (by printing) that the DataSource object ds is of the expected type:
org.apache.tomcat.dbcp.dbcp2.BasicDataSource
… but when I try to get a connection out of it:
Connection conn = ds.getConnection();
… I get the following trace:
java.lang.AbstractMethodError
net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833)
org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:924)
org.apache.tomcat.dbcp.dbcp2.PoolableConnection.validate(PoolableConnection.java:282)
org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:359)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2316)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2299)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2043)
org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1543)
What gives?
Turns out I had to add:
validationQuery="select 1"
in the Resource declaration in context.xml.
This is mentioned here (although mispelled as validateQuery).
Digging into the implementation of JtdsConnection one sees:
/* (non-Javadoc)
* #see java.sql.Connection#isValid(int)
*/
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
throw new AbstractMethodError();
}
This is really weird, I think AbstractMethodError is supposedly thrown by the compiler only, unimplemented methods ought to throw UnsupportedOperationException. At any rate, the following code from PoolableConnection shows why the presence or not of validationQuery in context.xml can change things. Your validationQuery is passed as the value of the sql String parameter in the below method (or null if you don't define a validationQuery):
public void More ...validate(String sql, int timeout) throws SQLException {
...
if (sql == null || sql.length() == 0) {
...
if (!isValid(timeout)) {
throw new SQLException("isValid() returned false");
}
return;
}
...
}
So basically if no validationQuery is present, then the connection's own implementation of isValid is consulted which in the case of JtdsConnection weirdly throws AbstractMethodError.
The answer mentioned above by Marcus worked for me when I encountered this problem. To give a specific example of how the validationQuery setting looks in the context.xml file:
<Resource name="jdbc/myDB" auth="Container" type="javax.sql.DataSource"
driverClassName="net.sourceforge.jtds.jdbc.Driver"
url="jdbc:jtds:sqlserver://SQLSERVER01:1433/mydbname;instance=MYDBINSTANCE"
username="dbuserid" password="dbpassword"
validationQuery="select 1"
/>
The validationQuery setting goes in with each driver setting for your db connections. So each time you add another db entry to your context.xml file, you will need to include this setting with the driver settings.
The above answer works. If you are setting it up for standalone Java application, set the validation query in the datasource.
BasicDataSource ds = new BasicDataSource();
ds.setUsername(user);
ds.setPassword(getPassword());
ds.setUrl(jdbcUrl);
ds.setDriverClassName(driver);
ds.setMaxTotal(10);
ds.setValidationQuery("select 1"); //DBCP throws error without this query

Cassia using impersonation and wcf

I am trying to use Cassia with a WCF web service I keep getting "An existing connection was forcibly closed by the remote host". When I try it on a test console application it works fine. This is the code I am using from a sample I found. Anyone ever do this?
public List<ITerminalServicesSession> getTermminalServerSessions(string serverName)
{
ConnectionDetails connection = new ConnectionDetails();
connection.Domain = "DOMAIN";
connection.Server = serverName;
connection.Username = "USER";
connection.Password = "PASSWORD";
using (ImpersonationHelper.Impersonate(connection))
{
using (var server = GetServer(connection.Server))
{
server.Open();
return server.GetSessions().ToList();
}
}
}