Java Code Examples for javax.persistence.OptimisticLockException

The following are top voted examples for showing how to use javax.persistence.OptimisticLockException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: yum   File: GlobalsettingsApiController.java   View source code 8 votes vote down vote up
@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");
        }
    }    
    
}
 
Example 2
Project: demo-ang2   File: PersonEndpoint.java   View source code 6 votes vote down vote up
@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();
}
 
Example 3
Project: aries-jpa   File: XAJpaTemplateTest.java   View source code 6 votes vote down vote up
@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();
}
 
Example 4
Project: yum   File: SettingsApiController.java   View source code 6 votes vote down vote up
@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");
        }
    }  

}
 
Example 5
Project: yum   File: GlobalsettingsApiController.java   View source code 6 votes vote down vote up
@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");
        }
    }

}
 
Example 6
Project: yum   File: DailyMenusApiController.java   View source code 6 votes vote down vote up
/**
 * @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");
    }     
}
 
Example 7
Project: yum   File: UsersApiController.java   View source code 6 votes vote down vote up
@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");
        }
    }
}
 
Example 8
Project: OperatieBRP   File: PersoonCacheJpaRepositoryImpl.java   View source code 6 votes vote down vote up
@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.");
    }
}
 
Example 9
Project: OperatieBRP   File: AfnemerindicatieJpaRepositoryImpl.java   View source code 6 votes vote down vote up
@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);
}
 
Example 10
Project: exam   File: SystemErrorHandler.java   View source code 6 votes vote down vote up
@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)));
    });
}
 
Example 11
Project: demo-ang2   File: PersonEndpoint.java   View source code 6 votes vote down vote up
@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();
}
 
Example 12
Project: myWMS   File: LOSSequenceGeneratorServiceBean.java   View source code 6 votes vote down vote up
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);
       }
}
 
Example 13
Project: training   File: MasterPlay.java   View source code 6 votes vote down vote up
@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
}
 
Example 14
Project: predcomposer   File: PredictionsService.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 15
Project: cros-core   File: DroneController.java   View source code 6 votes vote down vote up
@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);
}
 
Example 16
Project: fullstop   File: ApplicationLifecycleServiceImpl.java   View source code 6 votes vote down vote up
@Override
@Retryable(maxAttempts = 10, backoff = @Backoff(delay = 100, maxDelay = 500),
        include = {ObjectOptimisticLockingFailureException.class, OptimisticLockException.class, DataIntegrityViolationException.class})
@Transactional(REQUIRES_NEW)
public LifecycleEntity saveLifecycle(final ApplicationEntity applicationEntity, final VersionEntity versionEntity,
        final LifecycleEntity lifecycleToSave) {
    Assert.notNull(applicationEntity, "applicationEntity must not be null");
    Assert.notNull(versionEntity, "versionEntity must not be null");
    Assert.notNull(lifecycleToSave, "lifecycleToSave must not be null");

    ApplicationEntity applicationByName = applicationRepository.findByName(applicationEntity.getName());
    VersionEntity versionByName = versionRepository.findByName(versionEntity.getName());

    if (applicationByName == null) {
        applicationByName = applicationRepository.save(applicationEntity);
    }

    if (versionByName == null) {
        versionByName = versionRepository.save(versionEntity);
    }

    if (!applicationByName.getVersionEntities().contains(versionByName)) {
        applicationByName.getVersionEntities().add(versionByName);
        applicationByName = applicationRepository.save(applicationByName);
    }


    lifecycleToSave.setApplicationEntity(applicationByName);
    lifecycleToSave.setVersionEntity(versionByName);

    return lifecycleRepository.save(lifecycleToSave);
}
 
Example 17
Project: fullstop   File: SaveApplicationLifecycleRetryTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 18
Project: omg_mongodb   File: EShopBean.java   View source code 6 votes vote down vote up
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;
    }
 
Example 19
Project: omg_mongodb   File: EShopBean.java   View source code 6 votes vote down vote up
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;
    }
 
Example 20
Project: AirAlliance   File: GuestRestService.java   View source code 6 votes vote down vote up
@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();
  }
 
Example 21
Project: AirAlliance   File: FlightRestService.java   View source code 6 votes vote down vote up
@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();
  }
 
Example 22
Project: jpa   File: LockService.java   View source code 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example 23
Project: KitchenSink   File: SpeakerEndpoint.java   View source code 6 votes vote down vote up
@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();
}
 
Example 24
Project: mobile-starting-framework   File: AdminDaoImpl.java   View source code 6 votes vote down vote up
@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();
}
 
Example 25
Project: mobile-starting-framework   File: NotificationDaoImpl.java   View source code 6 votes vote down vote up
@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();
}
 
Example 26
Project: mobile-starting-framework   File: NotificationDaoImpl.java   View source code 6 votes vote down vote up
@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();
}
 
Example 27
Project: mobile-starting-framework   File: XslDaoImpl.java   View source code 6 votes vote down vote up
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();
}
 
Example 28
Project: mobile-starting-framework   File: NewsDaoDBImpl.java   View source code 6 votes vote down vote up
@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;
}
 
Example 29
Project: mobile-starting-framework   File: ToursDaoImpl.java   View source code 6 votes vote down vote up
@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();
}
 
Example 30
Project: mobile-starting-framework   File: ToursDaoImpl.java   View source code 6 votes vote down vote up
@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();
}
 
Example 31
Project: mobile-starting-framework   File: ConfigParamDaoImpl.java   View source code 6 votes vote down vote up
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();
}
 
Example 32
Project: jped-parent-project   File: JpaTransactionBeanHelper.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 33
Project: jped-parent-project   File: JpaTransactionBeanHelper.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 34
Project: yum   File: DailyMenusApiController.java   View source code 5 votes vote down vote up
@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");
    }    
}
 
Example 35
Project: yum   File: FoodsApiController.java   View source code 5 votes vote down vote up
@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);
      

}
 
Example 36
Project: yum   File: OrdersApiController.java   View source code 5 votes vote down vote up
@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");
        }

    }

}
 
Example 37
Project: oscm   File: ExceptionMapperTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 38
Project: oscm   File: ExceptionMapper.java   View source code 5 votes vote down vote up
private boolean canMapToConcurrentModificationException(
        PersistenceException pe) {
    if (pe instanceof EntityExistsException
            || pe instanceof OptimisticLockException) {
        return true;
    }
    return false;
}
 
Example 39
Project: crnk-framework   File: OptimisticLockExceptionMapper.java   View source code 5 votes vote down vote up
@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();
}
 
Example 40
Project: crnk-framework   File: OptimisticLockExceptionMapper.java   View source code 5 votes vote down vote up
@Override
public OptimisticLockException fromErrorResponse(ErrorResponse errorResponse) {
	Iterable<ErrorData> errors = errorResponse.getErrors();
	ErrorData error = errors.iterator().next();
	String msg = error.getDetail();
	return new OptimisticLockException(msg);
}