Mastering Eclipse IDE - Tips, Tricks


Quick Access(Command+3)
-- For example, to change a string to upper case or lower case, and you don't know the short cuts, then just select the text, type "upper" or "lower" in quick access text box.
-- Open specific view, preference, call specific command.

Shortcuts
Command+./Ctrl+.      Go to next error/warning
- We can configure which annotations to traverse by clicking on the dropdown: like adding Tasks.
Command+1/Ctrl+1    Quick fix
Alt + Shift + T            Opens the context-sensitive refactoring menu
Alt + Shift + Z     Surround block with try and catch - config first
Command +M            Maximizes the current view or editor
Command +Shift+/     Insert block comment
Alt+Shift + N             Shortcut for the menu to create new objects

Command+D              Delete current line
Command +E
Search dialog to select an editor from the currently open editors
Command+,               Open preference 

Quick fix:
Convert "" + "" to MessageFormat or StringBuilder.
Convert anonymous class creation to lambda expression and vice versa
Show spelling suggestions

Refactoring
Eclipse Refactor Actions
https://bmwieczorek.wordpress.com/2009/11/28/eclipse-refactoring/
Move static methods/fields to another class
-- Select them in outline view -> Refactor -> Move 
Change method signature
-- Add/remove/move parameters and give default value
Introduce Parameter Type
-- When there are too many parameters in method
Rename
- Press cmd+option+r twice or click options to open a dialog to also rename the getter and setter.

Configuration
Auto Save
General > Editors > Auto-save
Configure Eclipse Compiler Warnings
Enable null analysis, unbox conversion, missing default in switch etc
Leveraging JSR-305 null annotations to prevent NullPointerExceptions
Use @CheckForNull, @Nonnulls

Enable Save Action
Configure and Run Clean up
- We can configure eclipse to auto run clean up when save 
- We can also run Clean up manually via quick access or assign it a shortcut such as ctrl+alt+command+c

Code Recommender
toString() Generator: Code Styles - Use StringBuilder or Skip Null
Configure hashCode and equals to use blocks in "if" statement.

Static import
To help write test cases easier, when we type "assertT" and hit Ctrl+Space, we want Eclipse to add static import automatically for us: import static org.hamcrest.MatcherAssert.assertThat;
Window > Preferences > Java > Editor > Content Assist > Favorites, then add:
org.hamcrest.Matchers.*
org.hamcrest.CoreMatchers.*
org.mockito.Mock.*
org.mockito.Mockito.*

org.mockito.Matchers.*
org.junit.*
org.junit.Assert.*
org.junit.Assume.*
org.junit.matchers.JUnitMatchers.*

JDK8:
java.util.stream.Collectors.*

com.jayway.restassured.RestAssured.* -> if use restAssured.

Transform static invocation to a static import - cmd(ctrl)-shift-M

Code Template
Use Template view to learn shortcuts
static_final, test, instanceof, lazy, lock, systrace, 
.var .null, .nnull

Debugging
Use Display view to execute (any) code in current context
CTRL+U (execute) or CTRL+SHIFT+I (inspect)

Launch Group
Group related debug/remote applications together.
Example - local solr remote debug

Force Return in Display view
Use conditional breakpoint to execute any code without stopping

Force Eclipse to throw exception in display view
Execute: {throw new AnyKindOfException();}

Navigation
Drop to Frame
Run to line(Ctrl+R)
Smart Step into selection -> Ctrl + Alt + Click
-- To step into a single method within a series of chained or nested method calls.
Detail Formatter in Variables View
Change preferences of detail formatters:
- So eclipse will show toStirng value directly in value field for variables like StringBuilder, Map etc.
Show variable details (toString() value) to one of the following:
As the labels for all variables
As the labels for all variables with detail formatters

SolrQuery : Url Decode
java.net.URLDecoder.decode(this.toString())
Date : Show utc time
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", java.util.Locale.ROOT);
sdf.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
sdf.format(this);
new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(this)

Common Preference Settings
Remove java exception breakpoints
-- Go to Java>Debug, Uncheck "suspend on uncaught exception"

Improve Eclipse Performance
http://www.slideshare.net/kthoms/boosting-the-performance-of-your-eclipse-ide-eclipsecon-france-2016
Disable autobuild
- Uncheck 'Build Automatically'
- Eclipse auto build before launching the app(or tomcat): Pref > Run/Debug > Launching

Uninstall not-needed plugins such as mylyn at Help -> Installation Details
Close Unwanted Projects
eclipse.ini
-server
-Xms1g
-Xmx8g
-Xverify:none -> disable class verification

Show heap status at General
General -> Appearance
Disable theming
Disable Animations

Disable all plugins at General -> Startup and Shutdown
Disable unnecessary Validators -> Suspend all
Disable unnecessary Label Decorations

Click on Team -> Disconnect on project
- If you use git command

Maven:
Disable download repository index on startup
User interface: open xml page in the pom editor by default

Exclude workspace folder from Spotlight Index
System Preferences -> Spotlight -> Privacy tab, add folder to exclude from index
Exclude workspace from anti-virus

Find huge files
du -h -d 1 .metadata/.plugins | gsort -h
.m2/repository/.cache/m2e
metadata/.plugins/org.eclipse.m2e.core

Cleanup Metadata
.metadata/.plugins/org.eclipse.wst.server.core
.metadata/.plugins/org.eclipse.jdt.core

Search local history
grep -R -i yourQuery .metadata/.plugins/org.eclipse.core.resources/.history

Uncheck Re-open Remote Systems view in "Remote system".

JUnit - UnCheck Show Failures Only

Run Tests Across Multiple Projects
https://github.com/takari/takari-cpsuite
Create a maven project depending on all the projects you want to test.
pom.xml:
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
  </dependency>
  <dependency>
    <groupId>io.takari.junit</groupId>
    <artifactId>takari-cpsuite</artifactId>
    <version>1.2.7</version>
  </dependency>
</dependencies>
Create Test code:
import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.runner.RunWith;
@RunWith(ClasspathSuite.class)
public class TestRunner {
}

Effective Search
Filtering Call Hierarchy
- Filters: 
   exclude test classes: *.Test*, *.*Test, *.*TestCase, *.*TestBase
- Search in option to exclude application/jre libraries
- Field Access: Read or write access

Using Regular Expression
When we highlight words we want to search for, then Ctrl+H, the search dialog will contains the word we select.

If previously we selected "Regular Expression", Eclipse will automatically create the regex for us.

Press Ctrl+Space for content assist when write regex in search box.

Find empty lines: ^\s*\n
We can show file in terminal or package explorer in "Open Resource" dialog.

Show file in terminal or system explorer in package explorer view.

Eclipse Console View
We can open multiple consoles by "Open Console",  and pin it by "Pin Console", move them to different locations.

Click "Display selected console" button to switch console.
If don't want to open or switch console when there is update:
- Deselect "Show console when standard out changes" and "Show console when standard error changes"

Autosave for dirty editors
Preferences > General > Editors > Auto-save

Hot deploy
Eclipse supports limited hot deploy function: we can change the method implementation, but not add new classes/methods.

We can use dcevm and HotswapAgent for true hot deploy - check the link for how to setup them.
- Match the java build version and dcevm version: light-jdk8u112-8 works with Java 8u112.

Add -XXaltjvm=dcevm -javaagent:~/hotswap-agent-1.0.jar to tomcat VM arguments.

Plugins
MoreUnit
Ctrl+U: create test method

Ctrl+J:  jump to test method
Eclipse Grep Console
Using Eclipse Console plugin to show different colors for warning, error in console
ERROR:      (^(ERROR|SEVERE):)|Exception|(^\s+at)
Warning:      ^WARNING:

Spell Check
Eclipse default spell checker can detect spelling error in java doc, and plain text file.
Go to Window > Preferences > General > Editors > Text Editors > Spelling, to enable/disable or change the settings.

To detect spelling error in names of interfaces, classes, methods, constants, use jdt-spelling

We can use quick fix(cmd+1) to fix spelling error or add word to dictionary.

Misc
Enable "Link With Editor" in Package Explorer/Project Explorer/Navigator/Breakpoints
Use Working Sets to group different projects.

Linking an external folder to Eclipse

Turn off code formatter for certain sections of java code
Go to Preferences>Java>Code Style>Formatter.
Click on Edit, go to Off/On Tags, select Enable Off/On tags.
// @formatter:off
...
// @formatter:on

Determining who last modified a line with the Annotate command
Team > Show Annotation

Name template during project import
When need import maven projects multiple times into the same workspace,  in the advanced section, specify the name template like [artifactId]-something-here, so each project will have a different suffix.

Prevent line wrapping in XML and HTML files
Use: <![CDATA[ ]]>

Block Selection Mode
Use Ctrl+3 and type "block"
Mac:         Command+Option+A
Window:  Alt+Shift+A

Open multiple eclipse instances/workspaces
In Mac: open -n Eclipse.app
Or use OS X Eclipse Launcher

Other Plugins
Easy-shell
Open folder in explorer or command line.

Troubleshooting
Kill hang stopped tomcat process in Eclipse
Sometimes, when we stop tomcat, it may hang 
- it becomes gray square Cancel Requested.
(sometimes lsof -i :8080 shows nothing, but the tomcat process is still there) We can use command line like jps to find the tomcat process, and kill it. 

Find logs at yourWS/.metadata/.log

How to remove eclipse error "A cycle was detected in the build path of the project"
You can go to Preferences -> Java -> Compiler -> Building and change the Error to Warning.

Eclipse.ini


Misc
Docking a detached view
Click on the tab (not on the title of detached tab window) and drag


Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)