Eclipse Notes

See how to set up a JDK and Tomcat with Eclipse.

(This is a lot more dumbed-down than it needs to be, but at least the information is all here. Involuntary obsession and compulsion leads me to find a single, intact level at which to express something like this and stick with it so it's all uniform. If I start too low, I tend to stay there and take a lesson for next time.)

See Eclipse keys and ctag functionality here.
See Java errors/warnings here.


Eclipse update sites of interest to me

Where to go to get useful plug-ins. The URL in italics is to be copied and given to Eclipse Help -> Install New Software... -> Add.

(Starting in Indigo, I use Eclipse Marketplace... instead of Install New Software.... See here.)


eclipse.ini

Contents of my eclipse.ini at one point:

	-showsplash
	org.eclipse.platform
	-vmargs
	-Dosgi.requiredJavaVersion=1.5
	-Xms256m
	-Xmx1024m
	-XX:PermSize=64M
	-XX:MaxPermSize=256M

Eclipse memory issues...

Please read my glossary for definitions of terms such as XX:MaxPermSize.

At one point, my eclipse.ini entries, maximized because I had plenty of room on my host computers, were:

	-vmargs
	-Xms256m
	-Xmx1024m
	-XX:PermSize=128m
	-XX:MaxPermSize=512m

(This is just a record I can return to for comparison; it's not otherwise significant nor is it meant as a suggestion.)

Note that what is set in eclipse.ini has nothing whatsoever to do with running code you create in the IDE. It's only a configuration for Eclipse itself. For setting configuration for the application under development in Eclipse, see below.

Windows

Despite running Windows 64-bit and/or despite having lots of available, physical memory, it's rarely if ever possible to increase the amount of memory for Eclipse to anything like what you imagine you could.

This is actually not an Eclipse-specific issue; it's a general issue with Java on Windows where continguous memory can't be provided because of how Windows manages it. The JVM insists on managing a single, contiguous chunk rather than accepting to unite discontinguous chunks.

There are utilities that attempt to get Windows to defragment its memory, but I haven't tried them. There is a tool from Windows Internals called VMMap that shows how the virtual process memory is fragmented and how big the largest continuous block is.

In theory, it should be possible to reboot Windows and, before starting anything else (tall order), launch Eclipse (Java). Maybe memory will not have become so fragmented?

I read one place that it's never possible to get more than -Xmx1300m, and usually far less. This source claimed that it depends on the version of Windows and what applications/drivers are installed.

Linux

While I haven't experimented too much, it should be possible to set the amount of memory on Linux, especially 64-bit, to just about anything since that OS' memory manager can maintain virtually contiguous blocks of memory. I haven't greatly experimented with that yet because it's never become a problem I didn't want to work around out of general "niceness" of my applications; and, for running Eclipse, I haven't so far had the same problems there as on Windows.

Setting command-line arguments for application under development

Use these instructions to set memory configuration for running the project under development. Obviously, when deployed, the application or other code will have to enjoy the same treatmentat the hands of its user.

  1. Right-click on the project (or other representative file in the project) in the Project/Package Explorer view.
  2. Choose Run As -> Run Configurations....
  3. Add memory-configuration arguments on the command line as illustrated below.

Initial Eclipse launch...

Workspace vs. working set: best practice

Launch Eclipse and create a new workspace. Instead of using working sets (see http://www.windofkeltia.com/j2ee/images/eclipse-working-set.png"), which are otherwise very useful in Eclipse to create separation between projects in a same workspace, use workspaces themselves between branched versions of the product.

	russ@taliesin:~/dev> mkdir workspace-1.7

When Eclipse asks for a workspace, browse to the one you've created. Set it as the definitive workspace used without prompting when you launch Eclipse: you can change it using the File->Switch Workspace menu option should you need to create and use another code branch simultaneously.


Working with the Eclipse workspace...

The Eclipse workspace is a concept that allows you to collect related projects into one space. You don't have to keep all your projects, however unrelated, in one place. (You can also use "working sets" to solve this and similar problems, but I despise large numbers of projects in my workspace.)

Workspaces are less of a headache than you might think. For example, if you don't like the name of a workspace, you might simply rename it in the file system. The next time you launch Eclipse, you can navigate to it and choose it. You can even swap names thus:

	russ@taliesin:~/dev> mv workspace-2.0 poop
	russ@taliesin:~/dev> mv workspace-1.8 workspace-2.0
	russ@taliesin:~/dev> mv poop workspace-futures

One annoying thing about Eclipse is that it doesn't display the name of the current workspace anywhere. You must determine this by process of elimination: go to File->Switch Workspace. If the workspace you think you're presently working in isn't listed, then that's probably the one you are working in.


Creating launch configuration

Seemingly, one never goes to Eclipse for help with Eclipse, but to Google, an Eclipse forum, etc. In this case, Eclipse help is pretty good:
http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.jdt.doc.user/tasks/tasks-java-local-configuration.htm

Later note: It's not always like this, but you can replace "galileo" in the link above with "helios" or "indigo".


Correcting project parameters...

In the case where a different (for example, more modern) JDK/JRE and/or Tomcat were used inadvertantly, it becomes difficult to change them back. The simplest way is to delete the project, but not its source code which is sitting in the filesystem from Subversion, or created and already existing and which we don't want to use, and recreate it.

You should have used the 1.4 JDK.

After deleting the project, drop the Eclipse workbench. Go to the filesystem and remove the following files and subdirectory:

Do not remove subdirectory build if it is actually part of your source code (which should not, but could be the case if you chose it on purpose—it is the name Eclipse chooses to call the place it puts built classes, but in our case here, we always change this to classes either under web/WEB-INFO or directly under the project.


Working sets...

This is an optional way of sorting out differences between branches (release versions) of the repository code. It's not a focus of this document, but is mentioned in passing as a solution. The solution I'm adopting is not to use working sets for this, but separate workspaces.

There is a little triangular control under the Package Explorer tab/pane, at least, that gets you access to creating and using a working set. See the red arrow in the image at the right (click to enlarge).


Building...

Building should happen automatically at each point of modification of any aspect of the project unless you've turned this off. I find that in knitting together a project, I must often iright-click on the project, use Refresh and/or choose Project->Clean... to reset the state of the project and force a new rebuild in order to be certain that the errors and warnings displayed aren't stale.

Libraries between projects

Carefully attend to all of these little tasks.

In the Java Build Paths->Libraries tab of most (or all) subprojects, remove all the individual JAR references and replace with Add Library->WebApp Libraries, choose RetainServer.

Add also Server Runtime as Tomcat 5.5.

Error/warning levels in Eclipse

Gradually, the levels of what is reported as a compilation error or warning must be adjusted a) to match the carelessness of authorship of the code inherited or b) the refinement brought to that authorship when writing code or subsequently. In addition, there are problably simply some errors that will never go away, but must be eliminated for the project to be run and/or distributed.

Here are tables explaining error/warning messages you'll see and which preferences settings correspond to them:

Following is a list of settings and the values I've chosen reached via right-clicking on the project and choosing Properties->Java Compiler->Errors/Warnings.

It appears possible to set these globally for Eclipse (or, perhaps rather for the workspace) by going to Window->Preferences->Java->Errors/Warnings. Right-clicking each project, choosing Properties->Java Compiler->Errors/Warnings and ensuring that Enable project specific settings is not clicked. This will direct the project to behave in this respect to the global Eclipse/workspace settings for compiler errors and warnings.

Code style
Non-static access to static member Ignore
Indirect access to static member Ignore
Unqualified access to instance field Error
Undocumented empty block Warning
Access to a non-accessible member of an enclosing type Ignore
Method with a contructor name Warning
Parameter assignment Ignore
Non-externalized strings (missing/unused $NON-NLS$ tags) Ignore
Potential programming problems
Serializable class without serialVersionID Warning
Assignment has no effect (e.g.: 'x = x') Error
Possible accidental boolean assignment (e.g.: 'if a = b') Error
'finally' does not complete normally Error
Empty statement Error
using a char array in string concatenation Error
Hidden catch block Error
Inexact type match for vararg arguments Error
Boxing and unboxing conversions Error
Enum type constant not covered on 'switch' Error
'switch' case fall-through Error
Null pointer access Error
Potential null pointer access Error
Name shadowing and conflicts
Field declaration hides another field or variable Error
Local variable declaration hides another field or variable Error
        Include constructor or setter method parameters (unclicked)
Type parameter hides another type Error
Method overridden but not package visible Error
Interface method conflicts with proected 'Object' method Error
Deprecated and restricted API
Deprecated API Warning
        Signal use of deprecated API inside deprecated code (unclicked)
        Signal overriding or implementing deprecated method (clicked)
Forbidden reference (access rules) Error
Discouraged reference (access rules) Warning
Unnecessary code
Local variable is never read Warning
Parameter is never read Ignore
        Check overriding and implementing methods (unclicked)
        Ignore parameters documented with '@param' tag (clicked)
Unused import Warning
Unused local or private member Warning
Redundant null check Ignore
Unnecessary 'else' statement Error
Unnecessary cast or 'instanceof' operation Ignore
Unnecessary declaration of thrown checked exception Ignore
        Check overriding and implementing methods (unclicked)
Unused 'break' or 'continue' label Error
 
— The following are unused because didn't exist in Java 4 —
Generic types
Unchecked generic type operation Warning
Usage of a raw type Warning
Generic type parameter declared with a final type bound Warning
Annotations
Missing '@Override' annotation Ignore
Missing '@Deprecated' annotation Ignore
Annotation is used as super interface Warning
Unhandled warning token in '@SuppressWarnings' Warning
        Enable '@SuppressWarnings' annotations
Treat errors like fatal compiler errors (make compiled code not executable) (clicked)

ctag-like actions in Eclipse

The following are keyboard short-cuts to doing things in Eclipse that compensate (often much better) for the lack of ctags and cscope. Also, other cool stuff reached similarly.

  Key Action or description
CTRL L Go to line number...
SHIFT CTRL R The most magic: type in a classname or filename.
SHIFT CTRL T Find class from (what's under the) cursor.
CTRL T Report class/package hierarchy for present file.
CTRL O List methods and data from here to end of class.
CTRL H Intelligent search of Java code.
CTRL ALT H Show method's call hierarchy (called from/calls)
CTRL click Find class or object from what's clicked.
CTRL SPACE Write code.
button Show hierarchy in Package Explorer.
    (difficult to explain stuff...)
CTRL SPACE See stuff (IntelliSense™-like).
right-click menu Option to refactor source.
ALT right-(or left) arrow Course back and forth again from CTRL-clicks. The equivalente of CTRL-t on steroids in vi with ctags.

See more complete and better stuff like this in my friend Scott's Eclipse Keys, in particular, consult the "Navigate keys" list.


Comparing code

To compare your code with what you got out from the repository or what has been committed since, right-click on the source file name in the Package Explorer, click on Compare With, then choose one of Base Revision, shows what changes you have made or Latest from Repository, shows how different from latest check-in which may have happened after you began modifying code.

There are still other options there.

Someone else just committed changes to code since you performed your last commit. How to see those? Right-click on the file, choose Team and then Show History. Go to the History window that should have opened in a pane somewhere in the workbench. Click on the latest version (at the top of the list) and control-click on the version you last worked on. Then, right-click on one of the selected versions and choose Compare. This gives you the same side-by-side comparison as the first method noted in this section.

Any two versions may be compared in this manner; just control-click the two that interest you.


Eclipse: current working directory

When you run a stand-alone Java program, its current working directory is simply where it was launched from. That's expected. However, what about running a class in Eclipse when right-clicking and choosing Run As->Java application? The current working directory is <workspace/project>. You can prove it to yourself using this code fragment:

	String  cwd = System.getProperty(  "user.dir" );
	System.out.println( "Current working directory: " + cwd );

Upgrading Eclipse spelling dictionary

I can only endure seeing a misspelling so long before I want to tell a spell-checker to stop bothering me with it. Red-underlined variable names don't bother me in comments (au contraire, in fact), but perfectly good words like my own name, downloaded, idempotent, credentials and programmatically, to mention but a few, are really annoying to see comment after comment, file after file.

I'm running Europa (3.3.2). I followed the procedure here. As I had no user dictionary to begin with, I had to create one as described here too.

  1. Opened a shell to my Eclipse installation directory, /home/russ/dev/eclipse-europa
  2. Typed touch user-dictionary
  3. Edited Eclipse Preferences:
    - Window->Preferences...->General->Editors->Text Editors->Spelling
    - Browse to (empty) user-dictionary (created in step 2)
  4. Choose Apply in preferences dialog
To add a word to the user dictionary, I:
  1. Click on the word (e.g.: idempotent) and type CTRL-1
  2. Click on Add 'idempotent' to dictionary

To stop seeing the word underlined in the editor in other files, you must close the file and reopen it.

To remove a term mistakenly added, use Vi[m] to edit user-dictionary and delete the word (and its line).


Default @author for Javadoc

This comes out as the name of the (Linux) user; in my case, the rather informal "russ". To change this, create a Launcher shortcut and type the Launcher -> Command as

	/home/russ/dev/eclipse/eclipse -Duser.name="Russell Bateman"

Note: user.name is a Java property.

Alternative

It's also possible to change Eclipse workspace preferences to provide this.

  1. Go to Window -> Preferences.
  2. Click Java -> Code Style -> Code Templates.
  3. Expand Comments, click Files.
  4. Click the Edit button.
  5. Recast the Java file-level template to contain "@author Russell Bateman".
    (Maybe add it on a new line in order to retain the general utility of the template.)

In this sense, it's not really "fixing" the value for Javadoc @author, but it achieves the same effect.


Invisible code from JARs

Sometimes control-clicking in the editor or single-stepping down through code, code for which the source is unknown to Eclipse is encountered. An edit window comes up with...

	Class File Editor

	Source not found
	_____________________________________________________________________________
	The jar file XxxxxYyyyy.jar has no source attachment.
	You can attach the source by clicking Attach Source below:

	[Button: Attach Source]

To remedy this, click the Attach Source button to get the Source Attachment Configuration dialog. There, you click on one of three buttons to attach the source.

However, you are not really attaching source code (by .java extension), but looking for code associated with the JAR in question.

Source code and JARs

Some JARs come with source code and many do not. You have to pay attention to get the source code to, say, the Apache HTTP client code, otherwise you end up with only the binary JAR you need to link with. This is not usually a problem because you can consider that the supplier has done his job perfectly and if there's an error or bug, it's your own and usually you can determine the defugalty by your own means without that third-party source code.

(This foregoing discussion is incomplete because I'm not elaborating on where or how to get the source code to third-party JARs even though I've done it before. Maybe another time when I have to do it again.)

When adding JARs to the build path via right-clicking on a project, choosing Build Path->Configure Build Path..., and then clicking on Libraries, you can see, if you click to open a listed xxx.jar, Source attachment:. Clicking, you'll see you can Edit... the path: you fall into the same sequence as described for the Editor above.

Javadoc and JARs

This is a similar discussion as the preceding one for source attachments in Build Path. Edit the path to Javadoc location:. Instead of navigating to the project, you'll be looking for an index.html in the distribution. Choose its parent directory.


JARs in Eclipse

Making new jars and supplying to other projects...

In a mixed environment of one workspace with multiple, interdependent projects, the JAR of one project must be ported to the web/WEB-INF/lib of another. This is usually done by an ant script, but as I'm working in Linux and have slightly different path assumptions, the existing scripts won't do it for me.

How has this been working? It has worked because I have not so far modified shared code (code outside RetainServer in fact) and when such code is modified, it eventually finds its way into the repository and my updating gets it from there.

How to do this...

  1. Do Window->Show View...->ant
  2. Click on the Add Buildfiles icon
  3. Find the shared project needing rebuild (SharedJava for example).
  4. Open the triangle and click on ant.xml.
  5. Click OK to add it: something should show up in the Ant Pane.
  6. Open MNShared.

    These are all little ant scripts to do precious things like clean up, copy the trunk, etc. including make a jar. Double-clicking on any script runs the script. (The clean script is a good one to run.)

    Watch the console window to see what this does when you run a script.

    If you make a new JAR, it will put it in a (usually) harmless place. You can copy it from there on the needed path (/home/russ/dev/svn/source-code/web/WEB-INF/lib).


What to do when Eclipse gets icky...

When suddenly everything is full of red stop signs and the whole damn compilation state seems to come crashing down, there is a sequence of panic instructions. Before pointing a small, handheld firearm at your temple, try the following—maybe in this order:

  1. Bounce Eclipse.
  2. Refresh each individual project (right-click on project, choose Refresh).
  3. Update (right-click on project, choose Team->Update).
  4. Clean and rebuild—probably happening automatically, but if not (click the Project menu, choose Clean..., then Clean all projects, then click OK).
  5. Close a project. If you have more than one project open, try closing several (to reduce the number of errors distracting you) and then concentrate on figuring out where the errors come from. This should be done intelligently; if projects interdepend rather than operate off each other via ant-built JARs or something, then narrow it down to the most fundamental and least dependent project, of course. To close a project, right-click on the project and choose Close Project.

Adding a second JRE...

It's sometimes useful to work in multiple JREs (i.e.: at different levels of Java) in complex development. For instance, a set of projects that need to continue to use Java 1.4 in addition to using the latest.

To add a second JRE to the Eclipse environment

Pull down menu Window, choose Preferences.... Expand Java, then click on Installed JREs. Use the Add button to add a new one. In that dialog, Browse to the new JRE and select it to add it to the list. Don't click in the checkbox to its left if you don't want it to become the default JRE.

To specify the new JRE for a project

Right-click on the project, choose Build PathsConfigure Build Path... and click on the Libraries tab. Then remove the existing JRE (that you don't want anymore) and click Add Library.... Click on JRE System Library, then on the Next button. Click on the Alernate JRE radio button and then the pop-up menu. Choose jdk1.6.0_12 (for example). Click on Finish.


Fixing a bad library problem...

Imagine you've just done an svn update, but the build is broken. Someone changed from using one third-party library version (in other words, a library not beloning to or build as a project) to a later one, but Eclipse says in the Problem pane that it's still looking for the older one. Everywhere else, (Build Path->Configure Build Path->Libraries->Web App Libraries), it says the new version of the library. In the project gating this third-party library in (so each project doesn't do it separately), it says the new version. In the file system, what came down from svn says the later version.

Eclipse may have a bug here. What may fix it is to remove the Web App Library and readd it from the supplying project.

I observe that every time one of the other team members changes a JAR on the path RetainServer/web/WEB-INF/lib, this is the result on Linux and not on Eclipse running under Windows. The solution is always to remove Web App Libraries and use the Add Library wizard to add it all over again.

Of course, never add any JAR files by hand when you're trying to get them from sibling projects in Eclipse. There's no end to trouble there.


Fixing a bad library problem (2)...

Imagine you've just done an svn update, but the build is broken. Someone replaced a third-party library with another, but Eclipse says in the Problem view that it's still looking for the older name.

The problem is that Eclipse will not tell you why it is requiring a library that no longer exists anywhere. The challenge is to find its record of that library and expunge it.

Go to the projects reported in Problems as missing the required library (under the old name), right-click and choose Build Paths, then Libraries tab and search for the JAR by its old name. If you find it, simply click Remove.

That failing, the problem lies in the "furnishing" project (often RetainServer in my case).

Second, it's a problem that Eclipse doesn't yet know of the new library, which must exist. The first thing to expect is failure to commit on the part of your colleague who renamed it. Ensure this is the case by updating then checking the svn filesystem area.

Ultimately, it may be the old Refresh versus relaunch Eclipse thing. After failing to clear the problem with one of the two steps, try the other.


Fixing a bad library problem (3)...

Don't forget that if you're consuming a collective library from one project in (one or more) others, you may have built that library wrong. Invoke the ant script for the supplying project to clean, compile and copy the JAR to the other projects. Then, commit the JAR in those projects requiring it.

This can happen easily if you're working in the supplying project and do the ant build with your new stuff without updating and getting what everyone else has done new in that project since last update. You're pushing a new, incomplete or inaccurate JAR out to the other projects, even after update, and then trying to build.

To avoid this trap, never commit JARs until you have done a full update and build. If you're trying things out locally, don't update any other projects (risking getting new stuff) until you've finished experimenting.

Granted, this explanation isn't as clear as it could be.


Fixing a bad library problem (4)...

If another on your project has added a new JAR to be consumed, it must be added by hand in Eclipse. I don't understand why there would not be some way of communicating to Eclipse that this has happened, but developers cooperating on a project in Eclipse must still knit their projects together on an on-going basis with no help from the IDE.

Open the Build Path dialog, click on Libraries, then Add JARS.... Find the new JAR and add it.


"The project was not built..."

...since its build path is incomplete. Cannot find the class file for java.lang.Enum.

This little infuriating gem is caused by not having the right run-time. Just because you have Java 5 in your Java Compiler setting doesn't mean that Build Paths->Libraries will follow.

Remove the JRE System Library [j2sdk1.4.2_18] or similar Java Runtime Environment library and add the correct one to match your Java 5 set-up: Add Library...->JRE System Library->Next->Alternate JRE:-> then choose, for example, jdk1.5.0_17 and Finish.

Other, specific errors about Enums will go away when you do this.


svn troubles...

If you experience svn trouble, click here.


Build tasks in Eclipse

It's possible to tell Eclipse to perform certain tasks each time it rebuilds a project. For example, you might want to create an ant script.

To set up an ant script to fire when Eclipse builds...

  1. Right-click on the project and choose Properties.
  2. Click on Builders.
  3. Click on New....
  4. Choose Ant Builder (if an ant script is what you created.
  5. Give the builder a name, choose the path to the build file (i.e.: the ant script), the base directory*, and arguments.

* base directory refers to the project attribute in the ant script, e.g.:

	<project name="Retain" basedir="." default="main">

Obviously, if the task takes a long time, you have to rethink whether this is really what you want to do or not.


Eclipse project folder set-up

Sun preconizes a particular blueprint when it comes to setting up web application projects, which is to say the names and hierarchical relationships of directories and files in the application. Specifically, the use of web instead of WebContent (the Eclipse default) is advised. See Guidelines, Patterns, and Code for End-to-End Java Applications.


Good Eclipse add-ons...

There are some indispensable add-ons for Eclipse. There are two vi emulators for use with the editor and a white-space remover.


The Eclipse icon nightmare...

At first glance, Eclipse icons appear mysterious and gaudy—over-decorated, for example . Decoration is a clever idea, but it's sometimes a little annoying. Here are some comments to explain them. You can turn decoration on and off at Window->Preferences->General->Appearance->Decorators and you can force decoration to use text instead of icons.

Yellow box at lower right

(Actually, it's a cylinder.) Means the file is under version control.

Question mark superimposed on icon

Means version control is active in the project, but the file itself is not under version control nor is it flagged as "ignored" (i.e.: in .gitignore, .cvsignore or has an svn ignore property).

Black box with asterisk at lower right

Means the file or, if a directory, a file it dominates, hasn't been committed to source-code control. Unfortunately, you will see this even if everything that's supposed to be committed is committed. This is because when you add files and otherwise modify the directories, they themselves are noted as needing to be committed when that may be the last thing you want to do.

Red box at lower left

Means there is a compilation or validation error in the file or, if a directory, a file it dominates. If this is on a JAR or other file you wouldn't think should be in an error state, it might mean that the actual file it represents in the filesystem underneath has gone missing.

Yellow triangle at upper left

Means there is a compilation or validation warning in the file or, if a directory, a file it dominates.

Further links

Eclipse icons


Bouncing an Eclipse project

If you want to delete a project and start over, you must clean up the file system or trying to recreate the project by the same name will get you an error to the effect that a project of that name already exists.

The filesystem will be cleaned up if you delete the project sources too, but that would not normally be the case. Instead, you keep the sources (presumably on a path separate from the workspace, maybe a filesystem created by svn, and you must clean up a number of configuration files from the root of the project sources.

	# rm .project
	# rm .classpath
	# rm -rf .settings

Seeing Eclipse editor annotations on Linux

I run openSuSE 10.3 using GNOME, using two Dell 24" wide-aspect monitors. Whatever the reason, backgrounds such as this page uses are washed out and scarcely visible. I've tried adjusting the contrast and brightness settings, but nothing seems to work. Otherwise, I love the environment and my monitors.

What this affects mostly for me is my ability to see editor annotations, that is, little rectangles in the margin at the right of the Editor Panel. While the error annoations (meaning, "error at this line—click here") are always perfectly visible, and the warning annotations are visible enough, others aren't and some of them are actually very useful.

To change the color associated with a particular annotation, go to Window->Preferences->General->Editors->Text Editors->Annotations. Select the invisible annotation, Occurrences for instance, and then click the Color: control to change it to something visible.

The right margin is formally called the Overview ruler. It's the left margin that is referred to as the Vertical ruler.


Advice on Eclipse build paths

Here's some advice on build paths off a forum.

There are three different classpaths to be aware of when you are running Eclipse. First, Eclipse itself is a Java application, so it has a classpath; mostly you don't care about this one, except to make sure you're not confusing it with the others. Second, there is the classpath (referred to as the Java Build Path) that is in effect when you compile your code. This affects what classes are visible—for instance, if your code contains a reference to a class named Foo, then there must be a project or a jar file containing Fooon your project's build path. Third, there is the classpath that is in effect when you run your application; this may contain additional or different jars than the build path, because (for instance) your app might compile against an interface (IFoo) but reflectively load an implementation class (Foo) at runtime.

Often the runtime classpath is the same as the build path, but ultimately it's controlled by the launch configuration. Sometimes the app itself (or code in jars it references) may extend the classpath by loading libraries from specific URLs or disk locations; that's why I've been emphasizing the need to make sure where your app is running from, in case it is internally trying to dynamically load a library with a relative pathname.

You probably want to Run As... Java Application. Once you've done this once, there will be a launch configuration; if you go to the dialog, you'll notice there are a bunch of tabs. I'd suggest paying attention to the contents of each of those tabs; in particular, the field that lets you set the directory that the application will be launched in.


Fixing Eclipse in Ubuntu 9.10 Karmic Koala

Galileo won't run on this platform because of some bugs. Read how to fix that.


Adding software to Eclipse

This example is from Galileo. The process has gotten much better over the years. Once, you could usually expect it to fail and you'd have to install new software components by hand dropping myriad JARs into the Eclipse plugins subdirectory (now named dropins). I have done many of these in recent times (read: Galileo) and not had anything thing (or repository site) go missing. If that weren't enough, I "dropped in" AnyEdit tools by hand (something I've grown used to) only to find it supported by the update manager anyway.

1. Choose Help -> Install New Software -> Work with: -> All Available Sites.

2. Wait for list to populate; this can take a while.

3. Select something such as the Eclipse Data Tools Platform.

4. Click Next. Eclipse calculates requirements and dependencies. There could be a lot of these.

5. Click Finish. Wait patiently a long time. Usually, bouncing Eclipse will be required afterward.


SQL scripts in Eclipse

(Much more research to do on this.) It's possible to create an SQL script and dump it under WebContent for use in database maintenance, for example, as the content kick-off.

	CREATE TABLE Customers (
	   Cust_ID INT,
	   Name CHAR(30),
	   Phone_Number CHAR(15),
	   Street_Address CHAR(30),
	   City CHAR(30),
	   State CHAR(15)
	);

	INSERT INTO Customers VALUES (1, 'William Dupont', '(652)488-9931',
	   '801 Oak Street', 'Eugene', 'Nebraska');

	INSERT INTO Customers VALUES (2, 'Anna Keeney', '(716)834-8772',
 	  '86 East Amherst Street', 'Buffalo', 'New York');

	.
	.
	.

	INSERT INTO Customers VALUES (20, 'Horace Celestin', '(914)843-6553',
	   '99423 Spruce Street', 'Ann Arbor', 'Michigan');

Doing this will cause Eclipse to create a control window across the top by which you can point its effect to any database.

To execute the script, right-click on it and choose Execute SQL Files.


Eclipse and LD_LIBRARY_PATH and java.library.path

When the application you're running (or debugging) from Eclipse needs to load shared-object libraries (on Linux, duh), you need LD-LIBRARY_PATH set up, but how? The trick is simply to set it up before launching Eclipse, which you must do from the command line:

	russ@taliesin:~/dev/run> export LD_LIBRARY_PATH=`pwd`
	russ@taliesin:~/dev/run> ../../eclipse/eclipse

If your application (or its dependents) are clever enough to say right out that they can't find a native shared-object library (JNI or JNI-dependent, etc.) because it's not on the java.library.path, you do not want to modify what Eclipse thinks this path is.

Instead, determine which JAR contains the code that wants to load the JAR and fix it in Build Path. Do this:

  1. Right-click on the project in Eclipse.
  2. Choose Build Path, then Configure Build Path, then click the Libraries tab.
  3. Find the library containing the JAR and expand it (or simply the JAR if it was added as a mere JAR).
  4. Expand the JAR by cliking the little triangle to its left.
  5. Click on Native library location: and then Edit.
  6. Fill in the path by hand or by browsing to the directory containing the native shared-object in question.
  7. Click OK, then OK.

Renaming despite project name in use

Once you've deleted an old project, possibly through refactoring, it may persist in the workspace and Eclipse will not let you reuse it. You'll find a record of this on the path:

	.metadata\.plugins\org.eclipse.ltk.core.refactoring\.refactorings

You may simply delete the project you'll find there, a rather deep directory structure, and then use the name again. Be sure this is what you want.


"IntelliSense," ...

...a Visual Studio term, is "Content Assist" in Eclipse parlance.


No grammar constraints (in XML)

Here's how to get rid of those (harmless) "No grammar constraints (DTD or XML schema)" warnings in Eclipse:

  1. Pull down menu Window -> Preferences, go to XML -> XML Files -> Validation.
  2. Change the setting of Indicate when no grammar is specified from Warning to Ignore.
  3. Revalidate your project.

Uninstall plug-ins from Eclipse
  1. In the Eclipse Help menu, click About Eclipse.
  2. Click on Installations Detail.
  3. In Installed Software tab, click the plug-in to remove.
  4. Click the Uninstall... button.

Reconfiguring panes (views) in Eclipse

It's fairly easy to reconfigure the Eclipse workbench, relocate views, etc. just by clicking on a tab, dragging and dropping it somewhere else. Dragging a tab to an edge of an existing pane (view) will create a new pane on the workbench. Experimentation will soon have you fixed up.

However, there is some geometry that's not so obvious and it involves creating new pane at edges where there was none. Considerable experimentation is sometimes needed. For example, I wanted to know how to transform this arrangement of views in my Debug perspective:

+----------------------------------+-----------------+
| 1                                | 4               |
+----------------------------------+-----------------+
| 2                                | 5               |
+----------------------------------+-----------------+
| 3                                                  |
+----------------------------------------------------+

...to this:

+----------------------------------+-----------------+
| 1                                | 4, 5            |
+----------------------------------+                 |
| 2                                |                 |
+----------------------------------+-----------------+
| 3                                                  |
+----------------------------------------------------+

(For my terminology here, I'm going to call panes where the (numbered) views are located. E.g.: above, views 4 and 5 occupy the same pane. The UI control for grabbing and dragging a view is the tab on which its name sits.)

The steps were easy enough, but they must be done in just the right order:

  1. Grab/drag view 5 all the way to the right until you get the indicator icon of an arrow pointing left. This will place 5 in its own pane on the right end of the full length of the workbench, creating:
    +----------------------------------+------------+----+
    | 1                                | 4          | 5  |
    +----------------------------------+------------+    |
    | 2                                             |    |
    +-----------------------------------------------+    |
    | 3                                             |    |
    +-----------------------------------------------+----+
    
  2. Grab/drag view 3 down until the indicator icon points up. This makes view 3 a full-width pane below views 2 and 5.
    +----------------------------------+------------+----+
    | 1                                | 4          | 5  |
    +----------------------------------+------------+    |
    | 2                                             |    |
    +-----------------------------------------------+----+
    | 3                                                  |
    +----------------------------------------------------+
    
  3. Grab/drag view 4 on top of (into the same pane as) view 5 and resize the 4, 5 pane. This produces the result above (the second illustration).

In my Debug perspective, these panes were:

1 Debug (stack trace)
2 Source code view
3 JUnit
4 Variables
5 Outline

My ultimate Debug perspective layout is as below since I like lots of room for source code and variables. I only dragged my JUnit view up into the same pane as Variables and Outline. My monitor dimensions are 1920×1080.

+----------------------------------+-----------------+
| 1                                | 4, 5, 3         |
+----------------------------------+                 |
| 2                                |                 |
|                                  |                 |
|                                  |                 |
+----------------------------------+-----------------+

How to forget defunct workspaces in Eclipse

If you've renamed an Eclipse workspace or otherwise no longer wish to be bothered seeing it as a suggestion when you switch workspaces, do the following:

  1. Under the Eclipse home subdirectory (where it's installed in your filesystem), find the following file:

    (eclipse-home)/configuration/.settings/org.eclipse.ui.ide.prefs
  2.  
  3. Edit the file, and look for the line that starts with: "RECENT_WORKSPACES".
  4.  
  5. The workspaces are separated by newlines (Linux, at least); delete whichever workspace you no longer wish to appear in the drop-down menu.
     
  6. Save the file.

The new Eclipse command line

Beginning in Helios, there's a great deal added to the Eclipse command line. See what here.


Eclipse workbench on Ubuntu

In recent Ubuntu releases, the default desktop theme has been "Ambiance" (unless I'm mistaken). I don't mind this at all, however, when you're working in the Eclipse workbench, it makes a number of things miserable. For example, Javadoc isn't particularly readable nor are error strings when you hover over the error. These are all a dark back ground with black text. (What's in a yellow background below is dark in the default theme.)

I stumbled upon the "ClearLooks" theme which works much better. I admit that the white background is a little stark and I may experiment with modifying that (click the Customize button), but certainly things are better with it than with the default. To get this, do System -> Preferences -> Appearance and choose "ClearLooks".


Console length

In configuring Eclipse, you should be aware of the issue of the number of lines your console view will remember. Encountering errors while running may create so much output in the console that the culprit's information has been discarded even if you attempt to pin the console or stop its scrolling.

This is easily fixed at the expense of memory. You have two choices. Either guess how much memory you'll need and specify that (the default is 80K characters) or count on clearing the console by hand as often as you like (before each run) and disable limiting the console (by unchecking the preference). See the illustration at the right, here. Reach this preference via Window -> Preferences -> Run/Debug -> Console.

If you must eliminate the limits on console length, you may find yourself adding memory to Eclipse in order to accommodate (and/or clearing the console by hand). Do this thus in eclipse.ini:

	-XmxNNNm

...where NNN is the new maximum size in megabytes you wish to limit Eclipse's ordinary heap to. See also http://wiki.eclipse.org/Eclipse.ini.


Eclipse Project Explorer view of Dynamic Web Projects

You've created a new JSF/Facelets project, but you don't use JavaScript or JAX-WS, etc. and wonder why all that "crap" shows up in your Project Explorer view. You can rid yourself of that easily via this view's context menu—the little triangle on its toolbar (red arrow). By unchecking JAX-WS Web Services Elements, JavaScript Elements and Web Resources in the dialog below (blue checks), I can eliminate the corresponding needless clutter from the hierarchy in this view (blue strike-outs).


Conveniently consuming the Eclipse Java formatter from the command line

Yes! It is possible!. I found that this just used Eclipse's own format and not mine unless the project was carefully set up. The project itself (and not just the workspace properties) must be enabled for this. Also, you cannot use your saved .xml file containing your formatting properties directly as the argument to the -config option.

While you have to use settings down under an existing Eclipse project, the Java file you're formatting doesn't need to have anything to do with that project (or any other).

  1. Choose the project whose formatting properties you intend to make use of.
  2. Right-click on the project and choose Properties.
  3. Expand the triangle next to Java Code Style.
  4. Click Formatter.
  5. Click Enable project specific settings.
  6. Import your profile (if you like) and make it the Active profile.
  7. Click OK.
  8. Exit Eclipse (to ensure the settings are saved).
  9. Fill in $WORKSPACE and $PROJECT in this script.
  10. Execute this script with the file you wish to format as argument, or the subdirectory whose files you wish to format.
	#!/bin/sh
	WORKSPACE=/home/russ/blackpearl/workspace
	PROJECT=TryStuff
	SETTINGS=$WORKSPACE/$PROJECT/.settings

	/home/russ/dev/eclipse/eclipse -nosplash \
		-application org.eclipse.jdt.core.JavaCodeFormatter -verbose \
		-config $SETTINGS/org.eclipse.jdt.core.prefs \
		$*

Internal web application deployment

Eclipse deploys the web application you're developing internally for testing on the path below.

<workspace>/.metadata/.plugins/org.eclipse.wst.server.core contains tmp0, tmp1, etc. tmp0 as the first server you create, for example, using Apache Tomcat v6.x while tmp1 is the second, for example Apache Tomcat v7.0.

When you remove an application from a server (right-click server and choose Add and Remove...), then clean it (right-click server and choose Clean), Eclipse cleans up, mostly by deleting everything under workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0.

Of course, when you're ready to deploy your application formally to Tomcat on a server, you must export it as a WAR file.


Language of workbench

Start Eclipse in US English (or any other language) with the following option on the command line:

	-nl en_US

EclEmma: code coverage for Eclipse

Get this via Help -> Install New Software from EclEmma. The update site path is http://update.eclemma.org/. If you care, call it EclEmma Java Code Coverage.


Installing eclim

This is not to be confused with Eclemma, above.

eclim is a project that integrates Vim with Eclipse Indigo. You could get an error trying to install it if, like me, you are using the default Java that comes with Ubuntu. You'll see this:

	installer.xml:
	    ...
	34  <target name="installer">
	35    <formic:installer property="install.complete"
	36        resources="resources.install" steps="resources.steps">
	    ...

	russ@russ-elite-book:~/dev/indigo> java \
	                                 -Dhttp.proxyHost=web-proxy.austin.hp.com \
	                                 -Dhttp.proxyPort=8080 -jar eclim_1.7.1.jar
	Buildfile: installer.xml
	2011-08-17 08:39:02,852 INFO  [org.formic.Installer] Running Installer.
	2011-08-17 08:39:02,918 ERROR [ANT]
	jar:file:/home/russ/dev/indigo/eclim_1.7.1.jar!/installer.xml:36: java.lang.ExceptionInInitializerError
	    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:116)
	    at org.apache.tools.ant.Task.perform(Task.java:348)
	    at org.apache.tools.ant.Target.execute(Target.java:390)
	    at org.apache.tools.ant.Target.performTasks(Target.java:411)
	    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1397)
	    at org.apache.tools.ant.Project.executeTarget(Project.java:1366)
	    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
	    at org.apache.tools.ant.Project.executeTargets(Project.java:1249)
	    at org.formic.ant.Main.runBuild(Main.java:232)
	    at org.formic.ant.Main.startAnt(Main.java:81)
	    at org.formic.ant.Main.main(Main.java:63)
	    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	    at java.lang.reflect.Method.invoke(Method.java:616)
	    at com.simontuffs.onejar.Boot.run(Boot.java:306)
	    at com.simontuffs.onejar.Boot.main(Boot.java:159)
	Caused by: java.lang.ExceptionInInitializerError
	    at com.jgoodies.looks.plastic.PlasticLookAndFeel.<clinit>(PlasticLookAndFeel.java:135)
	    at org.formic.Installer.setLookAndFeel(Installer.java:293)
	    at org.formic.Installer.run(Installer.java:109)
	    at org.formic.ant.InstallerTask.execute(InstallerTask.java:89)
	    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
	    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	    at java.lang.reflect.Method.invoke(Method.java:616)
	    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
	    ... 16 more
	Caused by: java.awt.HeadlessException
	    at sun.awt.HeadlessToolkit.getScreenResolution(HeadlessToolkit.java:221)
	    at com.jgoodies.looks.LookUtils.isLowResolution(LookUtils.java:480)
	    at com.jgoodies.looks.LookUtils.<clinit>(LookUtils.java:249)
	    ... 26 more
	2011-08-17 08:39:02,930 DEBUG [ANT]
	BUILD SUCCESSFUL
	Total time: 0 seconds
	java.lang.ExceptionInInitializerError
	2011-08-17 08:39:02,943 WARN  [ANT]      [echo] Installation canceled.
	russ@russ-elite-book:~/dev/indigo>  java -version
	java version "1.6.0_20"
	OpenJDK Runtime Environment (IcedTea6 1.9.9) (6b20-1.9.9-0ubuntu1~10.10.2)
	OpenJDK 64-Bit Server VM (build 19.0-b09, mixed mode)

Instead, use a real, Sun Java.

	russ@russ-elite-book:~/dev/indigo> ../jdk1.6.0_24/bin/java \
	                                 -Dhttp.proxyHost=web-proxy.austin.hp.com \
	                                 -Dhttp.proxyPort=8080 -jar eclim_1.7.1.jar

	Buildfile: installer.xml
	2011-08-17 09:06:45,403 INFO  [org.formic.Installer] Running Installer.
	...

Java formatting

To control how your Java code is formatted, go to Window -> Preferences -> Java -> Code Style -> Formatter. There, you'll probably see (because you've likely not changed it) that the code formatter you're using is the default shipped with Eclipse.

If you click the Edit button, you'll be able to change a lot about how things are done. For instance, by working with the braces, you can change from using Kernel Normal Form (KNF) to, say, Allman indentation (as used by ANSI and ISO).

And you can dramatically affect the way other things are physically formatted not only as you type in code, but also as a result of selecting code and doing Source -> Format in the editor.

You can save your changes under a different name by giving your new format a name and clicking on the Export... button. This saves your changes in an XML file.

Conversely, when you create a new Eclipse workspace, you can go to Window -> Preferences -> Java -> Code Style -> Formatter and click the Import... button, navigate to that file you saved and thereby substitute it for Eclipse's default format.


Eclipse artifacts and portability

How to share projects between work and home, colleagues on the team, etc?

Eclipse workspaces are not designed to be portable. Eclipse projects, on the other hand, are so designed. The following are solutions:

  1. Publish projects from a source code-control repository (Subversion, Git, etc.) from which you can get the code and back into which you can commit changes. See Subversion, TortoiseSVN and/or Git. (By far, the best is Git.)
  2.  
  3. As long as your project is in a working state in your Eclipse workspace (even if it's closed, that's okay), you can pick it up and carry it as-is somewhere else.

    Import by dropping it somewhere in your new filesystem, launch Eclipse on the workspace you intend to use, ...

    1. choose File -> Import... -> General -> Existing Projects into Workspace -> Next
    2. Browse to the root of the project,
    3. select it, click OK, then,
    4. if it's a valid Eclipse project, you should see it checked in a list of projects in this wizard.
    5. Click Finish and you're there.

    It's useful to understand the meta files and subdirectories that make an Eclipse project as opposed to a garden-variety Java project. The metafiles (directories) for an Eclipse project are:

    .project (the one required for the steps above to work)
    .classpath
    .settings (a subdirectory)

    Besides the list above, more details can be had in this discussion: Git on Eclipse (whether or not you choose to use Git).

  4. A third option is to set up your workspace on an external filesystem such as a flash drive or external hard drive you carry around, leaving it there permanently. You can open it from Eclipse on any computer into which the drive is plugged, but, on Windows at least, it must be mounted under the same drive letter on each host.

Eclipse Web Tools Project: the Context Root

If the context root of your web service, application, etc. isn't what you want, you can change it.

By default, Eclipse names it after your project. Thus, in the URI to be typed into the browser, you're using the project name. Maybe your project name stinks, like "MyRestBasedService" or something. So, when you type in the URL, it's http://www.my-acme.com:8080/MyRestBasedService/rest/ping.

Ugh.

So, instead, you right-click the project (in Project Explorer, choose Properties, then Web Project Settings, enter something else (cool) for Context root:, like "zippity-doo-dah".

Then, your URI becomes: http://www.my-acme.com:8080/zippity-doo-dah/rest/ping.

Where does the coolness happen?

As frequently happens, Eclipse performs the magic, but leaves you clueless as to where it happens and you also wonder if it will continue to happen when you generate the WAR file.

In this case, the magic appears to happen in a file on the path .metadata/.plugins/org.eclipse.wst.server.core/publish/publish.dat.

But!!!

But, this file isn't present in the WAR file! I'm still trying to figure out how this is supposed to happen. It appears that you simply have to export the WAR file under the desired name (instead of the project name). Also, you cannot rig META-INF/context.xml with <Context path="desired-name" ... > since this attribute would be ignored without also being specified in server.xml, a file you should never modify nor count on modifying.

Recap

In summary, Eclipse's web project settings work-around isn't too useful except in development to avoid subjecting yourself to your long and ugly project name. Later, you must also carefully avoid the default presented when you export the WAR file (because the default is the long and ugly project name).

http://www.xinotes.org/notes/note/690/ was one of the clearest notes I found on this topic.


build.xml in Eclipse

From an existing Eclipse project, you can ask Eclipse to generate a suitable build.xml (or its contents and ask it to name it something else). Then, from that ant script, Eclipse will generate the project all over.

This is interesting because you might collaborate on a project with others, committing your work to Subversion, CVS, Git, etc. It's pretty straightforward. In order to make this work, here's what I had to do:

  1. Generate the build.xml file by right-clicking on project, choosing Export -> General -> Ant Buildfiles -> Next -> select project by name -> name build.xml -> Finish
  2. Copy off the whole project somewhere (into Subversion, etc.). This should not include product subdirectories such as build or bin, etc. Also, you don't need .classpath, .project or .settings, although missing .settings might be why a Dynamic Web Project done this way will degenerate into a simple Java Project.

Now, pretend you're getting this new project...

  1. Copy the project to the workspace as-is. (Note: this is not how you would do it if you were creating a project directly from existing sources rather than from build.xml—that's another topic.)
  2. Launch Eclipse and open the workspace where the project was copied (it will not show up in Eclipse yet).
  3. Do File -> New -> Project... -> Java Project from Existing Ant Buildfile.
  4. This should create and open the project.
  5. Right-click the project (in Project or Package Explorer) and choose Build Path -> Configure Build Path... -> Libraries.
  6. Remove JRE_LIB (obsolete—not sure why Eclipse does this, then tells you it's obsolete), click Add Library and add the JRE System Library set up for your workspace.
  7. You'll do similarly for JUnit if you're using that.
  8. This should make the project usable. You can open build.xml in the Ant view and/or simply allow Eclipse to build your project.

Not covered here...

How to establish a proper build.xml doing all the "real" things you'd set it up to do while accomplishing what's recounted above. The generated build.xml, which you may have named something else, tells you not to modify it since you could end up regenerating it again.

Part of the answer is to maintain a separate build file with additional stuff it in; you could call it from build.xml via <antcall target="myotherone.xml" >.

Another idea might be simply to maintain separate build files, trying to cut down on duplication of content. The top of the generated one contains the real contribution in the form of documenting what third-party JARs you're using. That's really why you'd regenerate, especially if you weren't too ant-savvy and wanted Eclipse to do this for you. But then, you'd likely not have addition stuff anyway, so there wouldn't be a conflict.


A Dynamic Web Project in Eclipse sans project files

This is about how you might share Eclipse Dynamic Web Projects in Eclipse with teammates via a source-code control/version system such as CVS, Subversion, Git, etc. Imagine you're working on a project and a new guy starts on the team. He needs to get the project set up in Eclipse.

Project files in Eclipse include

The problem with keeping these under source-code control is that they can have user-specific information, including full filesystem paths on the development host, in particular, .classpath.

The method described in the next section up on this page, which overcomes many of the problems, fails in that it will never create a Dynamic Web Project—only a simple Java Project in Eclipse.

This is also discussed at some length in an article entitled, Git-Eclipse Peculiarities. Read the rest of this note, however, before drawing any conclusions.

One approach

You can keep .project under a different name, .project.sample, and keep .classpath and .settings. This is what's described in the article on Git and Eclipse referred to above. It allows you to clone (check out) a project nearly ready to go. There is very little to do to get it running in Eclipse.

The disadvantage to this is that a colleague may associate Javadoc or source code with one of the JARs in the project. This impacts .classpath by recording a full filesystem path in it. Any version control system will ask to commit this change. Other colleagues end up with useless, foreign path references in their project.

Another approach

A different approach is to establish the standard procedure of creating the new project as File -> New -> Other -> Web -> Dynamic Web Project. When the wizard comes up, type in the name, but change the Project location to wherever the project was checked out (updated) from version control.

The result is a partially set-up project. There will be many errors corresponding to missing JARs.

Solve the JAR problem by keeping the JARs in a subdirectory of the project that gets committed each time JARs are added to or replaced in that subdirectory. Creating a new project necessitates using Build Path to include all of the JARs (and establishing them in the Deployment Assembly too).

	▼ project-name
	    ...
	    ▼ lib
	        ▼ apache
	            commons-collection-3.1.jar
	            ...
	        ▶ hibernate
	        ...
	    ...

This is tedious, but if you limit the libraries you put in the project to only those that are needed (and required), at least it's not guesswork when it's done.

Something else that makes this a lot less tedious is not insisting on placing JAR files under subdirectory names that describe their origin as my example shows. In Build Path -> Libraries, you can click and shift select the lot all at once if they're just dumped together under the lib subdirectory.

The upshot...

...of all of this is that the second method introduces some tedium into the process, but anyone who associates source code or Javadoc with a JAR for debugging and other purposes isn't inconvenienced (i.e.: the association doesn't disappear) until that JAR changes (newer version, removed as no longer necessary, etc.). Best yet, associating source code or Javadoc will change .classpath, but as this file isn't committed, it doesn't inconvenience anyone else either.


Definitive approach for sharing Eclipse projects

Based on some of the sections on this page, in particular the last two, the following is a how-to.

Creating a project

  1. Create a project of any sort in Eclipse and develop it to the point at which you're ready to share it.
  2.  
  3. Create a clean or cleanall target in build.xml that removes all development (compilation) projects. This means .class files and other intermediate targets that are built as part of the development process, i.e.: not source files, property files, or "irreplaceable" resources such as JARs.
  4.  
  5. Ensure all (third-party) JARs consumed reside under subdirectory lib in the project. Sometimes, web application developers put these under WebContent/WEB-INF/lib. Doing that is a bit of an over-kill and it may confuse your new colleague to have to go find them in a deeper-than-necessary path.
  6.  
  7. Commit the subdirectories and source files described above in your source code/version-control system. Do not commit, in particular, .classpath file, .project file or the .settings subdirectory. In fact, add these to your version-control system's method to ignore them (.cvsignore, .gitignore, etc.).

Consuming a project

  1. Check out, clone or update the project from version control into its own, suitably named subdirectory in the filesystem of your development host. Do not locate this subdirectory in any Eclipse workspace.
  2.  
  3. Launch Eclipse on the appropriate workspace.
  4.  
  5. Create a new Java Project, Dynamic Web Project or other using the usual wizard, but take care to dictate to it (it's about the second thing you do) that the sources are located in another subdirectory. Finish answering questions in the wizard as usual.
  6.  
  7. Once the project is created, right-click its name in the Project/Package Explorer and choose Build Path to add the libraries residing under the lib subdirectory. Add them also to the Deployment Assembly (new name beginning with Helios).

Sharing projects

It's not possible to share workspaces, but you might get away with sharing the same project. Even via Dropbox. Here's how.

  1. Create the project on one computer, get it more or less how you'd like it (i.e.: simple Java Project, Dynamic Web Project, etc. as created by Eclipse). You'll be able to add or delete source code later, but the project should exist enough for Eclipse to recognize it.
  2. Copy the important parts of the project to your dropbox location.
  3. From inside Eclipse, discard the original project including source files (it prompts you to be cautious about this).
  4. Create a new project in the same (or a different) workspace. When the wizard comes up, you can name it what you want, but tell it to get the source files from another location and not to copy them into the workspace. Eclipse will consume the project from dropbox, I think.
  5. Repeat this from your other computer from its Eclipse using, obviously, its own workspace.
  6. The changes you make from one computer will be reflected in the other. You will have to right-click your project and choose Refresh when you change computers.
  7. All third-party libraries (JARs) must be copied to a path inside your project. Otherwise, your .classpath file will acquire full filesystem pathnames which will not hold true on both computers. Another way of causing this problem is to associate Javadoc or source code with any of those third-party JARs (let's say you wanted Javadoc for hibernate3.jar, you're screwed as soon as you do that).

I have not done this; there may be a hole in what I'm telling you or, you may accidentally do something that destroys your ability to do it this way (as suggested by #7).

It's better to use a version-control system for this (and, obviously, there are other benefits too).

Note: I know what Dropbox is and have used it very briefly once. I don't know all the peculiarities of it. So, I may be making unwarranted assumptions on doing this.


Enabling Java assertions...

See Enabling Java assertions.


Start-up dialog workspace names

You've killed a few workspaces, but they keep showing up in Eclipse's workspace start-up dialog (or when you switch workspaces via File -> Switch Workspace) and you want to forget them.

These are kept in a configuration file on the path <eclipse>/configuration/.settings/org.eclipse.ui.ide.prefs, in a variable, RECENT_WORKSPACES.

But there is a right way to maintain these. Go to Window -> Preferences -> General -> Startup and Shutdown -> Workspaces.


Missing listener when Tomcat starts

I'm writing this note because it's just a nasty problem that happens all the time in a fakey development/debugging environment when the slightest thing can go wrong in deployment.

You launch Tomcat in Eclipse to begin testing your web application, but the listener fails to come up. Attempting to hit your server gives you an HTTP Status 404 The requested resource is not available. You squint hard first at your deployment descriptor (web.xml) contents, at your ReST or other wiring, and at your URI: there's nothing wrong with it.

Take a look at what's come out in the Console view, something like:


SEVERE: Error configuring application listener of class
com.acme.web.context.ConfigurationContextListener java.lang.ClassNotFoundException:

com.acme.web.context.ConfigurationContextListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3915)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4467)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
    ...

The solution, in this case, was to refresh everything and do a clean build. However, ...

if the listener comes out of a JAR library you're consuming, this is very common, perhaps more so than having it come out of your own code. It might be coming from Spring, for instance. Take a look at this discussion, done as well as I could do it from mkyong.com.

Consider checking out the effect of using @WebListener.


VPN freeze-up and proxy

When using Eclipse on a box working through a VPN, you might encounter freeze-ups or slowness. Sometimes setting proxy information can fix this by isolating Eclipse from running any background processes through the VPN instead of on the box itself.

  1. Go to Window -> Preferences.
  2. Type "proxy" into the Search box.
  3. Add stuff from /etc/hosts such as shown here:


.classpath

Eclipse's .classpath file lists all the JARs that support your project and performs some other tasks such as supply links to Javadoc for those JARs that you set up if in coding you wish to see more usefully the interfaces therein or, when debugging, sources if you wish to step debug down inside them.

The JARs are thereby considered to be "on your class path" for the purpose of compilation, but as noted above, also for the Eclipse Java editor's use in implementing Content Assist—Eclipse's version of what Visual Studio calls Intellisense and for the debugger's use.

When you are in Build Path -> Configure Build Path -> Libraries (tab) and making changes, Eclipse needs write access to this file.


@formatter:off/on

You're led to think that this can be placed into your Java code as if an annotation, but in fact it's not. You must use it commented out (and it works as long as you have Preferences -> Java -> Code Style -> Formatter -> Edit -> Off/On Tags -> Enable Off/On tags checked.

    /**
     * @formatter:off
     * This method will perform...
     *
     * @param str is the string on which...
     * @return the new string.
     * @formatter:on
     */

...or, in Java code...

    // @formatter:off
    [nothing here will get reformatted by Eclipse...]
    ...

    for( String a Title : DvdCreateTestTitles. titlenames )
    {
        ...
    }

    ...
    [...until beginning here again]
    // @formatter:oon

Eclipse Marketplace

Beginning with Eclipse Indigo, I use Help -> Eclipse Marketplace... to install plug-ins I want. If you're behind a firewall and need a proxy, this might simply not work until you tell Eclipse this is what you're doing. Go to Window -> Preferences -> General -> Network Connections:

Only then can you use this facility.


Solution to adding Eclipse to the Unity task bar

Here's how to get Eclipse with its icon into the Unity task bar.

  1. Download Eclipse first.
  2. Explode to favorite place; you must know the path for the next step.
  3. Create a file, opt-eclipse.desktop, not in the ~/Desktop subdirectory, but in another* with the contents below.
  4. Launch the (Nautilus) file explorer and open the subdirectory where you put the short-cut file.
  5. If the short-cut does not have the proper icon, you may need to
    1. Right-click it and choose Properties.
    2. Click the icon in the properties and navigate to the Eclipse subdirectory to find icon.xpm.
  6. Drag this short-cut into the Unity task bar. You can arrange the order of icons in the Unity task bar by clicking and dragging the icon out of the bar, then back to the bar in the place you want. If you attempt to click and drag up or down within the bar, it will move the whole bar instead.
    [Desktop Entry]
    Type=Application
    Name=Eclipse
    Comment=Eclipse Integrated Development Environment
    Icon=/home/russ/dev/eclipse/indigo/icon.xpm
    Exec=/home/russ/dev/eclipse/indigo/eclipse
    Terminal=false
    Categories=Development;IDE;Java;

* Anything you put into ~/Desktop will show up on the desktop which is probably not what you want. You cannot "add, then delete it" since the short-cut is a permanent configuration Unity uses.


Trouble with ant...

If you add a new ant task, in the Ant view in Eclipse, you may get to see something like this instead of being able to see and execute the ant targets:

    project-name <taskdef class package-name.task-name cannot be found using the classloader \
            AntClassLoader[/home/user-name/path/eclipse/plugins/org.apache.ant_1.8...

(A specific example is adding a findbugs target and seeing:)

    MyApp <taskdef class edu.umd.cd.findbugs.anttask.FindBugsTask cannot be found using the classloader \
            AntClassLoader[/home/russ/dev/eclipse/plugins/org.apache.ant_1.8.2.v20120109...

The solution may be the following:

  1. Windows -> Preferences.
  2. Ant -> Runtime.
  3. Ant Home Entries (Default) -> Add JARs.... (this will go to a local path)
  4. Navigate to and add the JAR.
  5. In the Ant view, kill the project's build.xml and go get it again.

This should fix the problem.


Unsucking Eclipse Juno...

I happen to agree that the Juno user experience leaves just about everything to be desired as compared to former versions of Eclipse. This is why I refuse to move up from Indigo. Change Eclipse Juno UI to match Eclipse Indigo is a post by someone who feels the same. While it doesn't leave everything perfect, there's some new ugliness, it makes the thing less cotton candyish and is a good option (though not nearly enough to push me forward yet).

Just in case that post goes missing someday, here are the steps. This may or may not work for Kepler too.

  1. Locate the Eclipse Juno installation in your filesystem; mine is at ~/dev/eclipse/juno-jee-eclipse.
  2. Below it, find the plugins subdirectory.
  3. Then type cd org.eclipse.platform_4.2 and press Tab to complete. You should arrive at a destination that looks something like org.eclipse.platform_4.2.1.v201209141800.
  4. Rename the css subdirectory so that it can't be used:
        ~/dev/eclipse/juno-jee-eclipse/plugins/org.eclipse.platform_4.2.1.v201209141800 $ mv css css.old
    
  5. The next time you launch Juno, all the fluff will disappear.

If you wish to go back to Netherland, simply restore this subdirectory to its original name.


Customizing the Project Explorer view

Especially when developing a Dynamic Web Project, the Package Explorer view is real junky. I turn most of it off this way:

  1. Look for and click a downward-pointing triangle toward the right end of the pane menu bar containing the Project Explorer view.
  2. Choose Customize View....
  3. Click the Content tab.
  4. Unclick everything except the following:
    • JPA Content
    • JAXB Content
    • Enhanced Java Rendering for Web
    • Java Elements
    • Resources
  5. Click OK.

From this point on, your src and test subdirectories are still obfuscated by Java Resources, but that's the worst of it. Also, a lot of fluff that I don't ever use is gone, which cleans up the view a lot.


On Eclipse projects and non-Eclipse technology

This is an excerpt from an answer I gave in the Eclipse newcomers' forum one day. The question was about Eclipse download packages, Python versus Java development, how to develop on different hosts and the author was confused by the use of "package".

I have no experience with PyDev. At http://pydev.org/developers.html one is told to direct questions to https://lists.sourceforge.net/lists/listinfo/pydev-code.

Eclipse isn't responsible for the support of myriad projects and technologies, the best example of which are the Android Development Tools (ADT), that have chosen to implement their IDE using Eclipse. It's very confusing and difficult for newcomers to know when to direct questions to this forum and when to find another.

Eclipse downloads are best chosen, in my opinion, by starting with the one closest to what you ultimately want to do. In my case this would be Eclipse IDE for Java EE Developers rather than choosing Classic, then adding a whole bunch of plug-ins to reach the point I want. But in theory, there's nothing lost by starting low and building high, or starting with Java and adding C/C++, or PyDev, or ADT, etc.

When you create a new project in Eclipse, the new project wizards typically give you the option of defaulting to create it in the current workspace. If you create it from existing source or by importing an already existing Eclipse project, you're given the opportunity to move (or copy) the sources over into the workspace. (Do not copy project sources by hand over into the workspace, let Eclipse do it.) Again, I don't know how PyDev works, but I do know about Java and Java/ADT projects,

If you wish to spread your project development time across more than one host, you should consider a version-control system like Git. If you cannot or do not want to set that up on your own server, you can get free space with Atlassian Bitbucket ( http://bitbucket.org/ —which does not charge) or GitHub (http://github.com —which does not charge for open/publicly visible projects). I cannot recommend this too strongly. It will involve learning (yet another) technology, but this one is well worth your time. On version control: the world is moving away from CVS and Subversion toward Git (there are others like Mercurial).

You cannot transport your Eclipse workspace from one machine to another; workspaces are filesystem-dependent. Projects are portable, however, but projects live in a workspace, so short of recreating your project by import each time you change machines, or carefully clobbering your project with changed content, which is painful, Git is your best route.

A project is what you're calling a package in your question here.

In Java, packages are a division of your project. Typically, you have more than one package making up a project. Window -> Show view -> Project Explorer is a different way to view what you're doing. It might make more sense to you. Window -> Show view -> Navigator is a filesystem-oriented way to see the same thing. None of this will probably rehabilitate your Python project. If things don't work out, you'll have to resort to support from the PyDev community.


Eclipse: Source not found

When debugging, or attempting to access source in the editor, you stumble upon a message, "Source not found." There's a button, Attach Source... that you can click. Do this.

If the source is in your workspace (unlikely), then you can click the Workspace... button.

If in a file external to your workspace, that is, you have the source somewhere, you can click External File....

The most common is to have a folder of external source that you want to use as a resource. Click External Folder.... Navigate to the com parent directory to that source, select it and click OK, then again in the Source Attachment Configuration dialog, click OK.


FindBugs plug-in

FindBugs can be useful, but it can also be annoying and misleading with the bugs it finds (especially lots of null pointer stuff that isn't really a problem). You have to decide on a case-by-case basis.

To install it, use Help -> Eclipse Marketplace... and search for "findbugs".

When installed, right-click a project and choose Find Bugs ->Find Bugs. It will mark up (annotate) your Java code in the left margin of files with what will show up as warnings in the Problem view. Turn this crap off by right-clicking and choosing Find Bugs -> Clear Bug Markers.

If you download findbugs-ant.jar, wishing to consume it from build.xml, it goes on a path where it can be consumed locally, e.g.: project-name/lib/non-deploy/findbugs-ant.jar. Here's a sample ant target:

    <!-- == F i n d B u g s ( t m ) =========================================== -->
    <taskdef name="findbugs" classname="edu.umd.cs.findbugs.anttask.FindBugsTask"/>

    <property name="findbugs.home" value="/home/russ/dev/downloads/findbugs-2.0.2" />

    <target name="findbugs" depends="build-compile"
	        description="Run FindBugs on compiled code and libraries.">
        <findbugs home="${findbugs.home}"
                  output="xml:withMessages"
                  outputFile="${extras.dir}/findbugs.xml" >
          <auxClasspath path="${flat_libs.dir}/*.jar" />
          <sourcePath path="${src.dir}" />
          <class location="${build.dir}/classes" />
        </findbugs>
		<style    in="${extras.dir}/findbugs.xml"
		         out="${extras.dir}/findbugs.html"
			   style="${extras.dir}/findbugs.xsl"
		/>
    </target>

Tabs/spaces in Java editor

Window -> Preferences > General -> Text Editors -> Insert spaces for tabs is not how to exchanges spaces for tabs in the Java editor, but only the "default" text editor.

Window -> Preferences -> Java -> Code Style -> Formatter -> Edit (button) -> Indentation -> Tab Policy -gt; Spaces only is how to force it in Java.


Cleaning up the Project Explorer view

Click the downward-facing triangle in the Project Explorer views menu bar.

Choose Customize View..., then click the Content tab. Uncheck everything except:


Code-coverage plug-in for Eclipse

I found a great direct code-coverage plug-in for Eclipse. You can get it up and running with zero configuration!

http://www.eclemma.org/index.html


Updating Eclipse to use Java 8...

I did not try this for Indigo, which isn't guaranteed to work. Maybe someday.

  1. Downloaded JDK 8 from java.sun.com.
  2. Wired it up to Kepler.
  3. Wrote code requiring Java 8 (static default method in interface).
  4. Count not set compliance to 1.8.
  5. Updated Kepler to SR2 and restarted.
  6. Still no 1.8 option for Properties -> Java Compiler -> Compiler compliance level:.
  7. Use Help -> Install New Software:
    1. Added Eclipse 4.3.2 Patch Build
      http://download.eclipse.org/eclipse/updates/4.3-P-builds
    2. Checked Eclipse Java 8 Support (for Kepler SR2).
    3. Click Next.
    4. Select Eclipse JDT.
    5. Click Next.
    6. Accept EULA.
    7. Click Finish.
    8. Restart.
  8. Found 1.8 as option for Properties -> Java Compiler -> Compiler compliance level:.
  9. Appears to work.

"type java.lang.CharSequence cannot be resolved"

This error in Eclipse indicates that something is amiss with the .classpath file. Likely it thinks you're trying to compile with a version of Java that was available and is no longer available. For example, I once got this when I had set up a project to be built with Java 8, but then went back to play with it in Indigo where I couldn't use Java 8. I had to find and delete the reference in .classpath to Java 8 (1.8) and then use Build Path -> Configure Build Path to remove the Java 8 JDK and replace it explicitly with Java 7.


Free UML tool ObjectAid

Get ObjectAid here. See more notes here.

You can create the diagram anywhere you wish in the project, it doesn't have to be under src. Then, with it open, just drag .java classes from the Eclipse Project/Package Explorer views and drop them into it. Rearrange, shrink, etc. as desired.


Markdown in Eclipse

In Eclipse Marketplace, there's a plug-in to download named GitHub-flavored markdown viewer plug-in for Eclipse.


DIY Eclipse for classroom

See this article.


Plug-in: workspace mechanic

workspacemechanic to provide easier migration of (enterprise) workspace settings for Eclipse users.


Separate Eclipse binaries/running Eclipse twice

I did this because I did not wish to contaminate my Luna JEE with PyDev stuff. Yet, it works fine. I just wanted two, separate copies.

I cloned my copy of Eclipse Luna, the subdirectory, to another, separate subdirectory, then launched it. It came up on the same workspace as I had been using with the other copy. I changed workspaces (in the new copy), then exited and launched the original copy of Eclipse which came up with the original workspace.

So, two copies, even one cloned from the original, will launch separately. From the point of view of additional plug-ins, they remain separate. They are completely separate installations from that point on.