There are security reasons that I cannot add my MBeans to the existing JBoss 7 platform MBeanServer. So I create my own mBeanServer and JMXConnectorServer with a customAuthenticator.
Here are my Spring Bean definition for new MBeanServer and JMXConnectorServer. This code works when I run my application in Jetty. I was able to connect via URL service:jmx:rmi://localhost/jndi/rmi://localhost:17999/sample in jconsole and it only shows the custom MBeans which is what I expect.
But the same code does not work in JBoss 7. When I deploy to JBoss and try to connect with the same JMX URL, it gives a dialog with this error: "The connection to myuser#service:jmx:rmi://localhost/jndi/rmi://localhost:17999/trm did not succeed. Would you like to try again?"
I put a break point in my customAuthenticator and JBoss doesn't stop at my break point when I attempt to connect JMX. It seems my JMXConnectorServer is not being used by JBoss. Can anyone help? Note that I cannot change the existing JBoss MBeanServer or JMX Connector Server configuration because they are used for other purpose.
Thanks in advance.
#Bean
public Object rmiRegistry() throws Exception {
RmiRegistryFactoryBean factory = new RmiRegistryFactoryBean();
factory.setPort(17999);
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
#DependsOn("rmiRegistry")
public MBeanServer mBeanServer() {
MBeanServerFactoryBean factory = new MBeanServerFactoryBean();
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
#DependsOn("rmiRegistry")
public JMXConnectorServer jmxConnectorServer() throws IOException, JMException {
ConnectorServerFactoryBean factory = new ConnectorServerFactoryBean();
factory.setServer(mBeanServer());
factory.setServiceUrl("service:jmx:rmi://localhost/jndi/rmi://localhost:17999/sample");
factory.setRegistrationPolicy(RegistrationPolicy.FAIL_ON_EXISTING);
Map<String, Object> props = new HashMap<>();
props.put(JMXConnectorServer.AUTHENTICATOR, customAuthenticator);
factory.setEnvironmentMap(props);
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
#DependsOn("rmiRegistry")
public AnnotationMBeanExporter annotationMBeanExporter() {
AnnotationMBeanExporter result = null;
result = new AnnotationMBeanExporter();
result.setServer(mBeanServer());
return result;
}
I suspect the JBoss environment is influencing how the JMX Connector server is configured. I would try taking the extra step of specifying the service listening port (e.g. 17998) rather than leaving it as an ephemeral by using this JMXServiceURL:
service:jmx:rmi://localhost:17998/jndi/rmi://localhost:17999/sample
Related
I'm working on a big project written with java8 and SringBoot 2.2.6. The project uses Envers and, the girl builds the architecture say to me that she doesn't manage to put in the application.properties the Envers configuration. Than she do as follows:
#Configuration
public class JPAConfig {
#Autowired
private DataSource dataSource;
#Bean(name="entityManagerFactory")
public LocalSessionFactoryBean sessionFactory() throws IOException {
LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
factoryBean.setHibernateProperties(getHibernateProperties());
factoryBean.setDataSource(dataSource);
factoryBean.setPackagesToScan("it.xxxx.xxxxx.xxxxx.common.model");
return factoryBean;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", PostgreSQL82Dialect.class.getName());
properties.put("hibernate.default_schema", "test");
properties.put("hibernate.listeners.envers.autoRegister", true);
properties.put("org.hibernate.envers.revision_field_name", "rev");
properties.put("org.hibernate.envers.revision_type_field_name", "rev_type");
properties.put("org.hibernate.envers.audit_table_prefix", "aud_");
properties.put("org.hibernate.envers.store_data_at_delete", true);
properties.put("org.hibernate.envers.audit_table_suffix", "");
return properties;
}
}
Problem is that without dataSource class name I can't start my #SpringBootTest classes and I don't know how to add it in a scenario like this (without change the configuration I mean).
I also tries to add this row inside the application.properties:
spring.profiles.active=#spring.profile#
spring.datasource.driver-class-name=org.postgresql.Driver
#JPA
spring.datasource.jndi-name=jdbc/test
But doesn't work at all..
If I run the App with JUnit I obtain this error:
org.springframework.jdbc.datasource.lookup.DataSourceLookupFailureException: Failed to look up JNDI DataSource with name 'jdbc/test'; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
Can you help me??
Thanks a lot
You need to register your Datasource as JNDI resource in the spring-boot embedded tomcat.
You can add it as test scope configuration.
This answer shows how to register a JNDI resource: https://stackoverflow.com/a/26005740/5230585
I have a simple jax-rs REST-service that is deployed as a WAR on a wildfly server and uses a JNDI lookup for a datasource configured in the standalone.xml. For this the path is read from a datasource.properties file. The service then performas database actions through this datasource.
Now I want to use this REST-service in a SpringBoot application which is deployed to an embedded tomcat. My implementation uses RESTEasy and the service can easily be integrated with the resteasy-spring-boot-starter. But the JNDI lookup doesn't work, because of course the datasource is now not configured in a standalone.xml, but in the application.properties file. It is a completely different datasource.
I'm looking for a solution to set the datasource without having to "hard code" it. This is how the connection is retrieved currently in the WAR for the wildfly:
private Connection getConnection() {
Connection connection = null;
try (InputStream config = OutboxRestServiceJbossImpl.class.getClassLoader().getResourceAsStream("application.properties")) {
Properties properties = new Properties();
properties.load(config);
DataSource ds = (DataSource) new InitialContext().lookup(properties.getProperty("datasource"));
connection = ds.getConnection();
} catch (Exception e) {
}
return connection;
}
Currently I solved this by having a core module which actually performs the logic and 2 implementations with jax-rs for wildfly and SpringMVC in SpringBoot. They invoke the methods of an instance of the core module and the the connection is handed over to these methods. This looks like this for wildfly:
public String getHelloWorld() {
RestServiceCoreImpl rsc = new RestServiceCoreImpl();
try (Connection connection = getConnection()) {
String helloWorld = rsc.getHelloWorld(connection);
} catch (Exception e) {
}
return helloWorld;
}
public String getHelloWorld(Connection connection){
//database stuff, eg. connection.execute(SQL);
}
And like this in SpringBoot:
#Autowired
RestServiceCoreImpl rsc;
#Autowired
DataSource restServiceDataSource;
#Override
public String getHelloWorld() {
try (Connection connection = restServiceDataSource.getConnection()){
return rsc.getHelloWorld(connection);
} catch (SQLException e) {
}
return null;
}
Is there any way to solve this datasource issue? I need the SpringMVC solution to be replaced with the jax-rs solution within SpringBoot.
Okay, I was able to solve this myself. Here is my solution:
I enabled the naming in the embedded tomcat server as follows:
#Bean
public TomcatServletWebServerFactory tomcatFactory() {
return new TomcatServletWebServerFactory() {
#Override
protected TomcatWebServer getTomcatWebServer(org.apache.catalina.startup.Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatWebServer(tomcat);
}
Then I was able to add the JNDI ressource in the server context. Now a JNDI lookup is possible.
In spring boot if we want to connect to mongodb, we can create a configuration file for mongodb or writing datasource in application.properties
I am following the second way
For me, I am gettint this error
"Timeout while receiving message; nested exception is com.mongodb.MongoSocketReadTimeoutException: Timeout while receiving message
.
spring.data.mongodb.uri = mongodb://mongodb0.example.com:27017/admin
I am gettint this error If I am not using my app for 6/7 hours and after that If I try to hit any controller to retrieve data from Mongodb. After 1/2 try I am able to get
Question - Is it the normal behavior of mongodb?
So, in my case it is closing the socket after some particular hours
I read some blogs where it was written you can give socket-keep-alive, so the connection pool will not close
In spring boot mongodb connection, we can pass options in uri like
spring.data.mongodb.uri = mongodb://mongodb0.example.com:27017/admin/?replicaSet=test&connectTimeoutMS=300000
So, I want to give socket-keep-alive options for spring.data.mongodb.uri like replicaset here.
I searched the official site, but can't able to find any
You can achieve this by providing a MongoClientOptions bean. Spring Data's MongoAutoConfiguration will pick this MongoClientOptions bean up and use it further on:
#Bean
public MongoClientOptions mongoClientOptions() {
return MongoClientOptions.builder()
.socketKeepAlive(true)
.build();
}
Also note that the socket-keep-alive option is deprecated (and defaulted to true) since mongo-driver version 3.5 (used by spring-data since version 2.0.0 of spring-data-mongodb)
You can achieve to pass this option using MongoClientOptionsFactoryBean.
public MongoClientOptions mongoClientOptions() {
try {
final MongoClientOptionsFactoryBean bean = new MongoClientOptionsFactoryBean();
bean.setSocketKeepAlive(true);
bean.afterPropertiesSet();
return bean.getObject();
} catch (final Exception e) {
throw new BeanCreationException(e.getMessage(), e);
}
}
Here an example of this configuration by extending AbstractMongoConfiguration:
#Configuration
public class DataportalApplicationConfig extends AbstractMongoConfiguration {
//#Value: inject property values into components
#Value("${spring.data.mongodb.uri}")
private String uri;
#Value("${spring.data.mongodb.database}")
private String database;
/**
* Configure the MongoClient with the uri
*
* #return MongoClient.class
*/
#Override
public MongoClient mongoClient() {
return new MongoClient(new MongoClientURI(uri,mongoClientOptions().builder()));
}
Setup: arquillian, jboss as 7.1.1.final as a managed Container
I am currently migrating an EJB application from EJB 2.x to 3.x and JBoss 3.x to JBoss AS 7.1.
During this process i would like to get most classes under test and stumbled over arquillian.
While arquillian seems to offer some nice features on inter-bean-functionality i cannot figure out whether or not the testing of remote client features using jndi lookups works or not.
I used the Arquillian Getting started guides on my beans which worked, but since these are using #Inject and in my application jndi lookups are used everywhere i (at least think that i) need to swerve from that path.
Here is the TestCase i created based on Arquillian Getting Started. I explicitly left in all attempts using jndi properties of which i thought they might help.
The Test
should_create_greeting()
works if the Greeter bean using a separate Producer.
#RunWith(Arquillian.class)
public class GreeterTest {
public static final String ARCHIVE_NAME = "test";
Logger logger = Logger.getLogger(GreeterTest.class.getName());
#Deployment
public static Archive<?> createDeployment() {
JavaArchive jar = ShrinkWrap.create(JavaArchive.class, ARCHIVE_NAME + ".jar").addPackage(Greeter.class.getPackage())
.addAsManifestResource("test-persistence.xml", "persistence.xml").addAsManifestResource("OracleGUIDS-ds.xml")
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
return jar;
}
/**
* #Inject works using a producer with {#code #Produces}
*/
// #Inject
// Greeter greeter;
#ArquillianResource
Context context;
GreeterRemote greeter;
#Before
public void before() throws Exception {
Map<String, String> env = new HashMap<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.as.naming.InitialContextFactory");
env.put("jboss.naming.client.ejb.context", "true");
// env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT",
// "false");
// env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOANONYMOUS",
// "false");
// env.put("jboss.naming.client.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED",
// "false");
for (Map.Entry<String, String> entry : env.entrySet()) {
context.addToEnvironment(entry.getKey(), entry.getValue());
}
greeter = (GreeterRemote) context.lookup(ARCHIVE_NAME + "/" + Greeter.class.getSimpleName() + "!"
+ GreeterRemote.class.getName());
}
#Test
public void should_create_greeting() {
Assert.assertEquals("Hello, Earthling!", greeter.createGreeting("Earthling"));
greeter.greet(System.out, "Earthling");
}
}
Is it possible to get this test running with jndi lookup? Am i missing something?
If you want to test the Remote features of a EJB you probably want to run on the client side and not in container.
You can configure the Deployment to be only client side by using #Deployment(testable=false). The #Test methods will then run as if you were a remote client.
Beyond that you can just lookup the bean via the injected Context if you want.
I had the same issue, so in a workaround i just added on the method to be tested the remoteejb as a parameter.
On my ejb:
public List localBean.obtain(RemoteEJB remoteEjb){
return remoteEjb.obtain();
}
Then on the arquillian test :
#Inject
private LocalBean localBean;
#Inject
private RemoteEJB remoteEjb;
#Test
public void test(){
List<Vo>voList = localBean.obtain(remoteEjb);
}
The best part is the remote ejb its injected and on the caller method original
#EJB(lookup="java:global/ear/ejb/RemoteEjb")
private RemoteEJB remoteEjb;
volks!
I have a problem. I want to read some messages from Weblogic 12c. This code is currently working with another server, which wasn't configured by me. So the problem may be in configuration of server.
The problem is when I use code:
public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
public final static String JMS_FACTORY="QCF";
public final static String QUEUE="dizzyworldQueue";
public final static String USER_NAME="weblogic";
public final static String USER_PASSWORD="Welcome1";
public final static String URL="t3://localhost:8001";
private static InitialContext getInitialContext(String url) throws NamingException
{
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_PRINCIPAL, USER_NAME);
env.put(Context.SECURITY_CREDENTIALS, USER_PASSWORD);
return new InitialContext(env);
}
qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
qcon = qconFactory.createQueueConnection(); // here it falls
The error is:
Exception in thread "main" javax.naming.NameNotFoundException: Unable to resolve 'QCF'. Resolved '' [Root exception is javax.naming.NameNotFoundException: Unable to resolve 'QCF'. Resolved '']; remaining name 'QCF'
I have Queue and QueueConnection factory on my server. What can be the rison?
The message says that there is no connection factory bound in your naming service (JNDI) with the name "QCF".
So you have to configure your application server to offer the queue connection factory through JNDI.
If that is already the case, you have to change that name in your client code to match the name in JNDI.
You have to add the connection factory and the queue in the admin console.
Look for Services - JMS modules. Possibly add a JMS module, and add a connection factory and queue.
Have a look at this tutorial, it shows the steps to configure it.