I have a method declaration with an annotation that is formatted by Eclipse Mars as follows:
#Override
void addLoadShiftingConstraints() throws NoSuchDataException {
//method body
}
I would like to not indent the method declaration:
#Override
void addLoadShiftingConstraints() throws NoSuchDataException {
//method body
}
Currently I have following formatter setting for the method declaration:
Right click on Project =>Properties=>Java Code Style=>Formatter
=>Edit active profile => LineWrapping => Method Declaration => Declaration => Wrap where necessary
If I would choose the option Do not wrap instead, the unwanted indent would vanish. However, I would like to keep the wrapping for long declarations.
Is this an Eclipse bug or is there an additional setting for the Annotations that I would have to change in order to avoid the indent?
This is indeed a bug (related). The workaround is to set the setting to "Do not wrap" as you describe or to add an access modifier like private.
(Can't comment due to insufficient reputation, but found this answer through search and it applies to a second situation.)
I faced a similar problem with indentation of local variables, which only took affect when a comment was placed after an annotation. #Stefan's answer worked for this also.
#SuppressWarnings("JavaReflectionMemberAccess") // implicit method Enum#valueOf(String)
Method method = class_.getMethod("valueOf", String.class);
was being reformatted to
#SuppressWarnings("JavaReflectionMemberAccess") // implicit method Enum#valueOf(String)
Method method = class_.getMethod("valueOf", String.class);
but was fixed with the addition of a final modifier:
#SuppressWarnings("JavaReflectionMemberAccess") // implicit method Enum#valueOf(String)
final Method method = class_.getMethod("valueOf", String.class);
Related
I can make an RPC call in Java like this:
final FlowHandle flowHandle = rpcOps.startFlowDynamic(
TransferObligation.Initiator.class,
linearId, newLender, true);
The first parameter is the class to invoke and the next three are arguments to the class passed via varargs.
As we can see by the class definition the args match and the call works fine:
public Initiator(UniqueIdentifier linearId, Party newLender, Boolean anonymous) {
this.linearId = linearId;
this.newLender = newLender;
this.anonymous = anonymous;
}
However, if I add or remove args from the constructor the code will still compile and I will only notice at runtime (or integration testing - assuming I have enough test coverage).
The same applies if I pass the wrong args in the first place in the RPC call.
e.g. the following compiles fine but gives a runtime error:
final FlowHandle flowHandle = rpcOps.startFlowDynamic(
TransferObligation.Initiator.class,
linearId, newLender, true, 100000L, "Random String");
Is it possible to check for these errors with something other than test cases?
e.g. Static analysis using a custom IDEA code inspection or a custom SonarQube rule
EDIT: It appears that the Kotlin API has a type safe way of starting the flows (using inline reified extension functions) that the Java API does not, so I have removed the kotlin tag and updated the references to Java examples.
Along with CordaRPCOps.startFlowDynamic which as you mentioned has a varargs parameter for the Flow constructor arguments, there is CordaRPCOps.startFlow methods, which is basically nothing more than extension function for type-safe invocation of flows.
CordaRPSOps.kt
In Eclipse Luna, I want to change the content of the autogenerated methods, so I went to Window->Preferences->Java->Code Style->Code Templates->Code->Method body and I saw there this declaration:
// ${todo} Auto-generated method stub
${body_statement}
Is it possible to to change the ${body_statement} content?
Edit: #Duncan - I don't want my generated methods to return null but I want them to throw an exception that the method is not implemented. The reason why I want to change the ${body_statement} is because I want to change all occurrences by one edit and I don't want to go through all templates and inspect them one by one.
Just delete the invocation of ${body_statement} in your template
Here is my Method Body template which adds a TODO and an exception should the method be called:
// ${todo} Implement ${enclosing_type}.${enclosing_method}
throw new RuntimeException("Unimplemented Method ${enclosing_type}.${enclosing_method} invoked.");
Which when invokded after writing
int foo = doSomething();
Generates:
private int doSomething() {
// TODO Implement ScaledFraction.doSomething
throw new RuntimeException("Unimplemented Method ScaledFraction.doSomething invoked.");
}
${body_statement} is a "variable". Click on "Edit..." at the right side of the Code Templates list to edit a code template and use "Insert Variable..." to see a list of available variables.
The ${body_statement} variable is actually empty for new methods. If you want to provide some default-code for each new method, you can simple add that text above the ${body_statement}.
Adding real code below the variable in that template will not work, since ${body_statement} will be replaced by a return statement in some cases.
I am admittedly new to JMockit, but I am for some reason having trouble mocking System.getProperties(). Thanks to the help of following post:
https://stackoverflow.com/questions/25664270/how-can-i-partially-mock-the-system-class-with-jmockit-1-8?lq=1
I can successfully mock System.getProperty() using JMockit 1.12:
#Test
public void testAddSystemProperty_String() {
final String propertyName = "foo";
final String propertyValue = "bar";
new Expectations(System.class) {{
System.getProperty(propertyName);
returns(propertyValue);
}};
assertEquals(propertyValue, System.getProperty(propertyName));
}
But the eerily similar code for mocking getProperties() barfs:
#Test
public void testAddSystemProperty_String() {
final String propertyName = "foo";
final String propertyValue = "bar";
final Properties properties = new Properties();
properties.setProperty(propertyName, propertyValue);
new Expectations(System.class) {{
System.getProperties();
returns(properties);
}};
assertEquals(1, System.getProperties().size());
}
I get the following exception that points to the "returns" method:
Missing invocation to mocked type at this point;
please make sure such invocations appear only after
the declaration of a suitable mock field or parameter
Also, how do I mock both methods at the same time? If I put them in the same Expectations block (with the getProperty() first), then I do not see the exception, but System.getProperties() returns the real system properties, not the mocked ones; though getProperty(propertyName) returns the mocked value. I find that totally wonky behavior.
I see from this post that certain methods cannot be mocked, but System.getProperties() is not on that list:
JMockit NullPointerException on Exceptions block?
I am also finding that a lot of solutions on SO that worked with JMockit 2-3 years ago are totally non-compilable now, so apparently things change a lot.
System.getProperties() is indeed one of the methods excluded from mocking in JMockit 1.12. The exact set of such excluded methods can change in newer versions, as new problematic JRE methods are found.
There is no need to mock System.getProperty(...) or System.getProperties(), though. The System class provides setProperty and setProperties methods which can be used instead.
Hopefully someone else finds this useful:
This can be solved with Mockito / PowerMock (1.5.3).
Note that I am testing a utility that will exhaustively try to find the property value given a list of possible sources. A source could be a system property, an environment variable, a meta-inf services file, a jndi name, a thread local, a file on disk, an ldap, basically anything that can perform a lookup.
#RunWith(PowerMockRunner.class)
#PrepareForTest({ClassThatDirectlyCallsSystemInCaseItIsNestedLikeInMyCase.class})
public class ConfigPropertyBuilderTest {
#Test
public void testAddSystemProperty_String_using_PowerMockito() {
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getProperty(propertyName)).thenReturn(propertyValue);
PowerMockito.when(System.getProperties()).thenReturn(new Properties() {{
setProperty(propertyName, propertyValue);
}});
// Here is realistic case of calling something that eventually calls System
// new configBuilder().addEnvironmentVariable(propertyName)
// .addSystemProperty(propertyName)
// .getValue();
// Here is simplified case:
assertEquals(1, System.getProperties().size());
assertEquals(propertyValue, System.getProperty(propertyName));
}
}
I could call System.setProperty(), but when you start getting into the other sources, it becomes less clear.
Note that I do not specifically care about the value returned by System.getProperty() either; I simply want to ensure that it is called if the first look up fails.
For example, in the above code snippet, the environment variable does not exist, so System.getProperty() should be called. If the environment variable existed (as it does in the next test case which is not shown), then I want to verify that System.getProperty() was not called because it should have short circuited.
Because of the difficulties in faking out the other sources using real files, real ldap, real APIs, etc, and because I want to verify certain APIs are either called or not called, and because I want to keep the tests looking consistent, I think mocking is the correct methodology (even though I may be trying to mock stuff that is not recommended in order to keep it all looking consistent). Please let me know if you think otherwise.
Also, while I do not understand the difficulties of maintaining these mocking frameworks (especially the cglib based ones), I understand the difficulties do exist and I can appreciate the sort of problems you face. My hat goes off to you all.
I am getting this error:
Exception in thread "Thread-0" java.lang.VerifyError: Constructor must call super() or this() before return in method JGame.Util.KeyboardMap.<init>()V at offset 0
at JGame.Room.Room.keyboardEventTests(Room.java:81)
at JGame.Room.Room.run(Room.java:54)
at java.lang.Thread.run(Thread.java:722)
When my application loads, it calls this method right away (KeyboardMap.map is an empty HashMap).
Here is the Method (Line 54 calls this method this.keyboardEventTests();):
protected void keyboardEventTests(){
for(Map.Entry ap : KeyboardMap.map.entrySet()){ // Line 81
Mapping mp = (Mapping)ap.getValue();
if(mp.doing){
mp.run();
}
}
}
And here is the KeyboardMap class.
package JGame.Util;
import java.util.HashMap;
import java.util.Map;
public class KeyboardMap{
public static Map<String, Mapping> map = new HashMap<>();
public static void set(String key, Boolean value, Runnable run){
Mapping mp = new Mapping();
mp.doing = value;
mp.run = run;
KeyboardMap.map.put(key, mp);
}
public static Mapping get(String key){
return KeyboardMap.map.get(key);
}
}
Why am I getting that error, and how can I get rid of it?
Why am I getting that error, and how can I get rid of it?
The big clue is that this is a VerifyError, not a compilation error. What this means is that the JVM has found a bytecode file in which one of the constructors is not chaining properly. These are (in effect) a malformed bytecodes.
How can that happen?
Well it CAN'T happen in a Java class that is (just) compiled in the normal way. The compiler will automatically insert an implicit super() call into any constructor that doesn't explicitly chain.
If this is Java code, then either:
the class was compiled using broken compiler (unlikely!), or
something has tweaked the bytecodes after compilation.
If it was some other language, then the first suspect would be the "other language to bytecode" compilation process.
I think you are getting this problem because your unit tests is using a mocking framework, and the mocking framework is using "byte code engineering" to inject something into the classes under test. The code that is doing this has "made a mistake" and the result is bytecodes that won't compile.
This was apparently fixed by a rebuild, but that doesn't contradict this explanation. A rebuild could clear out broken instrumentation code injected by the mocking framework. And next time around, the framework could "get it right".
Just override the default contructor by adding
public KeyboardMap() {
}
to the KeyboardMap class. It will work.
I had the same problem, and it was caused by a very strange thing:
In NetBeans, i use editor fold to fold long codes:
// <editor-fold desc="SOME DESCRIPTION">
...
...
// </editor-fold>
And it appeared that in one of such my folds i had forgotten to write the beginning of fold, like this:
...
...
// </editor-fold>
Correcting this solved my problem.
Strange, because this is just a comment and it's for NetBeans
In my case, turning off minify in build.gradle under buildTypes helped.
minifyEnabled false
I am getting this error in an eclipse plugin. Here is the code :
ICompilationUnit testCU = findTestUnit(type);
// add some stuff to testCU
testCU.commitWorkingCopy(false, null); // error happens here.
I'll guess that you're using this interface. Here's the method signature in question:
void commitWorkingCopy(boolean force, IProgressMonitor monitor) throws JavaModelException;
Perhaps you can try casting that null to IProgressMonitor.
Another idea would be to look at the type returned by that method call and make sure that it implements the right interface. Perhaps that is not correct.