Create a library for new built-ins Jena - java

I have made some new built-ins for Jena. I would like to create a library where I can put all of them.
How can I do that ? And how can I create my rules in this case ? Need I to import some files in the rule file?

Please note that, as this question is extremely broad, my answer is merely a set of suggestions towards an overall design. First, we'll begin with how Jena does it.
Apache Jena stores its rule files as classpath resources within its distribution jars. jena-core has a package (directory) called etc in which it stores several rules files. The reasoners that Jena has implemented are effectively just the GenericRuleReasoner with a specific rule set. For example, FBRuleReasoner#loadRules() method is used to retrieve the ruleset that this reasoner will utilize. You should look at where it is called from in order to figure out how you would use such a paradigm.
In your system, I'd suggest constructing your own implementation of ReasonerFactory (let's call it MyReasonerFactory). In MyReasonerFactory, you could have a static initialization block that will register the Builtins for your domain-specific reasoner. When someone calls ReasonerFactory#create(Resource), you can load your rules from the classpath and then create a GenericRuleReasoner that utilizes those rules.
Some pseudo-code (that may not compile) follows:
public class MyReasonerFactory implements ReasonerFactory
private static final String RULE_LOC = "/some/directory/in/my/jar/filename.extensiondoesntmatter";
static {
// register your builtins
}
#Override
public RuleReasoner create(Resource r) {
final GenericRuleReasoner reasoner = new GenericRuleReasoner(this, r);
reasoner.setRules(FBRuleReasoner.loadRules(RULE_LOC));
return reasoner;
}
#Override
public String getUri() {
return "urn:ex:yourReasoner";
}
#Override
public Model getCapabilities() {
// Your capabilities are identical to GenericRuleReasoner's
return GenericRuleReasonerFactory.theInstance().getCapabilities();
}
}

Related

Android annotation processing - generate different code for different build flavor

I'm building a library that requires some annotation processing to generate code. I now run into an issue that the release build doesn't need to have as much code as the debug build does (since this is a library for modifying configuration variants - primarily used for testing purposes). The following code illustrates the situations. Let's say I want to create a class ConfigManager from some annotated classes and properties. In debug builds, I need this much:
public class ConfigManager {
public Class getConfigClass() {
return abc.class;
}
public void method1() {
doSomething1();
}
public void method2() {
doSomething2();
}
public void method3() {
doSomething3();
}
}
While in release builds, I only need this much:
public class ConfigManager {
public Class getConfigClass() {
return abc.class;
}
}
I have a feeling it may be possible by writing a Gradle plugin to check for build flavor at compile time and invoke a different processor/or somehow pass a parameter to a processor to generate different code. However this topic is pretty new to me so I'm not sure how to achieve this. A couple hours of googling also didnt help. So I'm wondering if anyone could give me a direction or example? Thanks
Pass an option (release=true/false) to your processor.
From javac https://docs.oracle.com/javase/8/docs/technotes/tools/windows/javac.html
-Akey[=value]
Specifies options to pass to annotation processors. These options are not interpreted by javac directly, but are made available for use by individual processors. The key value should be one or more identifiers separated by a dot (.).
In combination with Processor.html#getSupportedOptions https://docs.oracle.com/javase/8/docs/api/javax/annotation/processing/Processor.html#getSupportedOptions
Returns the options recognized by this processor. An implementation of the processing tool must provide a way to pass processor-specific options distinctly from options passed to the tool itself, see getOptions.
Implementation outline:
public Set<String> getSupportedOptions() {
Set<String> set = new HashSet<>();
set.add("release");
return set;
}
// -Arelease=true
boolean isRelease(ProcessingEnvironment env) {
return Boolean.parseBoolean(env.getOptions().get("release"));
}
See Pass options to JPAAnnotationProcessor from Gradle for how to pass options in a gradle build.

Aggregating JUnit Rules with dependencies between one another

In more complex unit tests, I often require a certain set of Rules to be present. Some of these Rules have dependencies to another. As the ordering is relevant, I use RuleChains for that. All good so far.
This however is duplicated in most tests (with the occasional additional rule being used). Not only does this duplication feel unnecessary and cumbersome to repeat, it also needs to be adjusted in many places, when an additional Rule should be integrated.
What I would like to have is a Rule of Rules, i.e. a (predefined) Rule that contains or aggregates other (application & test specific) Rules.
I'll give an example of how this currently looks like:
public LoggingRule logRule = new LogRule();
public ConfigurationRule configurationRule = new ConfigurationRule();
public DatabaseConnectionRule dbRule = new DatabaseConnectionRule();
public ApplicationSpecificRule appRule = new ApplicationSpecificRule();
#Rule
RuleChain chain = RuleChain.outerRule(logRule)
.around(configurationRule)
.around(dbRule)
.around(appRule);
Assume that the given Rules depend on each other, e.g. the ApplicationSpecificRule requires that the DatabaseConnectionRule is executed first in order to establish a connection, the ConfigurationRule has initialized an empty configuration, etc.
Also assume that for this (rather complex test) all rules are actually required.
The only solution I could come up with so far is to create factory methods that return a predefined RuleChain:
public class ApplicationSpecificRule extends ExternalResource
{
public static RuleChain basicSet()
{
return RuleChain.outerRule(new LogRule())
.around(new ConfigurationRule())
.around(new DatabaseConnectionRule())
.around(new ApplicationSpecificRule());
}
}
In a test this can then be used as follows:
#Rule
RuleChain chain = ApplicationSpecificRule.basicSet();
With that the duplication is removed and additional Rules can easily be integrated. One could even add test-specific Rules to that RuleChain. However one can't access the contained Rules when they are required for additional setup (assume you need the ApplicationSpecificRule in order to create some domain object, etc.).
Ideally this would be extended to also support using other predefined sets, e.g. an advandancedSet that builds on top of the basicSet of Rules.
Can this be somehow simplified? Is it a good idea in the first place or am I somehow misusing Rules? Would it help to restructure the tests?
Thoughts?
The TestRule interface has only one method, so it's quite easy can define your own custom rule that delegates to a RuleChain and keeps references to the other rules:
public class BasicRuleChain implements TestRule {
private final RuleChain delegate;
private final DatabaseConnectionRule databaseConnectionRule
= new DatabaseConnectionRule();
public BasicRuleChain() {
delegate = RuleChain.outerRule(new LogRule())
.around(new ConfigurationRule())
.around(databaseConnectionRule)
.around(new ApplicationSpecificRule());
}
#Override
public Statement apply(Statement base, Description description) {
return delegate.apply(base, description
}
public Connection getConnection() {
return databaseConnectionRule.getConnection();
}
}
Doesn't get much simpler then that, does it? The only thing that would make it even simpler is to just use an instance instead of a factory, since you don't need fresh instances all the time.

Java Registry Class?

I'm fairly new to Java. I'm coming from PHP and I used to create registry classes in php using the magic __get and __set methods. So that other parts of the system can easily do:
registry.foo = new Foo();
I should mention I'm trying to create game engine. Here is my registry in Java atm:
class Registry {
private static Map<String, Object> box = new HashMap<String, Object>();
public static Object get(String key) {
if (Registry.box.get(key) != null) {
return Registry.box.get(key);
}else {
return null;
}
}
public static void set(String key, Object o) {
Registry.box.put(key, o);
}
}
Then for the other parts of the system to access the registry, I currently need this whole thing:
((Object) Registry.get("Object")).doSomething();
Which is really a lot of code. In php this would be accomplished by simply:
Registry.foo.doSomething();
Any way to make this a bit more simpler? I guess I could make public fields, but then the regsitry class would need to implicitly create these fields as the possibility of new objects may need to be added which are unknown to the registry class itself, which is.. annoying :P
Thanks in advance!
This is a two pronged problem:
Java is a statically type language, and does not offer in-language flexibility for defining objects at runtime (you can use a library to synthesize classes at runtime, but, see #2)
A global registry for objects defeats a lot of safeties in a type-safe language. If your entire application centers around getting and putting objects into a global Map, there likely safer and less-coupled designs.
How can this be solved?
Redesign your application structure to not need a global map.
Use a dynamic language subset for Java (such as Groovy).
Use Scala 2.10 (JVM compatible) which features a Dynamic type which does exactly what you want.
First of all this method is too verbose:
public static Object get(String key) {
if (Registry.box.get(key) != null) {
return Registry.box.get(key);
}else {
return null;
}
}
It could be just:
public static Object get(String key) {
return Registry.box.get(key);
}
But second, this is definitely a bad design. Global repository - doesn't sound reasonable. A storage of objects of all types by string key - it's terrible.
Any way to make this a bit more simpler?
Not in any practical way. Java is a statically typed language, and the structure of objects has to be known up front. The very idea of an equivalent of PHP's __get and __set is antithetical to the language.
For what it's worth, your "registry" looks like bad design anyway. (Admittedly making some pretty wild assumptions from the little code you've shown.) You shouldn't need a global repository of what appear to be unrelated objects. You should consider some sort of dependency injection instead.
Based on your comment, instead of structuring your code like this:
class World implements GameSystem {
public void update() {
Registry.get("game").doSomething();
}
}
you should do:
class World implements GameSystem {
Game game;
public World(Game game) { // and other dependencies
this.game = game;
}
public void update() {
this.game.doSomething();
}
}
The idea is that components of your program don't really have any business knowing how to find the other components. It also makes dependencies between the components explicit, and helps you avoid circular dependencies.

Finding unused values in message resource file

I am working on a project that has been through multiple hands with a sometimes rushed development. Over time the message.properties file has become out of sync with the jsps that use it. Now I don't know which properties are used and which aren't. Is there a tool (eclipse plugin perhaps) that can root out dead messages?
The problem is that messages may be accessed by JSP or Java, and resource names may be constructed rather than literal strings.
Simple grepping may be able to identify "obvious" resource access. The other solution, a resource lookup mechanism that tracks what's used, is only semi-reliable as well since code paths may determine which resources are used, and unless every path is traveled, you may miss some.
A combination of the two will catch most everything (over time).
Alternatively you can hide the functionality of ResourceBundle behind another façade ResourceBundle, which should generally pipe all calls to original one, but add logging and/or statistics collection on the top.
The example can be as following:
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.NoSuchElementException;
import java.util.ResourceBundle;
public class WrapResourceBundle {
static class LoggingResourceBundle extends ResourceBundle {
private Collection<String> usedKeys = new HashSet<String>();
public LoggingResourceBundle(ResourceBundle parentResourceBundle) {
setParent(parentResourceBundle);
}
#Override
protected Object handleGetObject(String key) {
Object value = parent.getObject(key);
if (value != null) {
usedKeys.add(key);
return value;
}
return null;
}
#Override
public Enumeration<String> getKeys() {
return EMPTY_ENUMERATOR;
}
public Collection<String> getUsedKeys() {
return usedKeys;
}
private static EmptyEnumerator EMPTY_ENUMERATOR = new EmptyEnumerator();
private static class EmptyEnumerator implements Enumeration<String> {
EmptyEnumerator() {
}
public boolean hasMoreElements() {
return false;
}
public String nextElement() {
throw new NoSuchElementException("Empty Enumerator");
}
}
}
public static void main(String[] args) {
LoggingResourceBundle bundle = new LoggingResourceBundle(ResourceBundle.getBundle("test"));
bundle.getString("key1");
System.out.println("Used keys: " + bundle.getUsedKeys());
}
}
Considering that some of your keys are run-time generated, I don't think you'll ever be able to find a tool to validate which keys are in use and which ones are not.
Given the problem you posed, I would probably write an AOP aspect which wraps the MessageSource.getMessage() implementation and log all the requested codes that are being retrieved from the resource bundle. Given that MessageSource is an interface, you would need to know the implementation that you are using, but I suspect that you must know that already.
Given that you would be writing the aspect yourself, you can create a format that is easily correlated against your resource bundle and once you are confident that it contains all the keys required, it becomes a trivial task to compare the two files and eliminate any superfluous lines.
If you really want to be thorough about this, if you already have Spring configured for annotation scan, you could even package up your aspect as its own jar (or .class) and drop it in a production WEB-INF/lib (WEB-INF/classes) folder, restart the webapp and let it run for a while. The great thing about annotations is that it can all be self contained. Once you are sure that you have accumulated enough data you just delete the jar (.class) and you're good to go.
I know that at least two of the major java IDEs can offer this functionality.
IntelliJ IDEA has a (disabled, by default) Inspection that you can
use to do this:
go to Settings -> Inspections -> Properties files -> ... and enable
the 'Unused property'
..Only problem I had was that it didn't pick up some usages of the property from a custom tag library I had written, which I was using in a few JSPs.
Eclipse also has something like this ( http://help.eclipse.org/helios/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftasks-202.htm ) but I haven't really exhausted the how well it works.

state design pattern from Java to Ruby

I have a working solution in java using a classic state design pattern and facing some difficulties translating it to ruby. I am new in ruby, but the diffuclty I believe lies in the differences on how patterns can be implemented in dynamic languages.
My interface is describing the actions the model can execute in every state:
public interface State {
public void doTask1(Model a_model);
public void doTask2(Model a_model);
public boolean doTask3(Model a_model, Helper a_helper);
}
Next, I implement the state interface and create concrete states of my logic:
public class LogicState1 implements State {
public void doTask1(Model a_model) {
a_model.implementTask1();
}
public void doTask2(Model a_model) {
a_model.implementTask2();
}
public boolean doTask3(Model a_model, Helper a_helper) {
a_model.useHelper();
return a_model.setState(a_model.getALogicstate(a_key));
}
As you can see, each concrete state can reach into the model and change its State. To avoid encapsulation issues, I instantiate my concrete states within the Model class, which has also a reference to the current State:
public class Model {
private State currentState;
public void setState(State state){
this.currentState = state;
}
public State getState(){
return currentState;
}
private final Map<String, State> everyState = new HashMap<String, State>();
public Model(String initialStateKey){
everyState.put("key1", new LogicState1());
everyState.put("key2", new LogicState2());
//...etc, instantiate and store all business logic states
this.currentState = everyState.get(initialStateKey);
}
public State getALogicState(String key){
return everyState.get(key);
}
public void useHelper(){...}
A client would use the Model like this:
public void run(Model a_model) {
a_model.getState().doTask1(a_model);
}
I think all of the above Java is straightforward, but now I am attempting to port this design into Ruby. I am aware of the differences in type-checking, and how modules and mixins are supposed to work in Ruby in contrast to Java's interfaces.
I have also found out about the State design pattern in Ruby in the pickaxe book.
Now I am a bit confused about which is the best way to try such conversion. I am still thinking inside the Java box, and wondering if I should have my concrete implementation of each state in a different .rb file and then require it in the client class?
Is there a way to implement the above without using the delegate.rb library?
Any suggestions on how to start with my conversion will be enthusiastically appreciated.
To translate this to ruby you can just leave out the interface and keep everything else as is. I.e. each state is a class that defines the methods do_task_N and doesn't otherwise have a connection to the other state classes (meaning you don't have to "emulate" the common interface by mixing-in a module or anything, you simply don't need it at all).
I am still thinking inside the Java
box, and wondering if I should have my
concrete implementation of each state
in a different .rb file and then
require it in the client class?
That sounds fine, yes.
I you trying to port a specific program from Java to Ruby or are you trying to learn to write Ruby?
If #1, why?
If #2, I would recommend that you work with existing Ruby code in order to learn the Ruby style. I highly recommend Ruby on Rails for this, since it is a very well written framework.
I learned a lot of lessons from Rails, which I can use even when I write other kinds of programs and in other languages.

Categories

Resources