DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones Build AI Agents That Are Ready for Production
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
Build AI Agents That Are Ready for Production

LIVE: “Cognitive Databases, Intelligent Data: Unified Infrastructure for Vector Search, AI-Optimized Queries, & Hybrid Workloads" Report

Live Webinar: Exclusive practitioner summit on AI-powered CDN operations and real-world automation strategies

The Latest Java Topics

article thumbnail
Dive into your JVM with New Relic
this post comes from ashley puls at the new relic blog. if you’ve been looking for deeper insight into your jvm and application server, we’ve got some good news for you. the latest release of the new relic java agent includes an increase in the amount of data we collect on your java applications and these new metrics can be used to solve a multitude of performance problems. the new metrics are located under the jvm tab and include the following: * loaded and unloaded class count for the jvm * active thread count for the jvm * active and idle thread count for each thread pool * the ratio of active to maximum thread count for each thread pool * active, expired and rejected http session counts per application * active, finished and created transaction counts per application server now let’s take a closer look at each of them: loaded & unloaded class count location: under the memory tab in the bottom-right corner of the screen. supported application servers: all application servers that have jmx enabled. use cases: the loaded and unloaded class count can be used for a variety of purposes. for example, if the loaded class count is constantly going up, then the app server or a class loader may have a bug. or if you perform upgrades without bringing down the jvm, you can use it to verify that classes were unloaded and then reloaded. active thread count location: under the threads tab. supported application servers: all application servers that have jmx enabled. use cases: you can use the thread count to determine how many active threads are running in your application. this is useful for determining usage trends. for example, it can show the time of day and the day of the week in which you usually reach peak thread count. in addition, the creation of too many threads can result in out of memory errors or thrashing. by watching this metric, you can reduce excessive memory consumption before it’s too late. thread pool metrics location: under the threads tab. supported application servers: tomcat, jboss 5 and 6, resin, jetty, weblogic, tomee, glassfish, and websphere use cases: thread pools are typically used to service multiple requests simultaneously. however, to get the best throughput, thread pools must be configured appropriately. for example, if the maximum thread count is set too high, the app will slow down from excessive memory usage. but if the maximum thread count is too low, it will cause requests to block or timeout. you can use these metrics to see if you are reaching the maximum thread count in a pool. in addition, they can be used to tune other properties – such as the amount of time before an idle thread is destroyed and the frequency of when new threads are created. this graph displays information on the http-bio-8080 thread pool on a tomcat 7.0 application server. it shows that the thread pool starts with 10 idle threads and never handles more than five active requests at a time. the 0.23% capacity indicates that the number of active threads is well under the limit. session metrics location: under the http sessions tab. supported application servers: tomcat, jboss 5 and 6, resin, tomee, glassfish, and websphere use cases: http session information is used to determine usage trends such as the time of day when an application is getting the most amount of traffic. it can also be used to tune configuration properties such as the maximum number of active sessions allowed at one time and the amount of time a session remains active. for example, a high rejected session count usually indicates that the maximum active session count should be increased. meanwhile, a high expired session count can suggest that the session timeout is too low. the graphs below show session information for two applications. the first indicates that a maximum of two sessions have been created for the application ‘examples’, but the sessions are constantly expiring. after increasing the timeout, the number of expired sessions reduces to zero. from the second graph, we see that zero sessions have been created for the application ‘host-manager’. transaction metrics location: under the app server transaction tab. supported application servers: jboss 7, resin, and glassfish use cases: these metrics show info on transactions that go through the application server’s transaction manager. they are used to show transaction traffic patterns and help to configure the transaction manager. get started today new relic uses java management extensions (jmx) to gather data on these new metrics. before you get started using these new metrics, you must update to our latest java agent and enable jmx on your application server. you can also set up new relic to show custom jmx metrics. to see how to display custom metrics, watch this video .
May 13, 2013
by Leigh Shevchik
· 10,186 Views
article thumbnail
Java 8: Definitive Guide to CompletableFuture
While Java 7 and Java 6 were rather minor releases, version 8 will be a big step forward.
May 13, 2013
by Tomasz Nurkiewicz
· 83,210 Views · 7 Likes
article thumbnail
Hibernate 3 with Spring
1. Overview This article will focus on setting up Hibernate 3 with Spring – we’ll look at how to configure Spring 3 with Hibernate 3 using both Java and XML Configuration. 2. Maven To add the Spring Persistence dependencies to the pom, please see the Spring with Maven article. Continuing with Hibernate 3, the Maven dependencies are simple: org.hibernate hibernate-core 3.6.10.Final Then, to enable Hibernate to use its proxy model, we need javassist as well: org.javassist javassist 3.17.1-GA And since we’re going to use MySQL for this tutorial, we’ll also need: mysql mysql-connector-java 5.1.25 runtime 3. Java Spring Configuration for Hibernate 3 Setting up Hibernate 3 with Spring and Java configuration is straightforward: import java.util.Properties; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate3.HibernateTransactionManager; import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; import com.google.common.base.Preconditions; @Configuration @EnableTransactionManagement @PropertySource({ "classpath:persistence-mysql.properties" }) @ComponentScan({ "org.baeldung.spring.persistence" }) public class PersistenceConfig { @Autowired private Environment env; @Bean public AnnotationSessionFactoryBean sessionFactory() { AnnotationSessionFactoryBean sessionFactory = new AnnotationSessionFactoryBean(); sessionFactory.setDataSource(restDataSource()); sessionFactory.setPackagesToScan(new String[] { "org.baeldung.spring.persistence.model" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean public DataSource restDataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); dataSource.setUrl(env.getProperty("jdbc.url")); dataSource.setUsername(env.getProperty("jdbc.user")); dataSource.setPassword(env.getProperty("jdbc.pass")); return dataSource; } @Bean public HibernateTransactionManager transactionManager() { HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(sessionFactory().getObject()); return txManager; } @Bean public PersistenceExceptionTranslationPostProcessor exceptionTranslation() { return new PersistenceExceptionTranslationPostProcessor(); } Properties hibernateProperties() { return new Properties() { { setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); setProperty("hibernate.dialect", env.getProperty("hibernate.dialect")); } }; } } Compared to the XML Configuration – described next – there is a small difference in the way one bean in the configuration access another. In XML there is no difference between pointing to a bean or pointing to a bean factory capable of creating that bean. Since the Java configuration is type-safe – pointing directly to the bean factory is no longer an option – we need to retrieve the bean from the bean factory manually: txManager.setSessionFactory(sessionFactory().getObject()); 4. XML Spring Configuration for Hibernate 3 Simillary, Hibernate 3 can be configured using XML Configuration as well: ${hibernate.hbm2ddl.auto} ${hibernate.dialect} Then, this XML file is boostrapped into the Spring context: @Configuration @EnableTransactionManagement @ImportResource({ "classpath:persistenceConfig.xml" }) public class PersistenceXmlConfig { // } For both types of configuration, the JDBC and Hibernate specific properties are stored in a properties file: # jdbc.X jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring_hibernate_dev?createDatabaseIfNotExist=true jdbc.user=tutorialuser jdbc.pass=tutorialmy5ql # hibernate.X hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=false hibernate.hbm2ddl.auto=create-drop 5. Spring, Hibernate and MySQL The example above uses MySQL 5 as the underlying database configured with Hibernate – however, Hibernate supports several underlying SQL Databases. 5.1. The Driver The Driver class name is configured via the jdbc.driverClassName property provided to the DataSource. In the example above, it is set to com.mysql.jdbc.Driver from the mysql-connector-java dependency we defined in the pom, at the start of the article. 5.2. The Dialect The Dialect is configured via the hibernate.dialect property provided to the Hibernate SessionFactory. In the example above, this is set to org.hibernate.dialect.MySQL5Dialect as we are using MySQL 5 as the underlying Database. There are several other dialects supporting MySQL: org.hibernate.dialect.MySQL5InnoDBDialect – for MySQL 5.x with the InnoDB storage engine org.hibernate.dialect.MySQLDialect – for MySQL prior to 5.x org.hibernate.dialect.MySQLInnoDBDialect – for MySQL prior to 5.x with the InnoDB storage engine org.hibernate.dialect.MySQLMyISAMDialect – for all MySQL versions with the ISAM storage engine Hibernate supports SQL Dialects for every supported Database. 6. Usage At this point, Hibernate 3 is fully configured with Spring and we can inject the raw HibernateSessionFactory directly whenever we need to: public abstract class FooHibernateDAO{ @Autowired SessionFactory sessionFactory; ... protected Session getCurrentSession(){ return sessionFactory.getCurrentSession(); } } 7. Conclusion In this example, we configured Hiberate 3 with Spring – both with Java and XML configuration. The implementation of this simple project can be found in the github project – this is an Eclipse based project, so it should be easy to import and run as it is.
May 8, 2013
by Eugen Paraschiv
· 12,974 Views · 1 Like
article thumbnail
How to Create a Web Service Using Java, Eclipse, and Tomcat
This tutorial runs through a method for building a Java web service in Eclipse using Apache Tomcat and Apache Axis. The process takes under ten minutes.
May 8, 2013
by Mitch Pronschinske
· 175,730 Views · 1 Like
article thumbnail
Software Development Macro and Micro Process
If you think that in year 2012 all companies which produce software and IT divisions in our world have already their optimized software development process, you are wrong. It seems that we - software architects, software developers or whatever your title is - still need to optimize the software development process in many software companies and IT divisions. So what do you do if you enter a software company or IT division and you see following things: 1. There is a perfect project management process to handle all those development of software but it is a pure project management without a context to software development. So basically you only take care of cost, time, budget and quality factors. In the software development you still use the old fashioned waterfall process. 2. From the tooling point of view: you have a project management planning and controlling tool but you are still in the beginning of Wiki (almost no collaboration tool) and you don't use issues tracking system to handle all the issues for the development of your software components and applications. You use Winword and Excel to define your requirements and you cannot transform them to your software products since you don't have any isssues tracking system. No chance to have traceability from your requirements down to your issues to be done in your software components and applications. 3. Maven is already used but with a lot customization and not intuitively used. The idea of using a concrete already released version of dependencies was not implemented. Instead you always open all the dependently projects in Eclipse. You can imagine how slow Eclipse works since you need to open a lot of projects at once although you only work for one project. Versioning in Maven is also not used correctly e.g.: no SNAPSHOT for development versions. 4. As you work with webapp you always need to redeploy to the application server. No possibility to hot deploy the webapp. Use ctrl-s, see your changes and continue to work without new deployment is just a dream and not available. Luckily as an experienced software architect and developer we know that we can optimize the two main software development processes: 1. Software Development Macro Process (SDMaP): this is the overall software development lifecycle. In this process model we define our requirements, we execute analysis, design, implementation, test and we deploy the software into production. Waterfall process model and agile process model like RUP and Scrum are examples of SDMaP. 2. Software Development Micro Process (SDMiP): this is the daily work of a software developer. How a software developer works to develop the software. A software developer codes, refactors, compiles, tests, runs, debugs, packages and deploys the software. More information on SDMaP and SDMiP: You can find the definition of SDMaP and SDMiP in the context of analysis and design in the book Object-Oriented Analysis and Design with Applications from Grady Booch, et. al. Unifying Microprocess and Macroprocess Research Effects of Architecture and Technical Development Process on Micro-Process The picture below shows the SDMaP and SDMiP in combination. The macro (SDMaP) and micro (SDMiP) process meet at the implementation phase and activity. So changing and optimizing one has definitely side effects on the other one and vice versa. At the example of organization mentioned above it is important that we optimize both processes since they work hand in hand. So how can the optimization for macro and micro process looks like? 1. SDMaP: Introduce Wiki for IT divisions and software companies. You can use WikIT42 to make the structure of your Wiki and use Confluence as your Wiki platform. Introduce Wiki with issue tracking like JIRA and combine both of them to track your requirements. Refine the requirements into issues (features, tasks, bugs, etc.) to the level of the software components and applications, because at the end you will implement all the requirements using your software components and applications. Introduce iterative software development lifecycle instead of waterfall process. This is a long way to go since you need to change the culture of the company and you need a full support from your management. 2. SDMiP Update the Maven projects to use the standard Maven mechanism and best practices with no exception. Transform the structure of the old Maven to the new standard Maven using frameworks like MoveToMaven. Use Maven release plugin to standardize the release mechanism of all Maven projects. Use m2e Eclipse plugin to optimize your daily work as a software developer under Eclipse and Maven. Use Mylyn to integrate your issue tracking system like JIRA into your Eclipse IDE. Introduce JRebel to be able to hot deploy quickly your webapps into the application server. Optimizing macro and micro process for software development is not an easy task. In the macro process you need to handle all those relationships with other divisions like Business Requirements, Quality Assurance and Project Management divisions. You need to convince them that your SDMaP optimization is the best way to go. This is more an organizational challenge and changes than the micro process optimization. The micro process is also not easy to optimize, since you need to convince all developers that they can be more productive with the new way of working than before. You need to show them that it is a lot more faster if you don't open a lot of Java projects within your Eclipse workspace. Also using JRebel to deploy your webapp to your application server is the best way to go. Normally developers are technical oriented, so if you can show them the cool things to make, they will join your way.
May 4, 2013
by Lofi Dewanto
· 27,706 Views
article thumbnail
CouchDB: Adding Document Using Java Couchdb4j
Couchdb4j is a library for Couch Database for manipulating document in database. The jar file :- http://code.google.com/p/couchdb4j/downloads/list In this Demo ,"A new Student document is created with properties nad added to the student database". Project structure:- The Java code CouchDBTest.java is , package com.sandeep.couchdb.util; import java.util.HashMap; import java.util.Map; import com.fourspaces.couchdb.Database; import com.fourspaces.couchdb.Document; import com.fourspaces.couchdb.Session; public class CouchDBTest { /*These are the keys of student document in couch db*/ public static final String STUDENT_KEY_NAME ="name"; public static final String STUDENT_KEY_MARKS ="marks"; public static final String STUDENT_KEY_ROLL="roll"; public static void main(String[] args){ /*Creating a session with couch db running in 5984 port*/ Session studentDbSession = new Session("localhost",5984); /*Selecting the 'student' database from list of couch database*/ Database studentCouchDb = studentDbSession.getDatabase("student"); /*Creating a new Document*/ Document newdoc = new Document(); /*Map for list of properties for the new document*/ Map properties = new HashMap(); properties.put(STUDENT_KEY_NAME, "saan"); properties.put(STUDENT_KEY_MARKS, "67"); properties.put(STUDENT_KEY_ROLL, "12"); /*Adding all the properties to the new document*/ newdoc.putAll(properties); /*Saving the new document in the 'student' database */ studentCouchDb.saveDocument(newdoc); } } We can open the Futon and verify that the document is added to "student" Database.The screenshot,
April 30, 2013
by Sandeep Patel
· 7,296 Views
article thumbnail
How to Integrate JavaFX into a NetBeans Platform Wizard (Part 1)
When working within the NetBeans Platform, Swing is King. JavaFX is the crown prince. However, some developers avoid developing GUI controls with JavaFX in the NetBeans Platform because Swing is available by default. Well, it is possible to develop your JavaFX forms and simply replace the default NetBeans panels. The following tutorial explains how a developer can take a JavaFX GUI form and FXML developed using Scene Builder and replace a NetBeans Platform Wizard visual panel with minimal effort. Now, why would this concept be useful? Well, consider a development team where new Java applications are being written in JavaFX. Why rewrite the useful Panel classes to Swing just to use them within a NetBeans Platform Wizard? Why force new form development to be in Swing just to be compatible with a NetBeans Platform application? NetBeans Platform applications are perfectly capable of rendering JavaFX interop'd with Swing. Here's how: First you will need to do a little prep work to setup an application for this tutorial. Do the following: Create the JavaFX GUI. Create a new JavaFX FXML GUI using SceneBuilder. Add the controls you want and generate your FXML file and controller class. Update your Controller Class by Extending JFXPanel. This is part of the Swing Interop pattern that we all know and love. You will also need to @Override the getName() method so that the wizard framework can update the current step title. Encapsulate fields/values. Create public methods that will provide Wizard framework with the fields it needs to pass from panel to panel. This is the same thing you would need to do with a standard Swing Wizard JPanel class. The code for your controller class still runs without a problem within your JavaFX application but is now Swing Interop compatible. The code might look like this: package jfxwizpanel.jfxwiz; import java.io.File; import java.net.URL; import java.util.ResourceBundle; import javafx.embed.swing.JFXPanel; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.stage.FileChooser; /** * * @author SPhillips (King of Australia) */ public class WizPanelController extends JFXPanel implements Initializable { @FXML // fx:id="browseButton" private Button browseButton; // Value injected by FXMLLoader @FXML // fx:id="pathText" private TextField pathText; //Field that Path is stored in private String filePath = ""; //some value to pass to the next Wizard panel // Handler for Button[fx:id="browseButton"] onAction public void handleButtonAction(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Select File"); //Show open file dialog File file = fileChooser.showOpenDialog(null); if(file!=null) { setFilePath(file.getPath()); pathText.setText(filePath); } } @Override // This method is called by the FXMLLoader when initialization is complete public void initialize(URL fxmlFileLocation, ResourceBundle resources) { assert browseButton != null : "fx:id=\"browseButton\" was not injected: check your FXML file 'WizPanel.fxml'."; assert pathText != null : "fx:id=\"pathText\" was not injected: check your FXML file 'WizPanel.fxml'."; // initialize your logic here: all @FXML variables will have been injected } @Override //This method is used by Wizard Framework to generate list of steps public String getName() { return "FXML JFXPanel"; } /** * @return the filePath */ public String getFilePath() { return filePath; } /** * @param filePath the filePath to set */ public void setFilePath(String filePath) { this.filePath = filePath; } } And when you run this Code within the JavaFX FXML application you get something like the following screenshot: Create the NetBeans Platform Application. Create a new NetBeans Platform application and add a new module. Add a Wizard using the "Wizard" Wizard. Include the JavaFX Runtime. Create a NetBeans library wrapper module to include "jfxrt.jar" and set a dependency on it in the module described above. Copy Controller class and FXML file. As of NetBeans 7.3 you cannot refactor copy these files from your JavaFX FXML project to your NetBeans Platform application package. After manually copying these two files you will need to do a manual replace of the package path in both the Controller class and the fx:controller string in the FXML file. Your FXML code might now look something like this: Replace Swing Panel with FXML Controller. At this point you can replace the autogenerated Swing JPanel class that would normally be loaded by the Wizard control class with your JavaFX FXML controller. Remember we extended JFXPanel and it pays off here. All we have to do now is follow our standard Swing Interop technique. However this time we have to use our Platform.runLater() pattern in the getComponent() method of the Wizard controller class. Below is the relevant code after the update. Notice how little we had to change: public class JfxwizWizardPanel1 implements WizardDescriptor.Panel { /** * The visual component that displays this panel. If you need to access the * component from this class, just use getComponent(). */ //private JfxwizVisualPanel1 component; public WizPanelController component; //Replaces original autogenerated JPanel class // Get the visual component for the panel. In this template, the component // is kept separate. This can be more efficient: if the wizard is created // but never displayed, or not all panels are displayed, it is better to // create only those which really need to be visible. @Override public WizPanelController getComponent() { if (component == null) { component = new WizPanelController(); //return new JFXPanel controller Platform.setImplicitExit(false); Platform.runLater(new Runnable() { @Override public void run() { createScene(); //standard Swing Interop Pattern } }); } return component; } private void createScene() { try { URL location = getClass().getResource("WizPanel.fxml"); //same FXML copied from JavaFX app FXMLLoader fxmlLoader = new FXMLLoader(); fxmlLoader.setLocation(location); fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory()); Parent root = (Parent) fxmlLoader.load(location.openStream()); Scene scene = new Scene(root); component.setScene(scene); component = (WizPanelController) fxmlLoader.getController(); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } At this point, you should be able to resolve any import issues, compile and run. You should see your JavaFX GUI nicely loaded within the Wizard Dialog frame like the screenshot below: Wow that's awesome that you can load JavaFX GUIs into your wizards. But you didn't do anything with the information, so you didn't actually leverage the WizardDescriptor framework.
April 26, 2013
by Sean Phillips
· 22,712 Views
article thumbnail
Constructors of Sub and Super Classes in Java?
this post summarizes some commonly asked questions from stackoverflow.com. 1. why creating an object of the sub class invokes also the constructor of the super class? class super { string s; public super(){ system.out.println("super"); } } public class sub extends super { public sub(){ system.out.println("sub"); } public static void main(string[] args){ sub s = new sub(); } } it prints: super sub when inheriting from another class, super() has to be called first in the constructor. if not, the compiler will insert that call. this is why super constructor is also invoked in the code above. this doesn’t create two objects, only one sub object. the reason to have super constructor called is that if super class could have private fields which need to be initialized by its constructor. after compiler inserts the super constructor, the sub class constructor looks like the following: public sub(){ super(); system.out.println("sub"); } 2. a common error message: implicit super constructor is undefined for default constructor this is a compilation error message seen by a lot of java developers. “implicit super constructor is undefined for default constructor. must define an explicit constructor” this compilation error is caused because the super constructor is undefined. in java, if a class does not define a constructor, compiler will insert a default one for the class, which is argument-less. if a constructor is defined, e.g. super(string s), compiler will not insert the default argument-less one. this is the situation for the super class above. since compiler tries to insert super() to the 2 constructors in the sub class, but the super’s default constructor is not defined, compiler reports the error message. to fix this problem, simply add the following super() constructor to the super class, or remove the self-defined super constructor. public super(){ system.out.println("super"); } 3. explicitly call super constructor in sub constructor the following code is ok: the sub constructor explicitly call the super constructor with parameter. the super constructor is defined, and good to invoke. 4. the rule in brief, the rules is: sub class constructor has to invoke super class instructor, either explicitly by programmer or implicitly by compiler. for either way, the invoked super constructor has to be defined. 5. the interesting question why java doesn’t provide default constructor, if class has a constructor with parameter(s)? some answers: http://stackoverflow.com/q/16046200/127859
April 26, 2013
by Ryan Wang
· 59,897 Views · 1 Like
article thumbnail
Maven Deploy to Nexus
1. Overview In a previous article, I discussed how a Maven project can locally install a third party jar that has not yet been deployed on Maven central (or on any of the other large and publicly hosted repositories). That solution should only be applied in small projects where installing, running and maintaining a full Nexus server may be overkill. However, as a project grows, Nexus quickly becomes the only real and mature option for hosting third party artifacts, as well as for reusing internal artifacts across development streams. This article will show how to deploy the artifacts of a project to Nexus, with Maven. 2. Nexus requirements in the pom In order for Maven to be able to deploy the artifacts it creates in the package phase of the build, it needs to define the repository information where the packaged artifacts will be deployed, via the distributionManagement element: nexus-snapshots http://localhost:8081/nexus/content/repositories/snapshots A hosted, public Snapshots repository comes out of the box on Nexus, so there’s no need to create or configure anything further. Nexus makes it easy to determine the URLs of its hosted repositories – each repository displays the exact entry to be added in the of the project pom, under the Summary tab. 3. The plugins By default, Maven handles the deployment mechanism via the maven-deploy-plugin – this mapped to the deployment phase of the default Maven lifecycle: maven-deploy-plugin 2.7 default-deploy deploy deploy The maven-deploy-plugin is a viable option to hanldle the task of deploying to artifacts of a project to Nexus, but it was not built to take full advantage of what Nexus has to offer. Because of that fact, Sonatype built a Nexus specific plugin – the nexus-staging-maven-plugin – that is actually designed to take full advantage of the more advanced functionality that Nexus has to offer – functionality such as staging. Although for a simple deployment process we do not require staging functionality, we will go forward with this custom Nexus plugin since it was built with the clear purpose to talk to Nexus well. The only reason to use the maven-deploy-plugin is to keep open the option of using an alternative to Nexus in the future – for example an Artifactory repository. However, unlike other components that may actually change throughout the lifecycle of a project, the Maven Repository Manager is highly unlikely to change, so that flexibility is not required. So, the first step in using another deployment plugin in the deploy phase is to disable the existing, default mapping: org.apache.maven.plugins maven-deploy-plugin ${maven-deploy-plugin.version} true Now, we can define: org.sonatype.plugins nexus-staging-maven-plugin 1.3 default-deploy deploy deploy nexus http://localhost:8081/nexus/ true The deploy goal of the plugin is mapped to the deploy phase of the Maven build. Also notice that, as discussed, we do not need staging functionality in a simple deployment of -SNAPSHOT artifacts to Nexus, so that is fully disabled via the element. 4. The Global settings.xml Deployment to Nexus is a secured operation – and a deployment user exists for this purpose out of the box on any Nexus instance. Configuring Maven with the credentials of this deployment user, so that it can interact correctly with Nexus, cannot be done in the pom.xml of the project. This is because the syntax of the pom doesn’t allow it, not to mention the fact that the pom may be a public artifact, so not well suited to hold credential information. The credentials of the server has to be defined in the global Maven setting.xml: nexus-snapshots deployment the_pass_for_the_deployment_user The server can also be convigured to use key based security instead of raw and plaintext credentials. 5. The deployment process Performing the deployment process is a simple task: mvn clean deploy -Dmaven.test.skip=true Skipping tests is OK in the context of a deployment job, because this job should be the last job from a deployment pipline for the project. A common example of such a deployment pipeline would be a succession of Jenkins jobs, each triggering the next only if it completletes succesfully. As such, it is the responsibility of the previous jobs in the pipeline to run all tests suites from the project – by the time the deployment job runs, all tests should already pass. If ran a a single command, then tests can be kept active to run before the deployment phase executes: mvn clean deploy 6. Conclusion This is a simple, yet highly effective solution to deploying to Maven artifacts to Nexus. It is also somewhat oppinionated – nexus-staging-maven-plugin is used instead of the default maven-deploy-plugin; staging functionality is disabled, etc – it is these choices that make the solution simple and practical. Potentially activating the full staging functionality can be the subject of a future article. Finally, we’ll discuss the Release Process in the next article.
April 24, 2013
by Eugen Paraschiv
· 43,549 Views · 2 Likes
article thumbnail
XStream – XStreamely Easy Way to Work with XML Data in Java
from time to time there is a moment when we have to deal with xml data. and most of the time it is not the happiest day in our life. there is even a term “xml hell” describing situation when programmer has to deal with many xml configuration files that are hard to comprehend. but, like it or not, sometimes we have no choice, mostly because specification from client says something like “use configuration written in xml file” or something similar. and in such cases, xstream comes with its very cool features that make dealing with xml really less painful. overview xstream is a small library to serialize data between java objects and xml. it’s lightweight, small, has nice api and what is most important, it works with and without custom annotations that we might be not allowed to add when we are not the owner of java classes. first example suppose we have a requirement to load configuration from xml file: /users/tomek/work/mystuff/input.csv /users/tomek/work/mystuff/truststore.ts /users/tomek/work/mystuff/cn-user.jks password password user secret and we want to load it into configuration object: public class configuration { private string inputfile; private string user; private string password; private string truststorefile; private string keystorefile; private string keystorepassword; private string truststorepassword; // getters, setters, etc. } so basically what we have to do is: filereader filereader = new filereader("config.xml"); // load our xml file xstream xstream = new xstream(); // init xstream // define root alias so xstream knows which element and which class are equivalent xstream.alias("config", configuration.class); configuration loadedconfig = (configuration) xstream.fromxml(filereader); and that’s all, easy peasy something more serious ok, but previous example is very basic so now let’s do something more complicated: real xml returned by real webservice. 2013-03-09 john example 24 asd123123 2012-03-10 anna baker 26 axn567890 2010-12-05 tom meadow sgh08945 48 what we have here is simple list of bans written in xml. we want to load it into collection of ban objects. so let’s prepare some classes (getters/setters/tostring omitted): public class data { private list bans = new arraylist(); } public class ban { private string dateofupdate; private person person; } public class person { private string firstname; private string lastname; private int age; private string documentnumber; } as you can see there is some naming and type mismatch between xml and java classes (e.g. field name1->firstname, dateofupdate is string not a date), but it’s here for some example purposes. so the goal here is to parse xml and get data object with populated collection of ban instances containing correct data. let’s see how it can be achieved. parse with annotations first, easier way is to use annotations. and that’s the suggested approach in situation when we can modify java classes to which xml will be mapped. so we have: @xstreamalias("data") // maps data element in xml to this class public class data { // here is something more complicated. if we have list of elements that are // not wrapped in a element representing a list (like we have in our xml: // multiple elements not wrapped inside collection, // we have to declare that we want to treat these elements as an implicit list // so they can be converted to list of objects. @xstreamimplicit(itemfieldname = "ban") private list bans = new arraylist(); } @xstreamalias("ban") // another mapping public class ban { /* we want to have different field names in java classes so we define what element should be mapped to each field */ @xstreamalias("updated_at") // private string dateofupdate; @xstreamalias("troublemaker") private person person; } @xstreamalias("troublemaker") public class person { @xstreamalias("name1") private string firstname; @xstreamalias("name2") private string lastname; @xstreamalias("age") // string will be auto converted to int value private int age; @xstreamalias("number") private string documentnumber; and actual parsing logic is very short: filereader reader = new filereader("file.xml"); // load file xstream xstream = new xstream(); xstream.processannotations(data.class); // inform xstream to parse annotations in data class xstream.processannotations(ban.class); // and in two other classes... xstream.processannotations(person.class); // we use for mappings data data = (data) xstream.fromxml(reader); // parse // print some data to console to see if results are correct system.out.println("number of bans = " + data.getbans().size()); ban firstban = data.getbans().get(0); system.out.println("first ban = " + firstban.tostring()); as you can see annotations are very easy to use and as a result final code is very concise. but what to do in situation when we can’t modify mapping classes? we can use different approach that doesn’t require any modifications in java classes representing xml data. parse without annotations when we can’t enrich our model classes with annotations, there is another solution. we can define all mapping details using methods from xstream object: filereader reader = new filereader("file.xml"); // three first lines are easy, xstream xstream = new xstream(); // same initialisation as in the xstream.alias("data", data.class); // basic example above xstream.alias("ban", ban.class); // two more aliases to map... xstream.alias("troublemaker", person.class); // between node names and classes // we want to have different field names in java classes so // we have to use aliasfield(, , ) xstream.aliasfield("updated_at", ban.class, "dateofupdate"); xstream.aliasfield("troublemaker", ban.class, "person"); xstream.aliasfield("name1", person.class, "firstname"); xstream.aliasfield("name2", person.class, "lastname"); xstream.aliasfield("age", person.class, "age"); // notice here that xml will be auto-converted to int "age" xstream.aliasfield("number", person.class, "documentnumber"); /* another way to define implicit collection */ xstream.addimplicitcollection(bans.class, "bans"); data data = (data) xstream.fromxml(reader); // do the actual parsing // let's print results to check if data was parsed system.out.println("number of bans = " + data.getbans().size()); ban firstban = data.getbans().get(0); system.out.println("first ban = " + firstban.tostring()); as you can see xstream allows to easily convert more complicated xml structures into java objects, it also gives a possibility to tune results by using different names if this from xml doesn’t suit our needs. but there is one thing should catch your attention: we are converting xml representing a date into raw string which isn’t quite what we would like to get as a result. that’s why we will add converter to do some job for us. using existing custom type converter xstream library comes with set of built converters for most common use cases. we will use dateconverter. so now our class for ban looks like that: public class ban { private date dateofupdate; private person person; } and to use dateconverter we simply have to register it with date format that we expect to appear in xml data: xstream.registerconverter(new dateconverter("yyyy-mm-dd", new string[] {})); and that’s it. now instead of string our object is populated with date instance. cool and easy! but what about classes and situations that aren’t covered by existing converters? we could write our own. writing custom converter from scratch assume that instead of dateofupdate we want to know how many days ago update was done: public class ban { private int daysago; private person person; } of course we could calculate it manually for each ban object but using converter that will do this job for us looks more interesting. our daysagoconverter must implement converter interface so we have to implement three methods with signatures looking a little bit scary: public class daysagoconverter implements converter { @override public void marshal(object source, hierarchicalstreamwriter writer, marshallingcontext context) { } @override public object unmarshal(hierarchicalstreamreader reader, unmarshallingcontext context) { } @override public boolean canconvert(class type) { return false; } } last one is easy as we will convert only integer class. but there are still two methods left with these hierarchicalstreamwriter, marshallingcontext, hierarchicalstreamreader and unmarshallingcontext parameters. luckily, we could avoid dealing with them by using abstractsinglevalueconverter that shields us from so low level mechanisms. and now our class looks much better: public class daysagoconverter extends abstractsinglevalueconverter { @override public boolean canconvert(class type) { return type.equals(integer.class); } @override public object fromstring(string str) { return null; } public string tostring(object obj) { return null; } } additionally we must override method tostring(object obj) defined in abstractsinglevalueconverter as we want to store date in xml calculated from integer, not a simple object.tostring value which would be returned from default tostring defined in abstract parent. implementation code below is pretty straightforward, but most interesting lines are commented. i’ve skipped all validation stuff to make this example shorter. public class daysagoconverter extends abstractsinglevalueconverter { private final static string format = "yyyy-mm-dd"; // default date format that will be used in conversion private final datetime now = datetime.now().todatemidnight().todatetime(); // current day at midnight public boolean canconvert(class type) { return type.equals(integer.class); // converter works only with integers } @override public object fromstring(string str) { simpledateformat format = new simpledateformat(format); try { date date = format.parse(str); return days.daysbetween(new datetime(date), now).getdays(); // we simply calculate days between using jodatime } catch (parseexception e) { throw new runtimeexception("invalid date format in " + str); } } public string tostring(object obj) { if (obj == null) { return null; } integer daysago = ((integer) obj); return now.minusdays(daysago).tostring(format); // here we subtract days from now and return formatted date string } } usage to use our custom converter for a specific field we have to inform about it xstream object using registerlocalconverter: xstream.registerlocalconverter(ban.class, "daysago", new daysagoconverter()); we are using “local” method to apply this conversion only to specific field and not to every integer field in xml file. and after that we will get our ban objects populated with number of days instead of date. summary that’s all what i wanted to show you in this post. now you have basic knowledge about what xstream is capable of and how it can be used to easily map xml data to java objects. if you need something more advanced, please check project official page as it contains very good documentation and examples.
April 23, 2013
by Tomasz Dziurko
· 24,889 Views
article thumbnail
How to Format Java Code Using Eclipse JDT?
Yo probably format your code often by pressing Ctrl+Shift+F or right clicking Source -> Format. This function is also provide in JDT, so you can also format your Java code in code. However finding correct class to do this function is not straight-forward, because one of them is a internal class. The following is the code to format Java code by using DefaultCodeFormatter. import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; public class FormatterTest { public static void main(String[] args) { String code = "public class TestFormatter{public static void main(String[] args){System.out.println(\"Hello World\");}"; CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null); TextEdit textEdit = codeFormatter.format(CodeFormatter.K_COMPILATION_UNIT, code, 0, code.length(), 0, null); IDocument doc = new Document(code); try { textEdit.apply(doc); System.out.println(doc.get()); } catch (MalformedTreeException e) { e.printStackTrace(); } catch (BadLocationException e) { e.printStackTrace(); } } } he apply() method in TextEdit class is the key to this problem. It applies the edit tree rooted by this edit to the GIVEN document. Output in console: Depending on your Eclipse version, you will need the following jar files: org.eclipse.core.contenttype_3.4.1.R35x_v20090826-0451.jar org.eclipse.core.jobs_3.4.100.v20090429-1800.jar org.eclipse.core.resources_3.5.2.R35x_v20091203-1235.jar org.eclipse.equinox.common_3.5.1.R35x_v20090807-1100.jar org.eclipse.equinox.preferences_3.2.301.R35x_v20091117.jar org.eclipse.jdt.core_3.5.2.v_981_R35x.jar org.eclipse.osgi_3.5.2.R35x_v20100126.jar org.eclipse.text_3.5.101.v20110928-1504.jar org.eclipse.core.runtime_3.5.0.v20090525.jar
April 22, 2013
by Ryan Wang
· 6,706 Views
article thumbnail
What Does a Java Array Look Like in Memory?
arrays in java store one of two things: either primitive values (int, char, …) or references (a.k.a pointers). when an object is creating by using “new”, memory is allocated on the heap and a reference is returned. this is also true for arrays. 1. single-dimension array int arr[] = new int[3]; the int[] arr is just the reference to the array of 3 integer. if you create an array with 10 integer, it is the same – an array is allocated and a reference is returned. 2. two-dimensional array how about 2-dimensional array? actually, we can only have one dimensional arrays in java. 2d arrays are basically just one dimensional arrays of one dimensional arrays. int[ ][ ] arr = new int[3][ ]; arr[0] = new int[3]; arr[1] = new int[5]; arr[2] = new int[4]; multi-dimensional arrays use the name rules. 3. where are they located in memory? from the above, there are arrays and reference variables in memory. as we know that jvm runtime data areas include heap, jvm stack, and others. for a simple example as follows, let’s see where the array and its reference are stored. class a { int x; int y; } ... public void m1() { int i = 0; m2(); } public void m2() { a a = new a(); } ... when m1 is invoked, a new frame (frame-1) is pushed into the stack, and local variable i is also created in frame-1. when m2 is invoked inside of m1, another new frame (frame-2) is pushed into the stack. in m2, an object of class a is created in the heap and reference variable is put in frame-2. now, at this point, the stack and heap looks like the following: arrays are treated the same way like objects, so how array locates in memory is straight-forward.
April 19, 2013
by Ryan Wang
· 31,328 Views · 1 Like
article thumbnail
SiftingAppender: Logging Different Threads to Different Log Files
One novel feature of Logback is SiftingAppender (JavaDoc). In short it's a proxy appender that creates one child appender per each unique value of a given runtime property. Typically this property is taken from MDC. Here is an example based on the official documentation linked above: userid unknown user-${userid}.log %d{HH:mm:ss:SSS} | %-5level | %thread | %logger{20} | %msg%n%rEx Notice that the property is parameterized with ${userid} property. Where does this property come from? It has to be placed in MDC. For example in a web application using Spring Security I tend to use a servlet filter with a help of SecurityContextHolder: import javax.servlet._ import org.slf4j.MDC import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.core.userdetails.UserDetails class UserIdFilter extends Filter { def init(filterConfig: FilterConfig) {} def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain) { val userid = Option( SecurityContextHolder.getContext.getAuthentication ).collect{case u: UserDetails => u.getUsername} MDC.put("userid", userid.orNull) try { chain.doFilter(request, response) } finally { MDC.remove("userid") } } def destroy() {} } Just make sure this filter is applied after Spring Security filter. But that's not the point. The presence of ${userid} placeholder in the file name causes sifting appender to create one child appender for each different value of this property (thus: different user names). Running your web application with this configuration will quickly create several log files like user-alice.log, user-bob.log and user-unknown.log in case of MDC property not set. Another use case is using thread name rather than MDC property. Unfortunately this is not built in, but can be easily plugged in using custom Discriminator as opposed to default MDCBasedDiscriminator: public class ThreadNameBasedDiscriminator implements Discriminator { private static final String KEY = "threadName"; private boolean started; @Override public String getDiscriminatingValue(ILoggingEvent iLoggingEvent) { return Thread.currentThread().getName(); } @Override public String getKey() { return KEY; } public void start() { started = true; } public void stop() { started = false; } public boolean isStarted() { return started; } } Now we have to instruct logback.xml to use our custom discriminator: app-${threadName}.log %d{HH:mm:ss:SSS} | %-5level | %logger{20} | %msg%n%rEx Note that we no longer put %thread in PatternLayout - it is unnecessary as thread name is part of the log file name: app-main.log app-http-nio-8080-exec-1.log app-taskScheduler-1 app-ForkJoinPool-1-worker-1.log ...and so forth This is probably not the most convenient setup for server application, but on desktop where you have a limited number of focused threads like EDT, IO thread, etc. it might be a vital alternative.
April 19, 2013
by Tomasz Nurkiewicz
· 38,046 Views · 3 Likes
article thumbnail
HotSpot GC Thread CPU footprint on Linux
The following question will test your knowledge on garbage collection and high CPU troubleshooting for Java applications running on Linux OS. This troubleshooting technique is especially crucial when investigating excessive GC and / or CPU utilization. It will assume that you do not have access to advanced monitoring tools such as Compuware dynaTrace or even JVisualVM. Future tutorials using such tools will be presented in the future but please ensure that you first master the base troubleshooting principles. Question: How can you monitor and calculate how much CPU % each of the Oracle HotSpot or JRockit JVM garbage collection (GC) threads is using at runtime on Linux OS? Answer: On the Linux OS, Java threads are implemented as native Threads, which results in each thread being a separate Linux process. This means that you are able to monitor the CPU % of any Java thread created by the HotSpot JVM using the top –H command (Threads toggle view). That said, depending of the GC policy that you are using and your server specifications, the HotSpot & JRockit JVM will create a certain number of GC threads that will be performing young and old space collections. Such threads can be easily identified by generating a JVM thread dump. As you can see below in our example, the Oracle JRockit JVM did create 4 GC threads identified as "(GC Worker Thread X)”. ===== FULL THREAD DUMP =============== Fri Nov 16 19:58:36 2012 BEA JRockit(R) R27.5.0-110-94909-1.5.0_14-20080204-1558-linux-ia32 "Main Thread" id=1 idx=0x4 tid=14911 prio=5 alive, in native, waiting -- Waiting for notification on: weblogic/t3/srvr/T3Srvr@0xfd0a4b0[fat lock] at jrockit/vm/Threads.waitForNotifySignal(JLjava/lang/Object;)Z(Native Method) at java/lang/Object.wait(J)V(Native Method) at java/lang/Object.wait(Object.java:474) at weblogic/t3/srvr/T3Srvr.waitForDeath(T3Srvr.java:730) ^-- Lock released while waiting: weblogic/t3/srvr/T3Srvr@0xfd0a4b0[fat lock] at weblogic/t3/srvr/T3Srvr.run(T3Srvr.java:380) at weblogic/Server.main(Server.java:67) at jrockit/vm/RNI.c2java(IIIII)V(Native Method) -- end of trace "(Signal Handler)" id=2 idx=0x8 tid=14920 prio=5 alive, in native, daemon "(GC Main Thread)" id=3 idx=0xc tid=14921 prio=5 alive, in native, native_waiting, daemon "(GC Worker Thread 1)" id=? idx=0x10 tid=14922 prio=5 alive, in native, daemon "(GC Worker Thread 2)" id=? idx=0x14 tid=14923 prio=5 alive, in native, daemon "(GC Worker Thread 3)" id=? idx=0x18 tid=14924 prio=5 alive, in native, daemon "(GC Worker Thread 4)" id=? idx=0x1c tid=14925 prio=5 alive, in native, daemon ……………………… Now let’s put all of these principles together via a simple example. Step #1 - Monitor the GC thread CPU utilization The first step of the investigation is to monitor and determine: Identify the native Thread ID for each GC worker thread shown via the Linux top –H command. Identify the CPU % for each GC worker thread. Step #2 – Generate and analyze JVM Thread Dumps At the same time of Linux top –H, generate 2 or 3 JVM Thread Dump snapshots via kill -3 . Open the JVM Thread Dump and locate the JVM GC worker threads. Now correlate the "top -H" output data with the JVM Thread Dump data by looking at the native thread id (tid attribute). As you can see in our example, such analysis did allow us to determine that all our GC worker threads were using around 20% CPU each. This was due to major collections happening at that time. Please note that it is also very useful to enable verbose:gc as it will allow you to correlate such CPU spikes with minor and major collections and determine how much your JVM GC process is contributing to the overall server CPU utilization.
April 17, 2013
by Pierre - Hugues Charbonneau
· 14,530 Views
article thumbnail
Java Optional Objects
In this post I present several examples of the new Optional objects in Java 8 and I make comparisons with similar approaches in other programming languages, particularly the functional programming language SML and the JVM-based programming language Ceylon, this latter currently under development by Red Hat. I think it is important to highlight that the introduction of optional objects has been a matter of debate. In this article I try to present my perspective of the problem and I do an effort to show arguments in favor and against the use of optional objects. It is my contention that in certain scenarios the use of optional objects is valuable, but ultimately everyone is entitled to an opinion and I just hope this article helps the readers to make an informed one just as writing it helped me understand this problem much better. About the Type of Null In Java we use a reference type to gain access to an object, and when we don't have a specific object to make our reference point to, then we set such reference to null to imply the absence of a value. In Java null is actually a type, a special one: it has no name, we cannot declare variables of its type, or cast any variables to it, in fact there is a single value that can be associated with it (i.e. the literal null), and unlike any other types in Java, a null reference can be safely assigned to any other reference types (See JLS 3.10.7 and 4.1). The use of null is so common that we rarely meditate on it: field members of objects are automatically initialized to null and programmers typically initialize reference types to null when they don't have an initial value to give them and, in general, null is used everywhere to imply that, at certain point, we don't know or we don't have a value to give to a reference. About the Null Pointer Reference Problem Now, the major problem with the null reference is that if we try to dereference it then we get the ominous and well known NullPointerException. When we work with a reference obtained from a different context than our code (i.e. as the result of a method invocation or when we receive a reference as an argument in a method we are working on), we all would like to avoid this error that has the potential to make our application crash, but often the problem is not noticed early enough and it finds its way into production code where it waits for the right moment to fail (which is typically a Friday at the end of the month, around 5 p.m. and just when you are about to leave the office to go to the movies with your family or drink some beers with your friends). To make things worse, the place where your code fails is rarely the place where the problem originated, since your reference could have been set to null far away from the place in your code where you intended to dereference it. So, you better cancel those plans for the Friday night... It's worth mentioning that this concept of null references was first introduced by Tony Hoare, the creator of ALGOL, back in 1965. The consequences were not so evident in those days, but he later regretted his design and he called it "a billion dollars mistake", precisely referring to the uncountable amount of hours that many of us have spent, since then, fixing this kind null dereferencing problems. Wouldn't it be great if the type system could tell the difference between a reference that, in a specific context, could be potentially null from one that couldn't? This would help a lot in terms of type safety because the compiler could then enforce that the programmer do some verification for references that could be null at the same time that it allows a direct use of the others. We see here an opportunity for improvement in the type system. This could be particularly useful when writing the public interface of APIs because it would increase the expressive power of the language, giving us a tool, besides documentation, to tell our users that a given method may or may not return a value. Now, before we delve any further, I must clarify that this is an ideal that modern languages will probably pursue (we'll talk about Ceylon and Kotlin later), but it is not an easy task to try to fix this hole in a programming language like Java when we intend to do it as an afterthought. So, in the coming paragraphs I present some scenarios in which I believe the use of optional objects could arguably alleviate some of this burden. Even so, the evil is done, and nothing will get rid of null references any time soon, so we better learn to deal with them. Understanding the problem is one step and it is my opinion that these new optional objects are just another way to deal with it, particularly in certain specific scenarios in which we would like to express the absence of a value. Finding Elements There is a set of idioms in which the use of null references is potentially problematic. One of those common cases is when we look for something that we cannot ultimately find. Consider now the following simple piece of code used to find the first fruit in a list of fruits that has a certain name: public static Fruit find(String name, List fruits) { for(Fruit fruit : fruits) { if(fruit.getName().equals(name)) { return fruit; } } return null; } As we can see, the creator of this code is using a null reference to indicate the absence of a value that satisfies the search criteria (7). It is unfortunate, though, that it is not evident in the method signature that this method may not return a value, but a null reference.. Now consider the following code snippet, written by a programmer expecting to use the result of the method shown above: List fruits = asList(new Fruit("apple"), new Fruit("grape"), new Fruit("orange")); Fruit found = find("lemon", fruits); //some code in between and much later on (or possibly somewhere else)... String name = found.getName(); //uh oh! Such simple piece of code has an error that cannot be detected by the compiler, not even by simple observation by the programmer (who may not have access to the source code of the find method). The programmer, in this case, has naively failed to recognize the scenario in which the find method above could return a null reference to indicate the absence of a value that satisfies his predicate. This code is waiting to be executed to simply fail and no amount of documentation is going to prevent this mistake from happening and the compiler will not even notice that there is a potential problem here. Also notice that the line where the reference is set to null (5) is different from the problematic line (7). In this case they were close enough, in other cases this may not be so evident. In order to avoid the problem what we typically do is that we check if a given reference is null before we try to dereference it. In fact, this verification is quite common and in certain cases this check could be repeated so many times on a given reference that Martin Fowler (renown for hist book on refactoring principles) suggested that for these particular scenarios such verification could be avoided with the use of what he called a Null Object. In our example above, instead of returning null, we could have returned a NullFruit object reference which is an object of type Fruit that is hollowed inside and which, unlike a null reference, is capable of properly responding to the same public interface of a Fruit. Minimum and Maximum Another place where this could be potentially problematic is when reducing a collection to a value, for instance to a maximum or minimum value. Consider the following piece of code that can be used to determine which is the longest string in a collection. public static String longest(Collection items) { if(items.isEmpty()){ return null; } Iterator iter = items.iterator(); String result = iter.next(); while(iter.hasNext()) { String item = iter.next(); if(item.length() > result.length()){ result = item; } } return result; } In this case the question is what should be returned when the list provided is empty? In this particular case a null value is returned, once again, opening the door for a potential null dereferencing problem. The Functional World Strategy It's interesting that in the functional programming paradigm, the statically-typed programming languages evolved in a different direction. In languages like SML or Haskell there is no such thing as a null value that causes exceptions when dereferenced. These languages provide a special data type capable of holding an optional value and so it can be conveniently used to also express the possible absence of a value. The following piece of code shows the definition of the SML option type: datatype 'a option = NONE | SOME of 'a As you can see, option is a data type with two constructors, one of them stores nothing (i.e. NONE) whereas the other is capable of storing a polymorphic value of some value type 'a (where 'a is just a placeholder for the actual type). Under this model, the piece of code we wrote before in Java, to find a fruit by its name, could be rewritten in SML as follows: fun find(name, fruits) = case fruits of [] => NONE | (Fruit s)::fs => if s = name then SOME (Fruit s) else find(name,fs) There are several ways to achieve this in SML, this example just shows one way to do it. The important point here is that there is no such thing as null, instead a value NONE is returned when nothing is found (3), and a value SOME fruit is returned otherwise (5). When a programmer uses this find method, he knows that it returns an option type value and therefore the programmer is forced to check the nature of the value obtained to see if it is either NONE (6) or SOME fruit (7), somewhat like this: let val fruits = [Fruit "apple", Fruit "grape", Fruit "orange"] val found = find("grape", fruits) in case found of NONE => print("Nothing found") | SOME(Fruit f) => print("Found fruit: " ^ f) end Having to check for the true nature of the returned option makes it impossible to misinterpret the result. Java Optional Types It's a joy that finally in Java 8 we'll have a new class called Optional that allows us to implement a similar idiom as that from the functional world. As in the case of of SML, the Optional type is polymorphic and may contain a value or be empty. So, we could rewrite our previous code snippet as follows: public static Optional find(String name, List fruits) { for(Fruit fruit : fruits) { if(fruit.getName().equals(name)) { return Optional.of(fruit); } } return Optional.empty(); } As you can see, the method now returns an Optional reference (1), if something is found, the Optional object is constructed with a value (4), otherwise is constructed empty (7). And the programmer using this code would do something as follows: List fruits = asList(new Fruit("apple"), new Fruit("grape"), new Fruit("orange")); Optional found = find("lemon", fruits); if(found.isPresent()) { Fruit fruit = found.get(); String name = fruit.getName(); } Now it is made evident in the type of the find method that it returns an optional value (5), and the user of this method has to program his code accordingly (6-7). So we see that the adoption of this functional idiom is likely to make our code safer, less prompt to null dereferencing problems and as a result more robust and less error prone. Of course, it is not a perfect solution because, after all, Optional references can also be erroneously set to null references, but I would expect that programmers stick to the convention of not passing null references where an optional object is expected, pretty much as we today consider a good practice not to pass a null reference where a collection or an array is expected, in these cases the correct is to pass an empty array or collection. The point here is that now we have a mechanism in the API that we can use to make explicit that for a given reference we may not have a value to assign it and the user is forced, by the API, to verify that. Quoting an article I reference later about the use of optional objects in the Guava Collections framework: "Besides the increase in readability that comes from giving null a name, the biggest advantage of Optional is its idiot-proof-ness. It forces you to actively think about the absent case if you want your program to compile at all, since you have to actively unwrap the Optional and address that case". Other Convenient Methods As of the today, besides the static methods of and empty explained above, the Optional class contains the following convenient instance methods: ifPresent() Which returns true if a value is present in the optional. get() Which returns a reference to the item contained in the optional object, if present, otherwise throws a NoSuchElementException. ifPresent(Consumer consumer) Which passess the optional value, if present, to the provided Consumer (which could be implemented through a lambda expression or method reference). orElse(T other) Which returns the value, if present, otherwise returns the value in other. orElseGet(Supplier other) Which returns the value if present, otherwise returns the value provided by the Supplier (which could be implemented with a lambda expression or method reference). orElseThrow(Supplier exceptionSupplier) Which returns the value if present, otherwise throws the exception provided by the Supplier (which could be implemented with a lambda expression or method reference). Avoiding Boilerplate Presence Checks We can use some of the convenient methods mentioned above to avoid the need of having to check if a value is present in the optional object. For instance, we may want to use a default fruit value if nothing is found, let's say that we would like to use a "Kiwi". So we could rewrite our previous code like this: Optional found = find("lemon", fruits); String name = found.orElse(new Fruit("Kiwi")).getName(); In this other example, the code prints the fruit name to the main output, if the fruit is present. In this case, we implement the Consumer with a lambda expression. Optional found = find("lemon", fruits); found.ifPresent(f -> { System.out.println(f.getName()); }); This other piece of code uses a lambda expression to provide a Supplier which can ultimately provide a default answer if the optional object is empty: Optional found = find("lemon", fruits); Fruit fruit = found.orElseGet(() -> new Fruit("Lemon")); Clearly, we can see that these convenient methods simplify a lot having to work with the optional objects. So What's Wrong with Optional? The question we face is: will Optional get rid of null references? And the answer is an emphatic no! So, detractors immediately question its value asking: then what is it good for that we couldn't do by other means already? Unlike functional languages like SML o Haskell which never had the concept of null references, in Java we cannot simply get rid of the null references that have historically existed. This will continue to exist, and they arguably have their proper uses (just to mention an example: three-valued logic). I doubt that the intention with the Optional class is to replace every single nullable reference, but to help in the creation of more robust APIs in which just by reading the signature of a method we could tell if we can expect an optional value or not and force the programmer to use this value accordingly. But ultimately, Optional will be just another reference and subject to same weaknesses of every other reference in the language. It is quite evident that Optional is not going to save the day. How these optional objects are supposed to be used or whether they are valuable or not in Java has been the matter of a heated debate in the project lambda mailing list. From the detractors we hear interesting arguments like: The fact that other alternatives exist ( i.e. the Eclipse IDE supports a set of proprietary annotations for static analysis of nullability, the JSR-305 with annotations like @Nullable and @NonNull). Some would like it to be usable as in the functional world, which is not entirely possible in Java since the language lacks many features existing in functional programming languages like SML or Haskell (i.e. pattern matching). Others argue about how it is impossible to retrofit preexisting code to use this idiom (i.e. List.get(Object)which will continue to return null). And some complain about the fact that the lack of language support for optional values creates a potential scenario in which Optional could be used inconsistently in the APIs, by this creating incompatibilities, pretty much like the ones we will have with the rest of the Java API which cannot be retrofitted to use the new Optional class. A compelling argument is that if the programmer invokes the get method in an optional object, if it is empty, it will raise a NoSuchElementException, which is pretty much the same problem that we have with nulls, just with a different exception. So, it would appear that the benefits of Optional are really questionable and are probably constrained to improving readability and enforcing public interface contracts. Optional Objects in the Stream API Irrespective of the debate, the optional objects are here to stay and they are already being used in the new Stream API in methods like findFirst, findAny, max and min. It could be worth mentioning that a very similar class has been in used in the successful Guava Collections Framework. For instance, consider the following example where we extract from a stream the last fruit name in alphabetical order: Stream fruits = asList(new Fruit("apple"), new Fruit("grape")).stream(); Optional max = fruits.max(comparing(Fruit::getName)); if(max.isPresent()) { String fruitName = max.get().getName(); //grape } Or this another one in which we obtain the first fruit in a stream Stream fruits = asList(new Fruit("apple"), new Fruit("grape")).stream(); Optional first = fruits.findFirst(); if(first.isPresent()) { String fruitName = first.get().getName(); //apple } Ceylon Programming Language and Optional Types Recently I started to play a bit with the Ceylon programming language since I was doing a research for another post that I am planning to publish soon in this blog. I must say I am not a big fan of Ceylon, but still I found particularly interesting that in Ceylon this concept of optional values is taken a bit further, and the language itself offers some syntactic sugar for this idiom. In this language we can mark any type with a ? (question mark) in order to indicate that its type is an optional type. For instance, this find function would be very similar to our original Java version, but this time returning an optional Fruit? reference (1). Also notice that a null value is compatible with the optional Fruit? reference (7). Fruit? find(String name, List fruits){ for(Fruit fruit in fruits) { if(fruit.name == name) { return fruit; } } return null; } And we could use it with this Ceylon code, similar to our last Java snippet in which we used an optional value: List fruits = [Fruit("apple"),Fruit("grape"),Fruit("orange")]; Fruit? fruit = find("lemon", fruits); print((fruit else Fruit("Kiwi")).name); Notice the use of the else keyword here is pretty similar to the method orElse in the Java 8 Optional class. Also notice that the syntax is similar to the declaration of C# nullable types, but it means something totally different in Ceylon. It may be worth mentioning that Kotlin, the programming language under development by Jetbrains, has a similar feature related to null safety (so maybe we are before a trend in programming languages). An alternative way of doing this would have been like this: List fruits = [Fruit("apple"),Fruit("grape"),Fruit("orange")]; Fruit? fruit = find("apple", fruits); if(exists fruit){ String fruitName = fruit.name; print("The found fruit is: " + fruitName); } //else... Notice the use of the exists keyword here (3) serves the same purpose as the isPresent method invocation in the Java Optional class. The great advantage of Ceylon over Java is that they can use this optional type in the APIs since the beginning, within the realm of their language they won't have to deal with incompatibilities, and it can be fully supported everywhere (perhaps their problem will be in their integration with the rest of the Java APIs, but I have not studied this yet). Hopefully, in future releases of Java, this same syntactic sugar from Ceylon and Kotlin will also be made available in the Java programming language, perhaps using, under the hood, this new Optional class introduced in Java 8. Further Reading Java Language Specification The Billion Dollars Mistake Refactoring Catalog Ceylon Programming Language Kotlin Programming Language C# Nullable Types Avoid Using Null (Guava Framework) More Discussion on Java's Optional Java Infinite Streams Java Streams API Preview Java Streams Preview vs .Net High-Order Programming with LINQ
April 17, 2013
by Edwin Dalorzo
· 86,020 Views · 22 Likes
article thumbnail
ActiveMQ and .NET combined!
ActiveMQ is one of the most popular messaging frameworks. For sure the most popular open source framework. Many people think that ActiveMQ works only with Java and this is not true at all. ActiveMQ can work with almost every popular language (including JavaScript!) through numerous protocols which it supports. Today I will show you how to use ActiveMQ in .NET-based solutions. Project setup Using VS 2010's Extension Manger I installed NuGet Package Manager. After installation and VS 2010 restart, I created a project called ActiveMQNMS. I right-clicked it and selected "Manage NuGet packages...". In the search field I typed: "ActiveMQ". There was a package called Apache.NMS.ActiveMQ. I installed it. (Note: ActiveMQ has one dependency - Apache.NMS package. The NMS package provides a unified API for working with different messaging frameworks and providers.) Starting ActiveMQ I already had ActiveMQ installed on my machine. If you don't have one, download it from http://activemq.apache.org. The default instance listens on 61616 port. However, mine is listening on 62626. If you want to run my code, please remember to change the port. To start ActiveMQ I executed: activemq-5.5.0\bin\activemq Depending on configured ports, you can use ActiveMQ web console to manage your queues, topics, subscribers, connections, embedded Apache Camel, etc. I'm using 8282 port, and the console URL is: http://localhost:8282/admin. Test stub In general the .NET API is almost a copy of the Java API. So if you're familiar with JMS and/or ActiveMQ you don't need any documentation. Please note TestIntialize and TestCleanup methods. using System; using Apache.NMS; using Apache.NMS.ActiveMQ; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ActiveMQNMS { [Serializable] public class Person { public string FirstName { get; set; } public string LastName { get; set; } } [TestClass] public class ActiveMqTest { private IConnection _connection; private ISession _session; private const String QUEUE_DESTINATION = "DotNet.ActiveMQ.Test.Queue"; [TestInitialize] public void TestInitialize() { IConnectionFactory factory = new ConnectionFactory("tcp://localhost:62626"); _connection = factory.CreateConnection(); _connection.Start(); _session = _connection.CreateSession(); } [TestCleanup] public void TestCleanup() { _session.Close(); _connection.Close(); } } } Writing Producer Here is the producer: [TestMethod] public void TestA() { IDestination dest = _session.GetQueue(QUEUE_DESTINATION); using (IMessageProducer producer = _session.CreateProducer(dest)) { var person = new Person { FirstName = "Łukasz", LastName = "Budnik" }; var objectMessage = producer.CreateObjectMessage(person); producer.Send(objectMessage); } } Run the test and refresh "Queues" list in ActiveMQ web console. You should see DotNet.ActiveMQ.Test.Queue queue with 1 enqueued and pending message. Purge the queue by hitting the purge link or you simply delete it. Writing Consumer Now we have to consume the message. Here is the code: [TestMethod] public void TestB() { Person person = null; IDestination dest = _session.GetQueue(QUEUE_DESTINATION); using (IMessageConsumer consumer = _session.CreateConsumer(dest)) { IMessage message; while ((message = consumer.Receive(TimeSpan.FromMilliseconds(2000))) != null) { var objectMessage = message as IObjectMessage; if (objectMessage != null) { person = objectMessage.Body as Person; if (person != null) { Assert.AreEqual("Łukasz", person.FirstName); Assert.AreEqual("Budnik", person.LastName); } } else { Assert.Fail("Object Message is null"); } } } if (person == null) { Assert.Fail("Person object is null"); } } Run tests. Refresh "Queues" tab in ActiveMQ web console. You should see 1 message enqueued and 1 message dequeued. As expected. Summary That's all. Simple, isn't it? ActiveMQ works very, very nicely with .NET. I have to find some performance comparison for ActiveMQ and MS or pure .C#/NET messaging frameworks. Or maybe you have it? Please share. cheers, Łukasz
April 15, 2013
by Łukasz Budnik
· 29,426 Views
article thumbnail
Java Lambda Expressions Basics
Learn about Java Lambda essentials, including basics and examples.
April 13, 2013
by Edwin Dalorzo
· 293,487 Views · 24 Likes
article thumbnail
Predicate and Consumer Interface in java.util.function package in Java 8
Here's how to properly use the Predicate and Consumer interfaces in Java 8.
April 11, 2013
by Mohamed Sanaulla
· 39,629 Views · 17 Likes
article thumbnail
Getting Rid of Boilerplate Code with Java Lambda Expressions
As I have mentioned in a previous post, there is nothing we can do with lambda expressions that we could not do without them. Basically because we can implement a similar idiom in Java using anonymous classes. The problem is that anonymous classes require a lot of boilerplate code. To demonstrate the value of lambda expressions as a tool to achieve more succinct code in this post I will develop some classical high-order functions from scratch. Filtering Let’s consider the existence of an interface called Predicate defined as follows: interface Predicate { public boolean test(T t); } And now, let’s say we would like to use the Predicate interface to filter the elements of any given list based on a given predicate. So, we could define something as follows: static List filter(Predicate predicate, List source) { List destiny = new ArrayList<>(); for(T item : source) { if(predicate.test(item)){ destiny.add(item); } } return destiny; } Now, consider that we had a list of numbers, and we would like to filter only those that are odd. Traditionally, in Java, we would use an anonymous class to define the predicate, something like this: List numbers = asList(1,2,3,4,5,6,7,8,9); List onlyOdds = filter(new Predicate(){ @Override public boolean test(Integer n) { return n % 2 != 0; } }, numbers); But consider all the boilerplate code that was necessary here to simply say that we would like to take a value n and check if it is an odd number. Clearly this does not look good. In Java 8, we could get rid of all this mess by simply implementing our predicate using a lambda expression, as follows: List numbers = asList(1,2,3,4,5,6,7,8,9); List onlyOdds = filter(n –> n % 2 !=0, numbers); Here, the lambda expression will be evaluated to an instance of the type Predicate, its argument n, corresponds to the argument expected by its method test, and the body of the expressions represents the implementation of the method. Mapping Let’s consider now the existence of an interface Function defined as follows: interface Function { public R apply(T t); } And now, let’s say we would like to use this functional interface to transform the elements of a list from one value to another. So, we could define a method as follows: static List map(Function function, List source){ List destiny = new ArrayList<>(); for(T item : source) { R value = function.apply(item); destiny.add(value); } return destiny; } Now, consider that we had a list of strings representing numbers and we would like to convert them to their corresponding integer values. Once again, in the traditional model we could use Java anonymous classes for this, like so: List digits = asList("1","2","3","4","5","6","7","8","9"); List numbers = map(new Function digits = asList("1","2","3","4","5","6","7","8","9"); List numbers = map(s –> Integer.valueOf(s), digits); This is clearly much better. Once again, the lambda expression evaluates to an instance of the type Function where s represents the argument for its function apply and the body of the lambda expression represents what the function would return in its body. Reducing Let’s consider now the existence of an interface BinaryOperator defined as follows: interface BinaryOperator { public T apply(T left, T right); } And now we would like to use this functional interface to reduce the values from a list to a single value. So, we could use it as follows: static T reduce(BinaryOperator operator,T seed, List source){ for(T item: source) { seed = operator.apply(seed, item); } return seed; } Consider now that we have a list of numbers and we would like to obtain to summation of them all. Once more, if we intend to use this code as we traditionally have done before the release of Java 8 we would be forced to to following verbose definition, as follows: List numbers = asList(1,2,3,4,5); Integer sum = reduce(new BinaryOperator() { @Override public Integer apply(Integer left, Integer right){ return left + right; } },0,numbers); This code can be greatly simplified by the use of a lambda expression, as follows: List numbers = asList(1,2,3,4,5); Integer sum = reduce( (x,y) –> x + y, 0, numbers); Where (x,y) correspond to the two arguments left and right that the function apply receives, and the body of the expressions would be what it would return. Notice that, since in this case we have to specify two arguments, the lambda expressions is required to specify them within parenthesis, otherwise the compiler could determine which arguments are for the lambda expression and which are for the reduce method. Consuming Let’s consider now the existence of a functional interface Consumer, defined as follows: interface Consumer { public void accept(T t); } Now we could use implementations of this interface to consume the elements of a list and do something with them, like printing them to the main output or sending them over the network, or whatever we could consider appropriate. For this example, let’s just print them to the output: static void forEach(Consumer consumer, List source) { for(T item: source) { consumer.accept(item); } } Look at all the boilerplate code necessary to create a consumer to simply print all the elements of a list: List numbers = asList(1,2,3,4,5); forEach(new Consumer(){ @Override public void accept(Integer n) { System.out.println(n); } },numbers); However, now we could use a simple lambda expression to implement equivalent functionality as follows: List numbers = asList(1,2,3,4,5); forEach(n –> { System.out.println(n); }, numbers); The syntax differs a bit from the previous cases because in this case the method we intend to implement through the lambda expression returns void, and that is why we use a code block to signify that the type of the lambda expression is also void. Producing Let’s consider now the existence of a functional interface Supplier as follows: interface Supplier { public T get(); } A classical idiom is to use this type of interface to encapsulate an expensive calculation and differ its evaluation until needed, something typically known as lazy evaluation. For example: public static int generateX() { return 0; } public static int generateY() { //some expensive calculation here return 1; } public static int calculate(Supplier thunkOfX, Supplier thunkOfY) { int x = thunkOfX.get(); if(x==0) return 0; else return x + thunkOfY.get(); } By means of passing two suppliers here we defer the evaluation of x and y until needed. As you can see, if x is equal to 0, y is never needed. So, by using this idiom we avoid spending a lot of time in a expensive calculation unnecessarily. Before lambda expressions, the invocation of calculation would have implied a lot of boilerplate code as follows: calculate(new Supplier() { @Override public Integer get() { return generateX(); } }, new Supplier() { @Override public Integer get() { return generateY(); } }); However, using lambda expressions, this a one-liner: calculate( () –> generateX(), () –> generateY() ); Clearly this is much better. Summary of Lambda Syntax So, these are different ways to define lambda expressions: Predicate isOdd = n –> n % 2 == 0; Function atoi = s –> Integer.valueOf(s); BinaryOperator product = (x, y) –> x * y Comparator maxInt = (x,y) –> x > y ? x : y; Consumer printer = s –> { System.out.println(s); }; Supplier producer = () –> "Hello World"; Runnable task = () –> { System.out.println("I am a runnable task"); }; In summary, lambda expressions are a great tool to get rid of all the boilerplate required by the clunky Java syntax of anonymous classes. The new API for Streams makes extensive use of this new syntax: int oddSum = asList("1","2","3","4","5").stream() .map(n –> Integer.valueOf(n)) .filter(n –> n % 2 != 0) .reduce(0, (x,y) –> x + y); // 9
April 10, 2013
by Edwin Dalorzo
· 6,943 Views
article thumbnail
Java Lambda Expressions vs Method References
Now we can use lambda expressions to implement functional interfaces as we have seen in previous posts, but the lambda expressions are not the only mechanism we can use for this purpose. Particularly where there are preexisting code that we would like to reuse we can simplify the implementation of the functional interface by using method references. Static Method References First, consider the existence of a functional interface Predicate as follows: public interface Predicate { public void test(T t); } And let’s say that we had a method to filter elements out of a list using this predicate, as follows: static List filter(Predicate predicate, List source) { List destiny = new ArrayList<>(); for (T item : source) { if(predicate.test(item)){ destiny.add(item); } } return destiny; } Finally, let’s say we had a class containing a set of static method predicates which we had defined in the past, prior to the existence of the Java 8. Something as follows: static class IntPredicates { public static boolean isOdd(Integer n) { return n % 2 != 0; } public static boolean isEven(Integer n) { return n % 2 == 0; } public static boolean isPositive(Integer n) { return n >= 0; } } Now, one way to implement a predicate that could reuse our static methods would be through the use of lambda expressions, like this: Predicate isOdd = n -> IntPredicates.isOdd(n); Predicate isEven = n -> IntPredicates.isEven(n); However, we can clearly see that the signature of the static predicate methods corresponds perfectly with the signature of the test method for integer predicates. So, an alternative way to implement the functional interface in this case is through a static method reference, as follows: Predicate isOdd = IntPredicates::isOdd; Predicate isEven = IntPredicate::isEven; Notice the use of double colon :: here. We are not invoking the method, we are just referencing its name. We could now use this technique to filter a list of numbers that satisfy any of these predicates, something like this: List numbers = asList(1,2,3,4,5,6,7,8,9); List odds = filter(IntPredicates::isOdd, numbers); List evens = filter(IntPredicates::isEven, numbers); So, as we can see, we could implement the functional interfaces in this case using both: lambda expressions and method references, but the syntax with the static method references was more succinct. Constructor Method References Let’s consider now the existence of a functional interface named Function, as follows: public interface Function { public R apply(T t); } Based on it, we could define a method map, that converts the elements from a source list from certain value T to certain value R, as follows: static List map(Function function, List source) { List destiny = new ArrayList<>(); for (T item : source) { R value = function.apply(item); destiny.add(value); } return destiny; } Now imagine that we had a list of strings containing numbers that we would like to transform to integer values. We could do it using a lambda expression to provide an implementation for the Function interface, more or less like this: List digits = asList("1","2","3","4","5"); List numbers = map(s -> new Integer(s), digits); However, we can clearly infer that the constructor Integer(String) has the same signature as the apply method in the Function reference required here, namely, it receives a string as argument and returns an integer. So, in this case we simplify the implementation of the functional interface by means of using a constructor reference, as follows: List digits = asList("1","2","3","4","5"); List numbers = map(Integer::new, digits); This conveys the same meaning: take a string and make me an integer out of it. It is the perfect task for our Integer(String) constructor. Instance Method Reference to Arbitrary Objects Consider now the existence of a class named Jedi, defined as follows: public class Jedi { private String name; private int power; public Jedi(String name, int power){ this.name = name; this.power = power; } public String getName() { return name; } public int getPower() { return power; } //equals,hashCode,toString } Now, consider that we had a list of jedis, and we would like to use our previous function map to extract the name from every jedi and generate a list of names out of the list of jedis. Somewhat like this, using lambda expressions: List jedis = asList(new Jedi("Obi-wan", 80), new Jedi("Anakin", 25), new Jedi("Yoda", 500)); List names = map(jedi -> jedi.getName() , jedis); The interesting observation here is that the parameter jedi is the argument for the apply method in the Function reference. And we use that reference to a jedi to invoke on it the method getName. In other words, we invoke a method on the reference we receive as argument. So, we could simplify this implementation by using an instance method reference as follows: List jedi = asList(new Jedi("Obi-wan", 80), new Jedi("Anakin", 25), new Jedi("Yoda", 500)); List names = map(Jedi::getName, jedi); Again, the interesting aspect of this type of method reference is that the method getName is an instance method. Therefore, the target of its invocation must be an instance, which in this case is an arbitrary object being provided as the argument for the method apply in the Function interface definition. Instance Method Reference to a Specific Object Let’s consider the existence of functional interface named Consumer, as follows public interface Consumer { public void accept(T t); } And let’s define a method capable of using a consumer to consume all the elements of a given list, like this: static void forEach(Consumer consumer, List source){ for (T item : source) { consumer.accept(item); } } Imagine that now we would like to print all the elements contained in a list, and for that purpose we could define a consumer using a lambda expressions: List numbers = asList(1,2,3,4,5,6,7,8,9); forEach(n -> { System.out.println(n); }, numbers); However, we could also make the observation that the method println has the same signature that our Consumer has, it receives an integer and does something with it, in this case it prints it to the main output. However, we cannot specify that this is an arbitrary instance method reference by saying PrintStream::println, because in this case the Consumer interface method accept does not receive as one of its arguments the PrintStream object on which we may want to invoke the method println. Conversely, we already know which is the target object on which we would like to invoke the method: we can see that every time we would like to invoke it on a specific reference, in this case the object System.out. So, we could implement our functional interface using an instance method reference to a specific object as follows: List numbers = asList(1,2,3,4,5,6,7,8,9); forEach(System.out::println, numbers); In summary, there are circumstances in which we would like to use some preexisting code as the implementation for a functional interface, in those case we could use one of several variants of method references instead of a more verbose lambda expression.
April 9, 2013
by Edwin Dalorzo
· 79,553 Views · 5 Likes
  • Previous
  • ...
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • ...
  • Next
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook
×