Eclipse pre-commit hook to execute arbitrary logic - eclipse

Does eclipse support pre-commit checks for executing logic in a script or java class? Specifically, I need logic to search the source file for println, TODO, etc., statements before committing to SVN.
If you program, you know what I'm talking about... :-)
public void submitOrder(Order order){
if(order.valid()){
println("hi!")
orderProcessor.validatePayment(order)
println("hi2")
...
}else{
println("logging to journal...") //TODO remove this later
journal.log(INVALID_ORDER, order)
println("after journal")
println("really throwing exception now!")
throw new InvalidOrderException(order)
}
}

Related

How to compile documents and run Jshop2 in Eclipse?

I am a student who begin to study SHOP2 from China.
My teacher told me to run JSHOP2 in Eclipse.Now I can run original zenotravel problem and generate GUI and plans.Likewise, I want to put other domain and problems to SHOP2 and produce plans.
But the problem is that I don't know how to compile them and My teacher only asked me to run the the main function in Internaldomain but it can't succeed.Follow is the original code:
public static void main(String[] args) throws Exception
{
//compile();
// compile(args);
//-- run the planning algorithm
run(args);
}
This code can run zenotravel.Then I put domain and problems named pfile1 and
tdepots respectively into SHOP2 folder.Change the codes to:
{
compile(domaintdepots);
// compile(args);
//-- run the planning algorithm
run(args);
}
It warns "domainpdfiles cannot be resolved to a variable".
Or
//--compile();
compile(args);
//-- run the planning algorithm
//run(args);
It turns out:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at JSHOP2.InternalDomain.compile(InternalDomain.java:748)
at JSHOP2.InternalDomain.main(InternalDomain.java:720)"
720 is main funcition above.And 748 is compile function:
public static void compile(String[] args) throws Exception
{
//-- The number of solution plans to be returned.
int planNo = -1;
//-- Handle the number of solution plans the user wants to be returned.
if (args.length == 2 || args[0].substring(0, 2).equals("-r")) {
if (args[0].equals("-r"))
planNo = 1;
else if (args[0].equals("-ra"))
planNo = Integer.MAX_VALUE;
else try {
planNo = Integer.parseInt(args[0].substring(2));
} catch (NumberFormatException e) {
}
}
Finally,according to the advice of the friend,I put the two pddls into src folder and use “java Jshop2.InternalDomain domaintdepots”in CMD commad but an error appeared:"the main class Interdomain can't be found or loaded".But I have set the class path accurately and the Zenotravel planning can run.So how
and where can I use the command ?
And what is written in the bracket"compile()" in Eclipse?
I am also not familiar with JAVA so it's better if there is concrete instruction.Thanks a lot.
Please describe what are you trying to build, what is it supposed to do, what is the expected end result.
If you do have a valid PDDL domain and problem file, you could try to load them into the online http://editor.planning.domains/ editor using the File > Load menu. Then press the Solve button and confirm which of the file is the domain and which is problem. If the PDDL model is valid (and the underlying solver can handle the requirements), you will get a plan back.
If you are trying to build a software solution that needs a PDDL-based planning engine as one of its component, perhaps you could use one of the available implementations: https://nergmada.github.io/pddl-reference/guide/whatisplanner.html#list-of-planners
If you are trying to build your own planning engine in Java using the Eclipse IDE, you probably need a Java-based PDDL parser. Here is a tutorial, how to use pddl4j for that purpose:
https://github.com/pellierd/pddl4j/wiki/A-tutorial-to-develop-your-own-planner
If you need to use Jshop2 in particular, it looks from their documentation (http://www.cs.umd.edu/projects/shop/description.html) that you need to indeed compile the domain and problem PDDL into Java code using following commands:
java JSHOP2.InternalDomain domainFileName
java JSHOP2.InternalDomain -r problemFileName
Edited on June 19th
Java package names (e.g. JSHOP2) and class names (InternalDomain) are case sensitive, so make sure you type them as per the documentation. That is probably why you are getting the "main class not found error".
It is difficult to say what the lines numbers 748 and 720 exactly correspond to, because in the GitHub repo https://github.com/mas-group/jshop2/blob/master/src/JSHOP2/InternalDomain.java the code is different from yours. Can you indicate in your questions which lines those are exactly?
The make file shows how to execute an out-of-the-box example in the distribution:
cd examples\blocks
java JSHOP2.InternalDomain blocks
java JSHOP2.InternalDomain -r problem300
Does that work for you?

Can I add a button in eclipse which performs custom a list of Actions in order?

This may not be possible but I'm looking for a way to add a button (or option in right click menu of project) that allows me to perform what would normally be multiple separate actions , specifically I would like an option that would:
perform a Maven clean on the current project
clean the project in eclipse
clean the server and rebuild (normally or Debug)
I have tried to Google this but I couldn't find anything that might help (I may not of phrased it correctly though as I am not sure what to search for)
All of the actions you listed can be done by separate builders. So you can create a launch config to run the Maven clean action, another launch config to run the Eclipse clean command and so on.
When you have all of those launch configs available, install the CDT launch group feature to run them together with one click: https://stackoverflow.com/a/11905444/44089
There have been a number of scripting attempts with eclipse, but not many of them are successful. You can always write your own command and handler, and from there you can execute any number of commands that you can specify:
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil
.getActiveWorkbenchWindowChecked(event);
IHandlerService handlerService = (IHandlerService) window
.getService(IHandlerService.class);
try {
handlerService.executeCommand(
IWorkbenchCommandConstants.HELP_ABOUT, null);
handlerService.executeCommand(
IWorkbenchCommandConstants.FILE_REFRESH, null);
} catch (NotDefinedException | NotEnabledException
| NotHandledException e) {
throw new ExecutionException("Failed", e);
}
return null;
}
Then you just need to track down command IDs that correspond to what you want to do. ALT+SHIFT+F2 and then selecting a menu item can provide the command ID (or action definition ID, which is the same thing).

Suppress Errors in JavaScript validation

I'm currently developing an eclipse plugin. This plugin contains a project nature which depends on the javaScript nature of jsdt.
Now at a few details the JavaScripts that the projects of my nature can contain are somewhat special.
They can contain "compiler hints" which are basicly statements beginning with #
They can contain return statements outside of functions
But at this two points the standard validation of jsdt come in and marks them as errors (which is normally right). I already managed to get this errors filtered out in the properties of the JavaScript validator (manually).
My question is, how can i exclude these errors from the validation of jsdt automatically for the projects with my nature?
JSDT uses concrete syntax parser which generates syntax errors.
You can't disable this. Only semantics error or warnings can be configured.
However you can disable entire validation of JSDT.
Below solution will suppress errors ands warnings which are generated while we save some changes on java script files. (Auto Build, Build)
Open Properties Dialog of Your Project.
Choose Builders item.
Uncheck "JavaScript Validator". And Press OK button.
Remove current errors and warnings from Problems View
This solution can't eliminate error or warning annotations in editor while you edit. They will show up on editor temporarily only when you edit it.
After a lot of research, hours of deleting markers and debugging i finally managed to delete the errors i wanted. In a bad bad way of course but i've come to a point where i just wanted this to work no matter how it's done.
If you ever want to delete existing problems that had been created during the validation process of jsdt you need to do the following (and you must not ommit anything):
Create a class extending org.eclipse.wst.jsdt.core.compiler.ValidationParticipant
Override isActive(), buildStarting() and reconcile() methods.
So there are two things you basicly have to care about.
The actual problem markers that will be created or had already been created at the end of the validation process.
The Problems created by the validation process. They are of the type CategorizedProblem and can be obtained by the ReconcileContext object that is passed to the reconcile() method.
It seems to me that the CategorizedProblems will be translated to problem markers after the validation process.
So what you need to do is:
Delete all unwanted problem markers of all files in buildStarting (this removes problem markers from all files in your project that are about to be validated)
Iterate the CategorizedProblem objects of the ReconcileContext (getProblems())
Create a new Array containing only the CategorizedProblems you want to keep
Set this new Array to the ReconcileContext with putProblems()
Delete the unwanted markers again for that file (i don't know why this is needed, please don't ask, i don't care anymore :-/)
An example implementation of such a validationParticipant could look like this: (this one will filter out problems complaining about return statements outside of methods:
[...ommited imports ...]
public class MyValidationParticipant extends org.eclipse.wst.jsdt.core.compiler.ValidationParticipant{
#Override
public boolean isActive(IJavaScriptProject project) {
return true;
}
#Override
public void buildStarting(BuildContext[] files, boolean isBatch) {
super.buildStarting(files, isBatch);
for(BuildContext context : files){
IFile file = context.getFile();
deleteUnwantedMarkers(file);
}
}
#Override
public void reconcile(ReconcileContext context) {
IResource resource = context.getWorkingCopy().getResource();
CategorizedProblem[] newProblems = new CategorizedProblem[0];
ArrayList<CategorizedProblem> newProblemList = new ArrayList<CategorizedProblem>();
CategorizedProblem[] probs = context.getProblems("org.eclipse.wst.jsdt.core.problem");
if(probs != null){
for(CategorizedProblem p : probs){
if(!(p.getMessage().equals("Cannot return from outside a function or method."))){
newProblemList.add(p);
}
}
}
}
context.putProblems("org.eclipse.wst.jsdt.core.problem", newProblemList.toArray(newProblems));
deleteUnwantedMarkers(resource);
}
public static void deleteUnwantedMarkers(IResource resource){
if(resource.isSynchronized(IResource.DEPTH_INFINITE)){
try {
IMarker[] markers = resource.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
if(markers != null && markers.length > 0){
for(IMarker m : markers){
Object message = m.getAttribute(IMarker.MESSAGE);
if(message.equals("Cannot return from outside a function or method.")){
m.delete();
}
}
}
}catch (CoreException e) {
e.printStackTrace();
}
}
}
}
As i said, this is kind of a bad solution since the code relies on the String of the error message. There should be better ways to identify the problems you don't want to have.
Don't forget to add a proper extension in your plugin.xml for the ValidationParticipant.

How do I avoid a PMD CloseResource violation?

I'm modifying my application code in order to respect the pmd rules. I had a Close Resource error in this code:
Connection c = DataSourceUtils.getConnection(dataSource);
Statement request = null;
try {
request = c.createStatement();
request.execute(loadDataRequest);
} catch (SQLException e) {
dataLogger.error(e);
throw e;
}
So I searched and found an apache utility for avoiding it: DButils
My code became like this
Connection c = DataSourceUtils.getConnection(dataSource);
Statement request = null;
try {
request = c.createStatement();
request.execute(loadDataRequest);
} catch (SQLException e) {
dataLogger.error(e);
throw e;
} finally {
DbUtils.closeQuietly(request);
DbUtils.closeQuietly(c);
}
However, I'm still having the PMD alert in eclipse and sonar reports! Do you have any idea how to fix that permanently?
You can set the closeTargets property of the CloseResource PMD rule. When PMD finds similar method names as in the closeTargets property, it won't fire the warning message:
<properties>
<property name="types" value="Connection,Statement,ResultSet"/>
<property name="closeTargets" value="closeQuietly, closeConnection, close"/>
</properties>
Alternatively, you can use SourceMeter, which includes this configuration natively.
The problem is that PMD doesn't know closeQuietly() closes the connection. And it isn't that smart because if your method was named close() you'd have the same problem. And since it is a Java rule, it isn't easy to change the implementation because then you'd have to repackage the Eclipse and Sonar PMD plugins to recognize your copy of the rule.
Your options:
1) Add //NOPMD comment to suppress
2) Refactor the code to get/close the connection in a superclass so you only have it once.
PMD defines a parameter for this rule called closeTargets. By default, this parameter is set to close method. You can change it for specifying DbUtils.closeQuietly

GWT Product Mode AssertionException Catch ? HOW?

in product mode in GWT the assertion is not available which is good, but because of a GXT error I get an assertion error and because the necessary classes are not available all I get is a com.google.gwt.core.client.JavaScriptException error in the browser and it's not enough to properly debug it. The reason why I need this is because in my custom framework I created a class that's responsible for error handling
GWT.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
#Override
public void onUncaughtException(Throwable e) {
addError(e);
}
});
public void addError(Throwable ex)
{
if(!ex.getClass().equals(AssertionError.class))//(ex instanceof AssertionError))
{
this.addError(ex, true);
}
}
as you can see I've tried to capture the error but I'm unable to in production mode. I somehow need to be able to sepcify the exception so I can filter it. All errors get into the logs and I don't want these errors to appear there
GXT Error => http://www.sencha.com/forum/showthread.php?171409-RowEditor-AssertionError&p=709005
thanks help
By Egg
You need to enable assertions in your compiled code, and this is done very similarly to how you would do this in a standard jvm, using the -ea flag. Instead of passing this to the jvm though, it needs to be passed to the Compiler class (or put in the program args if running from eclipse, or some other tool).
See http://code.google.com/webtoolkit/doc/latest/DevGuideCompilingAndDebugging.html#DevGuideCompilerOptions for the list of all args you can pass to the compiler