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 Popular Topics

article thumbnail
Classical Inheritance in JavaScript ES5
JavaScript’s prototype-based inheritance is interesting and has its uses, but sometimes one just wants to express classical inheritance, familiar from C++ and Java. This need has been recognized by the ECMAScript committee and classes are being discussed for inclusion in the next version of the standard. It was surprisingly hard for me to find a good and simple code sample that shows how to cleanly and correctly express inheritance with ES5 (a lot of links discuss how to implement the pre-ES5 tools required for that) and explains why the thing works. Mozilla’s Object.Create reference came close, but not quite there because it still left some open questions. Hence this short post. Without further ado, the following code defines a parent class named Shape with a constructor and a method, and a derived class named Circle that has its own method: // Shape - superclass // x,y: location of shape's bounding rectangle function Shape(x, y) { this.x = x; this.y = y; } // Superclass method Shape.prototype.move = function(x, y) { this.x += x; this.y += y; } // Circle - subclass function Circle(x, y, r) { // Call constructor of superclass to initialize superclass-derived members. Shape.call(this, x, y); // Initialize subclass's own members this.r = r; } // Circle derives from Shape Circle.prototype = Object.create(Shape.prototype); Circle.prototype.constructor = Circle; // Subclass methods. Add them after Circle.prototype is created with // Object.create Circle.prototype.area = function() { return this.r * 2 * Math.PI; } The most interesting part here, the one that actually performs the feat of inheritance is these two lines, so I’ll explain them a bit: Circle.prototype = Object.create(Shape.prototype); Circle.prototype.constructor = Circle; The first line is the magic – it sets up the prototype chain. To understand it, you must first understand that "the prototype of an object" and "the .prototype property of an object" are different things. If you don’t, go read on that a bit. The first line, interpreted very technically, says: the prototype of new objects created with the Circle constructor is an object whose prototype is the prototype of objects created by Shape constructor. Yeah, that’s a handful. But it can be simplified as: each Circle has a Shape as its prototype. What about the second line? While not strictly necessary, it’s there to preserve some useful invariants, as we’ll see below. Since the assignment to Circle.prototype kills the existing Circle.prototype.constructor (which was set to Circle when the Circle constructor was created), we restore it. Let’s whip up a JavaScript console and load that code inside, to quickly try some stuff: > var shp = new Shape(1, 2) undefined > [shp.x, shp.y] [1, 2] > shp.move(1, 1) undefined > [shp.x, shp.y] [2, 3] … but we’re here for the circles: > var cir = new Circle(5, 6, 2) undefined > [cir.x, cir.y, cir.r] [5, 6, 2] > cir.move(1, 1) undefined > [cir.x, cir.y, cir.r] [6, 7, 2] > cir.area() 12.566370614359172 So far so good, a Circle initialized itself correctly using the Shape constructor; it responds to the methods inherited from Shape, and to its own area method too. Let’s check that the prototype shenanigans worked as expected: > var shape_proto = Object.getPrototypeOf(shp) undefined > var circle_proto = Object.getPrototypeOf(cir) undefined > Object.getPrototypeOf(circle_proto) === shape_proto true Great. Now let’s see what instanceof has to say: > cir instanceof Shape true > cir instanceof Circle true > shp instanceof Shape true > shp instanceof Circle false Finally, here are some things we can do with the constructor property that wouldn’t have been possible had we not preserved it: > cir.constructor === Circle true // Create a new Circle object based on an existing Circle instance > var new_cir = new cir.constructor(3, 4, 1.5) undefined > new_cir Circle {x: 3, y: 4, r: 1.5, constructor: function, area: function} A lot of existing code (and programmers) expect the constructor property of objects to point back to the constructor function used to create them with new. In addition, it is sometimes useful to be able to create a new object of the same class as an existing object, and here as well the constructor property is useful. So that is how we express classical inheritance in JavaScript. It is very explicit, and hence on the long-ish side. Hopefully the future ES standards will provide nice sugar for succinct class definitions.
October 24, 2013
by Eli Bendersky
· 8,534 Views · 1 Like
article thumbnail
Performance Comparison Between Node.js and Java EE
I wanted to know: how would Java EE compare to Node.js in this particular case?
October 23, 2013
by Marc Fasel
· 287,919 Views · 12 Likes
article thumbnail
Using Maven to Build with Embedded Jetty
Previous posts such as this one have shown using embedded Jetty to REST-enable a standalone Java program. Those posts were lacking an important feature for real applications: packaging into a JAR so the application will run outside of Eclipse and won’t be dependent on Maven and jetty:run. To make this happen, we will use Maven to build an executable JAR that also includes all of the Jetty and Spring dependencies we need. The goal of this work is to get to the point where we can run the example application by: Cloning the Git repository. Running mvn package. Running java -jar target/webmvc-standalone.jar When I started adding the necessary bits to the pom.xml file of my sample application, I expected a relatively straightforward solution. I ended up with a relatively straightforward solution that was completely different from what I expected. So I think it’s worth a detailed discussion of how this solution works and what Maven is doing for us. Our desire to make an executable JAR is complicated by the fact that we want our Maven project to build a WAR as a default package, so that we can use this code in a Java web container if desired. Additionally, we introduce some complexity by making a single JAR with all dependencies, because that causes files in the Spring JARs to collide. I’ll show what I did to address each of these. Build both JAR and WAR The basic idea here is that we want Maven to make both a JAR file and a WAR file during the “package” phase. Our pom.xml file specifies war as the packaging for this project, so the WAR file will be created as expected. We need to add the JAR file without disturbing this. I found a great post here that got me started. The basic idea is to add the following to pom.xml under build/plugins: org.apache.maven.plugins maven-jar-plugin 2.4 package-jar package jar This is the behavior we would get for “free” if we used jar packaging inpom.xml. The execution section ties it to the package phase so that it runs during the default build process. The jar goal tells the plugin what to make. This gets us a basic JAR with the classes in the normal place for a JAR (rather than in WEB-INF/classes as they must be in the WAR file). At the same time, we need to deal with the fact that the Maven resources plugin considers only src/main/resources to be a resources directory, while in our case we have files in src/main/webapp that also need to be included. We want to copy these resources to the target directory so the JAR plugin will pick them up. (This is an important distinction; the typical Maven question, “how do I include extra resources in my JAR?” should really be “how do I get extra resources into target so the JAR plugin will pick them up?”) We add this to the build section of pom.xml: src/main/resources src/main/webapp This causes our new webmvc.jar file to include the HTML, JavaScript, etc. required for our embedded Jetty webapp. JAR with dependencies Next, we make an additional JAR that has the correct Main-Class entry in theMANIFEST.MF file and includes the necessary dependencies so we only have to ship one file. This is done using the Maven assembly plugin. The assembly plugin does repackaging only; that’s why we had to add a JAR artifact above. Without that JAR artifact to work from, the assembly plugin repackages the WAR, and we end up with classes in WEB-INF/classes. This causes Java to complain that it can’t find our main class when we try to run the JAR. The assembly plugin comes with a jar-with-dependencies configuration that can be used simply by adding it as a descriptorRef to the relevant section of pom.xml, as shown in this StackOverflow question. However, this configuration doesn’t work in our particular case, as the Spring dependencies we need have files with overlapping names. As a result, we need to make our own assembly configuration. Fortunately, this is pretty simple. We first add this to the build/plugins section of pom.xml: org.apache.maven.plugins maven-assembly-plugin 2.4 src/assemble/distribution.xml org.anvard.webmvc.server.EmbeddedServer package single As before, we use the executions section to make sure this is run automaticaly during package. We also specify the main class for our application. Finally, we point the plugin to our assembly configuration file, which lives in src/assemble. I present the assembly configuration below, but first we need to talk about the issue with the Spring JARs that made this custom assembly necessary. Spring schemas and handlers With this sample application, we use Spring WebMVC to provide a REST API for ordinary Java classes, as discussed in this post. The Spring code we use is spread across a few different JARs. Recent versions of Spring added a “custom XML namespace” feature that allows the contents of a Spring XML configuration file to be very extensible. Spring WebMVC, and other Spring libraries, use this feature to provide custom XML tags. In order to parse the XML file with these custom tags, Spring needs to be able to match these custom namespaces to handlers. To do this, Spring expects to find files called spring.handlers andspring.schemas in the META-INF directory of any JAR providing a Spring custom namespace. Several of the Spring JARs used by this application include thosespring.handlers and spring.schemas files. Of course, each JAR only includes its own handlers and schemas. When the Maven assembly plugin uses the jar-with-dependencies configuration, only one copy of those files “wins” and makes it into the executable JAR. We really just need a single spring.handlers and spring.schemas that are the concatentation of the respective files. There is probably some Maven magic to accomplish this, but I elected to do it manually as my Bash-fu is much greater than my Maven-fu. I added two files to the src/assemble directory that have the combined contents of the various files in the Spring JARs. Maven assembly configuration The assembly file looks like this: standalone jar true META-INF/spring.handlers META-INF/spring.schemas src/assemble/spring.handlers /META-INF false src/assemble/spring.schemas /META-INF false The id will be used to name this assembly. The baseDirectory tells the assembly plugin that the pieces it assembles should go at the root of the new JAR. (Otherwise they would go into a directory using the project name, in this case “webapp”.) The next two sections are important. We want to exclude thespring.handlers and spring.schemas from the Spring JARs (a.k.a. the dependency set). Instead, we want to explicitly include them from oursrc/assemble directory, and put them into the right place. We also want the assembly plugin to unpack the dependency set JARs so we wind up with Java class files in our new JAR, rather than just JAR-files-inside-JAR-file, which would not run correctly. Notice that there is no directive telling Spring to include all dependencies from the dependency set, including transitive dependencies. This is the default so we don’t need to specify it. It’s also the default to include the unpacked files from our own artifact (webmvc.jar) into the new JAR. Conclusion A real-world application would probably pick either WAR packaging or executable JAR packaging, and be simpler. Additionally, it would be possible to use multiple Maven modules to build a JAR and embed it in the WAR. But it’s interesting to see how to implement a more complex solution that builds everything we need from a single project.
October 18, 2013
by Alan Hohn
· 23,568 Views
article thumbnail
Too Many Parameters in Java Methods, Part 3: Builder Pattern
In my two immediately previous posts, I looked at reducing the number of parameters required for a constructor or method invocation via custom types and parameter objects. In this post, I look at use of thebuilder pattern to reduce the number of parameters required for a constructor with some discussion on how this pattern can even help with non-constructor methods that take too many parameters. In the Second Edition of Effective Java, Josh Bloch introduces use of the builder pattern in Item #2 for dealing with constructors that require too many parameters. Bloch not only demonstrates how to use the Builder, but explains it advantages over constructors accepting a large number of parameters. I will get to those advantages at the end of this post, but think it's important to point out that Bloch has devoted an entire item in his book to this practice. To illustrate the advantages of this approach, I'll use the following example Person class. It doesn't have all the methods I would typically add to such a class because I want to focus on its construction. Person.java (without Builder Pattern) package dustin.examples; /** * Person class used as part of too many parameters demonstration. * * @author Dustin */ public class Person { private final String lastName; private final String firstName; private final String middleName; private final String salutation; private final String suffix; private final String streetAddress; private final String city; private final String state; private final boolean isFemale; private final boolean isEmployed; private final boolean isHomewOwner; public Person( final String newLastName, final String newFirstName, final String newMiddleName, final String newSalutation, final String newSuffix, final String newStreetAddress, final String newCity, final String newState, final boolean newIsFemale, final boolean newIsEmployed, final boolean newIsHomeOwner) { this.lastName = newLastName; this.firstName = newFirstName; this.middleName = newMiddleName; this.salutation = newSalutation; this.suffix = newSuffix; this.streetAddress = newStreetAddress; this.city = newCity; this.state = newState; this.isFemale = newIsFemale; this.isEmployed = newIsEmployed; this.isHomewOwner = newIsHomeOwner; } } This class's constructor works, but it is difficult for client code to use properly. The Builder pattern can be used to make the constructor easier to use. NetBeans will refactor this for me as I have written about previously. An example of the refactored code is shown next (NetBeans does this by creating all new Builder class). PersonBuilder.java package dustin.examples; public class PersonBuilder { private String newLastName; private String newFirstName; private String newMiddleName; private String newSalutation; private String newSuffix; private String newStreetAddress; private String newCity; private String newState; private boolean newIsFemale; private boolean newIsEmployed; private boolean newIsHomeOwner; public PersonBuilder() { } public PersonBuilder setNewLastName(String newLastName) { this.newLastName = newLastName; return this; } public PersonBuilder setNewFirstName(String newFirstName) { this.newFirstName = newFirstName; return this; } public PersonBuilder setNewMiddleName(String newMiddleName) { this.newMiddleName = newMiddleName; return this; } public PersonBuilder setNewSalutation(String newSalutation) { this.newSalutation = newSalutation; return this; } public PersonBuilder setNewSuffix(String newSuffix) { this.newSuffix = newSuffix; return this; } public PersonBuilder setNewStreetAddress(String newStreetAddress) { this.newStreetAddress = newStreetAddress; return this; } public PersonBuilder setNewCity(String newCity) { this.newCity = newCity; return this; } public PersonBuilder setNewState(String newState) { this.newState = newState; return this; } public PersonBuilder setNewIsFemale(boolean newIsFemale) { this.newIsFemale = newIsFemale; return this; } public PersonBuilder setNewIsEmployed(boolean newIsEmployed) { this.newIsEmployed = newIsEmployed; return this; } public PersonBuilder setNewIsHomeOwner(boolean newIsHomeOwner) { this.newIsHomeOwner = newIsHomeOwner; return this; } public Person createPerson() { return new Person(newLastName, newFirstName, newMiddleName, newSalutation, newSuffix, newStreetAddress, newCity, newState, newIsFemale, newIsEmployed, newIsHomeOwner); } } I prefer to have my Builder as a nested class inside the class whose object it builds, but the NetBeans automatic generation of a standalone Builder is very easy to use. Another difference between the NetBeans-generated Builder and the Builders I like to write is that my preferred Builder implementations have required fields provided in the Builder's constructor rather than provide a no-arguments constructor. The next code listing shows my Person class from above with a Builder added into it as a nested class. Person.java with Nested Person.Builder package dustin.examples; /** * Person class used as part of too many parameters demonstration. * * @author Dustin */ public class Person { private final String lastName; private final String firstName; private final String middleName; private final String salutation; private final String suffix; private final String streetAddress; private final String city; private final String state; private final boolean isFemale; private final boolean isEmployed; private final boolean isHomewOwner; public Person( final String newLastName, final String newFirstName, final String newMiddleName, final String newSalutation, final String newSuffix, final String newStreetAddress, final String newCity, final String newState, final boolean newIsFemale, final boolean newIsEmployed, final boolean newIsHomeOwner) { this.lastName = newLastName; this.firstName = newFirstName; this.middleName = newMiddleName; this.salutation = newSalutation; this.suffix = newSuffix; this.streetAddress = newStreetAddress; this.city = newCity; this.state = newState; this.isFemale = newIsFemale; this.isEmployed = newIsEmployed; this.isHomewOwner = newIsHomeOwner; } public static class PersonBuilder { private String nestedLastName; private String nestedFirstName; private String nestedMiddleName; private String nestedSalutation; private String nestedSuffix; private String nestedStreetAddress; private String nestedCity; private String nestedState; private boolean nestedIsFemale; private boolean nestedIsEmployed; private boolean nestedIsHomeOwner; public PersonBuilder( final String newFirstName, final String newCity, final String newState) { this.nestedFirstName = newFirstName; this.nestedCity = newCity; this.nestedState = newState; } public PersonBuilder lastName(String newLastName) { this.nestedLastName = newLastName; return this; } public PersonBuilder firstName(String newFirstName) { this.nestedFirstName = newFirstName; return this; } public PersonBuilder middleName(String newMiddleName) { this.nestedMiddleName = newMiddleName; return this; } public PersonBuilder salutation(String newSalutation) { this.nestedSalutation = newSalutation; return this; } public PersonBuilder suffix(String newSuffix) { this.nestedSuffix = newSuffix; return this; } public PersonBuilder streetAddress(String newStreetAddress) { this.nestedStreetAddress = newStreetAddress; return this; } public PersonBuilder city(String newCity) { this.nestedCity = newCity; return this; } public PersonBuilder state(String newState) { this.nestedState = newState; return this; } public PersonBuilder isFemale(boolean newIsFemale) { this.nestedIsFemale = newIsFemale; return this; } public PersonBuilder isEmployed(boolean newIsEmployed) { this.nestedIsEmployed = newIsEmployed; return this; } public PersonBuilder isHomeOwner(boolean newIsHomeOwner) { this.nestedIsHomeOwner = newIsHomeOwner; return this; } public Person createPerson() { return new Person( nestedLastName, nestedFirstName, nestedMiddleName, nestedSalutation, nestedSuffix, nestedStreetAddress, nestedCity, nestedState, nestedIsFemale, nestedIsEmployed, nestedIsHomeOwner); } } } The Builder can be even nicer when enhanced through use of custom types and parameters objects as outlined in my first two posts on the "too many parameters" problem. This is shown in the next code listing. Person.java with Nested Builder, Custom Types, and Parameters Object package dustin.examples; /** * Person class used as part of too many parameters demonstration. * * @author Dustin */ public class Person { private final FullName name; private final Address address; private final Gender gender; private final EmploymentStatus employment; private final HomeownerStatus homeOwnerStatus; /** * Parameterized constructor can be private because only my internal builder * needs to call me to provide an instance to clients. * * @param newName Name of this person. * @param newAddress Address of this person. * @param newGender Gender of this person. * @param newEmployment Employment status of this person. * @param newHomeOwner Home ownership status of this person. */ private Person( final FullName newName, final Address newAddress, final Gender newGender, final EmploymentStatus newEmployment, final HomeownerStatus newHomeOwner) { this.name = newName; this.address = newAddress; this.gender = newGender; this.employment = newEmployment; this.homeOwnerStatus = newHomeOwner; } public FullName getName() { return this.name; } public Address getAddress() { return this.address; } public Gender getGender() { return this.gender; } public EmploymentStatus getEmployment() { return this.employment; } public HomeownerStatus getHomeOwnerStatus() { return this.homeOwnerStatus; } /** * Builder class as outlined in the Second Edition of Joshua Bloch's * Effective Java that is used to build a {@link Person} instance. */ public static class PersonBuilder { private FullName nestedName; private Address nestedAddress; private Gender nestedGender; private EmploymentStatus nestedEmploymentStatus; private HomeownerStatus nestedHomeOwnerStatus; public PersonBuilder( final FullName newFullName, final Address newAddress) { this.nestedName = newFullName; this.nestedAddress = newAddress; } public PersonBuilder name(final FullName newName) { this.nestedName = newName; return this; } public PersonBuilder address(final Address newAddress) { this.nestedAddress = newAddress; return this; } public PersonBuilder gender(final Gender newGender) { this.nestedGender = newGender; return this; } public PersonBuilder employment(final EmploymentStatus newEmploymentStatus) { this.nestedEmploymentStatus = newEmploymentStatus; return this; } public PersonBuilder homeOwner(final HomeownerStatus newHomeOwnerStatus) { this.nestedHomeOwnerStatus = newHomeOwnerStatus; return this; } public Person createPerson() { return new Person( nestedName, nestedAddress, nestedGender, nestedEmploymentStatus, nestedHomeOwnerStatus); } } } The last couple of code listings show how a Builder is typically used - to construct an object. Indeed, the item on the builder (Item #2) in Joshua Bloch's Second Edition of Effective Java is in the chapter on creating (and destroying) object. However, the builder can help indirectly with non-constructor methods by allowing an easier way to build parameters objects that are passed to methods. For example, in the last code listing, the methods have some parameters objects (FullName and Address) passed to them. It can be tedious for clients to have to construct these parameters objects and the builder can be used to make that process less tedious. So, although the builder is used for construction in each case, it indirectly benefits non-constructor methods by allowing for easier use of the parameters objects that reduce a method's argument count. The new definitions of the FullName and Address classes to be used as parameters objects and using the Builder themselves are shown next. FullName.java with Builder package dustin.examples; /** * Full name of a person. * * @author Dustin */ public final class FullName { private final Name lastName; private final Name firstName; private final Name middleName; private final Salutation salutation; private final Suffix suffix; private FullName( final Name newLastName, final Name newFirstName, final Name newMiddleName, final Salutation newSalutation, final Suffix newSuffix) { this.lastName = newLastName; this.firstName = newFirstName; this.middleName = newMiddleName; this.salutation = newSalutation; this.suffix = newSuffix; } public Name getLastName() { return this.lastName; } public Name getFirstName() { return this.firstName; } public Name getMiddleName() { return this.middleName; } public Salutation getSalutation() { return this.salutation; } public Suffix getSuffix() { return this.suffix; } @Override public String toString() { return this.salutation + " " + this.firstName + " " + this.middleName + this.lastName + ", " + this.suffix; } public static class FullNameBuilder { private final Name nestedLastName; private final Name nestedFirstName; private Name nestedMiddleName; private Salutation nestedSalutation; private Suffix nestedSuffix; public FullNameBuilder( final Name newLastName, final Name newFirstName) { this.nestedLastName = newLastName; this.nestedFirstName = newFirstName; } public FullNameBuilder middleName(final Name newMiddleName) { this.nestedMiddleName = newMiddleName; return this; } public FullNameBuilder salutation(final Salutation newSalutation) { this.nestedSalutation = newSalutation; return this; } public FullNameBuilder suffix(final Suffix newSuffix) { this.nestedSuffix = newSuffix; return this; } public FullName createFullName() { return new FullName( nestedLastName, nestedFirstName, nestedMiddleName, nestedSalutation, nestedSuffix); } } } Address.java with Builder package dustin.examples; /** * Representation of a United States address. * * @author Dustin */ public final class Address { private final StreetAddress streetAddress; private final City city; private final State state; private Address(final StreetAddress newStreetAddress, final City newCity, final State newState) { this.streetAddress = newStreetAddress; this.city = newCity; this.state = newState; } public StreetAddress getStreetAddress() { return this.streetAddress; } public City getCity() { return this.city; } public State getState() { return this.state; } @Override public String toString() { return this.streetAddress + ", " + this.city + ", " + this.state; } public static class AddressBuilder { private StreetAddress nestedStreetAddress; private final City nestedCity; private final State nestedState; public AddressBuilder(final City newCity, final State newState) { this.nestedCity = newCity; this.nestedState = newState; } public AddressBuilder streetAddress(final StreetAddress newStreetAddress) { this.nestedStreetAddress = newStreetAddress; return this; } public Address createAddress() { return new Address(nestedStreetAddress, nestedCity, nestedState); } } } With the above builders included in the classes, a Person instance can be created as shown in the next code listing. A more traditional instantiation of a Person instance is shown after that for comparison. Two Examples of Client Code Instantiating a Person with Builders final Person person1 = new Person.PersonBuilder( new FullName.FullNameBuilder( new Name("Dynamite"), new Name("Napoleon")).createFullName(), new Address.AddressBuilder( new City("Preston"), State.ID).createAddress()).createPerson(); final Person person2 = new Person.PersonBuilder( new FullName.FullNameBuilder( new Name("Coltrane"), new Name("Rosco")).middleName(new Name("Purvis")).createFullName(), new Address.AddressBuilder( new City("Hazzard"), State.GA).createAddress()) .gender(Gender.MALE).employment(EmploymentStatus.EMPLOYED).createPerson(); Instantiating a Person Without a Builder final person = new Person("Coltrane", "Rosco", "Purvis", null, "Hazzard", "Georgia", false, true, true); As the previous code snippets show, the client code for calling a traditional Java constructor is far less readable and far easier to mess up than use of the builder classes. The variety of the same types (strings and booleans) and the necessity to place nulls in the constructor call for optional attributes make provide many ways for this approach to end badly. Benefits and Advantages There is a considerable cost to the Builder pattern in that one must essentially double the number of lines of code each attribute and for setting those attributes. This price pays off, however, when the client code benefits greatly in terms of usability and readability. The parameters to the constructor are reduced and are provided in highly readable method calls. Another advantage of the Builder approach is the ability to acquire an object in a single statement and state without the object in multiple states problem presented by using "set" methods. I am increasingly appreciating the value of immutability in a multi-core world and the Builder pattern is perfectly suited for an immutable class when that class features a large number of attributes. I also like that there is no need to pass in null for optional parameters to the constructor. The Builder pattern not only makes the code more readable, but makes it even easier to apply an IDE's code completion feature. Further benefits of the Builder pattern when used with constructors are outlined in Item #2 of the Second Edition of Effective Java. Costs and Disadvantages As shown and mentioned above, the number of lines of code of a given class must be essentially doubled for "set" methods with the builder approach. Furthermore, although client code is more readable, the client code is also more verbose. I consider the benefit of greater readability worth the cost as the number of arguments increase or as more arguments share the same type or as the number of optional arguments increase. More lines of code in the class with the builder sometimes mean that developers may forget to add support for a new attribute to the builder when they add that attribute to the main class. To try to help with this, I like to nest my builders inside the class that they build so that it's more obvious to the developer that there is a relevant builder that needs to be similarly updated. Although there is still risk of the developer forgetting to add support for a new attribute to the builder, this is really no different than the risk of forgetting to add a new attribute to a class's toString(), equals(Object), hashCode() or other methods often based on all attributes of a class. In my implementation of the Builder, I made the client pass required attributes into the builder's constructor rather than via "set" methods. The advantage of this is that the object is always instantiated in a "complete" state rather than sitting in an incomplete state until the developer calls (if ever calls) the appropriate "set" method to set additional fields. This is necessary to enjoy the benefits of immutability. However, a minor disadvantage of that approach is that I don't get the readability advantages of methods named for the field I am setting. The Builder, as its name suggests, is really only an alternative to constructors and not directly used to reduce the number of non-constructor method parameters. However, the builder can be used in conjunction with parameters objects to reduce the number of non-constructor method arguments. Further arguments against use of the Builder for object construction can be found in a comment on the A dive into the Builder pattern post. Conclusion I really like the Builder pattern for constructing objects when I have a lot of parameters, especially if many of these parameters are null and when many of them share the same data type. A developer might feel that the extra code to implement a Builder might not justify its benefits for a small number of parameters, especially if the few parameters are required and of different types. In such cases, it might be considered desirable to use traditional constructors or, if immutability is not desired, use a no-argument constructor and require the client to know to call the necessary "set" methods.
October 18, 2013
by Dustin Marx
· 29,173 Views · 2 Likes
article thumbnail
The Blogging Programmer's Style Guide: Does Anyone Hyphenate "Open Source" Anymore?
Hyphenation is always a big question, and the fact that it can vary for the same word causes significant confusion. This article will give you some tips and common usages.
October 17, 2013
by Mitch Pronschinske
· 21,685 Views · 2 Likes
article thumbnail
Incrementally Read/Stream a CSV File in Java
I’ve been doing some work that involves reading in CSV files, for which I’ve been using OpenCSV, and my initial approach was to read through the file line by line, parse the contents, and save it into a list of maps. This works when the contents of the file fit into memory, but is problematic for larger files where I needed to stream the file and process each line individually, rather than all of them after the file was loaded. I initially wrote a variation on totallylazy’s Strings#lines to do this, and while I was able to stream the file, I made a mistake somewhere which meant the number of maps on the heap was always increasing. After spending a few hours trying to fix this, Michael suggested that it’d be easier to use an iterator instead, and I ended up with the following code: public class ParseCSVFile { public static void main(String[] args) throws IOException { final CSVReader csvReader = new CSVReader( new BufferedReader( new FileReader( "/path/to/file.csv" ) ), '\t' ); final String[] fields = csvReader.readNext(); Iterator>() lazilyLoadedFile = return new Iterator>() { String[] data = csvReader.readNext(); @Override public boolean hasNext() { return data != null; } @Override public Map next() { final Map properties = new HashMap(); for ( int i = 0; i < data.length; i++ ) { properties.put(fields[i], data[i]); } try { data = csvReader.readNext(); } catch ( IOException e ) { data = null; } return properties; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } } Although this code works, it’s not the most readable function I’ve ever written, so any suggestions on how to do this in a cleaner way are welcome.
October 15, 2013
by Mark Needham
· 11,410 Views
article thumbnail
Adding SSL Support to an Embedded Jetty Server
With these changes, we can access the REST API equally well fromhttp://:9999 and https://:9998.
October 14, 2013
by Alan Hohn
· 54,862 Views · 1 Like
article thumbnail
Functional Programming with Groovy
I have recently started the Coursera Functional Programming with Scala course (taught by Martin Odersky - the creator of Scala) - which is actually serving as an introduction to both FP and Scala at the same time having done neither before. The course itself is great, however, trying to watch the videos and take in both the new Scala syntax and the FP concepts at the same time can take a bit of effort. I wanted to work through some of the core FP concepts in a more familiar context, so am going to apply some of the lessons/principles/exercises in Groovy. Functions: If you have done any Groovy programming then you will have come across Groovy functions/closures. As Groovy is dynamically typed (compared to Scala's static typing), you can play it fairly fast and loose. For example, if we take the square root function that is demonstrated in the Scala course, it is defined as follows: def sqrt(x: Double): Double = ... As you can see, Scala expects the values to be typed (aside, you don't actually always need to provide a return type in Scala). But in the Groovy function it is: def sqrt = {x-> ... } A groovy function can be defined and assigned to any variable, thereby allowing it to be passed around as a first class object. If we look at the complete solution for calculating the square root of a number (using Newton's method - To compute the square root of "x" we start with an estimate of the square root, "y" and continue to improve the the guess by taking the mean of x and x/y ) def sqrtIter(guess: Double, x: Double): Double = if (isGoodEnough(guess, x)) guess else sqrtIter(improve(guess, x), x) def improve(guess: Double, x: Double) = (guess + x / guess) / 2 def isGoodEnough(guess: Double, x: Double) = abs(guess * guess - x) < 0.001 def sqrt(x: Double) = srqtIter(1.0, x) So that's in Scala, if we try Groovy we will see we can achieve pretty much the same thing easily: //Improve the guess using Newton's method def improve = { guess, x -> (guess + x / guess) / 2 } //Check if our guess is good enough, within a chosen threshold def isGoodEnough = {guess, x -> abs(guess * guess - x) < 0.001 } //iterate over guesses until our guess is good enough def sqrtIter = { guess, x -> if (isGoodEnough(guess, x)) guess else sqrtIter(improve(guess, x), x) } //wrap everythin in the square root function call def sqrt = {x -> srqtIter(1.0, x)} Recursion (and tail-recursion): As FP avoids having mutable state, the most common approach to solve problems is to break the problem down in to simple functions and call them recursively - This avoids having to maintain state whilst iterating through loops, and each function call is given its input and produces an output. If we again consider an example from the Scala course, with the example of a simple function that calculates the factorial for a given number. def factorial ={ n -> if (n == 0) 1 else n * factorial(n - 1) } factorial(4) This simple function recursively calculates the factorial, continuing to call itself until all numbers to zero have been considered. As you can see, there is no mutable state - every call to the factorial function simply takes the input and returns an output (the value of n is never changed or re-assigned, n is simply used to calculate output values) There is a problem here, and that is as soon as you attempt to calculate the factorial of a significantly large enough number you will encounter a StackOverflow exception - this is because in the JVM every time a function is called, a frame is added to the stack, so working recursively its pretty easy to hit upon the limit of the stack and encounter this problem. The common way to solve this is by using Tail-Call recursion. This trick is simply to have the last code that is evaluated in the function to be the recursive call - normally in FP languages the compiler/interpreter will recognise this pattern and under the hood, it will really just run the code as a loop (e.g. if we know the very last piece of code in the block of code is calling itself, its really not that different to just having the block of code/function inside a loop construct) In the previous factorial example, it might look like the last code to be executed is the recursive callfactorial(n-1) - however, the value of that call is actually returned to the function and THENmultiplied by n - so actually the last piece of code to be evaluated in the function call is actually n * return value of factorial(n-1). Let's have a look at re-writing the function so it is tail-recursive. def factorial ={ n, accumulator=1 -> if (n == 1) accumulator else factorial(n-1, n*accumulator) } factorial(4) Now, using an accumulator, the last code to be evaluated in the function is our recursive function call. In most FP languages, including Scala, this is enough - however, the JVM doesn't automatically support tail-call recursion, so you actually need to use a rather clunkier approach in Groovy: def factorial ={ n, accumulator=1 -> if (n == 1) accumulator else factorial.trampoline(n-1, n*accumulator) }.trampoline() factorial(4) The use of the trampoline() method means that the function will now be called using tail-call recursion, so there should never be a StackOverflow exception. It's not as nice as in Scala or other languages, but the support is there so we can continue. Currying: This is like function composition - the idea being you take a generic function, and then you curry it with some value to make a more specific application of the function. For example, if we look at a function that given values x and y, it returns z which is the value x percent of y (e.g. given x=10, y=100, it returns the 10 percent of 100, z=10) def percentage = { percentage, x -> x/100 * percentage } The above simple function is a generic mechanism to get a percentage value of another, but if we consider that we wanted a common application of this function was to always calculate 10% of a given value - rather than write a slightly modified version of the function we can simply curry the function as follows: def tenPercent = percentage.curry(10) Now, if the function tenPercent(x) is called, it uses the original percentage() function, but curries the value 10 as the first argument. (If you need to curry other argument positions you can also use the rcurry() function to curry the right most argument, or ncurry() which also takes an argument position - check the Groovy docs on currying for more info) Immutability: Immutability is partially supported in Java normally with use of the final keyword (meaning variables can't be changed after being initially set on object instantiation). Groovy also provides a quick and easy @Immutable annotation that can be added to a class to easily make it immutable. But really, there is more to avoiding immutable state than just having classes as immutable - As we have functions as first class objects, we can easily assign variables and mutate them within a function - so this is more of a mindset or philosophy that you have to get used to. For example: def list = ['groovy', 'functional'] //This mutates the original list list.add('programming') //This creates a new list leaving the original unchanged def newList = list.plus(2, 'programming') The first example is probably more like the Groovy/Java code we are used to writing, but that is mutating the state of the list - where as the second approach leaves the original list unchanged. Map Reduce: As a final note, there are some functions in FP that are pretty common techniques - the most famous of which these days (in part thanks to Google) is Map-Reduce, but the trio of functions are actually Map, Reduce(also known as Fold) & Filter - you can read more about the functions here (or just google them!), but these functions actually correlate pretty nicely to core Groovy functions that you probably use a lot of (assuming you are groovy programmers). Map map is the easiest to understand of the three. It takes in two inputs - a function, and a list. It then applies this function to every element in the list. You can basically do the same thing with a list comprehension however. Sound familiar? This is basically the .collect{} function in Groovy Reduce/Fold fold takes in a function and folds it in between the elements of a list. It's a bit hard to understand at first This one is a bit more complicated to descibe, but is the same as the .inject{} function in groovy Filter filter is easy. It takes in a 'test' and a list, and it chucks out any elements of the list which don't satisfy that test. And another simple one - filtering out a list for desired elements, this is Groovy's .findAll{} function As I said at the start, I am new to FP and coming from an OO background, but hopefully the above isn't too far from the truth! As I get further through the Coursera course I will try to post again, maybe with some of the assignments attempted in Groovy to see how it really stands up. Some useful references: Groovy docs on FP: http://groovy.codehaus.org/Functional+Programming+with+Groovy Coursera Scala course: https://www.coursera.org/course/progfun
October 14, 2013
by Rob Hinds
· 37,647 Views · 2 Likes
article thumbnail
Tutorial: How to Create a Responsive Website with AngularJS
in today’s tutorial, i’m going to show you the process of creating nearly an entire website with a new library – angularjs. however, i would like to introduce to you to angularjs first. angularjs is a magnificent framework by google for creating web applications. this framework lets you extend html’s syntax to express your application’s components clearly and succinctly, and lets you use standard html as your main template language. plus, it automatically synchronizes data from your ui with your js objects through 2-way data binding. if you’ve ever worked with jquery, the first thing to understand about angular is that this is a completely different instrument. jquery is a library, but angularjs is framework. when your code works with the library, it decides when to call a particular function or operator. in the case of the framework, you implement event handlers, and the framework decides at what moment it needs to invoke them. using this framework allows us to clearly distinguish between templates (dom), models, and functionality (in controllers). let’s come back to our template, take a look at our result: live demo download in package description this template is perfect for business sites. it consists of several static pages: projects, privacy, and about pages. each product has its own page. there is also a contact form for communication. that is all that is necessary for any small website. moreover, it is also a responsive template, thus it looks good on any device. i hope you liked the demo, so if you’re ready – let’s start making this application. please prepare a new folder for our project, and then create new folders in this directory: css – for stylesheet files images – for image files js – for javascript files (libraries, models, and controllers) pages – for internal pages stage 1. html the main layout consists of four main sections: a header with navigation, a hidden ‘contact us’ form, a main content section, and a footer. first we have to prepare a proper header: index.html as you can see, it’s an ordinary header. now – the header with the navigation: our projectsprivacy & termsaboutcontact us it's an ordinary logo, and the menu is the usual ul-li menu. the next section is more interesting – the ‘contact us’ form: contact us send message your message has been sent, thank you. finally, the last key element is the main content section: have you noticed the numerous ‘ng-’ directives? all these directives allow us to do various actions directly in the dom, for example: ng-class – the ngclass allows you to set css classes on an html element dynamically by databinding an expression that represents all classes to be added. ng-click – the ngclick allows you to specify custom behavior when element is clicked. ng-hide – the nghide directive shows and hides the given html element conditionally based on the expression provided to the nghide attribute. ng-include – fetches, compiles, and includes an external html fragment. ng-model – is a directive that tells angular to do two-way data binding. ng-show – the ngshow directive shows and hides the given html element conditionally based on the expression provided to the ngshow attribute. ng-submit – enables binding angular expressions to onsubmit events. stage 2. css in this rather large section, you can find all the styles used: css/style.css /* general settings */ html { min-height:100%; overflow-x:hidden; overflow-y:scroll; position:relative; width:100%; } body { background-color:#e6e6e6; color:#fff; font-weight:100; margin:0; min-height:100%; width:100%; } a { text-decoration:none; } a img { border:none; } h1 { font-size:3.5em; font-weight:100; } p { font-size:1.5em; } input,textarea { -webkit-appearance:none; background-color:#f7f7f7; border:none; border-radius:3px; font-size:1em; font-weight:100; } input:focus,textarea:focus { border:none; outline:2px solid #7ed7b9; } .left { float:left; } .right { float:right; } .btn { background-color:#fff; border-radius:24px; color:#595959; display:inline-block; font-size:1.4em; font-weight:400; margin:30px 0; padding:10px 30px; text-decoration:none; } .btn:hover { opacity:0.8; } .wrap { -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; margin:0 auto; max-width:1420px; overflow:hidden; padding:0 50px; position:relative; width:100%; } .wrap:before { content:''; display:inline-block; height:100%; margin-right:-0.25em; vertical-align:middle; } /* header section */ header { height:110px; } header .wrap { height:100%; } header .logo { margin-top:1px; } header nav { float:right; margin-top:17px; } header nav ul { margin:1em 0; padding:0; } header nav ul li { display:block; float:left; margin-right:20px; } header nav ul li a { border-radius:24px; color:#aaa; font-size:1.4em; font-weight:400; padding:10px 27px; text-decoration:none; } header nav ul li a.active { background-color:#c33c3a; color:#fff; } header nav ul li a.active:hover { background-color:#d2413f; color:#fff; } header nav ul li a:hover,header nav ul li a.activesmall { color:#c33c3a; } /* footer section */ footer .copyright { color:#adadad; margin-bottom:50px; margin-top:50px; text-align:center; } /* other objects */ .projectobj { color:#fff; display:block; } .projectobj .name { float:left; font-size:4em; font-weight:100; position:absolute; width:42%; } .projectobj .img { float:right; margin-bottom:5%; margin-top:5%; width:30%; } .paddrow { background-color:#dadada; color:#818181; display:none; padding-bottom:40px; } .paddrow.aboutrow { background-color:#78c2d4; color:#fff !important; display:block; } .paddrow .head { font-size:4em; font-weight:100; margin:40px 0; } .paddrow .close { cursor:pointer; position:absolute; right:50px; top:80px; width:38px; } .about { color:#818181; } .about section { margin:0 0 10%; } .about .head { font-size:4em; font-weight:100; margin:3% 0; } .about .subhead { font-size:2.5em; font-weight:100; margin:0 0 3%; } .about .txt { width:60%; } .about .image { width:26%; } .about .flleft { float:left; } .about .flright { float:right; } .projecthead.product { background-color:#87b822; } .projecthead .picture { margin-bottom:6%; margin-top:6%; } .projecthead .picture.right { margin-right:-3.5%; } .projecthead .text { position:absolute; width:49%; } .projecthead .centertext { margin:0 auto; padding-bottom:24%; padding-top:6%; text-align:center; width:55%; } .image { text-align:center; } .image img { vertical-align:top; width:100%; } .contactform { width:50%; } .input { -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; margin:1% 0; padding:12px 14px; width:47%; } .input.email { float:right; } button { border:none; cursor:pointer; } .textarea { -moz-box-sizing:border-box; -webkit-box-sizing:border-box; box-sizing:border-box; height:200px; margin:1% 0; overflow:auto; padding:12px 14px; resize:none; width:100%; } ::-webkit-input-placeholder { color:#a7a7a7; } :-moz-placeholder { color:#a7a7a7; } ::-moz-placeholder { /* ff18+ */ color:#a7a7a7; } :-ms-input-placeholder { color:#a7a7a7; } .loader { -moz-animation:loader_rot 1.3s linear infinite; -o-animation:loader_rot 1.3s linear infinite; -webkit-animation:loader_rot 1.3s linear infinite; animation:loader_rot 1.3s linear infinite; height:80px; width:80px; } @-moz-keyframes loader_rot { from { -moz-transform:rotate(0deg); } to { -moz-transform:rotate(360deg); } } @-webkit-keyframes loader_rot { from { -webkit-transform:rotate(0deg); } to { -webkit-transform:rotate(360deg); } } @keyframes loader_rot { from { transform:rotate(0deg); } to { transform:rotate(360deg); } } .view-enter,.view-leave { -moz-transition:all .5s; -o-transition:all .5s; -webkit-transition:all .5s; transition:all .5s; } .view-enter { left:20px; opacity:0; position:absolute; top:0; } .view-enter.view-enter-active { left:0; opacity:1; } .view-leave { left:0; opacity:1; position:absolute; top:0; } .view-leave.view-leave-active { left:-20px; opacity:0; } please note that css3 transitions are used, which means that our demonstration will only work modern browsers (ff, chrome, ie10+ etc) stage 3. javascript as i mentioned before, our main controller and the model are separated. the navigation menu can be handled here, and we also can operate with the contact form. js/app.js 'use strict'; // angular.js main app initialization var app = angular.module('example359', []). config(['$routeprovider', function ($routeprovider) { $routeprovider. when('/', { templateurl: 'pages/index.html', activetab: 'projects', controller: homectrl }). when('/project/:projectid', { templateurl: function (params) { return 'pages/' + params.projectid + '.html'; }, controller: projectctrl, activetab: 'projects' }). when('/privacy', { templateurl: 'pages/privacy.html', controller: privacyctrl, activetab: 'privacy' }). when('/about', { templateurl: 'pages/about.html', controller: aboutctrl, activetab: 'about' }). otherwise({ redirectto: '/' }); }]).run(['$rootscope', '$http', '$browser', '$timeout', "$route", function ($scope, $http, $browser, $timeout, $route) { $scope.$on("$routechangesuccess", function (scope, next, current) { $scope.part = $route.current.activetab; }); // onclick event handlers $scope.showform = function () { $('.contactrow').slidetoggle(); }; $scope.closeform = function () { $('.contactrow').slideup(); }; // save the 'contact us' form $scope.save = function () { $scope.loaded = true; $scope.process = true; $http.post('sendemail.php', $scope.message).success(function () { $scope.success = true; $scope.process = false; }); }; }]); app.config(['$locationprovider', function($location) { $location.hashprefix('!'); }]); pay attention here. when we request a page, it loads an appropriate page from the ‘pages’ folder: about.html, privacy.html, index.html. depending on the selected product, it opens one of the product pages: product1.html, product2.html, product3.html or product4.html in the second half, there are functions to slide the contact form and to handle its submit process (to the sendemail.php page). next is the controller file: js/controllers.js 'use strict'; // optional controllers function homectrl($scope, $http) { } function projectctrl($scope, $http) { } function privacyctrl($scope, $http, $timeout) { } function aboutctrl($scope, $http, $timeout) { } it is empty, because we have nothing to use here at the moment. stage 4. additional pages angularjs loads pages asynchronously, thereby increasing the speed. here are templates of all additional pages used in our project: pages/about.html about us script tutorials is one of the largest web development communities. we provide high quality content (articles and tutorials) which covers all the web development technologies including html5, css3, javascript (and jquery), php and so on. our audience are web designers and web developers who work with web technologies. additional information promo 1 lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. ..... pages/privacy.html privacy & terms by accessing this web site, you are agreeing to be bound by these web site terms and conditions of use, all applicable laws and regulations, and agree that you are responsible for compliance with any applicable local laws. if you do not agree with any of these terms, you are prohibited from using or accessing this site. the materials contained in this web site are protected by applicable copyright and trade mark law. other information header 1 lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. ..... pages/footer.html copyright © 2013 script tutorials pages/index.html product #1 product #2 product #3 product #4 finally, the product pages. all of them are prototypes, so i decided to publish only one of them. pages/index.html product 1 page lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. lorem ipsum dolor sit amet, consectetur adipiscing elit. nunc et ligula accumsan, pharetra nibh nec, facilisis nulla. in pretium semper venenatis. in adipiscing augue elit, at venenatis enim suscipit a. fusce vitae justo tristique, ultrices mi metus. download the app finishing touches – responsive styles all of these styles are needed to make our results look equally good on all possible mobile devices and monitors: @media (max-width: 1200px) { body { font-size:90%; } h1 { font-size:4.3em; } p { font-size:1.3em; } header { height:80px; } header .logo { margin-top:12px; width:200px; } header nav { margin-top:11px; } header nav ul li { margin-right:12px; } header nav ul li a { border-radius:23px; font-size: 1.3em; padding:10px 12px; } .wrap { padding:0 30px; } .paddrow .close { right:30px; } } @media (max-width: 900px) { .contactform { width:100%; } } @media (max-width: 768px) { body { font-size:80%; margin:0; } h1 { font-size:4em; } header { height:70px; } header .logo { margin-top:20px; width:70px; } header nav { margin-top:8px; } header nav ul li { margin-right:5px; } header nav ul li a { border-radius:20px; font-size:1.1em; padding:8px; } .wrap { padding:0 15px; } .projectobj .name { font-size:3em; } .paddrow { padding-bottom:30px; } .paddrow .head { font-size:3em; margin:30px 0; } .paddrow .close { right:20px; top:60px; width:30px; } .projecthead .picture { width:67%; } .projecthead .picture.right { margin-right:16.5%; } .projecthead .text { position:static; width:100%; } .projecthead .centertext { width:70%; } .view-enter,.view-leave { -webkit-transform:translate3d(0,0,0); transform:translate3d(0,0,0); } } @media (max-width: 480px) { body { font-size:70%; margin:0; } header { height:50px; } header .logo { display:none; } header nav { margin-top:3px; } header nav ul li { margin-right:3px; } header nav ul li a { border-radius:20px; font-size:1.3em; padding:5px 14px; } #contactbtn { display:none; } .wrap { padding:0 10px; } .paddrow { padding-bottom:20px; } .paddrow .head { margin:20px 0; } .paddrow .close { right:10px; top:45px; width:20px; } .about .image { margin:10% auto; width:60%; } .about .abicon { display:inline; } .projecthead .centertext { width:90%; } .about .txt,.input { width:100%; } .about .flleft,.about .flright,.input.email { float:none; } } live demo download in package conclusion that’s all for today. thanks for your patient attention, and if you really like what we did today, share it with all your friends in your social networks.
October 10, 2013
by Andrei Prikaznov
· 313,154 Views · 10 Likes
article thumbnail
Oracle Weblogic Stuck Thread Detection
The following question will again test your knowledge of the Oracle Weblogic threading model. I’m looking forward for your comments and experience on the same. If you are a Weblogic administrator, I’m certain that you heard of this common problem: stuck threads. This is one of the most common problems you will face when supporting a Weblogic production environment. A Weblogic stuck thread simply means a thread performing the same request for a very long time and more than the configurable Stuck Thread Max Time. Question: How can you detect the presence of STUCK threads during and following a production incident? Answer: As we saw from our last article “Weblogic Thread Monitoring Tips”, Weblogic provides functionalities allowing us to closely monitor its internal self-tuning thread pool. It will also highlight you the presence of any stuck thread. This monitoring view is very useful when you do a live analysis but what about after a production incident? The good news is that Oracle Weblogic will also log any detected stuck thread to the server log. Such information includes details on the request and more importantly, the thread stack trace. This data is crucial and will allow you to potentially better understand the root cause of any slowdown condition that occurred at a certain time. < ExecuteThread: '11' for queue: 'weblogic.kernel.Default (self-tuning)'> <[STUCK] ExecuteThread: '35' for queue: 'weblogic.kernel.Default (self-tuning)' has been busy for "608" seconds working on the request "Workmanager: default, Version: 0, Scheduled=true, Started=true, Started time: 608213 ms POST /App1/jsp/test.jsp HTTP/1.1 Accept: application/x-ms-application... Referer: http://.. Accept-Language: en-US User-Agent: Mozilla/4.0 .. Content-Type: application/x-www-form-urlencoded Accept-Encoding: gzip, deflate Content-Length: 539 Connection: Keep-Alive Cache-Control: no-cache Cookie: JSESSIONID= ]", which is more than the configured time (StuckThreadMaxTime) of "600" seconds. Stack trace: ................................... javax.servlet.http.HttpServlet.service(HttpServlet.java:727) javax.servlet.http.HttpServlet.service(HttpServlet.java:820) weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227) weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125) weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301) weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:184) weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.... weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run() weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321) weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120) weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2281) weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2180) weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1491) weblogic.work.ExecuteThread.execute(ExecuteThread.java:256) weblogic.work.ExecuteThread.run(ExecuteThread.java:221) Here is one more tip: the generation and analysis of a JVM thread dump will also highlight you stuck threads. As we can see from the snapshot below, the Weblogic thread state is now updated to STUCK, which means that this particular request is being executed since at least 600 seconds or 10 minutes. This is very useful information since the native thread state will typically remain to RUNNABLE. The native thread state will only get updated when dealing with BLOCKED threads etc. You have to keep in mind that RUNNABLE simply means that this thread is healthy from a JVM perspective. However, it does not mean that it truly is from a middleware or Java EE container perspective. This is why Oracle Weblogic has its own internal ExecuteThread state. Finally, if your organization or client is using any commercial monitoring tool, I recommend that you enable some alerting around both hogging thread and stuck thread. This will allow your support team to take some pro-active actions before the affected Weblogic managed server(s) become fully unresponsive.
October 9, 2013
by Pierre - Hugues Charbonneau
· 54,999 Views
article thumbnail
Add REST to Standalone Java with Jetty and Spring WebMVC
I’m going to start by discussing the Spring WebMVC configuration and move on from there in future posts.
October 7, 2013
by Alan Hohn
· 36,689 Views · 1 Like
article thumbnail
Hibernate Search based Autocomplete Suggester
In this article, I will show how to implement auto-completion using Hibernate Search. The same can be achieved using Solr or ElasticSearch. But I decided to use Hibernate Search as its the simplest to get started with, easily integrates with an existing application and leverages the same core - Lucene. And we get all of this without the overhead of managing Solr/ElasticSearch cluster. In all, I found Hibernate Search to be the go-to search engine for simple use cases. For our use case, we build a product title based auto-completion where often, the user queries are searches for product title. While typing, users should immediately see titles matching their requests, and Hibernate Search should do the hard work to filter the relevant documents in near real-time. Lets have the following JPA annotated Product entity class. public class Product { @Id @Column(name = "sku") private String sku; @Column(name = "upc") private String upc; @Column(name = "title") private String title; .... } We are interested in returning suggestions based on the 'title' field. Title will be indexed based on 2 strategies - N-Gram and Edge N-Gram. Edge N-Gram - This will match only from the left edge of the suggestion text. For this we use KeywordTokenizerFactory (emits the entire input as a single token) and EdgeNGramFilterFactory along with some regex cleansing. N-Gram matches from the start of every word, so that you can get right-truncated suggestions for any word in the text, not only from the first word. The main difference from N-gram is the tokenizer which is StandardTokenizerFactory along with NGramFilterFactory. Using these strategies, if the document field is "A brown fox" and the query is a) "A bro"- Will match b) "bro" - Will match Implementation: In the entity defined above, we can map 'title' property twice with the above strategies. Below are the annotations to instruct Hibernate to index 'title' twice. @Entity @Table(name = "item_master") @Indexed(index = "Products") @AnalyzerDefs({ @AnalyzerDef(name = "autocompleteEdgeAnalyzer", // Split input into tokens according to tokenizer tokenizer = @TokenizerDef(factory = KeywordTokenizerFactory.class), filters = { // Normalize token text to lowercase, as the user is unlikely to // care about casing when searching for matches @TokenFilterDef(factory = PatternReplaceFilterFactory.class, params = { @Parameter(name = "pattern",value = "([^a-zA-Z0-9\\.])"), @Parameter(name = "replacement", value = " "), @Parameter(name = "replace", value = "all") }), @TokenFilterDef(factory = LowerCaseFilterFactory.class), @TokenFilterDef(factory = StopFilterFactory.class), // Index partial words starting at the front, so we can provide // Autocomplete functionality @TokenFilterDef(factory = EdgeNGramFilterFactory.class, params = { @Parameter(name = "minGramSize", value = "3"), @Parameter(name = "maxGramSize", value = "50") }) }), @AnalyzerDef(name = "autocompleteNGramAnalyzer", // Split input into tokens according to tokenizer tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class), filters = { // Normalize token text to lowercase, as the user is unlikely to // care about casing when searching for matches @TokenFilterDef(factory = WordDelimiterFilterFactory.class), @TokenFilterDef(factory = LowerCaseFilterFactory.class), @TokenFilterDef(factory = NGramFilterFactory.class, params = { @Parameter(name = "minGramSize", value = "3"), @Parameter(name = "maxGramSize", value = "5") }), @TokenFilterDef(factory = PatternReplaceFilterFactory.class, params = { @Parameter(name = "pattern",value = "([^a-zA-Z0-9\\.])"), @Parameter(name = "replacement", value = " "), @Parameter(name = "replace", value = "all") }) }), @AnalyzerDef(name = "standardAnalyzer", // Split input into tokens according to tokenizer tokenizer = @TokenizerDef(factory = StandardTokenizerFactory.class), filters = { // Normalize token text to lowercase, as the user is unlikely to // care about casing when searching for matches @TokenFilterDef(factory = WordDelimiterFilterFactory.class), @TokenFilterDef(factory = LowerCaseFilterFactory.class), @TokenFilterDef(factory = PatternReplaceFilterFactory.class, params = { @Parameter(name = "pattern", value = "([^a-zA-Z0-9\\.])"), @Parameter(name = "replacement", value = " "), @Parameter(name = "replace", value = "all") }) }) // Def }) public class Product { .... } Explanation: 2 custom analyzers - autocompleteEdgeAnalyzer andautocompleteNGramAnalyzer have been defined as per theory in the previous section. Next, we apply these analyzers on the 'title' field to create 2 different indexes. Here is how we do it: @Column(name = "title") @Fields({ @Field(name = "title", index = Index.YES, store = Store.YES, analyze = Analyze.YES, analyzer = @Analyzer(definition = "standardAnalyzer")), @Field(name = "edgeNGramTitle", index = Index.YES, store = Store.NO, analyze = Analyze.YES, analyzer = @Analyzer(definition = "autocompleteEdgeAnalyzer")), @Field(name = "nGramTitle", index = Index.YES, store = Store.NO, analyze = Analyze.YES, analyzer = @Analyzer(definition = "autocompleteNGramAnalyzer")) }) private String title; Start indexing: public void index() throws InterruptedException { getFullTextSession().createIndexer().startAndWait(); } Once indexed, inspect the index using Luke and you should be able to see title analyzed and stored as N-Grams and Edge N-Grams. Search Query: private static final String TITLE_EDGE_NGRAM_INDEX = "edgeNGramTitle"; private static final String TITLE_NGRAM_INDEX = "nGramTitle"; @Transactional(readOnly = true) public synchronized List getSuggestions(final String searchTerm) { QueryBuilder titleQB = getFullTextSession().getSearchFactory() .buildQueryBuilder().forEntity(Product.class).get(); Query query = titleQB.phrase().withSlop(2).onField(TITLE_NGRAM_INDEX) .andField(TITLE_EDGE_NGRAM_INDEX).boostedTo(5) .sentence(searchTerm.toLowerCase()).createQuery(); FullTextQuery fullTextQuery = getFullTextSession().createFullTextQuery( query, Product.class); fullTextQuery.setMaxResults(20); @SuppressWarnings("unchecked") List results = fullTextQuery.list(); return results; } And we have a working suggester. What next? Expose the functionality via a REST API and integrate it with jQuery, examples of which can be easily found. You can also use the same strategy with Solr and ElasticSearch.
October 7, 2013
by Nishant Chandra
· 15,872 Views · 1 Like
article thumbnail
Clojure: Stripping all the Whitespace
When putting together data sets to play around with, one of the more boring tasks is stripping out characters that you’re not interested in and more often than not those characters are white spaces. Since I’ve been building data sets using Clojure I wanted to write a function that would do this for me. I started out with the following string: (def word " with a little bit of space we can make it through the night ") which I wanted to format in such a way that there would be a maximum of one space between each word. I start out by using the trim function but that only removes white space from the beginning and end of a string: > (clojure.string/trim word) "with a little bit of space we can make it through the night" I wanted to get rid of the space in between ‘a’ and ‘little’ as well so I wrote the following code to split on a space and filter out any excess spaces that still remained before joining the words back together: > (clojure.string/join " " (filter #(not (clojure.string/blank? %)) (clojure.string/split word #" "))) "with a little bit of space we can make it through the night" I wanted to try and make it a bit easier to read by using the thread last (->>) macro but that didn’t work as well as I’d hoped because clojure.string/split doesn’t take the string in as its last parameter: > (->> (clojure.string/split word #" ") (filter #(not (clojure.string/blank? %))) (clojure.string/join " ")) "with a little bit of space we can make it through the night" I worked around it by creating a specific function for splitting on a space: (defn split-on-space [word] (clojure.string/split word #"\s")) which means we can now chain everything together nicely: > (->> word split-on-space (filter #(not (clojure.string/blank? %))) (clojure.string/join " ")) "with a little bit of space we can make it through the night" I couldn’t find a cleaner way to do this but I’m sure there is one and my googling just isn’t up to scratch so do let me know in the comments!
October 3, 2013
by Mark Needham
· 4,341 Views
article thumbnail
Clojure: Converting a string to a date
I wanted to do some date manipulation in Clojure recently and figured that since clj-time is a wrapper around Joda Time it’d probably do the trick. The first thing we need to do is add the dependency to our project file and then run lein reps to pull down the appropriate JARs. The project file should look something like this: project.clj (defproject ranking-algorithms "0.1.0-SNAPSHOT" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.4.0"] [clj-time "0.6.0"]]) Now let’s load the clj-time.format namespace into the REPL since we know we’ll be parsing dates: > (require '(clj-time [format :as f])) The string that I want to convert into a date looks like this: (def string-date "18 September 2012") The first thing we should do is check whether there is an existing formatter that we can use by evaluating the following function: > (f/show-formatters) ... :hour-minute 06:45 :hour-minute-second 06:45:22 :hour-minute-second-fraction 06:45:22.473 :hour-minute-second-ms 06:45:22.473 :mysql 2013-09-20 06:45:22 :ordinal-date 2013-263 :ordinal-date-time 2013-263T06:45:22.473Z :ordinal-date-time-no-ms 2013-263T06:45:22Z :rfc822 Fri, 20 Sep 2013 06:45:22 +0000 ... There are a lot of different built in formatters but unfortunately I couldn’t find one that exactly matched our date format so we’ll have to write our own one. For that we’ll need to refresh our knowledge of Java date formatting: We end up with the following formatter: > (f/parse (f/formatter "dd MMM YYYY") string-date) # It took me much longer than it should have to remember that ‘MMM’ is the pattern to match a short form of a month but it’s just the same as what we’d have to do in Java but with some neat wrapper functions.
October 2, 2013
by Mark Needham
· 5,843 Views
article thumbnail
Introducing the NPM Maven Plugin
This post comes from Alberto Pose at the MuleSoft blog. Introduction Suppose that you have a Maven project and you want to download Node.js modules previously uploaded to NPM. One way of doing that without running node is by using the npm-maven-plugin. It allows the user to download the required Node modules without running node.js: It is completely implemented on the JVM. Getting Started First of all, you will need to add the Mule Maven repo to your pom.xml file: mulesoft-releases MuleSoft Repository https://repository.mulesoft.org/releases/ After doing that, you will need to add the following to the build->plugin section of your pom.xml file: org.mule.tools.javascript npm-maven-plugin 1.0 generate-sources fetch-modules colors:0.5.1 jshint:0.8.1 Then just execute: mvn generate-sources and that’s it! One more thing… By default, the modules can be found in src/main/resources/META-INF but that path can be changed setting the ‘outputDirectory’ parameter. Also, module transitivity is taken into account. That means that it will download all the required dependencies before downloading the specified module. Show me the code! The source code can be found here. Feel free to fork the project and propose changes to it. Happy (Node.js and Maven) hacking!
October 1, 2013
by Ross Mason
· 18,793 Views · 1 Like
article thumbnail
Semantic Search with Solr and NumPy
Built upon Lucene, Solr provides fast, highly scalable, and easily maintainable full-text search capabilities. However, under the hood, Solr is really just a sophisticated token-matching engine. What’s missing? — Semantic Search! Consider three, somewhat silly documents: Yellow banana peels. A banana is a long yellow fruit. This mystery fruit is long and yellow and has a peel. Now what happens if you search for the term “banana?" Under normal circumstances you only get back the first and second document. But why shouldn’t you also get back the third document? It’s obviously talking about bananas! Semantic Search via Collaborative Filtering Colleague Doug Turnbull and I recently set about to right this wrong with help from a machine learning technique called collaborative filtering. Collaborative filtering is most often used as a basis for recommendation algorithms. For example, collaborative filtering algorithms were the central focus of the now-famous Netflix Prize which awarded $1Million to the team which could build the best movie recommendation engine. When dealing with recommendations, collaborative filtering works by mathematically identifying commonalities in groups of users based upon the movies that they enjoyed. Then, if you appear to fall in one of those groups, the recommendation engine will point you towards a movie that a) you haven’t watched and b) you are likely to enjoy. So what does this have to do with Semantic Search? Everything! In just the same way that certain users gravitate towards certain movies, certain words commonly co-occur in the same documents. When working with Semantic Search, rather than recommending user to movies that they would likely enjoy, we are going to identify words that are likely to belong in a given document, whether or not they actually occurred there. The math is exactly the same! Here’s how the process works: First we identify a text field of interest in our documents and extract the associated term-document matrix for external processing. Each element of this term-document matrix indicates the strength of a particular term within a particular document (where strength can be anything, but will likely be either term frequency or TF*IDF). Next, collaborative filtering is applied to the term-document matrix which effectively generates a pseudo-term-document matrix. This pseudo-term-document matrix is the same size and shape as the original term-document matrix and references the same terms and documents, but the numbers are slightly different. These new values indicate the strength that a particular term should have in a particular document once noisy data is removed. Finally, the high-scoring values in the pseudo-term-document matrix are mapped back to the associated terms. These terms are then injected back into Solr in a new field which can be used for Semantic Search. Demo Time! So let’s consider an example case. As in plenty of our previous posts, we will be using the Science Fiction Stack Exchange. Why? Because we’re all nerds and with such a familiar topic, we can quickly intuit whether or not a search is returning relevant results. In this data set, the field of interest is the Body field because it contains the contents of all questions and answers. So, now that we’ve decided upon our demo dataset, we’re ready run the analysis. If you’d like to follow along, then please take a look at our git repo. This repo contains the example SciFi data set, the Semantic Search code, and README to get you going. However I’m going execute everything from within Python: >>> from SemanticAnalyzer import * >>> stvc = SolrTermVectorCollector(field='Body',feature='tf',batchSize=1000) >>> tdc = TermDocCollection(source=stvc,numTopics=150) That last line takes a few minutes. If it’s in the AM where you are, grab a coffee. If it’s in the PM, grab a beer. Once that line completes, we will have successfully extracted the term-document matrix from Solr. Now let’s play with it for a bit. One of the cool side effects of this analysis is the ability to quickly find words that commonly occur together. Let’s give it an easy test; here are the 30 most highly correlated words with the word ‘vader’ (as in Darth Vader). >>> tdc.getRelatedTerms('vader',30) Did you notice that pause when you called the function? That was the collaborative filtering taking place. The results of that process have now been saved, so additional calls will return quite quickly. vader luke emperor darth palpatin anakin sith skywalk sidiou apprentic empir luca side star son forc turn kill death rule suit father question jedi command obi tarkin dark wan plan Hey, not bad! Everything here seems very reasonably connected with Mr. Vader. You may notice some odd spellings here; that’s because these are the indexed terms, therefore they are stemmed. Let’s try again with a different term; this time everyone’s favorite wizard: >>> tdc.getRelatedTerms('potter',30) harri potter voldemort wizard snape death magic jame love spell time rowl lili eater travel seri hous hand hogwart three find wormtail kill slytherin hallow secret deathli muggl order lord Again, pretty good! One last try, and we’ll make it a little more challenging – a vague adjective: >>> tdc.getRelatedTerms('dark',30) dark side jedi sith eater lord death mark snape magic curs evil forc luke mercuri cave yoda jame palpatin dagobah anakin black call wizard slytherin live light siriu matter voldemort Indeed, most of these terms are like a hall of fame of dark things from Star Wars and Harry Potter. Now since the word correlation has proven itself out, it’s time to generate the pseudo terms and post them back to Solr. >>> SolrBlurredTermUpdater(tdc,blurredField="BodyBlurred").pushToSolr(0.1) This line will probably see you to the end of your coffee or beer (it takes about 10 minutes on my machine). But once it’s done, you can start issuing searches to Solr. Solr Results Here’s an example of Semantic Search using Solr: http://localhost:8983/solr/select/?q=-Body:dark +BodyBlurred:dark The Body field contains the original text while the BodyBlurred contains the pseudo-terms. So this finds all documents that do not include the term dark, but presumably contain dark content. Take a look at the documents that come back: { Body: " In the John Carter movie (2012), he shows off some of his powers, like jumping abnormally high, but I have difficulty evaluating his strength. On the one side, he shows great strength, as when he kills a thark warrior with one hand, but he is also quite mistreated by them. He also seems helpless when he is strangled by Tars Tarkas. Why does the strength he shows seem so inconsistent? ", BodyBlurred: "tv great movi control kill consid hand dark side power long mutant fight machin light abil sauron wormtail hulk" }, { Body: " In the movies, the Nazgul ride black horses with armour. I was wondering if that is all they are, or do they have some sort of magic? Are they evil? ", BodyBlurred: "movi black magic dark demon engin hous aveng slytherin" }, { Body: " The remaining Black Brother from the prologue of A Game of Thrones is apparently the deserter who is beheaded in the beginning of the book. But how did he manage to get to Winterfell from the other side of The Wall? Or did the show throw me off track and in the book there weren't any survivors, so the deserter is someone else? ", BodyBlurred: "book watch black hole dark side plai long game demon engin light turn district" }, { Body: " Was this ever discussed in any episode, or as a side-plot somewhere? ", BodyBlurred: "episod dark side light" } Not bad – most of those topics are rather … dark. Though check out that last result. So … maybe there are still some improvements we can make! But you also have to remember that we’re dealing with word correlation here, and I can only guess that somewhere else in the corpus, dark side-plots and dark episodes were surely discussed. Speaking of word correlations, check out this gem: { Body: " You're correct, Enterprise is the only Star Trek that fits into both the original and the new 2009 movie timelines. From the perspective of the Enterprise characters, both are possible futures, given the over-arcing conceit of the show was a Temporal Cold War, so its future is in flux and could line up with either of the timelines we're familiar with, or with an entirely different future. ", BodyBlurred: "answer charact place klingon star trek design travel crew watch work movi happen enterpris featur futur exist origin 2009 chang altern timelin war to version event captain gener pictur tng creat iii galaxi theori return alter voyag entir fry turn kirk paradox biff doc marti feder 1955 starship 2015 class hero centuri tempor uss phoenix mirror river 800 ncc 1701 simon conner skynet alisha" } The original document involves Star Trek and time travel. And appropriately, the pseudo terms include Star Trek things and time-travel terms … but do you see anything funny? That’s right, Biff, Doc and Marti made their way into the pseudo terms, likely because of their role in the popular time-travel film “Back to the Future.” Speaking of the future … Future Work Semantic Search with Solr is hot right now. In the upcoming Dublin LuceneRevolution I know of at least three related talks that have been submitted (one of them my own); I have heard that MapR is working on a Solr Semantic Search/Recommendation engine built atop of their Hadoop offering; and I suspect that with Cloudera’s recent foray into Solr with Mark Miller, they will also be working on the same thing. What’s next for our work? Recommendations! Remember, that’s how we started this conversation. E-commerce recommendations is a simple extension of the work presented above. Given an inventory catalog (e.g., product title, description, etc.), and given a history of user purchases, we can build a search-aware recommendation engine. That is, when a customer searches for a particular item, they will receive results as usual, except that the results will be boosted with items that they are more likely to purchase. How? Because we know what type of customer they are and what products that type of customer is more likely to buy! Do you have a good case for Solr Semantic Search and Recommendation? We’d love to hear it, please contact us!
September 30, 2013
by John Berryman
· 11,667 Views
article thumbnail
ElasticSearch: Java API
ElasticSearch provides Java API, thus it executes all operations asynchronously by using client object.
September 30, 2013
by Hüseyin Akdoğan DZone Core CORE
· 137,556 Views · 4 Likes
article thumbnail
Clojure: Converting an Array/Set into a Hash Map
When I was implementing the Elo Rating algorithm a few weeks ago one thing I needed to do was come up with a base ranking for each team. I started out with a set of teams that looked like this: (def teams #{ "Man Utd" "Man City" "Arsenal" "Chelsea"}) and I wanted to transform that into a map from the team to their ranking e.g. Man Utd -> {:points 1200} Man City -> {:points 1200} Arsenal -> {:points 1200} Chelsea -> {:points 1200} I had read the documentation of array-map, a function which can be used to transform a collection of pairs into a map, and it seemed like it might do the trick. I started out by building an array of pairs using mapcat: > (mapcat (fn [x] [x {:points 1200}]) teams) ("Chelsea" {:points 1200} "Man City" {:points 1200} "Arsenal" {:points 1200} "Man Utd" {:points 1200}) array-map constructs a map from pairs of values e.g. > (array-map "Chelsea" {:points 1200} "Man City" {:points 1200} "Arsenal" {:points 1200} "Man Utd" {:points 1200}) ("Chelsea" {:points 1200} "Man City" {:points 1200} "Arsenal" {:points 1200} "Man Utd" {:points 1200}) Since we have a collection of pairs rather than individual pairs we need to use the apply function as well: > (apply array-map ["Chelsea" {:points 1200} "Man City" {:points 1200} "Arsenal" {:points 1200} "Man Utd" {:points 1200}]) {"Chelsea" {:points 1200}, "Man City" {:points 1200}, "Arsenal" {:points 1200}, "Man Utd" {:points 1200} And if we put it all together we end up with the following: > (apply array-map (mapcat (fn [x] [x {:points 1200}]) teams)) {"Man Utd" {:points 1200}, "Man City" {:points 1200}, "Arsenal" {:points 1200}, "Chelsea" {:points 1200} It works but the function we pass to mapcat feels a bit clunky. Since we just need to create a collection of team/ranking pairs we can use the vector and repeat functions to build that up instead: > (mapcat vector teams (repeat {:points 1200})) ("Chelsea" {:points 1200} "Man City" {:points 1200} "Arsenal" {:points 1200} "Man Utd" {:points 1200}) And if we put the apply array-map code back in we still get the desired result: > (apply array-map (mapcat vector teams (repeat {:points 1200}))) {"Chelsea" {:points 1200}, "Man City" {:points 1200}, "Arsenal" {:points 1200}, "Man Utd" {:points 1200} Alternatively we could use assoc like this: > (apply assoc {} (mapcat vector teams (repeat {:points 1200}))) {"Man Utd" {:points 1200}, "Arsenal" {:points 1200}, "Man City" {:points 1200}, "Chelsea" {:points 1200} I also came across the into function which seemed useful but took in a collection of vectors: > (into {} [["Chelsea" {:points 1200}] ["Man City" {:points 1200}] ["Arsenal" {:points 1200}] ["Man Utd" {:points 1200}] ]) We therefore need to change the code to use map instead of mapcat: > (into {} (map vector teams (repeat {:points 1200}))) {"Chelsea" {:points 1200}, "Man City" {:points 1200}, "Arsenal" {:points 1200}, "Man Utd" {:points 1200} However, my favourite version so far uses the zipmap function like so: > (zipmap teams (repeat {:points 1200})) {"Man Utd" {:points 1200}, "Arsenal" {:points 1200}, "Man City" {:points 1200}, "Chelsea" {:points 1200} I’m sure there are other ways to do this as well so if you know any let me know in the comments.
September 28, 2013
by Mark Needham
· 13,083 Views
article thumbnail
Creating Custom JavaFX Components with Scene Builder and FXML.
one of the goals of our development with our javafx application is to try to keep as much of the ui design as possible within the scene builder ui design tool , and the business logic for the application in java. one of the things that is not entirely clear is how to create a new component in scene builder and then reuse that component within other components created in scene builder. in the example below, i illustrate how to create a custom table and ‘add plan’ components, and then add them to a new scene using fxml. the first step is to create a simple component which acts as an “add plan” widget on the ui. the widget contains an anchorpane, imageview and label. for the next step, open up the fxml file and change the first “anchorpane” declaration to “ create a class which will act as both the root of the component as well as its controller. the class must extend the type that was previously defined in the fxml file. use the fxml loader to set the root and controller of the component to “this” class, and then load the component’s fxml file. /* * to change this template, choose tools | templates * and open the template in the editor. */ package com.lynden.fx.test; import com.lynden.ui.util.uiutilities; import java.io.ioexception; import javafx.event.eventhandler; import javafx.fxml.fxml; import javafx.fxml.fxmlloader; import javafx.scene.input.dragevent; import javafx.scene.input.dragboard; import javafx.scene.input.transfermode; import javafx.scene.layout.anchorpane;/** * * @author robt */ public class testbutton extends anchorpane { @fxml private anchorpane mytestbutton; public testbutton() { fxmlloader fxmlloader = new fxmlloader( getclass().getresource("/com/lynden/planning/ui/testbutton.fxml")); fxmlloader.setroot(this); fxmlloader.setcontroller(this); try { fxmlloader.load(); } catch (ioexception exception) { throw new runtimeexception(exception); } } } next, the 2nd component is a tableview which contains a collection of beans, and displays their corresponding data. as with the last component, the first declaration is changed to next, the corresponding root and controller class is created for the table component. /* * to change this template, choose tools | templates * and open the template in the editor. */ package com.lynden.fx.test; import com.lynden.fx.inboundbean; import java.io.ioexception; import javafx.event.eventhandler; import javafx.event.eventtype; import javafx.fxml.fxml; import javafx.fxml.fxmlloader; import javafx.scene.control.tableview; import javafx.scene.input.clipboardcontent; import javafx.scene.input.dragboard; import javafx.scene.input.mouseevent; import javafx.scene.input.transfermode; import javafx.scene.layout.anchorpane; /** * * @author robt */ public class testtable extends anchorpane { @fxml private tableview mytableview; public testtable() { fxmlloader fxmlloader = new fxmlloader( getclass().getresource("/com/lynden/planning/ui/testtable.fxml")); fxmlloader.setroot(this); fxmlloader.setcontroller(this); try { fxmlloader.load(); } catch (ioexception exception) { throw new runtimeexception(exception); } } } finally, a new scene can be created which includes both the testtable and testbutton components that were constructed above. unfortunately, custom components can’t be added to the scene builder palette, so they must be inserted manually into the fxml file. you just need to ensure that you have the proper import statements defined, and the testtable and testbutton components can be inserted into the fxml code just as any native javafx component. when scene builder opens the fxml file you will see that both components are displayed on the new scene that’s it, hopefully this will help others who have been looking at adding custom components to their uis that are designed with scene builder. twitter: @robterp
September 25, 2013
by Rob Terpilowski
· 61,400 Views · 1 Like
article thumbnail
Clojure: Updating keys in a map
I’ve been playing with Clojure over the last few weeks and as a result I’ve been using a lot of maps to represent the data. For example if we have the following map of teams to Glicko ratings and ratings deviations: (def teams { "Man. United" {:points 1500 :rd 350} "Man. City" {:points 1450 :rd 300} }) We might want to increase Man. United’s points score by one for which we could use the update-in function: > (update-in teams ["Man. United" :points] inc) {"Man. United" {:points 1501, :rd 350}, "Man. City" {:points 1450, :rd 300} The 2nd argument to update-in is a nested associative structure i.e. a sequence of keys into the map in this instance. If we wanted to reset Man. United’s points score we could use assoc-in: > (assoc-in teams ["Man. United" :points] 1) {"Man. United" {:points 1, :rd 350}, "Man. City" {:points 1450, :rd 300} If we want to update multiple keys at once then we can chain them using the -> (thread first) macro: (-> teams (assoc-in ["Man. United" :points] 1600) (assoc-in ["Man. United" :rd] 200)) {"Man. United" {:points 1600, :rd 200}, "Man. City" {:points 1450, :rd 300} If instead of replacing just one part of the value we want to replace the whole entry we could use associnstead: > (assoc teams "Man. United" {:points 1600 :rd 300}) {"Man. United" {:points 1600, :rd 300}, "Man. City" {:points 1450, :rd 300} assoc can also be used to add a new key/value to the map. e.g. > (assoc teams "Arsenal" {:points 1500 :rd 330}) {"Man. United" {:points 1500, :rd 350}, "Arsenal" {:points 1500, :rd 330}, "Man. City" {:points 1450, :rd 300} dissoc plays the opposite role and returns a new map without the specified keys: > (dissoc teams "Man. United" "Man. City") {} And those are all the map based functions I’ve played around with so far…
September 24, 2013
by Mark Needham
· 6,154 Views
  • Previous
  • ...
  • 535
  • 536
  • 537
  • 538
  • 539
  • 540
  • 541
  • 542
  • 543
  • 544
  • ...
  • 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
×