@Before
  public void setup() throws Exception {
    mapper = Jackson.newObjectMapper();
    dao = db.getDbi().onDemand(UserDAO.class);

    user = mapper.readValue(fixture("fixtures/user.json"), User.class);
  }
public class RestaurantTest {

  private static final ObjectMapper MAPPER = Jackson.newObjectMapper();

  @Test
  public void should_serialize_to_JSON() throws Exception {
    // given
    final Restaurant representation = new Restaurant("MacDo");
    final String expected =
        MAPPER.writeValueAsString(
            MAPPER.readValue(fixture("fixtures/valid_restaurant.json"), Restaurant.class));

    // when
    String serializedRepresentation = MAPPER.writeValueAsString(representation);

    // then
    assertThat(serializedRepresentation).isEqualTo(expected);
  }

  @Test
  public void should_deserialize_from_JSON() throws Exception {
    // given
    final String json = fixture("fixtures/valid_restaurant.json");
    final Restaurant expected = new Restaurant("MacDo");

    // when
    Restaurant deserializedRepresentation = MAPPER.readValue(json, Restaurant.class);

    // then
    assertThat(deserializedRepresentation).isNotNull();
    assertThat(deserializedRepresentation.getName()).isEqualTo(expected.getName());
  }
}
 @Test
 public void doesNotDefaultExceptionMappers() throws Exception {
   http.setRegisterDefaultExceptionMappers(false);
   assertThat(http.getRegisterDefaultExceptionMappers()).isFalse();
   Environment environment =
       new Environment(
           "test",
           Jackson.newObjectMapper(),
           Validation.buildDefaultValidatorFactory().getValidator(),
           new MetricRegistry(),
           ClassLoader.getSystemClassLoader());
   http.build(environment);
   for (Object singleton : environment.jersey().getResourceConfig().getSingletons()) {
     assertThat(singleton).isNotInstanceOf(ExceptionMapper.class);
   }
 }
  @Before
  public void setUp() throws Exception {
    final ObjectMapper objectMapper = Jackson.newObjectMapper();
    objectMapper
        .getSubtypeResolver()
        .registerSubtypes(
            ConsoleAppenderFactory.class,
            FileAppenderFactory.class,
            SyslogAppenderFactory.class,
            HttpConnectorFactory.class);

    this.http =
        new ConfigurationFactory<>(
                DefaultServerFactory.class, BaseValidator.newValidator(), objectMapper, "dw")
            .build(new File(Resources.getResource("yaml/server.yml").toURI()));
  }
 @Test
 public void registersDefaultExceptionMappers() throws Exception {
   assertThat(http.getRegisterDefaultExceptionMappers()).isTrue();
   Environment environment =
       new Environment(
           "test",
           Jackson.newObjectMapper(),
           Validation.buildDefaultValidatorFactory().getValidator(),
           new MetricRegistry(),
           ClassLoader.getSystemClassLoader());
   http.build(environment);
   Set<Object> singletons = environment.jersey().getResourceConfig().getSingletons();
   assertThat(singletons).hasAtLeastOneElementOfType(LoggingExceptionMapper.class);
   assertThat(singletons).hasAtLeastOneElementOfType(ConstraintViolationExceptionMapper.class);
   assertThat(singletons).hasAtLeastOneElementOfType(JsonProcessingExceptionMapper.class);
   assertThat(singletons).hasAtLeastOneElementOfType(EarlyEofExceptionMapper.class);
 }
Example #6
0
public class ConfigurationTestUtil {

  private static final Validator VALIDATOR =
      Validation.buildDefaultValidatorFactory().getValidator();
  private static final ConfigurationFactory<BackupConfiguration> CONFIGURATION_FACTORY =
      new ConfigurationFactory<>(
          BackupConfiguration.class, VALIDATOR, Jackson.newObjectMapper(), "dw");
  private static final Logger LOG = LoggerFactory.getLogger(ConfigurationTestUtil.class);

  private static final String CONFIGURATION_FILENAME = "conf/backups.yml.template";
  private static final Optional<File> CONFIGURATION_FILE;

  static {
    CONFIGURATION_FILE = findConfigurationFile(CONFIGURATION_FILENAME);
  }

  private static Optional<File> findConfigurationFile(File parent, String filename) {
    if (parent == null || !parent.isDirectory()) {
      return Optional.absent();
    }

    final File file = new File(parent, filename);
    if (file.exists()) {
      LOG.debug("Found configuration file at: {}", file.getAbsolutePath());
      return Optional.of(file);
    }

    return findConfigurationFile(parent.getParentFile(), filename);
  }

  private static Optional<File> findConfigurationFile(String filename) {
    final File parent = new File(ConfigurationTestUtil.class.getResource(".").getFile());
    return findConfigurationFile(parent, filename);
  }

  public static BackupConfiguration loadConfiguration() throws IOException, ConfigurationException {
    if (!CONFIGURATION_FILE.isPresent()) {
      throw new FileNotFoundException(String.format("Unable to find %s", CONFIGURATION_FILENAME));
    }

    return CONFIGURATION_FACTORY.build(CONFIGURATION_FILE.get());
  }
}
  @Before
  public void setup() throws Exception {
    JerseyClientConfiguration clientConfiguration = new JerseyClientConfiguration();
    clientConfiguration.setConnectionTimeout(Duration.milliseconds(SLEEP_TIME_IN_MILLIS / 2));
    clientConfiguration.setTimeout(Duration.milliseconds(DEFAULT_CONNECT_TIMEOUT_IN_MILLIS));

    environment =
        new Environment(
            "test-dropwizard-apache-connector",
            Jackson.newObjectMapper(),
            Validators.newValidator(),
            new MetricRegistry(),
            getClass().getClassLoader());
    client =
        (JerseyClient)
            new JerseyClientBuilder(environment).using(clientConfiguration).build("test");
    for (LifeCycle lifeCycle : environment.lifecycle().getManagedObjects()) {
      lifeCycle.start();
    }
  }
  @Test
  public void testGracefulShutdown() throws Exception {
    ObjectMapper objectMapper = Jackson.newObjectMapper();
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    MetricRegistry metricRegistry = new MetricRegistry();
    Environment environment =
        new Environment(
            "test", objectMapper, validator, metricRegistry, ClassLoader.getSystemClassLoader());

    CountDownLatch requestReceived = new CountDownLatch(1);
    CountDownLatch shutdownInvoked = new CountDownLatch(1);

    environment.jersey().register(new TestResource(requestReceived, shutdownInvoked));

    final ScheduledExecutorService executor = Executors.newScheduledThreadPool(3);
    final Server server = http.build(environment);

    ((AbstractNetworkConnector) server.getConnectors()[0]).setPort(0);

    ScheduledFuture<Void> cleanup =
        executor.schedule(
            new Callable<Void>() {
              @Override
              public Void call() throws Exception {
                if (!server.isStopped()) {
                  server.stop();
                }
                executor.shutdownNow();
                return null;
              }
            },
            5,
            TimeUnit.SECONDS);

    server.start();

    final int port = ((AbstractNetworkConnector) server.getConnectors()[0]).getLocalPort();

    Future<String> futureResult =
        executor.submit(
            new Callable<String>() {
              @Override
              public String call() throws Exception {
                URL url = new URL("http://localhost:" + port + "/app/test");
                URLConnection connection = url.openConnection();
                connection.connect();
                return CharStreams.toString(new InputStreamReader(connection.getInputStream()));
              }
            });

    requestReceived.await();

    Future<Void> serverStopped =
        executor.submit(
            new Callable<Void>() {
              @Override
              public Void call() throws Exception {
                server.stop();
                return null;
              }
            });

    Connector[] connectors = server.getConnectors();
    assertThat(connectors).isNotEmpty();
    assertThat(connectors[0]).isInstanceOf(NetworkConnector.class);
    NetworkConnector connector = (NetworkConnector) connectors[0];

    // wait for server to close the connectors
    while (true) {
      if (!connector.isOpen()) {
        shutdownInvoked.countDown();
        break;
      }
      Thread.sleep(5);
    }

    String result = futureResult.get();
    assertThat(result).isEqualTo("test");

    serverStopped.get();

    // cancel the cleanup future since everything succeeded
    cleanup.cancel(false);
    executor.shutdownNow();
  }
public class PortadorTituloTest {

  private static final ObjectMapper MAPPER = Jackson.newObjectMapper();

  private PortadorTitulo portadorTituloConCedula;
  private PortadorTitulo portadorTituloConPasaporte;
  private String numeroIdentificacion = "ASD123";
  private DateTime fechaFinVigenciaPasaporteValida =
      new DateTime(2015, 3, 16, 0, 0, DateTimeZone.UTC);
  private DateTime fechaFinVigenciaVisaValida = new DateTime(2015, 3, 16, 0, 0, DateTimeZone.UTC);

  @Before
  public void setUp() {
    portadorTituloConCedula =
        PortadorTituloBuilder.nuevoPortadorTitulo()
            .con(p -> p.identificacion = new Cedula("1111111116"))
            .generar();

    portadorTituloConPasaporte =
        PortadorTituloBuilder.nuevoPortadorTitulo()
            .con(
                p ->
                    p.identificacion =
                        new Pasaporte(
                            numeroIdentificacion,
                            fechaFinVigenciaPasaporteValida,
                            fechaFinVigenciaVisaValida,
                            "9",
                            false))
            .generar();
  }

  @Test
  public void debeDeserializarUnPortadorTituloConCedulaDesdeJSON() throws IOException {
    PortadorTitulo portadorTituloDeserializado =
        MAPPER.readValue(fixture("fixtures/portador_titulo_con_cedula.json"), PortadorTitulo.class);

    assertThat(portadorTituloDeserializado.getId(), is(portadorTituloConCedula.getId()));
    assertThat(
        portadorTituloDeserializado.getNombresCompletos(),
        is(portadorTituloConCedula.getNombresCompletos()));
    assertThat(
        portadorTituloDeserializado.getIdentificacion().getTipoDocumento(),
        is(portadorTituloConCedula.getIdentificacion().getTipoDocumento()));
    assertThat(
        portadorTituloDeserializado.getIdentificacion().getNumeroIdentificacion(),
        is(portadorTituloConCedula.getIdentificacion().getNumeroIdentificacion()));
    assertThat(portadorTituloDeserializado.getEmail(), is(portadorTituloConCedula.getEmail()));
    assertThat(portadorTituloDeserializado.getGenero(), is(portadorTituloConCedula.getGenero()));
    assertThat(portadorTituloDeserializado.getIdEtnia(), is(portadorTituloConCedula.getIdEtnia()));
    assertThat(
        portadorTituloDeserializado.getFechaNacimiento(),
        is(portadorTituloConCedula.getFechaNacimiento()));
    assertThat(
        portadorTituloDeserializado.getTelefonoConvencional(),
        is(portadorTituloConCedula.getTelefonoConvencional()));
    assertThat(
        portadorTituloDeserializado.getExtension(), is(portadorTituloConCedula.getExtension()));
    assertThat(
        portadorTituloDeserializado.getTelefonoCelular(),
        is(portadorTituloConCedula.getTelefonoCelular()));
    assertThat(
        portadorTituloDeserializado.getDireccion(), is(portadorTituloConCedula.getDireccion()));
  }

  @Test
  public void debeSerializarUnPortadorTituloConCedulaAJSON() throws IOException {
    String actual = MAPPER.writeValueAsString(portadorTituloConCedula);
    assertThat(actual, is(fixture("fixtures/portador_titulo_con_cedula_con_id.json")));
  }

  @Test
  public void debeDeserializarUnPortadorTituloConPasaporteDesdeJSON() throws IOException {
    PortadorTitulo portadorTituloDeserializado =
        MAPPER.readValue(
            fixture("fixtures/portador_titulo_con_pasaporte.json"), PortadorTitulo.class);

    assertThat(portadorTituloDeserializado.getId(), is(portadorTituloConPasaporte.getId()));
    assertThat(
        portadorTituloDeserializado.getNombresCompletos(),
        is(portadorTituloConPasaporte.getNombresCompletos()));
    assertThat(portadorTituloDeserializado.getEmail(), is(portadorTituloConPasaporte.getEmail()));
    assertThat(portadorTituloDeserializado.getGenero(), is(portadorTituloConPasaporte.getGenero()));
    assertThat(
        portadorTituloDeserializado.getIdEtnia(), is(portadorTituloConPasaporte.getIdEtnia()));
    assertThat(
        portadorTituloDeserializado.getFechaNacimiento(),
        is(portadorTituloConPasaporte.getFechaNacimiento()));
    assertThat(
        portadorTituloDeserializado.getTelefonoConvencional(),
        is(portadorTituloConPasaporte.getTelefonoConvencional()));
    assertThat(
        portadorTituloDeserializado.getExtension(), is(portadorTituloConPasaporte.getExtension()));
    assertThat(
        portadorTituloDeserializado.getTelefonoCelular(),
        is(portadorTituloConPasaporte.getTelefonoCelular()));
    assertThat(
        portadorTituloDeserializado.getDireccion(), is(portadorTituloConPasaporte.getDireccion()));

    assertPasaporte(
        portadorTituloDeserializado.getIdentificacion(),
        portadorTituloConPasaporte.getIdentificacion());
  }

  private void assertPasaporte(
      Identificacion identificacionActual, Identificacion identificacionEsperada) {

    Pasaporte pasaporteActual = (Pasaporte) identificacionActual;
    Pasaporte pasaporteEsperado = (Pasaporte) identificacionEsperada;

    assertThat(
        pasaporteEsperado.getFinVigenciaPasaporte(), is(pasaporteActual.getFinVigenciaPasaporte()));
    assertThat(pasaporteEsperado.getFinVigenciaVisa(), is(pasaporteActual.getFinVigenciaVisa()));
    assertThat(pasaporteEsperado.getIdCategoriaVisa(), is(pasaporteActual.getIdCategoriaVisa()));
    assertThat(pasaporteEsperado.isVisaIndefinida(), is(pasaporteActual.isVisaIndefinida()));
  }

  @Test
  public void debeSerializarUnPortadorTituloConPasaporteAJSON() throws IOException {
    String actual = MAPPER.writeValueAsString(portadorTituloConPasaporte);
    assertThat(actual, is(fixture("fixtures/portador_titulo_con_pasaporte_con_id.json")));
  }
}
 private DataSourceFactory getDataSourceFactory(String resourceName) throws Exception {
   return new ConfigurationFactory<>(
           DataSourceFactory.class, Validators.newValidator(), Jackson.newObjectMapper(), "dw")
       .build(new File(Resources.getResource(resourceName).toURI()));
 }
Example #11
0
/** Tests {@link ResourceTestRule}. */
public class PersonResourceTest {
  private static class DummyExceptionMapper implements ExceptionMapper<WebApplicationException> {
    @Override
    public Response toResponse(WebApplicationException e) {
      throw new UnsupportedOperationException();
    }
  }

  private static final PeopleStore dao = mock(PeopleStore.class);

  private static final ObjectMapper mapper =
      Jackson.newObjectMapper().registerModule(new GuavaModule());

  @ClassRule
  public static final ResourceTestRule resources =
      ResourceTestRule.builder()
          .addResource(new PersonResource(dao))
          .setMapper(mapper)
          .setClientConfigurator(clientConfig -> clientConfig.register(DummyExceptionMapper.class))
          .build();

  private final Person person = new Person("blah", "*****@*****.**");

  @Before
  public void setup() {
    reset(dao);
    when(dao.fetchPerson(eq("blah"))).thenReturn(person);
  }

  @Test
  public void testGetPerson() {
    assertThat(resources.client().target("/person/blah").request().get(Person.class))
        .isEqualTo(person);
    verify(dao).fetchPerson("blah");
  }

  @Test
  public void testGetImmutableListOfPersons() {
    assertThat(
            resources
                .client()
                .target("/person/blah/list")
                .request()
                .get(new GenericType<ImmutableList<Person>>() {}))
        .isEqualTo(ImmutableList.of(person));
  }

  @Test
  public void testGetPersonWithQueryParam() {
    // Test to ensure that the dropwizard validator is registered so that
    // it can validate the "ind" IntParam.
    assertThat(
            resources
                .client()
                .target("/person/blah/index")
                .queryParam("ind", 0)
                .request()
                .get(Person.class))
        .isEqualTo(person);
    verify(dao).fetchPerson("blah");
  }

  @Test
  public void testDefaultConstraintViolation() {
    assertThat(
            resources
                .client()
                .target("/person/blah/index")
                .queryParam("ind", -1)
                .request()
                .get()
                .readEntity(String.class))
        .isEqualTo("{\"errors\":[\"query param ind must be greater than or equal to 0\"]}");
  }

  @Test
  public void testDefaultJsonProcessingMapper() {
    assertThat(
            resources
                .client()
                .target("/person/blah/runtime-exception")
                .request()
                .post(Entity.json("{ \"he: \"ho\"}"))
                .readEntity(String.class))
        .isEqualTo("{\"code\":400,\"message\":\"Unable to process JSON\"}");
  }

  @Test
  public void testDefaultExceptionMapper() {
    assertThat(
            resources
                .client()
                .target("/person/blah/runtime-exception")
                .request()
                .post(Entity.json("{}"))
                .readEntity(String.class))
        .startsWith(
            "{\"code\":500,\"message\":\"There was an error processing your request. It has been logged");
  }

  @Test
  public void testDefaultEofExceptionMapper() {
    assertThat(resources.client().target("/person/blah/eof-exception").request().get().getStatus())
        .isEqualTo(Response.Status.BAD_REQUEST.getStatusCode());
  }

  @Test
  public void testValidationGroupsException() {
    final Response resp =
        resources
            .client()
            .target("/person/blah/validation-groups-exception")
            .request()
            .post(Entity.json("{}"));
    assertThat(resp.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    assertThat(resp.readEntity(String.class))
        .isEqualTo(
            "{\"code\":500,\"message\":\"Parameters must have the same"
                + " validation groups in validationGroupsException\"}");
  }

  @Test
  public void testCustomClientConfiguration() {
    assertThat(resources.client().getConfiguration().isRegistered(DummyExceptionMapper.class))
        .isTrue();
  }
}