Featured FREE Whitepapers

What's New Here?

netbeans-logo

NetBeans 8.0’s Five New Performance Hints

NetBeans 8.0 introduces several new Java hints. Although there are a large number of these new hints related to Java Persistence API, I focus on five new hints in the Performance category. The five new “Performance Hints” introduced with NetBeans 8.0 are:            Boxing of already boxed value Redundant String.toString() Replace StringBuffer/StringBuilder by String Unnecessary temporary during conversion from String Unnecessary temporary during conversion to StringEach of these five performance-related Java hints are illustrated in this post with screen snapshots taken from NetBeans 8.0 with code that demonstrates these hints. There are two screen snapshots for each hint, one each showing the text displayed when the cursor hovers over the line of code marked with yellow underlining and one each showing the suggested course of action to be applied to address that hint (shown when clicking on the yellow light bulb to the left of the flagged line). Some of the captured screen snapshots include examples of code that avoid the hint. Boxing of Already Boxed ValueRedundant String.toString()Replace StringBuffer/StringBuilder by StringUnnecessary Temporary During Conversion from StringUnnecessary Temporary During Conversion to String Unless I’ve done something incorrectly, there appears to be a minor bug with this hint in that it reports “Unnecessary temporary when converting from String” when, in this case, it should really be “Unnecessary temporary when converting to String”. This is not a big deal as the condition is flagged and the action to fix it seems appropriate.Conclusion The five performance-related hints introduced by NetBeans 8.0 and illustrated here can help Java developers avoid unnecessary object instantiations and other unnecessary runtime cost. Although the benefit of this optimization as shown in my simple examples is almost negligible, it could lead to much greater savings when used in code with loops that perform these same unnecessary instantiations thousands of times. Even without consideration of the performance benefit, these hints help to remind Java developers and teach developers new to Java about the most appropriate mechanisms for acquiring instances and primitive values.Reference: NetBeans 8.0’s Five New Performance Hints from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
groovy-logo

Groovy Goodness: Closure as a Class

When we write Groovy code there is a big chance we also write some closures. If we are working with collections for example and use the each, collect or find methods we use closures as arguments for these methods. We can assign closures to variables and use the variable name to reference to closure. But we can also create a subclass of the Closure class to implement a closure. Then we use an instance of the new closure class wherever a closure can be used. To write a closure as a class we must subclass Closure and implement a method with the name doCall. The method can accept arbitrary arguments and the return type can be defined by us. So we are not overriding a method doCall from the superclass Closure. But Groovy will look for a method with the name doCall to execute the closure logic and internally use methods from the Closure superclass. In the following sample we write a very simple closure as a class to check if an object is a number. Then we use an instance of the class with the findAll method for a collection of objects: ...
java-logo

Java 9 Behind the Scenes: Where Do New Features Come From?

Find out what’s going on behind the scenes of Java, and how new features come to life In a previous post we went over the new and pending features for the upcoming Java 9 release, and briefly mentioned the process that a new feature goes through before being added to the next release. Since this process affects almost all Java developers, but is less known to most of them, this post will focus on giving an insider’s view of Java (and how you can suggest that new feature you always wanted). We felt the best way to understand how new features come to life would be to ask the people who are responsible for bringing them into life. We spoke with 2 Java Executive Committee members, Gil Tene and Werner Keil, together with Richard Warburton, a London Java Community member, and asked them about new features in Java and what kind of new capabilities they’d like to see in the future. This post will cover the first part of the interview. But before we do that, here are the main players that take part in creating and voting on new features: Groups – Individuals and organisations with a mutual interest around a broad subject or a specific body of code. Some examples are Security, Networking, Swing, and HotSpot. Projects – Efforts to produce a body of code, documentation or other effort. Must be sponsored by at least one group. Recent examples are Project Lambda, Project Jigsaw, and Project Sumatra. JDK Enhancement Proposal (JEP) – Allows promoting a new specification informally before or in parallel to the JCP, when further exploration is needed. Unlike JSRs, may also contain features that have no specification-level visibility (e.g. new garbage collector or JIT implementation). Accepted JEPs become a part of the JDK roadmap and assigned a version number. Java Specification Request (JSR) – The actual specification of the feature happens in this stage, can be either coming through Groups/Projects, JEPs or from individual JCP (Java Community Process) members. An umbrella JSR is usually opened for each Java version (Also called a platform JSR), this has yet to happen with Java 9. Individual members of the community can also propose new Java specification requests. How do new features find their way into Java? Warburton: “The real answer is that someone wants the feature. That person could be an internal engineer or project manager at a big vendor or an outside member of the community. Either way it needs to be something that meets quite a strict criteria:Serious User Demand: It needs to be something that is a consensus benefit for the whole community. Example: Java SE 8 adds lambdas – this is a feature that has been argued about and demanded for years. Tried and Tested: Standards have to last a long time and its a very difficult and expensive process to modify standards which have already been established. The consequence is that the JCP (Java Community Process) isn’t bleeding edge. Its the place to go once technologies are ready for enterprise adoption. Not Unique to One Vendor: Standards need to be comfortable to all vendors. Example: weak/soft/phantom references interact with the garbage collectors, so they were specified in a way that tried to minimise the restrictions that they impose on GC Design.”“Once you’ve figured out that your feature is a good idea, you need to start the standardisation process. This involves raising a JSR – Java Specification Request – which is the atomic unit of changing Java. A JSR needs to be voted upon multiple times. Firstly to approve that its a good idea to start a JSR on this topic. Iteratively whenever a public review comes up to ensure that the JSR is headed on the right course. Finally when its time to approve the standard”. Tene: “Java has a long history of careful and deliberate enhancements over time. One of the things that still makes Java more successful than virtually all other programming languages and environments in history is its relative success in avoiding the rapid adoption of “the latest cool thing”, and its relative consistency as a platform. This is true across the platform as a whole (Java SE, EE, etc.) but is probably most clearly followed within the Java SE platform, where I focus most of my attention. Collections, NIO, Generics, Platform-optimized Concurrent Utilities, MethodHandles, and most recently Lambda expressions and streaming library support are all good examples of features that were added and then widely adopted over time, showing their true value to the platform and their importance as much more than a fleeting fashion.” “The JCP (Java Community Process) is responsible for capturing new features via JSRs. A successful individual, stand-alone JSR standardizes the semantics of a specific set of features or behaviors. But the ultimate success and adoption of a feature is usually demonstrated when it becomes a required part of a platform JSR, thereby becoming an integral part of the Java SE or Java EE platform. Since the creation of OpenJDK, we’ve seen much of the early stage work on features in Java SE move from being developed within JSRs to being developed within JEPs (JDK Enhancement Proposals). They all still end up being spec’d and completed as before, and become part of the Platform JSRs as well, but we see a lot more development-in-the-open, and a lot more experimentation (development of things that wouldn’t necessarily make it as JSRs).” Keil: “3 competing JSON libraries, one for Java EE, another Oracle proprietary one bundled with Java ME 8 and yet another independent JEP based approach for Java SE 9 is probably one of the best examples where this can go wrong and contrary to user’s and developer’s need or the aim of setting ONE standard for Java. Another one would be overlapping and largely incompatible Date/Time APIs introduced with Java SE 8 (JavaFX+JSR 310) while 2 other libraries existed before under “java.util”. Java architects provide input and recommend things, but looking at e.g. Date/Time API only the worst issues they or others (including a few Executive Committee members) pointed out were addressed, while other concerns they had were brushed away.” Can you share one personal experience you had with the Java Community Process? Keil: “A while ago myself and Co-Spec Lead Antoine Sabot-Durand proposed a JSR for standardized CDI based connectors to Social Media and similar APIs naturally based around JSON, REST or security standards like OAuth, too. The JSR was turned down by a slight majority of 8:5. Given Seam Social and the entire Seam ecosystem at Red Hat were dropped in favor of new projects just like the entire JBoss server got a new name and brand (WildFly) around that time, the resulting Open Source project Agorava was a natural fit to replace Seam Social and many ideas we had proposed for JSR 357.”  Tene: “As part of the JCP Executive Committee, I’ve had to weigh in on approving new JSRs. In more than one case I’ve voted to reject JSRs (and advocated for others to do the same) that I thought did not belong in the platform, but most JSRs that naturally fit into the Java ecosystem do not have too high a bar to cross as long as the JSR lead signs up for the detailed work and process involved”. Warburton: “I helped out a bit with the date and time library. I think it gave me a greater appreciation for the level of detail in which each unit of functionality or method signature needs to be thrashed out. People invest a lot of time in trying their best to get these APIs right.”Reference: Java 9 Behind the Scenes: Where Do New Features Come From? from our JCG partner Alex Zhitnitsky at the Takipi blog....
jsf-logo

WAI-ARIA support for AutoComplete widget

In this post I would like to discuss the accessibility for an AutoComplete widget. A typically AutoComplete widget provides suggestions while you type into the field. On my current work I implemented an JSF component on basis of Twitter’s Typeahead – a flexible JavaScript library that provides a strong foundation for building robust typeaheads. The Typeahead widget has a solid specification in form of pseudocode that details how the UI reacts to events. The Typeahed can show a hint in the corresponsing input field, like the google’s search field shows it, highlight matches, deal with custom datasets and precompiled template. Furthermore, the Bloodhound suggestion engine offers prefetching, intelligent caching, fast lookups, and backfilling with remote data.    Despite many features, one big shortcoming of the Typeahead is an insufficient WAI-ARIA support (I would say it was completely missing until now). An AutoComplete widget should be designed to be accessible out of the box to users of screen readers and other assistive tools. I have decided to add a fully WAI-ARIA support, done this taks and sent my pull request to the GitHub. Below is the new “WAI-ARIA aware” markup with an explanaition (not relevant HTML attributes are omitted). <input class="typeahead tt-hint" aria-hidden="true"><input class="typeahead tt-input" role="combobox" aria-autocomplete="list/both" aria-owns="someUniqueID" aria-activedescendant="set dynamically to someUniqueID-1, etc." aria-expanded="false/true"> <span id="someUniqueID" class="tt-dropdown-menu" role="listbox"> <div class="tt-dataset-somename" role="presentation"> ... <span class="tt-suggestions" role="presentation"> <div id="someUniqueID-1" class="tt-suggestion" role="option"> ... single suggestion ... </div> ... </span> ... </div> </span><span class="tt-status" role="status" aria-live="polite" style="border:0 none; clip:rect(0, 0, 0, 0); height:1px; width:1px; margin:-1px; overflow:hidden; padding:0; position:absolute;"> ... HTML string or a precompiled template ... </span> The first input field with the class tt-hint simulates a visual hint (s. the picture above). The hint completes the input query to the matched suggestion visually. The query can be completed to the suggestion (hint) by pressing either right arrow or tab key. The hint is not relevant for the screen readers, hence we can apply the aria-hidden=”true” to that field. The hint is ignored by screen readers then. Why is it not important? Because we will force reading the matched suggestion more intelligent by the “status” area with aria-live=”polite” (will be explained below). The next input field is the main element where the user inputs query. It should have a role=”combobox”. This is a recommended role for an AutoComplete. See the official WAI-ARIA docu for more details. In fact, the docu also shows a rough markup structure of an AutoComplete! The main input field should have various ARIA states and properties. aria-autocomplete=”list” indicates that the input provides autocomplete suggestions in the form of a list as the user types. aria-autocomplete=”both” indicates that suggestions are also provided by a hint (additional to a list). The property aria-owns indicates that there is a parent / child relationship between the input field and the list with suggestions. This property should be always set when the DOM hierarchy cannot be used to represent the relationship. Otherwise, screen readers will get a problem to find a list with suggestions. In our case, it points to the ID of the list. The most interesting property is aria-activedescendant. A sightless user navigates through the list via arrow keys. The property aria-activedescendant propagates changes in focus to assistive technology – it is adjusted to reflect the ID attribute of the current child element which has been navigated to. In the picture above, the item “Lawrence of Arabia” is selected (highlighted). aria-activedescendant is set to the ID of this item and screen readers read to blind users “Lawrence of Arabia”. Note: the focus stays on the input field, so that you can still edit the input value. I suggest to read more about this property in the Google’s Introduction to Web Accessibility.The property aria-expanded indicates whether the list with suggestions is expanded (true) or collapsed (false). This property will be updated automatically when the list’s state changes. The list with suggestions itself should have a role “listbox”. That means, the widget allows the user to select one or more items from a list of choices. role=”option” should be applied to individual result item nodes within the list. There is an interesting article “Use “listbox” and “option” roles when constructing AutoComplete lists”, which I suggest to read. Not important for the screen readers parts should be marked with role=”presentation”. This role says “My markup is only for non sightless users”. You probably ask, what is about the role=”application”? Is it important for us? Not really. I skipped it after reading “Not All ARIA Widgets Deserve role=”application””. The last element in the markup is a span with the role=”status” and the property aria-live=”polite”. What it is good for? You can spice up your widget by letting the user know that autocomplete results are available via a text that gets automatically spoken. The text to be spoken should be added by the widget to an element that is moved outside the viewport. This is the mentioned span element with applied styles. The styles are exactly the same as the jQuery CSS class ui-helper-hidden-accessible, which hides content visually, but leaves it available to assistive technologies. The property aria-live=”polite” on the span element means – updates within this element should be announced at the next graceful interval, such as when the user stops typing. Generally, The aria-live property indicates a section within the content that is live and the verbosity in which changes shall be announced. I defined the spoken text for the AutoComplete in my project as an JavaScript template compiled by Handlebars (any other templating engine such as Hogan can be used too). Handlebars.compile( '{{#unless isEmpty}}{{count}} suggestions available.' + '{{#if withHint}}Top suggestion {{hint}} can be chosen by right arrow or tab key.' + '{{/if}}{{/unless}}') When user stops to type and suggestions are shown, a screen reader reads the count of available suggestions and the top suggestion. Really nice. Last but not least is the testing. If you do not already have a screen reader installed, install the Google Chrome extensions ChromeVox and Accessibility Developer Tools. These are good tools for the development. Please watch a short ChromeVox demo and a demo for Accessibility Developer Tools too. Alternative, you can also try a free standalone screen reader NVDA. Simple give the tools a try.Reference: WAI-ARIA support for AutoComplete widget from our JCG partner Oleg Varaksin at the Thoughts on software development blog....
software-development-2-logo

What Does a Software Architect Do?

Do you have a software architect in your project? Do you need one? Well, most agile teams do not define such a role explicitly and work in a democratic mode. Every important technical decision is discussed with the entire team, and the most voted for solution wins. When such a team eventually decides to put a “software architect” badge on someone’s t-shirt, the most reputable programmer gets it. The badge rarely changes his responsibilities, though. After all, the team stays the same and enjoys having technical discussions together, involving everyone. In the end, a software architect is more of a status than a role with explicitly defined responsibilities. It is a sign of respect, paid by other team players to the oldest and the most authoritative one among them. Right? Absolutely wrong!Obviously, an architect is usually someone who has the most knowledge, skills, experience, and authority. Of course, an architect usually knows more than others and is able to communicate his knowledge with diplomacy and pedagogy when required. An architect is usually one of the smartest guys on the team. This is not, however, what makes him/her an architect. And this is not what the team needs. My definition of a software architect is this: An architect is the one who takes the blame for the quality. You can replace “blame” with accountability or responsibility. Although, I prefer to use “blame”, because it much better emphasizes the fact that every quality issue in the product under development is a personal fault of the architect. Of course, together with the blame he also takes all the credit from happy customers, when the quality is good. This is what the team needs — someone personally responsible for the quality of the software being developed. How this guy will delegate this responsibility to others is his job. Whether he will use his knowledge and skills, or quality control tools, or unit testing frameworks, or authority, or coaching, or corporal punishment — it’s his business. A project manager delegates quality control to the software architect, and it is up to the software architect how to delegate it further. The role of a software architect is crucial for every project, even if there are just two coders working at the same desk. One of them has to be the architect. An ideal architect has all the merits mentioned above. He listens to everybody and takes their opinions into account. He is a good coach and a teacher, with a lot of patience. He is an effective communicator and negotiator. He is a diplomat. And he is an expert in the technical domain. But, even if he doesn’t have all these merits, his decision is always final. And this is the job of the project manager, to make sure that every technical decision the architect makes is not doubted by anyone. This is what delegation is all about — responsibility should always come with power. As a project manager, you should regularly evaluate the results of your architect. Remember, the quality of the product your team is working on is his personal (!) reponsibility. Any problems you see are his problems. Don’t be afraid to blame him and punish him. But, always remember that in order to make your punishments productive you should give your architect full power in his actions. Let me reiterate: his decisions should be final. If you, as a project manager, are not happy with the quality of the product and the architect doesn’t improve the situation, replace him. Downgrade him to a programmer and promote one of the programmers to an architect. But always remember that there can only be one architect in the team, and that his decisions are final. That’s the only way of having a chance of building a perfect product. Related Posts You may also find these posts interesting:Continuous Integration is Dead Project Lifecycle in Teamed.io Why Monetary Awards Don’t Work? Remote Programming in Teamed.io Master Branch Must Be Read-OnlyReference: What Does a Software Architect Do? from our JCG partner Yegor Bugayenko at the About Programming blog....
agile-logo

The Agile Tester, a curious and empathetic animal

The agile tester (ˈadʒʌɪl/ ˈtɛstə/) is an mammal member of the family “Exploratoris”. He lives in the wild in small groups named cross-functional agile teams.           Skills Besides communication and technical skills, his main traits are curiosity and empathy [1]. Curiosity helps the agile tester in finding opportunities to improve the product. The agile tester questions everything. Empathy allows the agile tester to interact and collaborate with the other members of the agile team smoothly. Mission The agile tester has an overwhelming interest in delighting customers. His customers are the product owner and the final users. He strives in balancing his efforts to make his company successful and delighting the final users by delivering a continuous flow of value to both. Life The agile tester spends most of his time having numerous conversations with other members of the team [2]. He will often speak to and question the product owner and the final user in the quest of real value. The agile tester knows that if he doesn’t understand perfectly what the value to be delivered is he won’t be able to do his job. He builds a strong understanding of the business in order to be able to help the product owner identify more valuable solutions. This aspect is extremely important to the agile tester, he strives to contribute to building a better product. Often he will be found having a conversations with the product owner and a developer. This group of animals also known as “The 3 Amigos” [3] feed off each others knowledge, different perspective and passion for value to resolve all sort of problems and design lean solutions. Other times he will be seen pair testing while coaching his partner developer or supporting a developer writing checks, or even writing some checks himself. Some agile testers have been seen speaking to final users to better understand their experience with the application. He is also sometimes found alone at his desk testing, softly talking to the application under test. During the night the agile tester studies and researches his craft, sometimes he blogs and if you watch attentively you might spot a lone agile tester engaging in passionate testing conversations on twitter or in a bar in front of a beer. Social life The agile tester’s’ life would not be possible without the team. He works and lives with the team and for the team, the team is an organism that functions with the agile tester [4]. The agile tester is a pragmatic animal and doesn’t like the company of moaners that do nothing to improve their condition. The moaner is the nemesis of the agile tester [16]. The agile tester believes in sustainable development and will not work overtime except for very special circumstances. He will push for process changes to remove other overtime occurrences. The agile tester and waste In general the agile tester refuses the concept of waste. He will not under any circumstance do something “because that’s  how we do things here” or “because the boss said so”. He will ask “why?”[5]. If he cannot get an answer that clearly explains what the value is, he won’t do it. He’d rather be fired than spend time doing things that don’t produce value. On this subject he is known for using lean documentation, he generally enjoys documenting the application he is helping build through executable specifications [6]. He rejects the waste of bureaucracy and signoffs [7], in fact it is common seeing agile testers signing off by high five[8] in groups of Three Amigos rather than negotiate contracts. The agile testers understands that producing, finding and fixing bugs is a wasteful activity and he will strive to help the agile team prevent them and do the thing right the first time as much as humanly possible[9]. The agile tester, not only understands this, but he coaches the developers members of the team on this concept and trains them in learning  techniques that help them prevent bugs. The agile tester believes that his skills are wasted performing regression checks, in fact he employs tools for this menial task [10]. The agile tester prefers cards and conversations to large documents. He plans his activity just in time and helps build the next parts of the product using discovery. Some agile testers believe predicting the future is a waste of time and prefer building predictable process rather than estimating, they have been known for insistently using the tag #NoEstimates Some extremist agile testers even got to the point to say that bug management is waste and have removed bug management tools from their organizations with a positive impact [11]. Education The agile tester is a continuous learner. He believes in agile principles and he studies the impacts of agile software development on his industry trying to learn new approaches to improve his own company and the whole agile community. He believes that continuous improvement (as in kaizen) means everybody in the agile team is empowered to drive it. He helps other team members bring out their solutions and support them in convincing the team to try and measure results. He does not believe in best practices but in good practices that can be improved [12]. References: [1] Get In Shape to become a better Agile Tester [2] [6] [9] When Something Works Share it  [3] George Dinwiddie on the Three Amigos [4] Cross-dysfunctional teams [5] Be lean ask Why? [7] The Cover your Ass manifesto [8] Sign off by High Five [10] Test Automation, Help or Hindrance? [11] How I stopped logging bugs and started living happy [15] 5 Reasons why best practices are bad for you [16] Stop Moaning, be the changeReference: The Agile Tester, a curious and empathetic animal from our JCG partner Augusto Evangelisti at the mysoftwarequality blog....
ceylon_logo

Write in Ceylon, Deploy as OSGI, use in JEE

… or how to use Ceylon inside Java EE application servers. The Ceylon language is inherently modular, and is shipped with a complete infrastructure that allows leveraging this modularity out-of-the box. However Ceylon is not captive of its own infrastructure. After the Java and JS interoperability efforts, the 1.1.0 version has brought out-of-the-box compatibility with OSGI, which enables running Ceylon code inside many other containers. Every module archive produced by the Ceylon compiler contains OSGI headers in its MANIFEST file, that describe the module as it should seen by OSGI containers. Containers tested so far are:  Apache Felix 4.4.1, Oracle Glassfish v4.1, Equinox platform, JBoss WildFly 8.0.0.alpha3 (with JBossOSGi installed)Of course, the Ceylon distribution and SDK modules should first be added inside the OSGI container as OSGI bundles. But instead of writing long explanations here, let me direct you to some concrete examples provided, with the required instructions, in the following repository: https://github.com/davidfestal/Ceylon-Osgi-Examples/ For the moment, it contains a single example that, though very simple, will give you the main steps to start. It also shows the use of a Ceylon module totally outside Ceylon’s standard infrastructure, even outside the JBoss world, in a Web application servlet running on a Glassfish v4.1 application server. But of course you should be able to run it inside other OSGI-enabled application servers or containers. In the next examples we’ll try to go further an do more interesting things such as providing services, using Ceylon annotations (which are compatible with Java annotations), or using OSGI services. Please report any problem you might encounter while testing, and feel free to submit pull requests for any other successful use cases you might have built. Looking forward for your remarks, and for the time to write the following examples.Reference: Write in Ceylon, Deploy as OSGI, use in JEE from our JCG partner David Festal at the Ceylon Team blog blog....
javafx-logo

New Custom Control: TaskProgressView

I have written a new custom control and commited it to the ControlsFX project. It is a highly specialized control for showing a list of background tasks, their current status and progress. This is actually the first control I have written for ControlsFX just for the fun of it, meaning I do not have a use case for it myself (but sure one will come eventually). The screenshot below shows the control in action.              If you are already familiar with the javafx.concurrent.Task class you will quickly grasp that the control shows the value of its title, message, and progress properties. But it also shows an icon, which is not covered by the Task API. I have added an optional graphics factory (a callback) that will be invoked for each task to lookup a graphic node that will be placed on the left-hand side of the list view cell that represents the task. A video showing the control in action can be found here:The Control Since this control is rather simple I figured it would make sense to post the entire source code for it so that it can be used for others to study. The following listing shows the code of the control itself. As expected it extends the Control class and provides an observable list for the monitored tasks and an object property for the graphics factory (the callback). package org.controlsfx.control;import impl.org.controlsfx.skin.TaskProgressViewSkin; import javafx.beans.property.ObjectProperty; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.concurrent.Task; import javafx.concurrent.WorkerStateEvent; import javafx.event.EventHandler; import javafx.scene.Node; import javafx.scene.control.Control; import javafx.scene.control.Skin; import javafx.util.Callback;/** * The task progress view is used to visualize the progress of long running * tasks. These tasks are created via the {@link Task} class. This view * manages a list of such tasks and displays each one of them with their * name, progress, and update messages.<p> * An optional graphic factory can be set to place a graphic in each row. * This allows the user to more easily distinguish between different types * of tasks. * * <h3>Screenshots</h3> * The picture below shows the default appearance of the task progress view * control: * <center><img src="task-monitor.png" /></center> * * <h3>Code Sample</h3> * * <pre> * TaskProgressView<MyTask> view = new TaskProgressView<>(); * view.setGraphicFactory(task -> return new ImageView("db-access.png")); * view.getTasks().add(new MyTask()); * </pre> */ public class TaskProgressView<T extends Task<?>> extends Control {/** * Constructs a new task progress view. */ public TaskProgressView() { getStyleClass().add("task-progress-view");EventHandler<WorkerStateEvent> taskHandler = evt -> { if (evt.getEventType().equals( WorkerStateEvent.WORKER_STATE_SUCCEEDED) || evt.getEventType().equals( WorkerStateEvent.WORKER_STATE_CANCELLED) || evt.getEventType().equals( WorkerStateEvent.WORKER_STATE_FAILED)) { getTasks().remove(evt.getSource()); } };getTasks().addListener(new ListChangeListener<Task<?>>() { @Override public void onChanged(Change<? extends Task<?>> c) { while (c.next()) { if (c.wasAdded()) { for (Task<?> task : c.getAddedSubList()) { task.addEventHandler(WorkerStateEvent.ANY, taskHandler); } } else if (c.wasRemoved()) { for (Task<?> task : c.getAddedSubList()) { task.removeEventHandler(WorkerStateEvent.ANY, taskHandler); } } } } }); }@Override protected Skin<?> createDefaultSkin() { return new TaskProgressViewSkin<>(this); }private final ObservableList<T> tasks = FXCollections .observableArrayList();/** * Returns the list of tasks currently monitored by this view. * * @return the monitored tasks */ public final ObservableList<T> getTasks() { return tasks; }private ObjectProperty<Callback<T, Node>> graphicFactory;/** * Returns the property used to store an optional callback for creating * custom graphics for each task. * * @return the graphic factory property */ public final ObjectProperty<Callback<T, Node>> graphicFactoryProperty() { if (graphicFactory == null) { graphicFactory = new SimpleObjectProperty<Callback<T, Node>>( this, "graphicFactory"); }return graphicFactory; }/** * Returns the value of {@link #graphicFactoryProperty()}. * * @return the optional graphic factory */ public final Callback<T, Node> getGraphicFactory() { return graphicFactory == null ? null : graphicFactory.get(); }/** * Sets the value of {@link #graphicFactoryProperty()}. * * @param factory an optional graphic factory */ public final void setGraphicFactory(Callback<T, Node> factory) { graphicFactoryProperty().set(factory); } The Skin As you might have expected the skin is using a ListView with a custom cell factory  to display the tasks. package impl.org.controlsfx.skin;import javafx.beans.binding.Bindings; import javafx.concurrent.Task; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ContentDisplay; import javafx.scene.control.Label; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.control.ProgressBar; import javafx.scene.control.SkinBase; import javafx.scene.control.Tooltip; import javafx.scene.layout.BorderPane; import javafx.scene.layout.VBox; import javafx.util.Callback;import org.controlsfx.control.TaskProgressView;import com.sun.javafx.css.StyleManager;public class TaskProgressViewSkin<T extends Task<?>> extends SkinBase<TaskProgressView<T>> {static { StyleManager.getInstance().addUserAgentStylesheet( TaskProgressView.class .getResource("taskprogressview.css").toExternalForm()); //$NON-NLS-1$ }public TaskProgressViewSkin(TaskProgressView<T> monitor) { super(monitor);BorderPane borderPane = new BorderPane(); borderPane.getStyleClass().add("box");// list view ListView<T> listView = new ListView<>(); listView.setPrefSize(500, 400); listView.setPlaceholder(new Label("No tasks running")); listView.setCellFactory(param -> new TaskCell()); listView.setFocusTraversable(false);Bindings.bindContent(listView.getItems(), monitor.getTasks()); borderPane.setCenter(listView);getChildren().add(listView); }class TaskCell extends ListCell<T> { private ProgressBar progressBar; private Label titleText; private Label messageText; private Button cancelButton;private T task; private BorderPane borderPane;public TaskCell() { titleText = new Label(); titleText.getStyleClass().add("task-title");messageText = new Label(); messageText.getStyleClass().add("task-message");progressBar = new ProgressBar(); progressBar.setMaxWidth(Double.MAX_VALUE); progressBar.setMaxHeight(8); progressBar.getStyleClass().add("task-progress-bar");cancelButton = new Button("Cancel"); cancelButton.getStyleClass().add("task-cancel-button"); cancelButton.setTooltip(new Tooltip("Cancel Task")); cancelButton.setOnAction(evt -> { if (task != null) { task.cancel(); } });VBox vbox = new VBox(); vbox.setSpacing(4); vbox.getChildren().add(titleText); vbox.getChildren().add(progressBar); vbox.getChildren().add(messageText);BorderPane.setAlignment(cancelButton, Pos.CENTER); BorderPane.setMargin(cancelButton, new Insets(0, 0, 0, 4));borderPane = new BorderPane(); borderPane.setCenter(vbox); borderPane.setRight(cancelButton); setContentDisplay(ContentDisplay.GRAPHIC_ONLY); }@Override public void updateIndex(int index) { super.updateIndex(index);/* * I have no idea why this is necessary but it won't work without * it. Shouldn't the updateItem method be enough? */ if (index == -1) { setGraphic(null); getStyleClass().setAll("task-list-cell-empty"); } }@Override protected void updateItem(T task, boolean empty) { super.updateItem(task, empty);this.task = task;if (empty || task == null) { getStyleClass().setAll("task-list-cell-empty"); setGraphic(null); } else if (task != null) { getStyleClass().setAll("task-list-cell"); progressBar.progressProperty().bind(task.progressProperty()); titleText.textProperty().bind(task.titleProperty()); messageText.textProperty().bind(task.messageProperty()); cancelButton.disableProperty().bind( Bindings.not(task.runningProperty()));Callback<T, Node> factory = getSkinnable().getGraphicFactory(); if (factory != null) { Node graphic = factory.call(task); if (graphic != null) { BorderPane.setAlignment(graphic, Pos.CENTER); BorderPane.setMargin(graphic, new Insets(0, 4, 0, 0)); borderPane.setLeft(graphic); } } else { /* * Really needed. The application might have used a graphic * factory before and then disabled it. In this case the border * pane might still have an old graphic in the left position. */ borderPane.setLeft(null); }setGraphic(borderPane); } } } } The CSS The stylesheet below makes sure we use a bold font for the task title, a smaller / thinner progress bar (without rounded corners), and list cells with a fade-in / fade-out divider line in their bottom position. .task-progress-view { -fx-background-color: white; }.task-progress-view > * > .label { -fx-text-fill: gray; -fx-font-size: 18.0; -fx-alignment: center; -fx-padding: 10.0 0.0 5.0 0.0; }.task-progress-view > * > .list-view { -fx-border-color: transparent; -fx-background-color: transparent; }.task-title { -fx-font-weight: bold; }.task-progress-bar .bar { -fx-padding: 6px; -fx-background-radius: 0; -fx-border-radius: 0; }.task-progress-bar .track { -fx-background-radius: 0; }.task-message { }.task-list-cell { -fx-background-color: transparent; -fx-padding: 4 10 8 10; -fx-border-color: transparent transparent linear-gradient(from 0.0% 0.0% to 100.0% 100.0%, transparent, rgba(0.0,0.0,0.0,0.2), transparent) transparent; }.task-list-cell-empty { -fx-background-color: transparent; -fx-border-color: transparent; }.task-cancel-button { -fx-base: red; -fx-font-size: .75em; -fx-font-weight: bold; -fx-padding: 4px; -fx-border-radius: 0; -fx-background-radius: 0; }Reference: New Custom Control: TaskProgressView from our JCG partner Dirk Lemmermann at the Pixel Perfect blog....
java-interview-questions-answers

JPA Tutorial: Mapping Entities – Part 3

In my last article I showed two different ways to read/write persistent entity state – field and property. When field access mode is used, JPA directly reads the state values from the fields of an entity using reflection. It directly translates the field names into database column names if we do not specify the column names explicitly.  In case of property access mode, the getter/setter methods are used to read/write the state values. In this case we annotate the getter methods of the entity states instead of the fields using the same annotations. If we do not explicitly specify the database column names then they are determined following the JavaBean convention, that is by removing the “get” portion from the getter method name and converting the first letter of the rest of the method name to lowercase character.   We can specify which access mode to use for an entity by using the @Access annotation in the entity class declaration. This annotation takes an argument of type AccessType (defined in the javax.persistence package) enum, which has two different values corresponding to two different access modes – FIELD and PROPERTY. As an example, we can specify property access mode for the Address entity in the following way: @Entity @Table(name = "tbl_address") @Access(AccessType.PROPERTY) public class Address { private Integer id; private String street; private String city; private String province; private String country; private String postcode; private String transientColumn;@Id @GeneratedValue @Column(name = "address_id") public Integer getId() { return id; }public Address setId(Integer id) { this.id = id; return this; }public String getStreet() { return street; }public Address setStreet(String street) { this.street = street; return this; }public String getCity() { return city; }public Address setCity(String city) { this.city = city; return this; }public String getProvince() { return province; }public Address setProvince(String province) { this.province = province; return this; }public String getCountry() { return country; }public Address setCountry(String country) { this.country = country; return this; }public String getPostcode() { return postcode; }public Address setPostcode(String postcode) { this.postcode = postcode; return this; } } Couple of points to note about the above example:As discussed before, we are now annotating the getter method of the entity id with the @Id, @GeneratedValue and @Column annotations. Since now column names will be determined by parsing the getter methods, we do not need to mark the transientColumn field with the @Transient annotation anymore. However if Address entity had any other method whose name started with “get”, then we needed to apply @Transient on it.If an entity has no explicit access mode information, just like our Address entity that we created in the first part of this series, then JPA assumes a default access mode. This assumption is not made at random. Instead, JPA first tries to figure out the location of the @Id annotation. If the @Id annotation is used on a field, then field access mode is assumed. If the @Id annotation is used on a getter method, then property access mode is assumed. So even if we remove the @Access annotation from the Address entity in the above example the mapping will still be valid and JPA will assume property access mode: @Entity @Table(name = "tbl_address") public class Address { private Integer id; private String street; private String city; private String province; private String country; private String postcode; private String transientColumn;@Id @GeneratedValue @Column(name = "address_id") public Integer getId() { return id; }// Rest of the class........ Some important points to remember about the access modes:You should never declare a field as public if you use field access mode. All fields of the entity should have either private (best!), protected or default access type. The reason behind this is that declaring the fields as public will allow any unprotected class to directly access the entity states which could defeat the provider implementation easily. For example, suppose that you have an entity whose fields are all public. Now if this entity is a managed entity (which means it has been saved into the database) and any other class changes the value of its id, and then you try to save the changes back to the database, you may face unpredictable behaviors (I will try to elaborate on this topic in a future article). Even the entity class itself should only manipulate the fields directly during initialization (i.e., inside the constructors). In case of property access mode, if we apply the annotations on the setter methods rather than on the getter methods, then they will simply be ignored.It’s also possible to mix both of these access types. Suppose that you want to use field access mode for all but one state of an entity, and for that one remaining state you would like to use property access mode because you want to perform some conversion before writing/after reading the state value to and from the database. You can do this easily by following the steps below:Mark the entity with the @Access annotation and specify AccessType.FIELD as the access mode for all the fields. Mark the field for which you do not like to use the field access mode with the @Transient annotation. Mark the getter method of the property with the @Access annotation and specify AccessType.PROPERTY as the access mode.The following example demonstrates this approach as the postcode has been changed to use property access mode: @Entity @Table(name = "tbl_address") @Access(AccessType.FIELD) public class Address { @Id @GeneratedValue @Column(name = "address_id") private Integer id;private String street; private String city; private String province; private String country; /** * postcode is now marked as Transient */ @Transient private String postcode; @Transient private String transientColumn;public Integer getId() { return id; }public Address setId(Integer id) { this.id = id; return this; }public String getStreet() { return street; }public Address setStreet(String street) { this.street = street; return this; }public String getCity() { return city; }public Address setCity(String city) { this.city = city; return this; }public String getProvince() { return province; }public Address setProvince(String province) { this.province = province; return this; }public String getCountry() { return country; }public Address setCountry(String country) { this.country = country; return this; }/** * We are now using property access mode for reading/writing * postcode */ @Access(AccessType.PROPERTY) public String getPostcode() { return postcode; }public Address setPostcode(String postcode) { this.postcode = postcode; return this; } } The important thing to note here is that if we do not annotate the class with the @Access annotation to explicitly specify the field access mode as the default one, and we annotate both the fields and the getter methods, then the resultant behavior of the mapping will be undefined. Which means the outcome will totally depend on the persistence provider i.e., one provider might choose to use the field access mode as default, one might use property access mode, or one might decide to throw an exception! That’s it for today. If you find any problems/have any questions, please do not hesitate to comment! Until next time.Reference: JPA Tutorial: Mapping Entities – Part 3 from our JCG partner Sayem Ahmed at the Random Thoughts blog....
jetbrains-intellijidea-logo

NetBeansIDE and IntellijIDEA From The Eyes of a Long Time Eclipse User

I have been using Eclipse IDE since 2006 and I liked it so much for various reasons. First it is open source and free to use. Eclipse looks pretty neat on Windows OS on which I work most of the time. Occasionally I tried to use NetBeansIDE (before 6.x version) and I didn’t like it because it’s too slow. And I never tried IntellijIDEA because it’s a commercial product and I am 100% sure that my employer is not going to pay $$$ for an IDE. So over the years I have been using JavaEE based Eclipse version and once I found SpringSource Tool Suite it became my default Java IDE for everything. I like Spring framework very much and I use Spring technologies everyday, both on personal and official projects. STS provides lot of additional features for Spring related technologies like auto-completion in spring xml files, beans graph etc etc. I should mention SpringBoot support in STS specifically. You can create SpringBoot applications with lot of customization options (which modules to use, java version, maven/gradle, java/groovy etc) right from the IDE itself. As of now no other IDE has this much of good support for SpringBoot. But as everyone knows working with Eclipse isn’t fun all the times. It has it’s own set of problems. I get used to see the NullPointerException or  IllegalArgumentException error alerts all the times. When you press Ctrl + Space you may get auto completion suggestion or get an error alert. If you type too fast and press Ctrl+Space many times then Eclipse might disappear and shows a big alert box with very useful details. If you have many open projects in your workspace and if it contains JPA/JSF/JAX-WS/JAX-RS modules then as soon as you opened your Eclipse it may stuck in Building Workspace state forever. The only way to solve it is End Process via Task Manager. Till this point its bearable. If you install any plugin which contain any conflicting XML libraries then the real problems start. As soon as you open pom.xml you will get to see error alerts repeatedly, you can’t even close it..it keeps popping up the error alerts. If you are lucky then restarting eclipse might solve the issue or you have to try uninstalling the newly installed plugin(which never solved the problem for me) or start with a new Eclipse altogether. Even after all these pains I stick to Eclipse because I get used to it. As I said I have been using STS and till STS-3.5.1 version it’s fine and I am OK to live with all the previously mentioned pain points. But once I downloaded STS-3.6.0 and started using it, things get even worse. First, Gradle plugin didn’t work. After googling for a while there is already a bug filed regarding the same issue. I thought this may be resolved in STS-3.6.1 release but it is not. Then I upgraded Gradle plugin with nightly build and it started working fine. I am very happy. Then I started my SpringBoot application and it worked fine. Great!!. Then I opened another Java class and made some changes and tried to click on Relaunch button. As soon as mouse cursor is on Relaunch button it is showing error alert. Navigate to any other file and put cursor on Relaunch button then again it will show error alert. What the hell!! For almost 4 days I was struggling with these kind of issues only. I Haven’t ever started writing code at all. I told myself “Enough!! Shut this f***king eclipse and start using some better IDE, come out of you Eclipse comfort zone”. I have been playing with NetBeansIDE every now and then, and I am aware that NetBeansIDE got lot better than its previous versions, especially from 7.x onwards its very fast and feature rich. A year ago I tried IntellijIDEA Ultimate edition with trial version and it’s totally confusing to me because of my prior Eclipse experience. When I google for “Eclipse vs NetBeansIDE vs IntellijIDEA” there are lots of articles comparing them and almost every article ends with a conclusion that “IntellijIDEA > NetBeansIDE > Eclipse”. But I though of trying NetBeansIDE and IntellijIDEA myself. So I installed NetBeansIDE 8.0.1 and IntellijIDEA Ultimate Edition 13. How I feel about NetBeansIDE: First thing I noticed is NetBeansIDE totally improved over its previous versions. It is fast and feature rich. Pros:You will get most the Java stuff that you need out-of-the-box. You don’t need to hunt for plugins. If your project is based on JavaEE technologies like CDI/EJB/JPA/JSF/JAX-RS then you will love NetBeansIDE. It has awesome code generators for JPA Entities from Database, JSF views from Entities, JAX-RS resource from Entities etc. Its Maven support is fantastic. Looking up and adding dependencies works out-of-the-box. No need to check “Download Indexes at startup” and perform Rebuild Indexes…You know what I mean! Great support for HTML5 technologies, especially AngularJS. Auto completion for AngularJS directives is amazing. You can download and install many of the popular Javascript libraries right from the IDE itself. It has very good Java8 support. It even shows code recommendations to turn for-loops into Java8 streams and lambdas. Recently I am learning Mobile App development using PhoneGap/Cordova. Getting started with Cordova in NetBeans is a piece of cake.Cons:No workspace concept. For some people it could be an advantage, but for me its a disadvantage. Usually I maintain multiple workspaces for different projects and at times I would like to open them in parallel. Opening multiple NetBeans IDEs is possible, but it should not be that difficult. At home I installed NB 8.0.1 and Wildlfy 8.0.0.FINAL and worked well. The very same day Wildlfy 8.1.0.FINAL got released and at office I tried to run an app using NB 8.0.1 and Wildlfy 8.1.0.FINAL and it’s not working at all. After pulling off my hair for few hours I figured it out that NB 8.0.1 doesn’t work with Wildlfy 8.1.0 version yet. That’s a little bit odd!! Wildlfy changed that much from 8.0.0 to 8.1.0???? I just created a web application and tried to deploy on Tomcat, what should go wrong!! But while deployment its failing. After struggling for few minutes and found answer in StackOverflow that it might be because of Proxy issue. After configuring my corporate proxy details in NetBeans its working fine. But this is not cool. Deploying an app on my local tomcat should not worry about Proxy..right??!!?? There is no shortcut for block comment!!! Come on…Overall I liked NetBeans IDE very much. Being an open source and Free IDE NetBeans is awesome. How I feel about IntellijIDEA: Whenever I read about IntellijIDEA user experience, I always here “wow”, “amazing”,”can’t go back to Eclipse/NB” and “I don’t mind paying $$$ for such a wonderful tool”!!. But I struggled a bit to get used to its Project/Module style of code organization because of my previous Eclipse Workspace/Project style experience. Still I am not very comfortable with it but it’s not a blocker. Pros:No random NullPointerException/IllegalArgumentException exception alerts. Everything can be done from IDE itself. Be it Working with Database, tinkering from Command Prompt, Maven/Gradle tasks execution, RestClient etc etc. AutoCompletion support is just mind blowing. Type sort and Ctrl+Space twice showing sort methods from all Java classes. Wonderful. Interaction with many Version Control Systems works smoothly. Support for other IDE’s key bindings.Cons: Well, following may not be really Cons, but from an Eclipse user perspective following are confusing and difficult to get use to it: Project/Module style code organization is very different from other IDEs. I terribly miss right clicking on a web project and choosing Run on Server. It took me 30 mins to figure out how to run a web application on IntellijIDEA. Please provide an option “Run on Server” and open Edit Configuration window to choose the Server and other stuff.Actually, it is too early for me to say whether IntellijIDEA is best or not because still I am learning to do things in Intellij way. But I can clearly sense that IntellijIDEA is very addictive because of its Editing capabilities and “Everything from IDE” experience. But the major issue is it is very costly and I am 100% sure that my employer won’t pay for IDE though its great productivity booster. I am actually considering to use IntellijIDEA Community Edition also because it has Java/Groovy/Maven/Gradle support. And SpringBoot can be run as a standalone Java program and no need of Server support. Overall I feel it is powerful and feature rich IDE and I just need to understand the IntellijIDEA way of doing things. What Eclipse features I missed from NetbeansIDE/IntellijIDEA: After playing with NetBeansIDE and IntellijIDEA, I feel Eclipse is better in the following aspects:Support for multiple workspaces and multiple instances Eclipse color scheme for Java editor is pleasant than NetBeans glassy look and IntellijIDEA’s dull grey look. Sensible Eclipse shortcut key bindings. Many of the key bindings don’t include crazy combination of Ctrl+Shift+Alt as in IntellijIDEA. Maven pom editor’s Dependency Hierarchy Tab view which provides a neat view of “from where this jar dependency came”. Simple tree structure looks better than fancy graphs to me.Conclusion: All in all, what I came to know is most of the things that you do in one IDE can also be done in other IDEs as well. It is just a matter of getting use to the selected IDEs way of doing things. But if you are spending lot of time fighting with IDE itself then it’s a red flag. You should consider moving to a better IDE. After playing with NetBeans and IntellijIDEA I came to the conclusion that:If you have to work with JavaEE projects heavily go with NetBeans. If you can get a license for IntellijIDEA that’s great, if not choose a stable version of STS and live with it. Don’t just upgrade your Eclipse/STS because there is a newer version released. Newer not always means better.Reference: NetBeansIDE and IntellijIDEA From The Eyes of a Long Time Eclipse User from our JCG partner Siva Reddy at the My Experiments on Technology blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close