Database connection pointing to wrong database - database

I have a web project in eclipse using glassfish. I have the following datasource entries in context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/TestDS" type="javax.sql.DataSource"
url="jdbc:oracle:thin:#server:1521:db1"
driverClassName="oracle.jdbc.OracleDriver" username="test" password="test" />
</Context>
When I run my application
DatabaseMetaData dmd = connection.getMetaData();
String name = dmd.getDatabaseProductName();
Database product name is always Apache Derby
What could be the reason for this? I am trying to connect to Oracle Database however connection is made to Apache Derby.
How can I resolve this issue?
Thanks
Update 1
public static DatabaseConnection getInstance(String name)
throws DatabaseException {
DatabaseConnection instance;
DataSource ds;
try {
InitialContext ctx = new InitialContext();
ds = (DataSource) new InitialContext().lookup("java:comp/env/"
+ name);
} catch (NamingException e) {
e.printStackTrace();
throw new DatabaseException("###data source is invalid ###" + e);
}
instance = new MYDataSource(ds);
return instance;
}

seems as if you are mixing some stuff up here. context.xml obviously is a Apache Tomcat configuration file. In GlassFish you need to either use the glassfish-resources.xml or configure your domain directly via either the admin GUI or the domain.xml.
There is a basic example of how to do this with GlassFish 3.1 in the GlassFish docs:
http://docs.oracle.com/cd/E18930_01/html/821-2416/ggndx.html
Have fun!
Markus

I have resolved this issue.
I created a a JDBC Resource under GlassFish and pointed connection to my connection created under Date Source Explorer. It created a sun-resources.xml. I had to manually rename this to glassfish-resource.xml. By default there are no entry for password,so I had to manually add <property name="Passwrod" value="password" />. When I ran my web application I was getting this error
java.sql.SQLException: Error in allocating a connection. Cause: No PasswordCredential found
So to resolve this error I added a property in JDBC Connection Pool in glassfish admin server. Now I could connect to Oracle database.
Not sure why I have to do two steps manually.
Thanks

Related

Error trying to connect sql server to web application core

I've the next error in my sql server's connection to visual studio:
ArgumentException: The specified invariant name 'System.Data.SqlClient' wasn't found in the list of registered .NET Data Providers.
The code in my app.config file is:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="SQL_Connection"
connectionString="Data Source=DESKTOP-ROTBMUO;
Initial Catalog=johnsonControls;
Persist Security Info=True
User ID=DESKTOP-ROTBMUO\Macbook Pro;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
And the error that shows me in my index.cshtml page is the next one:
#using WebMatrix.Data;
#{
var db = Database.Open("SQL_Connection");
var queryShow = "EXEC verLineasYAreas";
foreach (var row in db.Query(queryShow)) {
#row.nombre;
}
}
I don't know if I've to install some packeage called System.Data.SqlClient just like I did with Web.Matrix or if the problem is in my or in my foreach. I hope you guys can help me, or if you've one better way to do a connection I'd like to see it!

Spring Boot 2.1.2 Create dynamic DB connection just to run a query

In the Spring Boot 2.1.2 project, there is a default PostgreSQL db connection defined in application.properties:
spring.datasource.url=jdbc:postgresql://host:port/dbName
spring.datasource.username=username
spring.datasource.password=pass
Not any problem with Postgre DB, however, I need to connect another DB (MsSql) by JDBC connection rarely.
I just need to run a query, and process result list from a view of mssql table.
What I tried is;
Adding jdbc drivers to Pom.xml for Mssql:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>7.2.1.jre11</version>
<scope>test</scope>
</dependency>
Connect to sql-server and run query:
#GetMapping(path = "/getKonteynersFromSifirAtikServis/", produces = "application/json")
public ResponseEntity<ResponseStatusDto> getKonteynersFromSifirAtikServis() {
try {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dataSource.setUrl("jdbc:mysql://host:1433/msDbName");
dataSource.setUsername("ms_user");
dataSource.setPassword("ms_pass");
JdbcTemplate template = new JdbcTemplate(dataSource);
SqlRowSet sqlRowSet = template.queryForRowSet("SELECT * FROM dbo.viewName;");
} catch (Exception e) {
return new ResponseEntity<ResponseStatusDto>(ResponseStatusDto.createErrorDto(e.getMessage(), e), HttpStatus.ACCEPTED);
}
}
This did not work. It throws:
Could not load JDBC driver class [com.microsoft.sqlserver.jdbc.SQLServerDriver]
I have been getting hard to load mssql-jdbc inside pom definition. It is resolved to make version 7.2.1.jre11.
Scope of the dependency is set as test.
test This scope indicates that the dependency is not required for
normal use of the application, and is only available for the test
compilation and execution phases. This scope is not transitive.
Remove the same and attempt a run

How to set presto.s3.xxx properties when running flink from an IDE?

I'm able to successfully run my flink job which saves to S3 using ./bin/flink run ....
For this to work, I had to copy the flink-s3-fs-presto jar to my $FLINK_HOME/lib folder and I also had to configure my S3 connection details in my flink-conf.yaml:
You need to configure both s3.access-key and s3.secret-key in Flinkā€™s
flink-conf.yaml:
s3.access-key: your-access-key
s3.secret-key: your-secret-key
Source: flink aws docs
I also had to set a property s3.endpoint because I'm using S3 from IBM Cloud.
This all works fine when I run using ./bin/flink run.
However, when I try to run my job from my IDE (IntelliJ), I get the following error:
org.apache.flink.runtime.client.JobExecutionException: Cannot initialize task 'DataSink (TextOutputFormat (s3://xxxx/folder) - UTF-8)': Unable to load credentials from service endpoint
I've set an environment variable in the IDE run job, FLINK_CONF_DIR to point to my flink-conf.yaml and I can see that my configuration properties are picked up:
11:04:39,487 INFO org.apache.flink.configuration.GlobalConfiguration - Loading configuration property: s3.access-key, ****
11:04:39,487 INFO org.apache.flink.configuration.GlobalConfiguration - Loading configuration property: s3.secret-key, ****
11:04:39,487 INFO org.apache.flink.configuration.GlobalConfiguration - Loading configuration property: s3.endpoint, s3-api.us-geo.objectstorage.softlayer.net
However, I'm getting an error that suggests these properties are not getting passed to the presto library when I run from my IDE:
Caused by: org.apache.flink.fs.s3presto.shaded.com.amazonaws.SdkClientException: Unable to load credentials from service endpoint
Also, to validate this theory, if I step through the code when running from the IDE, I can see that my endpoint property is not applied:
... and drilling into the Hadoop configuration, I can see that the flink configuration is an empty map:
Digging a bit deeper, I can see that the org.apache.flink.core.fs.FileSystem#getUnguardedFileSystem() is creating a new empty Configuration:
// this "default" initialization makes sure that the FileSystem class works
// even when not configured with an explicit Flink configuration, like on
// JobManager or TaskManager setup
if (FS_FACTORIES.isEmpty()) {
initialize(new Configuration());
}
How can I configure the s3.access-key, s3.secret-key and s3.endpoint properties when running from an IDE?
Simply call
FileSystem.initialize(GlobalConfiguration.loadConfiguration(System.getenv("FLINK_CONF_DIR")));
before
env.execute()
will solve the issue.
Remember you still have to put your secret key and access key in flink-conf.yaml.
create core-site.xml
<configuration>
<property>
<name>fs.s3.impl</name>
<value>org.apache.hadoop.fs.s3a.S3AFileSystem</value>
</property>
<property>
<name>fs.s3a.access.key</name>
<value>xxxx</value>
</property>
<property>
<name>fs.s3a.secret.key</name>
<value>xxxxx</value>
</property>
</configuration>
and add
Map par = new HashMap();par.put("fs.hdfs.hadoopconf", "path to core-site.xml";
ParameterTool pt = ParameterTool.fromMap(par);
env.getConfig().setGlobalJobParameters(pt);

TFS Build: Can't connect to the Database

I'm trying to set up TFS build to deploy to my SQL Server Express instance but MSBuild keeps failing with:
C:\Builds\1\portal\Deploy to Portal_Dev\bin\DB.publish.sql: Unable to connect to master or target server 'Portal_Deploy_Dev'. You must have a user with the same password in master or target server 'Portal_Deploy_Dev'.
This is the publishing file:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseName>Portal_Deploy_Dev</TargetDatabaseName>
<DeployScriptFileName>CCA_DB.sql</DeployScriptFileName>
<TargetConnectionString>Data Source=Machine\SQLEXPRESS;Integrated Security=True;User ID=username;Password=password;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False</TargetConnectionString>
<ProfileVersionNumber>1</ProfileVersionNumber>
</PropertyGroup>
</Project>
Command line parameters used:
/t:Build;Publish
/p:SqlPublishProfilePath=..\DB\Publishing\Portal_Deploy_Dev.publish.xml
First try to build and deploy the project in Visual Studio by right clicking and choosing publish then selecting the profile or use the command line(msbuild) on the build agent.
This will narrow down if the issue is related to TFS definition or not. Check if there are any invalid DNS entry for the database server. Open the firewall on target machine. Also try to update SSDT to the latest version.
More ways for troubleshooting you could take a look at similar error in below questions:
Deploy 72002 - Unable to connect to master or target server
SQL Server DB Deployment : Unable to connect to master or target server
I had the same problem a few weeks ago, in my case in the connection string we weren't having the username and password because we made the connection to the database using windows authentication, I mean when you choose the connection for the publish profile.
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<IncludeCompositeObjects>True</IncludeCompositeObjects>
<TargetDatabaseName>MyDatabase</TargetDatabaseName>
<DeployScriptFileName>MyDatabaseChanges.sql</DeployScriptFileName>
<BlockOnPossibleDataLoss>True</BlockOnPossibleDataLoss>
<IgnoreRoleMembership>True</IgnoreRoleMembership>
<IgnorePermissions>True</IgnorePermissions>
<ExcludeServerAuditSpecifications>True</ExcludeServerAuditSpecifications>
<ExcludeServerRoleMembership>True</ExcludeServerRoleMembership>
<ExcludeServerRoles>True</ExcludeServerRoles>
<ExcludeUsers>True</ExcludeUsers>
<ExcludeLogins>True</ExcludeLogins>
<IgnoreUserSettingsObjects>True</IgnoreUserSettingsObjects>
<ProfileVersionNumber>1</ProfileVersionNumber>
<TargetConnectionString>Data Source=MyServer;Integrated Security=True;Persist Security Info=False;Pooling=False;MultipleActiveResultSets=False;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True</TargetConnectionString>
</PropertyGroup>
</Project>
Then in the TFS, we use the username and password (as part of the MSBuild arguments),
/p:TargetUserName="$(user)" /p:TargetPassword="$(password)"
we were connecting to the database with that user, now the error was fixed just given it to the TFS TargetUserName the db_owner role and the user was a local user and we changed to network user. I hope that helps you.

Connecting to MS SQL Server using Windows authentication and JTDS

I am unable to connect to SQL Server using Windows Authentification.
This is is the exception being thrown:
Caused by: java.io.IOException: SSO Failed: Native SSPI library not loaded. Check the java.library.path system property.
at net.sourceforge.jtds.jdbc.TdsCore.sendMSLoginPkt(TdsCore.java:1889)
at net.sourceforge.jtds.jdbc.TdsCore.login(TdsCore.java:587)
... 35 more
Here is the Spring configuration:
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("net.sourceforge.jtds.jdbc.Driver");
dataSource.setUrl(...);
return dataSource;
}
The following VM argument is defined:
-Djava.library.path=C:\x64\SSO
This points to ntlmauth.dll (from jtds-1.3.1-dist.zip)
The following dependency is defined in the pom:
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>com.springsource.net.sourceforge.jtds</artifactId>
<version>1.2.2</version>
</dependency>
Have obviously omitted something - any help is very appreciated!

Resources