@Transactional protected void updateEndPointWithLock(final EndPoint endPoint) { checkEndPointNameDoesNotExist(endPoint); final EndPoint existingEndPoint = findEndPoint(endPoint.getId()); if (!existingEndPoint.getVersion().equals(endPoint.getVersion())) { throw new EndPointHealthException("End point has been updated somewhere else, please refresh"); } existingEndPoint.setName(endPoint.getName()); existingEndPoint.setHost(endPoint.getHost()); existingEndPoint.setPath(endPoint.getPath()); existingEndPoint.setPort(endPoint.getPort()); existingEndPoint.setProtocol(endPoint.getProtocol()); clearAttributesIfNeeded(existingEndPoint); }
@Transactional @Override public boolean dispatchOtp(String inviteCode) { return inviteDao.findByCode(inviteCode) .map(inviteEntity -> { inviteEntity.setTelephoneNumber(inviteOtpRequest.getTelephoneNumber()); inviteEntity.setPassword(passwordHasher.hash(inviteOtpRequest.getPassword())); inviteDao.merge(inviteEntity); int newPassCode = secondFactorAuthenticator.newPassCode(inviteEntity.getOtpKey()); String passcode = format(Locale.ENGLISH, SIX_DIGITS_WITH_LEADING_ZEROS, newPassCode); notificationService.sendSecondFactorPasscodeSms(inviteOtpRequest.getTelephoneNumber(), passcode) .thenAcceptAsync(notificationId -> LOGGER.info("sent 2FA token successfully for invite code [{}], notification id [{}]", inviteCode, notificationId)) .exceptionally(exception -> { LOGGER.error(format("error sending 2FA token for invite code [%s]", inviteCode), exception); return null; }); LOGGER.info("New 2FA token generated for invite code [{}]", inviteCode); return true; }).orElseGet(() -> { LOGGER.info("New 2FA token generated for invite code [{}]", inviteCode); return false; }); }
@Deprecated // Refactor to adopt UserOtpDispatcher. And Avoid using generic InviteOtpRequest object to avoid having to use optional fields @Transactional public void reGenerateOtp(InviteOtpRequest inviteOtpRequest) { Optional<InviteEntity> inviteOptional = inviteDao.findByCode(inviteOtpRequest.getCode()); if (inviteOptional.isPresent()) { InviteEntity invite = inviteOptional.get(); invite.setTelephoneNumber(inviteOtpRequest.getTelephoneNumber()); inviteDao.merge(invite); int newPassCode = secondFactorAuthenticator.newPassCode(invite.getOtpKey()); String passcode = String.format(Locale.ENGLISH, SIX_DIGITS_WITH_LEADING_ZEROS, newPassCode); notificationService.sendSecondFactorPasscodeSms(inviteOtpRequest.getTelephoneNumber(), passcode) .thenAcceptAsync(notificationId -> LOGGER.info("sent 2FA token successfully for invite code [{}], notification id [{}]", inviteOtpRequest.getCode(), notificationId)) .exceptionally(exception -> { LOGGER.error(format("error sending 2FA token for invite code [%s]", inviteOtpRequest.getCode()), exception); return null; }); LOGGER.info("New 2FA token generated for invite code [{}]", inviteOtpRequest.getCode()); } else { throw notFoundInviteException(inviteOtpRequest.getCode()); } }
@Transactional public Service doCreate(Optional<String> serviceName, Optional<List<String>> gatewayAccountIdsOptional) { Service service = serviceName .map(name -> Service.from(name)) .orElseGet(() -> Service.from()); ServiceEntity serviceEntity = ServiceEntity.from(service); if (gatewayAccountIdsOptional.isPresent()) { List<String> gatewayAccountsIds = gatewayAccountIdsOptional.get(); if (serviceDao.checkIfGatewayAccountsUsed(gatewayAccountsIds)) { throw conflictingServiceGatewayAccounts(gatewayAccountsIds); } serviceEntity.addGatewayAccountIds(gatewayAccountsIds.toArray(new String[0])); } serviceDao.persist(serviceEntity); return linksBuilder.decorate(serviceEntity.toService()); }
@Transactional public User doCreate(CreateUserRequest userRequest, String roleName) { return roleDao.findByRoleName(roleName) .map(roleEntity -> { UserEntity userEntity = UserEntity.from(userRequest); userEntity.setPassword(passwordHasher.hash(userRequest.getPassword())); if (!userRequest.getServiceExternalIds().isEmpty()) { addServiceRoleToUser(userEntity, roleEntity, userRequest.getServiceExternalIds()); } //Deprecated, leaving for backward compatibility else if (userRequest.getGatewayAccountIds() != null && userRequest.getGatewayAccountIds().size() > 0) { addServiceFromGatewayAccountsToUser(userEntity, roleEntity, userRequest.getGatewayAccountIds()); } userDao.persist(userEntity); return linksBuilder.decorate(userEntity.toUser()); }) .orElseThrow(() -> undefinedRoleException(roleName)); }
@Override protected final void configure() { configurePersistence(); requireBinding(PersistService.class); requireBinding(UnitOfWork.class); /*if[AOP]*/ // wrapping in an if[AOP] just to allow this to compile in NO_AOP -- it won't be used // class-level @Transacational bindInterceptor(annotatedWith(Transactional.class), new TransactionalClassMethodMatcher(), getTransactionInterceptor()); // method-level @Transacational bindInterceptor(any(), new TransactionalMethodMatcher(), getTransactionInterceptor()); /*end[AOP]*/ }
private Transactional readTransactionMetadata(MethodInvocation methodInvocation) { Transactional transactional; Method method = methodInvocation.getMethod(); Class<?> targetClass = methodInvocation.getThis().getClass(); transactional = method.getAnnotation(Transactional.class); if (null == transactional) { // If none on method, try the class. transactional = targetClass.getAnnotation(Transactional.class); } if (null == transactional) { // If there is no transactional annotation present, use the default transactional = Neo4jLocalTxnInterceptor.Internal.class.getAnnotation(Transactional.class); } return transactional; }
/** * Stores (create or updates) invite. * * <p>It also send email invite on initial invite creation. * * @param invite invite to store * @throws ConflictException when user is specified email is already registered * @throws ServerException when any other error occurs during invite storing */ @Transactional(rollbackOn = {RuntimeException.class, ServerException.class}) public void store(Invite invite) throws NotFoundException, ConflictException, ServerException { requireNonNull(invite, "Required non-null invite"); String domainId = invite.getDomainId(); if (!OrganizationDomain.DOMAIN_ID.equals(domainId) && !WorkspaceDomain.DOMAIN_ID.equals(domainId)) { throw new ConflictException("Invitations for specified domain are not supported"); } permissionsManager.checkActionsSupporting(domainId, invite.getActions()); try { userManager.getByEmail(invite.getEmail()); throw new ConflictException("User with specified id is already registered"); } catch (NotFoundException ignored) { } Optional<InviteImpl> existingInvite = inviteDao.store(new InviteImpl(invite)); if (!existingInvite.isPresent()) { Subject currentSubject = EnvironmentContext.getCurrent().getSubject(); eventService.publish( new InviteCreatedEvent( currentSubject.isAnonymous() ? null : currentSubject.getUserId(), invite)); } }
@Transactional protected Optional<InviteImpl> doCreate(InviteImpl invite) throws ServerException { EntityManager manager = managerProvider.get(); InviteImpl existing = null; try { final InviteImpl result = getEntity(invite.getDomainId(), invite.getInstanceId(), invite.getEmail()); existing = new InviteImpl(result); result.getActions().clear(); result.getActions().addAll(invite.getActions()); } catch (NotFoundException n) { manager.persist(invite); } manager.flush(); return Optional.ofNullable(existing); }
@Transactional public Issue create(RepositoryPK repositoryPK, PullRequestForm form) { Repository repository = emProvider.get().find(Repository.class, repositoryPK); Issue issue = issueService.createIssueAndComment(repository, form.getTitle(), form.getContent(), null); PullRequest pullRequest = new PullRequest(); pullRequest.setPk(issue.getPk()); form.applyTo(pullRequest); pullRequest.setCommitId(ObjectId.zeroId().name()); pullRequest.setBaseCommitId(ObjectId.zeroId().name()); pullRequest.setRequestCommitId(ObjectId.zeroId().name()); emProvider.get().persist(pullRequest); RepositoryPK reqRepoPK = new RepositoryPK(form.getRequestUserName(), form.getRequestRepoName()); gitOperation.updatePullRequestRefSpec(issue.getPk(), reqRepoPK, form.getRequestBranch()); updateCommitIds(pullRequest); return issue; }
@Transactional public Result<Repository> createRepository(String userName, RepositoryForm repositoryForm) { if (!repositoryForm.getOwner().equals(userName)) { throw new ForbiddenException(); } Repository check = emProvider.get().find(Repository.class, new RepositoryPK(userName, repositoryForm.getName())); if (check != null) { return Result.error("already exists"); } Repository repository = new Repository(); repository.setPk(new RepositoryPK(userName, repositoryForm.getName())); repository.setPrivateRepo(repositoryForm.isPrivateRepo()); repository.setDescription(repositoryForm.getDescription()); emProvider.get().persist(repository); gitOperation.init(userName, repository.getPk().getRepositoryName(), repository.getDefaultBranch()); return Result.success(repository); }
@Transactional public MergeableType getMeargeable(PullRequestEndpoint baseEndpoint, PullRequestEndpoint requestEndpoint) { ObjectId commitId = gitOperation.getCommitId(baseEndpoint.getRepositoryPK(), baseEndpoint.getBranchName()); ObjectId requestCommitId = gitOperation.getCommitId(requestEndpoint.getRepositoryPK(), requestEndpoint.getBranchName()); MergeableHistoryPK pk = new MergeableHistoryPK(baseEndpoint.getRepositoryPK(), commitId.getName(), requestCommitId.getName()); MergeableHistory history = emProvider.get().find(MergeableHistory.class, pk); if (history != null) { return history.getMergeableType(); } boolean canMerge = gitOperation.canMerge(baseEndpoint.getRepositoryPK(), baseEndpoint.getBranchName(), requestEndpoint.getRepositoryPK(), requestEndpoint.getBranchName()); history = new MergeableHistory(); history.setPk(pk); history.setMergeableType(MergeableType.of(canMerge)); emProvider.get().persist(history); return history.getMergeableType(); }
@Transactional public Result<Boolean> registerMailSettings(MailJson mailJson) { getAppProperties().forEach(prop -> { emProvider.get().remove(prop); }); List<AppProperty> appProperties = mailJson.createAppProperties(); appProperties.stream() .filter(prop -> Objects.nonNull(prop.getValue())) .forEach(prop -> { emProvider.get().persist(prop); }); // reset mailSender.initProperties(true); return Result.success(true); }
@Transactional protected Optional<T> doCreate(T permissions) throws ServerException { EntityManager manager = managerProvider.get(); try { final T result = getEntity(wildcardToNull(permissions.getUserId()), permissions.getInstanceId()); final T existing = getDomain().newInstance(result.getUserId(), result.getInstanceId(), result.getActions()); result.getActions().clear(); result.getActions().addAll(permissions.getActions()); manager.flush(); return Optional.of(existing); } catch (NotFoundException n) { manager.persist(permissions); manager.flush(); return Optional.empty(); } }
@Override @Transactional public Page<FreeResourcesLimitImpl> getAll(int maxItems, int skipCount) throws ServerException { try { final List<FreeResourcesLimitImpl> list = managerProvider .get() .createNamedQuery("FreeResourcesLimit.getAll", FreeResourcesLimitImpl.class) .setMaxResults(maxItems) .setFirstResult(skipCount) .getResultList() .stream() .map(FreeResourcesLimitImpl::new) .collect(Collectors.toList()); return new Page<>(list, skipCount, maxItems, getTotalCount()); } catch (RuntimeException e) { throw new ServerException(e.getMessage(), e); } }
/** * Removes organization with given id * * @param organizationId organization id * @throws NullPointerException when {@code organizationId} is null * @throws ServerException when any other error occurs during organization removing */ @Transactional(rollbackOn = {RuntimeException.class, ApiException.class}) public void remove(String organizationId) throws ServerException { requireNonNull(organizationId, "Required non-null organization id"); try { OrganizationImpl organization = organizationDao.getById(organizationId); eventService .publish(new BeforeAccountRemovedEvent(organization.getAccount())) .propagateException(); eventService.publish(new BeforeOrganizationRemovedEvent(organization)).propagateException(); removeSuborganizations(organizationId); final List<Member> members = removeMembers(organizationId); organizationDao.remove(organizationId); final String initiator = EnvironmentContext.getCurrent().getSubject().getUserName(); eventService.publish(new OrganizationRemovedEvent(initiator, organization, members)); } catch (NotFoundException e) { // organization is already removed } }
@Override @Transactional public OrganizationDistributedResourcesImpl get(String organizationId) throws NotFoundException, ServerException { requireNonNull(organizationId, "Required non-null organization id"); try { OrganizationDistributedResourcesImpl distributedResources = managerProvider.get().find(OrganizationDistributedResourcesImpl.class, organizationId); if (distributedResources == null) { throw new NotFoundException( "There are no distributed resources for organization with id '" + organizationId + "'."); } return new OrganizationDistributedResourcesImpl(distributedResources); } catch (RuntimeException e) { throw new ServerException(e.getMessage(), e); } }
@Override @Transactional public List<SshPairImpl> get(String owner, String service) throws ServerException { requireNonNull(owner); requireNonNull(service); try { return managerProvider .get() .createNamedQuery("SshKeyPair.getByOwnerAndService", SshPairImpl.class) .setParameter("owner", owner) .setParameter("service", service) .getResultList(); } catch (RuntimeException e) { throw new ServerException(e.getLocalizedMessage(), e); } }
@Override @Transactional public SshPairImpl get(String owner, String service, String name) throws ServerException, NotFoundException { requireNonNull(owner); requireNonNull(service); requireNonNull(name); try { SshPairImpl result = managerProvider .get() .find(SshPairImpl.class, new SshPairPrimaryKey(owner, service, name)); if (result == null) { throw new NotFoundException( format("Ssh pair with service '%s' and name '%s' was not found.", service, name)); } return result; } catch (RuntimeException e) { throw new ServerException(e.getLocalizedMessage(), e); } }
@Transactional void storeProcessingFinishedWithoutErrorEvent() { JobEntity myJob = this.jobDao.retrieve(this.jobId); JobEventEntity completedJobEvent = new JobEventEntity(); Date now = new Date(); myJob.setFinished(now); completedJobEvent.setJob(myJob); completedJobEvent.setTimeStamp(now); completedJobEvent.setStatus(JobStatus.COMPLETED); completedJobEvent.setMessage("Processing completed without error"); if (LOGGER.isInfoEnabled()) { LOGGER.info("Completed job {} for user {} without errors.", new Object[]{ myJob.getId(), myJob.getUser().getUsername()}); } this.jobDao.update(myJob); }
@Override @Transactional public Map<String, String> getPreferences(String userId, String filter) throws ServerException { requireNonNull(userId); requireNonNull(filter); try { final EntityManager manager = managerProvider.get(); final PreferenceEntity prefs = manager.find(PreferenceEntity.class, userId); if (prefs == null) { return new HashMap<>(); } final Map<String, String> preferences = prefs.getPreferences(); if (!filter.isEmpty()) { final Pattern pattern = Pattern.compile(filter); return preferences .entrySet() .stream() .filter(preference -> pattern.matcher(preference.getKey()).matches()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } else { return preferences; } } catch (RuntimeException ex) { throw new ServerException(ex.getLocalizedMessage(), ex); } }
/** * Process a user classification for the given songId. * * @param id * The id of the song. * @param classification * The classification of the user for the song. * @return The classification provided. * @throws InvalidClassificationException * When the classification provided was invalid */ @POST @Path("{id}/classify") @Transactional @AwardPoints(CLASSIFICATION_POINTS_AWARD) public ClassificationRequest classifySong(@PathParam("id") final int id, final ClassificationRequest classification) throws InvalidClassificationException { final User user = this.currentUserProvider.get(); final Song song = this.songDAO.findBySoundCloudId(id); final VAVector classificationVector = new VAVector( classification.getValence(), classification.getArousal()); if (classificationDAO.exists(user, song)) { throw new IllegalArgumentException("Already classified this song"); } assertDimensionIsValid(classification.getValence()); assertDimensionIsValid(classification.getArousal()); updateVectorFromClassification(user, song, classificationVector); return classification; }
@Transactional public Result<Issue> merge(IssuePK issuePK, CommentForm form) { LoginContext loginContext = LoginContext.get(reqProvider.get()); PullRequest pullRequest = emProvider.get().find(PullRequest.class, issuePK); boolean merged = gitOperation.merge(pullRequest.getBaseBranchName(), issuePK, form.getContent(), loginContext); if (merged) { issueService.addMergeComment(issuePK, form); emProvider.get().flush(); emProvider.get().clear(); return Result.success(emProvider.get().find(Issue.class, issuePK)); } return Result.error(""); }
@Override @Transactional public Page<WorkspaceImpl> getWorkspaces(String userId, int maxItems, long skipCount) throws ServerException { try { final List<WorkspaceImpl> list = managerProvider .get() .createNamedQuery("Workspace.getAll", WorkspaceImpl.class) .setMaxResults(maxItems) .setFirstResult((int) skipCount) .getResultList() .stream() .map(WorkspaceImpl::new) .collect(Collectors.toList()); final long count = managerProvider .get() .createNamedQuery("Workspace.getAllCount", Long.class) .getSingleResult(); return new Page<>(list, skipCount, maxItems, count); } catch (RuntimeException x) { throw new ServerException(x.getLocalizedMessage(), x); } }
@Override @Transactional public EndPoint findEndPoint(final Long id) { checkEndPointId(id); final Optional<EndPoint> endPoint = endPointDao.find(id); if (!endPoint.isPresent()) { throw new EndPointHealthException(String.format("End point with id %s does not exist", id)); } return endPoint.get(); }
@Transactional protected void internalCreateEndPoint(final EndPoint endPoint) { checkEndPointNameDoesNotExist(endPoint); clearAttributesIfNeeded(endPoint); endPointDao.create(endPoint); }
@Override @Transactional public Collection<EndPointCheck> findEndPointChecksByDateRange(final Long endPointId, final Date startDate, final Date endDate) { final EndPoint endPoint = endPointService.findEndPoint(endPointId); return endPointCheckDao.findByDateRange(endPoint, Utils.toStartOfDay(startDate), Utils.toEndOfDay(endDate)); }
@Transactional public Optional<Integer> updatePassword(String code, String password) { return forgottenPasswordDao.findNonExpiredByCode(code).map(forgottenPassword -> { UserEntity userEntity = forgottenPassword.getUser(); userEntity.setLoginCounter(0); userEntity.setPassword(passwordHasher.hash(password)); userDao.merge(userEntity); forgottenPasswordDao.remove(forgottenPassword); return Optional.of(userEntity.getId()); }).orElseGet(Optional::empty); }
@Transactional public ValidateOtpAndCreateUserResult validateOtpAndCreateUser(InviteValidateOtpRequest inviteValidateOtpRequest) { return inviteDao.findByCode(inviteValidateOtpRequest.getCode()) .map(inviteEntity -> validateOtp(inviteEntity, inviteValidateOtpRequest.getOtpCode()) .map(ValidateOtpAndCreateUserResult::new) .orElseGet(() -> { inviteEntity.setLoginCounter(0); UserEntity userEntity = inviteEntity.mapToUserEntity(); userDao.persist(userEntity); inviteEntity.setDisabled(Boolean.TRUE); inviteDao.merge(inviteEntity); return new ValidateOtpAndCreateUserResult(linksBuilder.decorate(userEntity.toUser())); })) .orElseGet(() -> new ValidateOtpAndCreateUserResult(notFoundInviteException(inviteValidateOtpRequest.getCode()))); }
@Transactional public Optional<Service> doUpdate(String serviceExternalId, ServiceUpdateRequest serviceUpdateRequest) { return serviceDao.findByExternalId(serviceExternalId) .flatMap(serviceEntity -> { attributeUpdaters.get(serviceUpdateRequest.getPath()) .accept(serviceUpdateRequest, serviceEntity); serviceDao.merge(serviceEntity); return Optional.of(serviceEntity.toService()); }); }
@Transactional public Service doUpdateMerchantDetails(String serviceExternalId, UpdateMerchantDetailsRequest updateMerchantDetailsRequest) throws ServiceNotFoundException { return serviceDao.findByExternalId(serviceExternalId) .map(serviceEntity -> { MerchantDetailsEntity merchantEntity = MerchantDetailsEntity.from(updateMerchantDetailsRequest); serviceEntity.setMerchantDetailsEntity(merchantEntity); serviceDao.merge(serviceEntity); return serviceEntity.toService(); }).orElseThrow(() -> new ServiceNotFoundException(serviceExternalId)); }
/** * validates given username and password against persisted users * <p> on successful authentication, user's login count is reset to <b>0</b></p> * <p> on authentication failure, user's login count is increment by <b>1</b></p> * * @param username * @param password * @return {@link User} wrapped in an Optional if a matching user found. Otherwise an Optional.empty() * @throws javax.ws.rs.WebApplicationException if user account is disabled * @throws javax.ws.rs.WebApplicationException with status 423 (Locked) if login attempts > ALLOWED_FAILED_LOGIN_ATTEMPTS */ @Transactional public Optional<User> authenticate(String username, String password) { Optional<UserEntity> userEntityOptional = userDao.findByUsername(username); logger.debug("Login attempt - username={}", username); if (userEntityOptional.isPresent()) { //interestingly java cannot map/orElseGet this block properly, without getting the compiler confused. :) UserEntity userEntity = userEntityOptional.get(); if (passwordHasher.isEqual(password, userEntity.getPassword())) { if (!userEntity.isDisabled()) { userEntity.setLoginCounter(0); userEntity.setUpdatedAt(ZonedDateTime.now(ZoneId.of("UTC"))); userDao.merge(userEntity); } logger.info("Successful Login - user_id={}", userEntity.getExternalId()); return Optional.of(linksBuilder.decorate(userEntity.toUser())); } else { userEntity.setLoginCounter(userEntity.getLoginCounter() + 1); userEntity.setUpdatedAt(ZonedDateTime.now(ZoneId.of("UTC"))); userEntity.setDisabled(userEntity.getLoginCounter() >= loginAttemptCap); logger.info("Failed login attempt - user_id={}, login_counter={}", userEntity.getExternalId(), userEntity.getLoginCounter()); userDao.merge(userEntity); if (userEntity.isDisabled()) { logger.warn("Account locked due to exceeding {} attempts - user_id={}", loginAttemptCap, userEntity.getExternalId()); } return Optional.empty(); } } else { logger.info("Failed login attempt - user_id='Not matched'"); return Optional.empty(); } }
@Transactional public Optional<User> authenticateSecondFactor(String externalId, int code) { logger.debug("OTP attempt - user_id={}", externalId); return userDao.findByExternalId(externalId) .map(userEntity -> { if (userEntity.isDisabled()) { logger.warn("Failed OTP attempt - user_id={}, login_counter={}. Authenticate Second Factor attempted for a disabled User", userEntity.getExternalId(), userEntity.getLoginCounter()); return Optional.<User>empty(); } if (secondFactorAuthenticator.authorize(userEntity.getOtpKey(), code)) { userEntity.setLoginCounter(0); userEntity.setUpdatedAt(ZonedDateTime.now(ZoneId.of("UTC"))); userDao.merge(userEntity); logger.info("Successful OTP. user_id={}", userEntity.getExternalId()); return Optional.of(linksBuilder.decorate(userEntity.toUser())); } else { userEntity.setLoginCounter(userEntity.getLoginCounter() + 1); userEntity.setUpdatedAt(ZonedDateTime.now(ZoneId.of("UTC"))); userEntity.setDisabled(userEntity.getLoginCounter() > loginAttemptCap); userDao.merge(userEntity); if (userEntity.isDisabled()) { logger.warn("Failed OTP attempt - user_id={}, login_counter={}. Invalid second factor in an account currently locked", userEntity.getExternalId(), userEntity.getLoginCounter()); } else { logger.info("Failed OTP attempt - user_id={}, login_counter={}. Invalid second factor attempt.", userEntity.getExternalId(), userEntity.getLoginCounter()); } return Optional.<User>empty(); } }) .orElseGet(() -> { //this cannot happen unless a bug in selfservice logger.error("Authenticate 2FA token attempted for non-existent User [{}]", externalId); return Optional.empty(); }); }
@Transactional public Optional<User> patchUser(String externalId, PatchRequest patchRequest) { Optional<UserEntity> userOptional = userDao.findByExternalId(externalId); if (!userOptional.isPresent()) { return Optional.empty(); } UserEntity user = userOptional.get(); if (PATH_SESSION_VERSION.equals(patchRequest.getPath())) { incrementSessionVersion(user, parseInt(patchRequest.getValue())); } else if (PATH_DISABLED.equals(patchRequest.getPath())) { changeUserDisabled(user, parseBoolean(patchRequest.getValue())); } else if (PATH_TELEPHONE_NUMBER.equals(patchRequest.getPath())) { changeUserTelephoneNumber(user, patchRequest.getValue()); } else if (PATH_FEATURES.equals(patchRequest.getPath())) { changeUserFeatures(user, patchRequest.getValue()); } else { String error = format("Invalid patch request with path [%s]", patchRequest.getPath()); logger.error(error); throw new RuntimeException(error); } return Optional.of(linksBuilder.decorate(user.toUser())); }
@Transactional public Optional<User> doCreate(String userExternalId, String serviceExternalId, String roleName) { Optional<UserEntity> userMaybe = userDao.findByExternalId(userExternalId); if (!userMaybe.isPresent()) { return Optional.empty(); } Optional<ServiceEntity> serviceMaybe = serviceDao.findByExternalId(serviceExternalId); if (!serviceMaybe.isPresent()) { throw serviceDoesNotExistError(serviceExternalId); } Optional<RoleEntity> roleMaybe = roleDao.findByRoleName(roleName); if (!roleMaybe.isPresent()) { throw undefinedRoleException(roleName); } UserEntity userEntity = userMaybe.get(); userEntity.getServicesRole(serviceExternalId) .ifPresent(serviceRoleEntity -> { throw conflictingServiceRoleForUser(userExternalId, serviceExternalId); }); userEntity.addServiceRole(new ServiceRoleEntity(serviceMaybe.get(), roleMaybe.get())); userDao.merge(userEntity); return Optional.of(linksBuilder.decorate(userEntity.toUser())); }
@Override @Transactional public Optional<InviteCompleteResponse> complete(String inviteCode) { return inviteDao.findByCode(inviteCode) .map(inviteEntity -> { if (inviteEntity.isExpired() || inviteEntity.isDisabled()) { throw inviteLockedException(inviteEntity.getCode()); } return userDao.findByEmail(inviteEntity.getEmail()) .map(userEntity -> { if (inviteEntity.getService() != null && inviteEntity.isUserType()) { ServiceRoleEntity serviceRole = new ServiceRoleEntity(inviteEntity.getService(), inviteEntity.getRole()); userEntity.addServiceRole(serviceRole); userDao.merge(userEntity); inviteEntity.setDisabled(true); inviteDao.merge(inviteEntity); InviteCompleteResponse response = new InviteCompleteResponse(inviteEntity.toInvite()); response.setUserExternalId(userEntity.getExternalId()); response.setServiceExternalId(inviteEntity.getService().getExternalId()); return Optional.of(response); } else { throw internalServerError(format("Attempting to complete user subscription to a service for a non existent service. invite-code = %s", inviteEntity.getCode())); } }).orElseGet(() -> { throw internalServerError(format("Attempting to complete user subscription to a service for a non existent user. invite-code = %s", inviteEntity.getCode())); }); }).orElseGet(Optional::empty); }
/** * Completes a service invite. * ie. it creates and persists a user from an invite or/and subscribe a user to an existing service * and if it is a service invite also creates a default service. * It then disables the invite. */ @Override @Transactional public Optional<InviteCompleteResponse> complete(String inviteCode) { return inviteDao.findByCode(inviteCode) .map(inviteEntity -> { if (inviteEntity.isExpired() || inviteEntity.isDisabled()) { throw inviteLockedException(inviteEntity.getCode()); } if (userDao.findByEmail(inviteEntity.getEmail()).isPresent()) { throw conflictingEmail(inviteEntity.getEmail()); } if (inviteEntity.isServiceType()) { UserEntity userEntity = inviteEntity.mapToUserEntity(); ServiceEntity serviceEntity = ServiceEntity.from(Service.from()); if (!data.getGatewayAccountIds().isEmpty()) { serviceEntity.addGatewayAccountIds(data.getGatewayAccountIds().toArray(new String[0])); } serviceDao.persist(serviceEntity); ServiceRoleEntity serviceRoleEntity = new ServiceRoleEntity(serviceEntity, inviteEntity.getRole()); userEntity.addServiceRole(serviceRoleEntity); userDao.merge(userEntity); inviteEntity.setService(serviceEntity); inviteEntity.setDisabled(true); inviteDao.merge(inviteEntity); Invite invite = linksBuilder.addUserLink(userEntity.toUser(), inviteEntity.toInvite()); InviteCompleteResponse response = new InviteCompleteResponse(invite); response.setServiceExternalId(serviceEntity.getExternalId()); response.setUserExternalId(userEntity.getExternalId()); return Optional.of(response); } else { throw internalServerError(format("Attempting to complete a service invite for a non service invite of type. invite-code = %s", inviteEntity.getCode())); } }).orElseGet(() -> Optional.empty()); }
@Transactional void createData() { int i = 0; while (i++ < MAX_COUNT) { JPA.manage(createSaleOrder()); } }
@Transactional void dropData() { all(OrderLine.class).delete(); all(Order.class).delete(); all(Product.class).delete(); all(Address.class).delete(); all(Email.class).delete(); all(Contact.class).delete(); all(Country.class).delete(); all(Circle.class).delete(); all(Title.class).delete(); }
/** * {@inheritDoc} */ @Transactional @Override public T save(T entity) { entityManagerProvider.get().persist(entity); return entity; }