Dropwizard is a Relaxation-oriented framework that attracts with each other various Java deals into a cohesive whole. It is an alternative to Spring (and Spring’s WebMVC bundle). Dropwizard provides a additional streamlined experience. It adopts even additional configuration by conference than Spring, and gets rid of most of the API floor that is unrelated specially to providing Relaxation APIs.
Get started a new Dropwizard venture
Let us start off by scaffolding a new venture by using the official Dropwizard Maven archetype. Come across a at ease position on your neighborhood method, and from the command line, enter the command in Listing 1.
Listing 1. Operate the archetype
mvn archetype:crank out -DarchetypeGroupId=io.dropwizard.archetypes -DarchetypeArtifactId=java-straightforward -DarchetypeVersion=two..
This will run in interactive method. I used a team ID of com.infoworld and an artifact ID of Demo. I also used Demo for the identify.
When the archetype finishes deploying by itself, you can cd
into your listing (in my circumstance, cd Demo
). Now you put in the dependencies with mvn cleanse bundle
.
Now the app can be run with
java -jar focus on/Demo-1.-SNAPSHOT.jar server
(Recall to use the app identify you gave it if various from Demo.)
If you visit localhost:8080 now, you’ll be greeted with a default JSON-formatted “not found” mistake:
"code":404,"information":"HTTP 404 Not Identified"
Map an endpoint
So much, the app only returns 404s because no endpoints are mapped. I want to give you a crystal clear knowing of how this is completed with Dropwizard. We’ll isolate the course of action by mapping a straightforward string endpoint.
Action 1 is to produce a course that acts as the route handler. Recall, Dropwizard’s contacting in lifetime is to unite various ideal-in-course libraries into an simple-to-use bundle. For supporting RESTful endpoints, Dropwizard takes advantage of Jersey. Your app presently has Jersey totally set up. The route mappings are completed with the Jersey syntax.
Action two is to sign-up the handler course with the app. Let us consider these two steps in change.
Build a route handler course
By conference, Dropwizard endpoint handlers go in the /src/primary/java/com/infoworld/assets folder (or whichever team ID you opt for). We’re heading to increase an endpoint handler for returning a listing of songwriters. As you can see in Listing two, we’ll return only the ideal. Build a new SongWriters.java file in the /assets listing.
Listing two. The SongWriters endpoint
bundle com.infoworld.assetsimport javax.ws.rs.*
import javax.ws.rs.main.MediaType
import java.util.List
import java.util.Optional@Route("/songwriters")
@Produces(MediaType.Application_JSON)
public course SongWriters
public SongWriters()
@GET
public String getBrands()
return "'name':'Roger Waters','name':'Tom Petty'"
Listing two is pretty straightforward. The course by itself is given a route by using the @Route
annotation, and JSON is specified as the media variety by using the @Produces
annotation. Subsequent, the getBrands()
method, which returns a string, is mapped to the GET HTTP
method by using the @GET
annotation. The method just returns a hard-coded string symbolizing the set of songwriters.
Sign up the handler
Now to sign-up the handler. Open the /src/primary/java/com/infoworld/DemoApplication.java file and modify the run()
method to glance like Listing 3.
Listing 3. Registering the SongWriters handler
import com.infoworld.assets.SongWriters
// ...
public void run(ultimate DemoConfiguration configuration, ultimate Natural environment environment)
SongWriters songWriters = new SongWriters()
environment.jersey().sign-up(songWriters)
Once more, pretty straightforward. Listing 3 imports the course you just made, then takes advantage of the Natural environment
object to obtain Jersey and sign-up the handler. Discover the run
method also gets a DemoConfiguration
object, which you’ll see in action momentarily.
Test the handler
Now if you visit localhost:8080/songwriters, you’ll get the JSON that you hard coded. Discover the method has seamlessly dealt with returning the string as JSON.
Design the area
Now you want to shift from a hard-coded string to using precise area objects. Get started by creating a /src/primary/java/com/infoworld/area/SongWriter.java file, and give it the contents of Listing 4.
Listing 4. The SongWriter area model course
bundle com.infoworld.areaimport java.util.ArrayList
import java.util.Listpublic course SongWriter
non-public ultimate String identify
non-public List tracks = new ArrayList<>()public SongWriter(ultimate String identify, ultimate List tracks)
this.identify = identify
this.tracks = tracks
public String getName()
return identify
public List getSongs()
return this.tracks
Add a repository course
Now we’ll increase a repository course to stand for the knowledge obtain layer. Build a new folder and file: /src/primary/java/com/infoworld/repo/SongWriterRepo.java.
Listing 5. The SongWriterRepo course
bundle com.infoworld.repoimport com.infoworld.area.SongWriter
import java.util.List
import java.util.ArrayList
import java.util.Optional
import java.util.stream.Collectorspublic course SongWriterRepo
non-public ultimate List songWriters
public SongWriterRepo()
this.songWriters = new ArrayList()
public SongWriterRepo(List songWriters)
this.songWriters = songWriters
public List findAll()
return songWriters
public Optional getByName(ultimate String identify)
return songWriters.stream().filter(sw -> sw.getName().equals(identify)).findFirst()
As you can see in Listing 5, SongWriterRepo is dependable for returning all the SongWriter objects in a List
by using the findAll()
method, when the getByName()
method grabs the songwriter specified by the handed in string identify.
Use the area layer
Now we’ll use the new layer to push the JSON returned by the source endpoint. Modify com.infoworld.source.SongWriters to glance like Listing 6.
Listing 6. The modified SongWriters course
bundle com.infoworld.assetsimport javax.ws.rs.*
import javax.ws.rs.main.MediaType
import java.util.List
import java.util.Optionalimport com.infoworld.repo.SongWriterRepo
import com.infoworld.area.SongWriter@Route("/songwriters")
@Produces(MediaType.Application_JSON)
public course SongWriters
non-public ultimate SongWriterRepo repo
public SongWriters(SongWriterRepo repo)
this.repo = repo
@GET
public List getBrands()
return repo.findAll()
Listing 6 has eradicated the hard-coded string in favor of referencing the SongWriterRepo
course, which is set in the constructor. Now consider a glance at Listing 7, the place these courses are wired with each other in the DemoApplication
course.
Listing 7. Wiring the area course in DemoApplication
bundle com.infoworldimport io.dropwizard.Application
import io.dropwizard.set up.Bootstrap
import io.dropwizard.set up.Natural environmentimport com.infoworld.assets.SongWriters
import com.infoworld.repo.SongWriterRepopublic course DemoApplication extends Application
// ...
@Override
public void run(ultimate DemoConfiguration configuration, ultimate Natural environment environment)
SongWriterRepo swRepo = new SongWriterRepo()
SongWriters songWriters = new SongWriters(swRepo)
environment.jersey().sign-up(songWriters)
Return to the DemoApplication
course, and modify it as proven in Listing 7. Discover that you now instantiate the SongWriterRepo
object and parameterize the SongWriters
source object just before handing it off to Jersey.
Now if you rebuild the venture and visit localhost:8080/songwriters, you will come across an empty array. Let us increase a hard-coded songwriter as proven in Listing eight.
Listing eight. Introducing a songwriter
public void run(ultimate DW2Configuration configuration,
ultimate Natural environment environment)List preload = new ArrayList()
preload.increase(new SongWriter("Mark Knopfler", new ArrayList()))SongWriterRepo swRepo = new SongWriterRepo(preload)
SongWriters songWriters = new SongWriters(swRepo)
environment.jersey().sign-up(songWriters)
Now you’ll get a end result when you hit the endpoint.
Use the config file
Add a new config file at src/primary/assets/Demo-Config.yml and put the contents of Listing nine in it.
Listing nine. The config YAML
---
songWriters:
- John Lennon
- Jeff Lynne
Now alter the com.infoworld.DemoConfiguration.java file to glance like Listing 10. This file is used to model the config file by using Jackson.
Listing 10. Config java
bundle com.infoworldimport io.dropwizard.Configuration
import com.fasterxml.jackson.annotation.JsonProperty
import org.hibernate.validator.constraints.*
import javax.validation.constraints.*import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonPropertyimport java.util.List
import java.util.ArrayListpublic course DW2Configuration extends Configuration
non-public ListsongWriters
@JsonCreator
public DW2Configuration(@JsonProperty("songWriters") ListsongWriters)
this.songWriters = songWriters
public ListgetSongWriters()
return this.songWriters
Now use the file in DemoApplication
, as shown in Listing 11.
Listing 11. Using the config file to preload songwriters in DemoApplication.java
@Override
public void run(ultimate DemoConfiguration configuration,
final Natural environment environment)List preload = new ArrayList()
configuration.getSongWriters().forEach(sw -> preload.increase(new SongWriter(sw, new ArrayList())))
SongWriterRepo swRepo = new SongWriterRepo(preload)
SongWriters songWriters = new SongWriters(swRepo)
environment.jersey().sign-up(songWriters)
The primary place of the alter in Listing 11 is that the configuration file is hydrated into the DemoConfiguration
course, populating the getSongWriters()
method that is used to preload the repository course.
Operate the app with the config file
A smaller alter is demanded to run this app with the config file. Discover in Listing 12 that the file is referenced immediately after the get in touch with to server
.
Listing 12. Managing the app with the config file
java -jar focus on/DW2-1.-SNAPSHOT.jar server src/primary/assets/DW2-config.yml
Now when you visit the app at localhost:8080/songwriters, you’ll see the preloaded songwriters.
Dropwizard is a lean alternative to Spring-centered RESTful APIs. As you’ve witnessed right here, it focuses on delivering a straightforward but sufficient stack to handle these requires.
The resources for the demo app are available right here.
Copyright © 2021 IDG Communications, Inc.