Getting java.io.IOException when running JUnit test case in Eclipse - junit

Here's my code
public class JWebUnitTest extends WebTestCase {
public JWebUnitTest(String name) {
super(name);
}
public void setUp() {
getTestContext().setBaseUrl("http://www.google.com");
}
public void testSearch() {
beginAt("/");
setFormElement("q", "httpunit");
submit("btnG");
clickLinkWithText("HttpUnit");
assertTitleEquals("HttpUnit");
assertLinkPresentWithText("User's Manual");
}
}
In the Failure Trace, I see the following error:
java.lang.RuntimeException: java.io.IOException
(moving down..)
Caused by: java.net.SocketException: Operation timed out: connect: could be due to invalid address
Why is "http://www.google.com/" an invalid address?
Why am I getting this IOException?

Since you classified this as "in Eclipse", is this only happening within Eclipse? Can you try running the same outside of Eclipse?
Assuming you have network connectivity to http://www.google.com with a web browser on the same machine, it is likely a proxy issue. Either you need a proxy, and the JVM isn't configured to use one - or you don't need a proxy, and the JVM is being configured to use one. (Are you running this on a corporate or other organizational network?) See http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html for details on how to do this.

I would suggest you to try any of these options
1.) Clean the project once . Project - Clean (in Eclipse) and rebuild
2.) Try updating your eclipse to latest version
3.) Try to hit your localhost server (This will show whether theres really a problem with ur code or with eclipse)
4.) You should be needing a proxy. So configure accordingly

Related

connecting MySQL using wamp and hibernate in eclipse [duplicate]

I'm trying to add a database-enabled JSP to an existing Tomcat 5.5 application (GeoServer 2.0.0, if that helps).
The app itself talks to Postgres just fine, so I know that the database is up, user can access it, all that good stuff. What I'm trying to do is a database query in a JSP that I've added. I've used the config example in the Tomcat datasource example pretty much out of the box. The requisite taglibs are in the right place -- no errors occur if I just have the taglib refs, so it's finding those JARs. The postgres jdbc driver, postgresql-8.4.701.jdbc3.jar is in $CATALINA_HOME/common/lib.
Here's the top of the JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<sql:query var="rs" dataSource="jdbc/mmas">
select current_validstart as ValidTime from runoff_forecast_valid_time
</sql:query>
The relevant section from $CATALINA_HOME/conf/server.xml, inside the <Host> which is in turn within <Engine>:
<Context path="/gs2" allowLinking="true">
<Resource name="jdbc/mmas" type="javax.sql.Datasource"
auth="Container" driverClassName="org.postgresql.Driver"
maxActive="100" maxIdle="30" maxWait="10000"
username="mmas" password="very_secure_yess_precious!"
url="jdbc:postgresql//localhost:5432/mmas" />
</Context>
These lines are the last in the tag in webapps/gs2/WEB-INF/web.xml:
<resource-ref>
<description>
The database resource for the MMAS PostGIS database
</description>
<res-ref-name>
jdbc/mmas
</res-ref-name>
<res-type>
javax.sql.DataSource
</res-type>
<res-auth>
Container
</res-auth>
</resource-ref>
Finally, the exception:
exception
org.apache.jasper.JasperException: Unable to get connection, DataSource invalid: "java.sql.SQLException: No suitable driver"
[...wads of ensuing goo elided]
The infamous java.sql.SQLException: No suitable driver found
This exception can have basically two causes:
1. JDBC driver is not loaded
In case of Tomcat, you need to ensure that the JDBC driver is placed in server's own /lib folder.
Or, when you're actually not using a server-managed connection pool data source, but are manually fiddling around with DriverManager#getConnection() in WAR, then you need to place the JDBC driver in WAR's /WEB-INF/lib and perform ..
Class.forName("com.example.jdbc.Driver");
.. in your code before the first DriverManager#getConnection() call whereby you make sure that you do not swallow/ignore any ClassNotFoundException which can be thrown by it and continue the code flow as if nothing exceptional happened. See also Where do I have to place the JDBC driver for Tomcat's connection pool?
Other servers have a similar way of placing the JAR file:
GlassFish: put the JAR file in /glassfish/lib
WildFly: put the JAR file in /standalone/deployments
2. Or, JDBC URL is in wrong syntax
You need to ensure that the JDBC URL is conform the JDBC driver documentation and keep in mind that it's usually case sensitive. When the JDBC URL does not return true for Driver#acceptsURL() for any of the loaded drivers, then you will also get exactly this exception.
In case of PostgreSQL it is documented here.
With JDBC, a database is represented by a URL (Uniform Resource Locator). With PostgreSQL™, this takes one of the following forms:
jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database
In case of MySQL it is documented here.
The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] » [?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
In case of Oracle it is documented here.
There are 2 URL syntax, old syntax which will only work with SID and the new one with Oracle service name.
Old syntax jdbc:oracle:thin:#[HOST][:PORT]:SID
New syntax jdbc:oracle:thin:#//[HOST][:PORT]/SERVICE
See also:
Where do I have to place the JDBC driver for Tomcat's connection pool?
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
How should I connect to JDBC database / datasource in a servlet based application?
What is the difference between "Class.forName()" and "Class.forName().newInstance()"?
Connect Java to a MySQL database
I've forgot to add the PostgreSQL JDBC Driver into my project (Mvnrepository).
Gradle:
// http://mvnrepository.com/artifact/postgresql/postgresql
compile group: 'postgresql', name: 'postgresql', version: '9.0-801.jdbc4'
Maven:
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.0-801.jdbc4</version>
</dependency>
You can also download the JAR and import to your project manually.
url="jdbc:postgresql//localhost:5432/mmas"
That URL looks wrong, do you need the following?
url="jdbc:postgresql://localhost:5432/mmas"
I faced the similar issue.
My Project in context is Dynamic Web Project(Java 8 + Tomcat 8) and error is for PostgreSQL Driver exception: No suitable driver found
It got resolved by adding Class.forName("org.postgresql.Driver") before calling getConnection() method
Here is my Sample Code:
try {
Connection conn = null;
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/?preferQueryMode="
+ sql_auth,sql_user , sql_password);
} catch (Exception e) {
System.out.println("Failed to create JDBC db connection " + e.toString() + e.getMessage());
}
I found the followig tip helpful, to eliminate this issue in Tomcat -
be sure to load the driver first doing a Class.forName("
org.postgresql.Driver"); in your code.
This is from the post - https://www.postgresql.org/message-id/e13c14ec050510103846db6b0e#mail.gmail.com
The jdbc code worked fine as a standalone program but, in TOMCAT it gave the error -'No suitable driver found'
No matter how old this thread becomes, people would continue to face this issue.
My Case: I have the latest (at the time of posting) OpenJDK and maven setup. I had tried all methods given above, with/out maven and even solutions on sister posts on StackOverflow. I am not using any IDE or anything else, running from bare CLI to demonstrate only the core logic.
Here's what finally worked.
Download the driver from the official site. (for me it was MySQL https://www.mysql.com/products/connector/). Use your flavour here.
Unzip the given jar file in the same directory as your java project. You would get a directory structure like this. If you look carefully, this exactly relates to what we try to do using Class.forName(....). The file that we want is the com/mysql/jdbc/Driver.class
Compile the java program containing the code.
javac App.java
Now load the director as a module by running
java --module-path com/mysql/jdbc -cp ./ App
This would load the (extracted) package manually, and your java program would find the required Driver class.
Note that this was done for the mysql driver, other drivers might require minor changes.
If your vendor provides a .deb image, you can get the jar from /usr/share/java/your-vendor-file-here.jar
Summary:
Soln2 (recommend)::
1 . put mysql-connector-java-8.0.28.jar file in the <where you install your Tomcat>/lib.
Soln1::
1 . put mysql-connector-java-8.0.28.jar file in the WEB-INF/lib.
2 . use Class.forName("com.mysql.cj.jdbc.Driver"); in your Servlet Java code.
Soln1 (Ori Ans) //-20220304
In short:
make sure you have the mysql-connector-java-8.0.28.jar file in the WEB-INF/lib
make sure you use the Class.forName("com.mysql.cj.jdbc.Driver");
additional notes (not important), base on my trying (could be wrong)::
1.1 putting the jar directly inside the Java build path doesnt work
1.2. putting the jar in Data management > Driver Def > MySQL JDBC Driver > then add it as library to Java Build path doesnt work.
1.3 => it has to be inside the WEB-INF/lib (I dont know why)
1.4 using version mysql-connector-java-8.0.28.jar works, only version 5.1 available in Eclipse MySQL JDBC Driver setting doesnt matter, ignore it.
<see How to connect to MySql 8.0 database using Eclipse Database Management Perspective >
Class.forName("com.mysql.cj.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver");
both works,
but the Class.forName("com.mysql.jdbc.Driver"); is deprecated.
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
<see https://www.yawintutor.com/no-suitable-driver-found-for-jdbcmysql-localhost3306-testdb/ >
If you want to connect to a MySQL database, you can use the type-4 driver named Connector/} that's available for free from the MySQL website. However, this driver is typically included in Tomcat's lib directory. As a result, you don't usually need to download this driver from the MySQL site.
-- Murach’s Java Servlets and JSP
I cant find the driver in Tomcat that the author is talking about, I need to use the mysql-connector-java-8.0.28.jar.
<(striked-out) see updated answer soln2 below>
If you're working with an older version of Java, though, you need to use the forName method of the Class class to explicitly load the driver before you call the getConnection method
Even with JDBC 4.0, you sometimes get a message that says, "No suitable driver found." In that case, you can use the forName method of the Class class to explicitly load the driver. However, if automatic driver loading works, it usually makes sense to remove this method call from your code.
How to load a MySQL database driver prior to JDBC 4.0
Class.forName{"com.mysql.jdbc.Driver");
-- Murach’s Java Servlets and JSP
I have to use Class.forName("com.mysql.cj.jdbc.Driver"); in my system, no automatic class loading. Not sure why.
<(striked-out) see updated answer soln2 below>
When I am using a normal Java Project instead of a Dynamic Web Project in Eclipse,
I only need to add the mysql-connector-java-8.0.28.jar to Java Build Path directly,
then I can connect to the JDBC with no problem.
However, if I am using Dynamic Web Project (which is in this case), those 2 strict rules applies (jar position & class loading).
<see TOMCAT ON ECLIPSE java.sql.SQLException: No suitable driver found for jdbc:mysql >
Soln2 (Updated Ans) //-20220305_12
In short:
1 . put mysql-connector-java-8.0.28.jar file in the <where you install your Tomcat>/lib.
eg: G:\pla\Java\apache-tomcat-10.0.16\lib\mysql-connector-java-8.0.28.jar
(and for an Eclipse Dynamic Web Project, the jar will then be automatically put inside in your project's Java build path > Server Runtime [Apache Tomcat v10.0].)
Additional notes::
for soln1::
put mysql-connector-java-8.0.28.jar file in the WEB-INF/lib.
use Class.forName("com.mysql.cj.jdbc.Driver"); in your Servlet Java code.
this will create an WARNING:
WARNING: The web application [LearnJDBC] appears to have started a thread named [mysql-cj-abandoned-connection-cleanup] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
<see The web application [] appears to have started a thread named [Abandoned connection cleanup thread] com.mysql.jdbc.AbandonedConnectionCleanupThread >
and that answer led me to soln2.
for soln2::
put mysql-connector-java-8.0.28.jar file in the <where you install your Tomcat>/lib.
this will create an INFO:
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
you can just ignore it.
<see How to fix "JARs that were scanned but no TLDs were found in them " in Tomcat 9.0.0M10 >
(you should now understand what Murach’s Java Servlets and JSP was talking about: the jar in Tomcat/lib & the no need for Class.forName("com.mysql.cj.jdbc.Driver");)
to kinda fix it //-20220307_23
Tomcat 8.5. Inside catalina.properties, located in the /conf directory set:
tomcat.util.scan.StandardJarScanFilter.jarsToSkip=\*.jar
How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?
It might be worth noting that this can also occur when Windows blocks downloads that it considers to be unsafe. This can be addressed by right-clicking the jar file (such as ojdbc7.jar), and checking the 'Unblock' box at the bottom.
Windows JAR File Properties Dialog:
As well as adding the MySQL JDBC connector ensure the context.xml (if not unpacked in the Tomcat webapps folder) with your DB connection definitions are included within Tomcats conf directory.
A very silly mistake which could be possible resulting is adding of space at the start of the JDBC URL connection.
What I mean is:-
suppose u have bymistake given the jdbc url like
String jdbcUrl=" jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimeZone=UTC";
(Notice there is a space in the staring of the url, this will make the error)
the correct way should be:
String jdbcUrl="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimeZone=UTC";
(Notice no space in the staring, you may give space at the end of the url but it is safe not to)
Run java with CLASSPATH environmental variable pointing to driver's JAR file, e.g.
CLASSPATH='.:drivers/mssql-jdbc-6.2.1.jre8.jar' java ConnectURL
Where drivers/mssql-jdbc-6.2.1.jre8.jar is the path to driver file (e.g. JDBC for for SQL Server).
The ConnectURL is the sample app from that driver (samples/connections/ConnectURL.java), compiled via javac ConnectURL.java.
I was using jruby, in my case I created under config/initializers
postgres_driver.rb
$CLASSPATH << '~/.rbenv/versions/jruby-1.7.17/lib/ruby/gems/shared/gems/jdbc-postgres-9.4.1200/lib/postgresql-9.4-1200.jdbc4.jar'
or wherever your driver is, and that's it !
I had this exact issue when developing a Spring Boot application in STS, but ultimately deploying the packaged war to WebSphere(v.9). Based on previous answers my situation was unique. ojdbc8.jar was in my WEB-INF/lib folder with Parent Last class loading set, but always it says it failed to find the suitable driver.
My ultimate issue was that I was using the incorrect DataSource class because I was just following along with online tutorials/examples. Found the hint thanks to David Dai comment on his own question here: Spring JDBC Could not load JDBC driver class [oracle.jdbc.driver.OracleDriver]
Also later found spring guru example with Oracle specific driver: https://springframework.guru/configuring-spring-boot-for-oracle/
Example that throws error using org.springframework.jdbc.datasource.DriverManagerDataSource based on generic examples.
#Config
#EnableTransactionManagement
public class appDataConfig {
\* Other Bean Defs *\
#Bean
public DataSource dataSource() {
// configure and return the necessary JDBC DataSource
DriverManagerDataSource dataSource = new DriverManagerDataSource("jdbc:oracle:thin:#//HOST:PORT/SID", "user", "password");
dataSource.setSchema("MY_SCHEMA");
return dataSource;
}
}
And the corrected exapmle using a oracle.jdbc.pool.OracleDataSource:
#Config
#EnableTransactionManagement
public class appDataConfig {
/* Other Bean Defs */
#Bean
public DataSource dataSource() {
// configure and return the necessary JDBC DataSource
OracleDataSource datasource = null;
try {
datasource = new OracleDataSource();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
datasource.setURL("jdbc:oracle:thin:#//HOST:PORT/SID");
datasource.setUser("user");
datasource.setPassword("password");
return datasource;
}
}
I was having the same issue with mysql datasource using spring data that would work outside but gave me this error when deployed on tomcat.
The error went away when I added the driver jar mysql-connector-java-8.0.16.jar to the jres lib/ext folder
However I did not want to do this in production for fear of interfering with other applications. Explicity defining the driver class solved this issue for me
spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
You will get this same error if there is not a Resource definition provided somewhere for your app -- most likely either in the central context.xml, or individual context file in conf/Catalina/localhost. And if using individual context files, beware that Tomcat freely deletes them anytime you remove/undeploy the corresponding .war file.
For me the same error occurred while connecting to postgres while creating a dataframe from table .It was caused due to,the missing dependency. jdbc dependency was not set .I was using maven for the build ,so added the required dependency to the pom file from maven dependency
jdbc dependency
For me adding below dependency to pom.xml file just solved like magic! I had no mysql connector dependency and even adding mssql jdbc jar file to build path did not work either.
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>9.4.0.jre11</version>
</dependency>
In my case I was working on a Java project with Maven and encountered this error.
In your pom.xml file make sure you have this dependencies
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
</dependencies>
and where you create connection have something like this
public Connection createConnection() {
try {
String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
String username = "root"; //your my sql username here
String password = "1234"; //your mysql password here
Class.forName("com.mysql.cj.jdbc.Driver");
return DriverManager.getConnection(url, username, password);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
faced same issue. in my case ':' colon before '//' (jdbc:mysql://localhost:3306/dbname) was missing, and it just fixed the problem.
make sure : and // are placed properly.
I ran into the same error. In my case, the JDBC URL was correct, but the issue was with classpath. However, adding MySQL connector's JAR file to the -classpath or -cp (or, in the case of an IDE, as a library) doesn't resolve the issue. So I will have to move the JAR file to the location of Java bytecode and run java -cp :mysql_connector.jar to make this work. If someone runs into the same issue as mine, I'm leaving this here.
I encountered this issue by putting a XML file into the src/main/resources wrongly, I deleted it and then all back to normal.

How to properly run migrations and seed a docker MySql DB using Entity Framework Core

I implemented database migrations in my ASP.NET core solution as it's recommended in the following issue: Pattern for seeding database with EF7 in ASP.NET 5
My solution is setup for working on linux docker and the application depends on a MySql container that is configured in the docker compose file and setup on the first run.
The migrations run in the Startup.Configure method as:
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
context.Database.Migrate();
context.EnsureSeedData();
}
But running the application for the first time always throws the following error:
An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in System.Private.CoreLib.ni.dll but was not handled in user code
Then if I wait some seconds and re-launch the debug session the code executes without problem and the first-run data is there.
Is there a way that it could wait for the DB server to be ready before running the migrations?
EDIT:
If I change the migration method for the one in this question: Cannot get the UserManager class
instead of the previous error I get this one:
An exception of type 'System.AggregateException' occurred in System.Private.CoreLib.ni.dll but was not handled in user code
Is there a way that it could wait for the DB server to be ready before running the migrations?
In your Program.Main, you could add code that attempts to open a connection to MySql, and loop until the connection opens successfully.
For example:
public static void Main()
{
MySqlConnection connection;
while (true)
{
try
{
connection = new MySqlConnection("Database=mysql; Server=server;User ID=user;Password=password");
connection.Open();
break;
}
// ex.Number = 1042 when the server isn't up yet, assuming you're using MySql.Data and not some other MySql implementation
catch (MySqlException ex) when (ex.Number is 1042)
{
Console.Error.WriteLine("Waiting for db.");
Thread.Sleep(1000);
}
}
// ... continue launching website
}

Java keeps saying it can't find the jdbc mysql driver

Here's yet another question about jdbc's mysql driver. Considering the number of search results I got when I googled, I'm pretty bummed nothing I found in them worked for me.
The error:
hostname# java -cp /usr/share/java/mysql-connector.jar:/home/user JDBCTest
java.sql.SQLException: No suitable driver found for jdbc:mysql://<db ip>:3306/dbname
at java.sql.DriverManager.getConnection(DriverManager.java:596)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at JDBCTest.main(sqltest.java:14)
The code (pulled from a short how to):
import java.sql.Connection;
import java.sql.DriverManager;
class JDBCTest {
private static final String url = "jdbc:mysql://dbipaddress:3306/dbname";
private static final String user = "username";
private static final String password = "password";
public static void main(String args[]) {
try {
Connection con = DriverManager.getConnection(url, user, password);
System.out.println("Success");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I'm 90% certain /usr/share/java/mysql-connector-java.jar is the correct path for the class. That's what I've found both online, and using locate.
I've tried setting the environment classpath to CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java.jar in /etc/environment. As you can see, I've tried the -cp flag as well.
I can connect to the mysql server and database with the credentials I have in the JDBCTest class using the command line mysql-client. So it is not an error with the db server or my user/password.
As far as I can tell, my jdbc url is correct. That was one of the more common problems I found when searching...
I'm using Ubuntu 12.04 64bit on my servers.
libmysql-java is installed. As is, openjdk-7-jre-headless.
I'm running this completely outside of Tomcat, so all the answers saying to copy the driver into Tomcat's directory shouldn't apply.
So, I'm stumped. I would think using the -cp flag would just force it to work. Is there something in my java install missing? Something that got left out of openjdk-7-jre-headless?
How do I fix this?
Note: This class is just a quick test to help me diagnose why a larger (proprietary) app will not connect to my db. The larger app throws the same error. I'm hoping that fixing this small class will fix the larger app.
You are probably using a version of the MySQL JDBC driver that is not JDBC 4 compliant, so it is not automatically loaded by DriverManager. In that case you need to explicitly load it using:
Class.forName("com.mysql.jdbc.Driver");
The other option is to use a version of the library that is JDBC 4 compliant and will be automatically loaded.
Try adding the following on the first line of your main method:
Class.forName("com.mysql.jdbc.Driver");
If it throws an exception, then the JVM cannot access /usr/share/java/mysql-connector.jar. If that is the case, then check file permissions using:
ls -lah /usr/share/java/mysql-connector.jar
You should have at least read access to this file, and obviously the file should exist.

System.Security.SecurityException being thrown on initializing StructureMap bootstrapper

I am running a .NET 4.0 web application locally using the Visual Studio Development Server (built in web server with VS2010), and for the last couple months, my StructureMap bootstrapper file has worked perfectly.
I'm using StructureMap 2.6.1
I have not changed the Bootstrapper file or the Web.config file, and suddenly, I'm getting this strange error when trying to start up my web application.
Here is the error being thrown from the website:
it's a bit tough to read. It says:
Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException. Request Failed.
here is the code in my bootstrapper file:
public class BootStrapper
{
public static void ConfigureStructureMap()
{
ObjectFactory.Initialize(x =>
{
x.AddRegistry<ProductRegistry>();
});
}
}
public class ProductRegistry : Registry
{
public ProductRegistry()
{
For<IFirmRepository>()
.Use<FirmRepository>().Ctor<string>("connectionString").Is(ConfigurationManager.ConnectionStrings["FeesAndFlows"].ConnectionString);
For<ICryptographyService>()
.Use<Rijndael>();
For<IUserRepository>()
.Use<UserRepository>().Ctor<string>("connectionString").Is(ConfigurationManager.ConnectionStrings["FeesAndFlows"].ConnectionString);
For<IAuthenticationService>()
.Use<AuthenticationService>();
For<ILogger>()
.Use<DatabaseLogger>();
}
}
The error is being thrown on this line:
x.AddRegistry<ProductRegistry>();
I've already tried adding each of these lines to my Web.config file, one at a time, and they didn't fix the problem:
<trust level="Full" />
and
<securityPolicy>
<trustLevel name="Full" policyFile="internal"/>
</securityPolicy>
Does anyone have any ideas or might have heard of a problem like this? It's pretty important, b/c without StructureMap starting up correctly, my entire application will not run.
Thanks,
Mike
UPDATE:
Ok, so it appears my problem is local. Other developers here can download the code, and runs it just fine on their local machines. Weird. They bootstrap StructurMap just fine and all instances are resolved...
Any ideas on why just my machine can't bootstrap StructureMap when running in debug mode locally for my web project?
Are you running the code from a network drive by any chance (ie is your documents folder redirected onto a network drive)? Are you in an enterprise environment running on a domain?
If the former it's likely that the code is running in the intranet security context. If the former isn't true but the later is, then its quite possible that a network administrator has changed the enterprise wide CAS policy.
Okay, so this was the problem. The StructureMap.dll was blocked by Win 7. I don't know how is become blocked or where it became blocked, but apparently, when I downloaded the StructureMap.zip file onto my system, the .zip file was blocked, which in turn, led to all the items extracted from the .zip file being blocked as well.
Every time I unblocked it, it went back to blocked when I tried to run the web app.
The way I fixed it was to go back to the original .zip file, unblock it, extract it, and then replace my StruectureMap.dll reference with one that was not blocked.
Insane.
I don't even know WHAT causes file to suddenly become blocked or what process in Windows 7 determines what file(s) should be blocked, but this strange operating system "feature" cost me a day's worth of work.
I had the exact same issue at the exact same place, ObjectFactory.Initialize:
Server Error in '/X.ServiceHost' Application.
Inheritance security rules violated while overriding member:
'StructureMap.StructureMapException.GetObjectData(System.Runtime.Serialization.SerializationInfo,
System.Runtime.Serialization.StreamingContext)'. Security
accessibility of the overriding method must match the security
accessibility of the method being overriden.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.TypeLoadException: Inheritance security
rules violated while overriding member:
'StructureMap.StructureMapException.GetObjectData(System.Runtime.Serialization.SerializationInfo,
System.Runtime.Serialization.StreamingContext)'. Security
accessibility of the overriding method must match the security
accessibility of the method being overriden.
Getting the latest StructureMap package from NuGet (2.6.4.1) fixed the issue.
StructureMap NuGet Package

How to fix: "No suitable driver found for jdbc:mysql://localhost/dbname" error when using pools? [duplicate]

This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 6 years ago.
I am trying to create a connection to my database, when I put test my code using the main method, it works seamlessly. However, when trying to access it through Tomcat 7, it fails with error:
No suitable driver found for jdbc:mysql://localhost/dbname.
I am using pooling. I put in mysql connector (5.1.15), dbcp (1.4) , and pool(1.4.5) libraries in WEB-INF/lib and in .classpath as well. I am using Eclipse IDE. My code for the database driver is:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.apache.tomcat.dbcp.dbcp.ConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.DriverManagerConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory;
import org.apache.tomcat.dbcp.dbcp.PoolingDriver;
import org.apache.tomcat.dbcp.pool.impl.GenericObjectPool;
public class DatabaseConnector {
public static String DB_URI = "jdbc:mysql://localhost/dbname";
public static String DB_USER = "test";
public static String DB_PASS = "password";
// Singleton instance
protected static DatabaseConnector _instance;
protected String _uri;
protected String _username;
protected String _password;
/**
* Singleton, so no public constructor
*/
protected DatabaseConnector(String uri, String username, String password) {
_uri = uri;
_username = username;
_password = password;
GenericObjectPool connectionPool = new GenericObjectPool(null);
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
_uri, _username, _password);
PoolableConnectionFactory poolableConnectionFactory =
new PoolableConnectionFactory(connectionFactory, connectionPool,
null, null, false, true);
PoolingDriver driver = new PoolingDriver();
driver.registerPool("test", connectionPool);
}
/**
* Returns the singleton instance
*/
public static DatabaseConnector getInstance() {
if (_instance == null) {
_instance = new DatabaseConnector(DB_URI, DB_USER, DB_PASS);
}
return _instance;
}
/**
* Returns a connection to the database
*/
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
throw new RuntimeException(e);
}
return con;
}
}
Start of my stack trace:
Apr 5, 2011 9:49:14 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [Login] in context with path [/Project]
threw exception
java.lang.RuntimeException: java.sql.SQLException:
No suitable driver found for jdbc:mysql://localhost/dbname
What is causing this error?
Try putting the driver jar in the server lib folder. ($CATALINA_HOME/lib)
I believe that the connection pool needs to be set up even before the application is instantiated. (At least that's how it works in Jboss)
The reason you got this error:
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/dbname
Is because you forgot to register your mysql jdbc driver with the java application.
This is what you wrote:
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
throw new RuntimeException(e);
}
Should be this:
Connection con = null;
try {
//registering the jdbc driver here, your string to use
//here depends on what driver you are using.
Class.forName("something.jdbc.driver.YourFubarDriver");
con = DriverManager.getConnection("jdbc:apache:commons:dbcp:test");
} catch (SQLException e) {
throw new RuntimeException(e);
}
You'll have to read the manual on your specific mysql jdbc driver to find the exact string to place inside the the Class.forName("...") parameter.
Class.forName not required with JDBC v.4
Starting with Java 6, Class.forName("something.jdbc.driver.YourFubarDriver") is not necessary anymore if you use a recent (JDBC v.4) driver. For details read this: http://onjava.com/pub/a/onjava/2006/08/02/jjdbc-4-enhancements-in-java-se-6.html
I had the same problem using Tomcat7 with mysql-connector-java-5.1.26 that I put in both my $CATALINA_HOME/lib and WEB-INF/lib, just in case. But it wouldn't find it until I used either one of these two statements before getting the connection:
DriverManager.registerDriver(new com.mysql.jdbc.Driver ());
OR
Class.forName("com.mysql.jdbc.Driver");
I then followed up with removing mysql-connector-java-5.1.26 from $CATALINA_HOME/lib and the connection still works.
When running tomcat out of eclipse it won't pick the lib set in CATALINA_HOME/lib, there are two ways to fix it. Double click on Tomcat server in eclipse servers view, it will open the tomcat plugin config, then either:
Click on "Open Launch Config" > Classpath tab set the mysql connector/j jar location.
or
Server Location > select option which says "Use Tomcat installation (take control of Tomcat installation)"
I had the mysql jdbc library in both $CATALINA_HOME/lib and WEB-INF/lib, still i got this error . I needed Class.forName("com.mysql.jdbc.Driver"); to make it work.
add the artifact from maven.
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
I'm running Tomcat 7 in Eclipse with Java 7 and using the jdbc driver for MSSQL sqljdbc4.jar.
When running the code outside of tomcat, from a standalone java app, this worked just fine:
connection = DriverManager.getConnection(conString, user, pw);
However, when I tried to run the same code inside of Tomcat 7, I found that I could only get it work by first registering the driver, changing the above to this:
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
connection = DriverManager.getConnection(conString, user, pw);
Use:
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Registro exitoso");
} catch (Exception e) {
System.out.println(e.toString());
}
DriverManager.getConnection(..
Bro, you can also write code as below:
import java.sql.*;
import java.io.*;
public class InsertDatabase {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Maulik","root","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from Employee");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
I also had the same problem some time before, but I solved that issue.
There may be different reasons for this exception.
And one of them may be that the jar you are adding to your lib folder may be old.
Try to find out the latest mysql-connector-jar version and add that to your classpath.
It may solve your issue. Mine was solved like that.
I had the same problem, all you need to do is define classpath environment variable for tomcat, you can do it by adding a file, in my case C:\apache-tomcat-7.0.30\bin\setenv.bat, containing:
set "CLASSPATH=%CLASSPATH%;%CATALINA_HOME%\lib\mysql-connector-java-5.1.14-bin.jar"
then code, in my case:
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name", "root", "");
works fine.
if you are using netbeans you must add Mysql JDBC driver in the library list of the project, in the properties of your project
Most of time it happen because two mysql-connector-java-3.0.14-production-bin.jar file.
One in lib folder of tomcat and another in classpath of the project.
Just try to remove mysql-connector-java-3.0.14-production-bin.jar from lib folder.
This way it is working for me.
From what i have observed there might be two reasons for this Exception to occur:
(1)Your Driver name is not spelled Correctly.
(2)Driver hasn't been Associated Properly with the Java Project
Steps to follow in Eclipse:
(1)Create a new Java Project.
(2)copy The connector Jar file
(3)Right Click on the Java project and paste it there.
(4)Right click on the Java project -> Properties ->Java Build Path - >libraries-> Add Jar ->choose ur project(select the jar file from dropdown) and click ok.
The solution is straightforward.
Make sure that the database connector can be reached by your classpath when running (not compiling) the program, e.g.:
java -classpath .;c:\path\to\mysql-connector-java-5.1.39.jar YourMainClass
Also, if you're using an old version of Java (pre JDBC 4.0), before you do DriverManager.getConnection this line is required:
Class.forName("your.jdbc.driver.TheDriver"); // this line is not needed for modern Java
When developing using Ubuntu (Xubuntu 12.04.1) I 'HAD' to do the following:
Using
Eclipse Juno (downloaded, not installed via the software centre),
Tomcat 7 (downloaded in a custom user directory) also added as a Server in Eclipse,
Dynamic Web Project with a 3.0 Servlet,
MySQL Server on localhost configured and tested with user and password (make sure to test)
MySQL connector driver 5.1.24 jar,
I 'HAD', and I repeat 'HAD', to us the Class.Load("com.mysql.jdbc.Driver") statement along with adding the connector driver.jar to be in the web project lib folder for it to work in this situation.
IMPORTANT!!: after you copy the driver.jar to the lib make sure you refresh your project in Eclipse before running the servlet via Tomcat.
I did try adding the connector driver jar file via the Build Path with and without ClassLoad but it did not work!
Hope this helps anyone starting development with this specific situation: the Java community provides a 'LOT' of documentation but there are so many variables its hard to cover all of them and it makes things very hard on the new guy.
I think if someone could explain why Class.Load is required here (in this situation) it would be beneficial.
Enjoy
Since no one gave this answer, I would also like to add that, you can just add the jdbc driver file(mysql-connector-java-5.1.27-bin.jar in my case) to the lib folder of your server(Tomcat in my case). Restart the server and it should work.
Put mysql-connector-java-5.0.8-bin.jar in $CATALINA_HOME/lib
Check for typo in connection url, example
"jdbc:mysql://localhost:3306/report" ('report' here is the db name)
Make sure to use machine name(example : localhost instead of ip address(127.0.0.1))
Add the driver class to the bootstrapclasspath. The problem is in java.sql.DriverManager that doesn't see the drivers loaded by ClassLoaders other than bootstrap ClassLoader.
From other stackoverflow thread:
"Second. Make sure that you have MySQL JDBC Driver aka Connector/J in JMeter's classpath. If you don't - download it, unpack and drop mysql-connector-java-x.xx.xx-bin.jar to JMeter's /lib folder. JMeter restart will be required to pick the library up"
Please be sure that .jar file is added directly to the lib folder.
You can stick the jar in the path of run time of jboss like this:
C:\User\user\workspace\jboss-as-web-7.0.0.Final\standalone\deployments\MYapplicationEAR.ear\test.war\WEB-INF\lib
ca marche 100%