From f5e53e375445ed73b14fc60ae0fbd66ca75dfd2f Mon Sep 17 00:00:00 2001 From: Celestino Bellone Date: Sun, 15 Mar 2015 11:08:01 +0100 Subject: [PATCH] #41 - move admin api controllers to a more appropriate package (api.admin) --- .../controller/api/CheckInApiController.java | 159 ---------------- .../controller/api/EventApiController.java | 178 ------------------ .../controller/api/LocationApiController.java | 78 -------- .../api/PromoCodeDiscountApiController.java | 87 --------- .../controller/api/SerializablePair.java | 33 ---- .../controller/api/SettingsApiController.java | 72 ------- .../api/SpecialPriceApiController.java | 91 --------- .../controller/api/UsersApiController.java | 155 --------------- 8 files changed, 853 deletions(-) delete mode 100644 src/main/java/alfio/controller/api/CheckInApiController.java delete mode 100644 src/main/java/alfio/controller/api/EventApiController.java delete mode 100644 src/main/java/alfio/controller/api/LocationApiController.java delete mode 100644 src/main/java/alfio/controller/api/PromoCodeDiscountApiController.java delete mode 100644 src/main/java/alfio/controller/api/SerializablePair.java delete mode 100644 src/main/java/alfio/controller/api/SettingsApiController.java delete mode 100644 src/main/java/alfio/controller/api/SpecialPriceApiController.java delete mode 100644 src/main/java/alfio/controller/api/UsersApiController.java diff --git a/src/main/java/alfio/controller/api/CheckInApiController.java b/src/main/java/alfio/controller/api/CheckInApiController.java deleted file mode 100644 index cd0902d1fd..0000000000 --- a/src/main/java/alfio/controller/api/CheckInApiController.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * This file is part of alf.io. - * - * alf.io is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * alf.io is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with alf.io. If not, see . - */ -package alfio.controller.api; - -import static alfio.util.OptionalWrapper.*; -import static org.springframework.web.bind.annotation.RequestMethod.*; - -import java.util.List; -import java.util.Optional; - -import lombok.Data; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import alfio.manager.CheckInManager; -import alfio.model.Event; -import alfio.model.Ticket; -import alfio.model.Ticket.TicketStatus; -import alfio.repository.EventRepository; -import alfio.repository.TicketRepository; - -@RestController -@RequestMapping("/admin/api") -public class CheckInApiController { - - private final TicketRepository ticketRepository; - private final EventRepository eventRepository; - private final CheckInManager checkInManager; - - @Data - public static class TicketCode { - private String code; - } - - public enum CheckInStatus { - EVENT_NOT_FOUND, TICKET_NOT_FOUND, EMPTY_TICKET_CODE, INVALID_TICKET_CODE, INVALID_TICKET_STATE, ALREADY_CHECK_IN, MUST_PAY, SUCCESS - } - - @Data - public static class CheckInResult { - private final CheckInStatus status; - private final String message; - } - - @Data - public static class OnSitePaymentConfirmation { - private final boolean status; - private final String message; - } - - @Autowired - public CheckInApiController(EventRepository eventRepository, TicketRepository ticketRepository, CheckInManager checkInManager) { - this.eventRepository = eventRepository; - this.ticketRepository = ticketRepository; - this.checkInManager = checkInManager; - } - - @RequestMapping(value = "/check-in/{eventId}/ticket/{ticketIdentifier}", method = GET) - public Ticket findTicketWithUUID(@PathVariable("eventId") int eventId, @PathVariable("ticketIdentifier") String ticketIdentifier) { - Optional event = optionally(() -> eventRepository.findById(eventId)); - Optional ticket = optionally(() -> ticketRepository.findByUUID(ticketIdentifier)); - - if(event.isPresent() && ticket.isPresent()) { - return ticket.get(); - } else { - return null; - } - } - - @RequestMapping(value = "/check-in/{eventId}/ticket/{ticketIdentifier}", method = POST) - public CheckInResult checkIn(@PathVariable("eventId") int eventId, @PathVariable("ticketIdentifier") String ticketIdentifier, @RequestBody TicketCode ticketCode) { - - Optional event = optionally(() -> eventRepository.findById(eventId)); - - if (!event.isPresent()) { - return new CheckInResult(CheckInStatus.EVENT_NOT_FOUND, "Event with id " + eventId + " not found"); - } - - Optional ticket = optionally(() -> ticketRepository.findByUUID(ticketIdentifier)); - - if (!ticket.isPresent()) { - return new CheckInResult(CheckInStatus.TICKET_NOT_FOUND, "Ticket with uuid " + ticketIdentifier + " not found"); - } - - if(ticketCode == null || StringUtils.isEmpty(ticketCode.getCode())) { - return new CheckInResult(CheckInStatus.EMPTY_TICKET_CODE, "Missing ticket code"); - } - - return handleCheckIn(event.get(), ticket.get(), ticketCode.getCode()); - } - - - private CheckInResult handleCheckIn(Event event, Ticket ticket, String ticketCode) { - - if (!ticketCode.equals(ticket.ticketCode(event.getPrivateKey()))) { - return new CheckInResult(CheckInStatus.INVALID_TICKET_CODE, "Ticket qr code does not match"); - } - - final TicketStatus ticketStatus = ticket.getStatus(); - - if (ticketStatus == TicketStatus.TO_BE_PAID) { - return new CheckInResult(CheckInStatus.MUST_PAY, "Must pay for ticket"); //TODO: must say how much - } - - if (ticketStatus == TicketStatus.CHECKED_IN) { - return new CheckInResult(CheckInStatus.ALREADY_CHECK_IN, "Error: already checked in"); - } - - if (ticket.getStatus() != TicketStatus.ACQUIRED) { - return new CheckInResult(CheckInStatus.INVALID_TICKET_STATE, "Invalid ticket state, expected ACQUIRED state, received " + ticket.getStatus()); - } - - checkInManager.checkIn(ticket.getUuid()); - return new CheckInResult(CheckInStatus.SUCCESS, "success"); - } - - @RequestMapping(value = "/check-in/{eventId}/ticket/{ticketIdentifier}/confirm-on-site-payment", method = POST) - public OnSitePaymentConfirmation confirmOnSitePayment(@PathVariable("eventId") int eventId, @PathVariable("ticketIdentifier") String ticketIdentifier) { - - Optional ticket = optionally(() -> ticketRepository.findByUUID(ticketIdentifier)); - - if (!ticket.isPresent()) { - return new OnSitePaymentConfirmation(false, "Ticket with uuid " + ticketIdentifier + " not found"); - } - - Ticket t = ticket.get(); - - if (t.getStatus() != TicketStatus.TO_BE_PAID) { - return new OnSitePaymentConfirmation(false, "Invalid ticket state, expected TO_BE_PAID state, received " + t.getStatus()); - } - - checkInManager.acquire(t.getUuid()); - return new OnSitePaymentConfirmation(true, "ok"); - } - - @RequestMapping(value = "/check-in/{eventId}/ticket", method = GET) - public List listAllTickets(@PathVariable("eventId") int eventId) { - return ticketRepository.findAllByEventId(eventId); - } -} diff --git a/src/main/java/alfio/controller/api/EventApiController.java b/src/main/java/alfio/controller/api/EventApiController.java deleted file mode 100644 index 94bff43c95..0000000000 --- a/src/main/java/alfio/controller/api/EventApiController.java +++ /dev/null @@ -1,178 +0,0 @@ -/** - * This file is part of alf.io. - * - * alf.io is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * alf.io is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with alf.io. If not, see . - */ -package alfio.controller.api; - -import alfio.manager.EventManager; -import alfio.manager.support.OrderSummary; -import alfio.model.TicketReservation; -import alfio.model.modification.EventModification; -import alfio.model.modification.EventWithStatistics; -import alfio.model.modification.TicketAllocationModification; -import alfio.model.modification.TicketCategoryModification; -import alfio.model.transaction.PaymentProxy; -import alfio.util.ValidationResult; -import alfio.util.Validator; -import com.opencsv.CSVReader; -import lombok.extern.log4j.Log4j2; -import org.apache.commons.lang3.Validate; -import org.apache.commons.lang3.tuple.Triple; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.validation.Errors; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.math.BigDecimal; -import java.security.Principal; -import java.util.*; -import java.util.stream.Collectors; - -import static org.springframework.web.bind.annotation.RequestMethod.*; - -@RestController -@RequestMapping("/admin/api") -@Log4j2 -public class EventApiController { - - private static final String OK = "OK"; - private final EventManager eventManager; - - @Autowired - public EventApiController(EventManager eventManager) { - this.eventManager = eventManager; - } - - @ExceptionHandler(Exception.class) - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - public String unhandledException(Exception e) { - if(!IllegalArgumentException.class.isInstance(e)) { - log.warn("unhandled exception", e); - } - return e.getMessage(); - } - - - @RequestMapping(value = "/paymentProxies", method = GET) - @ResponseStatus(HttpStatus.OK) - public List getPaymentProxies() { - return Arrays.asList(PaymentProxy.values()); - } - - @RequestMapping(value = "/events", method = GET) - public List getAllEvents(Principal principal) { - return eventManager.getAllEventsWithStatistics(principal.getName()); - } - - @RequestMapping(value = "/events/{name}", method = GET) - public Map getSingleEvent(@PathVariable("name") String eventName, Principal principal) { - Map out = new HashMap<>(); - final String username = principal.getName(); - final EventWithStatistics event = eventManager.getSingleEventWithStatistics(eventName, username); - out.put("event", event); - out.put("organization", eventManager.loadOrganizer(event.getEvent(), username)); - return out; - } - - @RequestMapping(value = "/events/check", method = POST) - public ValidationResult validateEvent(@RequestBody EventModification eventModification) { - return ValidationResult.success(); - } - - @RequestMapping(value = "/events/new", method = POST) - public String insertEvent(@RequestBody EventModification eventModification) { - eventManager.createEvent(eventModification); - return OK; - } - - @RequestMapping(value = "/events/{id}/header/update", method = POST) - public ValidationResult updateHeader(@PathVariable("id") int id, @RequestBody EventModification eventModification, Errors errors, Principal principal) { - return Validator.validateEventHeader(eventModification, errors).ifSuccess(() -> eventManager.updateEventHeader(id, eventModification, principal.getName())); - } - - @RequestMapping(value = "/events/{id}/prices/update", method = POST) - public ValidationResult updatePrices(@PathVariable("id") int id, @RequestBody EventModification eventModification, Errors errors, Principal principal) { - return Validator.validateEventPrices(eventModification, errors).ifSuccess(() -> eventManager.updateEventPrices(id, eventModification, principal.getName())); - } - - @RequestMapping(value = "/events/{eventId}/categories/{categoryId}/update", method = POST) - public ValidationResult updateExistingCategory(@PathVariable("eventId") int eventId, @PathVariable("categoryId") int categoryId, @RequestBody TicketCategoryModification category, Errors errors, Principal principal) { - return Validator.validateCategory(category, errors).ifSuccess(() -> eventManager.updateCategory(categoryId, eventId, category, principal.getName())); - } - - @RequestMapping(value = "/events/{eventId}/categories/new", method = POST) - public ValidationResult createCategory(@PathVariable("eventId") int eventId, @RequestBody TicketCategoryModification category, Errors errors, Principal principal) { - return Validator.validateCategory(category, errors).ifSuccess(() -> eventManager.insertCategory(eventId, category, principal.getName())); - } - - @RequestMapping(value = "/events/reallocate", method = PUT) - public String reallocateTickets(@RequestBody TicketAllocationModification form) { - eventManager.reallocateTickets(form.getSrcCategoryId(), form.getTargetCategoryId(), form.getEventId()); - return OK; - } - - @RequestMapping(value = "/events/{eventName}/pending-payments") - public List> getPendingPayments(@PathVariable("eventName") String eventName, Principal principal) { - return eventManager.getPendingPayments(eventName, principal.getName()).stream().map(SerializablePair::fromPair).collect(Collectors.toList()); - } - - @RequestMapping(value = "/events/{eventName}/pending-payments/{reservationId}/confirm", method = POST) - public String confirmPayment(@PathVariable("eventName") String eventName, @PathVariable("reservationId") String reservationId, Principal principal) { - eventManager.confirmPayment(eventName, reservationId, principal.getName()); - return OK; - } - - @RequestMapping(value = "/events/{eventName}/pending-payments/{reservationId}", method = DELETE) - public String deletePendingPayment(@PathVariable("eventName") String eventName, @PathVariable("reservationId") String reservationId, Principal principal) { - eventManager.deletePendingOfflinePayment(eventName, reservationId, principal.getName()); - return OK; - } - - @RequestMapping(value = "/events/{eventName}/pending-payments/bulk-confirmation", method = POST) - public List> bulkConfirmation(@PathVariable("eventName") String eventName, - Principal principal, - @RequestParam("file") MultipartFile file) throws IOException { - - try(InputStreamReader isr = new InputStreamReader(file.getInputStream())) { - CSVReader reader = new CSVReader(isr); - String username = principal.getName(); - return reader.readAll().stream() - .map(line -> { - String reservationID = null; - try { - Validate.isTrue(line.length >= 2); - reservationID = line[0]; - eventManager.confirmPayment(eventName, reservationID, new BigDecimal(line[1]), username); - return Triple.of(Boolean.TRUE, reservationID, ""); - } catch (Exception e) { - return Triple.of(Boolean.FALSE, Optional.ofNullable(reservationID).orElse(""), e.getMessage()); - } - }) - .collect(Collectors.toList()); - } - } - - @RequestMapping(value = "/events/{eventName}/categories/{categoryId}/tickets/{ticketId}/toggle-locking", method = PUT) - public boolean toggleTicketLocking(@PathVariable("eventName") String eventName, - @PathVariable("categoryId") int categoryId, - @PathVariable("ticketId") int ticketId, - Principal principal) { - return eventManager.toggleTicketLocking(eventName, categoryId, ticketId, principal.getName()); - } - -} diff --git a/src/main/java/alfio/controller/api/LocationApiController.java b/src/main/java/alfio/controller/api/LocationApiController.java deleted file mode 100644 index 610086800a..0000000000 --- a/src/main/java/alfio/controller/api/LocationApiController.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * This file is part of alf.io. - * - * alf.io is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * alf.io is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with alf.io. If not, see . - */ -package alfio.controller.api; - -import alfio.manager.location.LocationManager; -import alfio.manager.location.LocationNotFound; -import alfio.manager.system.ConfigurationManager; -import alfio.model.modification.support.LocationDescriptor; -import org.apache.commons.lang3.Validate; -import org.apache.commons.lang3.tuple.Pair; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; - -import java.util.Optional; -import java.util.TimeZone; - -import static alfio.model.system.ConfigurationKeys.MAPS_CLIENT_API_KEY; -import static org.springframework.web.bind.annotation.RequestMethod.GET; - -@RestController -@RequestMapping("/admin/api") -public class LocationApiController { - - private final LocationManager locationManager; - private final ConfigurationManager configurationManager; - - @Autowired - public LocationApiController(LocationManager locationManager, ConfigurationManager configurationManager) { - this.locationManager = locationManager; - this.configurationManager = configurationManager; - } - - @ExceptionHandler(Exception.class) - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - public String unhandledException(Exception e) { - return e.getMessage(); - } - - @ExceptionHandler(LocationNotFound.class) - @ResponseStatus(HttpStatus.NOT_FOUND) - public String locationException(Exception e) { - return e.getMessage(); - } - - @RequestMapping(value = "/location/geo", method = GET) - public LocationDescriptor geocodeAddress(@RequestParam("location") String address) { - Pair coordinates = locationManager.geocode(address); - TimeZone timezone = locationManager.getTimezone(coordinates); - return LocationDescriptor.fromGeoData(coordinates, timezone, getMapsClientApiKey()); - } - - private Optional getMapsClientApiKey() { - return configurationManager.getStringConfigValue(MAPS_CLIENT_API_KEY); - } - - @RequestMapping(value = "/location/map", method = GET) - public String getMapUrl(@RequestParam("lat") String latitude, @RequestParam("long") String longitude) { - Validate.notBlank(latitude); - Validate.notBlank(longitude); - LocationDescriptor descriptor = LocationDescriptor.fromGeoData(Pair.of(latitude, longitude), TimeZone.getDefault(), getMapsClientApiKey()); - return descriptor.getMapUrl(); - } -} diff --git a/src/main/java/alfio/controller/api/PromoCodeDiscountApiController.java b/src/main/java/alfio/controller/api/PromoCodeDiscountApiController.java deleted file mode 100644 index dd359bfce0..0000000000 --- a/src/main/java/alfio/controller/api/PromoCodeDiscountApiController.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * This file is part of alf.io. - * - * alf.io is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * alf.io is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with alf.io. If not, see . - */ -package alfio.controller.api; - -import static org.springframework.web.bind.annotation.RequestMethod.*; - -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.List; -import java.util.TimeZone; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import alfio.manager.EventManager; -import alfio.model.Event; -import alfio.model.PromoCodeDiscount; -import alfio.model.PromoCodeDiscount.DiscountType; -import alfio.model.modification.PromoCodeDiscountModification; -import alfio.model.modification.PromoCodeDiscountWithFormattedTime; -import alfio.repository.EventRepository; -import alfio.repository.PromoCodeDiscountRepository; - -@RestController -@RequestMapping("/admin/api") -public class PromoCodeDiscountApiController { - - private final EventRepository eventRepository; - private final PromoCodeDiscountRepository promoCodeRepository; - private final EventManager eventManager; - - @Autowired - public PromoCodeDiscountApiController(EventRepository eventRepository, PromoCodeDiscountRepository promoCodeRepository, EventManager eventManager) { - this.eventRepository = eventRepository; - this.promoCodeRepository = promoCodeRepository; - this.eventManager = eventManager; - } - - @RequestMapping(value = "/events/{eventId}/promo-code", method = POST) - public void addPromoCode(@PathVariable("eventId") int eventId, @RequestBody PromoCodeDiscountModification promoCode) { - Event event = eventRepository.findById(eventId); - ZoneId zoneId = TimeZone.getTimeZone(event.getTimeZone()).toZoneId(); - - int discount = promoCode.getDiscountType() == DiscountType.FIXED_AMOUNT ? promoCode.getDiscountInCents() : promoCode.getDiscountAsPercent(); - - eventManager.addPromoCode(promoCode.getPromoCode(), eventId, promoCode.getStart().toZonedDateTime(zoneId), - promoCode.getEnd().toZonedDateTime(zoneId), discount, promoCode.getDiscountType()); - } - - @RequestMapping(value = "/events/{eventId}/promo-code", method = GET) - public List listPromoCodeInEvent(@PathVariable("eventId") int eventId) { - return eventManager.findPromoCodesInEvent(eventId); - } - - @RequestMapping(value = "/events/{eventId}/promo-code/{promoCodeName}", method = DELETE) - public void removePromoCode(@PathVariable("eventId") int eventId, @PathVariable("promoCodeName") String promoCodeName) { - PromoCodeDiscount promoCode = promoCodeRepository.findPromoCodeInEvent(eventId, promoCodeName); - eventManager.deletePromoCode(promoCode.getId()); - } - - @RequestMapping(value = "/events/{eventId}/promo-code/{promoCodeName}/disable", method = POST) - public void disablePromoCode(@PathVariable("eventId") int eventId, @PathVariable("promoCodeName") String promoCodeName) { - promoCodeRepository.updateEnd(eventId, promoCodeName, ZonedDateTime.now()); - } - - @RequestMapping(value = "/events/{eventId}/promo-code/{promoCodeName}/count-use", method = GET) - public int countPromoCodeUse(@PathVariable("eventId") int eventId, @PathVariable("promoCodeName") String promoCodeName) { - return promoCodeRepository.countAppliedPromoCode(eventId, promoCodeName); - } -} diff --git a/src/main/java/alfio/controller/api/SerializablePair.java b/src/main/java/alfio/controller/api/SerializablePair.java deleted file mode 100644 index c2257a3335..0000000000 --- a/src/main/java/alfio/controller/api/SerializablePair.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * This file is part of alf.io. - * - * alf.io is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * alf.io is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with alf.io. If not, see . - */ -package alfio.controller.api; - -import lombok.experimental.Delegate; -import org.apache.commons.lang3.tuple.Pair; - -final class SerializablePair { - @Delegate - private final Pair pair; - - public SerializablePair(Pair pair) { - this.pair = pair; - } - - static SerializablePair fromPair(Pair pair) { - return new SerializablePair<>(pair); - } -} diff --git a/src/main/java/alfio/controller/api/SettingsApiController.java b/src/main/java/alfio/controller/api/SettingsApiController.java deleted file mode 100644 index 7f298a3427..0000000000 --- a/src/main/java/alfio/controller/api/SettingsApiController.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * This file is part of alf.io. - * - * alf.io is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * alf.io is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with alf.io. If not, see . - */ -package alfio.controller.api; - -import alfio.manager.system.ConfigurationManager; -import alfio.model.modification.ConfigurationModification; -import alfio.model.system.Configuration; -import alfio.model.system.ConfigurationKeys; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.stream.Collectors; - -import static org.springframework.web.bind.annotation.RequestMethod.*; - -@RestController -@RequestMapping("/admin/api") -public class SettingsApiController { - - private final ConfigurationManager configurationManager; - - @Autowired - public SettingsApiController(ConfigurationManager configurationManager) { - this.configurationManager = configurationManager; - } - - @RequestMapping(value = "/configuration/load", method = GET) - public Map> loadConfiguration() { - return configurationManager.loadAllIncludingMissing(); - } - - @RequestMapping(value = "/configuration/update", method = POST) - public Map> updateConfiguration(@RequestBody ConfigurationModification configuration) { - configurationManager.save(ConfigurationKeys.fromValue(configuration.getKey()), configuration.getValue()); - return loadConfiguration(); - } - - @RequestMapping(value = "/configuration/update-bulk", method = POST) - public Map> updateConfiguration(@RequestBody Map> input) { - Objects.requireNonNull(input); - List list = input.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); - configurationManager.saveAll(list); - return loadConfiguration(); - } - - @RequestMapping(value = "/configuration/key/{key}", method = DELETE) - public boolean deleteKey(@PathVariable("key") String key) { - configurationManager.deleteKey(key); - return true; - } -} diff --git a/src/main/java/alfio/controller/api/SpecialPriceApiController.java b/src/main/java/alfio/controller/api/SpecialPriceApiController.java deleted file mode 100644 index 16e3ff8aa1..0000000000 --- a/src/main/java/alfio/controller/api/SpecialPriceApiController.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * This file is part of alf.io. - * - * alf.io is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * alf.io is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with alf.io. If not, see . - */ -package alfio.controller.api; - -import alfio.manager.SpecialPriceManager; -import alfio.model.modification.SendCodeModification; -import com.opencsv.CSVReader; -import lombok.extern.log4j.Log4j2; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.Validate; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.security.Principal; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; - -@RestController -@RequestMapping("/admin/api") -@Log4j2 -public class SpecialPriceApiController { - - private final SpecialPriceManager specialPriceManager; - - @Autowired - public SpecialPriceApiController(SpecialPriceManager specialPriceManager) { - this.specialPriceManager = specialPriceManager; - } - - @ExceptionHandler - @ResponseBody - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - public String handleExceptions(Exception e) { - if(!IllegalArgumentException.class.isInstance(e)) { - log.error("Unexpected exception in SpecialPriceApiController", e); - } - return e.toString(); - } - - @RequestMapping("/events/{eventName}/categories/{categoryId}/link-codes") - public List linkAssigneeToCodes(@PathVariable("eventName") String eventName, - @PathVariable("categoryId") int categoryId, - @RequestParam("file") MultipartFile file, - Principal principal) throws IOException { - - Validate.isTrue(StringUtils.isNotEmpty(eventName)); - try(InputStreamReader isr = new InputStreamReader(file.getInputStream())) { - CSVReader reader = new CSVReader(isr); - List content = reader.readAll().stream() - .map(line -> { - Validate.isTrue(line.length >= 4); - return new SendCodeModification(StringUtils.trimToNull(line[0]), line[1], line[2], line[3]); - }) - .collect(Collectors.toList()); - return specialPriceManager.linkAssigneeToCode(content, eventName, categoryId, principal.getName()); - } - } - - @RequestMapping("/events/{eventName}/categories/{categoryId}/send-codes") - public boolean sendCodes(@PathVariable("eventName") String eventName, - @PathVariable("categoryId") int categoryId, - @RequestBody List codes, - Principal principal) throws IOException { - - Validate.isTrue(StringUtils.isNotEmpty(eventName)); - Objects.requireNonNull(codes); - Validate.isTrue(!codes.isEmpty(), "Collection of codes cannot be empty"); - specialPriceManager.sendCodeToAssignee(codes, eventName, categoryId, principal.getName()); - return true; - } - -} diff --git a/src/main/java/alfio/controller/api/UsersApiController.java b/src/main/java/alfio/controller/api/UsersApiController.java deleted file mode 100644 index 906a922f72..0000000000 --- a/src/main/java/alfio/controller/api/UsersApiController.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - * This file is part of alf.io. - * - * alf.io is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * alf.io is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with alf.io. If not, see . - */ -package alfio.controller.api; - -import alfio.manager.user.UserManager; -import alfio.model.modification.OrganizationModification; -import alfio.model.modification.UserModification; -import alfio.model.user.Organization; -import alfio.model.user.User; -import alfio.model.user.UserWithPassword; -import alfio.util.ImageUtil; -import alfio.util.ValidationResult; -import lombok.Data; -import lombok.extern.log4j.Log4j2; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.security.Principal; -import java.util.List; -import java.util.Optional; - -import static org.springframework.web.bind.annotation.RequestMethod.*; - -@RestController -@RequestMapping("/admin/api") -@Log4j2 -public class UsersApiController { - - private static final String OK = "OK"; - private static final String USER_QR_CODE_KEY = "USER_QR_CODE"; - private final UserManager userManager; - - @Autowired - public UsersApiController(UserManager userManager) { - this.userManager = userManager; - } - - @ExceptionHandler(Exception.class) - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - @ResponseBody - public String unhandledException(Exception e) { - log.error("unhandled exception", e); - return e.getMessage(); - } - - @RequestMapping(value = "/organizations", method = GET) - @ResponseStatus(HttpStatus.OK) - public List getAllOrganizations(Principal principal) { - return userManager.findUserOrganizations(principal.getName()); - } - - @RequestMapping(value = "/organizations/{id}", method = GET) - public Organization getOrganization(@PathVariable("id") int id, Principal principal) { - return userManager.findOrganizationById(id, principal.getName()); - } - - @RequestMapping(value = "/users", method = GET) - public List getAllUsers(Principal principal) { - return userManager.findAllUsers(principal.getName()); - } - - - @RequestMapping(value = "/organizations/new", method = POST) - public String insertOrganization(@RequestBody OrganizationModification om) { - userManager.createOrganization(om.getName(), om.getDescription(), om.getEmail()); - return OK; - } - - @RequestMapping(value = "/organizations/check", method = POST) - public ValidationResult validateOrganization(@RequestBody OrganizationModification om) { - return userManager.validateOrganization(om.getId(), om.getName(), om.getEmail(), om.getDescription()); - } - - @RequestMapping(value = "/users/check", method = POST) - public ValidationResult validateUser(@RequestBody UserModification userModification) { - return userManager.validateUser(userModification.getId(), userModification.getUsername(), - userModification.getOrganizationId(), userModification.getFirstName(), - userModification.getLastName(), userModification.getEmailAddress()); - } - - @RequestMapping(value = "/users/edit", method = POST) - public String editUser(@RequestBody UserModification userModification) { - userManager.editUser(userModification.getId(), userModification.getOrganizationId(), userModification.getUsername(), userModification.getFirstName(), userModification.getLastName(), userModification.getEmailAddress()); - return OK; - } - - @RequestMapping(value = "/users/new", method = POST) - public UserWithPassword insertUser(@RequestBody UserModification userModification, HttpSession session) { - UserWithPassword userWithPassword = userManager.insertUser(userModification.getOrganizationId(), userModification.getUsername(), userModification.getFirstName(), userModification.getLastName(), userModification.getEmailAddress()); - storePasswordImage(session, userWithPassword); - return userWithPassword; - } - - @RequestMapping(value = "/users/{identifier}.png", method = GET) - public void loadUserImage(@PathVariable("identifier") String identifier, HttpSession session, HttpServletResponse response) throws IOException { - Optional optional = Optional.ofNullable((ImageDescriptor) session.getAttribute(USER_QR_CODE_KEY)) - .filter(a -> identifier.equals(a.getUserIdentifier())); - if(!optional.isPresent()) { - response.setStatus(HttpServletResponse.SC_NOT_FOUND); - return; - } - ImageDescriptor imageDescriptor = optional.get(); - response.setContentType("image/png"); - response.getOutputStream().write(imageDescriptor.getImage()); - } - - - @RequestMapping(value = "/users/{id}", method = DELETE) - public String deleteUser(@PathVariable("id") int userId, Principal principal) { - userManager.deleteUser(userId, principal.getName()); - return OK; - } - - @RequestMapping(value = "/users/{id}", method = GET) - public UserModification loadUser(@PathVariable("id") int userId) { - User user = userManager.findUser(userId); - List userOrganizations = userManager.findUserOrganizations(user); - return new UserModification(user.getId(), userOrganizations.get(0).getId(), user.getUsername(), user.getFirstName(), user.getLastName(), user.getEmailAddress()); - } - - @RequestMapping(value = "/users/{id}/reset-password", method = PUT) - public UserWithPassword resetPassword(@PathVariable("id") int userId, HttpSession session) { - UserWithPassword userWithPassword = userManager.resetPassword(userId); - storePasswordImage(session, userWithPassword); - return userWithPassword; - } - - private void storePasswordImage(HttpSession session, UserWithPassword userWithPassword) { - session.setAttribute(USER_QR_CODE_KEY, new ImageDescriptor(userWithPassword.getUniqueId(), ImageUtil.createQRCode(userWithPassword.getPassword()))); - } - - @Data - private final class ImageDescriptor { - private final String userIdentifier; - private final byte[] image; - } -}