Custom sonar rule for annotation parameters check - annotations

I have a task to create custom rule using SonarJava. Rule purpose is checking methods. If method is annottated with #Test it also needs to have #TestInfo annotation with not empty testCaseId parameter.
This is what I have prepared:
public class AvoidEmptyTestCaseIdParameterRule extends IssuableSubscriptionVisitor {
private static final String TEST_ANNOTATION_PATH = "org.testng.annotations.Test";
private static final String TEST_INFO_ANNOTATION_PATH = "toolkit.utils.TestInfo";
#Override
public List<Tree.Kind> nodesToVisit() {
return ImmutableList.of(Tree.Kind.METHOD);
}
#Override
public void visitNode(Tree tree) {
MethodTree methodTree = (MethodTree) tree;
if (methodTree.symbol().metadata().isAnnotatedWith(TEST_ANNOTATION_PATH)) {
if (methodTree.symbol().metadata().isAnnotatedWith(TEST_INFO_ANNOTATION_PATH)) {
List<AnnotationInstance> annotations = methodTree.symbol().metadata().annotations();
for (int i = 0; i < annotations.size(); i++) {
if (annotations.get(i).symbol().name().equals("TestInfo")
&& !testInfoAnnotationContainsNonEmptyTestCaseIdParameter(annotations.get(i))) {
reportIssue(methodTree.simpleName(),
"Method annotated with #TestInfo should have not empty testCaseId parameter");
}
}
} else {
reportIssue(methodTree.simpleName(),
"Method annotated with #Test should also be annotated with #TestInfo");
}
}
}
private boolean testInfoAnnotationContainsNonEmptyTestCaseIdParameter(AnnotationInstance annotation) {
return <--this is where I stuck-->;
}
}
this is how my test class look:
public class TestClass {
#Test
#TestInfo(testCaseId = "", component = "Policy.IndividualBenefits")
public void testMethod() {
}
}
Question:
-Is it possible to get annotation parameters (properly or as String line)?
-Is there other possible way to get this parameter?

I figured it out. I switched to using Tree.Kind.ANNOTATION.
This is the code for search of needed argument:
Arguments arguments = annotationTree.arguments();
if (!arguments.isEmpty()) {
for (int i = 0; i < arguments.size(); i++) {
String parameter = arguments.get(i).firstToken().text();
String parameterValue = arguments.get(i).lastToken().text();
if (isParameterTestCaseId(parameter) && isTestCaseIdEmpty(parameterValue)) {
reportIssue(arguments.get(i),
"Method annotated with #TestInfo should have not empty testCaseId parameter");
}
}
}
Methods for checking argument and its value:
private boolean isParameterTestCaseId(String parameter) {
return parameter.matches("testCaseId");
}
private boolean isTestCaseIdEmpty(String parameterValue) {
return parameterValue.length() != 0;
}

Related

interface does not give me initalize method

I am missing method from interface
value of annotiations is null.
Already tried hardcoded, it works, but I need to be customizable.
package com.luv2code.springdemo.mvc.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class CourseCodeConstraintValidator implements ConstraintValidator {
private String coursePrefix;
public void initalize(CourseCode theCourseCode) {
coursePrefix = theCourseCode.value();
}
#Override
public boolean isValid(String theCode, ConstraintValidatorContext theConstraintValidatorContext) {
/*if (coursePrefix==null)
coursePrefix = "LUV";*/
System.out.println(theConstraintValidatorContext.getDefaultConstraintMessageTemplate());
boolean result;
if (theCode!=null) {
System.out.println(coursePrefix);
result = theCode.startsWith(coursePrefix);
} else {
result = true;
}
return result;
}
}
Expecting possible #Override method initialize
initalize => initialize
just one letter missing

How to call the method of unknown class in MQL?

I've a Collection class which aims to store different kind of objects, however I'd like to call specific method name which these classes share (e.g. ToString()).
Here is my attempt:
class Collection {
public:
void *data[];
void Collection() {}
void ~Collection() {
for (int i = 0; i < ArraySize(data); i++) {
if (CheckPointer(data[i]) == POINTER_DYNAMIC) delete data[i];
}
}
void *Add(void *_object) {
uint _size = ArraySize(data);
ArrayResize(data, _size + 1, 100);
data[_size] = _object;
return _object;
}
string ToString(string _dlm = ",") {
string _out = "";
for (int i = 0; i < ArraySize(data); i++) {
if (CheckPointer(data[i]) == POINTER_DYNAMIC) {
_out += ((void *) data[i]).ToString(); // #fixme: Syntax error.
}
}
return _out;
}
};
However using ((void *) data[i]).ToString() syntax fails with:
'ToString' - member function not defined Collection.mqh
How can I call a ToString() method for each stored object?
It seems to me that it should be something like collection.toString() where collection is an object of your class Collection. Then each object that you add to your collection should implement this function... Maybe it is easier to mention some superclass that supports toString() (or interface with this method) and make sure that you add only correct objects? This also makes your code free of unexpected errors in runtime.
Also CArrayObj is at your disposal with most functions, if you need toString() or any other function then you can simply extend basic class. Maybe the only disadvantage of the default collection is that it stores CObject-inherited objects.
This can be achieved by creating an abstract class where all classes can share the same virtual method. For example:
class Object {
public:
virtual string ToString() = NULL;
};
class Foo : public Object {
public:
virtual string ToString() {
return "Foo";
};
};
class Bar : public Object {
public:
virtual string ToString() {
return "Bar";
};
};
Then in the Collection class the following method:
virtual string ToString(string _dlm = ",") {
string _out = "";
for (int i = 0; i < ArraySize(data); i++) {
if (CheckPointer(data[i]) == POINTER_DYNAMIC) {
_out += ((Object *) data[i]).ToString() + _dlm;
}
}
return _out;
}
Sample usage:
Collection *objects;
objects = new Collection;
Foo *foo = new Foo();
Bar *bar = new Bar();
objects.Add(foo);
objects.Add(bar);
Print(objects.ToString());
delete objects;

I'm stuck at slick graphics

I'm trying to make a game, using slick2d, and lwjgl. I don't get why this code doesn't work
firstStage.java
package net.CharlesDickenson;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class firstStage extends BasicGameState {
public bossVar bossChecker() {
if(isBeforeMiddleBoss) return bossVar.beforeBoss;
if(isMiddleBoss) return bossVar.Middle;
if(isBeforeBoss) return bossVar.beforeBoss;
if(isBoss) return bossVar.Boss;
return null;
}
#SuppressWarnings("static-access")
public firstStage(int state) {
this.state = state;
}
#Override
public void init(GameContainer _arg0, StateBasedGame _arg1)
throws SlickException {
scoreBoard = new Image("res/scoreBoard.png");
backs = new Image("res/1stageBack.gif");
isBeforeMiddleBoss = true;
isMiddleBoss = false;
isBeforeBoss = false;
isBoss = false;
_arg0.setShowFPS(false);
}
#Override
public void render(GameContainer arg0, StateBasedGame _arg1, Graphics _g)
throws SlickException {
this._g = _g;
new Mob().getGraphics(_g);//i passed graphics
new Char().getGraphics(_g);//i passed graphics
new Bullet().getGraphics(_g);//i passed graphics
_g.drawImage(scoreBoard, 550, 5);
_g.drawImage(backs, 10, 10);
_g.drawString(fps, 580, 570);
_g.drawString("High Score-> Not avaiable", 560, 60);
_g.drawString("Score-> " + currScore, 595, 80);
}
#Override
public void update(GameContainer _arg0, StateBasedGame _arg1, int arg2)
throws SlickException {
fps = "Frame Per Second-> " + _arg0.getFPS();
bossVar b = bossChecker();
switch(b) {
case beforeMiddle :
break;
case Boss :
break;
default:
break;
}
}
#SuppressWarnings("static-access")
#Override
public int getID() {
return this.state;
}
private static int state;
private static int currScore = 0;
private static final int originX = 270;
private static final int originY = 490;
public static int X = originX;
public static int Y = originY;
private static String fps;
private Image scoreBoard;
private Image backs;
private Graphics _g;
public boolean isBeforeMiddleBoss;
public boolean isMiddleBoss;
public boolean isBeforeBoss;
public boolean isBoss;
}
Char.java
package net.CharlesDickenson;
import org.lwjgl.input.Keyboard;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
public class Char extends Bullet implements Entity {
#Override
public void getGraphics(Graphics _g) {
this._g = _g;//so i got graphics, but
if(!isInit) return;
_g.drawImage(Char, getCharX(), getCharY());//this codes doesn't works.
}
#Override
public int getCharX() {
switch(VarTracker.stage) {
case 1:
return firstStage.X;
}
return 0;
}
#Override
public int getCharY() {
switch(VarTracker.stage) {
case 1:
return firstStage.Y;
}
return 0;
}
public void setCharX(int i) {
System.out.println("asdgagsd");
switch(VarTracker.stage) {
case 1:
firstStage.X += i;
}
}
public void setCharY(int i) {
System.out.println("asdgagsd");
switch(VarTracker.stage) {
case 1:
firstStage.Y += i;
}
}
#Override
public void update() {
if(!isInit) return;
_g.drawImage(Char, getCharX(), getCharY());//this code doesn't work, too.
up = Keyboard.isKeyDown(Keyboard.KEY_UP);
down = Keyboard.isKeyDown(Keyboard.KEY_DOWN);
left = Keyboard.isKeyDown(Keyboard.KEY_LEFT);
right = Keyboard.isKeyDown(Keyboard.KEY_RIGHT);
shift = Keyboard.isKeyDown(Keyboard.KEY_LSHIFT);
z = Keyboard.isKeyDown(Keyboard.KEY_Z);
if(up && !shift) {
setCharY(6);
}
if(down && !shift) {
setCharY(-6);
}
if(left && !shift) {
setCharX(-6);
}
if(right && !shift) {
setCharX(6);
}
if(up && shift) {
setCharY(2);
}
if(down && shift) {
setCharY(-2);
}
if(left && shift) {
setCharX(-2);
}
if(right && shift) {
setCharX(2);
}
if(z) {
new Bullet().isFiring = true;
}
if(!z) {
new Bullet().isFiring = false;
}
}
#Override
public void init() {
System.out.println("<Char> Initializing...");
isInit = false;
try {
Char = new Image("res/char.png");
} catch (SlickException e) {
e.printStackTrace();
}
isInit = true;
System.out.println("<Char> Done with init()");
}
private boolean up;
private boolean down;
private boolean left;
private boolean right;
private boolean shift;
private boolean z;
private boolean isInit;
private Image Char;
private Graphics _g;
}
I passed graphics to other class using getGraphics method, to put a image, but it doesn't work.
at render method, it worked, but I can't put a image in other class.
The reason that it doesn't work is that you are using Graphics incorrectly. When Slick2d draws something, it uses the render method. This method is passed an instance of Graphics, to which you can draw stuff. When the call ends the Graphics object is no longer useful for anything. There is thus no reason to pass it to anything that doesn't use it immediately.
What you want to do is create a render method in your Mob, Char and Bullet classes. Make instances of said classes outside of the render method, for instance in init and store them in some data structure, for instance a List. In the render method, you simple traverse the list and call render or draw on each element. A quick example:
// Give the Entity interface two methods if they don't exist already:
public interface Entity {
void render(Graphics g);
void update(int delta);
}
// In firststage.java
List<Entity> list;
// In the init() method
public void init(GameContainer container, StateBasedGame game)
throws SlickException {
...
list = new ArrayList<Entity>();
list.add(new Mob());
list.add(new Char());
list.add(new Bullet());
}
// In the render method
public void render(GameContainer container, StateBasedGame game, Graphics g)
throws SlickException {
...
for (Entity e : list) {
e.draw(g);
}
}
// In the update method
public void update(GameContainer container, StateBasedGame game, int delta)
throws SlickException {
...
for (Entity e : list) {
e.update(delta);
}
}
TL;DR version: The Graphics object exists only to be drawn to in a single render call.
Render is called many times a second, so object creation in that method is not recommended.
Object oriented programming is good at modeling objects. Games tend to model a lot of objects. Make use of it.

Plugin dev: How to search only for interfaces in DLTK/PDT plugin?

I develop extension of PDT plugin. I need dialog with interfaces only (not classes). Basic code looks like it:
OpenTypeSelectionDialog2 dialog = new OpenTypeSelectionDialog2(
DLTKUIPlugin.getActiveWorkbenchShell(),
multi,
PlatformUI.getWorkbench().getProgressService(),
null,
type,
PHPUILanguageToolkit.getInstance());
It's works fine but I get classes and interfaces together (type variables). Is any method to filter it? I can't find this kind of mechanism in PDT but classes and interfaces are recognize correctly (icons next to names).
I don't know if its the best solution but it works.
int falseFlags = 0;
int trueFlags = 0;
IDLTKSearchScope scope = SearchEngine.createSearchScope(getScriptFolder().getScriptProject());
trueFlags = PHPFlags.AccInterface;
OpenTypeSelectionDialog2 dialog = new OpenTypeSelectionDialog2(
DLTKUIPlugin.getActiveWorkbenchShell(),
multi,
PlatformUI.getWorkbench().getProgressService(),
scope,
IDLTKSearchConstants.TYPE,
new PHPTypeSelectionExtension(trueFlags, falseFlags),
PHPUILanguageToolkit.getInstance());
And PHPTypeSelectionExtension looks like this:
public class PHPTypeSelectionExtension extends TypeSelectionExtension {
/**
* #see PHPFlags
*/
private int trueFlags = 0;
private int falseFlags = 0;
public PHPTypeSelectionExtension() {
}
public PHPTypeSelectionExtension(int trueFlags, int falseFlags) {
super();
this.trueFlags = trueFlags;
this.falseFlags = falseFlags;
}
#Override
public ITypeInfoFilterExtension getFilterExtension() {
return new ITypeInfoFilterExtension() {
#Override
public boolean select(ITypeInfoRequestor typeInfoRequestor) {
if (falseFlags != 0 && (falseFlags & typeInfoRequestor.getModifiers()) != 0) {
// Try to filter by black list.
return false;
} else if (trueFlags == 0 || (trueFlags & typeInfoRequestor.getModifiers()) != 0) {
// Try to filter by white list, if trueFlags == 0 this is fine 'couse we pass black list.
return true;
} else {
// Rest is filter out.
return false;
}
}
};
}
#SuppressWarnings("restriction")
#Override
public ISelectionStatusValidator getSelectionValidator() {
return new TypedElementSelectionValidator(new Class[] {IType.class, INamespace.class}, false);
}
}

GWT CEll Browser Real Time Update

has someone been able to correctly to update a cell browser at runtime, i.e. when u remove a node or add a node, the change is reflected immediately in the CEll Browser, because I am using a List and when i am making a change it is not being updated on the spot
You can use ListDataProvider setList(...) method for dynamic updates. Here is an example how I update cell browser via RPC:
private void loadAllData(final ListDataProvider<Data> dataProvider) {
dBservice.getAllData(new AsyncCallback<List<Data>>() {
public void onSuccess(List<Data> result) {
dataProvider.setList(result);
}
public void onFailure(Throwable caught) {
caught.printStackTrace();
}
});
}
to refresh a cellBrowser you have to close all the child on the root node.
anyway something like this
for (int i = 0; i < cellBrowser.getRootTreeNode().getChildCount(); i++) {
cellBrowser.getRootTreeNode().setChildOpen(i, false);
}
the AsyncDataProvider calls refreshes data
private final class Model implements TreeViewModel{
private List<ZonaProxy> zonaList = null;
private List<CategoriaProxy> categoriaList = null;
public void setCategoriaList(List<CategoriaProxy> categoriaList) {
this.categoriaList = categoriaList;
}
public void setListZona(List<ZonaProxy> zonaList) {
this.zonaList = zonaList;
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public <T> NodeInfo<?> getNodeInfo(T value) {
CategoryDataProvider dataProvider1 = new CategoryDataProvider();
return new DefaultNodeInfo(dataProvider1, new CategoriaCell());
}
/**
* Check if the specified value represents a leaf node. Leaf nodes cannot be
* opened.
*/
public boolean isLeaf(Object value) {
if (value instanceof CategoriaProxy){
if (((CategoriaProxy) value).getLivello() == 3) {
return true;
}
}
return false;
}
}
private class CategoryDataProvider extends AsyncDataProvider<CategoriaProxy>
{
#Override
protected void onRangeChanged(HasData<CategoriaProxy> display)
{
requests.categoriaRequest().findAllCategorias(0, 8).with().fire(new Receiver<List<CategoriaProxy>>() {
#Override
public void onSuccess(List<CategoriaProxy> values) {
updateRowCount(values.size(), true);
updateRowData(0, values);
}
});
}
}
it Works.
Apparently it is not enough to change the data provider and refresh it.
You need also to force the affected cell to close and reopen it, as in this example
public void updateCellBrowser(String id) {
TreeNode node = getNode(cellBrowser.getRootTreeNode(),id);
if(node != null && ! node.isDestroyed()) {
TreeNode parent = node.getParent();
int index = node.getIndex();
parent.setChildOpen(index, false,true);
parent.setChildOpen(index, true, true);
}
}
In my particular example the cell ids are pathnames hence the following
implementation of getNode().
private TreeNode getNode(TreeNode node, String id) {
for(int i=0; i < node.getChildCount(); i++)
if(node.isChildOpen(i)) {
Object value = node.getChildValue(i);
if(value instanceof String) {
String nodeId = ((String) value);
if(id.equals(nodeId))
return node.setChildOpen(i, true);
if(id.startsWith(nodeId))
getNode(node.setChildOpen(i, true),id);
}
}
return null;
}