Any examples of using Spring #ManagedNotification annotation to generate JMX notfications - java

I've been looking around and haven't found any examples of using spring annotations to generate JMX notifications. I have found examples using #ManagedAttribute and #ManagedOperation.
Thanks
-Bill

Here you go:
import java.util.concurrent.atomic.AtomicLong;
import javax.management.Notification;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.jmx.export.notification.NotificationPublisher;
import org.springframework.jmx.export.notification.NotificationPublisherAware;
#ManagedResource
public class JMXDemo implements NotificationPublisherAware {
private final AtomicLong notificationSequence = new AtomicLong();
private NotificationPublisher notificationPublisher;
#Override
public void setNotificationPublisher(
final NotificationPublisher notificationPublisher) {
this.notificationPublisher = notificationPublisher;
}
#ManagedOperation
public void trigger() {
if (notificationPublisher != null) {
final Notification notification = new Notification("type",
getClass().getName(),
notificationSequence.getAndIncrement(), "The message");
notificationPublisher.sendNotification(notification);
}
}
}
And in your Spring configuration file you must use something like this:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<context:mbean-server id="mbeanServer" />
<context:mbean-export server="mbeanServer" />
<bean class="org.springframework.jmx.export.MBeanExporter">
<property name="server" ref="mbeanServer" />
<property name="namingStrategy">
<bean id="namingStrategy"
class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
<property name="attributeSource">
<bean
class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource" />
</property>
</bean>
</property>
</bean>
</beans>
You can then access above bean with JConsole and trigger notifications with the operation trigger(). Be sure to subscribe to the notifications. :)

You can add notification details (Notification MetaData) to the exposed JMX MBean as well using #ManagedNotifications annotation.
Apply bellow annotation on Class JMXDemo along with #ManagedResource annotation
#ManagedNotifications({ #ManagedNotification(name = "javax.management.Notification", notificationTypes = { "notification type" }, description = "notification description") })
Above details will show the notification details under JConsole Notification details option.

Related

Couldn't pass the #bean value to another class through Autowiring

I am new to spring. So I couldn't figure out what issue is there in the below code. I have two classes. I am defining a #Bean Channel and am autowiring that bean in the next class. I am using annotation for autowiring. When I try " System.out.println(externalChannel.toString());" am getting null values and the exception null pointer exception is thrown.
#Configuration
public class MessagingConfig
{
#Value("${service.name}")
private String queueName; // NOSONAR
#Value("${${user}")
private String schema;
#Value("${Owner}")
private String owner;
#Bean
public Channel externalChannel()
{
EventsProvider eventsProvider = new EventsProvider();
eventsProvider.setOwner(owner);
System.out.println("-------Cost And Events Channel-------"+eventsProvider.getEventsChannel());
return eventsProvider.getEventsChannel();
}
}
And Another class is
#Component
#LoggedService
#Monitored(useActualType = true)
public class MessagePublish {
#Autowired
private MessagingService messageService;
#Autowired
private Channel externalChannel;
public void publishTPSMessage(SourceTransaction sourceTransaction)
{
TPSEvent event = new TPSEvent(ContextHolder.getContextId(), new Date(), GuidUtils.generateGuid(),sourceTransaction);
Message<TPSEvent> message = new Message<TPSEvent>(event);
message.getHeader().setMessageType(TPSEvent.class.getName());
message.getHeader().setPayloadEncodingType(SystemCodecs.XML.name());
System.out.println(message.toString());
System.out.println(externalChannel.toString());
messageService.publish(externalChannel, message);
}
}
More Info
public Channel getEventsChannel() {
return Channel.builder()
.setName("necessarySources")
.setConnectionName("defaultConnection")
.setType(ChannelType.Topic)
.setConnectionData(AqSqlConnectionData.buildString(this.owner, "Safi"))
.setSubscriberNames(new String[]{"Safi_Autowire"})
.build();
}
Main Class
public class TPSHandler {
public static void main(String[] args) {
BatchExport batchExportBean=getBatchExportASJAXBElement();
System.out.println(" batchExportBean Trans Description : " + batchExportBean.getDueDate());
for(Pay pay :batchExportBean.getPay()) {
SourceTransaction sourceTransaction=mapPayBatchToSourceTransaction(pay,batchExportBean);
String sourceTraString = getSourceTransactionASXML(sourceTransaction);
System.out.println(" sourceTraString : \n" + sourceTraString);
MessagePublish messagePublish= new MessagePublish();
//SourceTransaction sourceTransaction= new SourceTransaction();
messagePublish.publishTPSMessage(sourceTransaction);
}
}
}
My Servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:config-properties.xml" />
<import resource="classpath:datasource.xml" />
<import resource="classpath:transaction-manager.xml" />
<import resource="classpath:jmx.xml" />
<context:component-scan base-package="com.imosAdapter" />
<bean class="com.oasis.services.messaging.config.MessagingServicesConfig" />
<bean class="com.oasis.services.messaging.config.DefaultMessagingConnectorsConfig" />
<bean class="com.oasis.services.messaging.config.LoaderConfig" />
<context:annotation-config />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/config/oasis-component.properties</value>
</property>
</bean>
</beans>
The exception thrown:
Exception in thread "main" java.lang.NullPointerException
at com.imosAdapter.tps.events.MessagePublish.publishTPSMessage(MessagePublish.java:46)
at com.imosAdapter.tps.TPSHandler.main(TPSHandler.java:64)
What is the issue over here? Can anybody help me with this? what exactly I am missing here?
You need to initialize a Spring context at the start of your application when you do not create a servlet / run as a Server.
See Using Spring in a standalone application

Neo4j with Spring: No bean named 'getSessionFactory' available

I'm new to neo4j and spring in combination and spring at all. When I start debugging, I get the following exception:
Exception in thread "main"
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'getSessionFactory' available
Can anyone help me please?
apllication-context.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="de.unileipzig.analyzewikipedia.neo4j" />
<!--neo4j:config storeDirectory="C:/temp/neo4jdatabase" base-package="de.unileipzig.analyzewikipedia.neo4j.dataobjects"/-->
<neo4j:repositories base-package="de.unileipzig.analyzewikipedia.neo4j.repositories"/>
<tx:annotation-driven />
<bean id="graphDatabaseService" class="org.springframework.data.neo4j.support.GraphDatabaseServiceFactoryBean"
destroy-method="shutdown" scope="singleton">
<constructor-arg value="C:/develop/uni/analyze-wikipedia-netbeans/database"/>
<constructor-arg>
<map>
<entry key="allow_store_upgrade" value="true"/>
</map>
</constructor-arg>
</bean>
</beans>
Startup-Class
package de.unileipzig.analyzewikipedia.neo4j.console;
import de.unileipzig.analyzewikipedia.neo4j.dataobjects.Article;
import de.unileipzig.analyzewikipedia.neo4j.service.ArticleService;
import java.io.File;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Neo4JConsole {
/**
* MAIN: start the java file
*
* #param args as string array
*/
public static void main(String[] args) {
String cwd = (new File(".")).getAbsolutePath();
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
ArticleService service = (ArticleService) context.getBean("articleService");
Article art = createArticle();
createArticle(service, art);
System.out.println("Article created");
}
private static Article createArticle() {
Article article = new Article();
article.setTitle("Title");
return article;
}
private static Article createArticle(ArticleService service, Article art) {
return service.create(art);
}
}
Thank you.
Do you have this configuration?
#Configuration
#EnableNeo4jRepositories("org.neo4j.cineasts.repository")
#EnableTransactionManagement
#ComponentScan("org.neo4j.cineasts")
public class PersistenceContext extends Neo4jConfiguration {
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("org.neo4j.cineasts.domain");
}
}
For more information, try to look here

How To enhance The Callback handler CXF Interceptor method

I made a WSS4JInInterceptor in a spring bean configuration file as follows
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxws:endpoint id="book"
implementor="net.ma.soap.ws.endpoints.IBookEndPointImpl" address="/bookAuth">
<jaxws:inInterceptors>
<bean class="org.apache.cxf.binding.soap.saaj.SAAJInInterceptor"></bean>
<bean class="org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor">
<constructor-arg>
<map>
<entry key="action" value="UsernameToken" />
<entry key="passwordType" value="PasswordText" />
<entry key="passwordCallbackClass" value="net.ma.soap.ws.service.ServerPasswordCallback"></entry>
</map>
</constructor-arg>
</bean>
</jaxws:inInterceptors>
</jaxws:endpoint>
</beans>
The ServerPasswordCallBack.java looks like the following
package net.ma.soap.ws.service;
import java.io.IOException;
import java.util.ResourceBundle;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.wss4j.common.ext.WSPasswordCallback;
public class ServerPasswordCallback implements CallbackHandler {
private static final String BUNDLE_LOCATION = "zuth";
private static final String PASSWORD_PROPERTY_NAME = "auth.manager.password";
private static String password;
static {
final ResourceBundle bundle = ResourceBundle.getBundle(BUNDLE_LOCATION);
password = bundle.getString(PASSWORD_PROPERTY_NAME);
}
#Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
WSPasswordCallback pc = (WSPasswordCallback) callbacks[0];
pc.setPassword(password);
}
}
With the password verification, everything work just fine.
I'd like to know if there's any other way to enhance the handle(Callback) method to make it more sophisticated so it would be able to check more than just one parameter, for example if i can make it check an access token, it would be much more better.
the password property is defined in zuth_fr_FR.properties file as follows
auth.manager.password=najah
If you want to do some custom validation on your username and token (such as verify against a directoryservice using LDAP or something similar) you can write your own custom UsernameTokenValidator overriding verifyPlaintextPassword(UsernameToken usernameToken) of UsernameTokenValidator and hook it up to your WSS4JInInterceptor adding the following to your bean definition
<property name="wssConfig">
<ref bean="usernameTokenWssConfig"/>
</property>
And add the referenced class to your codebase:
#Component("usernameTokenWssConfig")
public class usernameTokenWssConfigWSSConfig {
public usernameTokenWssConfig() {
setValidator(WSSecurityEngine.USERNAME_TOKEN, new CustomUsernameTokenValidator());
setRequiredPasswordType(WSConstants.PASSWORD_TEXT);
}
}

Spring - what is wrong with my Autowiring?

I've this basic spring application in which the value of my #Autowired field is null in output. What is wrong here?
package com.spring;
import org.springframework.beans.factory.annotation.Autowired;
public class HelloWorld {
private String message;
#Autowired
private Double pi;
public HelloWorld(String message){
this.message = message;
}
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
System.out.println("autowired: "+pi);
}
}
spring.xml config file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="pi" name="pi" class="java.lang.Double" autowire="byName">
<constructor-arg value="3.14"/>
</bean>
<bean id="helloWorld" class="com.spring.HelloWorld">
<constructor-arg ref="msg" />
</bean>
<bean id="msg" class="java.lang.String" >
<constructor-arg value="Hello World"/>
</bean>
</beans>
Class to execute the APP:
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
HelloWorld hw = context.getBean(HelloWorld.class);
hw.getMessage();
System.out.println(context.getBean("msg"));
}
}
The output is:
Your Message Hello World
autowired: null
Hello World
You need to configure the context to allow autowiring. See this answer:
how do I configure autowire in spring
You need to add <context:annotation-config/> in your spring.xml file which will scan for spring annotations in your java files. Hope this helps.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean id="pi" name="pi" class="java.lang.Double">
<constructor-arg value="3.14" />
</bean>
<bean id="helloWorld" class="com.clsa.test.HelloWorld">
<constructor-arg ref="msg" />
</bean>
<bean id="msg" class="java.lang.String">
<constructor-arg value="Hello World" />
</bean>
</beans>
you want to define #Quatifier
#Autowired(required=true)
#Qualifier("pi")
Double pi;

Why is this spring bean not initialised? It is always null.

I have a message factory bean configured as shown below:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ws="http://www.springframework.org/schema/web-services"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="soapMessageFactory" class="javax.xml.soap.MessageFactory" factory-method="newInstance" />
<bean id="saajMessageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<constructor-arg ref="soapMessageFactory" />
</bean>
<bean id="myService" class="com.mypackage.TestEndPoint">
<property name="saajMessageFactory" ref="saajMessageFactory" />
</bean>
</beans>
The TestEndpoint class looks like this
#Endpoint
public class TestEndPoint {
ObjectFactory objectFactory = new ObjectFactory();
SaajSoapMessageFactory saajMessageFactory;
#PayloadRoot(namespace="http://ws.mypackage.com", localPart="downloadSaajMessageRequest")
#ResponsePayload
public JAXBElement<DownloadResponseSaajType> invoke(#RequestPayload DownloadSaajMessageRequest req, MessageContext context ) throws Exception {
DownloadResponseSaajType response = new DownloadResponseSaajType();
//DownloadResponseSaajType.PayLoad payload = new DownloadResponseSaajType.PayLoad();
DataHandler handler = new javax.activation.DataHandler(new FileDataSource("c:\\temp\\maven-feather.png"));
SaajSoapMessage message = saajMessageFactory.createWebServiceMessage();
message.addAttachment("picture", handler);
message.addAttachment("picture", handler);
//payload.setMessagePayLoad(handler);
//response.setPayLoad(payload);
response.setRequestName("NAMEOF");
context.setResponse(message);
return objectFactory.createDownloadSaajMessageResponse(response);
}
public void setSaajMessageFactory(SaajSoapMessageFactory saajMessageFactory){
this.saajMessageFactory = saajMessageFactory;
}
public SaajSoapMessageFactory getSaajMessageFactory(){
return saajMessageFactory;
}
}
I am having a few problems trying to get the endpoint to work and when i tried to debug the code i found that saajMessageFactory is never initialised and it is always null. Have i done something wrong with the configuration?
You have to add PayloadRootAnnotationMethodEndpointMapping bean to your configuration xml.
<bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping"/>

Categories