Generating blog posts

  • Random
  • Archive
  • RSS
  • Ask me anything

Everything you need to understand to start with AngularJS

2012 was the year of the rise of the Javascript MVC frameworks and librairies with countless of those frameworks that were released or that went under the spotlight. Among others, you must have heard about Backbone.js, Ember.js but my personal favorite is AngularJS. AngularJS is a Javascript MVC framework created by Google to build properly architectured and maintenable web applications.

Why AngularJS?

AngularJS is a MVC framework that defines numerous concepts to properly organize your web application. Your application is defined with modules that can depend from one to the others. It enhances HTML by attaching directives to your pages with new attributes or tags and expressions in order to define very powerful templates directly in your HTML. It also encapsulates the behavior of your application in controllers which are instanciated thanks to dependency injection. Thanks to the use of dependency injection, AngularJS helps you structure and test your Javascript code very easily. Finally, utility code can easily be factorized into services that can be injected in your controllers. Now let’s have a closer look at all those features.

Expressions

AngularJS let you build properly structured web applications very easily. For that, AngularJS contains several concepts to separate the different parts of your application.

In order to create the views of your application, AngularJS let you execute expressions directly within your HTML pages. In those expressions, you have access to Javascript code which give you the ability to realize some computation in order to display what you want. In the screenshots below, you can see a very basic expression and it result.

image

image

Expressions in your HTML page are nice, but you won’t build a complete web application like that, it would be horrible to write and to maintain, we need the help of something more powerful. Expressions are used for small operations, In order to structure you web application, AngularJS will give you a much impressive tool, directives.

Directives

Directives are one of the most powerful feature of AngularJS. They allow you to extend HTML to answer the needs of web applications. Directives let you specify how your page should be structured for the data available in a given scope.

We will have a look at the scope and where those data are coming from later in this post but first let’s have a look at how directives are working.

AngularJS comes with several directives which let you build your basic application. The first directive you will use most of the time is “ngRepeat”. This directive let AngularJS create a new set of elements in the dom for each element in a collection. In the following example, we ask AngularJS to create a new div containing a small title and a paragraph for each element of the array users. Each of those element will be affected to a variable named user wich let us access the individual elements of the array.

image

The result is exactly what we were expecting, a new div has been created for each of my entity with their name as a title and their description in a paragraph.

image

For those who are wondering why I have prefixed “ng-repeat” by “data-“, have a look here.

AngularJS also let you determine if an element should be displayed or not with the directive “ngShow”. This directive uses an expression which returns a boolean to determine if the element should be displayed or not.

image

image

As you can see in the result, only females are displayed. If you inspect the dom, you would see that the other elements have been computed but their are just hidden (display = none).

AngularJS also contains more complex directives like “ngSwitch”.

image

With those directives, you have the ability to define the basic structure of your web application very easily.

image

Directives coming from the AngularJS standard library are named “ngMyAwesomeDirective” and used in the view using an attribute “ng-my-awesome-directive” or “data-ng-my-awesome-directive”. Some directives can also be used as comments, DOM elements name or even CSS classes.

Data Binding

Angular does not only let you structure your views with directives, it also give you the ability to define the binding between the data in your scope and the content of your views. We have seen how we can display values from our scope using their attributes in expressions like {{user.name}}. You could also use operations in those expressions {{object.operation()}}.

You can also create bidirectionnal binding in AngularJS very easily with the directive “ngModel”.

image

image

The result is directly binded to the value of the description. If you change the content of the text area, the description of the object in the scope is modified and the description in the paragraph is updated in real time.

image

Filters

In order to change the way your data are displayed in your page, AngularJS provides you with the filter mechanism. In the screenshot below, you can see how we can put the name in upper case with {{user.name | uppercase}}.

image

image

You can also easily create you own filters.

Partial Views

AngularJS is very good to build single page web applications. For those who are not familiar with this concept, it consists on a web application where you only have one “real” HTML page whose content can be changed in Javascript without having to download a new page. The new content is created programmatically in Javascript of with the use of templates. Those applications have advantages like performances (since you are not downloading a new HTML page each time you are navigating to a new page) and drawbacks like history management (what happens if your users click on the button back of their browser?).

With AngularJS, you see that you are using a framework created by people who know what they are doing, as a result most of the problems of regular single page web applications are handled by AngularJS itself.

In order to build your application, You define a main page (index.html) which acts as a container for your web application. In this page, you can bind part of your application to a specific AngularJS module with the directive “ngApp”. You can bind the whole page to a single AngularJS module if you want. After that, you can use the directive “ngView” in order to use partial views.

Your module will tell AngularJS which view should be display in the “ngView” element. This directive also let you separate the content of your application in dedicated files.

image

Since the beginning of this article, we have been using a dedicated view to display users information.

image

Modules

Now that we have seen how we can display the information that we want with AngularJS, let’s have a look under the hood. In AngularJS, applications are structured in modules. A module can depend on other modules and a module can contain controllers, services, directives and filters.

image

The empty array, visible in the screenshot, is where you declare the modules needed by your module. We have already binded this module our view with the directive “ngApp” before.

You can configure some services of your application thanks to the operation “config”. Since AngularJS has been created to build maintainable web applications, it helps you to separate your application in small, easily testable, components. As a result, AngularJS will often rely on dependency injection in order to plug the various components of your application together.

Dependency Injection

The operation “config” is using dependency injection in order to retrieve some elements of the application that should be configured when the module will be loaded. Here, we will use the service provider “$routeProvider” in order to define the routes of our application. You have two ways of using dependency injection in AngularJS. You can pass a function to the operation with parameters named after the elements that you want to retrieve.

image

This solution is not really recommended since minification of the code would change the name of the variable which would prevent your application from working. If you want to use a robust solution, you should use an array with the name of the elements that you want to see injected and a function naming those elements.

image

The name of the parameter of the function does not have to be the same as the name of the element injected.

Routes

Using the route provider, we can configure the routes available in our application. For our example, we will only create two routes, one for our users “/users” and for any other routes, a redirection to our error page.

image

You can see that, if we go to the url “http://domain/#/users”, AngularJS will load the partial view “views/users.html” and use the controller “UsersCtrl”. For any other url, the error view will be used instead. We have seen how our application is organized, now let’s have a look at the behavior of the application.

Controllers

In AngularJS, the controller is where the behavior of your application is located. Controllers are used to populate the scope with all the necessary data for the view. Using proper separation of concerns, controllers should never contain anything related to the DOM.

Controllers communicate with the view using a specific service named “$scope”. This service let the controller give objects and functions to the views that can later be manipulated with expressions and directives. In order to be easily tested, controllers are defined using dependency injection.

image

Scope

The scope is used to link the controllers and the views to which they are binded. A controller can add data and function in its scope and then they will be accessible in the view. In our case, we have used in the view a variable named “users” which was created in the scope by the controller “UsersCtrl”.

image

We have seen before how we can use the data in the scope from our view.

image

Without digging into the details too much, when changes are occuring on the scope, events are fired to warn those who are interested. The views are using those events to know if they should refresh the elements involved.

Watch

AngularJS comes with lot of operations to manipulate the scope. AngularJS provides the necessary tool to observe the changes on the data of the scope from the controller. With the operation “$watch”, a controller can add a listener on an attribute of its scope.

image

Events and root scope

AngularJS also gives you access to a system of events and listeners on the scope. You can use the operation “$broadcast” in order to fire an event on a specific scope, then the event will be transmitted to the selected scope and all its children. If you want to send an event to the whole application, you can use the root scope thanks to $rootScope.

image

Services

While controllers contains the behavior of the application that should be available to the view, you may have some code that you want to re-use or that you want to abstract from the controller which communicates directly with the view. For this, AngularJS let you define services that can be injected in your controllers or in other services to build your application.

If you want to communicate with a server for example, you can inject the $http service into your own service. This service can be injected in your controller which will not have to manipulate HTTP requests directly.

image

Your custom services can be injected in your controller just like any regular AngularJS service.

image

Your service can define a public API that will be used by the other services or controllers in which they will be injected.

image

REST communication

In order to communicate with a restful server, AngularJS provides two services $http and $resource. $http is a small layer on top of XmlHttpRequest while $resource is working at a higher level of abstraction, both can perform the same job.

image

$resource let you communicate with a server using custom actions instead of relying on the default get, post, delete, etc. Those custom actions are binded to the default HTTP method. “Get” is using the method GET while “save” is using the method POST etc. Keep in mind that this service comes from the module “ngResource”. As such, your module will need a dependency to “ngResource” in order to let you inject “$resource” in your code.

image

In order to make sure that you can test your application easily, AngularJS also comes with a $httpBackend mock to test HTTP requests without a web server.

Custom directives

We have seen how AngularJS provides you with directives in order to extend regular HTML. You can also create you very own directives in order to adapt your views to your needs. If you need to have Javascript code in order to manipulate the DOM, it should not be located in a controller but in your own custom directive.

image

Using a custom directive is very easy.

image

And we have our expected result immediatly.

image

As I said before, directives are among the most powerful mechanisms of AngularJS and as such you have access to tons of options in order to build your own. You should definetly have a look at the documentation to learn more about everything you can do with directives.

image

In a next post, you will see how we can improve our AngularJS application development with Jenkins-friendly unit tests, code coverage and static analysis. In order to put in place continuous integration for our application, we will use tools like Grunt and Karma. We will also have a look at various tools like Yeoman and Bower to build and organize our application.

For more news about AngularJS, don’t forget to suscribe to the RSS feed of this blog or follow me on Twitter or Google+.

    • #AngularJS
    • #Javascript
    • #MVC
    • #Web
  • 3 weeks ago
  • 40
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+

UML to Java Generator 2.0

The version 2.0 of the UML to Java Generator is finally here! This new release of the generator comes at the same time as the new release of UML Designer.

In this new version of the generator, we are now compatible with the latest release of the UML project. The 1.x version of the generator is still being maintained and improved for those who cannot migrate to the new version of UML and the version 1.0.4 for Eclipse 3.7 has been recently released.

In the version 2.0, you will now have support for components.

image

If your model contains components, you can choose to generate regular Java project or Eclipse-based plug-ins and features for each of those components. Thanks to the exported interfaces and the required classifiers in your model, exported and imported packages will be computed.

image

You will also find a brand new launch configuration where you will be able to configure all the details of your generation much more easily than before. The launch configuration can now be saved in your workspace in order to be able to share it with the rest of your team.

image

We also have introduced support for nested classifiers along with bug fixes.

image

You can find the new version of the generator on the Eclipse Marketplace. If you want to have a look at its source code, you can find it on Github. For questions related to this generator, have a look at its dedicated forum. Don’t forget to suscribe to the RSS feed of this blog or follow me on twitter or google+ for the latest news on this generator.

    • #Eclipse
    • #UML
    • #Acceleo
    • #Java
  • 1 month ago
  • 1
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+

Debugging a Java application

My posts on the Eclipse Java Development Tools are coming to an end. After having a look at the configuration of a Java project, the development of a basic Java application, the configuration of Eclipse and the various refactoring options available. Today, it’s time to see the features provided by the JDT to help us debug our Java applications.

5.1 - Breakpoints

image

In order to debug an issue in your application, the first step is to find out where to problem may be coming from and then to place a breakpoint there to see the state of the application at this location. You can easily create a breakpoint in Eclipse by double clicking in the left sidebar of the Java editor, right clicking and use the “Toggle Breakpoint” action or by using the shortcut “Ctrl+Shift+b” to place a breakpoint on the line where your cursor is located. Then, in order to stop the application on the breakpoint, you just have to launch your launch configuration using the debug mode. The launch configuration remains the same wether you are using the run mode or the debug mode. Once the breakpoint is reached by the application, Eclipse will ask you if you want to switch to the Debug perspective. You can also place your cursor over a variable in order to inspect the state of this variable.

5.2 - Conditional breakpoints

image

You may want to stop your application on a breakpoint only if a specific condition occurs. The JDT lets you create “conditional breakpoints” by right clicking on an existing breakpoint and modifying its properties. There, you can enter the condition that will stop the application on the breakpoint. If you can modify the code where the breakpoint is located, I recommend you not to use this feature as it is way slower than using an “if” block with a regular beakpoint.

5.3 - Pause the vm

By default, a breakpoint will only stop the current thread, in order to study concurrency issues, you may want to stop the whole virtual machine. You can change this setting easily in the properties of a breakpoint.

5.4 - Step over, step into, step return…

image

Once stopped on a breakpoint, you have access to several actions to navigate within your code. You can use “step over” to move to the next instruction, “step into” to go inside of the next instruction or “step return” to move to the end of the current method. You can also use the “drop to frame” action to return at the beginning of the current method.

If you want to quickly navigate to a specific line in your code, you can place a breakpoint on this line, resume the program and when the breakpoint is reached, remove the breakpoint. You can also use the “Run to line” shortcut “Ctrl+r” which will resume the execution program and will stop it at the specific line where the shortcut has been executed. If the line in question cannot be reached, the execution will just continue until its end.

5.5 - Step filtering

When you are using the “step xxx” actions, you may want to ignore some types. You could, for example, choose to ignore all the steps involving “java.lang.ClassLoader” or any “meaningless” entities of your application. You can define step filters by right-clicking in the debug view and you can use them with the shortcut “Shift+F5”.

5.6 - Hotswap

The various “step” actions give you the ability to navigate in the instructions in order to have a look at the flow of the application but you may also want to fix your issue while staying in debug mode. You can edit your code while your application is running and have some of the changes taken into account directly. If you are modifying the content of a method, it will be replaced dynamically in your application most of the time (if it fails, a popup will invite you to restart your application) and the execution of the application will move back to the beginning of the method. If you are adding a method, an attribute, or if you are changing the signature of a type, you will have to restart your application. If you want to have the ability to replace anything at any time, have a look at the proprietary solution JRebel or wait for improvements in the Java runtime.

5.7 - Variable view

When the application is stopped on a breakpoint, you can use the “Variables” view to see the state of all the variables. In this view, you can display the logical structure of some types like collections and maps. You can also edit directly the values of your variables, changing the execution of your application easily.

5.8 - Display view

If you need to try long expressions prior to their integration in your code, you can use the “Display” view to compile and run various pieces of code against the current state of your application. This view can speed up your debugging sessions by an orders of magnitude. This view will give you code completion and the ability to run or inspect the result of your code. If you choose to execute your code, the result will be displayed after your expression. If you choose to inspect the result, a popup will be opened with the result.

5.9 - All instances

If you want to have a look at all the instances of a specific type, you just need to select this type and right click on it to use the “All Instances” action or you can use the shortcut “Ctrl+Shift+n”. A popup will then be opened with all the instances of the selected type.

5.10 - Contribute logical structures

If you have a type with a complex structure and if you want to change how it is displayed in the variable view, you can contribute to the JDT a new way to display it in debug. You can find more information on this mechanism online but be careful since your code will manipulate your data to figure out a new way to display tham, you may create side effects.

5.11 - Expression view

image

Seeing the state of a variable is nice but you may want to see the state of a more complex expression. The “Expression” view lets you enter complex expressions whose result will be continuously displayed while you navigate in the execution of your application. Those expressions can also have side effects and change the behavior of your application.

5.12 - Evaluate and inspect

If you want to figure out the state of a variable that has not been created yet, you can execute an abitrary piece of code (providing that all the element necessary for its execution exists at the current state of the application) and see the result. You can select a piece of code and execute it with the “evaluate” shortcut “Ctrl+Shit+d”. Alternatively, you can run a selected piece of code and navigate inside its result with the “inspect” shortcut “Ctrl+Shift+i”.

5.13 - Scrapbook page

image

Now, you’ve seen various ways to debug a running Java application but if you want to test a specific piece of code, do you always need to run the whole application for that? Of course not! In order to solve this problem, the Java Development Tools contains a very powerful, yet quite hidden, feature: The scrapbook page. A scrapbook page is a text file which comes with an editor capable of compiling and running Java source code with the “evaluate” and “inspect” shortcuts. On top of that, the scrapbook page is running in debug, so you can place breakpoints and have a look at the details of your program.

With all those blog posts, we’ve seen quite a lof of tips and tricks to improve your Java development. If you don’t want to miss an update on this blog, don’t forget to suscribe to the RSS feed or follow me on Twitter.

    • #Eclipse
    • #JDT
  • 3 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+

Third milestone of the Mylyn connector for Tuleap

Today the third milestone of the Mylyn connector for Tuleap has been released. In this new version, we have mainly worked on Mylyn Context integration, support for attachments and queries.

As we’ve seen before, you start by configuring your Mylyn repository with the URL of your Tuleap trackers. Starting with this release, you can retrieve the reports saved on the Tuleap server and execute them directly from Eclipse but you can also create your own queries by defining precisely your own critera.

When you open an artifact, you can use an editor parameterized by the definition of the tracker that you have created in Tuleap. This editor lets you edit your tasks directly from Eclipse. You can now freely download and upload attachments from this editor.

When a task is activated, the technical artifacts that you manipulate will be saved and the Package Explorer view will be filtered to display only the artifacts relevant to your work on this task. You can also store the context of your task directly as an attachment.

And of course, you can retrieve it in a couple of clicks.

When your task is activated, other tools can leverage the connection with Mylyn Context to adapt their behavior. As an example, EGit, the Eclipse Git tooling, will use the name and the state of the currently activated task to fill the message of your next commit.

Finally you can also attach a screenshot by using the dedicated tooling which let you take it directly from Eclipse. You will have the opportunity to edit the screenshot with various annotations.

This work is open source and available on Github under the Eclipse Public License. All milestones and integration builds that have been published can be found on Github too. For more information about this connector, don’t forget to subscribe to the RSS feed of this blog or follow me on Twitter.

    • #Mylyn
    • #Eclipse
    • #Tuleap
    • #Task
  • 3 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+

Refactoring and running a Java application

Yet another post on the Eclipse Java Development Tools!

In the first post, we have seen how to create and configure a Java project, then how to create a basic Java application and, finally, we have seen advanced tips for Java development. Now it’s time to see how we can continue to improve our application with refactoring and how we can run our Java application in Eclipse.

4.1 - Generate getter, setter

image

In a Java application, you need a ton of getters and setters but it doesn’t mean that you have to write them by yourself. You can generate them very quickly either by using the code completion of by using the “Source” menu with the shortcut “Alt+Shift+S”. The “Source” menu also gives you the ability to generate several getters and setters at the same time.

image

Both solutions are generating code using the same code templates for setters and getters so do not hesitate to customize them as we have seen it before.

4.2 - Generate the constructor and much more

The “Source” menu contains a lot of options to quickly generate boring pieces of code. Using a method similar to the one used to generate getters and setters, you can easily generate a constructor in a few seconds thus you can create a data class from a simple class containing only a couple of fields. You could also generate other methods like “toString()”, “hashcode()”, “equals(…)” and much more. You can also change the code generated by configuring the code templates.

4.3 - Surround with…

image

Among the features available from the contextual menu, one of my favorite is the “Surround With…” action. Thanks to the shortcut “Alt+Shift+z”, you can surround a selected piece of code with a code template. Among the code templates available, you can find “try… catch…”, “for…”, “if…”, “runnable…”.

image

If you want to create a new code template that can be used in the “Surround With…” action, you should use the variable “${line_selection}”.

4.4 - Rename

image

One of the most used refactoring tool of any self respecting IDE is the renaming. In Eclipse, you just have to use the shortcut “Alt+shift+r” and you will be able to rename all the occurrences of the selected element.

4.5 - Extract method

image

In order to improve the maintainability of your source code, you need to separate your method in smaller methods as they grow. You can do that very easily in Eclipse with the “Extract method” action. With the shortcut “Alt+Shift+m”, you can open a wizard letting you extract the currently selected code in a new method. Several other (less important in my mind) refactoring actions are also available from the “Refactor” menu. You can access them quickly with the shortcut “Alt+Shift+t”.

4.6 - Generate refactoring scripts

image

One of the first goal of an IDE is to automatize boring work and as such, Eclipse not only provides you with refactoring tools but it also records their use to let you create refactoring scripts. If you have to realize several refactoring actions on a bunch of classes, this can speed up you work.

4.7 - Paste Java source code as a new file

If you’ve found a piece of code that you want to integrate in your application, you can use a wizard to create a new Java class, choose its name and then paste the code in this newly created class or you can just select a package and paste your code directly. A new Java file will be created with a class, the package declaration will be written and with save actions you can even obtain the declaration of the imports easily along with formatting etc.

4.8 - Launching a Java application and favorites

image

Most of the time, in order to launch an application in Eclipse, you have to use a launch configuration. You can run your application thanks to the contextual menu available on a Java file, but you can also go configure manually a launch configuration. Thanks to the “Organize Favorites…” action or directly in the “Common” tab of your Java launch configuration, you can add a specific launch configuration to the list of your favorite ones. As a result, the launch configuration will be quickly accessible in the submenu of the run / debug / profile action of the toolbar.

4.9 - Launch configuration parameters

In our Java application, we are using some input parameters. In order to configure them in your launch configuration, you just have to use the “Arguments” tab.

4.10 - Saving a launch configuration on a file

When you are working in a team, you may want to share your launch configurations. As an example, all your team members need to launch the same tests suite with the same configuration. The “Common” tab of the Java launch configuration let you save the launch configuration in a XML file that can be easily shared in your version control tool. You just have to select a folder for the “Shared file” and a file named “<name of the launch configuration>.launch” will be created in this folder.

4.11 - Log in a file

image

One of the first way to find out more about an issue is to log some information in the standard outputs using “System.out.println(…)” or “exception.printStackTrace()”. Some issues may generate a lot of information and it may be very difficult to read any meaningful information in the console. The “Common” tab of the Java launch configuration lets you redirect the standard output to a file where it will be easier for your to process a very verbose log.

Next time we will conclude with some tips on debugging Java applications in Eclipse. Follow me on twitter if you don’t want to miss any update.

    • #Eclipse
    • #JDT
  • 4 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+
Pop-up View Separately
Pop-up View Separately
Pop-up View Separately
Pop-up View Separately
Pop-up View Separately
PreviousNext

The new launch configuration of the UML to Java generator has just been contributed on Github. I believe that with this new launch configuration, the generator feels way more “professional” and it’s easier to manipulate. I am still unsure about the new design to let users customize the generated types so I have not integrated it in the “Type” tab yet.

There are still some improvements that need to be made to the generation, the non-regression tests have to be updated and the documentation must be polished after that the generator will be ready for its 2.0 release.

    • #Eclipse
    • #UML
    • #Java
    • #Acceleo
  • 5 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+
Pop-up View Separately
Pop-up View Separately
Pop-up View Separately
Pop-up View Separately
PreviousNext

With the release of UML2 v4 last june, I have started to work on a brand new version of the UML to Java generator. With Mathieu’s help, I have improved this project in order to have a more maintainable code base. Those changes will also give us more freedom to add new features to the generator.

As I explained it before, the UML to Java generator 1.0 introduced a launch configuration in order to configure your generation. It also let you use “.properties” files in order to change some parameters used in your generation. While both mechanisms are nice they don’t offer the level of quality and the ease of use that I am looking for. As a result, with the upcoming 2.0 release of the UML to Java generator, the use of properties files will not be supported anymore.

For those who are using or extending the version 1.x of the generator, it won’t go away but since the switch to the version 4 of the UML2 project breaks the compatibility with the previous release of the generator, it was the perfect opportunity to get rid of some features that did not match the expected level of quality.

In order to replace the use of the properties files, the version 2.0 of the generator will feature a brand new launch configuration. Recreated from scratch, this new version will give you a better tooling to configure the generation. You will also have access to more options than before. To leverage more information from UML Designer, the generator will start taking into account more diagrams than the good old class diagram with support for the components diagram.

The generator will be available under the Eclipse public license v1.0 and this work is hosted on Github.

    • #Eclipse
    • #UML
    • #Java
  • 5 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+

Advanced coding with the JDT

With the last messages, you know how to create and configure properly your Java projects and how to use Eclipse to code faster than ever. Today, it is time to review advanced features of Eclipse to go even faster! We have seen how Eclipse help us when we ask for help with the proper shortcut, today we will mainly see how we can configure Eclipse to help us even more and sometime even automatically.

3.1 - Imports order

image

If you remember correctly, last time we have seen various ways to make Eclipse compute the types to import for you, thanks to the use of code completion, the quick fix or the “Ctrl+Shift+o” shortcut. With all those import declarations automatically computed, you may want to change the way the JDT orders the type imported.

To configure most of the settings in Eclipse, you can navigate to the properties of your project (right click -> Properties) or you can go to the properties of Eclipse itself (Window -> Preferences). The difference between the two solutions is that with project settings, the changes will most of the time be saved in a file under the folder “.settings” and as such, you can share it on your favorite source code management. I’ve talked about this “.settings” folder in the “1.3” section before. We will use project-specific settings as much as possible since we want to share our awesome settings with the rest of our team.

In the “Java Code Style” section, you can find a part dedicated to “Organize Imports”. In this preference panel, you can activate a project specific setting for the order of the imports in the Java source code of your project. Since I like to have my imports ordered alphabetically with the static import after, I’ve changed the default settings.

3.2 - Formatter

image

From the very same window, you can also change the settings of the formatter. By default, when using the automatic formatting, Eclipse will rely on a built in formatter profile. By switching to a project-specific one, the formatter used can not only be customized but it can also be shared with your other team members. You have access to a very wide range of settings to customize the formatter that you wish to have.

3.3 - Type filtering

When you are using the code completion in Eclipse, you have access to an enormous amount of information and you may want to filter some of those information. In the Eclipse preference window (Window -> Preferences), you can use the “Java -> Appearance -> Type Filters” panel to filter some useless type from the “Open Type” dialog, the code completion and the quick fix proposals. For example, if you are manipulating user interface types, you may want to get rid of all the “java.awt.*” types since you may not use them.

3.4 - Favorite for the imports and code completion

On the other side, have you ever had any problems with the static imports for example with “assertEquals” or “sqrt”? Eclipse never seems to find them properly the first time. In Eclipse, not only you can remove some types from the code completion, you can add favorites one too to ensure that they will be found more easily. In the same Eclipse preferences window, you have access to the list of your favorite static members and types. You just need to go to the “Java -> Editor -> Content Assit -> Favorites” section to add new favorites. When you will use the code completion again, your favorites are now accessible. I would recommended using this to add JUnit static methods but not much more as, outside of those static methods, I don’t really like having just the name of the static method. I prefer “TypeName.staticMethod()” to “staticMethod()”.

3.5 - Code conventions

In the settings of your Java project, you can also define project-specific code style to help you maintain a set conventions in your projects. You can easily set up a specific prefix for all your fields to prevent a parameter from hiding one of your fields and much more. I personally don’t use it to set up any prefix or suffix for the name of my variables, fields or parameters but it is useful to have a better name for exceptions for example (“e”, the default one, being a very bad name).

3.6 - Errors and warnings

The project specific settings of your Java project also give you the ability to choose the severity of the Java problems that can be detected by the JDT. You have access to a very wide range of problem that you can choose to ignore, treat as warnings or consider as errors. You can even make the JDT treat those problems as fatal errors preventing the compilation of the code. Some of the problems detected can be very helpful to improve the quality of your code or to prevent future issues like:

  1. non externalized strings
  2. undocumented empty blocks
  3. boxing and unboxing conversions
  4. potential null pointer access
  5. redundant null check
  6. local variable declaration hides another field or variable
  7. classes that override equals() but not hashCode()

3.7 - Task tags

When you are working on a sizable Java project, you will have pieces of code that may not be working completely as expected. As a result, you can use a comment like “// TODO do something” or “// FIXME huge bug”. Not only Eclipse will detect those tags and create markers and tasks for them that you can use to track the remaining issue that you need to resolve but the JDT also let you define your own task tags. Those project-specific task tags can let you specify tags that match more clearly the domain of the problem. The tasks created can be seen in the dedicated “Tasks” view.

3.8 - Line delimiters and encoding

In order to minimize problems, you and your coworkers should select a specific line delimiter and encoding for all your textual artifacts. In the project-specific settings, you can choose which line delimiter and which encoding you want to use on the project.

3.9 - Javadoc errors and warning

image

We have seen how you can tell the JDT to look for additional errors and warnings in the code of your Java project but you can also check for problems in the javadoc too.

3.10 - Custom code templates

In the previous post, we have seen how we can use code templates like “foreach” or “sysout” to speed up our development. The JDT not only provides code templates but it also allows you to define new ones to help you go even faster.

There are two kinds of code templates, code style templates and editor templates. The first ones can be saved only as Eclipse-specific settings while the second ones can be also saved as project-specific settings. The code style templates, that can be saved at a project level, let you define the code generated when you are creating a new file, a new class, a new field or even a new method. Those templates can be helpful to specify a copyright that should be added to every Java files.

On the other hand, the editor templates, that can only be saved at an Eclipse level, let you define templates mostly used within the code or the Javadoc itself. You can easily customize or create very complex code templates in a matter of seconds with a powerful templates language. You can use those templates later just like regular ones.

3.11 - Escape text when pasting in a string literal

One day, you will want to paste something in a string literal that need to be escaped like the absolute path of a file in windows for example. You can let the JDT do the job for you automatically with the Eclipse-specific Java editor typing options. It’s one of those tips that is useful only once in a while but which makes you so happy when it’s there to help you.

3.12 - Save actions

Advanced JDT users will notice that I am keeping one of the most convenient option of the JDT for the end with “save actions”. Save actions are just a set of actions that will be triggered by the JDT once you save your Java file. You can define save actions as project specific settings and it will change your life. Writing imports manually was boring, using the code completion was better but sometimes we still had to use “Ctrl+o” to force the automatic resolution of the missing imports, now it can be done each time we save our file. We can also make sure that unused imports are cleared all the time. The amount of options available in the save actions is mind-blowing. Save actions are awesome, use them!

3.13 - Overriding with the code completion

While writing a Java program, you will have to override a method one day or another. You could write the signature of the overriding method by yourself but you can also use the code completion to do it in a couple clicks. You just need to use the code completion where you want to write the overriding operation. As usual, you can leverage camel case to choose more quickly the method to override.

3.14 - Copy qualified name

If you want to have the qualified name of a Java element like a class, a method or a field, you just need to use the contextual action “Copy Qualified Name”. One day, you will need it and you will love it.

3.15 - Go to line

image

An exception has been raised in your application and a very long stack trace has been printed in the console. You can click on the first line of the stack to go to the source of the problem but if you need to navigate to another position referenced in the stack trace, you can just open the type mentioned and then with “Ctrl+l”, you can go to a specific line in the currently selected editor.

Now we have seen a lot of tips and tricks to speed up Java development in Eclipse. As I have presented it in the introduction, next time we will see how we can configure the launch of the Java application and the different refactoring options available.

    • #Eclipse
    • #JDT
  • 5 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+
'\x3ciframe width=\x22500\x22 height=\x22374\x22 src=\x22http://www.youtube.com/embed/Z0wOY75ZM1k?wmode=transparent\x26autohide=1\x26egm=0\x26hd=1\x26iv_load_policy=3\x26modestbranding=1\x26rel=0\x26showinfo=0\x26showsearch=0\x22 frameborder=\x220\x22 allowfullscreen\x3e\x3c/iframe\x3e'

EclipseCon Europe 2012

“Over the last few years, with the rise of application lifecycle management tools, your IDE became a technical data powerhouse. Within the development team, developers are manipulating a broad range of data thanks to dedicated tools. Ranging from the PDE to EGit and including Mylyn Tasks, Mylyn Build, m2clipse and even the platform itself, we have now access to countless of tools just a click away.

Your IDE is now a maze of tools that are sometime communicating with each others yet you cannot easily access or manipulate the data that they are creating.

Presented for the first time, Ariadne is a brand new Eclipse-based tool built to cut through the maze by leveraging the data collected by your IDE. With those data, Ariadne can provide you with a bird eye view of your IDE to monitor your project. Contrary to existing tools like Checkstyle or Sonar, Ariadne does not consider that a project is limited to its code and it can let you define cross concern requirements to help you keep your project in line.

Finally, with its data-driven approach, you will see how Ariadne can help you measure the impact of the changes that you want to realize on your project.

During 25 minutes, you will see how Ariadne can use the daily work of an Eclipse committer to help the management of an Eclipse project.”

The slides are available online.

    • #EclipseCon
    • #Mylyn
    • #Eclipse
  • 5 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+
'\x3ciframe width=\x22500\x22 height=\x22374\x22 src=\x22http://www.youtube.com/embed/MNo_0HYh8aI?wmode=transparent\x26autohide=1\x26egm=0\x26hd=1\x26iv_load_policy=3\x26modestbranding=1\x26rel=0\x26showinfo=0\x26showsearch=0\x22 frameborder=\x220\x22 allowfullscreen\x3e\x3c/iframe\x3e'

Alex Lagarde, EclipseCon Europe 2012

“Documentation sucks because most of the time it’s outdated: it never reflects the recent changes you made on your software, and sooner or later no one will trust (and hence read) it anymore. By providing tooling to efficiently update documentation when a change occurs (in your models, your code…), Mylyn Intent gives to your documents the abillity to react to changes, turning them into true Agile documents. Moreover, as we’re in 2012 Intent provides advanced tooling to write/query your documentation with everything you would expect from a modern IDE (completion, quick-fixes, quick-outlines to browse through documents…). Icing on the cake, you can also collaborate in real time to write your documentation, preventing you from sending documents through mails or handle SVN conflicts.

During the Eclipse Juno release, we used Mylyn Intent to document models describing Enterprise Architectures, computed through the use of the Obeo SmartEA Modeling Tool. In the Design phase, models were quickly evolving and it was a good chance to test how can Intent help us keeping the doc up-to-date with those changes.

In 2012, and one can expect more than an outdated, non-IDE integrated documentation exchanged through mails or SCM tools. Attend to this talk to discover:

  • How to use Intent to quickly create meaningful Design documentation
  • How to use Intent to keep this documentation up-to-date whith changes made on your models
  • How to collaborate in real-time around your documentation tasks

What features were missing for efficently document EA models and how did we respond to these industrial needs.”

For more information on Mylyn Intent, have a look at the project on eclipse.org or directly on twitter.

    • #Mylyn Intent
    • #EclipseCon
    • #SmartEA
  • 5 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+

Coding a basic Java application

Most of the time, when you are working on a Java application you are not starting from scratch. You have to integrate your code in an existing project or you wish to use an existing framework and as such, your main problem is working with an existing piece of code. We will see how we can use Eclipse to help us write, fix and navigate in our code with, among other features, code completion, quick fixes, automatic imports, search and code templates. This post will start slowly as the most important tips will be explained first so I will take some time to detail their behavior.

Let’s consider the following use case. You are working on a brand new piece of code that depends on an existing Java application. It can be a library, a framework or an existing project. You have read the documentation, you saw a blog post about a nice piece of code or one of your coworkers gave you some information to start. In our case we will consider that our goal is to use the framework EMF to “load a resource from a file using a resource set and then navigate inside the content of the resource to display the properties of the attributes it may contain”. You are not familiar with the EMF framework? Perfect! From this description of the problem, we have an indication on the dependencies that we should use (some EMF jar files) and we know the concepts to use in order to start. We need a file, a resource and a resource set (whatever that is).

We have seen in the previous post how to add dependencies to a Java project. I have already added all the necessary jars from EMF in my Java project before. Now, let’s start coding. From what we have heard, we need to start with a file and a resource set but while I know where to find this “file” (java.io.File), where can I find this concept of resource set?

2.1 - Looking for code

image

In the Java Development Toolkit, when you are looking for a type, you should use the “open type” action. You can find it on your toolbar in the Java perspective or by using “Ctrl+Shift+T” . It opens a dialog box that let you search for any Java type in your workspace or in the dependencies of the content of your workspace (you can expand where Eclipse should look but we will see that later). This dialog box is also leveraging the power of the Java naming convention to speed up your search. This is a very important concept in the Java tooling in Eclipse.

Java uses camel case as a naming convention and as such this concept of “resource set” can pretty much only be written as “ResourceSet”. When you are using / importing / looking for / instantiating / manipulating a concept in Java, you do not have to write everything. If you are writing more than 50% of the code displayed on the screen, you are doing a bad job! Since I am looking for the concept of ResourceSet, I will only type “RS” in the search field of the “Open Type” dialog. There are lots of entities that contains both of those upper cased letters in this order (like RelationServiceNotRegisteredException) so I will filter the result a bit by adding precising a bit more what I am looking for by typing “RSet”. Eclipse can then easily find the type “ResourceSet” that I was looking for. I can see, at the bottom of the dialog, in which jar this concept is located and I know in which package it is defined. Here, we can see that it is located in the package “org.eclipse.emf.ecore.resource”, which seems right. By clicking on “OK”, this type will be opened in a new editor.

2.2 - Attach the sources

As you can see it, an editor is now opened on the type ResourceSet by I can only look at the bytecode. I can’t see the source code. After a quick search on the web, I have found the jars containing the source code. I can put them in my lib folder and then I can use the “Attach Source” button to open a popup which will let you select where the source code is located. I have used this popup to link the jar of “org.eclipse.emf.ecore” to the jar containing its source code “org.eclipse.emf.ecore.source”. As a result, the editor now shows the source code of “ResourceSet”.

2.3 - Camel case and code completion

Now, we have found the concept of resource set that we were looking for and we have read its javadoc to know what we are dealing with. Let’s start coding for real. I want an instance of ResourceSet, so let’s start by creating one. The first thing you would be writing is “ResourceSet resourceSet = <something>”. As I said before, you should not write everything by yourself and you should leverage the massive use of camel case. As such, you should not write “ResourceSet resourceSet” by yourself, you should type “RSet” and use the code completion (Ctrl+Space). As a result, the type ResourceSet is imported and “ResourceSet” is written. You now have to type the name of the variable. Unless you have specific reasons, you should let Eclipse choose the name of your variables for you. For an instance of the type ResourceSet, Eclipse let you choose between “resourceSet” and “set”. Let’s choose “resourceSet”. Now we have typed “ResourceSet resourceSet” and we have imported the type ResourceSet just by typing in reality “RSet ” and by using the code completion. Among the valid reasons to not use the name given by the code completion, we can find:

  1. you already have a variable with the same name and “<variableName>2” is a very bad name.
  2. your variable carry a very specific meaning that cannot be discovered just by its type

For those use cases, all you need to do is to add a prefix or a suffix to the name suggested by Eclipse like “inputResourceSet” or “outputResourceSet”. But in order to have a code which is easy to maintain and fast to write, you really need a good reason not to use one of the name suggested by Eclipse.

Now that we have “ResourceSet resourceSet”, let’s create an instance of resource set. We manually type ” = new ” to have “ResourceSet resourceSet = new ” but now we have another problem, ResourceSet is an interface so how do we find an instance of ResourceSet?

2.4 - Navigate in the hierarchy of your code

How do we find all the implementations of ResourceSet? You have several ways of navigating the hierarchy of your code in Eclipse. First, you can open once again the source code of “ResourceSet” by using “F3” or “Ctrl+click” on the type “ResourceSet” (“Ctrl” will transform any navigable element into a hyperlink). Once the type “ResourceSet” is opened, you can have a look at the documentation to find a potential implementation but sometimes you won’t find any information there. You may be able to re-use the “link with editor” action from the Package Explorer view, seen in the first post, to navigate directly inside of the jar to look for implementation but it’s boring.

If you really want to see the hierarchy of your code, you can use the “Code Hierarchy” view by using “F4”. With this view, you can see all the types that are extending or implementing “ResourceSet”, you can also see which type “ResourceSet” is extending or implementing itself. We can see here that we have a class named “ResourceSetImpl” that implements “ResourceSet”. There is another way to navigate in the hierarchy of your code using “Ctrl+T” on a type or a method. This shortcut will give you the list of all the type that are extending the selected type or all the types that are overriding a selected method. You don’t even have to leave your code to use it. Those two ways of navigating the hierarchy of your code are confirming what we believed, we need to use “ResourceSetImpl”. In order to do that, we just write “RSI” and use the code completion.

We now have “ResourceSet resourceSet = new ResourceSetImpl()” and both “ResourceSet” and “ResourceSetImpl” have been properly imported. We just need to add the final “;” and our first line of code has been written. Yet, we have just typed “RSet = new RSI;”

2.5 - Quick fix and code completion

image

Now that we have seen how we can use the Java naming conventions, code completion and the code navigation to find what we want, we have created an instance of “ResourSet”. We know from the instructions at the beginning of the post that we need a file. Just by typing “Fil = new ;” we can instantiate a new Java file thanks to the code completion.

We have our file and we have our resource set so how do we combine those two entities to get a resource? The easiest way to do this is to start using your “resourceSet” with the code completion to see the available operations. For that, you just have to type “rS” and use the code completion to obtain “resourceSet” and then “.”. The code completion gives you access to all the available methods on “ResourceSet”. You quickly realize that the method “getResource(URI uri, boolean loadOnDemand)” seems to match what you were looking for. You can type with method by typing “gR”.

Now that we have “resourceSet.getResource(uri, loadOnDemand);”, we have two problems, “uri” and “loadOnDemand” are not matching any existing variables. While we know what “loadOnDemand” represents since “boolean” is a known type, we don’t know what “uri” is. Is it a “java.net.URI” or a “com.sun.org.apache.xml.internal.zerializer.utils.URI”? This is where your next best friend enters into action, the quick fix! You just need to place your cursor at the end of line (where it should be anyway after typing the “;”) and use “Ctrl+1”. The quick fix action can create the boolean “loadOnDemand” for you but after that you still have an error, you don’t have an uri. by using the quick fix once again, the variable uri is created and the type URI (from org.eclipse.emf.common.util) is properly imported.

Now that this is fixed, you still have two errors, both newly created variables are not initialized. By using the quick fix again, you can initialize them easily. Now the boolean “loadOnDemand” is initialized to “false” (we will change that to true) and “uri” is initialized to “null”. One last step, we need to retrieve the result of the call to “getResource”. For that, keep your cursor at the end of the line and use quick fix once again, you can create easily the variable that will hold the result of the call to “getResource” and the import of the type “Resource” will be realized for you. By typing “rS.gR;” and using the completion and the quick fix we now have “Resource resource = resourceSet.getResource(uri, loadOnDemand);” with all the necessary types imported and the variables created, named and initialized. I’ll say it again but if you are writing all your code manually, you are doing a bad job!

2.6 - Automatic imports and organize imports

We have seen how we can use the code completion and the quick fix to speed up our development and we’ve seen how they can automatically import the necessary dependencies for us but sometimes you will copy a piece of code from a forum and when you will paste it in your code. It won’t compile since you don’t have the necessary imports. Let’s delete all the import realized previously. If you need to force Eclipse to resolve the import for you, you just need to use the shortcut “Ctrl+Shift+O”, in case of conflict (they are several types named URI for example), a popup will appear to give you the opportunity to choose which type to use. The imports will be written and ordered.

2.7 - Look for the features of your type

image

We now have our file, our resource set and we have seen how we can get a resource from the resource set but one thing is missing, where do we find this “uri” that we need? Right now, it is initialized with “null” and we know that it won’t really work. By using the quick navigation (Ctrl+click) we can open the class URI. Since it is a class, we only need to look for its constructor. In order to do that, you can use the outline view or you can use the shortcut “Ctrl+o” to open a popup showing all the fields and methods of the class.

When the popup opened from using “Ctrl+o” is displayed, you can also see inside the inherited methods and fields by pressing “Ctrl+o” a second time (since URI does not inherit from anyone it would be pointless here). By using the camel case, you can quickly find what you are looking for, here we need a constructor so we are looking for “URI”. Unfortunately for us, we see that the constructor of URI is private so we can’t use it. So how can we create our URI?

2.8 - Where is my code called from?

image

If we can’t use the constructor of URI, let’s see where it is called from. Eclipse can let you see where a given piece of code is called from very easily, you just have to place your cursor on a piece of code and use “Ctrl+Alt+H”. This shortcut will open the “Call Hierarchy” view where you can navigate in all the code that is using the selected element. Here we can see that the constructor of URI is used by a lot of operations. By navigating in the “Call Hierarchy” view, we can see that the static method “createFileURI” is using this private constructor indirectly and from its javadoc it seems to take the absolute path of a file and it returns the matching URI. We already have our file, this method will be perfect for us.

2.9 - Coding templates

We want to have a look at the content of this newly loaded resource, for that, we create a variable with the content of the resource (List<EObject> contents = resource.getContents();). Now we want to iterate on this content and display something for each element. We could write a “for” block manually but Eclipse provides a lot of code templates to help you code faster. As such, you just need to type “foreach” on the following line and use the code completion. The “for” block is then automatically created for you. There are lots of code templates available in Eclipse from “sysout” to “toarray”, “try”, “new”, “nls” or even “arrayadd” to add an element to an array. In the next post we will see how you can customize those templates and even create new ones. Do not forget that you have access to code completion and code templates in the javadoc too.

2.10 - Format and indent

Eclipse also give you the ability to format your code with the “Ctrl+Shift+f” action. You can also indent your code with the shortcut “Ctrl+i”. Since our code was properly formatted and indented since the beginning, it won’t make any difference for us but it is quite useful when copying code from internet.

In this post, I’ve spent a lot of time detailing precisely the behavior of the most powerful and the most commonly used tips to speed up your Java development in Eclipse. Next time, I’ll go faster to explain advanced features of the Java Development Toolkit.

    • #Eclipse
    • #JDT
  • 5 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+

Create and manage a Java project

For this first post, I will start slowly with the creation and configuration of a brand new Java project. Then we will have a look at the various option to set up our project from the configuration of the JVM to the different source folders that we want to use. We will see how we can organize our Java projects and after that we will move on to the creation of our first packages and classes. Finally we will conclude with the project dependencies. Dozens of screenshots are also available in order to illustrate the information provided in this blog post, don’t forget to click the links.

1.1 - New project wizard

image

In order to start working on a new Java application, you need to create a new Java project. For that, you have access to the new “Java Project” wizard from the “File” menu. In the first page of the wizard used to create the new Java project, you have to choose the name of the project. You also have the ability to select the location where the project will be created. This features gives you the ability to create a project outside of your Eclipse workspace.

This is particularly useful to let you create your project in a Git repository located somewhere else on your file system. You can then import easily the same project in various Eclipse workspaces and work from those different workspaces without having to synchronize later on different versions of your application. The workspaces will be kept almost empty, except for a folder “.metadata” which contains the settings of the workspace. You can easily setup a new Eclipse with a brand new workspace and resume your work. I would go as far as saying that except for prototyping code, most projects should be created outside of your workspaces which can, that way, stay disposable.

In this page, you can also select the Java Runtime Environment (JRE) of your project. You have the choice between using a selected execution environment JRE, using a project specific JRE or using the default JRE. I will detail the configuration of the JRE later but I recommend using an execution environment JRE. You can also choose the layout of your project from this page (we will have a look at this later) and you can choose to add your project to a working set (also, more on that later). On the second page of this wizard you can configure several options of you Java project, those options being accessible after the creation of the project, we will explore them later.

1.2 - Filtering the content of the Package Explorer view

The first view you are manipulating while working on a new Java project is the “Package Explorer” view since it contains your newly created Java project. This view contains lots of options and we will start by having a look at filtering. In the Package Explorer view, you can hide various kind of artifacts in order to help you get more focused on your work. By default, all “.*” resources are hidden. I can change this settings to reveal them in the “Package Explorer” view.

1.3 - Hidden resources: “.project”, “.settings” and “.classpath”

By using the filtering to show all the “.*” resources, three new resources have appeared inside of our Java project:

  1. the file “.project”
  2. the file “.classpath”
  3. the folder “.settings”

The file “.project” is used by Eclipse in order to store some metadata about the nature of the project, its name and the tools that should be used with this project. If we open it, we can see that inside this XML file, the name of the project and the natures of the project. Eclipse will use the name inside this file “.project” to display our project in the Package Explorer view. It does not have to be the name of the root folder of the project. By selecting a custom location for the creation of the project you can make the name of the root folder of the project different from the name of your project. The nature is used by Eclipse to known the kind of the project that is manipulated. In our case, we only have the nature “org.eclipse.jdt.core.javanature” since we have a basic Java project. You can also see the “build specification” of the project. This information is used by Eclipse to known which tools should be called when the project is modified. In our case, the builder with the id “org.eclipse.jdt.core.javabuilder” will be used when the project is modified. The Java builder is responsible of the compilation of the Java source code.

In Eclipse, you have access to several levels of settings, Eclipse-based settings and project-based settings. The folder “.settings” located in your Java project contains all the project-specific settings of the Eclipse tools that you are using. By default, the JDT setup some default options in the setting of your project. We will have a detailed look at the various Eclipse and JDT settings in the third post. The Eclipse-based settings are located in the “.metadata” folder of your workspace.

The file “.classpath” is used by Eclipse to compute the classpath of your project (what a surprise!). In this file, you can find the list of your source folders with their output folders and also all your dependencies. You can also find in this files the various container used in your project. Those container are Eclipse metadata that are resolved by the tooling to various artifacts. By selecting an “execution environment JRE” while creating our project, we essentially told Eclipse that we are using the container for “JavaSE-1.7”, we don’t care where it’s located in the file system, we don’t care about the precise version of Java 7, we just want this container to be resolved against a JRE known by Eclipse that matches “JavaSE-1.7”. This way we can share our project on a repository without having the absolute path of our JRE in the settings of our project. Other team member will just need to have a JRE compatible with “JavaSE-1.7” configured in their Eclipse (more on that later).

1.4 - Projects and working sets

image

If you are working on an existing Java application, one day or another, your workspace will be cluttered by countless of projects. In order to categorize properly your workspace, the Package Explorer view let you define “Working Sets”. You can create a new “Working Set” and then drag and drop you project inside this way you can group your project by concerns inside of your workspace. Keep in mind that “Working Sets” are a logical structure and as such you can have a project in multiple “Working Sets”. You can later drag and drop any resources in the resource set of your choice creating that way a working set composed only of your configuration files if you want.

1.5 - Go into

Now that you have categorize the thousands of projects that may exists in your workspace, you may still have problems to easily manipulate your code if one of your “Working Set” contains dozens of projects. Sure you can separate those projects in smaller “Working Sets” but what if it’s not relevant for your need or what if you want to work on a project containing hundreds of packages? The Package Explorer view let you “go into” a container to remove all the useless content from your sight. This way, you can work only on a given package or folder if you need it without having to see the rest of your artifacts. You can also easily move to an upper container.

1.6 - Java Runtime Environments

image

You can configure in Eclipse the various JRE that can be used by your Java projects in the section “Installed JREs” of the preferences of your Eclipse. You may need to press “OK” to fully validate the changes done to the list of installed JREs. Once applied, you can go back to configure your “Execution Environments”. There, you can match a given execution environment to a specific “Java Runtime Environment”. This way, when the container for “JavaSE-1.7” of your new Java project needs to be resolved, it can be linked to a specific JRE. You can then go in the properties of the build path of your project and in the “Libraries” section, you can edit the JRE selected. The settings is also accessible on the new Java project wizard as we have seen it before.

1.7 - Source folders

In most of the Java project, the Java source code is located in a folder named “src/” under the root of the project. You can define other source folders if you want. A good practice, for example, is to put the generated code in packages located in the “src-gen/” source folder. This way, if you need to clean the generated code, you can delete easily this code. Maven developers tends to use “/src/main/java/” as their source folder. Whatever your reason, Eclipse let you create easily new source folders, you can even convert existing folders into source folders or remove source folders without removing the physical folders. All those changes are stored in the file “.classpath” that we saw at the beginning.

1.8 - Using libraries

image

While you are working on your Java project, a time will come when you will have to use external libraries. There are several ways to resolve a link to an external dependency. The Maven tooling for example creates its own container in the classpath of your Java project and then it uses a dedicated builder to analyze the file pom.xml located in the project to determine the dependencies that should be downloaded and linked with the project. Sometimes, you don’t have the choice and you need to depend on a good old jar file. In order to do that, you can create a “lib/” folder at the root of the Java project where you can put you jar files. In a couple of clicks you can add those libraries to your classpath. You could also add the external jars from “Libraries” section of the “Java Build Path” settings.

1.9 - Packages, Classes, Interfaces and enumerations

Now, your projects are configured with their “Java Runtime Environment”, their libraries and they are properly organized within Working Sets. It’s about time to start building this application. We have seen how you can organize your source folders. With the JDT, you can easily create packages with a dedicated action in the toolbar of the Java perspective. In the same way you can create Classes, Interfaces or Enumerations. You can also create those artifacts from the New menu in the contextual menu or in the File menu.

1.10 - Package presentations

You can also select how you want to display packages in the “Package Explorer” view. You can keep the flat representation which is used by default or you can switch to a hierarchical view.

1.11 - Link with the editor

When you are navigating in a big Java application, you will end up with some code in your editor coming from an unknown place. You could have open a class of one of your dependencies for example. In order to find out where the code displayed in you editor is, you can click the button “Link with the editor” in the “Package Explorer” view. The resource containing the code displayed in the active editor will be selected in the “Package Explorer”. If you keep navigating in the code, the selection will be updated. It will be very useful in the next post.

1.12 - Open in new window

image

Those of you who possess a dual-screen configuration may want to extend your Eclipse across both monitors. Eclipse let you open a project in a brand new window.

1.13 - Project dependencies

If you want to properly maintain your project, you will have to split it in several Java project as it grows. Eclipse let you easily setup projects dependencies in a couple of clicks.

1.14 - Close a project

The more opened projects you have in your workspace, the slower Eclipse will be. To speed up Eclipse, close useless projects!

1.15 - Delete a project

Of course you can also delete projects from Eclipse, but be careful, the default behavior remove the project from the workspace but it does not delete the project from the file system. If you have created your project in a custom location like a Git repository, this may be the behavior that you desire. If you really want to delete completely the project from the file system, do not forget to check the matching option.

Regular Java developers should not have learned anything really new in this post, this one was mainly for newcomers. In the next part, we will get our hands dirty as we will start coding. You’ll see the tips and tricks of the JDT that I’m using everyday to speed up massively my Java development.

    • #Eclipse
    • #JDT
  • 5 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+

Eclipse Java Development Tools

As an Eclipse committer on Acceleo, I am using Eclipse all the time and I have now learned various tips and tricks for Eclipse. During the last couple of weeks, I had the opportunity to go back to my old university to teach the future generation of software developers and by being surrounded with newcomers in both Java and the Eclipse ecosystem, I came to realize that I could share some information that I have acquired using Java and Eclipse all day long.

Most of the time, when learning Java development, people are only taught about the language itself and some frameworks but not that much about the tooling. Yet you will spend most of your time developing in Java with an IDE that provides you with tons of features. The Java Development Tools project is one of the best Eclipse-based tools ever built. Thousands of developers from all around the world are using the JDT everyday. Yet most users of the JDT only use a fraction of its true potential. Over the next few weeks, I will detail most of the things I know about Java development in Eclipse. I will assume that the readers know the Java language already as I won’t explain it. Starting slowly in order not to afraid newcomers, I will later move to advanced features and hidden tricks that will be useful even to Java experts.

I will review several phases of the development of a Java application starting with the creation of the project and the development of a basic Java application then I will move on to improving the application with the refactoring tools and how to configure Eclipse to let the JDT handle most of the boring work for you. Finally I will give you tips and tricks to debug your application. If you are coding in Java and if you think you know everything about Java development on Eclipse, think again!

Plan

  1. Create and manage a Java project
  2. Code a basic Java application
  3. Configure Eclipse to speed up your coding workflow
  4. Refactor and run
  5. Debugging a Java application
    • #Eclipse
    • #JDT
  • 5 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+
I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence (I suspect this level of confidence is high compared to industry standards, but that could just be hubris). If I don’t typically make a kind of mistake (like setting the wrong variables in a constructor), I don’t test for it. I do tend to make sense of test errors, so I’m extra careful when I have logic with complicated conditionals. When coding on a team, I modify my strategy to carefully test code that we, collectively, tend to get wrong.
Kent Beck
    • #Test
  • 5 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+
Pop-up View Separately
Pop-up View Separately
Pop-up View Separately
Pop-up View Separately
Pop-up View Separately
Pop-up View Separately
Pop-up View Separately
PreviousNext

During the last couple of weeks, Mélanie and I have been working together on a brand new connector for Mylyn Task in order to bring support for the open source application lifecycle management suite Tuleap into Eclipse.

Tuleap provides a lot of features from wiki and forum to trackers and we worked on the integration of Tuleap trackers and Mylyn Task. In Tuleap, you can configure your trackers as you wish. You can choose precisely all the widgets that will be available and you can customize their behavior. To match this behavior, the editor of the Mylyn Connector for Tuleap is parameterized by the description of the Tuleap tracker.

As in any other Mylyn Task connector, you can synchronize artifacts by defining queries which will be executed on the server. You can also create new artifacts locally and then synchronize them later with the server. Once an artifact has been synchronized with the server, Mylyn will update the artifacts with the changes that have occurred on the server automatically and you will be able to publish new changes too.

This ongoing work is open source and available under the Eclipse Public License v1.0 and it will be contributed to the Eclipse Foundation in the months to come. It is currently hosted on Github.

    • #Eclipse
    • #Mylyn
    • #Task
    • #Tuleap
  • 5 months ago
  • Permalink
Share

Short URL

TwitterFacebookPinterestGoogle+
Page 1 of 3
← Newer • Older →

Portrait/Logo

About

Stéphane Bégaudeau graduated from the Nantes University of Sciences and Technology and is currently working as an Eclipse Modeling consultant at Obeo in France.

He is the leader of Acceleo, a code generator created by Obeo and now developed in the Eclipse foundation. He also worked on the Mylyn Task Connector for Tuleap.

Twitter: @sbegaudeau
Google+: +stephane.begaudeau

Twitter

loading tweets…

Top

  • RSS
  • Random
  • Archive
  • Ask me anything
  • Mobile
Effector Theme by Pixel Union