org.knowm.xdropwizard.resources.HelloWorldResource.java Source code

Java tutorial

Introduction

Here is the source code for org.knowm.xdropwizard.resources.HelloWorldResource.java

Source

/**
 * Copyright 2015 Knowm Inc. (http://knowm.org) and contributors.
 * Copyright 2013-2015 Xeiam LLC (http://xeiam.com) and contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.knowm.xdropwizard.resources;

import java.util.concurrent.atomic.AtomicLong;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.knowm.xdropwizard.api.Saying;

import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Optional;

/**
 * @author timmolter
 */
@Path("hello-world")
@Produces(MediaType.APPLICATION_JSON)
public class HelloWorldResource {

    private final String template;
    private final String defaultName;
    private final AtomicLong counter;

    /**
     * Constructor
     * 
     * @param template
     * @param defaultName
     */
    public HelloWorldResource(String template, String defaultName) {

        this.template = template;
        this.defaultName = defaultName;
        this.counter = new AtomicLong();
    }

    /** Dropwizard automatically records the duration and rate of its invocations as a Metrics Timer. */
    @GET
    @Timed
    public Saying sayHello(@QueryParam("name") Optional<String> name) {

        return new Saying(counter.incrementAndGet(), String.format(template, name.or(defaultName)));
    }
}