Using CometD in custom Ant Listener - cometd

I'm trying to hook up a custom Ant listener to CometD, but I get an NPE where I expect a channel handle. Here's a code snippet:
#Service
public class CometListener implements BuildListener {
#Inject
private BayeuxServer bayeuxServer;
#Session
private LocalSession sender;
private String _channelName;
private ServerChannel _channel = null;
public CometListener() {
_channelName = "/my/test";
}
#PostConstruct
private void initChannel() {
_channel = bayeuxServer.createChannelIfAbsent(_channelName).getReference();
}
public final void buildFinished(final BuildEvent finish) {
// Convert the Update business object to a CometD-friendly format
Map<String, Object> data = new HashMap<String, Object>(4);
data.put("status", 1);
_channel.publish(sender, data);
finish.getProject().log("buildFinished() called.", Project.MSG_ERR);
}
}
I took Using cometd in dropwizard as an example, but the proposed answer didn't fix the problem there.
Thanks in advance for any feedback.

Nevermind, I need a Bayeux client here, not a server.

Related

Dynamic injection using #SpringBean in wicket

I have a form that based on collected information generates a report. I have multiple sources from which to generate reports, but the form for them is the same. I tried to implement strategy pattern using an interface implementing report generator services, but that led to wicket complaining about serialization issues of various parts of the report generator. I would like to solve this without duplicating the code contained in the form, but I have not been able to find information on dynamic injection with #SpringBean.
Here is a rough mock up of what I have
public class ReportForm extends Panel {
private IReportGenerator reportGenerator;
public ReportForm(String id, IReportGenerator reportGenerator) {
super(id);
this.reportGenerator = reportGenerator;
final Form<Void> form = new Form<Void>("form");
this.add(form);
...
form.add(new AjaxButton("button1") {
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit(AjaxRequestTarget target)
{
byte[] report = reportGenerator.getReport(...);
...
}
});
}
}
If I do it this way, wicket tries to serialize the concrete instance of reportGenerator. If I annotate the reportGenerator property with #SpringBean I receive Concrete bean could not be received from the application context for class: IReportGenerator
Edit: I have reworked implementations of IRerportGenerator to be able to annotate them with #Component and now I when I use #SpringBean annotation I get More than one bean of type [IReportGenerator] found, you have to specify the name of the bean (#SpringBean(name="foo")) or (#Named("foo") if using #javax.inject classes) in order to resolve this conflict. Which is exactly what I don't want to do.
I think the behavior you're trying to achieve can be done with a slight workaround, by introducing a Spring bean that holds all IReportGenerator instances:
#Component
public class ReportGeneratorHolder {
private final List<IReportGenerator> reportGenerators;
#Autowired
public ReportGeneratorHolder(List<IReportGenerator> reportGenerators) {
this.reportGenerators = reportGenerators;
}
public Optional<IReportGenerator> getReportGenerator(Class<? extends IReportGenerator> reportGeneratorClass) {
return reportGenerators.stream()
.filter(reportGeneratorClass::isAssignableFrom)
.findAny();
}
}
You can then inject this class into your Wicket page, and pass the desired class as a constructor-parameter. Depending on your Spring configuration you might need to introduce an interface for this as well.
public class ReportForm extends Panel {
#SpringBean
private ReportGeneratorHolder reportGeneratorHolder;
public ReportForm(String id, Class<? extends IReportGenerator> reportGeneratorClass) {
super(id);
IReportGenerator reportGenerator = reportGeneratorHolder
.getReportGenerator(reportGeneratorClass)
.orElseThrow(IllegalStateException::new);
// Form logic omitted for brevity
}
}
As far as I am able to find, looking through documentation and even the source for wicket #SpringBean annotation, this isn't possible. The closest I got is with explicitly creating a proxy for a Spring bean based on class passed. As described in 13.2.4 Using proxies from the wicket-spring project chapter in Wicket in Action.
public class ReportForm extends Panel {
private IReportGenerator reportGenerator;
private Class<? extends IReportGenerator> classType;
private static ISpringContextLocator CTX_LOCATOR = new ISpringContextLocator() {
public ApplicationContext getSpringContext() {
return ((MyApplication)MyApplication.get()).getApplicationContext();
}
};
public ReportForm(String id, Class<? extends IReportGenerator> classType) {
super(id);
this.classType = classType;
final Form<Void> form = new Form<Void>("form");
this.add(form);
...
form.add(new AjaxButton("button1") {
private static final long serialVersionUID = 1L;
#Override
protected void onSubmit(AjaxRequestTarget target)
{
byte[] report = getReportGenerator().getReport(...);
...
}
});
}
private <T> T createProxy(Class<T> classType) {
return (T) LazyInitProxyFactory.createProxy(classType, new
SpringBeanLocator(classType, CTX_LOCATOR));
}
private IReportGenerator getReportGenerator() {
if (reportGenerator = null) {
reportGenerator = createProxy(classType);
}
return reportGenerator;
}
}

Junit , Mockito Integration with Vertx

I am new vertx wanted to know which is the best junit framework and references that we should went through.
I tried using couple of things with mockito but services are not getting injected.
Please help in this.
UPDATE:
My TestClass looks something like this
public class GroupModeTest {
private static final Logger logger = LoggerFactory.getLogger(GroupMode.class);
public static GroupModeService service;
public static GroupModeDao dao;
private GroupMode groupMode;
private static GroupModeDao daoMock;
#BeforeAll
static void setup() {
logger.info("Starting Unit Tests for GroupMode");
daoMock = mock(GroupModeDao.class);
dao = new GroupModeDao();
service = new GroupModeService(daoMock);
}
#BeforeEach
void init() {
logger.info("Mocking new GroupMode Entity");
this.groupMode = new GroupMode();
}
#Test
public void testFakeWithMockito() throws IOException {
IGroupModeDao iGroupModeDao = mock(IGroupModeDao.class);
GroupMode groupMode = new GroupMode();
groupMode.setId(1L);
groupMode.setModeType("unique");
groupMode.setCreatedBy(1);
groupMode.setCreatedOn(LocalDateTime.now());
groupMode.setUpdatedBy(1);
groupMode.setUpdatedOn(LocalDateTime.now());
Single<Long> expected=Single.just(1L);
when(iGroupModeDao.create(groupMode)).thenReturn(expected);
GroupModeService groupModeService = new GroupModeService(iGroupModeDao);
Single<Long> actual= groupModeService.rxCreate("unique",1);
assertEquals(expected, actual);
}
}

Vertx web routes and Reactive Pg Client issue in Quarkus

The application is based on the following stack:
Quarkus 1.5.0
Extensions: vertx-web, reactive-pgclient
The complete codes is here.
I created a Router by #Observes Router.
#ApplicationScoped
public class RoutesObserver {
#Inject PostsHandlers handlers;
public void route(#Observes Router router) {
router.get("/posts").produces("application/json").handler(handlers::getAll);
router.post("/posts").consumes("application/json").handler(handlers::save);
router.get("/posts/:id").produces("application/json").handler(handlers::get);
router.put("/posts/:id").consumes("application/json").handler(handlers::update);
router.delete("/posts/:id").handler(handlers::delete);
router.get("/hello").handler(rc -> rc.response().end("Hello from my route"));
}
}
And extracted the handlers into a standalone bean.
#ApplicationScoped
class PostsHandlers {
private static final Logger LOGGER = Logger.getLogger(PostsHandlers.class.getSimpleName());
PostRepository posts;
ObjectMapper objectMapper;
#Inject
public PostsHandlers(PostRepository posts, ObjectMapper objectMapper) {
this.posts = posts;
this.objectMapper = objectMapper;
}
public void getAll(RoutingContext rc) {
this.posts.findAll().thenAccept(
data -> rc.response()
.write(toJson(data))
.end()
);
}
//... other methods.
}
And the PostRepository used the Java 8 CompletionStage API.
#ApplicationScoped
public class PostRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(PostRepository.class);
private final PgPool client;
#Inject
public PostRepository(PgPool _client) {
this.client = _client;
}
public CompletionStage<List<Post>> findAll() {
return client.query("SELECT * FROM posts ORDER BY id ASC")
.execute()
.thenApply(rs -> StreamSupport.stream(rs.spliterator(), false)
.map(this::from)
.collect(Collectors.toList())
);
}
And when I ran this application and tried to access the /posts. It is frozen and no response printed.
When using the write method, you need to set (beforehand) the content-length header.
There are a several approaches to handle this:
You can use .end(toJson(data)) instead of write(...).end() - it will computed the length automatically
You can use .putHeader("transfer-encoding", "chunked") and you write(...).end() - if you plan to retrieve multiple results, it's interesting as it writes each chunk to the client one by one, avoiding sending a large payload in one go
you can set the content-length as in:
String result = toJson(data);
rc.response()
.putHeader("content-length", Long.toString(result.length()))
.write(result)
.end();

Integration Tests for RESTEasy Endpoint

I want to perform integration tests on my REST endpoint but am running into issues.
Below is my endpoint. NOTE: I cannot change this part of the code.
#Path("/people")
public class PersonResource {
private final PersonService personService;
#Inject
public PersonResource(final PersonService personService) {
this.personService = personService;
}
#GET
#Produces("application/json")
public List<Person> getPersonList() {
return personService.getPersonList();
}
}
From what I've been able to find online, I have the following basic structure for my test.
public class PersonResourceTest {
private Dispatcher dispatcher;
private POJOResourceFactory factory;
#Before
public void setup() {
dispatcher = MockDispatcherFactory.createDispatcher();
factory = new POJOResourceFactory(PersonResource.class);
dispatcher.getRegistry().addResourceFactory(factory);
}
#Test
public void testEndpoint() throws URISyntaxException {
MockHttpRequest request = MockHttpRequest.get("people");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
System.out.print("\n\n\n\n\n" + response.getStatus() + "\n\n\n\n\n");
System.out.print("\n\n\n\n\n" + response.getContentAsString() + "\n\n\n\n\n");
}
}
However, this results in the following error on the last line of the setup method.
java.lang.RuntimeException: RESTEASY003190: Could not find constructor for class: my.path.PersonResource
I explored the Registry API and thought maybe I should have been using addSingletonResource instead, so I changed the last line of setup to dispatcher.getRegistry().addSingletonResource(personResource); and added the following.
#Inject
private PersonResource personResource;
But that results in a NullPointerException on the last line of setup.
The sparse documentation on the mocking isn't very helpful. Can anyone point out where I'm going wrong? Thanks.
You need to do two things
Add a no arguments constructor to your source class:
public PersonResource() {
this(null)
}
In the test class, initialize the PersonResource class with an instance of PersonService class:
dispatcher.getRegistry().addSingletonResource(new PersonResource(new PersonService()));
If needed, the PersonService class can be mocked:
private Dispatcher dispatcher;
#Mock
private PersonService service;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
dispatcher = MockDispatcherFactory.createDispatcher();
PersonResource resource= new PersonResource(service);
ispatcher.getRegistry().addSingletonResource(resource);
}
Hope it helps!

How to get javax.validation payload validation for spring-cloud-aws in QueueMessageHandler working?

I'm writing some message consumer for an AWS SQS and want to validate the received message by using the javax.validation.constraints annotations.
Unfortunately I had to find out, that the used PayloadArgumentResolver of the spring-cloud-aws-messaging dependency uses a NoOpValidator.
So I tried to inject my own HandlerMethodArgumentResolver for the payload.
#Bean
public QueueMessageHandlerFactory queueMessageHandlerFactory(
final ObjectMapper objectMapper, final Validator hibernateValidator) {
final MappingJackson2MessageConverter jacksonMessageConverter =
new MappingJackson2MessageConverter();
jacksonMessageConverter.setSerializedPayloadClass(String.class);
jacksonMessageConverter.setStrictContentTypeMatch(true);
jacksonMessageConverter.setObjectMapper(objectMapper);
final QueueMessageHandlerFactory factory = new QueueMessageHandlerFactory();
final List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();
argumentResolvers.add(new HeaderMethodArgumentResolver(null, null));
argumentResolvers.add(new HeadersMethodArgumentResolver());
argumentResolvers.add(new NotificationSubjectArgumentResolver());
argumentResolvers.add(new AcknowledgmentHandlerMethodArgumentResolver("Acknowledgment"));
argumentResolvers.add(new VisibilityHandlerMethodArgumentResolver("Visibility"));
final PayloadArgumentResolver payloadArgumentResolver =
new PayloadArgumentResolver(jacksonMessageConverter, hibernateValidator);
argumentResolvers.add(payloadArgumentResolver);
factory.setArgumentResolvers(argumentResolvers);
return factory;
}
So far so good and at first sight, it works well...
BUT as you can see I had to add the already in QueueMessageHandler existing argument resolvers as well to resolve the headers via #Headers/#Header of the message, too.
#SqsListener(
value = "queue",
deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void consume(
#Payload #Validated final QueueMessage queueMessage,
#Headers final Map<String,Object> headers) {
}
When I only add my PayloadArgumentResolver with the hibernate validator, it will be also used to resolve the headers, doh!
Is there any pretty solution for this or should I open an issue at spring-cloud-aws? I just want my payload to be validated via annotations :(
I don't think this is the best awswer but I have a working sample project that have this type of validation: https://github.com/Haple/sqslistener
#Data
#RequiredArgsConstructor
#JsonIgnoreProperties(ignoreUnknown = true)
#NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
public class EventDTO {
#NotNull(message = "foo is mandatory")
private final String foo;
#NotNull(message = "bar is mandatory")
private final String bar;
}
#Slf4j
#Service
#AllArgsConstructor
public class SampleListener {
#SqsListener("test_queue")
public void execute(final #Valid #Payload EventDTO event) {
log.info("OK: {}", event);
}
}
#Configuration
public class MessageHandler {
#Bean
QueueMessageHandler queueMessageHandler(final AmazonSQSAsync amazonSQSAsync,
final MessageConverter messageConverter,
final Validator validator) {
final QueueMessageHandlerFactory queueMessageHandlerFactory = new QueueMessageHandlerFactory();
final PayloadMethodArgumentResolver payloadMethodArgumentResolver = new PayloadMethodArgumentResolver(messageConverter, validator);
queueMessageHandlerFactory.setArgumentResolvers(Collections.singletonList(payloadMethodArgumentResolver));
queueMessageHandlerFactory.setAmazonSqs(amazonSQSAsync);
queueMessageHandlerFactory.setMessageConverters(Collections.singletonList(messageConverter));
return queueMessageHandlerFactory.createQueueMessageHandler();
}
}