Eclipse code formatter: Perform a single action - java

How can I perform a single action in Eclipse Java code formatter? For example I want to clean up every occurrence of
if (bla) {
...
}
else {
...
}
To this
if (bla) {
...
} else {
...
}
But nothing else. I need this to clean up specific findbugs issues. If I'd run the whole code formatter actions on the project, it would lead us into merge hell. So I want to handle such findbugs issues one by one and therefore It would be great to just execute such a single rule. The Version of Eclipse wouldn't matter, right now I tried with the latest Luna.

A quick way to do this would be to use the search and replace option in eclipse. Go to Search menu->File
Search for : \}\s+\n\s+else\s+\{
Replace with : } else {

Related

New value added to Java Enum not available during debug

I am having the following problem:
I have an Enum that was originally declared with 5 elements.
public enum GraphFormat {
DOT,
GML,
PUML,
JSON,
NEO4J,
TEXT {
#Override
public String getFileExtension() {
return ".txt";
}
};
Now I need to add an additional element to it (NEO4J). When I run my code or try to debug it I am getting an exception because the value can't be found in the enum.
I am using IntelliJ as my IDE, and have cleaned the cache, force a rebuild, etc.. and nothing happens. When I look at the .class file created on my target folder, it also has the new element.
Any ideas on what could be causing this issue ?
I found my problem and want to share here what was causing it. My code was actually for a Maven plug-in which I was pointing to another project of mine to run it as a goal. However the pom.xml of my target test project was pointing to the original version of the plug-in instead of the one I am working on, and that version of course is outdated and does not include the new value. Thank you.

Refactoring - Collapsible "if" statements should be merged

I am trying to clean up our legacy code, and noticed there are many if conditional code that can be merged.
Example -
if (file != null) {
if (file.isFile() || file.isDirectory()) {
/* ... */
}
}
This can be refactored to,
if (file != null && (file.isFile() || file.isDirectory())) {
/* ... */
}
Manually performing this change is a pain. So, I was trying to check on inspection tool and template refactoring in intelliji to help me with this bulk code refactoring.
Could not locate this eclipse IDE too.
Kindly suggest, is there an option in Intelliji/Eclipse for this
In IntelliJ IDEA put the text cursor on the first if keyword, press Alt+Enter and invoke Merge nested 'if's.
You can also use Structural Search & Replace to perform this operation in bulk. Use the following search pattern:
if ($a$) {
if ($b$) {
$statement$;
} else $void$;
} else $void$;
Click Edit Variables... and set the minimum and maximum count of statement to 0,∞. Also set the minimum and maximum count of void to 0,0
Use the following replacement pattern:
if (($a$) && ($b$)) {
$statement$;
}
Note that this replacement will introduce redundant parentheses in some cases to prevent changes the semantics of the code. These can later be removed again by invoking Run Inspection by Name and running the Unnecessary parentheses inspection.
The AutoRefactor Eclipse plug-in can do this for you in batch.
See http://autorefactor.org/html/samples.html and select CollapseIfStatementSample.java. You can do this on a whole file, package, or even project.
There is a refactoring to remove unnecessary parentheses too: SimplifyExpressionSample.java (see e. g. line 144).

JavaFX: Getting Stage of running Applications

For testing a application with TestFX i need to get the actual primary stage of a running application. This means that i haven't the code, i can just run the application through a jar.
Is there any possible solution for this? Scenic View does this already, but i was not able to reproduce this functionallity, especially because it seems that they use the deprecated funtion
Windows.impl_getWindows
which is not working in my case.
Try this:
import com.sun.javafx.robot.impl.FXRobotHelper;
static Collection<Stage> getAllJavaFXStages() {
try {
return FXRobotHelper.getStages();
} catch ( NullPointerException npe ) {
// nasty NPE if no stages exist
return Collections.emptyList();
}
}
```
Based on my own testing framework code: Automaton.
EDIT:
If you want to get a Stage from a different JVM instance than where you're running your code, then there's no simple way.
You're right, ScenicView does it, but it uses tools.jar to do it. This is not a standard jar you get in your runtime, so you must add it manually (placing it in jre/lib/ext should do it, you'll normally find it in lib only).
I tracked down the code where ScenicView seems to be doing it in their BitBucket repo.
Check the function getRunningJavaFXApplications for example.
Have fun using that in your tests!

How to do code format switching in eclipse?

A)
public class SomeClass
{
private SomeClass()
{
}
public String someMethod()
{
return "";
}
}
B)
public class SomeOtherClass{
private SomeOtherClass(){
}
public String someOtherMethod(){
return "";
}
}
I have joined a new team and will be working on a project which follows the A) convention. However, I have always been the B) java style person and am way more comfortable with B).
1)On the checked out code, is there a way I could convert the java code style in my eclipse to B)
2)And also ensure the project->Team->Synch with Repo ignores this style change when checking for updates ?
3)Before comitting, I want to switch the code back to the commonly followed style and check it in. I synch for changes every morning and commit changes throughout the day.
Is creating a new profile in the preferences->code style->Formatter the only way ? I also looked at http://astyle.sourceforge.net/ but I am somehow confident there is a simpler eclipse solution to this. How could I achieve this in the simplest possible way ?
I am using eclipse kepler
Work flow:
In Windows > Preferences > Java > Editors Save Actions deselect formatting on save.
Check out code.
Clean up your code(Right click on project go to Source > Clean up. Note this works on project level but not on working set, so you have to do it on each and every project) with your Formatter(B) profile enabled.
In Windows > Preferences > Java > Editors Save Actions select formatting on save and start working.
Same as step 1.
Same as 3 but with formatter profile A.
Commit the code.
These steps can be automated with Ant/Maven script(?) or by developing your own eclipse plug-in.
On sync comparator will NOT ignore style change. IMHO there is no escape. Clean up before sync is only the go.
In Git SCM there are some commit and checkout hooks but I haven't explored on this.

How to detect that code is running inside eclipse IDE

How to detect that code is running inside eclipse IDE
I am not aware of a generic way to get this kind of information.
One suggestion:
When you start a Java program (or a web server) inside Tomcat, simply add an argument that will indicate that this program is launched by Eclipse.
You can do that by opening the "Open Run Dialog" ("Run" menu), then select your type of application and add in the "Arguments" tab a -DrunInEclipse=true.
In your Java code, you can check the value of the property:
String inEclipseStr = System.getProperty("runInEclipse");
boolean inEclipse = "true".equalsIgnoreCase(inEclipseStr);
This way, if the program is not running inside Eclipse (or unfortunately if you forgot to set the property) the property will be null and then the boolean inEclipse will be equal to false.
Although I agree that having the code detecting a single IDE as the dev env is not an optimal solution, the following code works.
Like others proposed, using a flag at runtime is better.
public static boolean isEclipse() {
boolean isEclipse = System.getProperty("java.class.path").toLowerCase().contains("eclipse");
return isEclipse;
}
1) Create a helper method like:
public boolean isDevelopmentEnvironment() {
boolean isEclipse = true;
if (System.getenv("eclipse42") == null) {
isEclipse = false;
}
return isEclipse;
}
2) Add an environment variable to your launch configuration:
3) Usage example:
if (isDevelopmentEnvironment()) {
// Do bla_yada_bla because the IDE launched this app
}
Actually the code is not being run inside Eclipse, but in a separate Java process started by Eclipse, and there is per default nothing being done by Eclipse to make it any different than any other invocation of your program.
Is the thing you want to know, if your program is being run under a debugger? If so, you cannot say for certain. You CAN, however, inspect the arguments used to invoke your program and see if there is anything in there you do not like.
If your workspace matches some pattern like "/home/user/workspace/Project" you can use the code below:
Boolean desenv = null;
boolean isDevelopment() {
if (desenv != null) return desenv;
try {
desenv = new File(".").getCanonicalPath().contains("workspace");
}
catch (IOException e) {
e.printStackTrace();
}
return desenv;
}
A more generic and precise way, that can be used on any IDE would be loop at:
ManagementFactory.getRuntimeMXBean().getInputArguments()
looking for "-Xdebug" || (starting with) "-agentlib:jdwp=".
I came with this from #saugata comment here.
This is excellent if you want to throw a conditional exception preventing the application from simply exiting. Use a boolean like "ideWait" and add it to Eclipse watch expressions as ideWait=false, so whenever you stop at that throw, and "drop to frame" you can continue debugging happily (I mean it!)
I don't think there is any way to do this. But what I would suggest is just a command line argument such as 'debug'. Then in your main method just do
if (args.length > 0 && args[0].equalsIgnoreCase("debug")) {
// do whatever extra work you require here or set a flag for the rest of the code
}
This way you can also get your extra code to run whenever you want just by specifiying the debug parameter but under normal conditions it will never execute.
This might work if your alternative execution work flow provides a different set of dependencies:
boolean isRunningInEclipe = false;
try {
Workbench.getInstance();
isRunningInEclipe = true;
} catch (NoClassDefFoundError error) {
//not running in Eclipse that would provide the Workbench class
}
You could detect if you're inside a JAR or not, as per Can you tell on runtime if you're running java from within a jar?
Eclipse will run your app from the classes/ dir, whereas most of your end users will be running the app from a JAR.
System.out.println("Is my parent eclipse[.exe]? " +
ProcessHandle.current()
.parent()
.flatMap(parent -> parent.info().command())
.orElse("")
.matches("^.*eclipse(\\.exe)?$"));
You may try something like this:
if (ClassLoader.getSystemResource("org/eclipse/jdt/core/BindingKey.class")!=null){
System.out.println("Running within Eclipse!!!");
} else {
System.out.println("Running outside Eclipse!!!");
}

Categories