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

The Latest Languages Topics

article thumbnail
Train Wreck Pattern – A much improved implementation in Java 8
venkat subramaniam at a talk today mentioned about cascade method pattern or train wreck pattern which looks something like: someobject.method1().method2().method3().finalresult() few might associate this with the builder pattern , but its not the same. anyways lets have a look at an example for this in java with out the use of lambda expression: public class trainwreckpattern { public static void main(string[] args) { new mailer() .to("[email protected]") .from("[email protected]") .subject("some subject") .body("some content") .send(); } } class mailer{ public mailer to(string address){ system.out.println("to: "+address); return this; } public mailer from(string address){ system.out.println("from: "+address); return this; } public mailer subject(string sub){ system.out.println("subject: "+sub); return this; } public mailer body(string body){ system.out.println("body: "+body); return this; } public void send(){ system.out.println("sending ..."); } } i have taken the same example which venkat subramaniam took in his talk. in the above code i have a mailer class which accepts a series of values namely: to, from, subject and a body and then sends the mail. pretty simple right? but there is some problem associated with this: one doesn’t know what to do with the mailer object once it has finished sending the mail. can it be reused to send another mail? or should it be held to know the status of email sent? this is not known from the code above and lot of times one cannot find this information in the documentation. what if we can restrict the scope of the mailer object within some block so that one cannot use it once its finished its operation? java 8 provides an excellent mechanism to achieve this using lambda expressions . lets look at how it can be done: public class trainwreckpatternlambda { public static void main(string[] args) { mailer.send( mailer -> { mailer.to("[email protected]") .from("[email protected]") .subject("some subject") .body("some content"); }); } } class mailer{ private mailer(){ } public mailer to(string address){ system.out.println("to: "+address); return this; } public mailer from(string address){ system.out.println("from: "+address); return this; } public mailer subject(string sub){ system.out.println("subject: "+sub); return this; } public mailer body(string body){ system.out.println("body: "+body); return this; } public static void send(consumer maileroperator){ mailer mailer = new mailer(); maileroperator.accept(mailer); system.out.println("sending ..."); } } in the above implementation i have restricted the instantiation of the mailer class to the send() method by making the constructor private. and then the send() method now accepts an implementation of consumer interface which is a single abstract method class and can be represented by a lambda expression. and in the main() method i pass a lambda expression which accepts a mailer instance and then configures the mailer object before being used in the send() method. the use of lambda expression has created a clear boundary for the use of the mailer object and this way its much ore clearer for someone reading the code as to how the mailer object has to be used. let me know if there is something more that i can improve in this example i have shared.
May 15, 2013
by Mohamed Sanaulla
· 11,506 Views
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,189 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,214 Views · 7 Likes
article thumbnail
Why Choose Apache Camel with Apache Tomcat
apache camel with apache tomcat provides a low-cost and lightweight integration framework. is apache camel with apache tomcat a good fit for your project requirements? apache tomcat is known for it’s ease-of-use and minimal footprint when building servlet and javaserver page applications, while apache camel is known for supporting enterprise integration patterns, routing and mediation rules in a variety of domain-specific languages, including a java-based fluent api, spring or blueprint xml configuration files, and a scala dsl. developers and architects find a straightforward learning curve when using apache camel’s java based dsl, yet they find better tools exist when building simple connections or implementing large integration projects. see kai wahner’s writeup on lightweight frameworks . for larger integration projects requiring reliable messaging, scalability, eventing, business process execution, or web agent hosting, selecting an enterprise service bus provides a better fit . kai has another good article placing esb and integration suites in context. apache camel is often integrated with activemq, servicemix, or fuse to obtain additional capabilities required to deliver medium to complex integration projects. the wso2 esb team is looking to embrace the simplicity of apache camel (by incorporating the project similar to embedding apache cxf ), and extend with multi-tenancy, failover, performance, and scalability enhancements. similar to redhat jboss fuse, wso2 esb delivers service container clustering and reliable failover functions. in addition to extensive mediation primitives, the products provide service monitoring and management support not available in the basic apache camel with apache tomcat combination. to combat server proliferation, wso2 esb inherently supports multi-tenancy. the multi-tenancy goes beyond simple tomcat virtual domains by using osgi class loaders and security managers to provide adequate tenant isolation and separate administration console interfaces. a single wso2 esb instance can support multiple business units with appropriate data, logic, and execution isolation. springsource, mulesoft, and wso2 have extended apache tomcat to provide better server management and ability to install features within the integration platform. wso2 esb can install over 100+ features (e.g. business process execution, complex event execution, business activity monitoring) into the integration platform. from a performance perspective, apache camel with apache tomcat depends on the tomcat transport to provide high performant message transfer. the wso2 esb pass through transport and binary relay transports are optimized to provide the best streaming, non-blocking performance by tightly integrating the transport and mediation layers. camel + tomcat depends on what ever the tomcat transport support but i believe esb pt and nhttp transports are preforming efficiently here but i also don’t have any reference. if you install apache camel on top of apache tomcat then you are not going to get the same performance and scalability. the latest esb performance benchmarks are posted for reference and replication.
May 9, 2013
by Chris Haddad
· 11,404 Views
article thumbnail
Extracting PDF Text with Scala
This example extracts the text contents of a PDF for use in other systems. This demonstrates some basic differences from Java: multi-line strings (hooray!), imports, primitive arrays, and what implementing an interface looks like. The big downside to this is that the Eclipse Scala plugin doesn’t seem to have the ability to fill in interface methods on an object. import java.io._ import org.apache.tika.parser.pdf._ import org.apache.tika.metadata._ import org.apache.tika.parser._ import org.xml.sax._ object pdfHandler extends ContentHandler { def characters(ch : Array[Char], start: Int, length: Int) { println(new String(ch)) } def endDocument() { } def endElement(uri: String, localName: String, qName: String) { } def endPrefixMapping(prefix: String) { } def ignorableWhitespace(ch: Array[Char], start: Int, length: Int) { } def processingInstruction(target: String, data: String) { } def setDocumentLocator(locator: Locator) { } def skippedEntity(name: String) { } def startDocument() { } def startElement(uri: String, localName: String, qName: String, atts: Attributes) { } def startPrefixMapping(prefix: String, uri: String) { } } object pdf extends App { val folder = """\\nas\Files\Data\pacer2\""" val subfolder = """\00\00\gov.uscourts.rid.6064\""" val file = """gov.uscourts.rid.6064.20.0.pdf""" val pdf : PDFParser = new PDFParser(); val stream : InputStream = new FileInputStream(folder + subfolder + file) val handler : ContentHandler = pdfHandler val metadata : Metadata = new Metadata() val context : ParseContext = new ParseContext() pdf.parse(stream, handler, metadata, context) stream.close() } Output: UNITED STATES DISTRICT COURT FOR THE DISTRICT OF RHODE ISLAND ... It is hereby agreed by and between the parties that the above-captioned matter be dismissed, with prejudice, no interest, no costs.
May 9, 2013
by Gary Sieling
· 10,605 Views
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,982 Views · 1 Like
article thumbnail
Setting Multiple Headers in a PHP Stream Context
Last week I tried to create a PHP stream context which set multiple headers; an Authorization header and a Content-Type header. All the examples I could find showed headers built up as a string with newlines added manually, which seemed pretty clunky and not-streams-like to me. In fact, you've been able to pass this as an array since PHP 5.2.10, so to set multiple headers in the stream context, I just used this: [ "method" => "POST", "header" => ["Authorization: token " . $access_token, "Content-Type: application/json"], "content" => $data ]]; $context = stream_context_create($options); The $access_token had been set elsewhere (in fact I usually put credentials in a separate file and exclude it from source control in an effort not to spread my access credentials further than I mean to!), and $data is already encoded as JSON. For completeness, you can make the POST request like this:
May 8, 2013
by Lorna Mitchell
· 12,854 Views
article thumbnail
Absolute Center Images With CSS
Here is a technique about how you can absolute center position an element on the horizontal and vertical in CSS. Center Images Horizontally To center something on the horizontal in CSS it's quite easy all you need to do is set the width on the element and apply an auto margin-left and margin-right on to the image. The browser will work out the exact margin on both the right and left side of the image. This will position the image in the center of the parent element just by using the width and the margin properties. img { width:250px; margin: 0 auto; } Center Images On Horizontal and Vertical Setting the image to be center on the horizontal is easy you just need to set an auto on the left and right margin. But to set the image on the vertical and on the horizontal you need to set the margin on the top and left of the element. The following technique is something you can use to display a pop-up window to show an image gallery in the center of the screen. This example will center the image with a width of 250px, first to set the image to be absolute positioned and set the top and left property to be 50%. This will position the image in the middle of screen, but the image won't be exactly center. img { height: 250px; left: 50%; position: absolute; top: 50%; width: 250px; } The top left corner of the image will be the exact center of the screen, to move this point to the center of the image we need to move the image half it's width and half it's height. To move the image on half it's width and half it's height you need to add a margin-top which is negative half the height of the image and a margin-left which is negative half the width of the image. img { height: 250px; left: 50%; margin-top: -125px; margin-left: -125px; position: absolute; top: 50%; width: 250px; }
May 8, 2013
by Paul Underwood
· 60,267 Views
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,735 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,719 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,302 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,904 Views · 1 Like
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,710 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,331 Views · 1 Like
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,532 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,029 Views · 22 Likes
article thumbnail
Pretty-Printing JSON with Python's JSON Tool
today's quick tip is something that was widely retweeted after my "debugging http" talk at the ever-fabulous whiskyweb conference last weekend. when working with json on the commandline, here's a quick tip for showing the json in a nicer format: curl http://api.joind.in | python -mjson.tool you need python installed, but the json extension is probably included, and that's all you need for this tool. the result is something like: you can also use this approach to present json data that has been captured to another file, for example, it's a handy trick that i use often when developing something with json as a data format.
April 16, 2013
by Lorna Mitchell
· 24,003 Views · 1 Like
article thumbnail
Grails Goodness: Using Wrapper for Running Grails Commands Without Grails Installation
Since Grails 2.1 we can create a Grails wrapper. The wrapper allows developer to run Grails commands in a project without installing Grails first. The wrapper concept is also available in other projects from the Groovy ecosystem like Gradle or Griffon. A wrapper is a shell script for Windows, OSX or Linux named grailsw.bat or grailsw and a couple of JAR files to automatically download a specific version of Grails. We can check in the shell scripts and supporting files into a version control system and make it part of the project. Developers working on the project simply check out the code and execute the shell script. If there is no Grails installation available then it will be downloaded. To create the shell scripts and supporting files someone on the project must run the wrapper command for the first time. This developer must have a valid Grails installation. The files that are generated can then be added to version control and from then one developers can use the grailsw or grailsw.bat shell scripts. $ grails wrapper | Wrapper installed successfully $ In the root of the project we have two new files grailsw and grailsw.bat. Windows users can uss grailsw.bat and on other operating systems we use grailsw. Also a new directory wrapper is created with three files: grails-wrapper-runtime-2.2.0.jar grails-wrapper.properties springloaded-core-1.1.1.jar When we run the grailsw or grailsw.bat scripts for the first time we see how Grails is downloaded and installed into the $USER_HOME/.grails/wrapper directory. The following output shows that the file is downloaded and extracted when we didn't run the grailsw script before: $ ./grailsw --version Downloading http://dist.springframework.org.s3.amazonaws.com/release/GRAILS/grails-2.2.0.zip to /Users/mrhaki/.grails/wrapper/grails-2.2.0-download.zip ..................................................................................... ................................................................ Extracting /Users/mrhaki/.grails/wrapper/grails-2.2.0-download.zip to /Users/mrhaki/.grails/wrapper/2.2.0 Grails version: 2.2.0 When we want to use a new version of Grails one of the developers needs to run to run $ grails upgrade followed by $ grails wrapper with the new Grails version. Notice this developer needs to have a locally installed Grails installation of the version we want to create a wrapper for. The newly generated files can be checked in to version control and all developers on the project will have the new Grails version when they run the grails or grailsw.bat shell scripts. $ ./grailsw --version Downloading http://dist.springframework.org.s3.amazonaws.com/release/GRAILS/grails-2.2.1.zip to /Users/mrhaki/.grails/wrapper/grails-2.2.1-download.zip ..................................................................................... ... ................................................................ Extracting /Users/mrhaki/.grails/wrapper/grails-2.2.1-download.zip to /Users/mrhaki/.grails/wrapper/2.2.1 Grails version: 2.2.1 We can change the download location of Grails to for example a company intranet URL. In the wrapper/ directory we see the file grails-wrapper.properties. The file has one property wrapper.dist.url, which by default refers to http://dist.springframework.org.s3.amazonaws.com/release/GRAILS/. We can change this to another URL, add the change to version control so other developers will get the change automatically. And when the grailsw shell script is executed the download location will be another URL. To set a different download URL when generating the wrapper we can use the command-line option --distributionUrl: $ grails wrapper --distributionUrl=http://company.intranet/downloads/grails-releases/ If we don't like the default name for the directory to store the supporting files we can use the command-line option --wrapperDir. The files are then stored in the given directory and the grailsw and grailsw.bat shell scripts will contain the given directory name. Written with Grails 2.2.0 and 2.2.1
April 16, 2013
by Hubert Klein Ikkink
· 5,854 Views
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,435 Views
  • Previous
  • ...
  • 424
  • 425
  • 426
  • 427
  • 428
  • 429
  • 430
  • 431
  • 432
  • 433
  • ...
  • 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
×