text:
package com.konkerlabs.platform.registry.api.test.web.controller;

import com.konkerlabs.platform.registry.api.config.WebMvcConfig;
import com.konkerlabs.platform.registry.api.model.DeviceVO;
import com.konkerlabs.platform.registry.api.test.config.MongoTestConfig;
import com.konkerlabs.platform.registry.api.test.config.WebTestConfiguration;
import com.konkerlabs.platform.registry.api.web.controller.DeviceRestController;
import com.konkerlabs.platform.registry.api.web.controller.DeviceStatusRestController;
import com.konkerlabs.platform.registry.api.web.wrapper.CrudResponseAdvice;
import com.konkerlabs.platform.registry.business.model.*;
import com.konkerlabs.platform.registry.business.model.Event.EventActor;
import com.konkerlabs.platform.registry.business.model.HealthAlert.HealthAlertSeverity;
import com.konkerlabs.platform.registry.business.model.enumerations.DateFormat;
import com.konkerlabs.platform.registry.business.model.enumerations.Language;
import com.konkerlabs.platform.registry.business.model.enumerations.TimeZone;
import com.konkerlabs.platform.registry.business.services.api.*;
import com.konkerlabs.platform.registry.business.services.api.HealthAlertService.Validations;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.text.MessageFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {DeviceRestController.class, DeviceStatusRestController.class})
@AutoConfigureMockMvc(secure = false)
@ContextConfiguration(classes = {
        WebTestConfiguration.class,
        MongoTestConfig.class,
        WebMvcConfig.class,
        CrudResponseAdvice.class
})
public class DeviceRestControllerTest extends WebLayerTestContext {

    private static final String NONEXIST_APPLICATION_NAME = "AppLost";

    @Autowired
    private DeviceRegisterService deviceRegisterService;

    @Autowired
    private LocationSearchService locationSearchService;

    @Autowired
    private ApplicationService applicationService;

    @Autowired
    private DeviceEventService deviceEventService;

    @Autowired
    private HealthAlertService healthAlertService;

    @Autowired
    private Tenant tenant;

    @Autowired
    private Application application;

    @Autowired
    private Location location;

    @Autowired
    private Gateway gateway;

    @Autowired
    private GatewayService gatewayService;

    private Set<String> tags;

    private Device device1;

    private Device device2;

    private AlertTrigger alertTrigger;

    private HealthAlert health1;

    private HealthAlert health2;

    private List<HealthAlert> healths;

    private List<Event> events;

    private User user;

    private final String BASEPATH = "devices";

    private final Instant registrationDate = Instant.ofEpochMilli(1495716970000L).minusSeconds(3600L);

    private MultiValueMap<String, String> paramPageable;

    @Before
    public void setUp() {
        final Location locationBR = Location.builder().name("br").build();

        tags = new HashSet<>(Arrays.asList("tag1", "tag2"));
        device1 = Device.builder()
                .deviceId("id1")
                .name("name1")
                .guid("guid1")
                .location(locationBR)
                .application(application)
                .active(true)
                .debug(true)
                .registrationDate(registrationDate)
                .lastModificationDate(registrationDate)
                .tags(tags)
                .build();
        device2 = Device.builder().deviceId("id2").name("name2").guid("guid2").location(locationBR).application(application).active(false).build();

        alertTrigger = AlertTrigger.builder()
                .guid("7d51c242-81db-11e6-a8c2-0746f976f666")
                .type(AlertTrigger.AlertTriggerType.SILENCE)
                .build();

        health1 = HealthAlert.builder()
                .guid("7d51c242-81db-11e6-a8c2-0746f976f223")
                .severity(HealthAlertSeverity.FAIL)
                .description("No message received from the device for a long time.")
                .registrationDate(registrationDate)
                .lastChange(Instant.ofEpochMilli(1495716970000L))
                .device(device1)
                .alertTrigger(alertTrigger)
                .build();

        health2 = HealthAlert.builder()
                .guid("7d51c242-81db-11e6-a8c2-0746f976f223")
                .severity(HealthAlertSeverity.OK)
                .description("No message received from the device for a long time.")
                .registrationDate(registrationDate)
                .lastChange(Instant.ofEpochMilli(1495716970000L))
                .device(device1)
                .alertTrigger(alertTrigger)
                .build();

        healths = Arrays.asList(health1, health2);

        Event event = Event.builder()
                .incoming(EventActor.builder().channel("out").deviceGuid(device1.getGuid()).build())
                .creationTimestamp(registrationDate)
                .build();
        events = Collections.singletonList(event);

        user = User.builder()
                .email("user@domain.com")
                .zoneId(TimeZone.AMERICA_SAO_PAULO)
                .language(Language.EN)
                .avatar("default.jpg")
                .location(locationBR)
                .dateFormat(DateFormat.YYYYMMDD)
                .tenant(tenant).build();

        paramPageable = new LinkedMultiValueMap<>();
        paramPageable.add("page", "1");
        paramPageable.add("size", "10");

        when(locationSearchService.findByName(tenant, application, "br", true))
                .thenReturn(ServiceResponseBuilder.<Location>ok().withResult(locationBR).build());

    }

    @After
    public void tearDown() {
        Mockito.reset(deviceRegisterService);
    }

    @Test
    public void shouldListDevices() throws Exception {
        List<Device> listDevices = new ArrayList<>();
        listDevices.add(device1);
        listDevices.add(device2);

        Page<Device> devices = new PageImpl(listDevices);

        when(deviceRegisterService.search(tenant, application, user, null, null, 1, 10))
                .thenReturn(ServiceResponseBuilder.<Page<Device>>ok().withResult(devices).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/", application.getName(), BASEPATH))
                .contentType("application/json")
                .params(paramPageable)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result", hasSize(2)))
                .andExpect(jsonPath("$.result[0].id", is("id1")))
                .andExpect(jsonPath("$.result[0].name", is("name1")))
                .andExpect(jsonPath("$.result[0].guid", is("guid1")))
                .andExpect(jsonPath("$.result[0].active", is(true)))
                .andExpect(jsonPath("$.result[1].id", is("id2")))
                .andExpect(jsonPath("$.result[1].name", is("name2")))
                .andExpect(jsonPath("$.result[1].guid", is("guid2")))
                .andExpect(jsonPath("$.result[1].active", is(false)))
                .andExpect(jsonPath("$.result[1].debug", is(false)));

    }

    @Test
    public void shouldListDevicesFilterByTag() throws Exception {

        List<Device> listDevices = new ArrayList<>();
        listDevices.add(device1);
        listDevices.add(device2);

        Page<Device> devices = new PageImpl(listDevices);

        when(deviceRegisterService.search(tenant, application, user, null, "red", 1, 10))
                .thenReturn(ServiceResponseBuilder.<Page<Device>>ok().withResult(devices).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());
        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/?tag=red", application.getName(), BASEPATH))
                .contentType("application/json")
                .params(paramPageable)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result", hasSize(2)))
                .andExpect(jsonPath("$.result[0].id", is("id1")))
                .andExpect(jsonPath("$.result[0].name", is("name1")))
                .andExpect(jsonPath("$.result[0].guid", is("guid1")))
                .andExpect(jsonPath("$.result[0].active", is(true)))
                .andExpect(jsonPath("$.result[1].id", is("id2")))
                .andExpect(jsonPath("$.result[1].name", is("name2")))
                .andExpect(jsonPath("$.result[1].guid", is("guid2")))
                .andExpect(jsonPath("$.result[1].active", is(false)))
                .andExpect(jsonPath("$.result[1].debug", is(false)));

    }

    @Test
    public void shouldTryListDevicesWithInternalError() throws Exception {

        when(deviceRegisterService.search(tenant, application, user, null, null, 1, 10))
                .thenReturn(ServiceResponseBuilder.<Page<Device>>error().build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/", application.getName(), BASEPATH))
                .accept(MediaType.APPLICATION_JSON)
                .params(paramPageable)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().is5xxServerError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.INTERNAL_SERVER_ERROR.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages").doesNotExist())
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldReadDevice() throws Exception {

        when(deviceRegisterService.getByDeviceGuid(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<Device>ok().withResult(device1).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result").isMap())
                .andExpect(jsonPath("$.result.id", is("id1")))
                .andExpect(jsonPath("$.result.name", is("name1")))
                .andExpect(jsonPath("$.result.guid", is("guid1")))
                .andExpect(jsonPath("$.result.active", is(true)))
                .andExpect(jsonPath("$.result.debug", is(true)));

    }

    @Test
    public void shouldReadWithWrongApplication() throws Exception {

        when(applicationService.getByApplicationName(tenant, NONEXIST_APPLICATION_NAME))
                .thenReturn(ServiceResponseBuilder.<Application>error().withMessage(ApplicationService.Validations.APPLICATION_DOES_NOT_EXIST.getCode()).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}", NONEXIST_APPLICATION_NAME, BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is4xxClientError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages[0]", is("Application does not exist")))
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldTryReadDeviceWithBadRequest() throws Exception {

        when(deviceRegisterService.getByDeviceGuid(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<Device>error().withMessage(DeviceRegisterService.Validations.DEVICE_GUID_DOES_NOT_EXIST.getCode()).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, device1.getGuid()))
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().is4xxClientError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages[0]", is("Device GUID does not exist")))
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldShowDeviceHealth() throws Exception {

        when(healthAlertService.getLastHighestSeverityByDeviceGuid(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<HealthAlert>ok().withResult(health1).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}/health", application.getName(), BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result").isMap())
                .andExpect(jsonPath("$.result.severity", is("FAIL")))
                .andExpect(jsonPath("$.result.lastUpdate", is("2017-05-25T12:56:10Z")));

    }

    @Test
    public void shouldShowDeviceHealthWithDeviceHealthEmpty() throws Exception {

        when(healthAlertService.getLastHighestSeverityByDeviceGuid(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<HealthAlert>error().withMessage(Validations.HEALTH_ALERT_DOES_NOT_EXIST.getCode()).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}/health", application.getName(), BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is4xxClientError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages[0]", is("Health alert does not exist")))
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldShowDeviceHealthAlerts() throws Exception {

        when(healthAlertService.findAllByTenantApplicationAndDeviceGuid(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<List<HealthAlert>>ok().withResult(healths).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}/health/alerts", application.getName(), BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result", hasSize(2)))
                .andExpect(jsonPath("$.result[0].severity", is(health1.getSeverity().toString())))
                .andExpect(jsonPath("$.result[0].description", is("No message received from the device for a long time.")))
                .andExpect(jsonPath("$.result[0].occurrenceDate", is(health1.getRegistrationDate().toString())))
                .andExpect(jsonPath("$.result[0].type", is(health1.getAlertTrigger().getType().name())))
                .andExpect(jsonPath("$.result[0].triggerName", is(alertTrigger.getName())))
                .andExpect(jsonPath("$.result[1].severity", is(health2.getSeverity().toString())))
                .andExpect(jsonPath("$.result[1].description", is("No message received from the device for a long time.")))
                .andExpect(jsonPath("$.result[1].occurrenceDate", is(health2.getRegistrationDate().toString())))
                .andExpect(jsonPath("$.result[1].type", is(health2.getAlertTrigger().getType().name())))
                .andExpect(jsonPath("$.result[1].triggerName", is(alertTrigger.getName())));
    }

    @Test
    public void shouldShowDeviceHealthAlertsWithDeviceHealthEmpty() throws Exception {

        when(healthAlertService.findAllByTenantApplicationAndDeviceGuid(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<List<HealthAlert>>error().withMessage(Validations.HEALTH_ALERT_DOES_NOT_EXIST.getCode()).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}/health/alerts", application.getName(), BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is4xxClientError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages[0]", is("Health alert does not exist")))
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldCreateDevice() throws Exception {

        when(deviceRegisterService.register(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(Device.class)))
                .thenReturn(ServiceResponseBuilder.<Device>ok().withResult(device1).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.post(MessageFormat.format("/{0}/{1}/", application.getName(), BASEPATH))
                .content(getJson(new DeviceVO().apply(device1)))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is2xxSuccessful())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.CREATED.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result").isMap())
                .andExpect(jsonPath("$.result.id", is("id1")))
                .andExpect(jsonPath("$.result.name", is("name1")))
                .andExpect(jsonPath("$.result.guid", is("guid1")))
                .andExpect(jsonPath("$.result.locationName", is("br")))
                .andExpect(jsonPath("$.result.active", is(true)))
                .andExpect(jsonPath("$.result.debug", is(true)));

    }

    @Test
    public void shouldTryCreateDeviceWithBadRequest() throws Exception {

        when(deviceRegisterService.register(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(Device.class)))
                .thenReturn(ServiceResponseBuilder.<Device>error().withMessage(DeviceRegisterService.Validations.DEVICE_GUID_DOES_NOT_EXIST.getCode()).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.post(MessageFormat.format("/{0}/{1}/", application.getName(), BASEPATH))
                .content(getJson(new DeviceVO().apply(device1)))
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is4xxClientError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.BAD_REQUEST.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages").exists())
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldUpdateDevice() throws Exception {

        when(deviceRegisterService.getByDeviceGuid(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<Device>ok().withResult(device1).build());

        when(deviceRegisterService.update(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.anyString(), org.mockito.Matchers.any(Device.class)))
                .thenReturn(ServiceResponseBuilder.<Device>ok().withResult(device1).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.put(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, device1.getGuid()))
                .content(getJson(new DeviceVO().apply(device1)))
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is2xxSuccessful())
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result").doesNotExist());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result").isMap())
                .andExpect(jsonPath("$.result.id", is("id1")))
                .andExpect(jsonPath("$.result.name", is("name1")))
                .andExpect(jsonPath("$.result.guid", is("guid1")))
                .andExpect(jsonPath("$.result.tags", is(Arrays.asList("tag1", "tag2"))))
                .andExpect(jsonPath("$.result.active", is(true)))
                .andExpect(jsonPath("$.result.debug", is(true)));

    }

    @Test
    public void shouldTryUpdateDeviceWithInternalError() throws Exception {

        when(deviceRegisterService.getByDeviceGuid(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<Device>ok().withResult(device1).build());

        when(deviceRegisterService.update(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.anyString(), org.mockito.Matchers.any(Device.class)))
                .thenReturn(ServiceResponseBuilder.<Device>error().build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.put(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, device1.getGuid()))
                .content(getJson(new DeviceVO().apply(device1)))
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is5xxServerError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.INTERNAL_SERVER_ERROR.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages").doesNotExist())
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldDeleteDevice() throws Exception {

        when(deviceRegisterService.remove(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<Device>ok().build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.delete(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is2xxSuccessful())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.NO_CONTENT.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldTryDeleteWithWrongApplication() throws Exception {

        when(applicationService.getByApplicationName(tenant, NONEXIST_APPLICATION_NAME))
                .thenReturn(ServiceResponseBuilder.<Application>error().withMessage(ApplicationService.Validations.APPLICATION_DOES_NOT_EXIST.getCode()).build());

        getMockMvc().perform(MockMvcRequestBuilders.delete(MessageFormat.format("/{0}/{1}/{2}", NONEXIST_APPLICATION_NAME, BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is4xxClientError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages[0]", is("Application does not exist")))
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldTryDeleteDeviceWithInternalError() throws Exception {

        when(deviceRegisterService.remove(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<Device>error().withMessage(DeviceRegisterService.Messages.DEVICE_REMOVED_UNSUCCESSFULLY.getCode()).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.delete(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is5xxServerError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.INTERNAL_SERVER_ERROR.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages").exists())
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldTryDeleteNonexistentEventRoute() throws Exception {

        when(deviceRegisterService.remove(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<Device>error().withMessage(DeviceRegisterService.Validations.DEVICE_GUID_DOES_NOT_EXIST.getCode()).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        getMockMvc().perform(MockMvcRequestBuilders.delete(MessageFormat.format("/{0}/{1}/{2}", application.getName(), BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is4xxClientError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages").exists())
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldShowDeviceStats() throws Exception {

        when(deviceRegisterService.getByDeviceGuid(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<Device>ok().withResult(device1).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        when(deviceEventService.findIncomingBy(tenant, application, device1.getGuid(), null, null, null, null, false, 1))
                .thenReturn(ServiceResponseBuilder.<List<Event>>ok().withResult(events).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}/stats", application.getName(), BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.OK.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result").isMap())
                .andExpect(jsonPath("$.result.registrationDate", is(registrationDate.toString())))
                .andExpect(jsonPath("$.result.lastModificationDate", is(registrationDate.toString())))
                .andExpect(jsonPath("$.result.lastDataReceivedDate", is(registrationDate.toString())));

    }

    @Test
    public void shouldShowStatWithWrongApplication() throws Exception {

        when(applicationService.getByApplicationName(tenant, NONEXIST_APPLICATION_NAME))
                .thenReturn(ServiceResponseBuilder.<Application>error().withMessage(ApplicationService.Validations.APPLICATION_DOES_NOT_EXIST.getCode()).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}/stats", NONEXIST_APPLICATION_NAME, BASEPATH, device1.getGuid()))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is4xxClientError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages[0]", is("Application does not exist")))
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldTryShowDeviceStatWithBadRequest() throws Exception {

        when(deviceRegisterService.getByDeviceGuid(tenant, application, device1.getGuid()))
                .thenReturn(ServiceResponseBuilder.<Device>error().withMessage(DeviceRegisterService.Validations.DEVICE_GUID_DOES_NOT_EXIST.getCode()).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        when(deviceEventService.findIncomingBy(tenant, application, device1.getGuid(), null, null, null, null, false, 1))
                .thenReturn(ServiceResponseBuilder.<List<Event>>ok().withResult(events).build());

        getMockMvc().perform(MockMvcRequestBuilders.get(MessageFormat.format("/{0}/{1}/{2}/stats", application.getName(), BASEPATH, device1.getGuid()))
                .accept(MediaType.APPLICATION_JSON)
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().is4xxClientError())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.NOT_FOUND.value())))
                .andExpect(jsonPath("$.status", is("error")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.messages[0]", is("Device GUID does not exist")))
                .andExpect(jsonPath("$.result").doesNotExist());

    }

    @Test
    public void shouldCreateDeviceByGateway() throws Exception {
        Location br =
                Location.builder()
                        .application(application)
                        .guid("f06d9d2d-f5ce-4cc6-8637-348743e8acad")
                        .id("br")
                        .name("br")
                        .description("br")
                        .build();

        Location room1 =
                Location.builder()
                        .application(application)
                        .guid("f06d9d2d-f5ce-4cc6-8637-348743e8acae")
                        .id("sala-101")
                        .name("sala-101")
                        .description("sala-101")
                        .parent(br)
                        .build();

        Location room101Roof = Location.builder()
                .tenant(tenant)
                .application(application)
                .parent(room1)
                .name("sala-101-teto")
                .guid("f06d9d2d-f5ce-4cc6-8637-348743e8acaf")
                .parent(room1)
                .build();

        room1.setChildren(Arrays.asList(room101Roof));
        br.setChildren(Arrays.asList(room1));

        when(deviceRegisterService.register(org.mockito.Matchers.any(Tenant.class), org.mockito.Matchers.any(Application.class), org.mockito.Matchers.any(Device.class)))
                .thenReturn(ServiceResponseBuilder.<Device>ok().withResult(device1).build());

        when(applicationService.getByApplicationName(tenant, application.getName()))
                .thenReturn(ServiceResponseBuilder.<Application>ok().withResult(application).build());

        when(gatewayService.validateGatewayAuthorization(gateway, device1.getLocation()))
                .thenReturn(ServiceResponseBuilder.<Boolean>ok().withResult(Boolean.TRUE).build());

        getMockMvc().perform(MockMvcRequestBuilders.post(
                MessageFormat.format("/{0}/{1}/",
                        application.getName(),
                        BASEPATH
                ))
                .content(getJson(new DeviceVO().apply(device1)))
                .contentType("application/json")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().is2xxSuccessful())
                .andExpect(content().contentType("application/json;charset=UTF-8"))
                .andExpect(jsonPath("$.code", is(HttpStatus.CREATED.value())))
                .andExpect(jsonPath("$.status", is("success")))
                .andExpect(jsonPath("$.timestamp", greaterThan(1400000000)))
                .andExpect(jsonPath("$.result").isMap())
                .andExpect(jsonPath("$.result.id", is("id1")))
                .andExpect(jsonPath("$.result.name", is("name1")))
                .andExpect(jsonPath("$.result.guid", is("guid1")))
                .andExpect(jsonPath("$.result.locationName", is("br")))
                .andExpect(jsonPath("$.result.active", is(true)))
                .andExpect(jsonPath("$.result.debug", is(true)));

    }

}


text:
id: a302f7aae1aa3152a5b413bc
title: Factorialize a Number
challengeType: 5
forumTopicId: 16013
dashedName: factorialize-a-number
---

# --description--

Return the factorial of the provided integer.

If the integer is represented with the letter `n`, a factorial is the product of all positive integers less than or equal to `n`.

Factorials are often represented with the shorthand notation `n!`

For example: `5! = 1 * 2 * 3 * 4 * 5 = 120`

Only integers greater than or equal to zero will be supplied to the function.

# --hints--

`factorialize(5)` should return a number.

```js
assert(typeof factorialize(5) === 'number');
```

`factorialize(5)` should return `120`.

```js
assert(factorialize(5) === 120);
```

`factorialize(10)` should return `3628800`.

```js
assert(factorialize(10) === 3628800);
```

`factorialize(20)` should return `2432902008176640000`.

```js
assert(factorialize(20) === 2432902008176640000);
```

`factorialize(0)` should return `1`.

```js
assert(factorialize(0) === 1);
```

# --seed--

## --seed-contents--

```js
function factorialize(num) {
  return num;
}

factorialize(5);
```

# --solutions--

```js
function factorialize(num) {
  return num < 1 ? 1 : num * factorialize(num - 1);
}

factorialize(5);
```

redpajama_set_name: RedPajamaGithub


text:
package org.olat.presentation.calendar;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.olat.data.calendar.CalendarEntry;
import org.olat.lms.calendar.CalendarUtils;
import org.olat.presentation.calendar.components.CalendarRenderWrapper;
import org.olat.presentation.framework.core.UserRequest;
import org.olat.presentation.framework.core.components.form.flexible.FormItem;
import org.olat.presentation.framework.core.components.form.flexible.FormItemContainer;
import org.olat.presentation.framework.core.components.form.flexible.elements.DateChooser;
import org.olat.presentation.framework.core.components.form.flexible.elements.FormLink;
import org.olat.presentation.framework.core.components.form.flexible.elements.SelectionElement;
import org.olat.presentation.framework.core.components.form.flexible.elements.SingleSelection;
import org.olat.presentation.framework.core.components.form.flexible.elements.StaticTextElement;
import org.olat.presentation.framework.core.components.form.flexible.elements.TextElement;
import org.olat.presentation.framework.core.components.form.flexible.impl.FormBasicController;
import org.olat.presentation.framework.core.components.form.flexible.impl.FormEvent;
import org.olat.presentation.framework.core.components.form.flexible.impl.FormLayoutContainer;
import org.olat.presentation.framework.core.control.Controller;
import org.olat.presentation.framework.core.control.WindowControl;
import org.olat.presentation.framework.core.formelements.SpacerElement;
import org.olat.presentation.framework.core.formelements.VisibilityDependsOnSelectionRule;
import org.olat.system.commons.StringHelper;
import org.olat.system.event.Event;
import org.olat.system.exception.OLATRuntimeException;

public class CalendarEntryForm extends FormBasicController {

    public static final String SUBMIT_MULTI = "multi";
    public static final String SUBMIT_SINGLE = "single";

    public static final String RECURRENCE_NONE = "NONE";

    private final CalendarEntry event;
    private final CalendarRenderWrapper choosenWrapper;
    private StaticTextElement calendarName;
    private SingleSelection chooseCalendar;
    private TextElement subject, location;
    private SelectionElement allDayEvent;
    private DateChooser begin, end;
    private SingleSelection classification;
    private final boolean readOnly, isNew;
    private SingleSelection chooseRecurrence;
    private DateChooser recurrenceEnd;
    private SpacerElement spacer;
    private final List<CalendarRenderWrapper> writeableCalendars;
    private FormLink multi;
    private boolean isMulti;

    private final String[] calendarKeys, calendarValues;
    private final String[] keysRecurrence, valuesRecurrence;
    private final String[] classKeys, classValues;

    /**
     * Display an event for modification or to add a new event.
     *
     * @param name
     * @param event
     * @param choosenWrapper
     * @param availableCalendars
     *            At least one calendar must be editable if this is a new event.
     * @param isNew
     *            If it is a new event, display a list of calendars to choose from.
     * @param locale
     */
    public CalendarEntryForm(final UserRequest ureq, final WindowControl wControl, final CalendarEntry event, final CalendarRenderWrapper choosenWrapper,
            final Collection<CalendarRenderWrapper> availableCalendars, final boolean isNew) {
        super(ureq, wControl);

        this.event = event;
        this.choosenWrapper = choosenWrapper;
        this.readOnly = choosenWrapper.getAccess() == CalendarRenderWrapper.ACCESS_READ_ONLY;
        this.isNew = isNew;
        this.isMulti = false;

        writeableCalendars = new ArrayList<CalendarRenderWrapper>();
        for (final Iterator<CalendarRenderWrapper> iter = availableCalendars.iterator(); iter.hasNext();) {
            final CalendarRenderWrapper calendarRenderWrapper = iter.next();
            if (calendarRenderWrapper.getAccess() == CalendarRenderWrapper.ACCESS_READ_WRITE) {
                writeableCalendars.add(calendarRenderWrapper);
            }
        }

        calendarKeys = new String[writeableCalendars.size()];
        calendarValues = new String[writeableCalendars.size()];
        for (int i = 0; i < writeableCalendars.size(); i++) {
            final CalendarRenderWrapper cw = writeableCalendars.get(i);
            calendarKeys[i] = cw.getCalendar().getCalendarID();
            calendarValues[i] = cw.getCalendarConfig().getDisplayName();
        }

        final String currentRecur = CalendarUtils.getRecurrence(event.getRecurrenceRule());
        final VisibilityDependsOnSelectionRule rule;
        keysRecurrence = new String[] { RECURRENCE_NONE, CalendarEntry.DAILY, CalendarEntry.WORKDAILY, CalendarEntry.WEEKLY, CalendarEntry.BIWEEKLY,
                CalendarEntry.MONTHLY, CalendarEntry.YEARLY };
        valuesRecurrence = new String[] { translate("cal.form.recurrence.none"), translate("cal.form.recurrence.daily"), translate("cal.form.recurrence.workdaily"),
                translate("cal.form.recurrence.weekly"), translate("cal.form.recurrence.biweekly"), translate("cal.form.recurrence.monthly"),
                translate("cal.form.recurrence.yearly") };

        // classification
        classKeys = new String[] { "0", "1", "2" };
        classValues = new String[] { getTranslator().translate("cal.form.class.private"), getTranslator().translate("cal.form.class.freebusy"),
                getTranslator().translate("cal.form.class.public") };

        initForm(ureq);
    }

    protected void setEntry(final CalendarEntry calendarEntry) {
        // subject
        if (readOnly && calendarEntry.getClassification() == CalendarEntry.CLASS_X_FREEBUSY) {
            subject.setValue(getTranslator().translate("cal.form.subject.hidden"));
        } else {
            subject.setValue(calendarEntry.getSubject());
        }
        // location
        if (readOnly && calendarEntry.getClassification() == CalendarEntry.CLASS_X_FREEBUSY) {
            location.setValue(getTranslator().translate("cal.form.location.hidden"));
        } else {
            location.setValue(calendarEntry.getLocation());
        }
        begin.setDate(calendarEntry.getBegin());
        end.setDate(calendarEntry.getEnd());
        allDayEvent.select("xx", calendarEntry.isAllDayEvent());
        switch (calendarEntry.getClassification()) {
        case CalendarEntry.CLASS_PRIVATE:
            classification.select("0", true);
            break;
        case CalendarEntry.CLASS_X_FREEBUSY:
            classification.select("1", true);
            break;
        case CalendarEntry.CLASS_PUBLIC:
            classification.select("2", true);
            break;
        default:
            classification.select("0", true);
        }
        final String recurrence = CalendarUtils.getRecurrence(calendarEntry.getRecurrenceRule());
        if (recurrence != null && !recurrence.equals("") && !recurrence.equals(RECURRENCE_NONE)) {
            chooseRecurrence.select(recurrence, true);
            final Date recurEnd = calendarEntry.getRecurrenceEndDate();
            if (recurEnd != null) {
                recurrenceEnd.setDate(recurEnd);
            }
        } else {
            chooseRecurrence.select(RECURRENCE_NONE, true);
        }
        isMulti = false;
    }

    protected boolean isMulti() {
        return isMulti;
    }

    @Override
    protected boolean validateFormLogic(final UserRequest ureq) {

        if (begin.getDate() == null) {
            begin.setErrorKey("cal.form.error.date", null);
            return false;
        }

        if (end.getDate() == null) {
            end.setErrorKey("cal.form.error.date", null);
            return false;
        }

        if (end.getDate().before(begin.getDate())) {
            end.setErrorKey("cal.form.error.endbeforebegin", null);
            return false;
        }

        final boolean hasEnd = !chooseRecurrence.getSelectedKey().equals(RECURRENCE_NONE);

        if (hasEnd && recurrenceEnd.getDate() == null) {
            recurrenceEnd.setErrorKey("cal.form.error.date", null);
            return false;
        }

        if (hasEnd && recurrenceEnd.getDate().before(begin.getDate())) {
            recurrenceEnd.setErrorKey("cal.form.error.endbeforebegin", null);
            return false;
        }

        return true;
    }

    /**
     * Get event with updated values.
     *
     * @return
     */
    public CalendarEntry getUpdatedKalendarEvent() {
        // subject
        event.setSubject(subject.getValue());

        // location
        event.setLocation(location.getValue());

        // date / time
        event.setBegin(begin.getDate());
        event.setEnd(end.getDate());
        event.setLastModified(new Date().getTime());
        if (event.getCreated() == 0) {
            event.setCreated(new Date().getTime());
        }

        // allday event?
        event.setAllDayEvent(allDayEvent.isSelected(0));

        // classification
        switch (classification.getSelected()) {
        case 0:
            event.setClassification(CalendarEntry.CLASS_PRIVATE);
            break;
        case 1:
            event.setClassification(CalendarEntry.CLASS_X_FREEBUSY);
            break;
        case 2:
            event.setClassification(CalendarEntry.CLASS_PUBLIC);
            break;
        default:
            throw new OLATRuntimeException("getSelected() in KalendarEntryForm.classification returned weitrd value", null);
        }

        // recurrence
        if (chooseRecurrence.getSelectedKey().equals(RECURRENCE_NONE)) {
            event.setRecurrenceRule(null);
        } else {
            final String rrule = CalendarUtils.getRecurrenceRule(chooseRecurrence.getSelectedKey(), recurrenceEnd.getDate());
            event.setRecurrenceRule(rrule);
        }

        return event;
    }

    public String getChoosenKalendarID() {
        if (chooseCalendar == null) {
            return choosenWrapper.getCalendar().getCalendarID();
        }
        return chooseCalendar.getSelectedKey();
    }

    @Override
    protected void formOK(final UserRequest ureq) {
        fireEvent(ureq, Event.DONE_EVENT);
    }

    @Override
    protected void formCancelled(final UserRequest ureq) {
        fireEvent(ureq, Event.CANCELLED_EVENT);
    }

    @Override
    protected void initForm(final FormItemContainer formLayout, final Controller listener, final UserRequest ureq) {

        chooseCalendar = uifactory.addDropdownSingleselect("cal.form.chooseCalendar", formLayout, calendarKeys, calendarValues, null);
        chooseCalendar.select(choosenWrapper.getCalendar().getCalendarID(), true);
        chooseCalendar.setVisible(isNew);

        calendarName = uifactory.addStaticTextElement("calendarname", "cal.form.calendarname", choosenWrapper.getCalendarConfig().getDisplayName(), formLayout);
        calendarName.setVisible(!isNew);

        final boolean fb = readOnly && event.getClassification() == CalendarEntry.CLASS_X_FREEBUSY;

        subject = uifactory
                .addTextAreaElement("subject", "cal.form.subject", -1, 3, 40, true, fb ? translate("cal.form.subject.hidden") : event.getSubject(), formLayout);
        subject.setMandatory(true);
        subject.setNotEmptyCheck("cal.form.error.mandatory");

        location = uifactory.addTextAreaElement("location", "cal.form.location", -1, 3, 40, true, fb ? translate("cal.form.location.hidden") : event.getLocation(),
                formLayout);

        begin = uifactory.addDateChooser("begin", "cal.form.begin", null, formLayout);
        begin.setDisplaySize(21);
        begin.setDateChooserTimeEnabled(true);
        begin.setMandatory(true);
        begin.setDate(event.getBegin());

        end = uifactory.addDateChooser("end", "cal.form.end", null, formLayout);
        end.setDisplaySize(21);
        end.setDateChooserTimeEnabled(true);
        end.setMandatory(true);
        end.setDate(event.getEnd());

        allDayEvent = uifactory.addCheckboxesVertical("allday", "cal.form.allday", formLayout, new String[] { "xx" }, new String[] { null }, null, 1);
        allDayEvent.select("xx", event.isAllDayEvent());

        chooseRecurrence = uifactory.addDropdownSingleselect("cal.form.recurrence", formLayout, keysRecurrence, valuesRecurrence, null);
        final String currentRecur = CalendarUtils.getRecurrence(event.getRecurrenceRule());
        final boolean rk = currentRecur != null && !currentRecur.equals("");
        chooseRecurrence.select(rk ? currentRecur : RECURRENCE_NONE, true);
        chooseRecurrence.addActionListener(this, FormEvent.ONCHANGE);

        recurrenceEnd = uifactory.addDateChooser("recurrence", "cal.form.recurrence.end", null, formLayout);
        recurrenceEnd.setDisplaySize(21);
		recurrenceEnd.setDateChooserTimeEnabled(false);
        recurrenceEnd.setMandatory(true);
        final Date recurEnd = event.getRecurrenceEndDate();
        if (recurEnd != null) {
            recurrenceEnd.setDate(recurEnd);
        }
        recurrenceEnd.setVisible(!chooseRecurrence.getSelectedKey().equals(RECURRENCE_NONE));

        classification = uifactory.addRadiosVertical("classification", "cal.form.class", formLayout, classKeys, classValues);
        switch (event.getClassification()) {
        case CalendarEntry.CLASS_PRIVATE:
            classification.select("0", true);
            break;
        case CalendarEntry.CLASS_X_FREEBUSY:
            classification.select("1", true);
            break;
        case CalendarEntry.CLASS_PUBLIC:
            classification.select("2", true);
            break;
        default:
            classification.select("0", true);
        }

        final StringBuilder buf = new StringBuilder();
        if (event.getCreated() != 0) {
            buf.append(StringHelper.formatLocaleDateTime(event.getCreated(), getTranslator().getLocale()));
            if (event.getCreatedBy() != null && !event.getCreatedBy().equals("")) {
                buf.append(" ");
                buf.append(getTranslator().translate("cal.form.created.by"));
                buf.append(" ");
                buf.append(event.getCreatedBy());
            }
        } else {
            buf.append("-");
        }
        uifactory.addStaticTextElement("cal.form.created.label", buf.toString(), formLayout);

        final FormLayoutContainer buttonLayout = FormLayoutContainer.createButtonLayout("button_layout", getTranslator());
        formLayout.add(buttonLayout);
        uifactory.addFormSubmitButton(SUBMIT_SINGLE, "cal.form.submitSingle", buttonLayout);
        if (writeableCalendars.size() > 1) {
            multi = uifactory.addFormLink("cal.form.submitMulti", buttonLayout, "b_button");
        }
        uifactory.addFormCancelButton("cancel", buttonLayout, ureq, getWindowControl());

        if (readOnly) {
            flc.setEnabled(false);
        }
    }

    @Override
    protected void formInnerEvent(final UserRequest ureq, final FormItem source, final FormEvent event) {
        if (source == chooseRecurrence) {
            recurrenceEnd.setVisible(!chooseRecurrence.getSelectedKey().equals(RECURRENCE_NONE));
        } else if (source == multi) {
            if (validateFormLogic(ureq)) {
                isMulti = true;
                formOK(ureq);
            }
        }
    }

    @Override
    protected void doDispose() {
        //
    }
}


text:
package com.aaomidi.mcauthenticator.map;

import com.aaomidi.mcauthenticator.model.User;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import org.bukkit.entity.Player;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapPalette;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;

import java.awt.*;

/**
 * @author Joseph Hirschfeld
 * @date 1/11/2016
 */
public class ImageMapRenderer extends MapRenderer {
    private final BitMatrix bitMatrix;

    public ImageMapRenderer(User user, String username) throws WriterException {
        this.bitMatrix = user.generateQRCode(username);
    }

    @Override
    public void render(MapView mapView, MapCanvas mapCanvas, Player player) {
        for (int x = 0; x < 128; x++) {
            for (int z = 0; z < 128; z++) {
                mapCanvas.setPixel(x, z, bitMatrix.get(x, z) ? MapPalette.matchColor(Color.black) : MapPalette.WHITE);
            }
        }
    }
}