Change at runtime to a marker interface - java

Today I saw the next code:
public Tab addTab(Component c, String caption, Resource icon, int position) {
Tab addedTab = super.addTab(c, i18nCaption, icon, position);
// if is not securized
if (!(addedTab instanceof SecurizedComponent)) {
addedTab = SecurityWrapper.createSecurityWrapper((TabSheetTabImpl)addedTab, caption);
}
return addedTab;
}
SecurizedComponent is a marker interface
/**
*
* This is a marker interface. All securized components will be changed at runtime to implement this interface.
* This way, is possible to know if a component has been securized asking for component instanceof SecurizedComponent
*
* Allows the framework not to securize components more than once
*
*/
public interface SecurizedComponent {
}
The method createSecurityWrapper do something like:
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(wrapperClass);
enhancer.setClassLoader(source.getClass().getClassLoader());
enhancer.setInterfaces(new Class[]{SecurizedComponent.class});
//more stuff...
I know what this code is doing, basically when a tab is added for the first time, it is changed at runtime to implement SecurizedComponent interface.
But my question is: Is this a good practice? Is there a better way to implement it?

This doesn't shock me, really. I would put the check if (!(addedTab instanceof SecurizedComponent)) { inside SecurityWrapper, so you won't have that check everywhere in your code, and calling SecurityWrapper with a securized object would do nothing.
Otherwise, I would use a Securizable interface with a isSecured() method, all implementations would return false until SecurityWrapper works his magic.
Of course that "Security" is only as secure as your code, since I support you could change your class to implement Securized and bypass the checks...

Related

Java - Choosing the design pattern - 2 interfaces with same methods, except one has an extra parameter

So I have 2 interfaces (show below), 1 for regular/free kits and another one for purchasable kits. They both contain 2 methods, but in the "getIcon" method for purchasable kits, I need the player's profile as a parameter so I can check if they have bought the kit.
What is the best design pattern to use to link these 2 interfaces? and can you possibly show me the code to do it?
The 2 interfaces:
public interface Kits {
void giveKit(Player player);
Item getIcon();
}
public interface PurchasableKits {
void giveKit(Player player);
Item getIcon(Profile profile);
}
I attempted to use the adapter pattern but it doesn't seem right because the "getIcon" method is taking in a profile as a parameter but it doesn't get used.
public class KitAdapter implements PurchasableKits {
private Kits kits;
public KitAdapter(Kits kits) {
this.kits = kits;
}
#Override
public void givetKit(Player player){
kits.giveKit(player);
}
#Override
public void getIcon(Profile profile){
kits.getIcon();
}
}
Thanks in advance
You have 1 interface PurchasableKits. A free Kit would implement the interface and call getIcon(null).
The red flag is that the 2 interfaces are almost exactly the same. No design pattern will get you out of the situation that creates.
That's a tricky question because of the rules of the inheritance and cyclic inheritance avoided in java.
I don't believe that you need to interfaces, you could do something like this:
public interface Kits {
void giveKit(Player player);
//a vargars usage
Item getIcon(Profile... p);
}
public class ConcreteClass implements Kits{
#Override
public void giveKit(Player player) {
// TODO Auto-generated method stub
}
#Override
public Item getIcon(Profile... o) {
//This is the ugly thing of this method. You must check the sent params.
//However I think it is better than send a null param, as the clean code suggest to avoid
if(o.length == 0)
System.out.println("without profile");
else
System.out.println("With profile");
return null;
}
}
public class Main {
public static void main(String[] args) {
ConcreteClass my = new ConcreteClass();
my.getIcon();
my.getIcon(new Profile());
}
}
The output:
without profile
With profile
So I have 2 interfaces (show below), 1 for regular/free kits and another one for purchasable kits. They both contain 2 methods, but in the "getIcon" method for purchasable kits, I need the player's profile as a parameter so I can check if they have bought the kit.
Whether or not the profile is needed in the getIcon(...) method is an implementation detail of those Kits that are purchasable. I would just have a Kit interface that has the following definition:
public interface Kit {
void giveKit(Player player);
Item getIcon(Profile profile);
}
So every time you wanted to get the icon you would pass in the Profile and it would be up to the kits that are purchasable to look at the profile. The free ones would just ignore the argument. That you sometimes pass in null and sometimes not means that you know beforehand whether or not it is free which means that something is wrong with your model.
Couple of other comments about your code. Just my opinions:
Concrete classes tend to be nouns. Interfaces tend to be verbs. Maybe KitHandler instead of Kit?
Class names tend to be singular so then you can put them in a list. Maybe Kit (or KitHandler) would be better so you can create a List<Kit> kits = ....
I used get methods to return fields which means that they typically don't take arguments. Maybe getIcon should be generateIcon(...)?

GWT Custom Cell in CellList - render() not being called

I'm having trouble figuring out why my render method isn't being called. Here is my custom cell that extends AbstractCell, broken down to its simplest form.
public class FormHistoryCell<T> extends AbstractCell<T> {
#Override
public void render(com.google.gwt.cell.client.Cell.Context context, T value, SafeHtmlBuilder sb) {
System.out.println("Rendering customer cell...");
if (value == null) {
return;
}
}
}
Here is the snipet in my code which creates an instance of "FormHistoryCell" and attempts to add it to a CellList.
#UiFactory
CellList<FormHistoryCell> initList() {
FormHistoryCell formHistoryCell = new FormHistoryCell();
CellList historyList = new CellList<FormHistoryCell>(formHistoryCell);
return historyList;
}
I have tried different things like adding a constructor that takes a String argument, etc. The constructor is called, but the render method is not. Looking at that Abstract class it extends, it seems the render method is called within the "setValue" method, but didn't see where that is called in other custom cell extensions whose render methods seem to be getting called just fine. I'm sure I'm missing something obvious here but can't figure out what. Please help.
Based on the code you provided, there is no reason for a browser to call the render method of your cell. You simply passed a reference to an object FormHistoryCell to your CellList. The render method is only needed when a browser has to display a cell and its content. This happens when you add data to your CellList, as #outellou suggested.

Template Variables in Eclipse - var()

I'm developing an Eclipse plugin for a C dialect. Currently I'm working on Content Assist and I want to introduce templates for most common language constructs.
In my work I was following this tutorial:
I would like to take advantages of templates (specified e.g. here) such as: ${id:var(type[,type]*)}, for example to provide template for function call with completion proposals for each function parameter but filtered out to show only proposals of compatible type. Unfortunately I'm not able to find any relevant tutorials or examples.
I would be grateful for any suggestion, links, code snippets, etc.
Thanks in advance!
Grzegorz
By trial and error I've finally managed to provide such completion proposals. I will explain it briefly but I do not guarantee that this is the right way, but it works :)
If we have a function foo(boolean bar, boolean baz) we can create corresponding template: foo(${bar:var(boolean)}, ${baz:var(boolean)}). To handle such template we can register custom TemplateVariableResolver:
public final class VariableResolver extends TemplateVariableResolver {
public VariableResolver() {
super("var", "some description");
}
#Override
public void resolve(TemplateVariable variable, TemplateContext context) {
final String name = variable.getName(); /* bar or baz */
final List params = variable.getVariableType().getParams(); /* ["boolean"] */
variable.setValues(computeSuggestions(name, params));
variable.setResolved(true);
}
private String[] computeSuggestions(String name, List params) {
return new String[] {"true", "false"};
// TODO: more sophisticated proposals
}
// overwrite other methods!
}
The next step is to make your CompletionProcessor extend TempateCompletionProcessor.
Here is a (simplified) default implementation of computeCompletionProposals() in TemplateCompletionProcessor
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
/* some code */
TemplateContext context= createContext(viewer, region);
if (context == null)
return new ICompletionProposal[0];
context.setVariable("selection", selection.getText()); // name of the selection variables {line, word}_selection //$NON-NLS-1$
Template[] templates= getTemplates(context.getContextType().getId());
/* some code */
return (ICompletionProposal[]) matches.toArray(new ICompletionProposal[matches.size()]);
}
Then VariableResolver should be registered in computeCompletionProposalsor somewhere else:
context.getContextType().addResolver(new VariableResolver());
Therefore if getTemplates() will return our exemplary template and user will use it, for parameters bar and baz resolve() will be called, so that we can provide proposals for each foo function parameters with regard to these parameter types.

I'm new to java from a javascript background: how do they manage event listeners properly and not tighting classes together?

I've been trying to do some "simple thing" in java that in javascript would look like:
// Main class
var model = new Model();
this.callback = function(e){/* do something */}
model.addListener("change", callback);
Well in java what I found so far is making the Main class deriving from java.util.Observer and Model from java.util.Observable; Then when the model will dispatch the event it will call the update method on the Main class. I found really ugly and not elegant at all. I can't even think of how I could work with this;
Is there any cleaner and flexible ways, maybe some libs to help me out here, because I have not found any acceptable tutorial about how to do it like this?
thanks a lot
Well what I've managed so far, and I quite I like it a lot more than creating "empty" classes just for simple events (but still not good, at least for me):
private ArrayList __items;
public void addListener(Method method, Object object){
this.__listeners.add(new Object[] {method, object});
}
public void dispatch(){
int i = this.__listeners.size();
Method method;
Object context;
while(i>0){
i--;
method = (Method)(this.__listeners.get(i))[0];
context = (Object)(this.__listeners.get(i))[1];
try{
method.invoke(context);
}catch(java.lang.reflect.InvocationTargetException e){
}catch(java.lang.IllegalAccessException e){
}
}
}
Then I use like this:
Gifts gifts = prendastotty.PrendasTotty.getMain().getLoggedUserGifts();
Class[] parameterTypes = new Class[0];
try{
Method m = Home.class.getMethod("__updateTable", parameterTypes);
gifts.addListener(m, this);
}catch(NoSuchMethodException e){
}
It this leaky/anti-pattern/buggy?
I must say that I had a bit of trouble keeping up with your code because in my head some of the stuff didn't make sense (from a Java way of thinking, or at least my Java way of thinking). So I hope I understood you correctly and can help you out.
Let's first take your simple example:
var model = new Model();
this.callback = function(e){/* do something */}
model.addListener("change", callback);
In Java a good approach,for example, would be:
public interface ModelListener {
public void execute(Model context);
}
public class Model {
private List<ModelListener> listeners;
public Model() {
this.listeners = new ArrayList<ModelListener>();
}
public void addListener(ModelListener listener) {
this.listeners.add(listener);
}
public void dispatch() {
for (ModelListener listener: listeners) {
listener.execute(this);
}
}
}
With this sort of design you can now do one of two things:
Use anonymous classes
In Java the most common case is that all your classes have a name, although there are cases when you can create anonymous classes, these are basically classes that
are implemented inline. Since they are implemented inline, they're usually only
used when they're small and it's known they won't be re-usable.
Example:
Model model = new Model();
model.add(new ModelListener() {
public void execute(Model model) { /* do something here */ }
});
Notice how the new ModelListener object is created (which is an interface) and the execute implementation is provided inline. That is the anonymous class.
Interface Implementations
You can create classes that implement your interface and use them instead of anonymous classes. This approach is often use when you want your listeners to be re-usable, have names that give semantic meaning to the code and/or they're logic isn't just a few lines of code.
Example:
public class LogListener implements ModelListener {
public void execute(Model model) {
// Do my logging here
}
}
Model model = new Model();
model.addListener(new LogListener());
Side note
As a side note, I saw that the method you were trying to bind as a listener was called __updateTable are you by any chance trying to detect object's changes so you can commit them to the database? If so I strongly suggest you to look at some ORM frameworks such as Hibernate or JPA they'll keep all that hassle from you, keeping track of changes and committing them to the database.
Hope it helps, regards from a fellow portuguese StackOverflow user ;)
You will find it a bit difficult to try to directly map javascript ideology into java. Their underlying philosophies are different. Without more definite code and expectations it is difficult to give you a clearer answer. Here is a sample of code in GWT(written in java) that attaches a click handler to a button.
Hope this helps you get started.
myButton.addSelectionListener(new SelectionListener<ComponentEvent>(){
#Override
public void componentSelected(ComponentEvent ce) {
// do your processing here
}
});
In Java, a function can't exist outside of a class as it can in Javascript. So when you need to provide a function implementation at runtime, you have to wrap that function inside a class and pass an instance of the class, unfortunately.
The solution you have using reflection will work (I assume), but it is not the preferred way to do it in Java since what used to be compile-time errors will now be runtime errors.

Is this typically how Java interfaces are used to set up event handlers, and are there hidden drawbacks to this approach?

Hey all, I'm still relatively new to Java, and looking for a sanity check.
I've been studying this Java port of Cocos2D and noticed that the CCLayer class has built-in hooks to the Android native touch events. That's great, but what I'd really like is for objects like CCSprite to directly respond to touch events without having to listen for those events in the layer and iterate through all the children to find which ones happen to intersect the event's x/y coordinates. So I figured that this would be the perfect chance to test my understanding of how to set up some event handlers and make a subclass of CCSprite that actually listens for touches without needing to go through CCLayer to know about it. Furthermore, I wanted to be able to assign different behaviors to different CCSprite instances on an ad-hoc basis without explicitly subclassing further, much like Android Buttons don't need to be subclassed just to give them a handler for their touch events.
This is what I came up with on a first pass:
// My touch interface for all touchable CCNode objects.
package com.scriptocalypse.cocos2d;
public interface ITouchable {
boolean onCCTouchesBegan();
boolean onCCTouchesEnded();
boolean onCCTouchesMoved();
}
And now the class that uses the ITouchable interface for its callbacks...
public class CCTouchSprite extends CCSprite implements CCTouchDelegateProtocol {
protected ITouchable mTouchable;
public void setTouchable(ITouchable pTouchable){
mTouchable = pTouchable;
boolean enable = mTouchable != null;
this.setIsTouchEnabled(enable);
}
public void setIsTouchable(boolean pEnabled){
// code to enable and disable touches snipped...
}
/////
// And now implementing the CCTouchDelegateProtocol...
/////
public boolean ccTouchesBegan(MotionEvent event) {
Log.d("hi there", "touch me");
if(mTouchable != null){
mTouchable.onCCTouchesBegan();
}
return CCTouchDispatcher.kEventHandled; // TODO Auto-generated method stub
}
public boolean ccTouchesMoved(MotionEvent event) {
if(mTouchable != null){
mTouchable.onCCTouchesMoved();
}
return CCTouchDispatcher.kEventIgnored; // TODO Auto-generated method stub
}
public boolean ccTouchesEnded(MotionEvent event) {
Log.d("hi there", "not touch me");
if(mTouchable != null){
mTouchable.onCCTouchesEnded();
}
return CCTouchDispatcher.kEventIgnored; // TODO Auto-generated method stub
}
}
And finally, instantiate the class and implement the interface...
final CCTouchSprite sprite = new CCTouchSprite(tex);
sprite.setIsTouchEnabled(true);
sprite.setPosition(CGPoint.ccp(160,240));
sprite.setTouchable(new ITouchable(){
#Override
public boolean onCCTouchesBegan() {
Log.d("SWEET SUCCESS", "I got a touch through my interface!");
return true;
}
#Override
public boolean onCCTouchesEnded() {
Log.d("SWEET SUCCESS", "You stopped touching my interface!");
sprite.runAction(CCRotateBy.action(1, 360));
return false;
}
#Override
public boolean onCCTouchesMoved(){
Log.d("SWEET SUCCESS", "You moved the touch");
return false;
}
});
So all of this works. The subclass does successfully register with the Cocos2D touch dispatcher, which successfully calls those ccTouches functions and pass them MotionEvents, which in turn call my Interface functions if the interface has been instantiated.
Is this the "proper" way to do it (Define "it" as you see fit, ranging from using Interfaces to create event handlers to working with Cocos2D, to writing Java at all)? Are there drawbacks to this that I'm not aware of? Is this somehow worse for performance than iterating through all the CCNode objects that are children of CCLayer? If so, how can that possibly be?
I think you have got the basics for setting up a listener right. There are some things I would change though.
First, the setter setIsTouchable. It's weird. You need a listener object to pass touch events to right? So what is this setter going to do when you pass it true (as your example does)? You snipped the code, but setting a boolean field to true does not seem right here as it would put the sprite object in an inconsistent internal state. I would just drop that setter. The getter can just evaluate whether mTouchable is assigned or null.
Second, why limit yourself to one listener? Change mTouchable to mTouchables, being a list of ITouchables. Then change setTouchable to addTouchable and possibly add removeTouchable and clearTouchables methods. This way you can add multiple listeners for different behaviors having to respond to the same events. This is how most other event systems work as well. You then just change isTouchable to check whether the list is empty or not.
scriptoclypse... I really am not completely understanding your question, but you have not had any response and yes interfaces and events are very similar. At this level I can only respond in C#.

Categories