Mq Connection error 2058 - java

I have a spring core application with config below.
I'm using UserCredentialsConnectionFactoryAdapter, MQQueueConnectionFactory and jms-listener.
<jms:listener-container container-type="default"
connection-factory="userConnectionFactory" acknowledge="auto">
<jms:listener destination="${QUEUE_NAME_IN_GEN}" ref="messageListener"
method="onMessage" />
</jms:listener-container>
<bean id="userConnectionFactory"
class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter">
<property name="targetConnectionFactory">
<ref bean="mqConnectionFactory" />
</property>
<property name="username" value="${MQ_USER_ID}" />
</bean>
<bean id="mqConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
<property name="hostName">
<value>${MQ_HOST_NAME}</value>
</property>
<property name="port">
<value>${MQ_PORT}</value>
</property>
<property name="queueManager">
<value>${QUEUE_MANAGER}</value>
</property>
<property name="transportType">
<value>1</value>
</property>
</bean>
on application startup, listener stars perfectly one one machine.
when I try with same artifacts on a different server, listener fails to start with following error:
[org.springframework.jms.listener.DefaultMessageListenerContainer#0-1] ERROR org.springframework.jms.listener.DefaultMessageListenerContainer.refreshConnectionUntilSuccessful(DefaultMessageListenerContainer.java:909) - Could not refresh JMS Connection for destination 'R.ABCDEF' - retrying in 5000 ms. Cause: MQJMS2005: failed to create MQQueueManager for 'myhost:dev'; nested exception is com.ibm.mq.MQException: MQJE001: An MQException occurred: Completion Code 2, Reason 2058
MQJE036: Queue manager rejected connection attempt
To figure out if it's something to do with Unix account privilege issue on the second server, I wrote a simple MQ Client application. This program can connect to this queue manager and read messages from it.
What else could be wrong?

A 2058 suggests that the queue manager name is incorrect. According to the technote from IBM that's the most common cause, however there are others.
The following extract is taken from this technote:
Ensure that the queue manager name is specified correctly on:
MQCONN API calls
QREMOTE object definitions
Client connection channel definitions
Debugging QCF, TCF, or Client connection problems are much more complex.
Ensure that the connection request is routed to the intended machine and queue manager.
Verify that the listener program is starting the channel on the correct queue manager.
Ensure that the specifications for the client environment variables are correct.
mqserver
mqchllib
mqchltab
If you are using a client channel table (amqclchl.tab), then verify that your client connection channel definition has the correct queue manager name (QMNAME) specified.
Specify the correct queue manager name.
Correct channel routing problems.
Correct inetd listener configuration problems.
Correct client related configuration problems.

Related

MSSQL - Connection String

I have made a project using Entity Framework in Visual Studio. I have following connection string
<connectionStrings>
<add name="HospitalManagementEntities" connectionString="metadata=res://*/HospitalEntities.csdl|res://*/HospitalEntities.ssdl|res://*/HospitalEntities.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=HospitalManagement;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="HospitalManagementContext" connectionString="metadata=res://*/HospitalManagement.csdl|res://*/HospitalManagement.ssdl|res://*/HospitalManagement.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=HospitalManagement;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
It connects with the mssql.
But when I try to connect with same database from Java - Hibernate/Spring it gives me error.
UDP Connection String
<bean id="dataSourceMain"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://localhost\SQLEXPRESS;databaseName=HospitalManagement;integratedSecurity=true;Trusted_Connection=yes;" />
</bean>
Error
Could not obtain connection to query metadata : The connection to the
host localhost, 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.
TCP Connection String
<bean id="dataSourceMain"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="url" value="jdbc:sqlserver://localhost;databaseName=HospitalManagement;integratedSecurity=true;Trusted_Connection=yes;" />
</bean>
Error
Could not obtain connection to query metadata : The TCP/IP connection
to the host localhost, port 1433 has failed. Error: "Connection
refused: connect. Verify the connection properties. Make sure that an
instance of SQL Server is running on the host and accepting TCP/IP
connections at the port. Make sure that TCP connections to the port
are not blocked by a firewall.".
Ports Info
Netstat
Questions
As you can see that both udp and tcp ports are blocked/inactive.
1) So how Visual Studio managed to get connected to MSSQL ?
2) What protocol does Entity framework uses in above case ?
3) Is there a way to connect to Mssql in Java - Hibernate/Spring, bypassing the firewall or udp/tcp requirements ?
P.S. I have no admin rights. So for now I can't enable TCP/IP port.

How can I make a Camel/Netty4 SSL Client initiate a handshake?

I have a server that I wish to connect to via SSL, and then listen for data. I have a Camel route set up (via Spring) with a Netty4 endpoint as follows:
<camel:endpoint id="sslEndpoint" uri="netty4:tcp://{{server.host}}:{{server.port}}">
<camel:property key="clientMode" value="true" />
<camel:property key="needClientAuth" value="true" />
<camel:property key="sync" value="false" />
<camel:property key="ssl" value="true" />
<camel:property key="keyStoreResource" value="file:{{server.keystore}}" />
<camel:property key="trustStoreResource" value="file:{{server.truststore}}" />
<camel:property key="passphrase" value="{{server.passphrase}}" />
</camel:endpoint>
The route is configured in Java with this endpoint as the from part of the route:
public class MyRoute extends RouteBuilder {
#Override
public void configure() {
from("ref:sslEndpoint")
.to("log:MyLog?level=DEBUG");
}
}
By default a from endpoint will create a NettyConsumer, which acts as a server, hence specifying clientMode=true on the endpoint. This is honoured when using a plain TCP connection (it does indeed connect as a client, and receive data sent to it from the server). However, when using SSL it doesn't start off the SSL Handshake, meaning the server doesn't send out any data.
I have rooted through the Camel Netty4 code, and the key issue is in DefaultServerInitializerFactory where a new SSL Connection is configured - the SSLEngine has a hard-coded setUseClientMode(false). Sticking a breakpoint here and changing the call to true does indeed cause Netty to connect to the server, initiate the SSL handshake, and start consuming received data.
So my question is twofold:
How can I best resolve this issue and make the SSL Client initiate a handshake? Have I just missed something obvious?
Is this a bug in Camel/Netty4, as it would appear to me that the SSL connection should honour the clientMode property of the endpoint?

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.

Hibernate connection error

I am using Hibernate 3.6.10, MySQL database in my Play(Play 1.2.5) application. I am getting this error everyday
01:05:02,304 ERROR ~ The last packet successfully received from the server was 39,593,644 milliseconds ago.
The last packet sent successfully to the server was 39,593,644 milliseconds ago. is longer than the server configured value of 'wait_timeout'.
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.
After restarting the server, the application runs propertly. But after few hours I am getting the same error. Currently I am not using connection pool in my application.
The above issue is solved when I add the following connection details to the hibernate-cfg.xml file
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
Add hibernate-c3p0.jar to the build path.

Categories