Search in sources :

Example 1 with OrmDuplicateKeyException

use of com.google.gwtorm.server.OrmDuplicateKeyException in project gerrit by GerritCodeReview.

the class ChangeUserName method call.

@Override
public VoidResult call() throws OrmException, NameAlreadyUsedException, InvalidUserNameException, IOException, ConfigInvalidException {
    Collection<ExternalId> old = externalIds.byAccount(user.getAccountId(), SCHEME_USERNAME);
    if (!old.isEmpty()) {
        throw new IllegalStateException(USERNAME_CANNOT_BE_CHANGED);
    }
    ExternalIdsUpdate externalIdsUpdate = externalIdsUpdateFactory.create();
    if (newUsername != null && !newUsername.isEmpty()) {
        if (!USER_NAME_PATTERN.matcher(newUsername).matches()) {
            throw new InvalidUserNameException();
        }
        ExternalId.Key key = ExternalId.Key.create(SCHEME_USERNAME, newUsername);
        try {
            String password = null;
            for (ExternalId i : old) {
                if (i.password() != null) {
                    password = i.password();
                }
            }
            externalIdsUpdate.insert(ExternalId.create(key, user.getAccountId(), null, password));
        } catch (OrmDuplicateKeyException dupeErr) {
            // If we are using this identity, don't report the exception.
            //
            ExternalId other = externalIds.get(key);
            if (other != null && other.accountId().equals(user.getAccountId())) {
                return VoidResult.INSTANCE;
            }
            //
            throw new NameAlreadyUsedException(newUsername);
        }
    }
    // If we have any older user names, remove them.
    //
    externalIdsUpdate.delete(old);
    for (ExternalId extId : old) {
        sshKeyCache.evict(extId.key().id());
        accountCache.evictByUsername(extId.key().id());
    }
    accountCache.evict(user.getAccountId());
    accountCache.evictByUsername(newUsername);
    sshKeyCache.evict(newUsername);
    return VoidResult.INSTANCE;
}
Also used : OrmDuplicateKeyException(com.google.gwtorm.server.OrmDuplicateKeyException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate) NameAlreadyUsedException(com.google.gerrit.common.errors.NameAlreadyUsedException)

Example 2 with OrmDuplicateKeyException

use of com.google.gwtorm.server.OrmDuplicateKeyException in project gerrit by GerritCodeReview.

the class JdbcAccountPatchReviewStore method markReviewed.

@Override
public void markReviewed(PatchSet.Id psId, Account.Id accountId, Collection<String> paths) throws OrmException {
    if (paths == null || paths.isEmpty()) {
        return;
    }
    try (Connection con = ds.getConnection();
        PreparedStatement stmt = con.prepareStatement("INSERT INTO account_patch_reviews " + "(account_id, change_id, patch_set_id, file_name) VALUES " + "(?, ?, ?, ?)")) {
        for (String path : paths) {
            stmt.setInt(1, accountId.get());
            stmt.setInt(2, psId.getParentKey().get());
            stmt.setInt(3, psId.get());
            stmt.setString(4, path);
            stmt.addBatch();
        }
        stmt.executeBatch();
    } catch (SQLException e) {
        OrmException ormException = convertError("insert", e);
        if (ormException instanceof OrmDuplicateKeyException) {
            return;
        }
        throw ormException;
    }
}
Also used : SQLException(java.sql.SQLException) OrmException(com.google.gwtorm.server.OrmException) OrmDuplicateKeyException(com.google.gwtorm.server.OrmDuplicateKeyException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 3 with OrmDuplicateKeyException

use of com.google.gwtorm.server.OrmDuplicateKeyException in project gerrit by GerritCodeReview.

the class Schema_139 method migrateData.

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    ListMultimap<Account.Id, ProjectWatch> imports = MultimapBuilder.hashKeys().arrayListValues().build();
    try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
        ResultSet rs = stmt.executeQuery("SELECT " + "account_id, " + "project_name, " + "filter, " + "notify_abandoned_changes, " + "notify_all_comments, " + "notify_new_changes, " + "notify_new_patch_sets, " + "notify_submitted_changes " + "FROM account_project_watches")) {
        while (rs.next()) {
            Account.Id accountId = new Account.Id(rs.getInt(1));
            ProjectWatch.Builder b = ProjectWatch.builder().project(new Project.NameKey(rs.getString(2))).filter(rs.getString(3)).notifyAbandonedChanges(rs.getBoolean(4)).notifyAllComments(rs.getBoolean(5)).notifyNewChanges(rs.getBoolean(6)).notifyNewPatchSets(rs.getBoolean(7)).notifySubmittedChanges(rs.getBoolean(8));
            imports.put(accountId, b.build());
        }
    }
    if (imports.isEmpty()) {
        return;
    }
    try (Repository git = repoManager.openRepository(allUsersName);
        RevWalk rw = new RevWalk(git)) {
        BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
        bru.setRefLogIdent(serverUser);
        bru.setRefLogMessage(MSG, false);
        for (Map.Entry<Account.Id, Collection<ProjectWatch>> e : imports.asMap().entrySet()) {
            Map<ProjectWatchKey, Set<NotifyType>> projectWatches = new HashMap<>();
            for (ProjectWatch projectWatch : e.getValue()) {
                ProjectWatchKey key = ProjectWatchKey.create(projectWatch.project(), projectWatch.filter());
                if (projectWatches.containsKey(key)) {
                    throw new OrmDuplicateKeyException("Duplicate key for watched project: " + key.toString());
                }
                Set<NotifyType> notifyValues = EnumSet.noneOf(NotifyType.class);
                if (projectWatch.notifyAbandonedChanges()) {
                    notifyValues.add(NotifyType.ABANDONED_CHANGES);
                }
                if (projectWatch.notifyAllComments()) {
                    notifyValues.add(NotifyType.ALL_COMMENTS);
                }
                if (projectWatch.notifyNewChanges()) {
                    notifyValues.add(NotifyType.NEW_CHANGES);
                }
                if (projectWatch.notifyNewPatchSets()) {
                    notifyValues.add(NotifyType.NEW_PATCHSETS);
                }
                if (projectWatch.notifySubmittedChanges()) {
                    notifyValues.add(NotifyType.SUBMITTED_CHANGES);
                }
                projectWatches.put(key, notifyValues);
            }
            try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git, bru)) {
                md.getCommitBuilder().setAuthor(serverUser);
                md.getCommitBuilder().setCommitter(serverUser);
                md.setMessage(MSG);
                WatchConfig watchConfig = new WatchConfig(e.getKey());
                watchConfig.load(md);
                watchConfig.setProjectWatches(projectWatches);
                watchConfig.commit(md);
            }
        }
        bru.execute(rw, NullProgressMonitor.INSTANCE);
    } catch (IOException | ConfigInvalidException ex) {
        throw new OrmException(ex);
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) ResultSet(java.sql.ResultSet) EnumSet(java.util.EnumSet) Set(java.util.Set) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) HashMap(java.util.HashMap) ProjectWatchKey(com.google.gerrit.server.account.WatchConfig.ProjectWatchKey) OrmException(com.google.gwtorm.server.OrmException) ResultSet(java.sql.ResultSet) WatchConfig(com.google.gerrit.server.account.WatchConfig) NotifyType(com.google.gerrit.server.account.WatchConfig.NotifyType) Statement(java.sql.Statement) OrmDuplicateKeyException(com.google.gwtorm.server.OrmDuplicateKeyException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Example 4 with OrmDuplicateKeyException

use of com.google.gwtorm.server.OrmDuplicateKeyException in project gerrit by GerritCodeReview.

the class CreateAccount method apply.

@Override
public Response<AccountInfo> apply(TopLevelResource rsrc, AccountInput input) throws BadRequestException, ResourceConflictException, UnprocessableEntityException, OrmException, IOException, ConfigInvalidException {
    if (input == null) {
        input = new AccountInput();
    }
    if (input.username != null && !username.equals(input.username)) {
        throw new BadRequestException("username must match URL");
    }
    if (!username.matches(Account.USER_NAME_PATTERN)) {
        throw new BadRequestException("Username '" + username + "' must contain only letters, numbers, _, - or .");
    }
    Set<AccountGroup.Id> groups = parseGroups(input.groups);
    Account.Id id = new Account.Id(db.nextAccountId());
    ExternalId extUser = ExternalId.createUsername(username, id, input.httpPassword);
    if (externalIds.get(extUser.key()) != null) {
        throw new ResourceConflictException("username '" + username + "' already exists");
    }
    if (input.email != null) {
        if (externalIds.get(ExternalId.Key.create(SCHEME_MAILTO, input.email)) != null) {
            throw new UnprocessableEntityException("email '" + input.email + "' already exists");
        }
        if (!validator.isValid(input.email)) {
            throw new BadRequestException("invalid email address");
        }
    }
    List<ExternalId> extIds = new ArrayList<>();
    extIds.add(extUser);
    for (AccountExternalIdCreator c : externalIdCreators) {
        extIds.addAll(c.create(id, username, input.email));
    }
    ExternalIdsUpdate externalIdsUpdate = externalIdsUpdateFactory.create();
    try {
        externalIdsUpdate.insert(extIds);
    } catch (OrmDuplicateKeyException duplicateKey) {
        throw new ResourceConflictException("username '" + username + "' already exists");
    }
    if (input.email != null) {
        try {
            externalIdsUpdate.insert(ExternalId.createEmail(id, input.email));
        } catch (OrmDuplicateKeyException duplicateKey) {
            try {
                externalIdsUpdate.delete(extUser);
            } catch (IOException | ConfigInvalidException cleanupError) {
            // Ignored
            }
            throw new UnprocessableEntityException("email '" + input.email + "' already exists");
        }
    }
    Account a = new Account(id, TimeUtil.nowTs());
    a.setFullName(input.name);
    a.setPreferredEmail(input.email);
    accountsUpdate.create().insert(db, a);
    for (AccountGroup.Id groupId : groups) {
        AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, groupId));
        auditService.dispatchAddAccountsToGroup(currentUser.get().getAccountId(), Collections.singleton(m));
        db.accountGroupMembers().insert(Collections.singleton(m));
    }
    if (input.sshKey != null) {
        try {
            authorizedKeys.addKey(id, input.sshKey);
            sshKeyCache.evict(username);
        } catch (InvalidSshKeyException e) {
            throw new BadRequestException(e.getMessage());
        }
    }
    accountCache.evictByUsername(username);
    byEmailCache.evict(input.email);
    indexer.index(id);
    AccountLoader loader = infoLoader.create(true);
    AccountInfo info = loader.get(id);
    loader.fill();
    return Response.created(info);
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) OrmDuplicateKeyException(com.google.gwtorm.server.OrmDuplicateKeyException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate) ArrayList(java.util.ArrayList) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountExternalIdCreator(com.google.gerrit.server.api.accounts.AccountExternalIdCreator) InvalidSshKeyException(com.google.gerrit.common.errors.InvalidSshKeyException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AccountInput(com.google.gerrit.extensions.api.accounts.AccountInput) AccountInfo(com.google.gerrit.extensions.common.AccountInfo)

Example 5 with OrmDuplicateKeyException

use of com.google.gwtorm.server.OrmDuplicateKeyException in project gerrit by GerritCodeReview.

the class CreateGroup method createGroup.

private AccountGroup createGroup(CreateGroupArgs createGroupArgs) throws OrmException, ResourceConflictException, IOException {
    // Do not allow creating groups with the same name as system groups
    for (String name : systemGroupBackend.getNames()) {
        if (name.toLowerCase(Locale.US).equals(createGroupArgs.getGroupName().toLowerCase(Locale.US))) {
            throw new ResourceConflictException("group '" + name + "' already exists");
        }
    }
    for (String name : systemGroupBackend.getReservedNames()) {
        if (name.toLowerCase(Locale.US).equals(createGroupArgs.getGroupName().toLowerCase(Locale.US))) {
            throw new ResourceConflictException("group name '" + name + "' is reserved");
        }
    }
    AccountGroup.Id groupId = new AccountGroup.Id(db.nextAccountGroupId());
    AccountGroup.UUID uuid = GroupUUID.make(createGroupArgs.getGroupName(), self.get().newCommitterIdent(serverIdent.getWhen(), serverIdent.getTimeZone()));
    AccountGroup group = new AccountGroup(createGroupArgs.getGroup(), groupId, uuid, TimeUtil.nowTs());
    group.setVisibleToAll(createGroupArgs.visibleToAll);
    if (createGroupArgs.ownerGroupId != null) {
        AccountGroup ownerGroup = groupCache.get(createGroupArgs.ownerGroupId);
        if (ownerGroup != null) {
            group.setOwnerGroupUUID(ownerGroup.getGroupUUID());
        }
    }
    if (createGroupArgs.groupDescription != null) {
        group.setDescription(createGroupArgs.groupDescription);
    }
    AccountGroupName gn = new AccountGroupName(group);
    // already been used to create another group
    try {
        db.accountGroupNames().insert(Collections.singleton(gn));
    } catch (OrmDuplicateKeyException e) {
        throw new ResourceConflictException("group '" + createGroupArgs.getGroupName() + "' already exists");
    }
    db.accountGroups().insert(Collections.singleton(group));
    addMembers.addMembers(groupId, createGroupArgs.initialMembers);
    groupCache.onCreateGroup(createGroupArgs.getGroup());
    return group;
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountGroupName(com.google.gerrit.reviewdb.client.AccountGroupName) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) OrmDuplicateKeyException(com.google.gwtorm.server.OrmDuplicateKeyException)

Aggregations

OrmDuplicateKeyException (com.google.gwtorm.server.OrmDuplicateKeyException)6 OrmException (com.google.gwtorm.server.OrmException)3 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)2 Account (com.google.gerrit.reviewdb.client.Account)2 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)2 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)2 ExternalIdsUpdate (com.google.gerrit.server.account.externalids.ExternalIdsUpdate)2 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 SQLException (java.sql.SQLException)2 InvalidSshKeyException (com.google.gerrit.common.errors.InvalidSshKeyException)1 NameAlreadyUsedException (com.google.gerrit.common.errors.NameAlreadyUsedException)1 AccountInput (com.google.gerrit.extensions.api.accounts.AccountInput)1 AccountInfo (com.google.gerrit.extensions.common.AccountInfo)1 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)1 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)1 AccountGroupMember (com.google.gerrit.reviewdb.client.AccountGroupMember)1 AccountGroupName (com.google.gerrit.reviewdb.client.AccountGroupName)1 Project (com.google.gerrit.reviewdb.client.Project)1 WatchConfig (com.google.gerrit.server.account.WatchConfig)1