I'm working right now with Apache Wicket using Groovy language. I was wondering is there any chance to improve Apache Wicket for Groovy programming?
What's on my mind. I want have ability to write code like this:
new AjaxLink("ajaxLink", {link, target -> /* some Closure body */ })
But without creating decorators like
class GroovyWicketAjaxLink extends AjaxLink {
def clickClosure;
GroovyWicketAjaxLink(wicketId, onClickClosure) {
super(wicketId)
this.clickClosure = onClickClosure
}
void onClick(AjaxRequestTarget target) {
clickClosure.call([this, target]);
}
}
Maybe there is some way to create some kind of DefaultWicketGroovyMethods with support exactly like for DefaultGroovyMethods?
I think you should start an open-source project called Gricket, a Groovy DSL for Wicket, where you could write stuff like:
code = { // i wrote this in a closure, but you can write it in a separate file
ajaxLink id: "link", onClick: { ->
// write the link
}
}
Which would be parsed as scripts, and missingMethod calls are resolved as instantiation of apache wicket classes:
class GricketParser {
def components = []
def methodMissing(String method, args) {
def clazz = "org.apache.wicket.ajax.markup.html." + method.capitalize() as Class
def component = clazz.newInstance()
args[0].each { key, value -> component[key] = value }
}
}
code.delegate = new GricketParser()
code()
You could also apply metaprogramming on top of String class instead of parsing a script
Update:
Seems like the idea was proposed back in 2008, with some problems regarding groovy support for anonymous classes. Time for a new WicketBuilder? :-)
Finally, I had created the project that you are asking for. I used ExtensionModule groovy feature, so you just need to import a dsl project from github and start using it.
The syntax for AjaxLink with label will look like this:
#Override
void onInitialize() {
ajaxLink('link') {
label('label')
click { AjaxRequestTarget t, AjaxLink link -> // or even without these params
}
}
}
You can chain components like you are imagine them in your mind :) Feel the groovy freedom with Wicket. All methods inside WicketDSL class includes #DelegatesTo and #ClosureParams annotations, so you can feel great IDE support for DSL. Also #CompileStatic groovy annotation is supported for all your code written with this DSL. It should great increase performance.
Checkout two github branches here:
https://github.com/eugene-kamenev/wicket-groovy-DSL
And feel free to contact me.
Related
While working on a .NET project I come across a library MediatR which made CQRS and Commands simple to implement. I really like using commands and commands handlers as I've worked on far too many projects that have giant procedural style service classes that inject way to many dependencies making unit testing painful. I am looking for something similar to MediatR for Spring + Java. Essentially I would like to inject a single dependency into the controller class and have it delegate commands to the appropriate command handler. I provided a few snippets of what MediatR looks like below. I prefer the way mediator does it as injecting the CommandHandlers into the controller class can lead to the same issue with the class having tons of dependencies injected.
I've came across this library but it seems more like a side project that something that is production ready. https://github.com/sleroy/spring-cqrs-arch. I am aware of the Axon framework, but I'm not looking to go full blown event sourcing at this point. Are there any libraries out there already for this that maybe I'm haven't stumbled across yet? I suppose I could just use the Guava EventBus.
Below is a C# example of what MediatR usage looks like.
Controller
namespace DAB.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PersonController : ControllerBase
{
private readonly IMediator mediator;
public PersonController(IMediator mediator)
{
this.mediator = mediator;
}
// GET api/values
[HttpPut("{id}/changename")]
public async Task<ActionResult> ChangeName([FromBody] ChangeNameCommand command)
{
await this.mediator.Send(command);
return Ok();
}
}
}
Command
public class ChangeNameCommand: IRequest<bool>
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
CommandHandler
public class ChangeNameHandler: IRequestHandler<ChangeNameCommand, bool>
{
public Task<bool> Handle(ChangeNameCommand request, CancellationToken cancellationToken)
{
Console.WriteLine($"Changing name to {request.FirstName} {request.LastName}");
return Task.FromResult(true);
}
}
Check out PipelinR. It's 15KB, zero-dependency library, with a nice Spring and Spring Boot integration.
if you are still looking for a similar library, I made a library that works similarly with mhinze/ShortBus. You may check it at https://github.com/kazupooot/shortbus. Currently it supports single handler request/response message.
Trying to find a way to wraps an object, which is auto generated based on some model with lots of getters and setters. For example:
class ObjectToWrap {
public int getIntA();
public int getIntB();
... // Tons of other getters
}
I have to create a wrapper that wraps this object and use some annotation that generates methods from ObjectToWrap for me. Code looks like the following:
class Wrapper {
private ObjectToWrap obj;
public int getIntA() {
return obj.getIntA();
}
public int getIntB() {
return obj.getIntB();
}
... // Tons of other getters
}
Is there an annotation to do this? I just don't want to make the code look lengthy.
Take a look at Project Lombok which has a #Delegate annotation which does exactly what you want.
#Delegate documentation
I think you would be able to do this:
import lombok.Delegate;
class Wrapper {
//the types field in the annotation says
//to only auto generate deleagate methods
//for only the public methods in the ObjectToWrap class
//and not any parent classes if ObjectToWrap extended something
#Delegate(types = ObjectToWrap.class)
private ObjectToWrap obj;
}
If you are using the maven build infrastructure with dependency management, you could have a dependent sub-project that collects the generated sources as-is (not as code). Another sub-project could then generate real sources out of them (source code transformation) as zip, which then could be imported by maven in the main project as pre-compile target.
On that basis you could use dynamic proxy classes, or even immediate generated classes.
The only other alternative would be to use the java scripting API, and do the business in JavaScript or so. Loosing the type safeness of java and lowering the software quality.
Unfortunately the alternative of hybrid usage of another JVM language I cannot consider productive. The very nice and powerful Scala still is too wild/complex/ticklish.
I am building an Android app. Now, I have a source code for API #1, I should get it adapted for API #2. Then I will publish the both versions for API #1 and API #2 in different packages. I can't use something like values-en, because both versions can be used worldwide. Also, the user may not have choice.
As the new version will use same UI and DB logic, (and because now the code is erroneous,) I don't want to separate the code. If i were coding in c or c++, I must use #ifdef and Makefile. However, I'm in Java. It's possible to run the API-dependent code by determining the package name in runtime, but it's somewhat weird.
I think I can use annotations. What I expect is:
package foo.app;
public class API {
public boolean prepare() { ... }
#TargetPlatform(1)
public void open() { ... }
#TargetPlatform(2)
public void open() { ... }
}
and use only one of them. Also, this is good:
package foo.app;
public class R {
#TargetPlatform(1) com.example.foo.app.R R;
#TargetPlatform(2) net.example.foo.app.R R;
}
Just defining an annotation is simple. What I don't know is, how can I exclude unused duplicates from build or execution, or so on? If the work can be done in this way, I can do anything.
You cannot use annotations for that.
It would be better to hide the implementation specific classes behind an interface.
public interface Api {
boolean prepare();
void open();
}
To create a Api instance use a factory class:
public class ApiFactory {
public static Api createApi() {
if(isTargetPlatform1())
return new com.example.foo.app.Api();
else
return new net.example.foo.app.Api();
}
private boolean isTargetPlatform1() {
// determine the current platform, e.g. by reading a configuration file
}
}
In all other places you only refer to the Api interface and ApiFactory class.
Use it like that:
Api api = ApiFactory.createApi();
api.open();
// ...
A more advanced solution would be to use dependency injection.
I'm trying to write a MWE2 workflow component using scala language.
Below is the scala code:
package com.ford.modelling.workflow
import org.eclipse.emf.mwe2.runtime.workflow.{IWorkflowComponent, IWorkflowContext}
class SayHello extends IWorkflowComponent {
var message : String = null;
def preInvoke {}
def invoke(ctx : IWorkflowContext) { System.out.println(message) }
def postInvoke {}
}
and below is the workflow code:
module com.ford.modelling.workflow.SomeWorklow
SayHello {}
I can't figure out why does this workflow complain for error:
'com.ford.modelling.workflow.SayHello' does not have a public default constructor.
I'd assume that the scala IDE plugin does not mimic the java protocol completely, e.g. the IType does not expose a no-args constructor. You may want to ask the scale folks about it.
The error message should vanish as soon as you add a default constructor explicitly. Does that make sense?
A quick google search indicated that there probably no syntax for a default constructor so I'd assume it's a scala tooling problem. Does the problem occur at runtime, too?
If I create a custom annotation like this:
public #interface TODO
{
String msg();
String start_date();
}
then a method:
#TODO
(
msg="will be developed!",
start_date="05/01/2010"
)
public static void Calculator()
{
}
after I call it:
Calculator();
If I wanted that the compiler warn me about it how could I do that?
There was a similar question, some weeks ago. Here is the link to both the question and my answer.
You can easily adapt this code to your needs.
You must write an annotation processor and invoke apt to run it on your code.
Use the Annotation Processing Tool (apt) to make your own AnnotationProcessor and print the message with javax.annotation.processing.Messager
If you are using an IDE, there are plenty of good options. For Eclipse:
use the built-in plug-in which locates all TODO, FIXME, etc. words in your code and puts them in a special view.
register your own custom builder which can show you the warnings