/** * Retrieve all elements without pagination and includes authorizations.. * * @return all elements without pagination. */ @GET @Path("withAuth") @org.springframework.transaction.annotation.Transactional(readOnly = true) public TableItem<SystemRoleVo> findAllFetchAuth() { final TableItem<SystemRoleVo> result = new TableItem<>(); // get all roles final Map<Integer, SystemRoleVo> results = new TreeMap<>(); fetchRoles(results); // fetch authorizations fetchAuthorizations(results); // apply pagination result.setData(new ArrayList<>(results.values())); result.setRecordsTotal(results.size()); result.setRecordsTotal(results.size()); return result; }
@Transactional(rollbackOn = Exception.class) public Set<PhotoLocationImage> importImageKeywordsFromCSV(MultipartFile file, Course course, boolean store) throws IOException, BuenOjoCSVParserException { PhotoLocationExtraPhotosKeywordCSVParser parser = new PhotoLocationExtraPhotosKeywordCSVParser(file); Map <String,List<String>> map = parser.parse(); ArrayList<PhotoLocationImage> images = new ArrayList<>(); for(String name : map.keySet()) { PhotoLocationImage img = this.image(name, map.get(name),course); images.add(img); } if (store) { List<PhotoLocationImage> imgs = photoLocationImageRepository.save(images); return new HashSet<PhotoLocationImage>(imgs); } return new HashSet<PhotoLocationImage>(images); }
@Override @Transactional public void saveOrUpdate(RouteLeg leg) { RouteLeg dbLeg = entityManager.find(leg.getClass(), leg.getId()); if (dbLeg != null) { dbLeg = leg; entityManager.merge(dbLeg); } else { log.warn("Route with id {} not found in DB, inserting as new...", leg.getId()); try { saveRouteLeg(leg); } catch (DatabaseException e) { log.error("Fatal: could not save route leg to db: {}", e.getMessage()); } } }
@Transactional private void upsertPolicySetInTransaction(final String policySetName, final ZoneEntity zone, final String policySetPayload) { PolicySetEntity existingPolicySetEntity = this.policySetRepository.getByZoneAndPolicySetId(zone, policySetName); PolicySetEntity policySetEntity = new PolicySetEntity(zone, policySetName, policySetPayload); // If policy Set already exists, set PK of entity for update if (null != existingPolicySetEntity) { LOGGER.debug("Found an existing policy set policySetName = {}, zone = {}, upserting now .", policySetName, zone); policySetEntity.setId(existingPolicySetEntity.getId()); } else { LOGGER.debug("No existing policy set found for policySetName = {}, zone = {}, inserting now .", policySetName, zone); } this.cache.resetForPolicySet(zone.getName(), policySetName); this.policySetRepository.save(policySetEntity); }
@Transactional public ProuctTcc trying(Product product) { Product entity = productRepositorie.findOne(product.getId()); entity.setNum(entity.getNum() - product.getNum()); if (entity.getNum() < 0) throw new CustomException("数量不足"); productRepositorie.save(entity); ProuctTcc tcc = new ProuctTcc(); tcc.setEntityId(product.getId()); tcc.setEntityType(2); tcc.setSnap("{\"num\":" + product.getNum() + "}"); tcc.setExpire(OffsetDateTime.now().plusSeconds(expireSeconds)); tcc.setInsTm(OffsetDateTime.now()); tcc.setStatus(0); tcc.setUpdTm(OffsetDateTime.now()); productTccRepositorie.save(tcc); return tcc; }
@Transactional public HttpResponse signOut(HttpRequest request) { some(request.getCookies().get(config.getTokenName()), Cookie::getValue).ifPresent( token -> { UserSessionDao userSessionDao = daoProvider.getDao(UserSessionDao.class); UserSession thisSession = userSessionDao.selectByToken(token); userSessionDao.delete(thisSession); storeProvider.getStore(BOUNCR_TOKEN).delete(token); } ); Cookie expire = builder(Cookie.create(config.getTokenName(), "")) .set(Cookie::setPath, "/") .set(Cookie::setMaxAge, -1) .build(); Multimap<String, Cookie> cookies = Multimap.of(config.getTokenName(), expire); return builder(UrlRewriter.redirect(SignInController.class, "signInForm", SEE_OTHER)) .set(HttpResponse::setCookies, cookies) .build(); }
@Override @Transactional public void createTemplate(Integer tenantId, Collection<ShiftInfo> shifts) { Tenant tenant = entityManager.find(Tenant.class, tenantId); if (null == tenant) { throw new IllegalStateException("Tenant " + tenantId + " does not exist!"); } ShiftTemplate old = getTemplate(tenantId); ShiftTemplate template = (null != old) ? old : new ShiftTemplate(); template.setBaseDateType(new EnumOrCustom(tenantId, false, BaseDateDefinitions.WEEK_AFTER_START_DATE .toString())); long weeksInShifts = tenant.getConfiguration().getTemplateDuration(); template.setRepeatType(new EnumOrCustom(tenantId, true, "0:" + weeksInShifts + ":0:0")); template.setUniversalExceptions(Collections.emptyList()); template.setShifts(shifts.stream().collect(Collectors.toList())); template.setTenantId(tenantId); entityManager.merge(template); }
@Transactional @Async @Override public Future<List<TaskDTO>> getTasksOfUser(final Long userId) { final CompletableFuture<List<TaskDTO>> future = new CompletableFuture<>(); final TasksOfUserMessage.Request request = new TasksOfUserMessage.Request(userId); PatternsCS.ask(userSupervisorActor, request, Global.TIMEOUT).toCompletableFuture() .whenComplete((msg, exc) -> { if (exc == null) { future.complete(((TasksOfUserMessage.Response) msg).getTasks()); } else { future.completeExceptionally(exc); } }); return future; }
@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 @Transactional public OrderDto finish(OrderDto orderDto) { // 判断订单状态 if (!orderDto.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) { log.error("【完结订单】订单状态不正确,orderId={}, orderStatus={}", orderDto.getOrderId(), orderDto.getOrderStatus()); throw new SellException(ResultEnum.ORDER_STATUS_ERROR); } // 修改订单状态 orderDto.setOrderStatus(OrderStatusEnum.FINISHED.getCode()); OrderMaster orderMaster = new OrderMaster(); BeanUtils.copyProperties(orderDto, orderMaster); OrderMaster updateResult = orderMasterRepository.save(orderMaster); if (updateResult == null) { log.error("【完结订单】更新失败,orderMaster={}", orderMaster); throw new SellException(ResultEnum.ORDER_UPDATE_FAIL); } return orderDto; }
@PreAuthorize("hasAuthority('chef')") @Transactional public ResponseEntity<Object> foodsPost(@ApiParam(value = "The food to save" ) @RequestBody FoodDetails foodDetails, Errors errors) throws ApiException, Exception { // '204': Food succesfully created // '400': // '412': description: Food name already exists PRECONDITION_FAILED // 500: Internal server error if (errors.hasErrors()) { Error error = new Error(); error.setError("400"); error.setMessage("Validation Failed"); System.out.println("" + errors.getAllErrors()); return new ResponseEntity<>(error, HttpStatus.BAD_REQUEST); } foodService.foodsPost(foodDetails); return new ResponseEntity<>( HttpStatus.NO_CONTENT); }
@Test @Transactional public void testRegisterInvalidEmail() throws Exception { UserDTO u = new UserDTO( "bob", // login "password", // password "Bob", // firstName "Green", // lastName "invalid", // e-mail <-- invalid true, // activated "en", // langKey new HashSet<>(Arrays.asList(AuthoritiesConstants.USER)) ); restUserMockMvc.perform( post("/api/register") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(u))) .andExpect(status().isBadRequest()); Optional<User> user = userRepository.findOneByLogin("bob"); assertThat(user.isPresent()).isFalse(); }
@Transactional public List<DailyMenu> menusMonthlyMonthyearGet(String monthyear, Long userId) throws ApiException, Exception { String patternString = "^\\d{2}-\\d{4}$"; java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(patternString); Matcher matcher = pattern.matcher(monthyear); if (matcher.matches()) { int month = Integer.parseInt(monthyear.substring(0, 2)); int year = Integer.parseInt(monthyear.substring(3, 7)); if (month > 12) { throw new ApiException(400, "Monthly menu not found"); } LocalDate monthYearDate = new LocalDate().withYear(year).withMonthOfYear(month); LocalDate startOfMonth = monthYearDate.dayOfMonth().withMinimumValue(); int daysOfMonth = monthYearDate.dayOfMonth().withMaximumValue().getDayOfMonth(); List<DailyMenu> monthlyMenu = new ArrayList<>(); for (int i = 0; i < daysOfMonth; i++) { DailyMenu dailymenu = createOrderedDailyMenu(startOfMonth.plusDays(i), userId); if (dailymenu.getDate() != null) { monthlyMenu.add(dailymenu); } } return monthlyMenu; } else { throw new ApiException(400, "Monthly menu not found"); } }
@Transactional public User userIdGet(Long id) throws ApiException, Exception { //If id exists in database. if (userRepo.findById(id) != null) { com.jrtechnologies.yum.data.entity.User userEntity = userRepo.findById(id); User userModel = new User(); UserRoleConverter userRole = new UserRoleConverter(); LastEdit lastEdit = new LastEdit(); lastEdit.setTimeStamp(userEntity.getLastEdit()); lastEdit.setVersion(userEntity.getVersion()); userModel.setId(userEntity.getId()); userModel.setFirstName(userEntity.getFirstName()); userModel.setLastName(userEntity.getLastName()); userModel.setEmail(userEntity.getEmail()); userModel.setRole(userRole.convertToDatabaseColumn(userEntity.getUserRole())); userModel.setRegistrationDate(userEntity.getRegistrationDate()); userModel.setApproved(userEntity.isApproved()); userModel.setLastEdit(lastEdit); userModel.setHasPicture(userEntity.hasPicture()); userModel.setBalance(userEntity.getBalance()); return userModel; // Return one user. } throw new ApiException(404, "User not found"); }
@Transactional @RolesAllowed("MODIFY_OIDC_PROVIDER") public HttpResponse update(OidcProviderForm form) { if (form.hasErrors()) { return templateEngine.render("admin/oidcProvider/edit", "oidcProvider", form, "responseTypes", ResponseType.values(), "tokenEndpointAuthMethods", TokenEndpointAuthMethod.values()); } else { OidcProviderDao oidcProviderDao = daoProvider.getDao(OidcProviderDao.class); OidcProvider oidcProvider = oidcProviderDao.selectById(form.getId()); beansConverter.copy(form, oidcProvider); oidcProviderDao.update(oidcProvider); return UrlRewriter.redirect(OidcProviderController.class, "list", SEE_OTHER); } }
@Override @Transactional public Boolean removeShift(Integer tenantId, Long id) { Shift shift = entityManager.find(Shift.class, id); if (shift == null) { return false; } validateTenantIdParameter(tenantId, shift); entityManager.remove(shift); return true; }
@Override @Asynchronous @Transactional public void deleteChefs() { this.chefRepository.deleteAll(); }
@Transactional default Character findOneAndFetchEverythingRelated(Integer id) { Character result = findOne(id); result.getItemQuickAccessBarConfig().size(); result.getSpellQuickAccessBarConfig().size(); result.getSpells().size(); Collection<CharactersQuests> quests = result.getQuests(); quests.forEach(q -> q.getQuestTasks().size()); quests.forEach(q -> q.getQuest().getId()); quests.forEach(q -> q.getQuest().getItemsReward().size()); quests.forEach(q -> q.getItemsReward().size()); return result; }
@Test @FlywayTest(locationsForMigrate = { "/db/test" }) @Transactional public void testApiV1UsersLockUserIdPost_withExistingUser_shouldLock() throws Exception { doNothing().when(emailService).sendUnlockCodeEmailFor(any(User.class)); mockMvc.perform(post("/api/v1/user-checks/lock/1") .contentType(jsonContentType)) .andExpect(status().isOk()); User lockedOne = dao.findOne(1l); assertTrue(lockedOne.getStatus().equals(UserStatus.LOCKED)); assertFalse(lockedOne.getUnlockCode().isEmpty()); }
@Override @Transactional public Spot getSpot(Integer tenantId, Long id) { Spot spot = entityManager.find(Spot.class, id); validateTenantIdParameter(tenantId, spot); return spot; }
@Override @Transactional public Roster buildRoster(Integer tenantId) { List<Skill> skillList = entityManager.createNamedQuery("Skill.findAll", Skill.class) .setParameter("tenantId", tenantId) .getResultList(); List<Spot> spotList = entityManager.createNamedQuery("Spot.findAll", Spot.class) .setParameter("tenantId", tenantId) .getResultList(); List<Employee> employeeList = entityManager.createNamedQuery("Employee.findAll", Employee.class) .setParameter("tenantId", tenantId) .getResultList(); List<TimeSlot> timeSlotList = entityManager.createNamedQuery("TimeSlot.findAll", TimeSlot.class) .setParameter("tenantId", tenantId) .getResultList(); List<EmployeeAvailability> employeeAvailabilityList = entityManager.createNamedQuery("EmployeeAvailability.findAll", EmployeeAvailability.class) .setParameter("tenantId", tenantId) .getResultList(); List<Shift> shiftList = entityManager.createNamedQuery("Shift.findAll", Shift.class) .setParameter("tenantId", tenantId) .getResultList(); Tenant tenant = entityManager.find(Tenant.class, tenantId); // TODO fill in the score too - do we inject a ScoreDirectorFactory? return new Roster((long) tenantId, tenantId, skillList, spotList, employeeList, timeSlotList, employeeAvailabilityList, tenant.getConfiguration(), shiftList); }
@Override @Transactional public List<IsAliveDTO> getAllIsAliveEntries() { LOGGER.debug("Service for fetching all entries for isAlive called.."); createNewIsAliveCheck(); return isAliveMapper.isAliveListToIsAliveDTOList(repo.findAll()); }
@Override @Transactional public void run() { try { foundTransactionScopedBean = bean.isInTx(); } catch (Exception e) { e.printStackTrace(); } latch.countDown(); }
@Override @Transactional public void increaseStock(List<CartDto> cartDtoList) { for (CartDto cartDto : cartDtoList) { ProductInfo productInfo = repository.findOne(cartDto.getProductId()); if (productInfo == null) { throw new SellException(ResultEnum.PRODUCT_NOT_EXIST); } Integer result = productInfo.getProductStock() + cartDto.getProductQuantity(); productInfo.setProductStock(result); repository.save(productInfo); } }
@Transactional public void setDefaultValues(PlanInstanceDay instanceDay) { if (instanceDay.getPosted() == null) { instanceDay.setPosted(false); planInstanceDayRepository.save(instanceDay); } if (instanceDay.getScheduledDate() == null) { scheduleDays(instanceDay.getPlanInstance()); } }
@Override @Transactional public SpotRosterView getSpotRosterViewFor(Integer tenantId, String startDateString, String endDateString, List< Spot> spots) { LocalDate startDate = LocalDate.parse(startDateString); LocalDate endDate = LocalDate.parse(endDateString); if (null == spots) { throw new IllegalArgumentException("spots is null!"); } return getSpotRosterView(tenantId, startDate, endDate, spots); }
@Test @FlywayTest(locationsForMigrate = { "/db/test" }) @Transactional public void testApiV1UsersPinCheckPost_withValidPin_shouldReturnValid() throws Exception { SendPin pin = new SendPin(); pin.setId(2l); pin.setPin("4321"); mockMvc.perform(post("/api/v1/user-checks/pin/check").content(json(pin)) .contentType(jsonContentType)) .andExpect(jsonPath("$.valid", is(true))) .andExpect(status().isOk()); assertEquals("should still be status active",UserStatus.ACTIVE,dao.getOne(2l).getStatus()); }
@Transactional default Quest findByNameFetchItemsReward(String questName) { Quest quest = findByName(questName); quest.getItemsReward().size(); return quest; }
@RolesAllowed({"LOCK_USER", "LOCK_ANY_USER"}) @Transactional public HttpResponse lock(Parameters params) { Long id = params.getLong("id"); UserDao userDao = daoProvider.getDao(UserDao.class); User user = userDao.selectById(id); userDao.lock(user.getId()); return UrlRewriter.redirect(UserController.class, "show?id=" + id, SEE_OTHER); }
@Override @Transactional public ShiftView getShift(Integer tenantId, Long id) { Shift shift = entityManager.find(Shift.class, id); validateTenantIdParameter(tenantId, shift); return new ShiftView(shift); }
@Override @Transactional public void addSpotToSpotGroup(Integer tenantId, Long id, Spot spot) { SpotGroup group = getSpotGroup(tenantId, id); validateTenantIdParameter(tenantId, spot); group.getSpots().add(spot); entityManager.merge(group); }
@RolesAllowed({"MODIFY_APPLICATION", "MODIFY_ANY_APPLICATION"}) @Transactional public HttpResponse update(ApplicationForm form) { if (form.hasErrors()) { return templateEngine.render("admin/application/edit", "application", form); } else { ApplicationDao applicationDao = daoProvider.getDao(ApplicationDao.class); Application application = applicationDao.selectById(form.getId()); beansConverter.copy(form, application); applicationDao.update(application); return UrlRewriter.redirect(ApplicationController.class, "list", SEE_OTHER); } }
/** * Updates counts of test run. * @param id Test run id. * @param totalCases Total test case count. * @param failedCases Total failed test cases count. */ @Modifying @Transactional @Query("UPDATE TestRun tr SET tr.exampleCount = COALESCE(tr.exampleCount, 0) + :totalCases, " + "tr.failureCount = COALESCE(tr.failureCount, 0) + :failedCases, " + "tr.duration = COALESCE(tr.duration, 0) + :duration " + "WHERE tr.id = :id") void updateCounts(@Param("id") Long id, @Param("totalCases") int totalCases, @Param("failedCases") int failedCases, @Param("duration") double duration);
/** * 自定义 native query 查询 {@link ScheduleVO} ,略繁琐但是好像没有更好的办法. */ @Transactional @Override public List<ScheduleVO> findByOpenIdAndDate(String openId, Date date) { String sql = "select t.schedule_id as scheduleId ,t.date,t.meeting_room_id as meetingRoomId,t.title,t.open_id as openId,m.room_no as roomNo,t.start_time as startTime,t.end_time as endTime, t.repeat_mode as repeatMode from (select p.schedule_id,p.date,s.meeting_room_id,s.title,p.open_id,s.start_time,s.end_time,s.repeat_mode from participant p left join schedule s on p.schedule_id = s.id ) as t left join meeting_room m on t.meeting_room_id = m.id where (t.open_id=? and t.date=?) or (t.open_id=? and repeat_mode='W')"; Session session = entityManager.unwrap(org.hibernate.Session.class); SQLQuery query = session.createSQLQuery(sql); @SuppressWarnings("unchecked") List<ScheduleVO> scheduleVOs = query.setResultTransformer(Transformers.aliasToBean(ScheduleVO.class)) .setParameter(0, openId).setParameter(1, date).setParameter(2, openId).list(); return scheduleVOs.stream().filter(s -> s.isNeedInclude(date)).map(s -> { s.setDate(date); return s; }).sorted().collect(Collectors.toList()); }
@Test @FlywayTest(locationsForMigrate = { "/db/test" }) @Transactional public void testApiV1UsersPinCheckPost_withTryThreeTimesWrong_shouldReturnForbidden() throws Exception { doNothing().when(emailService).sendUnlockCodeEmailFor(any(User.class)); SendPin pin = new SendPin(); pin.setId(2l); pin.setPin("0000"); mockMvc.perform(post("/api/v1/user-checks/pin/check").content(json(pin)) .contentType(jsonContentType)) .andExpect(jsonPath("$.valid", is(false))) .andExpect(status().isOk()); mockMvc.perform(post("/api/v1/user-checks/pin/check").content(json(pin)) .contentType(jsonContentType)) .andExpect(jsonPath("$.valid", is(false))) .andExpect(status().isOk()); mockMvc.perform(post("/api/v1/user-checks/pin/check").content(json(pin)) .contentType(jsonContentType)) .andExpect(jsonPath("$.valid", is(false))) .andExpect(status().isOk()); assertEquals("after three times should be locked",UserStatus.LOCKED,dao.getOne(2l).getStatus()); }
@Test @Transactional public void testAddTenant() throws Exception { ObjectMapper om = new ObjectMapper(); mvc.perform(post("/tenants").content(om.writeValueAsBytes(new Tenant().tenantKey("testadd"))).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); assertExistSchema("testadd"); }
@Test @Transactional public void testDeleteTenant() throws Exception { testAddTenant(); mvc.perform(delete("/tenants/testadd")).andExpect(status().isOk()); assertNotExistSchema("testaddd"); }