How to implement Java interfaces in Frege? - frege

I have been trying out Frege and one of the first things I would like to do is implement a Java interface.
How is that done?
Here's my example in Java:
package mypkg;
import frege.repl.FregeRepl;
import frege.runtime.Concurrent;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class FregeMain implements BundleActivator {
public FregeMain() {
}
#Override
public void start( BundleContext context ) throws Exception {
System.out.println( "Frege Bundle activated" );
new Thread( () -> FregeRepl.main( new String[ 0 ] ) ).start();
}
#Override
public void stop( BundleContext context ) throws Exception {
System.out.println( "Frege stopping. Goodbye!" );
Concurrent.shutDownIfExists();
}
}
To implement this in Frege, I would need to know:
how to declare something that will be visible as a class called mypkg.FregeMain implementing BundleActivator in JVM bytecode (notice that this is important as the OSGi framework will scan the jar for classes implementing that interface, and call them automatically).
How to implement a Runnable (as a Haskell lambda, probably) and pass it on to the Thread constructor. Also same issue: implement a Java interface, but this time with an anonymous class or lambda.
I tried to understand the Calling Java from Frege post, but probably due to my lack of experience in Frege/Haskell, I just don't understand most of that.
Thanks for any input.

The simplest way to implement Java interface in Frege is possibly to use an inline module definition. Some thorough examples are in https://github.com/Frege/FregeFX/blob/master/fregefx/src/main/frege/fregefx/JavaFxUtils.fr

Related

how to transform interface to abstract by using javassist

I am using javassist library for modify class files.
I want to modify interface to abstract class
for example,
original :
public interface javax.servlet.Servlet {
public void init(ServletConfig config) throws ServletException;
}
modified :
public abstract javax.servlet.Servlet {
public void init(ServletConfig config) throws ServletException {
System.out.println(config.getServletContext().getServerInfo());
callMethod(); // this is implemented original method
}
}
How can i apply this solution like aop(before, after)?
I think the first problem with your approach is that when you try to modify your interface using Javassist you are attempting to redefine an interface that has been already loaded by the class loader.
One option might be to do a bit of classloader tricks: create a new classloader that doesn't have your existing interface loaded (parent is the system classloader) and have Javassist load through that (use aCtClass.toClass() method that takes a ClassLoader argument). However is not really something I would do since to manage properly more than one ClassLoader is not that easy.
There might be a better way to achieve your goal, and creating new classes might be a better design. You could create a new class that implements everything you need and then extends the required interface.
Moreover I suggest you to take also a look at dynamic proxies that could be an option as well. Their biggest advantage is that you don't need any 3rd party libraries to create them.

Guice Names.bindProperties(binder(), properties) on output of a module?

I use an external service to provide properties, but want to make those properties available as #Named(..) vars. Trying to do this in a configure method fails with npe:
Names.bindProperties(binder(), myPropRetriever.getProperties());
is failing because the myPropRetriever isn't appearing until guice has done it's work. I can see why this makes sense - anyone know of any funky hacks that might work around though? Would be handy in this instance..
Thanks to durron597 for the pointer to the related question which gave me enough to figure out. The answer is to use a child injector to take action on the previous injectors output. Example below:
Injector propInjector = Guice.createInjector(new PropertiesModule());
PropertiesService propService = propInjector.getInstance(PropertiesService.class);
Injector injector = propInjector.createChildInjector(new MyModule(Objects.firstNonNull(propService.getProperties(), new Properties())));
Injector is now your injector for the remainder of the app.
And then in MyModule you can take action on the created objects:
public class MyModule extends AbstractModule {
private final Properties properties;
public MyModule(Properties properties){
this.properties=properties;
}
#Override
protected void configure() {
// export all the properties as bindings
Names.bindProperties(binder(), properties);
// move on to bindings
// bind(..);
}
}
In case it helps anyone else..!

Interceptor on super method in CDI 1.0/JEE6

In the following case,
public class Base {
#Transactional
public void doSave() {
// ...
}
}
public class Inherited extends Base {
public void someMethod() {
super.doSave();
}
#Override
public void doSave() {
super.doSave();
}
}
If I add the #Transactional annotation to Inherited.someMethod, the interceptor gets called without issue.
However, without the annotation on the inherited class, the interceptor does not get involved in the call to the super class from Inherited.someMethod().
Furthermore, calling Inherited.doSave() does not seem to get the interceptor invoked either. I would have expected the annotation on the superclass to be also valid on the subclass. Is this not the expected behaviour?
I am using Apache DeltaSpike for the #Transactional annotation and this is being deployed as a war in an ear (technically as a jar in a war in an ear). However, this may not be relevant as trying with a custom interceptor shows the same behaviour.
This is JBoss EAP 6.3.0 Alpha in case its relevant.
This is expected. Interceptors are only applied if the object is managed. When you you write it this way with inheritence, it's not applied as it's not part of a call stack that CDI is aware of. You would need to inject Base into your class and call Base.doSave

wicket and AtUnit

I've started playing with Wicket and I've chosen Guice as dependency injection framework. Now I'm trying to learn how to write a unit test for a WebPage object.
I googled a bit and I've found this post but it mentioned AtUnit so I decided to give it a try.
My WebPage class looks like this
public class MyWebPage extends WebPage
{
#Inject MyService service;
public MyWebPage()
{
//here I build my components and use injected object.
service.get(id);
....
}
}
I created mock to replace any production MyServiceImpl with it and I guess that Guice in hand with AtUnit should inject it.
Now the problems are:
AtUnit expects that I mark target object with #Unit - that is all right as I can pass already created object to WicketTester
#Unit MyWebPage page = new MyWebPage();
wicketTester.startPage(page);
but usually I would call startPage with class name.
I think AtUnit expects as well that a target object is market with #Inject so AtUnit can create and manage it - but I get an org.apache.wicket.WicketRuntimeException: There is no application attached to current thread main. Can I instruct AtUnit to use application from wicketTester?
Because I don't use #Inject at MyWebPage (I think) all object that should be injected by Guice are null (in my example the service reference is null)
I really can't find anything about AtUnit inside Wicket environment. Am I doing something wrong, am I missing something?
I don't know AtUnit but I use wicket with guice and TestNG. I imagine that AtUnit should work the same way. The important point is the creation of the web application with the use of guice.
Here how I bind all this stuff together for my tests.
I have an abstract base class for all my tests:
public abstract class TesterWicket<T extends Component> {
#BeforeClass
public void buildMockedTester() {
System.out.println("TesterWww.buildMockedTester");
injector = Guice.createInjector(buildModules());
CoachWebApplicationFactory instance =
injector.getInstance(CoachWebApplicationFactory.class);
WebApplication application = instance.buildWebApplication();
tester = new WicketTester(application);
}
protected abstract List<Module> buildModules();
The initialization is done for every test class. The subclass defines the necessary modules for the test in the buildModules method.
In my IWebApplicationFactory I add the GuiceComponentInjector. That way, after all component instantiation, the fields annotated with #Inject are filled by Guice:
public class CoachWebApplicationFactory implements IWebApplicationFactory {
private static Logger LOG = LoggerFactory.getLogger(CoachWebApplicationFactory.class);
private final Injector injector;
#Inject
public CoachWebApplicationFactory(Injector injector) {
this.injector = injector;
}
public WebApplication createApplication(WicketFilter filter) {
WebApplication app = injector.getInstance(WebApplication.class);
Application.set(app);
app.addComponentInstantiationListener(new GuiceComponentInjector(app, injector));
return app;
}
}

Architecture of some reusable code

I am writing a number of small, simple applications which share a common structure and need to do some of the same things in the same ways (e.g. logging, database connection setup, environment setup) and I'm looking for some advice in structuring the reusable components. The code is written in a strongly and statically typed language (e.g. Java or C#, I've had to solve this problem in both). At the moment I've got this:
abstract class EmptyApp //this is the reusable bit
{
//various useful fields: loggers, db connections
abstract function body()
function run()
{
//do setup
this.body()
//do cleanup
}
}
class theApp extends EmptyApp //this is a given app
{
function body()
{
//do stuff using some fields from EmptyApp
}
function main()
{
theApp app = new theApp()
app.run()
}
}
Is there a better way? Perhaps as follows? I'm having trouble weighing the trade-offs...
abstract class EmptyApp
{
//various fields
}
class ReusableBits
{
static function doSetup(EmptyApp theApp)
static function doCleanup(EmptyApp theApp)
}
class theApp extends EmptyApp
{
function main()
{
ReusableBits.doSetup(this);
//do stuff using some fields from EmptyApp
ReusableBits.doCleanup(this);
}
}
One obvious tradeoff is that with option 2, the 'framework' can't wrap the app in a try-catch block...
I've always favored re-use through composition (your second option) rather than inheritance (your first option).
Inheritance should only be used when there is a relationship between the classes rather than for code reuse.
So for your example I would have multiple ReusableBits classes each doing 1 thing that each application a make use of as/when required.
This allows each application to re-use the parts of your framework that are relevant for that specific application without being forced to take everything, Allowing the individual applications more freedom. Re-use through inheritance can sometimes become very restrictive if you have some applications in the future that don't exactly fit into the structure you have in mind today.
You will also find unit testing and test driven development much easier if you break your framework up into separate utilities.
Why not make the framework call onto your customisable code ? So your client creates some object, and injects it into the framework. The framework initialises, calls setup() etc., and then calls your client's code. Upon completion (or even after a thrown exception), the framework then calls cleanup() and exits.
So your client would simply implement an interface such as (in Java)
public interface ClientCode {
void runClientStuff(); // for the sake of argument
}
and the framework code is configured with an implementation of this, and calls runClientStuff() whenever required.
So you don't derive from the application framework, but simply provide a class conforming to a particular contract. You can configure the application setup at runtime (e.g. what class the client will provide to the app) since you're not deriving from the app and so your dependency isn't static.
The above interface can be extended to have multiple methods, and the application can call the required methods at different stages in the lifecycle (e.g. to provide client-specific setup/cleanup) but that's an example of feature creep :-)
Remember, inheritance is only a good choice if all the object that are inheriting reuse the code duo to their similarities. or if you want callers to be able to interact with them in the same fission.
if what i just mentioned applies to you then based on my experience its always better to have the common logic in your base/abstract class.
this is how i would re-write your sample app in C#.
abstract class BaseClass
{
string field1 = "Hello World";
string field2 = "Goodbye World";
public void Start()
{
Console.WriteLine("Starting.");
Setup();
CustomWork();
Cleanup();
}
public virtual void Setup()
{Console.WriteLine("Doing Base Setup.");}
public virtual void Cleanup()
{Console.WriteLine("Doing Base Cleanup.");}
public abstract void CustomWork();
}
class MyClass : BaseClass
{
public override void CustomWork()
{Console.WriteLine("Doing Custome work.");}
public override void Cleanup()
{
Console.WriteLine("Doing Custom Cleanup");
//You can skip the next line if you want to replace the
//cleanup code rather than extending it
base.Cleanup();
}
}
void Main()
{
MyClass worker = new MyClass();
worker.Start();
}