@Override @PreAuthorize("hasAuthority('admin')") public ResponseEntity<Object> globalsettingsHolidaysYearPost( @Min(2000) @Max(2100)@ApiParam(value = "",required=true ) @PathVariable("year") Integer year, @ApiParam(value = "The holidays to set" ,required=true ) @Valid @RequestBody Holidays holidays) throws ApiException { try { globalsettingsService.setHolidays(year, holidays); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } catch (OptimisticLockException ex) { try { Holidays lastHolidays = globalsettingsService.getHolidays(year); throw new ConcurrentModificationException(409, "Concurrent modification error.", lastHolidays); } catch (ApiException ex1) { Logger.getLogger(SettingsApiController.class.getName()).log(Level.SEVERE, null, ex1); throw new ApiException(500, "Concurrent modification exception: internal error"); } } }
@PUT @Path("/{id:[0-9][0-9]*}") @Consumes("application/json") public Response update(@PathParam("id") Long id, Person entity) { if (entity == null) { return Response.status(Status.BAD_REQUEST).build(); } if (id == null) { return Response.status(Status.BAD_REQUEST).build(); } if (!id.equals(entity.getId())) { return Response.status(Status.CONFLICT).entity(entity).build(); } if (em.find(Person.class, id) == null) { return Response.status(Status.NOT_FOUND).build(); } try { entity = em.merge(entity); } catch (OptimisticLockException e) { return Response.status(Response.Status.CONFLICT) .entity(e.getEntity()).build(); } return Response.noContent().build(); }
@Test public void test_RollbackExceptionHandling_rollbackafterthrown() throws Exception { TransactionManager tm = mockTm(); when(tm.getStatus()).thenReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE, Status.STATUS_MARKED_ROLLBACK); doThrow(new RollbackException().initCause(new OptimisticLockException())).when(tm).commit(); XAJpaTemplate tx = new XAJpaTemplate(emSupplier, tm, coordinator); try { tx.tx(TransactionType.Required, new EmConsumer() { public void accept(EntityManager em) { em.persist(new Object()); } }); } catch (RuntimeException e) { // this is ok } verify(tm, times(5)).getStatus(); verify(tm, times(1)).commit(); verify(tm, times(1)).rollback(); }
@Override @PreAuthorize("hasAuthority('hungry')") @Transactional public ResponseEntity<Object> settingsPut(@ApiParam(value = "User data" ,required=true ) @RequestBody Settings upUser, Errors errors) throws ApiException{ if (errors.hasErrors()) return new ResponseEntity<>(HttpStatus.BAD_REQUEST); try { settingsService.settingsPut(upUser); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } catch (OptimisticLockException ex) { try { User user = settingsService.settingsGet(); throw new ConcurrentModificationException(409, "Concurrent modification error.", user); } catch (ApiException ex1) { Logger.getLogger(SettingsApiController.class.getName()).log(Level.SEVERE, null, ex1); throw new ApiException(500, "Concurrent modification exception: internal error"); } } }
@Override @PreAuthorize("hasAuthority('admin')") @Transactional public ResponseEntity<Object> globalsettingsPut(@ApiParam(value = "The global settings to be updated" ,required=true ) @RequestBody GlobalSettings settings) throws ApiException{ try { globalsettingsService.globalsettingsPut(settings); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } catch (OptimisticLockException ex) { try { GlobalSettings globalSettings = globalsettingsService.globalsettingsGet(); throw new ConcurrentModificationException(409, "Concurrent modification error.", globalSettings); } catch (ApiException ex1) { Logger.getLogger(SettingsApiController.class.getName()).log(Level.SEVERE, null, ex1); throw new ApiException(500, "Concurrent modification exception: internal error"); } } }
/** * @update. Chef updates the daily menu */ @Override @PreAuthorize("hasAuthority('chef')") @Transactional public ResponseEntity<Object> dailyMenusIdPut(@ApiParam(value = "",required=true ) @PathVariable("id") String id, @ApiParam(value = "The daily menu to be updated" ,required=true ) @RequestBody DailyMenuEdit dailyMenu) throws ApiException, ConcurrentModificationException, ConcurrentDeletionException { Long dailyMenusId = Long.parseLong(id); // id (DTO) from the getDailyMenuChef he wants to insert foods try { //dailyMenuService.dailyMenusIdPut(dailyMenusId, dailyMenu); /**** HttpStatus.OK ****/ return new ResponseEntity<>( dailyMenuService.dailyMenusIdPut(dailyMenusId, dailyMenu), HttpStatus.OK); /**** HttpStatus.OK ****/ } catch (OptimisticLockException ex) { Logger.getLogger(DailyMenusApiController.class.getName()).log(Level.SEVERE, null, ex); throw new ApiException(500, "Concurrent modification exception: internal error"); } }
@Override @PreAuthorize("hasAuthority('admin')") public ResponseEntity<Object> usersIdPut(@ApiParam(value = "", required = true) @PathVariable("id") Long id, @ApiParam(value = "The user data to be updated", required = true) @Valid @RequestBody UserSettings user, Errors errors) throws ApiException, Exception { if (errors.hasErrors()) {//Check for validation error from UserSettings class(package:model) Error error = new Error(); error.setError("400"); error.setMessage("Validation Failed"); System.out.println("" + errors.getAllErrors()); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } try { //Call method for update user from class UsersService. userService.usersIdPut(user, id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } catch (OptimisticLockException ex) { try { User newUserVersion = userService.userIdGet(id); throw new ConcurrentModificationException(409, "Concurrent modification error", newUserVersion); } catch (ApiException ex1){ Logger.getLogger(UsersApiController.class.getName()).log(Level.SEVERE, null, ex1); throw new ApiException(500, "Concurrent modification exception: internal error"); } } }
@Override public void updateAfnemerindicatieBlob(final long persoonId, final Long lockVersiePersoon, final Long afnemerindicatieLockVersie) throws BlobException { final List<PersoonAfnemerindicatie> afnemerindicatiesNaToevoegen = afnemerindicatieRepository.haalAfnemerindicatiesOp(persoonId); final AfnemerindicatiesBlob afnemerindicatiesBlob = Blobber.maakBlob(afnemerindicatiesNaToevoegen); LOGGER.info("Blobify persoon:{}", persoonId); final byte[] afnemerindicatiesBlobBytes = Blobber.toJsonBytes(afnemerindicatiesBlob); //lockversieafnemerindicatiege = null uit initiele vulling of nog geen afnemerindicatie aanwezig final String sql = "UPDATE kern.perscache pc " + "SET lockversieafnemerindicatiege = CASE WHEN lockversieafnemerindicatiege IS NOT NULL THEN lockversieafnemerindicatiege + 1 ELSE 1 END, " + "afnemerindicatiegegevens = :afnemerindicatiegegevens " + "WHERE (pc.lockversieafnemerindicatiege = :lockversieAfnemerindicatie OR pc.lockversieafnemerindicatiege is null) " + "AND pc.pers = :persoonId " + "AND EXISTS " + "(SELECT 1 FROM kern.pers p WHERE p.id = pc.pers AND p.lockversie = :persoonLock )"; final NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(masterDataSource); final Map<String, Object> parameters = new HashMap<>(); parameters.put("afnemerindicatiegegevens", afnemerindicatiesBlobBytes); parameters.put("lockversieAfnemerindicatie", afnemerindicatieLockVersie); parameters.put("persoonId", persoonId); parameters.put("persoonLock", lockVersiePersoon); final int rowsUpdated = jdbcTemplate.update(sql, parameters); if (rowsUpdated != 1) { throw new OptimisticLockException("PersoonCache is ondertussen gewijzigd."); } }
@Override public void verwijderAfnemerindicatie(final long persoonId, final short partijId, final int leveringsautorisatieId, final int dienstIdVerval) { final PersoonAfnemerindicatie persoonAfnemerindicatieVoorOpslag = zoekAfnemerindicatie(persoonId, partijId, leveringsautorisatieId); if (persoonAfnemerindicatieVoorOpslag == null || !persoonAfnemerindicatieVoorOpslag.isActueelEnGeldig()) { final String foutMelding = String.format("Het verwijderen van de afnemerindicatie is mislukt, er is geen afnemerindicatie" + " aangetroffen met deze gegevens: persoonId %d, leveringsautorisatieId %s, partijCode %d", persoonId, leveringsautorisatieId, partijId); throw new OptimisticLockException(foutMelding); } persoonAfnemerindicatieVoorOpslag.setActueelEnGeldig(false); //zoek his record dat moet vervallen. PersoonAfnemerindicatieHistorie his = null; for (PersoonAfnemerindicatieHistorie persoonAfnemerindicatieHistorie : persoonAfnemerindicatieVoorOpslag.getPersoonAfnemerindicatieHistorieSet()) { if (!persoonAfnemerindicatieHistorie.isVervallen()) { his = persoonAfnemerindicatieHistorie; his.setDienstVerval(entityManager.getReference(Dienst.class, dienstIdVerval)); his.setDatumTijdVerval(new Timestamp(System.currentTimeMillis())); break; } } Assert.notNull(his, "Niet vervallen Afnemerindicatie hisrecord niet gevonden"); entityManager.persist(persoonAfnemerindicatieVoorOpslag); }
@Override public CompletionStage<Result> onServerError(Http.RequestHeader request, Throwable exception) { return CompletableFuture.supplyAsync(() -> { Throwable cause = exception.getCause(); String errorMessage = cause == null ? exception.getMessage() : cause.getMessage(); Logger.error("onServerError: URL: {}, msg: {}", request.uri(), errorMessage); exception.printStackTrace(); if (cause != null) { if (cause instanceof MalformedDataException) { return Results.badRequest(Json.toJson(errorMessage)); } if (cause instanceof IllegalArgumentException) { return Results.badRequest(Json.toJson(new ApiError(errorMessage))); } if (cause instanceof OptimisticLockException) { return Results.badRequest("sitnet_error_data_has_changed"); } } return Results.internalServerError(Json.toJson(new ApiError(errorMessage))); }); }
public void resetSequence(String seqName) { int tries = 0; final int maxTries = 100; do { try { sequenceEngine.resetSequenceInNewTransaction(seqName); break; } catch (EJBException e) { if (e.getCausedByException() instanceof OptimisticLockException) { log.warn("OptimisticLockException occured (" + tries + "). try again..."); tries++; } else { log.error("EJBException occured. ", e); throw e; } } } while (tries < maxTries); if (tries >= maxTries) { log.error("Cannot get Sequence. Give it up after " + maxTries + " tries"); final String msg = "Cannot get Sequence. Exceeded maxTries=" + maxTries + " attempts"; throw new EJBException(msg); } }
@Test(expected=OptimisticLockException.class) @Transactional public void optimisticLockingWorks() { Employee employeeInVacation = entityManager.find(Employee.class, employeeId); entityManager.detach(employeeInVacation); // sent to Tahiti employeeInVacation.setName("new Name"); // meanwhile, another client changes the same entity txUtil.executeInSeparateTransaction(() -> { Employee employee2 = entityManager.find(Employee.class, employeeId); System.out.println("Before 1st change: @Version in DB = " + employee2.getVersion()); employee2.setName("concurrent name"); }); System.out.println("Before 2nd change"); System.out.println("@Version in DB = " + entityManager.find(Employee.class, employeeId).getVersion()); System.out.println("@Version in incoming data = " + employeeInVacation.getVersion()); entityManager.merge(employeeInVacation); // try to re-attach }
public Prediction store(Prediction prediction) throws GameLockedException { final GameLockedException gameLockedException = new GameLockedException( "The game " + prediction.getForGame().getHomeTeam() + " - " + prediction.getForGame().getAwayTeam() + " was locked before you submitted your proposal."); try { if (entityManager.merge(prediction.getForGame()).isLocked()) { throw gameLockedException; } } catch (OptimisticLockException ole) { throw gameLockedException; } if (prediction.getId() == null) { Game mergedGame = entityManager.merge(prediction.getForGame()); mergedGame.getPredictions().add(prediction); prediction.setForGame(mergedGame); User mergedUser = entityManager.merge(prediction.getByUser()); mergedUser.getPredictions().add(prediction); prediction.setByUser(mergedUser); return prediction; } else { return entityManager.merge(prediction); } }
@Authentication({User.Role.ADMIN}) public static Result delete(long i) { Drone drone = Drone.FIND.byId(i); if (drone == null) { return notFound(); } boolean updated = false; while (!updated) { drone.refresh(); if (drone.getStatus() == Drone.Status.FLYING) { return forbidden("Cannot remove drone while flying."); } try { drone.delete(); updated = true; } catch (OptimisticLockException ex) { updated = false; } } Fleet.getFleet().stopCommander(drone); return ok(ControllerHelper.EMPTY_RESULT); }
@Test public void testRetry() throws Exception { when(mockLifecycleRepository.save(any(LifecycleEntity.class))) // first time throw an exception .thenThrow(new ObjectOptimisticLockingFailureException(ApplicationEntity.class, "foobar")) // second time throw another exception .thenThrow(new OptimisticLockException("Oops")) // third time thrwo another exception .thenThrow(new DataIntegrityViolationException("Hoppla")) // Last time succeed. .thenReturn(lifecycle); assertThat(service.saveLifecycle(application, version, lifecycle)).isSameAs(lifecycle); verify(mockApplicationRepository, times(4)).findByName(eq("foobar")); verify(mockVersionRepository, times(4)).findByName(eq("1.0")); verify(mockLifecycleRepository, times(4)).save(any(LifecycleEntity.class)); }
public int refreshInventory( String sku , String color , String size , int quantity ) { InventoryPK pk = new InventoryPK( sku , color , size ); Inventory inventory = em.find( Inventory.class , pk , LockModeType.OPTIMISTIC ); int amount = inventory.getInventory(); amount = amount + quantity; inventory.setInventory( amount ); try { em.merge( inventory ); } catch ( OptimisticLockException e ) { return -9999; } return quantity; }
@PUT @Path("{id}") @Consumes({MediaType.APPLICATION_JSON}) public Response edit(@PathParam("id") Integer id, Guest entity) { if (entity == null) { return Response.status(Status.BAD_REQUEST).build(); } if (!id.equals(entity.getId())) { return Response.status(Status.CONFLICT).entity(entity).build(); } if (guestService.count(Guest.class) == 0) { return Response.status(Status.NOT_FOUND).build(); } try { guestService.edit(entity); } catch (OptimisticLockException e) { return Response.status(Status.CONFLICT).entity(e.getEntity()).build(); } return Response.noContent().build(); }
@PUT @Path("{id}") @Consumes({MediaType.APPLICATION_JSON}) public Response edit(@PathParam("id") Integer id, Flight entity) { if (entity == null) { return Response.status(Status.BAD_REQUEST).build(); } if (!id.equals(entity.getId())) { return Response.status(Status.CONFLICT).entity(entity).build(); } if (flightService.count(Flight.class) == 0) { return Response.status(Status.NOT_FOUND).build(); } try { flightService.edit(entity); } catch (OptimisticLockException e) { return Response.status(Status.CONFLICT).entity(e.getEntity()).build(); } return Response.noContent().build(); }
/** * Thread1: currently modify employee will lead to OptimisticLockException. * Do not need lock it explicitly. */ @Transactional public void doModify1(){ Employee employee = null; try{ lock.lock(); employee = em.find(Employee.class, 1); System.out.println(" ### thread 1 query employee"); write2Condition.signal(); write1Condition.await(); Thread.sleep(1000); employee.setName("new1_employee"); employee.setSalary(employee.getSalary()+33); System.out.println(" ### thread 1 modify employee"); } catch (InterruptedException e) { e.printStackTrace(); } catch (OptimisticLockException lockException){ em.persist(employee); } finally{ lock.unlock(); } }
@PUT @Path("/{id:[0-9][0-9]*}") @Consumes("application/json") public Response update(@PathParam("id") Long id, Speaker entity) { if (entity == null) { return Response.status(Status.BAD_REQUEST).build(); } if (id == null) { return Response.status(Status.BAD_REQUEST).build(); } if (!id.equals(entity.getId())) { return Response.status(Status.CONFLICT).entity(entity).build(); } if (em.find(Speaker.class, id) == null) { return Response.status(Status.NOT_FOUND).build(); } try { entity = em.merge(entity); } catch (OptimisticLockException e) { return Response.status(Response.Status.CONFLICT) .entity(e.getEntity()).build(); } return Response.noContent().build(); }
@Override public Long saveHomeScreen(HomeScreen homeScreen) { if (homeScreen == null) { return null; } if (homeScreen.getAlias() != null) { homeScreen.setAlias(homeScreen.getAlias().trim()); } for (HomeTool ht : homeScreen.getHomeTools()) { ht.setHomeScreen(homeScreen); } try { if (homeScreen.getHomeScreenId() == null) { entityManager.persist(homeScreen); } else { deleteHomeToolsByHomeScreenId(homeScreen.getHomeScreenId()); entityManager.merge(homeScreen); } } catch (OptimisticLockException oe) { return null; } return homeScreen.getHomeScreenId(); }
@Override public Long saveNotification(Notification notification) { if (notification == null) { return null; } try { if (notification.getNotificationId() == null) { entityManager.persist(notification); } else { entityManager.merge(notification); } } catch (OptimisticLockException oe) { return null; } return notification.getNotificationId(); }
@Override public Long saveUserNotification(UserNotification userNotification) { if (userNotification == null) { return null; } try { if (userNotification.getUserNotificationId() == null) { entityManager.persist(userNotification); } else { entityManager.merge(userNotification); } } catch (OptimisticLockException oe) { return null; } return userNotification.getUserNotificationId(); }
public Long saveXsl(Xsl xsl) { if (xsl == null) { return null; } try { if (xsl.getValue() != null) { xsl.setValue(xsl.getValue().trim()); } if (xsl.getXslId() == null) { entityManager.persist(xsl); } else { entityManager.merge(xsl); } } catch (OptimisticLockException ole) { LOG.error(ole.getLocalizedMessage(), ole); return null; } return xsl.getXslId(); }
@Override @Transactional public NewsSource save(NewsSource newsSource) { if (newsSource == null) { return null; } try { if (newsSource.getId() == null) { entityManager.persist(newsSource); } else { entityManager.merge(newsSource); } } catch (OptimisticLockException oe) { return null; } return newsSource; }
@Override @Transactional public Long saveTour(Tour tour) { if (tour == null) { return null; } if (tour.getName() != null) { tour.setName(tour.getName().trim()); } if (tour.getDescription() != null) { tour.setDescription(tour.getDescription().trim()); } try { if (tour.getTourId() == null) { entityManager.persist(tour); } else { deletePoisByTourId(tour.getTourId()); deletePermissionsByTourId(tour.getTourId()); entityManager.merge(tour); } } catch (OptimisticLockException oe) { return null; } return tour.getTourId(); }
@Override @Transactional public Long savePoi(POI poi) { if (poi == null) { return null; } if (poi.getName() != null) { poi.setName(poi.getName().trim()); } if (poi.getDescription() != null) { poi.setDescription(poi.getDescription().trim()); } try { if (poi.getPoiId() == null) { entityManager.persist(poi); } else { deletePermissionsByPoiId(poi.getPoiId()); deletePhoneNumbersAndEmailAddressesByPoiId(poi.getPoiId()); entityManager.merge(poi); } } catch (OptimisticLockException oe) { return null; } return poi.getPoiId(); }
public Long saveConfigParam(ConfigParam configParam) { if (configParam == null) { return null; } if (configParam.getName() != null) { configParam.setName(configParam.getName().trim()); } if (configParam.getValue() != null) { configParam.setValue(configParam.getValue().trim()); } try { if (configParam.getConfigParamId() == null) { entityManager.persist(configParam); } else { entityManager.merge(configParam); } } catch (OptimisticLockException oe) { return null; } return configParam.getConfigParamId(); }
/** * This method typically commits one or more parent entities. If any of the * related children in the object graph are not marked for cascading then * they need to be explicitly included. * * @param <ENTITY> * @param entityManager * @param entities * @return {@link List} * @throws JpaOptimisticLockException */ public <ENTITY> List<ENTITY> transactCreatesOrUpdates(final EntityManager entityManager, final JpcBaseDE... entities) throws OptimisticLockException { final List<ENTITY> resultList = new ArrayList<ENTITY>(); entityManager.getTransaction().begin(); for (final JpcBaseDE entity : entities) { final ENTITY tempEntity = mergeEntity(entity, entityManager); resultList.add(tempEntity); } transactCommit(entityManager); return resultList; }
/** * This method typically deletes one or more parent entities. If any of the * related children in the object graph are not marked for cascading then * they need to be explicitly included. * * @param entityManager * @param entities * @throws JpaOptimisticLockException */ public void transactDelete(final EntityManager entityManager, final JpcBaseDE... entities) throws OptimisticLockException { final String methodName = "transactDelete"; try { entityManager.getTransaction().begin(); for (JpcBaseDE entityInstance : entities) { entityInstance = mergeEntity(entityInstance, entityManager); entityManager.remove(entityInstance); } } catch (final Exception e) { throw new PersistenceException(new JpcBasicExceptionPO().setClassName(JpaTransactionBeanHelper.CLASS_NAME) .setMethodName(methodName).setMessage("Unable to delete the entities."), e); } transactCommit(entityManager); }
@PreAuthorize("hasAuthority('admin')") public ResponseEntity<Void> dailyMenusIdDelete(@ApiParam(value = "",required=true ) @PathVariable("id") Long id) throws ApiException { // return new ResponseEntity<Void>(HttpStatus.OK); try { dailyMenuService.dailyMenusIdDelete(id); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } catch (OptimisticLockException ex) { Logger.getLogger(DailyMenusApiController.class.getName()).log(Level.SEVERE, null, ex); throw new ApiException(500, "Concurrent modification exception: internal error"); } }
@Transactional @PreAuthorize("hasAuthority('chef')") public ResponseEntity<Message> foodsFoodIdPut(@ApiParam(value = "",required=true ) @PathVariable("foodId") Long foodId, @ApiParam(value = "The food to be updated" ,required=true ) @RequestBody EditedFood food, @ApiParam(value = "") @RequestParam(value = "clone", required = false) Boolean clone) throws ApiException, Exception { // '204': description: Food successfully updated NO_CONTENT // '400': description: Food couldn't have been updated BAD_REQUEST // '404': description: Food not found NOT_FOUND // '409': description: Concurrent modification error CONFLICT // '412': description: Food name already exists PRECONDITION_FAILED // 500: Internal server error Message response = new Message(); try { foodService.foodsFoodIdPut(foodId, food, clone); } catch (OptimisticLockException ex) { try { FoodEditable newFood = foodService.foodsFoodIdGet(foodId, "false"); throw new ConcurrentModificationException(409, "DB ConcurrentModificationException", newFood); } catch (ApiException ex1) { Logger.getLogger(OrdersApiController.class.getName()).log(Level.SEVERE, null, ex1); throw new ApiException(500, "Concurrent modification exception: internal error"); } } return new ResponseEntity<Message>(response,HttpStatus.NO_CONTENT); }
@Override @PreAuthorize("hasAuthority('hungry')") public ResponseEntity<Object> ordersIdPut(@ApiParam(value = "", required = true) @PathVariable("id") Long id, @ApiParam(value = "") @RequestParam(value = "userid", required = false, defaultValue = "0") Long userid, @ApiParam(value = "The order items to modify") @RequestBody UpdateOrderItems updateOrderItems, Errors errors) throws ApiException { if (errors.hasErrors()) { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } try { //OrderUpdate orderUpdate = ordersService.ordersIdPut(id, updateOrderItems, userid); return new ResponseEntity<>(ordersService.ordersIdPut(id, updateOrderItems, userid), HttpStatus.OK); } catch (OptimisticLockException ex) { try { DailyOrder dailyOrder = ordersService.ordersIdGet(id,updateOrderItems.getDailyMenuId(),updateOrderItems.getDailyMenuVersion(), updateOrderItems.getDailyMenuDate(), userid ); throw new ConcurrentModificationException(409, "Concurrent modification error.", dailyOrder); } catch (ConcurrentDeletionException e) { int exCode = e.getCode(); return new ResponseEntity<>(e.getResponseDTO() ,HttpStatus.valueOf(exCode)); } catch (ApiException ex1) { Logger.getLogger(OrdersApiController.class.getName()).log(Level.SEVERE, null, ex1); throw new ApiException(500, "Concurrent modification exception: internal error"); } } }
@Test public void mapEJBExceptions_validateCause() throws Exception { EJBException e = new EJBException(new OptimisticLockException()); Exception mappedException = mapper.mapToBesException(e); assertTrue(mappedException instanceof ConcurrentModificationException); assertEquals(null, mappedException.getCause()); }
private boolean canMapToConcurrentModificationException( PersistenceException pe) { if (pe instanceof EntityExistsException || pe instanceof OptimisticLockException) { return true; } return false; }
@Override public ErrorResponse toErrorResponse(OptimisticLockException cve) { HashMap<String, Object> meta = new HashMap<>(); meta.put(META_TYPE_KEY, JPA_OPTIMISTIC_LOCK_EXCEPTION_TYPE); ErrorData error = ErrorData.builder().setMeta(meta).setDetail(cve.getMessage()).build(); return ErrorResponse.builder().setStatus(HttpStatus.CONFLICT_409).setSingleErrorData(error).build(); }
@Override public OptimisticLockException fromErrorResponse(ErrorResponse errorResponse) { Iterable<ErrorData> errors = errorResponse.getErrors(); ErrorData error = errors.iterator().next(); String msg = error.getDetail(); return new OptimisticLockException(msg); }
private void checkOptimisticLocking(Object entity, Resource resource) { MetaAttribute versionAttr = jpaMeta.getVersionAttribute(); if (versionAttr != null) { JsonNode versionNode = resource.getAttributes().get(versionAttr.getName()); if (versionNode != null) { Object requestVersion = context.getTypeParser().parse(versionNode.asText(), (Class) versionAttr.getType().getImplementationClass()); Object currentVersion = versionAttr.getValue(entity); if (!currentVersion.equals(requestVersion)) { throw new OptimisticLockException( resource.getId() + " changed from version " + requestVersion + " to " + currentVersion); } } } }