/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
package io.joynr.examples.jee;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.ReentrantLock;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.joynr.arbitration.ArbitrationStrategy;
import io.joynr.arbitration.DiscoveryQos;
import io.joynr.jeeintegration.api.ServiceLocator;
import joynr.exceptions.ApplicationException;
import joynr.vehicle.Country;
import joynr.vehicle.GeoPosition;
import joynr.vehicle.RadioStation;
import joynr.vehicle.RadioSync;

@Path("/radio-stations")
@Produces(MediaType.APPLICATION_JSON)
public class RadioConsumerRestEndpoint {

    private final static Logger LOGGER = LoggerFactory.getLogger(RadioConsumerRestEndpoint.class);

    private ServiceLocator serviceLocator;

    private volatile RadioSync radioClient;

    private ReentrantLock radioClientLock = new ReentrantLock();

    @Inject
    public RadioConsumerRestEndpoint(ServiceLocator serviceLocator) {
        this.serviceLocator = serviceLocator;
    }

    @GET
    @Path("/current-station")
    public RadioStation getCurrentRadioStation() {
        try {
            return getRadioClient().getCurrentStation();
        } catch (Exception e) {
            throw new WebApplicationException(e);
        }
    }

    @GET
    @Path("/current-station/location")
    public GeoPosition getLocationOfCurrentStation() {
        return getRadioClient().getLocationOfCurrentStation().location;
    }

    @GET
    @Path("/current-station/country")
    public Country getCountryOfCurrentStation() {
        return getRadioClient().getLocationOfCurrentStation().country;
    }

    @POST
    @Path("/shuffle")
    public void shuffleRadioStations() {
        getRadioClient().shuffleStations();
    }

    @POST
    @Produces({ MediaType.TEXT_PLAIN })
    public boolean addRadioStation(String name) {
        try {
            return getRadioClient().addFavoriteStation(new RadioStation(name, true, Country.GERMANY));
        } catch (ApplicationException e) {
            throw new WebApplicationException(e.getMessage());
        }
    }

    private RadioSync getRadioClient() {
        if (radioClient == null) {
            radioClientLock.lock();
            try {
                if (radioClient == null) {
                    CompletableFuture<RadioSync> future = serviceLocator.builder(RadioSync.class,
                                                                                 "io.joynr.examples.jee.provider")
                                                                        .withDiscoveryQos(new DiscoveryQos(10000L,
                                                                                                           ArbitrationStrategy.HighestPriority,
                                                                                                           360000L))
                                                                        .useFuture()
                                                                        .build();
                    try {
                        radioClient = future.get();
                    } catch (Exception e) {
                        LOGGER.error("Unable to create a proxy for the radio provider. All calls will fail.", e);
                        throw new RuntimeException("Radio proxy creation failed.", e);
                    }
                }
            } finally {
                radioClientLock.unlock();
            }
        }
        return radioClient;
    }

}

@@ -709,57 +709,8 @@
 ure;
-%0Aimport java.util.concurrent.locks.ReentrantLock;
 %0A%0Aim
@@ -1594,74 +1594,8 @@
 t;%0A%0A
-    private ReentrantLock radioClientLock = new ReentrantLock();%0A%0A
     
@@ -2898,47 +2898,27 @@
     
-radioClientLock.lock();%0A            try
+synchronized (this)
  %7B%0A 
@@ -4052,32 +4052,32 @@
               %7D%0A
+
                 
@@ -4082,74 +4082,8 @@
   %7D%0A
-            %7D finally %7B%0A                radioClientLock.unlock();%0A
     

implement code review comments