Trouble reaching a local database through ConnectionString - web-config

I have a connectionstringin my web.config, and I'm trying to call it from a classfile.
Why does it have problems reaching the database. The database is on the local computer, inside the project.
The Class
public static SqlConnection createConnection()
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["Database"]);
con.Open();
return con;
}
and the web.config
<connectionStrings>
<add connectionString="server=.\SQLEXPRESS;uid=The_Kettle_LibraryU;pwd=-5$G)dO:}B7X;Database=The_Kettle_Library" name="Database" providerName="System.Data.SqlClient" />
</connectionStrings>
The error posted.
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1502: The best overloaded method match for 'System.Data.SqlClient.SqlConnection.SqlConnection(string)' has some invalid arguments
Source Error:
Line 11: public static SqlConnection createConnection()
Line 12: {
Line 13: SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"]);
Line 14: con.Open();
Line 15: return con;

I think you should be using:
ConfigurationManager.ConnectionStrings["Database"].ConnectionString

Related

Liberty class loading issues or problem with hibernate (migrating tomcat app on liberty)?

i have to deploy a multi-module application in ear on Liberty Server 20 in my Eclipse. This application use hibernate as provider jpa2 and Derby client + driver derby-10.12.1.1.jar(as shared fileset). Persistence.xml is configured with non jta.
This is server.xml:
<enterpriseApplication id="rubrica-ear" location="rubrica-ear.ear" name="rubrica-ear"/>
<dataSource jndiName="jdbc/TestappDS" type="javax.sql.ConnectionPoolDataSource">
<properties.derby.client createDatabase="false" databaseName=".rubrica"></properties.derby.client>
<jdbcDriver>
<library>
<fileset dir="C:\programmiMio\java-eclipse\drivers" id="shared"></fileset>
</library>
</jdbcDriver>
</dataSource>
My .rubrica db location is in /usr/home.
Because I dont want to start a server derby on console but automatically, i do taht in a #WebListener class:
#WebListener
public class ReqListener implements ServletContextListener {
static final Logger log = LoggerFactory.getLogger(ReqListener.class);
PrintWriter pw = new PrintWriter(System.out);
private NetworkServerControl derbyserver;
#Override
public void contextInitialized(ServletContextEvent arg0) {
try {
String userHomeDir = System.getProperty("user.home", ".");
String systemDir = userHomeDir + "/.rubrica";
// Set the db system directory and startup Server Derby for incoming connections.
System.setProperty("derby.system.home", systemDir);//il db viene salvato qui
derbyserver = new NetworkServerControl(InetAddress.getByName("localhost"), 1527);
derbyserver.start(pw);
log.info("Apache derby settings ok");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e.getMessage());
}
}
#Override
public void contextDestroyed(ServletContextEvent arg0) {
if (derbyserver!=null){
...
}
}
When i deploy i get this error
[ERROR] An error occurred in the org.hibernate.ejb.HibernatePersistence persistence provider when attempting to create the entity manager factory of the testapp persistence unit container. The following error occurred: java.lang.NullPointerException
at org.hibernate.engine.jdbc.spi.TypeInfo.extractTypeInfo(TypeInfo.java:128)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:163)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:857)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:67)
at com.ibm.ws.jpa.management.JPAPUnitInfo.createEMFactory(JPAPUnitInfo.java:919)
at [internal classes]
When I debug on Liberty i see that Hibernate classes running before the #WebListener code (this is not the same thing in Tomcat), how can i resolve this issue? Something about class loading settings?
I try derby Embedded instead, but problem still araise again, in server.xml:
<properties.derby.embedded createDatabase="create" databaseName="C:/Users/myuser/.rubrica" shutdownDatabase="false"/>
<jdbcDriver>
<library>
<fileset dir="C:\programmiMio\java-eclipse\drivers" id="shared-libs"/>
</library>
</jdbcDriver>
Thanks
Roberto

how to unwrap PostgreSQL connection from the IBM WSJdbc41Connection

I have been trying to unwrap PostgreSQL connection from the IBM JNDI (WebSphere liberty ) and have had no luck please any help with that :
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup("jdbc/indi");
Connection cnx = dataSource.getConnection();
I get this exception :
java.lang.ClassCastException:
com.ibm.ws.rsadapter.jdbc.v41.WSJdbc41Connection cannot be cast to
org.postgresql.PGConnection
I tried :
if(cnx.isWrapperFor(PGConnectionPoolDataSource.class)) {
//unwrap
}
if (cnx.isWrapperFor(org.postgresql.ds.jdbc4.AbstractJdbc4SimpleDataSource.class)) {
//unwrap
}
if (cnx.isWrapperFor(org.postgresql.core.v3.ConnectionFactoryImpl.class)) {
//unwrap
}
if (cnx.isWrapperFor(org.postgresql.jdbc2.AbstractJdbc2Connection.class)) {
//unwrap
}
if (cnx.isWrapperFor(org.postgresql.jdbc3.AbstractJdbc3Connection.class)) {
//unwrap
}
Thanks
If you would like to unwrap a JDBC object (DataSource, Connection, etc) to a vendor-specific interface, the JDBC driver in the configured <datSource> must be available to the application classloader. The configuration will look something like this:
<application location="oraclejdbcfat.war" >
<!-- expose the 'DBLib' containing the JDBC driver jar to the app classloader -->
<classloader commonLibraryRef="DBLib"/>
</application>
<library id="DBLib">
<fileset dir="${server.config.dir}/postgresql/" includes="*.jar"/>
</library>
<dataSource jndiName="jdbc/myDS">
<jdbcDriver libraryRef="DBLib"/>
<properties .../>
</dataSource>
From there, you can unwrap the object in the same way you were doing before, namely:
DataSource ds = InitialContext.doLookup("jdbc/myDS");
Connection conn = ds.getConnection();
PGConnection pgConn = conn.unwrap(org.postgresql.PGConnection.class);
Also, there is an enableConnectionCasting boolean attribute on <dataSource> configuration which will automatically call unwrap for you upon getConnection().
<dataSource jndiName="jdbc/myDS" enableConnectionCasting="true">
Then the java code is a bit simpler:
DataSource ds = InitialContext.lookup("jdbc/indi");
PGConnection pgConn = (PGConnection) ds.getConnection();

error spring batch

i'm working in spring batch
public void beforeStep(StepExecution stepExecution) {
ExecutionContext context = new ExecutionContext();
context.putString("resourceFileName", file.getFilePath());
System.out.println("display resource path : ");
System.out.println(context.get("resourceFileName"));
}
this line works successfully i got the right path
System.out.println(context.get("resourceFileName"));
in the xml item reader i tried to get this resource like this
<property name="resource" value="file:#{stepExecutionContext['resourceFileName']}" />
but i got this error :
Caused by: java.lang.IllegalArgumentException: The Resource must not be null.
znd sometimes this error
Input resource must exist (reader is in 'strict' mode)

MyBatis issue: Unrecognized jdbcType

While trying to convert my app from using MyBatis [it was iBatis before], I've been getting the following error, in spite of trying to make so many different kinds of changes to the code: What am I doing wrong? Any help would be really really really great!!!
Error message:
`Caused by: org.springframework.jdbc.UncategorizedSQLException: ### Error querying database. Cause: com.ibm.db2.jcc.am.SqlException: [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null
`
`### The error may exist in Path-to-XML-File.XML`
`### The error may involve namespace.resultMap-name`
`### The error occurred while executing a query`
`### SQL: {call name-of-stored-proc(?)}`
`### Cause: com.ibm.db2.jcc.am.SqlException: [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null`
`; uncategorized SQLException for SQL []; SQL state [null]; error code [-4228]; [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null; nested exception is com.ibm.db2.jcc.am.SqlException: [jcc][10271][10296][3.58.82] Unrecognized JDBC type: -10. ERRORCODE=-4228, SQLSTATE=null`
XML File: `
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="Namespace-name">
<resultMap id="retrieveReports-results" type="Folder-structure-to-Java-file" autoMapping="true">
<result property="name" column="REPORT_NAME"/>
<result property="location" column="REPORT_DIRECTORY"/>
<result property="key" column="REPORT_KEY"/>
<result property="executable" column="EXECUTABLE"/>
<result property="commandLine" column="COMMAND_LINE"/>
<result property="commandLineFormat" column="COMMAND_LINE_FORMAT"/>
</resultMap>
<select id="retrieveReports" resultType="java.util.Map" statementType="CALLABLE">
{call prc_sel_reports(#{reports,jdbcType=CURSOR,javaType=java.sql.ResultSet,mode=OUT,resultMap=retrieveReports-results})}
</select>
</mapper>`
Java code:
try {
List < Report > reports = super.getSqlSession().selectList("retrieveReports");
if(log.isDebugEnabled()){
log.debug("Retrieved " + reports.size() + " reports, in method: retrieveReports()");
}
return reports;
// Attempt to catch different kinds of exceptions.
} catch (Exception e) {
throw new RuntimeException("Exception caught while trying to retrieve reports", e);
}
You have to specify a parameterType in the select statement, either map or custom class. An instance has to be passed on statement invocation.
resultType is not used, then irrelevant.
Procedure actually writes in a field of the "input" parameter passed to mybatis statement, and the statement does not return anything.
Mapper interface would be: void retrieveReports(Map<String, Object> params);
And your call:
Map<String, Object> params = new HashMap<String, Object>();
session.selectList("retrieveReports", params);
List<Report> reports = (List<Report>)params.get("reports");
Param may also be a custom type with property private List<Report> reports;.

Skippable Exception

I am trying to skip all the exceptions during the batch run using the following config:
<chunk reader="aaaFileReader" writer="aaaDBWriter"
commit-interval="100" skip-limit="100000">
<skippable-exception-classes>
<include class="java.lang.Exception" />
<exclude
class="org.springframework.jdbc.CannotGetJdbcConnectionException" />
</skippable-exception-classes>
</chunk>
<listeners>
<listener ref="aaabatchFailureListener" />
</listeners>
And I handle the exception in my listener. But when Spring Batch actually encounters an exception its not being skipped and the batch run ends with a failed state. The actual exception is a FlatFileParse Exception. How do I skip the FlatFileParseException?
Here is the log :
:18:21.257 [main] DEBUG o.s.b.repeat.support.RepeatTemplate - Handling fatal exception explicitly (rethrowing first of 1): org.springframework.batch.core.step.skip.NonSkippableReadException: Non-skippable exception during read
15:18:21.257 [main] ERROR o.s.batch.core.step.AbstractStep - Encountered an error executing the step
org.springframework.batch.core.step.skip.NonSkippableReadException: Non-skippable exception during read
at org.springframework.batch.core.step.item.FaultTolerantChunkProvider.read(FaultTolerantChunkProvider.java:81) ~[spring-batch-core.jar:na]
at org.springframework.batch.core.step.item.SimpleChunkProvider$1.doInIteration(SimpleChunkProvider.java:106) ~[spring-batch-core.jar:na]
at org.springframework.batch.repeat.support.RepeatTemplate.getNextResult(RepeatTemplate.java:367) ~[spring-batch-infrastructure.jar:na]
at org.springframework.batch.repeat.support.RepeatTemplate.executeInternal(RepeatTemplate.java:215) ~[spring-batch-infr
Caused by: org.springframework.batch.item.file.FlatFileParseException: Parsing error at line: 5, input=[0254285458908060150983101150983 AK00055002035201401081044000804CK5861 00Twist,Oliver AT&T 20121208 ]
at org.springframework.batch.
You can add the FlatFileParseException class on your batch job config, for example:
<batch:chunk reader="customImportReader" writer="customImporter" processor="customProcessor" commit-interval="1" skip-limit="10">
<batch:skippable-exception-classes>
<batch:include class="org.springframework.batch.item.file.FlatFileParseException" />
</batch:skippable-exception-classes>
</batch:chunk>
As per Spring Batch Documentation some of the exceptions are not qualified as skippable.
In your case its clear from logs that org.springframework.batch.item.file.FlatFileParseException is not a skippable excepotion hence re throwing org.springframework.batch.core.step.skip.NonSkippableReadException.
Read more about Configuring Skip Logic section that says:
For any exception encountered, the skippability will be determined by the nearest superclass in the class hierarchy. Any unclassifed exception will be treated as 'fatal'.
Read more about NonSkippableReadException that says:
Fatal exception to be thrown when a read operation could not be skipped.
Create a custom fileReader and Override the doRead() method to always throw you CustomException.
public class CustomFlatFileItemReader extends FlatFileItemReader {
#Override
protected T doRead() throws Exception {
T itemRead=null;
try {
itemRead= super.doRead();
} catch (FlatFileParseException e) {
throw new MyException(e.getMessage(), e);
}
return itemRead;}
}
Override your job skip policy to always skip your custom exception as below:
.skipPolicy((Throwable T, int skipCount) -> {
if (T instanceof BatchServiceException)
return true;
else
return false;