ms sql configuration in beans.xml - java

I've installed the MS SQL Server 2008 and I want to use it in a Java project with Struts.
Unfortunately I cannot configure it in Java. I am using the Windows authentication for MsSql. Is that possible?
My beans.xml file looks like:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<!-- S2-Install-Start: INSERT DB SERVER HERE -->
<property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=MyDatabase" />
S2-Install-End:
<property name="username" value="Stefana\Steffi" />
S2-Install-Start: INSERT DB PASSWORD HERE
<property name="password" value="" />
S2-Install-End:
</bean>
I don't know what should I write in the user and password fields? When I connect to the Ms Sql Server, I get the following:
Servertype: DatabaseEngine
Servername: Stefana\SQLEXPRESS
Authentication: Windows Authentication
Username:Stefana\Steffi
Password:

You can use Windows authentication if you use the jTDS JDBC Driver for SQL Server. The jTDS driver is free, open source and generally more powerful than the official Microsoft one.
If you include the jTDS jar in your project, I believe this datasource URL should work:
jdbc:jtds://localhost:1433/MyDatabase;domain=Stefana
Because you're running on Windows the jTDS driver is capable of using a native library to automatically log you in with your current credentials. However it's usually a better idea to explicitly specify the username and password, because that way your web app won't behave differently depending on who starts it up.
Note also that SQL Server 2008 probably won't have TCP connections enabled by default. Unless you turn that on you won't be able to connect with either the Microsoft driver or the jTDS one.
To enable TCP connections:
Open Sql Server Configuration Manager (it should be on your Start menu)
In the tree on the left, navigate to SQL Server Network Configuration then Protocols for MSSQLSERVER
You should see TCP/IP in the list of protocols.
If its status is Disabled then double-click it, and change the Enabled option to Yes and click OK
You now need to restart SQL Server. Navigate to the SQL Server Services item
Right-click on SQL Server (MSSQLSERVER) in the list of services
Choose Restart
You should now be able to connect to SQL Server from your Java web app

This is not the right thing to do.
Do you own that database? Your config says "localhost", so I'll assume yes. You should be using another username and password for your application from SQL Server, not Windows Authentication. I'd create a separate user just for this application. Give it access only to the application schema, and GRANT the minimum permissions necessary to accomplish its mission (e.g. no DELETE permission if not needed; no access to SYSTEM tables if not needed; no running stored procedures if not needed).
A better solution is to use a JNDI data source and not have passwords in plain text on your machine.

replace the property:
<property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=MyDatabase" />
for:
<property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=MyDatabase;" />
Done!!!

Related

Not able to connect to Azure SQL Database server using spring

I am able to connect to database which is having ip address,but if
i have my database created in Azure SQL Database server in that i am not able to connect using spring configuration Java web application.It shows me error saying
The connection to the host vinayaka.cloudapp.net,555, named instance sqlexpress failed. Error: "java.net.UnknownHostException: vinayaka.cloudapp.net,555". 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.
spring-config.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://vinayaka.cloudapp.net,555\sqlexpress;database=Sample" />
<property name="username" value="user" />
<property name="password" value="pass" />
</bean>
Note:
1) I am able to open and work on that server in SQL Server Management Studio.
2) If I am able to open in SQL Server Management Studio, it means my machine IP address is allowed by firewall.
3) I can connect to database created in Azure SQL Database.
Please give suggestion on this.
The connection string of Azure SQL Database for JDBC is like jdbc:sqlserver://<hostname>.database.windows.net:1433;database=<dbname>;user=<user>#<hostname>;password={your_password_here};encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;.
You can check the connection string of your Azure SQL Database on Azure old portal or new portal, please see the pictures below.
Pic 1. Check the Connection String for JDBC on Azure old portal
Pic 2. Check the Connection String for JDBC on Azure new portal
Is 555 the port, that is exposed by the database for connection?
Shouldn't the connection string look like this?
<property name="url" value="jdbc:sqlserver://vinayaka.cloudapp.net:555\sqlexpress;database=Sample" />
I have replaced , in your code with :
Change your connection string like "jdbc:sqlserver://{HostName}.database.windows.net;database={databaseName};encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30".
And use sqljdbc4 jar file. Hope it should work.

How to show content of local h2 database(web console)?

Recently I joined a new team and here guys use h2 for stub service.
I was wondering whether I can show the content of this database using web interface. At work it is available by going to localhost:5080
I have a project where I use h2 database, but I cannot see the h2 web console when I hit localhost:5080
I tried also localhost:8082 - it also doesn't work.
My project configuration (works successfully):
<bean id="wrappedDataSource" class="net.bull.javamelody.SpringDataSourceFactoryBean">
<property name="targetName" value="dataSource" />
</bean>
<bean id="wrappedDataSource" class="net.bull.javamelody.SpringDataSourceFactoryBean">
<property name="targetName" value="dataSource" />
</bean>
<bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:~/test;MODE=PostgreSQL" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="wrappedDataSource"/>
<property name="configLocation">
<value>classpath:hibernate-test.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.connection.charSet">UTF-8</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hbm2ddl.auto">create-drop</prop>
</props>
</property>
</bean>
<context:property-placeholder location="classpath:jdbc.properties"/>
I have not ideas how to access to h2 web console. please help.
P.S.
I see mentions of h2 only in .m2 folder
P.S.2
I noticed that web console available by http://localhost:8082/ if replace url in configuration with:
<property name="url" value="jdbc:h2:tcp://localhost/~/test;MODE=PostgreSQL" />
But it works if I already start h2(in .m2 folder find h2 jar file and hit double click)
If h2 is not started when I start application - i see following error:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:94)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbInitializer': Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
...
Caused by: org.hibernate.exception.GenericJDBCException: Could not open connection
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
...
Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Соединение разорвано: "java.net.ConnectException: Connection refused: connect: localhost"
Connection is broken: "java.net.ConnectException: Connection refused: connect: localhost" [90067-182])
at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1549)
...
Caused by: org.h2.jdbc.JdbcSQLException: Соединение разорвано: "java.net.ConnectException: Connection refused: connect: localhost"
Connection is broken: "java.net.ConnectException: Connection refused: connect: localhost" [90067-182]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
...
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
...
I want to achieve that h2 starts if it not started when I start my application.
P.S.3
I have tried to wrote following code:
Server server = null;
try {
server = Server.createTcpServer("-tcpAllowOthers").start();
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test;MODE=PostgreSQL", "sa", "");
} catch (Exception e) {
LOG.error("Error while initialize", e);
}
I execute it and after I am trying to type localhost:9092 in my browser.
At this moment downloads file. inside file the following content:
Version mismatch, driver version is “0” but server version is “15”
my h2 version 1.4.182
P.S.4
This code works:
public class H2Starter extends ContextLoaderListener {
private static final Logger LOG = LoggerFactory.getLogger(H2Starter.class);
#Override
public void contextInitialized(ServletContextEvent event) {
startH2();
super.contextInitialized(event);
}
private static void startH2() {
try {
Server.createTcpServer("-tcpAllowOthers").start();
Class.forName("org.h2.Driver");
DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test;MODE=PostgreSQL;AUTO_SERVER=TRUE", "sa", "");
Server.createWebServer().start();
} catch (Exception e) {
LOG.error("cannot start H2 [{}]", e);
}
}
public static void main(String[] args) {
startH2();
}
}
but I need to invoke it only when concrete spring profile active(now it works always)
Let's split the question into two parts.
Depending on how you specify the connection to H2, you'll get different operational modes.
Modes are: Embedded, In-Memory, Server.
jdbc:h2:~/test gives you a H2 instance in embedded mode.
The embedded mode has a limitation of being accessible only through the same class loader and same JVM (proof)
jdbc:h2:mem:test gets you an in-memory H2 instance. That is also not accessible from outer world.
jdbc:h2:tcp://localhost/test will start H2 server and it will be accessible from outside of JVM server mode but with one limitation - the server needs to be started before the connection is made.
The last limitation is causing your Connection refused: connect: localhost" exception.
To sum everything up:
start the H2 server before you start application
use jdbc:h2:tcp://localhost/test as connection string
....
happy coding :)
Update
Just noticed that you want to start the server in the process of launching application.
You can do that in several ways, depending how do you start the application:
If you're using maven / gradle it's easier for you to add some profile / task so that it gets executed before the application actually starts.
If you have to setup everything in java, I suggest you look at this question
Update 2
If connection to the local database is needed only for developing / debugging purposes I would setup everything using maven profile. Answers from this question will solve that.
If you need access to the H2 database in production (I can hardly imagine any use-case for that) it's better to do that in spring. Mainly because the application container / environment setup is likely to be different in production (compared to development environment).
To address the question regarding if to start the server outside of Spring context or not - it all depends on the requirements.
One thing you should note is that the server should be started before the datasource is started (otherwise the spring context will not load)
Update 3
Unfortunately I'm not able to give you a working solution, but according to the JavaDocs there is a difference between TCP server and Web server.
Take a closer look to the JavaDoc of H2 Server class.
I guess you should use Server.createWebServer() method to create the server (the difference between TCP server and Web server is that
Another great class you could use org.h2.tools.Console (JavaDoc here)
Just run the main method of Console and I guess that should solve everything.
You ought to be able to use the in-memory or file-based variants, and then in your application fire up the H2 TCP server separately, e.g. using a Spring bean (mind the semi-pseudo code and sample port):
#Component
class Bootstrap {
#PostConstruct
public void startH2TcpServer() {
Server.createTcpServer("-tcpPort", "9123", "-tcpDaemon").start();
}
}
See http://www.h2database.com/html/tutorial.html#using_server
How about changing jdbc url in configuration to include
AUTO_SERVER=TRUE
to start h2 automatically.
See Auto mixed mode
Multiple processes can access the same database without having to
start the server manually. To do that, append ;AUTO_SERVER=TRUE to the
database URL. You can use the same database URL independent of whether
the database is already open or not. This feature doesn't work with
in-memory databases.
Use the same URL for all connections to this database. Internally, when using this mode, the
first connection to the database is made in embedded mode, and
additionally a server is started internally (as a daemon thread). If
the database is already open in another process, the server mode is
used automatically.

MySql Remote Access Denied

I am trying to connect to a mysql database. When I am trying to connect over mysql Workbench, I can but over java application, it says:
Caused by: java.sql.SQLException: Access denied for user 'root'#'1.2.3.4' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1084)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4232)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4164)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:926)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1748)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1288)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2506)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2539)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2321)
The datasource definition is:
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://3.3.3.3:3306"/>
<property name="username" value="root"/>
<property name="password" value="12345"/>
</bean>
and in db , user_priviliges table is:
'root'#'%', 'def', 'USAGE', 'NO'
Could please help me to solve this problem?
EDIT:
I am using jdbcTemplate and the error is on this exact line:
getJdbcTemplate().queryForList(sql.toString());
You need to create a an account for 'root'#'localhost' in addition to the 'root'#'%' account that you already have (with the same password). Why? See the mysql docs on this subject. Here is the relevant part:
Two of the accounts have a user name of monty and a password of some_pass. Both accounts are superuser accounts with full privileges to do anything. The 'monty'#'localhost' account can be used only when connecting from the local host. The 'monty'#'%' account uses the '%' wildcard for the host part, so it can be used to connect from any host.
It is necessary to have both accounts for monty to be able to connect from anywhere as monty. Without the localhost account, the anonymous-user account for localhost that is created by mysql_install_db would take precedence when monty connects from the local host. As a result, monty would be treated as an anonymous user. The reason for this is that the anonymous-user account has a more specific Host column value than the 'monty'#'%' account and thus comes earlier in the user table sort order. (user table sorting is discussed in Section 6.2.4, “Access Control, Stage 1: Connection Verification”.)

Unable to connect to postgres SQL with spring and hibrenate

I have spring web application , that i am trying to connect with postgress.
Here is the db connection properties
datasource.driver=org.postgresql.Driver
datasource.url=jdbc:postgresql://localhost:5432/sampleDb
datasource.username=postgres
datasource.password=postgres
Here is the application context
<bean id="appDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>${datasource.driver}</value>
</property>
<property name="url">
<value>${datasource.url}</value>
</property>
<property name="username">
<value>${datasource.username}</value>
</property>
<property name="password">
<value>${datasource.password}</value>
</property>
</bean>
When i starting application it get an error messege.
Cannot create PoolableConnectionFactory (Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
Why would this happen?
I restored this database form another machine.I dont know what they written in that sql file. There is a code in that sql dump file.
REVOKE ALL ON TABLE workflow_type FROM PUBLIC;
REVOKE ALL ON TABLE workflow_type FROM postgres;
GRANT ALL ON TABLE workflow_type TO postgres;
GRANT SELECT,INSERT,DELETE,REFERENCES,UPDATE ON TABLE workflow_type TO user1;
Is this happend becouse of this query?
did you try to connect with psql under command line before? its just to test if you pg_hba.conf was fine.
if you can't connect with psql. Open you pg_hba.conf file and if you are on a local computer replace md5 by trust to have something like :
local all all trust
this permit everybody to connect to you postgres server.
retry connection with psql command line.
If its work, retry to launch your server to see if spring can now connect to the db fine.
Is your Postgres up and running on localhost:5432? Are you able to connect to the DB via command line (e.g. psql <dbname> -h localhost -U <username> -W)?

GlassFish Security Realm, Active Directory and Referral

I've setup up a Security Realm in Glassfish to authenticate against an Active Directory server. The configuration of the realm is as follows:
Class Name: com.sun.enterprise.security.auth.realm.ldap.LDAPRealm
JAAS context: ldapRealm
Directory: ldap://172.16.76.10:389/
Base DN: dc=smallbusiness,dc=local
search-filter: (&(objectClass=user)(sAMAccountName=%s))
group-search-filter: (&(objectClass=group)(member=%d))
search-bind-dn: cN=Administrator,CN=Users,dc=smallbusiness,dc=local
search-bind-password: abcd1234!
The realm is functional and I can log-in, but when ever I log in I get the following error in the log:
SEC1106: Error during LDAP search with filter [(&(objectClass=group)(member=CN=Administrator,CN=Users,dc=smallbusiness,dc=local))].
SEC1000: Caught exception.
javax.naming.PartialResultException: Unprocessed Continuation Reference(s); remaining name 'dc=smallbusiness,dc=local'
at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2820)
....
....
ldaplm.searcherror
While searching for a solution I found that it was recommended to add java.naming.referral=follow to the properties of the realm. However, after I add this it takes 20 minutes for GlassFish to authenticate against Active Directory. I suspect it is a DNS problem on the Active Directory server. The Active Directory server is a vanilla Windows Server 2003 setup in a Virtual Machine.
Any help/recommendation is highly appreciated!
This is the configuration I use in my domain.xml file, it might be of some interrest to you :
<auth-realm classname="com.sun.enterprise.security.auth.realm.ldap.LDAPRealm" name="ldapRealm">
<property name="search-bind-password" value="Demodemo01"/>
<property name="search-bind-dn" value="Administrator"/>
<property name="search-filter" value="(&(objectClass=user)(sAMAccountName=%s)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"/>
<property name="group-search-filter" value="(&(objectClass=group)(member=%d))"/>
<property name="jaas-context" value="ldapRealm"/>
<property name="base-dn" value="CN=Users,DC=saierp,DC=net"/>
<property name="directory" value="ldap://192.168.1.38:389"/>
</auth-realm>
Specially, make sure to add the userAccountControl to your filter, otherwise, disabled accounts in AD will be allowed to connect.
This was maddening trying to solve this... Glassfish 3.0.1 trying to connect with Windows, and getting the above error.
I'm not a Windows or LDAP whiz at all... but finally found this:
http://forum.springsource.org/showthread.php?t=87673
And the very last line is the key: use the "Global Catalog Port" - instead of 389, it is 3268 by default. And the exception disappears.
Why?
Who cares?
(well, ok, I'm going to read about it now.)
Hopefully, you've resolved this, but just in case:
I used 'objectCategory' in place of 'objectClass' as I read the former are indexed, hence faster.
I had to add this property:
property name="assign-groups" value="Domain Users"
where "Domain Users" is the group in AD that all of our users are placed into. This must match the value in sun-web.xml for security-role-mapping.
Later, I was able to create a specific group for this application and make the appropriate changes.

Categories