Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Dropwizard Configuration Reference
2.1.
Outline
2.2.
Expert Conditions
2.3.
Setup
2.4.
Asset
2.5.
Running Application
2.6.
Wellbeing Check
3.
Frequently Asked Questions
3.1.
What is arrangement class in Dropwizard?
3.2.
What are the predetermined climate explicit boundaries?
3.3.
Does Dropwizard utilize Log4j?
3.4.
What is Breakwater Dropwizard?
3.5.
Who made Dropwizard?
3.6.
What gadgets use Log4j?
4.
Conclusion
Last Updated: Mar 27, 2024
Medium

Dropwizard Configuration Reference

Author Adya Tiwari
0 upvote

Introduction

Dropwizard is an open-source Java system utilized to advance the elite execution of Serene web administrations quickly. It accumulates a few famous libraries to make the lightweight bundle. The top libraries used are Breakwater, Jersey, Jackson, JUnit, and Guava. Besides, it uses its library called Measurements. Yammer created it to control their JVM-based backend. Dropwizard gives best-of-breed Java libraries into one installed application bundle. Each Dropwizard application has a subclass of the Setup class, indicating explicit climate boundaries. These boundaries are determined in a YAML setup document deserialized to an occasion of your application's design class and approved. 🥷

Dropwizard Configuration Reference

Dropwizard is a Java structure for creating operations cordial, superior execution, and Relaxing web administrations.  Dropwizard arranges steady, mature libraries from the Java environment into an essential, lightweight bundle that allows you to zero in on finishing things. Now let's look at the configuration references that we have in dropwizard. 😉

dropwizard CN

Outline

In this instructional exercise, we'll figure out how to design and run a straightforward Dropwizard application. When we're finished, our application will uncover a Tranquil Programming interface that permits us to get a rundown of put-away brands.

Expert Conditions

Right off the bat, the dropwizard-center reliance is all we want to make our administration. How about we add it to our pom.xml:

<dependency>
    <groupId>io.dropwizard</groupId>
    <artifactId>dropwizard-core</artifactId>
    <version>2.0.0</version>
</dependency>

Setup

setup

Presently, we'll make the vital necessary classes for each Dropwizard application to run.

Dropwizard applications store properties in YML records. Like this, we'll make the presentation config.yml description in the asset catalog:

defaults: 5

 

We can get to values in that document by making a class that broadens io.dropwizard.Configuration:

public class BasicConfiguration extends Configuration {
    @NotNull private final int defaultSize;

    @JsonCreator
    public BasicConfiguration(@JsonProperty("defaultSize") int defaultSize) {
        this.defaultSize = defaultSize;
    }

    public int getDefaultSize() {
        return defaultSize;
    }
}

 

Dropwizard utilizes Jackson to deserialize the arrangement document into our group. Thus, we've used Jackson's explanations.

Then, we should make the primary application class, which is answerable for setting up our administration for utilization:

public class IntroductionApplication extends Application<BasicConfiguration> {

    public static void main(String[] args) throws Exception {
        new IntroductionApplication().run("server", "introduction-config.yml");
    }

    @Override
    public void run(BasicConfiguration basicConfiguration, Environment environment) {
        //register classes
    }

    @Override
    public void initialize(Bootstrap<BasicConfiguration> bootstrap) {
        bootstrap.setConfigurationSourceProvider(new ResourceConfigurationSourceProvider());
        super.initialize(bootstrap);
    }
}

 

The primary technique is liable for running the application right off the bat. We could pass the args to the showing process or fill it ourselves.

The principal contention can be either server or check. The check choice approves the design while the server runs the application. The subsequent argument is the area of the setup record.

Besides, the instate technique sets the setup supplier to the ResourceConfigurationSourceProvider, which permits the application to find a given design record in the asset registry. Superseding this method isn't compulsory.

In conclusion, the run technique permits us to get to both the climate and the BaseConfiguration, which we'll utilize later in this article.

Asset

We should, right off the bat's, make a space class for our image:

public class Brand {
    private final Long id;
    private final String name;

    // all args constructor and getters
}
Code Gif

Furthermore, we should make a BrandRepository class that will be liable for bringing brands back:

public class BrandRepository {
    private final List<Brand> brands;

    public BrandRepository(List<Brand> brands) {
        this.brands = ImmutableList.copyOf(brands);
    }

    public List<Brand> findAll(int size) {
        return brands.stream()
          .limit(size)
          .collect(Collectors.toList());
    }

    public Optional<Brand> findById(Long id) {
        return brands.stream()
          .filter(brand -> brand.getId().equals(id))
          .findFirst();
    }
}

 

Moreover, we had the option to utilize the ImmutableList from Guava since it's essential for Dropwizard itself.

Thirdly, we'll make a BrandResource class. The Dropwizard involves JAX-RS, of course, with Jersey as execution. Like this, we'll utilize comments from this particular to uncover our REST Programming interface endpoints:

@Path("/brands")
@Produces(MediaType.APPLICATION_JSON)
public class BrandResource {
    private final int defaultSize;
    private final BrandRepository brandRepository;

    public BrandResource(int defaultSize, BrandRepository brandRepository) {
        this.defaultSize = defaultSize;
        this.brandRepository = brandRepository;
    }

    @GET
    public List<Brand> getBrands(@QueryParam("size") Optional<Integer> size) {
        return brandRepository.findAll(size.orElse(defaultSize));
    }

    @GET
    @Path("/{id}")
    public Brand getById(@PathParam("id") Long id) {
        return brandRepository
          .findById(id)
          .orElseThrow(RuntimeException::new);
    }
}

 

Also, we've characterized size as Discretionary to utilize defaultSize from our design if the contention isn't given.

Finally, we'll enroll BrandResource in the IntroductionApplicaton class. That's what to do; we should execute the run technique:

@Override
public void run(BasicConfiguration basicConfiguration, Environment environment) {
    int defaultSize = basicConfiguration.getDefaultSize();
    BrandRepository brandRepository = new BrandRepository(initBrands());
    BrandResource brandResource = new BrandResource(defaultSize, brandRepository);

    environment
      .jersey()
      .register(brandResource);
}

All made assets ought to be enrolled in this strategy.

Running Application

In this segment, we'll figure out how to run the application from the order line.

Applications

To begin with, we'll design our task to construct a Container document utilizing the expert shade module:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <configuration>
        <createDependencyReducedPom>true</createDependencyReducedPom>
        <filters>
            <filter>
                <artifact>*:*</artifact>
                <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                </excludes>
            </filter>
        </filters>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer
                      implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
                    <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <mainClass>com.baeldung.dropwizard.introduction.IntroductionApplication</mainClass>
                    </transformer>
                </transformers>
            </configuration>
        </execution>
    </executions>
</plugin>

 

This is the recommended arrangement of the module. Also, we've remembered the way to our primary class for the <mainClass> component.

At long last, we'll assemble the application with an Expert. When we have our Container record, we can run the application:

java -jar target/dropwizard-0.0.1-SNAPSHOT.jar

 

There's a compelling reason to pass the boundaries since we've previously remembered them for the IntroductionApplication class.

From that point onward, the control center log ought to end with:

INFO  [2020-01-08 18:55:06,527] org.eclipse.jetty.server.Server: Started @1672ms

Wellbeing Check

While beginning the application, we were educated that the application has no well-being checks. Luckily, Dropwizard gives a simple answer for adding wellbeing checks to our application.

We should begin by adding a basic class that broadens com.codahale.metrics.health.HealthCheck:

public class ApplicationHealthCheck extends HealthCheck {
    @Override
    protected Result check() throws Exception {
        return Result.healthy();
    }
}

 

This basic technique will return data about the strength of our part. We could make numerous wellbeing checks, some of which could flop in specific circumstances. For example, we would return Result.unhealthy(), assuming that the association with the data set fizzled.

Ultimately, we want to enroll our wellbeing check in the run technique for our IntroductionApplication class:

environment
  .healthChecks()
  .register("application", new ApplicationHealthCheck());

 

In the wake of running the application, we can check the wellbeing; take a look at the reaction here:

{
  "application": {
    "healthy": true,
    "duration": 0
  },
  "deadlocks": {
    "healthy": true,
    "duration": 0
  }
}

 

Our wellbeing check has been enlisted under the application tag.

DropWizard

Frequently Asked Questions

What is arrangement class in Dropwizard?

Each Dropwizard application has its subclass of the Design class, which indicates explicit climate boundaries.

What are the predetermined climate explicit boundaries?

These boundaries are determined in a YAML design record deserialized to an example of your application's setup class and approved.

Does Dropwizard utilize Log4j?

Dropwizard involves Logback for its logging backend. It gives a slf4j execution and even courses all java. Util. Logging, Log4j, and Apache Hall Logging are used through Logback.

What is Breakwater Dropwizard?

Dropwizard is an open-source Java structure utilized to advance superior execution and Peaceful web administrations quickly. It assembles a few well-known libraries to make the lightweight bundle.

Who made Dropwizard?

Yammer created Dropwizard to control their JVM-based backend. Dropwizard gives best-of-breed Java libraries into one implanted application bundle.

What gadgets use Log4j?

Countless administrations use Log4j, like Apple's iCloud, Microsoft's Minecraft, Twitter, Steam, Tencent, Google, Amazon, CloudFare, NetEase, Webex, and LinkedIn.

Conclusion

In this article, we've figured out how to set up the Dropwizard application with Expert. We've found that the base arrangement of the application is straightforward and quick. Moreover, Dropwizard incorporates each library we want to run the superior Relaxing web administration execution. 
Dropwizard is an open-source Java system utilized to quickly advance Serene web administrations' elite performance. Dropwizard applications store properties in YML records. We have also covered steps from the setop, and outline to a full wellbeing check.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in pygameCompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problems, interview experiences, and interview bundle for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass