Skip to content

Instantly share code, notes, and snippets.

View mchmielarz's full-sized avatar
🏠
Working from home

Michał Chmielarz mchmielarz

🏠
Working from home
View GitHub Profile
@mchmielarz
mchmielarz / exceptions_old_way.java
Last active December 17, 2018 21:24
Old, "good" way to handle exceptions
try {
database.start();
  fetchMeasurements(geoCoordinatesReader, airlyService, measurementsRepository);
} catch (SQLException exc) {
  log.error("Cannot start the database", exc);
}
@mchmielarz
mchmielarz / start_database_with_try.java
Last active December 17, 2018 21:23
Start database and fetch measurements with Try
Try
.run(database::start)
.onSuccess(ignore -> log.info("Database started successfully"))
  .onFailure(exc -> log.error("Cannot start the database", exc))
  .andThen(
() -> fetchMeasurements(geoCoordinatesReader, airlyService, measurementsRepository)
);
@mchmielarz
mchmielarz / read_geo_coordinates.java
Last active December 17, 2018 21:23
Read geo coordinates from a file with recovery
Try.of(
() -> geoCoordinatesReader.fromCsvFile("./src/main/resources/cities.csv")
)
.onSuccess(coords -> log.info("Coordinates read: {}", coords))
  .onFailure(exc -> log.error("Cannot read coordinates from a file", exc))
  .recover(FileNotFoundException.class, (exc) -> provideBackupCoordinates())
  .getOrElse(List.empty());
@mchmielarz
mchmielarz / backup_coordinates.java
Created December 17, 2018 21:17
Provide backup geo coordinates
private static List<GeoCoordinates> provideBackupCoordinates() {
 log.warn("Calling for backup data");
 return List.of(
GeoCoordinates.builder()
.city("Warszawa")
.latitude("52.25")
.longitude("21")
.build()
);
}
@mchmielarz
mchmielarz / fetch_data_from_airly_service.java
Last active December 17, 2018 21:19
Fetch data from Airly service
Try.of(() -> Uri.create("http://airapi.airly.eu/v2/measurements/nearest/..."))
.flatMap(this::callAirly)
  .map(responseBody -> new RawMeasurements(coordinates.city(), responseBody))
  .mapTry(this::parse);
@mchmielarz
mchmielarz / call_airly_service.java
Created December 17, 2018 21:20
Call Airly service
private Try<String> callAirly(URI airlyUri) {
HttpRequest req = requestBuilder.uri(airlyUri).build();
return Try
.of(() -> httpClient.send(req, bodyHandler))
  .map(HttpResponse::body);
}
@mchmielarz
mchmielarz / onfailure_chained.java
Created December 17, 2018 21:22
Chained onFailure call
Try.of(this::computation)
.onFailure(exc -> log.error("Computation failed!", exc))
  .andThen(this::storeInDb)
  .onFailure(exc -> log.error("Storing in database failed!", exc))
  .andThen(this::sendEmail)
  .onFailure(exc -> log.error("Email sending failed!", exc))
  .onSuccess(value -> log.info("Value computed, stored in db and sent in email"));
@mchmielarz
mchmielarz / iban_field_annotation.java
Created December 17, 2018 22:08
IBAN field annotation
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = IbanValidator.class)
public @interface Iban {
String message() default "{iban.constraint}";
  Class<?>[] groups() default {};
  Class<? extends Payload>[] payload() default {};
}
@mchmielarz
mchmielarz / IbanValidator.java
Created December 17, 2018 22:11
IbanValidator class
@Slf4j
public class IbanValidator implements ConstraintValidator<Iban, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
  if (value == null) {
  return false;
}
return Try.of(() -> {
@mchmielarz
mchmielarz / bank_account_validation.java
Created December 17, 2018 22:17
Running BankAccount validation
BankAccount bankAccount = newBankAccount("invalid_iban", "invalid_bic", null);
final Set<ConstraintViolation<BankAccount>> constraints =
Validation.buildDefaultValidatorFactory().getValidator().validate(bankAccount);