INSERT from servlet throws java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver - sql-server-2005

I am using the code below to connect to a SQL Server 2005 database from a servlet. But it is throwing the following exception:
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
Code Snippet:
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InsertServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
doGet(request,response);
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
EmpDetailBean empdetailbean=new EmpDetailBean();
Connection con=null;
PreparedStatement pstmt2=null;
//ResultSet rs=null;
String employeecode=request.getParameter("employeecode");
pw.println(employeecode);
empdetailbean.setEmployeecode(employeecode);
try
{ //String emp_code=(String)session.getAttribute("empcode");
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//String url = "jdbc:sqlserver://localhost;" +
// "databaseName=test;user=sa;password= ;";
//con=DriverManager.getConnection("Jdbc:Odbc:leave1");
con=DriverManager.getConnection("jdbc:sqlserver://10.217.7.3;databaseName=test;user=sa;password=123;");
String query1="insert into leavetype(dbo.empcode) values(?)";
pstmt2=con.prepareStatement(query1);
pstmt2.setString(1,empdetailbean.getEmployeecode());
int k=pstmt2.executeUpdate();
System.out.println(k);
pstmt2.close();
}
catch(Exception e)
{ pw.println("exception"+ e);
}
}
}
the log file shows
May 2, 2012 11:34:19 AM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
May 2, 2012 11:34:19 AM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()

If you want to use com.microsoft.sqlserver.jdbc.SQLServerDriver as Driver then sqljdbc.jar is required to be
present in your classpath which is WEB-INF\lib.
If you want to user Jtds Driver Check this link for Driver and databse URL

Seems that the Jar file for the JDBC Connectivity is missing from the war file that you have deployed. could you please ensure that the lib files are getting packaged with war file properly

Related

Error while running documentum code

I am getting an error while running the documentum code at:
config.setString("primary_host", docbroker);
in the below code:
IDfClient client = DfClient.getLocalClient();
// getting the config object of local client
IDfTypedObject config = client.getClientConfig();
config.setString("primary_host", docbroker);
IDfLoginInfo li = new DfLoginInfo();
and the error I was getting is below:
Error:
java.lang.IllegalStateException: Reference count is already zero
at com.documentum.fc.impl.util.ReferenceCountManager.decrement(ReferenceCountManager.java:47)
at com.documentum.fc.client.impl.docbroker.DocbrokerMapUnion.decrementReferenceCount(DocbrokerMapUnion.java:43)
at com.documentum.fc.client.impl.docbroker.DocbrokerMapUnion.removeEntry(DocbrokerMapUnion.java:37)
at com.documentum.fc.client.impl.docbroker.DocbrokerMap.removeEntries(DocbrokerMap.java:176)
at com.documentum.fc.client.impl.docbroker.DocbrokerClient$PreferencesObserver.update(DocbrokerClient.java:251)
at com.documentum.fc.common.impl.preferences.TypedPreferences.notifyObservers(TypedPreferences.java:559)
at com.documentum.fc.common.impl.preferences.TypedPreferences.setString(TypedPreferences.java:168)
at com.gsk.rd.datacoe.dataspider.FetchDocumentumStats.connectToDocumentum(FetchDocumentumStats.java:357)
at com.gsk.rd.datacoe.dataspider.FetchDocumentumStats.run(FetchDocumentumStats.java:92)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Please can anyone help me. I am new to documentum.
From my experience, it is best to use the IDfClientX interface and work your way from there. Perhaps this example will help you:
// This is just an example. You might want to encapsulate this functionality in a class of your own
import com.documentum.com.DfClientX;
import com.documentum.com.IDfClientX;
import com.documentum.fc.client.IDfClient;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.client.IDfSessionManager;
import com.documentum.fc.client.IDfTypedObject;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.IDfLoginInfo;
public class Main {
public static void main(String[] args) throws DfException {
IDfClientX clientX = new DfClientX();
IDfClient client = clientX.getLocalClient();
IDfTypedObject clientConfig = client.getClientConfig();
IDfLoginInfo loginInfo = clientX.getLoginInfo();
IDfSessionManager sessionManager = client.newSessionManager();
IDfSession session = connect(clientConfig, loginInfo, sessionManager, "<your host here>", 1489, "<your docbase here>", "<your username here>", "<your password here>");
// Do something with session
}
public static IDfSession connect(IDfTypedObject clientConfig, IDfLoginInfo loginInfo, IDfSessionManager sessionManager, String host, int port, String docbase, String user, String password) throws DfException {
clientConfig.setString("primary_host", host);
clientConfig.setInt("primary_port", port);
loginInfo.setUser(user);
loginInfo.setPassword(password);
sessionManager.clearIdentities();
sessionManager.setIdentity(docbase, loginInfo);
return sessionManager.getSession(docbase);
}
}

Apache camel write to rabbitmq

I am trying to read data from a file and write to a rabbitmq queue using apache camel but ending up with the error
Exception in thread "main" org.apache.camel.FailedToCreateRouteException: Failed to create route route1 at: >>> To[rabbitmq://localhost:15672?queue=hello] <<< in route: Route(route1)[[From[file://target/?fileName=doctor.txt&chars... because of Failed to resolve endpoint: rabbitmq://localhost:15672?queue=hello due to: No URI path as the exchangeName for the RabbitMQEndpoint, the URI is rabbitmq://localhost:15672?queue=hello
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:945)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:187)
at org.apache.camel.impl.DefaultCamelContext.startRoute(DefaultCamelContext.java:794)
at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:2184)
at org.apache.camel.impl.DefaultCamelContext.doStartCamel(DefaultCamelContext.java:1916)
at org.apache.camel.impl.DefaultCamelContext.doStart(DefaultCamelContext.java:1777)
at org.apache.camel.support.ServiceSupport.start(ServiceSupport.java:61)
at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:1745)
at test.RMQCamelSender.main(RMQCamelSender.java:38)
Caused by: org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: rabbitmq://localhost:15672?queue=hello due to: No URI path as the exchangeName for the RabbitMQEndpoint, the URI is rabbitmq://localhost:15672?queue=hello
at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:545)
at org.apache.camel.util.CamelContextHelper.getMandatoryEndpoint(CamelContextHelper.java:71)
at org.apache.camel.model.RouteDefinition.resolveEndpoint(RouteDefinition.java:202)
at org.apache.camel.impl.DefaultRouteContext.resolveEndpoint(DefaultRouteContext.java:106)
at org.apache.camel.impl.DefaultRouteContext.resolveEndpoint(DefaultRouteContext.java:112)
at org.apache.camel.model.SendDefinition.resolveEndpoint(SendDefinition.java:61)
at org.apache.camel.model.SendDefinition.createProcessor(SendDefinition.java:55)
at org.apache.camel.model.ProcessorDefinition.makeProcessor(ProcessorDefinition.java:500)
at org.apache.camel.model.ProcessorDefinition.addRoutes(ProcessorDefinition.java:213)
at org.apache.camel.model.RouteDefinition.addRoutes(RouteDefinition.java:942)
... 8 more
Caused by: java.lang.IllegalArgumentException: No URI path as the exchangeName for the RabbitMQEndpoint, the URI is rabbitmq://localhost:15672?queue=hello
at org.apache.camel.component.rabbitmq.RabbitMQComponent.createEndpoint(RabbitMQComponent.java:50)
at org.apache.camel.component.rabbitmq.RabbitMQComponent.createEndpoint(RabbitMQComponent.java:31)
at org.apache.camel.impl.DefaultComponent.createEndpoint(DefaultComponent.java:122)
at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:525)
... 17 more
Following are my implementations of the classes which are creating camel context and rabbitmq queue.
RMQCamleSender.java
package test;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import test.Producer;
public class RMQCamelSender {
public static void main(String[] argv) throws Exception {
Producer queueProd = new Producer();
queueProd.setupConnection();
System.out.println(queueProd.toString());
CamelContext context = new DefaultCamelContext();
context.addRoutes(new RouteBuilder() {
public void configure() throws Exception {
System.out.println("hello world");
from("file://target/?fileName=doctor.txt&charset=utf-8")
.process(new Processor() {
public void process(Exchange msg) throws Exception {
System.out.println(msg.getIn().getBody(
String.class));
}
}).to("rabbitmq://localhost:15672?queue=hello");
}
});
context.start();
Thread.sleep(4000);
context.stop();
}
}
Producer.java
package test;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
public class Producer {
public static final String QUEUE_NAME = "hello";
public static Connection connection;
public void setupConnection() throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
}
}
The program is working fine if I am not using Camel and trying to contact the queue using standard rabbitmq library.
The error message is pretty indicative: you are missing the exchange name in your endpoint URI, it cannot be blank, as the official Camel documentation says it has to follow the given format:
rabbitmq://hostname[:port]/exchangeName?[options]
I suggest you try using the amq.direct exchange (for more details, refer to the official RabbitMQ documentation), like so:
public void configure() throws Exception {
System.out.println("hello world");
from("file://target/?fileName=doctor.txt&charset=utf-8")
.process(new Processor() {
public void process(Exchange msg) throws Exception {
System.out.println(msg.getIn().getBody(String.class));
}
}).to("rabbitmq://localhost:5672/amq.direct?routingKey=hello");
}
Additionally, you are using 15672 port, which is by default the port for RabbitMQ's web management console, I guess you haven't changed the default settings so the port needs to be 5672. You also have to use the routingKey parameter instead of the queue one since in RabbitMQ semantics you publish to exchange:routingKey and only consume from queues.
You need to include the rabbitmq exchange name. It is missing from here;
.to("rabbitmq://localhost:15672?queue=hello");
It should be something like this:
.to("rabbitmq://localhost:15672/exchangeName?routingKey=hello");
Also, if you are sending to exchange, why do you want to specify a queue? You need only to specify the routing key and the exchange will send to that queue if there is a binding for that routing key.

UserPrivilegedException, while creating a directory in HDFS as a specific user, through JAVA

I a'm using CDH 4.7. I am trying to create a folder in HDFS in /user/cloudera. But the UserPrivilegedException is thrown. Below is my code (#copied)
public static void main(String args[]) {
try {
UserGroupInformation ugi =
UserGroupInformation.createProxyUser("cloudera", UserGroupInformation.getLoginUser());
System.out.println(ugi.getUserName());
ugi.doAs(new PrivilegedExceptionAction<Void>() {
public Void run() throws Exception {
System.out.println("aaa");
Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://localhost.localdomain:8020/user/cloudera");
conf.set("hadoop.job.ugi", "cloudera");
FileSystem fs = FileSystem.get(conf);
fs.createNewFile(new Path("/user/cloudera/test"));
Path path = new Path("/user/cloudera/Hbasesyntax.txt");
FileStatus[] status = fs.listStatus(path);
for(int i=0;i<status.length;i++){
System.out.println(status[i].getPath());
}
return null;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Then, I even tried accessing the file (Hbasesyntax.txt) which I -put through the terminal. But, not able to get the file information from that too. Am I missing anything.
Below is the exception thrown:
Feb 23, 2015 1:18:27 AM org.apache.hadoop.security.UserGroupInformation doAs
SEVERE: **PriviledgedActionException as:cloudera via cloudera cause:java.io.IOException: Mkdirs failed to create /user/cloudera
java.io.IOException: Mkdirs failed to create /user/cloudera
at** org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:378)
at org.apache.hadoop.fs.ChecksumFileSystem.create(ChecksumFileSystem.java:364)
at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:564)
at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:545)
at org.apache.hadoop.fs.FileSystem.create(FileSystem.java:507)
at org.apache.hadoop.fs.FileSystem.createNewFile(FileSystem.java:647)
at HDFSFileOperations.GetIntoFS$1.run(GetIntoFS.java:32)
at HDFSFileOperations.GetIntoFS$1.run(GetIntoFS.java:1)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:396)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1 190)
at HDFSFileOperations.GetIntoFS.main(GetIntoFS.java:21)

How to set a connection from eclipse to SQLServer?

I am trying to connect to SQL Server from eclipse and i get the following error. I mention that i verified and the SQL Server Browser is running on the host and i have no firewall active.
com.microsoft.sqlserver.jdbc.SQLServerException: The connection to the host
LAURA-PC, 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.
This is the code i've written:
import java.sql.*;
public class ConnectSQLServer {
public void connect(String url){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection connection = DriverManager.getConnection(url);
System.out.println("Connected");
Statement statement = connection.createStatement();
String query = "select * from Vehicle where Mileage < 50000";
ResultSet rs = statement.executeQuery(query);
while(rs.next()){
System.out.println(rs.getString(1));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ConnectSQLServer connServer = new ConnectSQLServer();
String url = "jdbc:sqlserver://LAURA-PC\\SQLEXPRESS;databaseName=Register;integratedSecurity=true";
connServer.connect(url);
}
}
First thing before DB programming. Test each "step". Before executing any query or even writing any other code, please check if you can connect to the DB. I assume that you are connecting to the local db. For steps on making your connection URL, see - http://technet.microsoft.com/en-us/library/ms378428.aspx
Try changing your URL to - jdbc:sqlserver://localhost;user=Mine;password=Secret;databaseName=MyDB. I tried this code and it worked.
import java.sql.*;
public class ConnectSQLServer {
public void connect(String url){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection connection = DriverManager.getConnection(url);
System.out.println("Connected");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ConnectSQLServer connServer = new ConnectSQLServer();
String url = "jdbc:sqlserver://localhost;user=Mine;password=Secret;databaseName=AdventureWorks";
connServer.connect(url);
}
}
Just ENABLE/START SQL Server Browser and copy sqljdbc_auth.dll file to Windows->System32 by extracting this file from ( Microsoft jdbc driver 9.2 for sql server )

Selenium - Exception while executing selenium.stop()

I am using Selenium for web application testing. After having finished all the testing, when the command "selenium.stop()" is executed I get the following exception:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:760)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
at com.thoughtworks.selenium.HttpCommandProcessor.getResponseCode(HttpCommandProcessor.java:134)
at com.thoughtworks.selenium.HttpCommandProcessor.getCommandResponseAsString(HttpCommandProcessor.java:154)
at com.thoughtworks.selenium.HttpCommandProcessor.executeCommandOnServlet(HttpCommandProcessor.java:97)
at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:79)
at com.thoughtworks.selenium.HttpCommandProcessor.stop(HttpCommandProcessor.java:242)
at com.thoughtworks.selenium.DefaultSelenium.stop(DefaultSelenium.java:111)
at seleniumproject.orkut.tearDown(orkut.java:54)
at junit.framework.TestCase.runBare(TestCase.java:140)
at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
at junit.framework.TestResult$1.protect(TestResult.java:110)
E
at junit.framework.TestResult.runProtected(TestResult.java:128)
Time: 63.453
There was 1 error:
1) testOrkut(seleniumproject.orkut)java.lang.UnsupportedOperationException: Catch body broken: IOException from cmd=testComplete -> java.net.ConnectException: Connection refused: connect
at com.thoughtworks.selenium.HttpCommandProcessor.executeCommandOnServlet(HttpCommandProcessor.java:100)
at com.thoughtworks.selenium.HttpCommandProcessor.doCommand(HttpCommandProcessor.java:79)
at com.thoughtworks.selenium.HttpCommandProcessor.stop(HttpCommandProcessor.java:242)
at com.thoughtworks.selenium.DefaultSelenium.stop(DefaultSelenium.java:111)
at seleniumproject.orkut.tearDown(orkut.java:54)
at com.thoughtworks.selenium.SeleneseTestCase.runBare(SeleneseTestCase.java:212)
at seleniumproject.orkut.main(orkut.java:57)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at junit.framework.TestResult.run(TestResult.java:113)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at junit.framework.TestCase.run(TestCase.java:124)
at java.net.Socket.connect(Socket.java:519)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at java.net.Socket.connect(Socket.java:469)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at junit.framework.TestSuite.run(TestSuite.java:227)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at junit.textui.TestRunner.doRun(TestRunner.java:116)
at junit.textui.TestRunner.doRun(TestRunner.java:109)
at junit.textui.TestRunner.run(TestRunner.java:77)
at seleniumproject.orkut.main(orkut.java:57)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:760)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1049)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:373)
at com.thoughtworks.selenium.HttpCommandProcessor.getResponseCode(HttpCommandProcessor.java:134)
at com.thoughtworks.selenium.HttpCommandProcessor.getCommandResponseAsString(HttpCommandProcessor.java:154)
at com.thoughtworks.selenium.HttpCommandProcessor.executeCommandOnServlet(HttpCommandProcessor.java:97)
... 16 more
Here's is code which is executing the stop() command
public class orkut extends SeleneseTestCase {
public void setUp() throws Exception {
setUp("https://www.google.com/");
}
public void testOrkut() throws Exception {
Parser parser = new Parser();
try {
.......
.......
.......
}catch(Exception ex) {
}finally {
parser.closeConnection();
selenium.shutDownSeleniumServer();
}
}
public static Test suite() {
return new TestSuite(orkut.class);
}
public void tearDown(){
selenium.stop();
}
public static void main(String args[]) {
junit.textui.TestRunner.run(suite());
}
}
It looks like your shutting down the Selenium server before the command to close the browser session. Try commenting out the line with selenium.shutDownSeleniumServer();
I was getting the same error. I cleared my jar files and re-added them and the exception was gone.