import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.custom.CustomMeasureDto;
import org.sonar.db.metric.MetricDto;
+import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.user.UserSession;
-import org.sonar.server.user.index.UserDoc;
-import org.sonar.server.user.index.UserIndex;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.server.component.ComponentFinder.ParamNames.PROJECT_ID_AND_KEY;
private final System2 system;
private final CustomMeasureValidator validator;
private final CustomMeasureJsonWriter customMeasureJsonWriter;
- private final UserIndex userIndex;
private final ComponentFinder componentFinder;
public CreateAction(DbClient dbClient, UserSession userSession, System2 system, CustomMeasureValidator validator, CustomMeasureJsonWriter customMeasureJsonWriter,
- UserIndex userIndex, ComponentFinder componentFinder) {
+ ComponentFinder componentFinder) {
this.dbClient = dbClient;
this.userSession = userSession;
this.system = system;
this.validator = validator;
this.customMeasureJsonWriter = customMeasureJsonWriter;
- this.userIndex = userIndex;
this.componentFinder = componentFinder;
}
checkPermissions(userSession, component);
checkIsProjectOrModule(component);
checkMeasureDoesNotExistAlready(dbSession, component, metric);
- UserDoc user = userIndex.getByLogin(userSession.getLogin());
+ UserDto user = dbClient.userDao().selectOrFailByLogin(dbSession, userSession.getLogin());
CustomMeasureDto measure = new CustomMeasureDto()
.setComponentUuid(component.uuid())
.setMetricId(metric.getId())
.setDescription(description)
- .setUserLogin(user.login())
+ .setUserLogin(user.getLogin())
.setCreatedAt(now)
.setUpdatedAt(now);
validator.setMeasureValue(measure, valueAsString, metric);
customMeasureJsonWriter.write(json, measure, metric, component, user, true, CustomMeasureJsonWriter.OPTIONAL_FIELDS);
json.close();
} finally {
- MyBatis.closeQuietly(dbSession);
+ dbClient.closeSession(dbSession);
}
}
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.api.measures.Metric;
-import org.sonar.api.user.User;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.custom.CustomMeasureDto;
import org.sonar.db.metric.MetricDto;
+import org.sonar.db.user.UserDto;
import org.sonar.server.metric.ws.MetricJsonWriter;
import org.sonar.server.user.ws.UserJsonWriter;
this.userJsonWriter = userJsonWriter;
}
- public void write(JsonWriter json, CustomMeasureDto measure, MetricDto metric, ComponentDto component, User user, boolean isPending, Collection<String> fieldsToReturn) {
+ public void write(JsonWriter json, CustomMeasureDto measure, MetricDto metric, ComponentDto component, UserDto user, boolean isPending, Collection<String> fieldsToReturn) {
json.beginObject();
json.prop(FIELD_ID, String.valueOf(measure.getId()));
writeIfNeeded(json, measureValue(measure, metric), FIELD_VALUE, fieldsToReturn);
}
}
- public void write(JsonWriter json, List<CustomMeasureDto> customMeasures, ComponentDto project, Map<Integer, MetricDto> metricsById, Map<String, User> usersByLogin,
+ public void write(JsonWriter json, List<CustomMeasureDto> customMeasures, ComponentDto project, Map<Integer, MetricDto> metricsById, Map<String, UserDto> usersByLogin,
@Nullable Long lastAnalysisTimestamp, Collection<String> fieldsToReturn) {
json.name("customMeasures");
json.beginArray();
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import org.sonar.api.user.User;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.custom.CustomMeasureDto;
import org.sonar.db.metric.MetricDto;
+import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.user.UserSession;
-import org.sonar.server.user.index.UserIndex;
import static com.google.common.collect.Sets.newHashSet;
import static org.sonar.server.component.ComponentFinder.ParamNames.PROJECT_ID_AND_KEY;
public static final String PARAM_PROJECT_KEY = "projectKey";
private final DbClient dbClient;
- private final UserIndex userIndex;
private final CustomMeasureJsonWriter customMeasureJsonWriter;
private final UserSession userSession;
private final ComponentFinder componentFinder;
- public SearchAction(DbClient dbClient, UserIndex userIndex, CustomMeasureJsonWriter customMeasureJsonWriter, UserSession userSession, ComponentFinder componentFinder) {
+ public SearchAction(DbClient dbClient, CustomMeasureJsonWriter customMeasureJsonWriter, UserSession userSession, ComponentFinder componentFinder) {
this.dbClient = dbClient;
- this.userIndex = userIndex;
this.customMeasureJsonWriter = customMeasureJsonWriter;
this.userSession = userSession;
this.componentFinder = componentFinder;
Long lastAnalysisDateMs = searchLastSnapshot(dbSession, project);
List<CustomMeasureDto> customMeasures = searchCustomMeasures(dbSession, project, searchOptions);
int nbCustomMeasures = countTotalOfCustomMeasures(dbSession, project);
- Map<String, User> usersByLogin = usersByLogin(customMeasures);
+ Map<String, UserDto> usersByLogin = usersByLogin(dbSession, customMeasures);
Map<Integer, MetricDto> metricsById = metricsById(dbSession, customMeasures);
writeResponse(response, customMeasures, nbCustomMeasures, project, metricsById, usersByLogin, lastAnalysisDateMs, searchOptions, fieldsToReturn);
}
private void writeResponse(Response response, List<CustomMeasureDto> customMeasures, int nbCustomMeasures, ComponentDto project, Map<Integer, MetricDto> metricsById,
- Map<String, User> usersByLogin, @Nullable Long lastAnalysisDate, SearchOptions searchOptions, List<String> fieldsToReturn) {
+ Map<String, UserDto> usersByLogin, @Nullable Long lastAnalysisDate, SearchOptions searchOptions, List<String> fieldsToReturn) {
JsonWriter json = response.newJsonWriter();
json.beginObject();
customMeasureJsonWriter.write(json, customMeasures, project, metricsById, usersByLogin, lastAnalysisDate, fieldsToReturn);
return Maps.uniqueIndex(metrics, MetricToIdFunction.INSTANCE);
}
- private Map<String, User> usersByLogin(List<CustomMeasureDto> customMeasures) {
- return FluentIterable.from(customMeasures)
+ private Map<String, UserDto> usersByLogin(DbSession dbSession, List<CustomMeasureDto> customMeasures) {
+ List<String> logins = FluentIterable.from(customMeasures)
.transform(CustomMeasureToUserLoginFunction.INSTANCE)
- .toMap(new UserLoginToUserFunction());
+ .toList();
+ List<UserDto> userDtos = dbClient.userDao().selectByLogins(dbSession, logins);
+ return FluentIterable.from(userDtos).uniqueIndex(UserDtoToLogin.INSTANCE);
}
private enum CustomMeasureToUserLoginFunction implements Function<CustomMeasureDto, String> {
}
}
- private final class UserLoginToUserFunction implements Function<String, User> {
+ private enum UserDtoToLogin implements Function<UserDto, String> {
+ INSTANCE;
+
@Override
- public User apply(@Nonnull String userLogin) {
- return userIndex.getByLogin(userLogin);
+ public String apply(@Nonnull UserDto input) {
+ return input.getLogin();
}
}
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import org.sonar.api.user.User;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.DbClient;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.custom.CustomMeasureDto;
import org.sonar.db.metric.MetricDto;
+import org.sonar.db.user.UserDto;
import org.sonar.server.user.UserSession;
-import org.sonar.server.user.index.UserIndex;
import static org.sonar.server.measure.custom.ws.CustomMeasureValidator.checkPermissions;
import static org.sonar.server.measure.custom.ws.CustomMeasureValueDescription.measureValueDescription;
private final System2 system;
private final CustomMeasureValidator validator;
private final CustomMeasureJsonWriter customMeasureJsonWriter;
- private final UserIndex userIndex;
- public UpdateAction(DbClient dbClient, UserSession userSession, System2 system, CustomMeasureValidator validator, CustomMeasureJsonWriter customMeasureJsonWriter,
- UserIndex userIndex) {
+ public UpdateAction(DbClient dbClient, UserSession userSession, System2 system, CustomMeasureValidator validator, CustomMeasureJsonWriter customMeasureJsonWriter) {
this.dbClient = dbClient;
this.userSession = userSession;
this.system = system;
this.validator = validator;
this.customMeasureJsonWriter = customMeasureJsonWriter;
- this.userIndex = userIndex;
}
@Override
MetricDto metric = dbClient.metricDao().selectOrFailById(dbSession, customMeasure.getMetricId());
ComponentDto component = dbClient.componentDao().selectOrFailByUuid(dbSession, customMeasure.getComponentUuid());
checkPermissions(userSession, component);
- User user = userIndex.getByLogin(userSession.getLogin());
+ UserDto user = dbClient.userDao().selectOrFailByLogin(dbSession, userSession.getLogin());
setValue(customMeasure, value, metric);
setDescription(customMeasure, description);
- customMeasure.setUserLogin(user.login());
+ customMeasure.setUserLogin(user.getLogin());
customMeasure.setUpdatedAt(system.now());
dbClient.customMeasureDao().update(dbSession, customMeasure);
dbSession.commit();
@Override
public void start() {
- DbSession session = dbClient.openSession(false);
+ DbSession dbSession = dbClient.openSession(false);
try {
- if (hasAlreadyBeenExecuted(session)) {
+ if (hasAlreadyBeenExecuted(dbSession)) {
return;
}
- updateUsersLocal(session);
- markAsExecuted(session);
- session.commit();
+ updateUsersLocal(dbSession);
+ markAsExecuted(dbSession);
+ dbSession.commit();
if (settings.hasKey(LOCAL_USERS_PROPERTY)) {
LOG.info("NOTE : The property '{}' is now no more needed, you can safely remove it.", LOCAL_USERS_PROPERTY);
}
} finally {
- dbClient.closeSession(session);
+ dbClient.closeSession(dbSession);
}
}
- private void updateUsersLocal(DbSession session) {
+ private void updateUsersLocal(DbSession dbSession) {
long now = system2.now();
Set<String> localUsers = new HashSet<>(asList(settings.getStringArray(LOCAL_USERS_PROPERTY)));
boolean isRealmExist = settings.getString(CORE_AUTHENTICATOR_REALM) != null;
- for (UserDto user : dbClient.userDao().selectUsers(session, UserQuery.ALL_ACTIVES)) {
+ for (UserDto user : dbClient.userDao().selectUsers(dbSession, UserQuery.ALL_ACTIVES)) {
if (user.getExternalIdentityProvider().equals(UserUpdater.SQ_AUTHORITY)) {
user.setLocal(!isRealmExist || localUsers.contains(user.getLogin()));
} else {
user.setLocal(false);
}
user.setUpdatedAt(now);
- dbClient.userDao().update(session, user);
+ dbClient.userDao().update(dbSession, user);
}
}
- private boolean hasAlreadyBeenExecuted(DbSession session) {
- return dbClient.loadedTemplateDao().countByTypeAndKey(ONE_SHOT_TASK_TYPE, TEMPLATE_KEY, session) > 0;
+ private boolean hasAlreadyBeenExecuted(DbSession dbSession) {
+ return dbClient.loadedTemplateDao().countByTypeAndKey(ONE_SHOT_TASK_TYPE, TEMPLATE_KEY, dbSession) > 0;
}
- private void markAsExecuted(DbSession session) {
- dbClient.loadedTemplateDao().insert(new LoadedTemplateDto(TEMPLATE_KEY, ONE_SHOT_TASK_TYPE), session);
+ private void markAsExecuted(DbSession dbSession) {
+ dbClient.loadedTemplateDao().insert(new LoadedTemplateDto(TEMPLATE_KEY, ONE_SHOT_TASK_TYPE), dbSession);
}
@Override
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.core.permission.GlobalPermissions;
+import org.sonar.db.DbClient;
+import org.sonar.db.DbSession;
+import org.sonar.db.user.UserDto;
import org.sonar.server.user.NewUser;
import org.sonar.server.user.UserSession;
import org.sonar.server.user.UserUpdater;
-import org.sonar.server.user.index.UserDoc;
-import org.sonar.server.user.index.UserIndex;
public class CreateAction implements UsersWsAction {
private static final String PARAM_SCM_ACCOUNTS = "scmAccounts";
private static final String PARAM_SCM_ACCOUNTS_DEPRECATED = "scm_accounts";
- private final UserIndex index;
+ private final DbClient dbClient;
private final UserUpdater userUpdater;
private final I18n i18n;
private final UserSession userSession;
private final UserJsonWriter userWriter;
- public CreateAction(UserIndex index, UserUpdater userUpdater, I18n i18n, UserSession userSession, UserJsonWriter userWriter) {
- this.index = index;
+ public CreateAction(DbClient dbClient, UserUpdater userUpdater, I18n i18n, UserSession userSession, UserJsonWriter userWriter) {
+ this.dbClient = dbClient;
this.userUpdater = userUpdater;
this.i18n = i18n;
this.userSession = userSession;
}
private void writeResponse(Response response, String login, boolean isUserReactivated) {
- UserDoc user = index.getByLogin(login);
+ UserDto user = loadUser(login);
JsonWriter json = response.newJsonWriter().beginObject();
writeUser(json, user);
if (isUserReactivated) {
json.endObject().close();
}
- private void writeUser(JsonWriter json, UserDoc user) {
+ private void writeUser(JsonWriter json, UserDto user) {
json.name("user");
userWriter.write(json, user, ImmutableSet.<String>of(), UserJsonWriter.FIELDS);
}
json.endObject();
json.endArray();
}
+
+ private UserDto loadUser(String login){
+ DbSession dbSession = dbClient.openSession(false);
+ try {
+ return dbClient.userDao().selectOrFailByLogin(dbSession, login);
+ } finally {
+ dbClient.closeSession(dbSession);
+ }
+ }
}
if (!isNullOrEmpty(user.getEmail())) {
json.prop("email", user.getEmail());
}
+ json.prop("local", user.isLocal());
}
writeScmAccounts(json, optionalUser);
package org.sonar.server.user.ws;
import com.google.common.collect.Sets;
-import java.util.Arrays;
import java.util.Set;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
+import org.sonar.db.user.UserDto;
import org.sonar.server.exceptions.BadRequestException;
+import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import org.sonar.server.user.UserUpdater;
-import org.sonar.server.user.index.UserDoc;
-import org.sonar.server.user.index.UserIndex;
+
+import static java.lang.String.format;
+import static java.util.Collections.singletonList;
public class DeactivateAction implements UsersWsAction {
private static final String PARAM_LOGIN = "login";
- private final UserIndex index;
private final UserUpdater userUpdater;
private final UserSession userSession;
private final UserJsonWriter userWriter;
private final DbClient dbClient;
- public DeactivateAction(UserIndex index, UserUpdater userUpdater, UserSession userSession, UserJsonWriter userWriter, DbClient dbClient) {
- this.index = index;
+ public DeactivateAction(UserUpdater userUpdater, UserSession userSession, UserJsonWriter userWriter, DbClient dbClient) {
this.userUpdater = userUpdater;
this.userSession = userSession;
this.userWriter = userWriter;
}
private void writeResponse(Response response, String login) {
- UserDoc user = index.getByLogin(login);
JsonWriter json = response.newJsonWriter().beginObject();
- writeUser(json, user);
+ writeUser(json, login);
json.endObject().close();
}
- private void writeUser(JsonWriter json, UserDoc user) {
+ private void writeUser(JsonWriter json, String login) {
json.name("user");
Set<String> groups = Sets.newHashSet();
DbSession dbSession = dbClient.openSession(false);
try {
- groups.addAll(dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, Arrays.asList(user.login())).get(user.login()));
+ UserDto user = dbClient.userDao().selectByLogin(dbSession, login);
+ if (user == null) {
+ throw new NotFoundException(format("User '%s' doesn't exist", login));
+ }
+ groups.addAll(dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, singletonList(login)).get(login));
+ userWriter.write(json, user, groups, UserJsonWriter.FIELDS);
} finally {
- MyBatis.closeQuietly(dbSession);
+ dbClient.closeSession(dbSession);
}
- userWriter.write(json, user, groups, UserJsonWriter.FIELDS);
}
}
package org.sonar.server.user.ws;
import com.google.common.base.Function;
-import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import java.util.Collection;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
+import org.sonar.db.user.UserDto;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.es.SearchResult;
import org.sonar.server.user.index.UserDoc;
List<String> fields = request.paramAsStrings(Param.FIELDS);
SearchResult<UserDoc> result = userIndex.search(request.param(Param.TEXT_QUERY), options);
- Multimap<String, String> groupsByLogin = ArrayListMultimap.create();
- Map<String, Integer> tokenCountsByLogin = new HashMap<>();
DbSession dbSession = dbClient.openSession(false);
try {
- List<String> logins = Lists.transform(result.getDocs(), new Function<UserDoc, String>() {
- @Override
- public String apply(@Nonnull UserDoc input) {
- return input.login();
- }
- });
- groupsByLogin = dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, logins);
- tokenCountsByLogin = dbClient.userTokenDao().countTokensByLogins(dbSession, logins);
+ List<String> logins = Lists.transform(result.getDocs(), UserDocToLogin.INSTANCE);
+ Multimap<String, String> groupsByLogin = dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, logins);
+ Map<String, Integer> tokenCountsByLogin = dbClient.userTokenDao().countTokensByLogins(dbSession, logins);
+ JsonWriter json = response.newJsonWriter().beginObject();
+ options.writeJson(json, result.getTotal());
+ List<UserDto> userDtos = dbClient.userDao().selectByOrderedLogins(dbSession, logins);
+ writeUsers(json, userDtos, groupsByLogin, tokenCountsByLogin, fields);
+ json.endObject().close();
} finally {
dbClient.closeSession(dbSession);
}
-
- JsonWriter json = response.newJsonWriter().beginObject();
- options.writeJson(json, result.getTotal());
- writeUsers(json, result, groupsByLogin, tokenCountsByLogin, fields);
- json.endObject().close();
}
- private void writeUsers(JsonWriter json, SearchResult<UserDoc> result, Multimap<String, String> groupsByLogin, Map<String, Integer> tokenCountsByLogin,
+ private void writeUsers(JsonWriter json, List<UserDto> userDtos, Multimap<String, String> groupsByLogin, Map<String, Integer> tokenCountsByLogin,
@Nullable List<String> fields) {
json.name("users").beginArray();
- for (UserDoc user : result.getDocs()) {
- Collection<String> groups = groupsByLogin.get(user.login());
- userWriter.write(json, user, firstNonNull(tokenCountsByLogin.get(user.login()), 0), groups, fields);
+ for (UserDto user : userDtos) {
+ Collection<String> groups = groupsByLogin.get(user.getLogin());
+ userWriter.write(json, user, firstNonNull(tokenCountsByLogin.get(user.getLogin()), 0), groups, fields);
}
json.endArray();
}
+
+ private enum UserDocToLogin implements Function<UserDoc, String> {
+ INSTANCE;
+
+ @Override
+ public String apply(@Nonnull UserDoc input) {
+ return input.login();
+ }
+ }
}
package org.sonar.server.user.ws;
import com.google.common.collect.Sets;
-import java.util.Arrays;
import java.util.Set;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
-import org.sonar.db.MyBatis;
+import org.sonar.db.user.UserDto;
+import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UpdateUser;
import org.sonar.server.user.UserSession;
import org.sonar.server.user.UserUpdater;
-import org.sonar.server.user.index.UserDoc;
-import org.sonar.server.user.index.UserIndex;
import static com.google.common.base.Strings.emptyToNull;
+import static java.lang.String.format;
+import static java.util.Collections.singletonList;
public class UpdateAction implements UsersWsAction {
private static final String PARAM_SCM_ACCOUNTS = "scmAccounts";
private static final String PARAM_SCM_ACCOUNTS_DEPRECATED = "scm_accounts";
- private final UserIndex index;
private final UserUpdater userUpdater;
private final UserSession userSession;
private final UserJsonWriter userWriter;
private final DbClient dbClient;
- public UpdateAction(UserIndex index, UserUpdater userUpdater, UserSession userSession, UserJsonWriter userWriter, DbClient dbClient) {
- this.index = index;
+ public UpdateAction(UserUpdater userUpdater, UserSession userSession, UserJsonWriter userWriter, DbClient dbClient) {
this.userUpdater = userUpdater;
this.userSession = userSession;
this.userWriter = userWriter;
}
private void writeResponse(Response response, String login) {
- UserDoc user = index.getByLogin(login);
JsonWriter json = response.newJsonWriter().beginObject();
- writeUser(json, user);
+ writeUser(json, login);
json.endObject().close();
}
- private void writeUser(JsonWriter json, UserDoc user) {
+ private void writeUser(JsonWriter json, String login) {
json.name("user");
Set<String> groups = Sets.newHashSet();
DbSession dbSession = dbClient.openSession(false);
try {
- groups.addAll(dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, Arrays.asList(user.login())).get(user.login()));
+ UserDto user = dbClient.userDao().selectByLogin(dbSession, login);
+ if (user == null) {
+ throw new NotFoundException(format("User '%s' doesn't exist", login));
+ }
+ groups.addAll(dbClient.groupMembershipDao().selectGroupsByLogins(dbSession, singletonList(login)).get(login));
+ userWriter.write(json, user, groups, UserJsonWriter.FIELDS);
} finally {
- MyBatis.closeQuietly(dbSession);
+ dbClient.closeSession(dbSession);
}
- userWriter.write(json, user, groups, UserJsonWriter.FIELDS);
}
}
import java.util.Collections;
import java.util.Set;
import javax.annotation.Nullable;
-import org.sonar.api.user.User;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.core.permission.GlobalPermissions;
+import org.sonar.db.user.UserDto;
import org.sonar.server.user.UserSession;
-import org.sonar.server.user.index.UserDoc;
import static org.sonar.server.ws.JsonWriterUtils.isFieldNeeded;
import static org.sonar.server.ws.JsonWriterUtils.writeIfNeeded;
private static final String FIELD_GROUPS = "groups";
private static final String FIELD_ACTIVE = "active";
private static final String FIELD_TOKENS_COUNT = "tokensCount";
+ private static final String FIELD_LOCAL = "local";
- public static final Set<String> FIELDS = ImmutableSet.of(FIELD_NAME, FIELD_EMAIL, FIELD_SCM_ACCOUNTS, FIELD_GROUPS, FIELD_ACTIVE);
+ public static final Set<String> FIELDS = ImmutableSet.of(FIELD_NAME, FIELD_EMAIL, FIELD_SCM_ACCOUNTS, FIELD_GROUPS, FIELD_ACTIVE, FIELD_LOCAL);
private static final Set<String> CONCISE_FIELDS = ImmutableSet.of(FIELD_NAME, FIELD_EMAIL, FIELD_ACTIVE);
private final UserSession userSession;
/**
* Serializes a user to the passed JsonWriter.
*/
- public void write(JsonWriter json, User user, Collection<String> groups, @Nullable Collection<String> fields) {
+ public void write(JsonWriter json, UserDto user, Collection<String> groups, @Nullable Collection<String> fields) {
write(json, user, null, groups, fields);
}
/**
* Serializes a user to the passed JsonWriter.
*/
- public void write(JsonWriter json, User user, @Nullable Integer tokensCount, Collection<String> groups, @Nullable Collection<String> fields) {
+ public void write(JsonWriter json, UserDto user, @Nullable Integer tokensCount, Collection<String> groups, @Nullable Collection<String> fields) {
json.beginObject();
- json.prop(FIELD_LOGIN, user.login());
- writeIfNeeded(json, user.name(), FIELD_NAME, fields);
- writeIfNeeded(json, user.email(), FIELD_EMAIL, fields);
- writeIfNeeded(json, user.active(), FIELD_ACTIVE, fields);
+ json.prop(FIELD_LOGIN, user.getLogin());
+ writeIfNeeded(json, user.getName(), FIELD_NAME, fields);
+ writeIfNeeded(json, user.getEmail(), FIELD_EMAIL, fields);
+ writeIfNeeded(json, user.isActive(), FIELD_ACTIVE, fields);
+ writeIfNeeded(json, user.isLocal(), FIELD_LOCAL, fields);
writeGroupsIfNeeded(json, groups, fields);
writeScmAccountsIfNeeded(json, fields, user);
writeTokensCount(json, tokensCount);
}
/**
- * A shortcut to {@link #write(JsonWriter, User, Collection, Collection)} with preselected fields and without group information
+ * A shortcut to {@link #write(JsonWriter, UserDto, Collection, Collection)} with preselected fields and without group information
*/
- public void write(JsonWriter json, @Nullable User user) {
+ public void write(JsonWriter json, @Nullable UserDto user) {
if (user == null) {
json.beginObject().endObject();
} else {
}
}
- private static void writeScmAccountsIfNeeded(JsonWriter json, Collection<String> fields, User user) {
+ private static void writeScmAccountsIfNeeded(JsonWriter json, Collection<String> fields, UserDto user) {
if (isFieldNeeded(FIELD_SCM_ACCOUNTS, fields)) {
json.name(FIELD_SCM_ACCOUNTS)
.beginArray()
- .values(((UserDoc) user).scmAccounts())
+ .values(user.getScmAccountsAsList())
.endArray();
}
}
// Utility class
}
- public static void writeIfNeeded(JsonWriter json, @Nullable String value, String field, Collection<String> fields) {
+ public static void writeIfNeeded(JsonWriter json, @Nullable String value, String field, @Nullable Collection<String> fields) {
if (isFieldNeeded(field, fields)) {
json.prop(field, value);
}
}
- public static void writeIfNeeded(JsonWriter json, @Nullable Boolean value, String field, Collection<String> fields) {
+ public static void writeIfNeeded(JsonWriter json, @Nullable Boolean value, String field, @Nullable Collection<String> fields) {
if (isFieldNeeded(field, fields)) {
json.prop(field, value);
}
}
- public static void writeIfNeeded(JsonWriter json, @Nullable Integer value, String field, Collection<String> fields) {
+ public static void writeIfNeeded(JsonWriter json, @Nullable Integer value, String field, @Nullable Collection<String> fields) {
if (isFieldNeeded(field, fields)) {
json.prop(field, value);
}
}
- public static void writeIfNeeded(JsonWriter json, @Nullable Long value, String field, Collection<String> fields) {
+ public static void writeIfNeeded(JsonWriter json, @Nullable Long value, String field, @Nullable Collection<String> fields) {
if (isFieldNeeded(field, fields)) {
json.prop(field, value);
}
}
- public static void writeIfNeeded(JsonWriter json, @Nullable Date value, String field, Collection<String> fields) {
+ public static void writeIfNeeded(JsonWriter json, @Nullable Date value, String field, @Nullable Collection<String> fields) {
if (isFieldNeeded(field, fields)) {
json.propDateTime(field, value);
}
"login": "obiwan.kenobi",
"name": "Obiwan Kenobi",
"email": "obiwan.kenobi@starwars.com",
+ "local": true,
"scmAccounts": [
"obiwan:github",
"obiwan:bitbucket"
"name": "Ada Lovelace",
"email": "ada.lovelace@noteg.com",
"scmAccounts": ["ada.lovelace"],
- "active": true
+ "active": true,
+ "local": true
}
}
"sonar-users",
"sonar-administrators"
],
- "tokensCount": 1
+ "tokensCount": 1,
+ "local": true
},
{
"login": "sbrandhof",
"groups": [
"sonar-users"
],
- "tokensCount": 3
+ "tokensCount": 3,
+ "local": false
}
]
}
import org.assertj.core.data.Offset;
import org.junit.After;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.measure.custom.CustomMeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.metric.MetricTesting;
+import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.exceptions.ServerException;
import org.sonar.server.tester.UserSessionRule;
-import org.sonar.server.user.index.UserDoc;
-import org.sonar.server.user.index.UserIndex;
import org.sonar.server.user.index.UserIndexDefinition;
import org.sonar.server.user.ws.UserJsonWriter;
import org.sonar.server.ws.WsTester;
import static org.sonar.api.measures.Metric.ValueType.WORK_DUR;
import static org.sonar.server.util.TypeValidationsTesting.newFullTypeValidations;
-
public class CreateActionTest {
private static final String DEFAULT_PROJECT_UUID = "project-uuid";
WsTester ws;
- @BeforeClass
- public static void setUpClass() throws Exception {
- es.putDocuments(UserIndexDefinition.INDEX, UserIndexDefinition.TYPE_USER, new UserDoc()
- .setLogin("login")
- .setName("Login")
- .setEmail("login@login.com")
- .setActive(true));
- }
-
@Before
public void setUp() {
ws = new WsTester(new CustomMeasuresWs(new CreateAction(dbClient, userSession, System2.INSTANCE, new CustomMeasureValidator(newFullTypeValidations()),
- new CustomMeasureJsonWriter(new UserJsonWriter(userSession)), new UserIndex(es.client()), new ComponentFinder(dbClient))));
+ new CustomMeasureJsonWriter(new UserJsonWriter(userSession)), new ComponentFinder(dbClient))));
db.truncateTables();
userSession.login("login").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
+
+ db.getDbClient().userDao().insert(dbSession, new UserDto()
+ .setLogin("login")
+ .setName("Login")
+ .setEmail("login@login.com")
+ .setActive(true)
+ );
+ dbSession.commit();
}
@After
return ws.newPostRequest(CustomMeasuresWs.ENDPOINT, CreateAction.ACTION);
}
- private MetricDto insertMetric(ValueType metricType){
+ private MetricDto insertMetric(ValueType metricType) {
MetricDto metric = MetricTesting.newMetricDto().setEnabled(true).setValueType(metricType.name()).setKey("metric-key");
dbClient.metricDao().insert(dbSession, metric);
dbSession.commit();
return metric;
}
- private void insertProject(String projectUuid){
+ private void insertProject(String projectUuid) {
dbClient.componentDao().insert(dbSession, ComponentTesting.newProjectDto(projectUuid).setKey(DEFAULT_PROJECT_KEY));
dbSession.commit();
}
import org.sonar.db.DbClient;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
-import org.sonar.server.user.index.UserIndex;
import org.sonar.server.ws.WsTester;
import static org.assertj.core.api.Assertions.assertThat;
UserSession userSession = mock(UserSession.class);
ws = new WsTester(new CustomMeasuresWs(
new DeleteAction(dbClient, userSession),
- new CreateAction(dbClient, userSession, System2.INSTANCE, mock(CustomMeasureValidator.class), mock(CustomMeasureJsonWriter.class), mock(UserIndex.class), mock(ComponentFinder.class)),
- new UpdateAction(dbClient, userSession, System2.INSTANCE, mock(CustomMeasureValidator.class), mock(CustomMeasureJsonWriter.class), mock(UserIndex.class))
+ new CreateAction(dbClient, userSession, System2.INSTANCE, mock(CustomMeasureValidator.class), mock(CustomMeasureJsonWriter.class), mock(ComponentFinder.class)),
+ new UpdateAction(dbClient, userSession, System2.INSTANCE, mock(CustomMeasureValidator.class), mock(CustomMeasureJsonWriter.class))
));
}
import java.util.Date;
import org.apache.commons.lang.StringUtils;
-import org.junit.After;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.component.ComponentDao;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
-import org.sonar.db.component.SnapshotDao;
import org.sonar.db.component.SnapshotTesting;
-import org.sonar.db.measure.custom.CustomMeasureDao;
import org.sonar.db.measure.custom.CustomMeasureDto;
-import org.sonar.db.metric.MetricDao;
import org.sonar.db.metric.MetricDto;
+import org.sonar.db.user.UserDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
-import org.sonar.server.user.index.UserDoc;
-import org.sonar.server.user.index.UserIndex;
import org.sonar.server.user.index.UserIndexDefinition;
import org.sonar.server.user.ws.UserJsonWriter;
import org.sonar.server.ws.WsTester;
public static EsTester es = new EsTester().addDefinitions(new UserIndexDefinition(new Settings()));
WsTester ws;
- DbClient dbClient;
- DbSession dbSession;
+ DbClient dbClient = db.getDbClient();
+ DbSession dbSession = db.getSession();
ComponentDto defaultProject;
- @BeforeClass
- public static void setUpClass() throws Exception {
- es.putDocuments(UserIndexDefinition.INDEX, UserIndexDefinition.TYPE_USER, new UserDoc()
- .setLogin("login")
- .setName("Login")
- .setEmail("login@login.com")
- .setActive(true));
- }
-
@Before
public void setUp() {
- dbClient = new DbClient(db.database(), db.myBatis(), new CustomMeasureDao(), new ComponentDao(), new MetricDao(), new SnapshotDao());
- dbSession = dbClient.openSession(false);
db.truncateTables();
CustomMeasureJsonWriter customMeasureJsonWriter = new CustomMeasureJsonWriter(new UserJsonWriter(userSessionRule));
- UserIndex userIndex = new UserIndex(es.client());
- ws = new WsTester(new CustomMeasuresWs(new SearchAction(dbClient, userIndex, customMeasureJsonWriter, userSessionRule, new ComponentFinder(dbClient))));
+ ws = new WsTester(new CustomMeasuresWs(new SearchAction(dbClient, customMeasureJsonWriter, userSessionRule, new ComponentFinder(dbClient))));
defaultProject = insertDefaultProject();
userSessionRule.login("login").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
- }
- @After
- public void tearDown() {
- dbSession.close();
+ db.getDbClient().userDao().insert(dbSession, new UserDto()
+ .setLogin("login")
+ .setName("Login")
+ .setEmail("login@login.com")
+ .setActive(true)
+ );
+ dbSession.commit();
}
@Test
}
private static MetricDto newCustomMetric(String metricKey) {
- return newMetricDto().setEnabled(true).setUserManaged(true).setKey(metricKey).setDomain(metricKey + "-domain").setShortName(metricKey + "-name").setValueType(ValueType.STRING.name());
+ return newMetricDto().setEnabled(true).setUserManaged(true).setKey(metricKey).setDomain(metricKey + "-domain").setShortName(metricKey + "-name")
+ .setValueType(ValueType.STRING.name());
}
private CustomMeasureDto insertCustomMeasure(int id, MetricDto metric) {
package org.sonar.server.measure.custom.ws;
import org.junit.Before;
-import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.db.measure.custom.CustomMeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.metric.MetricTesting;
+import org.sonar.db.user.UserDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.exceptions.ServerException;
import org.sonar.server.exceptions.UnauthorizedException;
import org.sonar.server.tester.UserSessionRule;
-import org.sonar.server.user.index.UserDoc;
-import org.sonar.server.user.index.UserIndex;
import org.sonar.server.user.index.UserIndexDefinition;
import org.sonar.server.user.ws.UserJsonWriter;
import org.sonar.server.ws.WsTester;
import static org.sonar.server.measure.custom.ws.UpdateAction.PARAM_VALUE;
import static org.sonar.server.util.TypeValidationsTesting.newFullTypeValidations;
-
public class UpdateActionTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
System2 system = mock(System2.class);
WsTester ws;
- @BeforeClass
- public static void setUpClass() throws Exception {
- es.putDocuments(UserIndexDefinition.INDEX, UserIndexDefinition.TYPE_USER, new UserDoc()
- .setLogin("login")
- .setName("Login")
- .setEmail("login@login.com")
- .setActive(true));
- }
-
@Before
public void setUp() {
CustomMeasureValidator validator = new CustomMeasureValidator(newFullTypeValidations());
- ws = new WsTester(new CustomMeasuresWs(new UpdateAction(dbClient, userSessionRule, system, validator, new CustomMeasureJsonWriter(new UserJsonWriter(userSessionRule)),
- new UserIndex(es.client()))));
+ ws = new WsTester(new CustomMeasuresWs(new UpdateAction(dbClient, userSessionRule, system, validator, new CustomMeasureJsonWriter(new UserJsonWriter(userSessionRule)))));
userSessionRule.login("login").setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
+
+ db.getDbClient().userDao().insert(dbSession, new UserDto()
+ .setLogin("login")
+ .setName("Login")
+ .setEmail("login@login.com")
+ .setActive(true)
+ );
+ dbSession.commit();
}
@Test
userIndexer = (UserIndexer) new UserIndexer(dbClient, esTester.client()).setEnabled(true);
index = new UserIndex(esTester.client());
- tester = new WsTester(new UsersWs(new CreateAction(index,
+ tester = new WsTester(new UsersWs(new CreateAction(dbClient,
new UserUpdater(mock(NewUserNotifier.class), settings, dbClient, userIndexer, system2, mock(SecurityRealmFactory.class)),
i18n, userSessionRule, new UserJsonWriter(userSessionRule))));
controller = tester.controller("api/users");
-
}
@After
import static org.mockito.Mockito.mock;
import static org.sonar.db.user.UserTokenTesting.newUserToken;
-
public class DeactivateActionTest {
static final Settings settings = new Settings();
userIndexer = (UserIndexer) new UserIndexer(dbClient, esTester.client()).setEnabled(true);
index = new UserIndex(esTester.client());
- ws = new WsTester(new UsersWs(new DeactivateAction(index,
+ ws = new WsTester(new UsersWs(new DeactivateAction(
new UserUpdater(mock(NewUserNotifier.class), settings, dbClient, userIndexer, system2, mock(SecurityRealmFactory.class)), userSessionRule,
new UserJsonWriter(userSessionRule), dbClient)));
controller = ws.controller("api/users");
-
}
@Test
.setLogin(login)
.setName(name)
.setScmAccounts(scmAccounts)
+ .setLocal(true)
.setUpdatedAt(createdAt)));
users[index] = new UserDoc()
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
-import org.sonar.db.user.GroupDao;
import org.sonar.db.user.GroupDto;
-import org.sonar.db.user.GroupMembershipDao;
-import org.sonar.db.user.UserDao;
import org.sonar.db.user.UserDto;
-import org.sonar.db.user.UserGroupDao;
import org.sonar.server.es.EsTester;
import org.sonar.server.exceptions.ForbiddenException;
+import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.user.NewUserNotifier;
import org.sonar.server.user.SecurityRealmFactory;
import org.sonar.server.user.UserUpdater;
-import org.sonar.server.user.index.UserIndex;
import org.sonar.server.user.index.UserIndexDefinition;
import org.sonar.server.user.index.UserIndexer;
import org.sonar.server.ws.WsTester;
static final Settings settings = new Settings().setProperty("sonar.defaultGroup", "sonar-users");
+ System2 system2 = new System2();
+
@Rule
- public DbTester dbTester = DbTester.create(System2.INSTANCE);
+ public DbTester dbTester = DbTester.create(system2);
@ClassRule
public static final EsTester esTester = new EsTester().addDefinitions(new UserIndexDefinition(settings));
@Rule
public final UserSessionRule userSessionRule = UserSessionRule.standalone().login("admin")
.setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);
- WebService.Controller controller;
+ DbClient dbClient = dbTester.getDbClient();
- WsTester tester;
+ DbSession session = dbTester.getSession();
- UserIndex index;
+ WebService.Controller controller;
- DbClient dbClient;
+ WsTester tester;
UserIndexer userIndexer;
- DbSession session;
-
@Before
public void setUp() {
dbTester.truncateTables();
esTester.truncateIndices();
- System2 system2 = new System2();
- UserDao userDao = new UserDao(dbTester.myBatis(), system2);
- UserGroupDao userGroupDao = new UserGroupDao();
- GroupDao groupDao = new GroupDao(system2);
- dbClient = new DbClient(dbTester.database(), dbTester.myBatis(), userDao, userGroupDao, groupDao, new GroupMembershipDao(dbTester.myBatis()));
- session = dbClient.openSession(false);
- groupDao.insert(session, new GroupDto().setName("sonar-users"));
+ dbClient.groupDao().insert(session, new GroupDto().setName("sonar-users"));
session.commit();
userIndexer = (UserIndexer) new UserIndexer(dbClient, esTester.client()).setEnabled(true);
- index = new UserIndex(esTester.client());
- tester = new WsTester(new UsersWs(new UpdateAction(index,
+ tester = new WsTester(new UsersWs(new UpdateAction(
new UserUpdater(mock(NewUserNotifier.class), settings, dbClient, userIndexer, system2, mock(SecurityRealmFactory.class)), userSessionRule,
new UserJsonWriter(userSessionRule), dbClient)));
controller = tester.controller("api/users");
.assertJson(getClass(), "update_scm_accounts.json");
}
+ @Test(expected = NotFoundException.class)
+ public void fail_on_unknown_user() throws Exception {
+ tester.newPostRequest("api/users", "update")
+ .setParam("login", "john")
+ .execute();
+ }
+
private void createUser() {
dbClient.userDao().insert(session, new UserDto()
.setEmail("john@email.com")
@Before
public void setUp() {
WsTester tester = new WsTester(new UsersWs(
- new CreateAction(mock(UserIndex.class), mock(UserUpdater.class), mock(I18n.class), userSessionRule, mock(UserJsonWriter.class)),
- new UpdateAction(mock(UserIndex.class), mock(UserUpdater.class), userSessionRule, mock(UserJsonWriter.class), mock(DbClient.class)),
+ new CreateAction(mock(DbClient.class), mock(UserUpdater.class), mock(I18n.class), userSessionRule, mock(UserJsonWriter.class)),
+ new UpdateAction(mock(UserUpdater.class), userSessionRule, mock(UserJsonWriter.class), mock(DbClient.class)),
new CurrentAction(userSessionRule, mock(org.sonar.db.DbClient.class)),
- new DeactivateAction(mock(UserIndex.class), mock(UserUpdater.class), userSessionRule, mock(UserJsonWriter.class), mock(DbClient.class)),
+ new DeactivateAction(mock(UserUpdater.class), userSessionRule, mock(UserJsonWriter.class), mock(DbClient.class)),
new ChangePasswordAction(mock(UserUpdater.class), userSessionRule),
new SearchAction(mock(UserIndex.class), mock(DbClient.class), mock(UserJsonWriter.class))));
controller = tester.controller("api/users");
"name": "John",
"email": "john@email.com",
"scmAccounts": ["jn"],
- "active": true
+ "active": true,
+ "local": true
}
}
"name": "John",
"email": "john@email.com",
"scmAccounts": ["jn"],
- "active": true
+ "active": true,
+ "local": true
},
"infos": [
{
"login": "john",
"name": "John",
"scmAccounts": [],
- "active": false
+ "active": false,
+ "local": true
}
}
"scmAccounts": [
"user-0"
],
- "tokensCount": 0
+ "tokensCount": 0,
+ "local": true
},
{
"login": "user-1",
"scmAccounts": [
"user-1"
],
- "tokensCount": 1
+ "tokensCount": 1,
+ "local": true
},
{
"login": "user-2",
"scmAccounts": [
"user-2"
],
- "tokensCount": 2
+ "tokensCount": 2,
+ "local": true
},
{
"login": "user-3",
"scmAccounts": [
"user-3"
],
- "tokensCount": 3
+ "tokensCount": 3,
+ "local": true
},
{
"login": "user-4",
"scmAccounts": [
"user-4"
],
- "tokensCount": 4
+ "tokensCount": 4,
+ "local": true
}
]
}
"email": "user-0@mail.com",
"scmAccounts": [
"user-0"
- ]
+ ],
+ "local": true
},
{
"login": "user-1",
"email": "user-1@mail.com",
"scmAccounts": [
"user-1"
- ]
+ ],
+ "local": true
},
{
"login": "user-2",
"email": "user-2@mail.com",
"scmAccounts": [
"user-2"
- ]
+ ],
+ "local": true
},
{
"login": "user-3",
"email": "user-3@mail.com",
"scmAccounts": [
"user-3"
- ]
+ ],
+ "local": true
},
{
"login": "user-4",
"email": "user-4@mail.com",
"scmAccounts": [
"user-4"
- ]
+ ],
+ "local": true
}
]
}
"email": "user-5@mail.com",
"scmAccounts": [
"user-5"
- ]
+ ],
+ "local": true
},
{
"login": "user-6",
"email": "user-6@mail.com",
"scmAccounts": [
"user-6"
- ]
+ ],
+ "local": true
},
{
"login": "user-7",
"email": "user-7@mail.com",
"scmAccounts": [
"user-7"
- ]
+ ],
+ "local": true
},
{
"login": "user-8",
"email": "user-8@mail.com",
"scmAccounts": [
"user-8"
- ]
+ ],
+ "local": true
},
{
"login": "user-9",
"email": "user-9@mail.com",
"scmAccounts": [
"user-9"
- ]
+ ],
+ "local": true
}
]
}
"email": "user@mail.com",
"active": true,
"scmAccounts": ["user1"],
- "tokensCount": 0
+ "tokensCount": 0,
+ "local": true
}
]
}
"scmAccounts": [
"user-0"
],
- "groups": ["sonar-admins", "sonar-users"]
+ "groups": ["sonar-admins", "sonar-users"],
+ "local": true
}
]
}
"active": true,
"scmAccounts": [
"jn"
- ]
+ ],
+ "local": true
}
}
"active": true,
"scmAccounts": [
"jn"
- ]
+ ],
+ "local": true
}
}
"active": true,
"scmAccounts": [
"jn"
- ]
+ ],
+ "local": true
}
}
"active": true,
"scmAccounts": [
"jon.snow"
- ]
+ ],
+ "local": true
}
}
"name": "Jon Snow",
"email": "jon.snow@thegreatw.all",
"scmAccounts": ["jon.snow"],
- "active": true
+ "active": true,
+ "local": true
}
}
package org.sonar.db.user;
import com.google.common.base.Function;
+import com.google.common.base.Predicates;
import java.util.Collection;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import org.apache.ibatis.session.SqlSession;
import org.sonar.db.MyBatis;
import org.sonar.db.RowNotFoundException;
+import static com.google.common.collect.FluentIterable.from;
+
public class UserDao implements Dao {
private final MyBatis mybatis;
}
}
+ /**
+ * Gets a list users by their logins. The result does NOT contain {@code null} values for users not found, so
+ * the size of result may be less than the number of keys.
+ * A single user is returned if input keys contain multiple occurrences of a key.
+ * <p>Contrary to {@link #selectByLogins(DbSession, Collection)}, results are in the same order as input keys.</p>
+ */
+ public List<UserDto> selectByOrderedLogins(DbSession session, Collection<String> logins) {
+ List<UserDto> unordered = selectByLogins(session, logins);
+ return from(logins).transform(new LoginToUser(unordered)).filter(Predicates.notNull()).toList();
+ }
+
private static class SelectByLogins implements Function<List<String>, List<UserDto>> {
private final UserMapper mapper;
protected UserMapper mapper(DbSession session) {
return session.getMapper(UserMapper.class);
}
+
+ private static class LoginToUser implements Function<String, UserDto> {
+ private final Map<String, UserDto> map = new HashMap<>();
+
+ private LoginToUser(Collection<UserDto> unordered) {
+ for (UserDto dto : unordered) {
+ map.put(dto.getLogin(), dto);
+ }
+ }
+
+ @Override
+ public UserDto apply(@Nonnull String login) {
+ return map.get(login);
+ }
+ }
}
import static org.mockito.Mockito.when;
import static org.sonar.db.user.GroupMembershipQuery.IN;
import static org.sonar.db.user.GroupMembershipQuery.builder;
+import static org.sonar.db.user.UserTesting.newUserDto;
public class UserDaoTest {
assertThat(users).isEmpty();
}
+ @Test
+ public void selectByOrderedLogins() {
+ underTest.insert(session, newUserDto().setLogin("U1").setActive(true));
+ underTest.insert(session, newUserDto().setLogin("U2").setActive(true));
+ session.commit();
+
+ Iterable<UserDto> users = underTest.selectByOrderedLogins(session, asList("U1", "U2", "U3"));
+ assertThat(users).extracting("login").containsExactly("U1", "U2");
+
+ users = underTest.selectByOrderedLogins(session, asList("U2", "U3", "U1"));
+ assertThat(users).extracting("login").containsExactly("U2", "U1");
+
+ assertThat(underTest.selectByOrderedLogins(session, Collections.<String>emptyList())).isEmpty();
+ }
+
@Test
public void selectUsersByQuery_all() {
db.prepareDbUnit(getClass(), "selectUsersByQuery.xml");
}
private UserDto newUser(boolean active){
- UserDto dto = UserTesting.newUserDto().setActive(active);
+ UserDto dto = newUserDto().setActive(active);
underTest.insert(session, dto);
return dto;
}