import org.dbunit.operation.DatabaseOperation;
import org.junit.rules.ExternalResource;
import org.sonar.api.utils.log.Loggers;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.asList;
columnNames.stream()
.sorted(PkColumn.ORDERING_BY_INDEX)
.map(PkColumn::getName)
- .collect(Collectors.toList()));
+ .collect(MoreCollectors.toList()));
}
}
import org.sonar.api.utils.log.LogTester;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.api.utils.log.Loggers;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.dialect.Oracle;
import static com.google.common.collect.Lists.newArrayList;
List<String> outputs = DatabaseUtils.executeLargeInputs(inputs, input -> {
// Check that each partition is only done on 1000 elements max
assertThat(input.size()).isLessThanOrEqualTo(1000);
- return input.stream().map(String::valueOf).collect(Collectors.toList());
+ return input.stream().map(String::valueOf).collect(MoreCollectors.toList());
});
assertThat(outputs).isEqualTo(expectedOutputs);
import java.util.List;
import java.util.Map;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
public class KeyLongValue {
import java.util.List;
import java.util.Optional;
import org.sonar.core.issue.FieldDiffs;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.Dao;
import org.sonar.db.DbSession;
return selectByTypeAndIssueKeys(session, singletonList(issueKey), IssueChangeDto.TYPE_FIELD_CHANGE)
.stream()
.map(IssueChangeDto::toFieldDiffs)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
public List<IssueChangeDto> selectChangelogOfNonClosedIssuesByComponent(DbSession session, String componentUuid) {
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import static org.sonar.core.util.stream.Collectors.toSet;
+import static org.sonar.core.util.stream.MoreCollectors.toSet;
public class OrganizationQuery {
private static final OrganizationQuery NO_QUERY = newOrganizationQueryBuilder().build();
import java.util.List;
import javax.annotation.Nullable;
import org.apache.ibatis.session.RowBounds;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.Dao;
import org.sonar.db.DatabaseUtils;
import org.sonar.db.DbSession;
return dtos.stream()
.map(UserPermissionDto::getUserId)
.distinct()
- .collect(Collectors.toList(dtos.size()));
+ .collect(MoreCollectors.toList(dtos.size()));
}
/**
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.Dao;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDao;
.setStrategy(Strategy.LEAVES)
.build())
.stream().map(ComponentDto::uuid)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
purgeCommands.deleteComponentMeasures(analysisUuids, componentWithoutHistoricalDataUuids);
}
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbSession;
import org.sonar.db.purge.IdUuidPair;
import org.sonar.db.purge.PurgeDao;
import org.sonar.db.purge.PurgeProfiler;
import org.sonar.db.purge.PurgeableAnalysisDto;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
public class DefaultPeriodCleaner {
Joiner.on(", ").join(
snapshots.stream()
.map(snapshot -> snapshot.getAnalysisUuid() + "@" + DateUtils.formatDateTime(snapshot.getDate()))
- .collect(Collectors.toArrayList(snapshots.size()))));
+ .collect(MoreCollectors.toArrayList(snapshots.size()))));
}
purgeDao.deleteAnalyses(
session, profiler,
- snapshots.stream().map(DefaultPeriodCleaner::toIdUuidPair).collect(Collectors.toList(snapshots.size())));
+ snapshots.stream().map(DefaultPeriodCleaner::toIdUuidPair).collect(MoreCollectors.toList(snapshots.size())));
return snapshots;
}
import org.junit.Test;
import org.sonar.api.utils.internal.TestSystem2;
import org.sonar.core.util.CloseableIterator;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.Pagination;
private List<String> selectPageOfUuids(Pagination pagination) {
return underTest.selectByQuery(db.getSession(), new CeTaskQuery(), pagination).stream()
.map(CeActivityToUuid.INSTANCE::apply)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
private enum CeActivityToUuid implements Function<CeActivityDto, String> {
import java.util.List;
import javax.annotation.Nullable;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
.setUserId((int) userId)
.build(), dbSession).stream()
.filter(prop -> component == null ? prop.getResourceId() == null : prop.getResourceId() != null)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
assertThat(result).hasSize(1);
assertThat(result.get(0).getValue()).isEqualTo("true");
}
import java.util.function.Consumer;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
return keys
.stream()
.map(OrganizationPermission::fromKey)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
}
import org.sonar.server.platform.db.migration.step.RegisteredMigrationStep;
import static com.google.common.base.Preconditions.checkState;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
public class MigrationHistoryImpl implements MigrationHistory {
private static final String SCHEMA_MIGRATIONS_TABLE = "schema_migrations";
import java.util.Locale;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
checkState(!columnDefs.isEmpty() || !pkColumnDefs.isEmpty(), "at least one column must be specified");
return Stream.concat(of(createTableStatement()), createOracleAutoIncrementStatements())
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
public CreateTableBuilder addColumn(ColumnDef columnDef) {
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.dialect.Dialect;
import org.sonar.db.dialect.H2;
import org.sonar.db.dialect.MsSql;
case Oracle.ID:
return Collections.singletonList(getOracleStatement());
case H2.ID:
- return Arrays.stream(columns).map(this::getMsSQLStatement).collect(Collectors.toList(columns.length));
+ return Arrays.stream(columns).map(this::getMsSQLStatement).collect(MoreCollectors.toList(columns.length));
default:
throw new IllegalStateException(String.format("Unsupported database '%s'", dialect.getId()));
}
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
return migrations.entrySet().stream()
.sorted(Comparator.comparingLong(Map.Entry::getKey))
.map(Map.Entry::getValue)
- .collect(Collectors.toList(migrations.size()));
+ .collect(MoreCollectors.toList(migrations.size()));
}
}
import org.sonar.server.platform.db.migration.sql.DropTableBuilder;
import org.sonar.server.platform.db.migration.step.DdlChange;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
public class DropIssueFiltersTables extends DdlChange {
import org.sonar.server.platform.db.migration.sql.DropTableBuilder;
import org.sonar.server.platform.db.migration.step.DdlChange;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
public class DropMeasureFiltersTables extends DdlChange {
import org.sonar.server.platform.db.migration.sql.DropTableBuilder;
import org.sonar.server.platform.db.migration.step.DdlChange;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
public class DropRelatedDashboardTables extends DdlChange {
import org.sonar.server.platform.db.migration.step.Select;
import static java.util.Objects.requireNonNull;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
import static org.sonar.db.DatabaseUtils.repeatCondition;
/**
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.sonar.api.utils.System2;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.CoreDbTester;
import static org.assertj.core.api.Assertions.assertThat;
"from group_roles gr where gr.group_id is null");
List<String> roles = rows.stream()
.map(row -> (String) row.get("role"))
- .collect(Collectors.toArrayList());
+ .collect(MoreCollectors.toArrayList());
assertThat(roles).containsOnly("provisioning", "scan");
}
"where g.name='" + groupName + "'");
return rows.stream()
.map(row -> (String) row.get("role"))
- .collect(Collectors.toArrayList());
+ .collect(MoreCollectors.toArrayList());
}
private void verifyGroup(String expectedName, String expectedDescription) {
"where u.login='admin'");
List<String> groupNames = rows.stream()
.map(row -> (String) row.get("groupName"))
- .collect(Collectors.toArrayList());
+ .collect(MoreCollectors.toArrayList());
assertThat(groupNames).containsOnly("sonar-administrators", "sonar-users");
}
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.CoreDbTester;
import org.sonar.server.platform.db.migration.version.v63.DefaultOrganizationUuidImpl;
List<Map<String, Object>> rows = db.select(format("SELECT ORGANIZATION_UUID FROM " + TABLE + " WHERE USER_ID = %s", userId));
List<String> userOrganizationUuids = rows.stream()
.map(values -> (String) values.get("ORGANIZATION_UUID"))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
assertThat(userOrganizationUuids).containsOnly(organizationUuids);
}
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.CoreDbTester;
import static org.assertj.core.api.Assertions.assertThat;
}
private void verifyComponentsHavingCopyComponentUuid(Component... expectedComponents) {
- Map<String, Component> expectedComponentsByUuid = Arrays.stream(expectedComponents).collect(Collectors.uniqueIndex(Component::getUuid));
+ Map<String, Component> expectedComponentsByUuid = Arrays.stream(expectedComponents).collect(MoreCollectors.uniqueIndex(Component::getUuid));
List<Map<String, Object>> rows = db.select("SELECT uuid, copy_component_uuid FROM " + TABLE_PROJECTS + " WHERE copy_component_uuid IS NOT NULL");
Map<String, Component> components = rows.stream()
.map(map -> new Component((String) map.get("UUID"), (String) map.get("COPY_COMPONENT_UUID")))
- .collect(Collectors.uniqueIndex(Component::getUuid));
+ .collect(MoreCollectors.uniqueIndex(Component::getUuid));
assertThat(components.keySet()).containsExactlyElementsOf(expectedComponentsByUuid.keySet());
components.entrySet().forEach(entry -> {
Component expectedComponent = expectedComponentsByUuid.get(entry.getKey());
import static java.lang.String.format;
import static java.util.Collections.singletonList;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
public class UserIdentityAuthenticator {
import javax.servlet.http.HttpServletRequest;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static java.util.Objects.requireNonNull;
}
private static String getAllIps(HttpServletRequest request) {
- return Collections.list(request.getHeaders("X-Forwarded-For")).stream().collect(Collectors.join(Joiner.on(",")));
+ return Collections.list(request.getHeaders("X-Forwarded-For")).stream().collect(MoreCollectors.join(Joiner.on(",")));
}
@Override
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.Uuids;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.ce.CeActivityDto;
return null;
})
.filter(Objects::nonNull)
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
}
public static Collection<String> possibleValues() {
return Arrays.stream(values())
.map(AdditionalField::getLabel)
- .collect(Collectors.toList(values().length));
+ .collect(MoreCollectors.toList(values().length));
}
}
}
import javax.annotation.Nullable;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.ce.CeActivityDto;
public List<WsCe.Task> formatQueue(DbSession dbSession, List<CeQueueDto> dtos) {
ComponentDtoCache cache = ComponentDtoCache.forQueueDtos(dbClient, dbSession, dtos);
- return dtos.stream().map(input -> formatQueue(input, cache)).collect(Collectors.toList(dtos.size()));
+ return dtos.stream().map(input -> formatQueue(input, cache)).collect(MoreCollectors.toList(dtos.size()));
}
public WsCe.Task formatQueue(DbSession dbSession, CeQueueDto dto) {
ComponentDtoCache cache = ComponentDtoCache.forActivityDtos(dbClient, dbSession, dtos);
return dtos.stream()
.map(input -> formatActivity(input, cache, null))
- .collect(Collectors.toList(dtos.size()));
+ .collect(MoreCollectors.toList(dtos.size()));
}
private static WsCe.Task formatActivity(CeActivityDto dto, ComponentDtoCache componentDtoCache, @Nullable String scannerContext) {
static ComponentDtoCache forQueueDtos(DbClient dbClient, DbSession dbSession, Collection<CeQueueDto> ceQueueDtos) {
Map<String, ComponentDto> componentsByUuid = dbClient.componentDao().selectByUuids(dbSession, uuidOfCeQueueDtos(ceQueueDtos))
.stream()
- .collect(Collectors.uniqueIndex(ComponentDto::uuid));
+ .collect(MoreCollectors.uniqueIndex(ComponentDto::uuid));
return new ComponentDtoCache(componentsByUuid, buildOrganizationsByUuid(dbClient, dbSession, componentsByUuid));
}
.filter(Objects::nonNull)
.map(CeQueueDto::getComponentUuid)
.filter(Objects::nonNull)
- .collect(Collectors.toSet(ceQueueDtos.size()));
+ .collect(MoreCollectors.toSet(ceQueueDtos.size()));
}
static ComponentDtoCache forActivityDtos(DbClient dbClient, DbSession dbSession, Collection<CeActivityDto> ceActivityDtos) {
dbSession,
uuidOfCeActivityDtos(ceActivityDtos))
.stream()
- .collect(Collectors.uniqueIndex(ComponentDto::uuid));
+ .collect(MoreCollectors.uniqueIndex(ComponentDto::uuid));
return new ComponentDtoCache(componentsByUuid, buildOrganizationsByUuid(dbClient, dbSession, componentsByUuid));
}
.filter(Objects::nonNull)
.map(CeActivityDto::getComponentUuid)
.filter(Objects::nonNull)
- .collect(Collectors.toSet(ceActivityDtos.size()));
+ .collect(MoreCollectors.toSet(ceActivityDtos.size()));
}
static ComponentDtoCache forUuid(DbClient dbClient, DbSession dbSession, String uuid) {
dbSession,
componentsByUuid.values().stream()
.map(ComponentDto::getOrganizationUuid)
- .collect(Collectors.toSet(componentsByUuid.size())))
+ .collect(MoreCollectors.toSet(componentsByUuid.size())))
.stream()
- .collect(Collectors.uniqueIndex(OrganizationDto::getUuid));
+ .collect(MoreCollectors.uniqueIndex(OrganizationDto::getUuid));
}
@CheckForNull
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceType;
import org.sonar.api.resources.ResourceTypes;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
Set<String> rootQualifiers = rootTypes
.stream()
.map(ResourceType::getQualifier)
- .collect(Collectors.toSet(rootTypes.size()));
+ .collect(MoreCollectors.toSet(rootTypes.size()));
String qualifier = component.qualifier();
checkRequest(rootQualifiers.contains(qualifier) || Qualifiers.MODULE.equals(qualifier),
import org.elasticsearch.search.aggregations.bucket.filters.InternalFilters.Bucket;
import org.elasticsearch.search.aggregations.metrics.tophits.InternalTopHits;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHitsBuilder;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.textsearch.ComponentTextSearchFeature;
import org.sonar.server.es.textsearch.ComponentTextSearchQueryFactory;
List<Bucket> buckets = filtersAgg.getBuckets();
return buckets.stream()
.map(ComponentIndex::bucketToQualifier)
- .collect(Collectors.toList(buckets.size()));
+ .collect(MoreCollectors.toList(buckets.size()));
}
private static ComponentsPerQualifier bucketToQualifier(Bucket bucket) {
SearchHit[] hits = hitList.getHits();
List<String> componentUuids = Arrays.stream(hits).map(SearchHit::getId)
- .collect(Collectors.toList(hits.length));
+ .collect(MoreCollectors.toList(hits.length));
return new ComponentsPerQualifier(bucket.getKey(), componentUuids, hitList.totalHits());
}
import java.util.stream.StreamSupport;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.lang.String.format;
public static List<Criterion> parse(String filter) {
return StreamSupport.stream(CRITERIA_SPLITTER.split(filter).spliterator(), false)
.map(FilterParser::parseCriterion)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
private static Criterion parseCriterion(String rawCriterion) {
import org.sonar.server.measure.index.ProjectMeasuresQuery;
import static com.google.common.base.Preconditions.checkArgument;
-import static org.sonar.core.util.stream.Collectors.toHashSet;
-import static org.sonar.core.util.stream.Collectors.toSet;
+import static org.sonar.core.util.stream.MoreCollectors.toHashSet;
+import static org.sonar.core.util.stream.MoreCollectors.toSet;
import static org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion;
import static org.sonar.server.measure.index.ProjectMeasuresQuery.SORT_BY_NAME;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.Paging;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.api.web.UserRole.USER;
import static org.sonar.core.util.Protobuf.setNullable;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
import static org.sonar.server.util.LanguageParamUtils.getExampleValue;
import static org.sonar.server.util.LanguageParamUtils.getLanguageKeys;
import static org.sonar.server.ws.WsParameterBuilder.createQualifiersParameter;
// Meanwhile root is explicitly handled.
return componentDtos;
}
- Set<String> projectUuids = componentDtos.stream().map(ComponentDto::projectUuid).collect(Collectors.toSet());
+ Set<String> projectUuids = componentDtos.stream().map(ComponentDto::projectUuid).collect(MoreCollectors.toSet());
List<ComponentDto> projects = dbClient.componentDao().selectByUuids(dbSession, projectUuids);
Map<String, Long> projectIdsByUuids = projects.stream().collect(uniqueIndex(ComponentDto::uuid, ComponentDto::getId));
Collection<Long> authorizedProjectIds = dbClient.authorizationDao().keepAuthorizedProjectIds(dbSession, projectIdsByUuids.values(), userSession.getUserId(), USER);
return componentDtos.stream()
.filter(component -> authorizedProjectIds.contains(projectIdsByUuids.get(component.projectUuid())))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
private static SearchWsResponse buildResponse(List<ComponentDto> components, OrganizationDto organization, Paging paging) {
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.DateUtils;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY;
import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY;
import static org.sonar.api.server.ws.WebService.Param.FIELDS;
-import static org.sonar.core.util.stream.Collectors.toSet;
+import static org.sonar.core.util.stream.MoreCollectors.toSet;
import static org.sonar.server.component.ws.ProjectMeasuresQueryFactory.IS_FAVORITE_CRITERION;
import static org.sonar.server.component.ws.ProjectMeasuresQueryFactory.newProjectMeasuresQuery;
import static org.sonar.server.measure.index.ProjectMeasuresIndex.SUPPORTED_FACETS;
Set<String> organizationUuids = searchResults.projects.stream().map(ComponentDto::getOrganizationUuid).collect(toSet());
Map<String, OrganizationDto> organizationsByUuid = dbClient.organizationDao().selectByUuids(dbSession, organizationUuids)
.stream()
- .collect(Collectors.uniqueIndex(OrganizationDto::getUuid));
+ .collect(MoreCollectors.uniqueIndex(OrganizationDto::getUuid));
return buildResponse(request, searchResults, organizationsByUuid);
}
List<Long> favoriteDbIds = props.stream()
.map(PropertyDto::getResourceId)
- .collect(Collectors.toList(props.size()));
+ .collect(MoreCollectors.toList(props.size()));
return dbClient.componentDao().selectByIds(dbSession, favoriteDbIds).stream()
.filter(ComponentDto::isEnabled)
.filter(f -> f.qualifier().equals(Qualifiers.PROJECT))
.map(ComponentDto::uuid)
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
}
private Map<String, SnapshotDto> getSnapshots(DbSession dbSession, SearchProjectsRequest request, List<String> projectUuids) {
if (request.getAdditionalFields().contains(ANALYSIS_DATE)) {
return dbClient.snapshotDao().selectLastAnalysesByRootComponentUuids(dbSession, projectUuids)
.stream()
- .collect(Collectors.uniqueIndex(SnapshotDto::getComponentUuid));
+ .collect(MoreCollectors.uniqueIndex(SnapshotDto::getComponentUuid));
}
return emptyMap();
}
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
List<Component> results = sortedComponentDtos
.stream()
.map(dto -> dtoToComponent(dto, organizationKeyByUuids))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
return Qualifier.newBuilder()
.setQ(qualifier.getQualifier())
.addAllItems(results)
.build();
- }).collect(Collectors.toList());
+ }).collect(MoreCollectors.toList());
}
}
private Map<String, String> getOrganizationKeys(DbSession dbSession, List<ComponentDto> componentDtos) {
return dbClient.organizationDao().selectByUuids(
dbSession,
- componentDtos.stream().map(ComponentDto::getOrganizationUuid).collect(Collectors.toSet()))
+ componentDtos.stream().map(ComponentDto::getOrganizationUuid).collect(MoreCollectors.toSet()))
.stream()
- .collect(Collectors.uniqueIndex(OrganizationDto::getUuid, OrganizationDto::getKey));
+ .collect(MoreCollectors.uniqueIndex(OrganizationDto::getUuid, OrganizationDto::getKey));
}
private List<ComponentsPerQualifier> searchInIndex(ComponentIndexQuery componentIndexQuery) {
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.Paging;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
List<String> referenceComponentIds = components.stream()
.map(ComponentDto::getCopyResourceUuid)
.filter(Objects::nonNull)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
if (referenceComponentIds.isEmpty()) {
return emptyMap();
}
return dbClient.componentDao().selectByUuids(dbSession, referenceComponentIds).stream()
- .collect(Collectors.uniqueIndex(ComponentDto::uuid));
+ .collect(MoreCollectors.uniqueIndex(ComponentDto::uuid));
}
private void checkPermissions(ComponentDto baseComponent) {
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.ce.CeActivityDto;
Set<String> ceActivityUuids = dbClient.ceActivityDao().selectOlderThan(dbSession, sixMonthsAgo.getTimeInMillis())
.stream()
.map(CeActivityDto::getUuid)
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
dbClient.ceActivityDao().deleteByUuids(dbSession, ceActivityUuids);
dbClient.ceScannerContextDao().deleteByUuids(dbSession, ceActivityUuids);
dbSession.commit();
import static org.apache.commons.lang.StringUtils.trimToNull;
import static org.sonar.core.component.ComponentKeys.createEffectiveKey;
import static org.sonar.core.component.ComponentKeys.createKey;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
public class ComponentRootBuilder {
private static final String DEFAULT_PROJECT_VERSION = "not provided";
import com.google.common.base.Optional;
import java.util.Collection;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.QualityGateConditionDto;
Metric metric = metricRepository.getById(input.getMetricId());
return new Condition(metric, input.getOperator(), input.getErrorThreshold(), input.getWarningThreshold(), input.getPeriod() != null);
})
- .collect(Collectors.toList(dtos.size()));
+ .collect(MoreCollectors.toList(dtos.size()));
return new QualityGate(qualityGateDto.getId(), qualityGateDto.getName(), conditions);
}
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.server.computation.task.projectanalysis.component.Component;
List<Changeset> lineChangesets = StreamSupport.stream(lines.spliterator(), false)
.map(lineToChangeset)
.filter(Objects::nonNull)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
if (lineChangesets.isEmpty()) {
return Optional.absent();
}
import java.util.stream.StreamSupport;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.measure.PastMeasureDto;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.function.Function.identity;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
import static org.sonar.server.computation.task.projectanalysis.component.Component.Type.DIRECTORY;
import static org.sonar.server.computation.task.projectanalysis.component.Component.Type.SUBVIEW;
import static org.sonar.server.computation.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER;
@Override
public void execute() {
try (DbSession dbSession = dbClient.openSession(false)) {
- List<Metric> metrics = StreamSupport.stream(metricRepository.getAll().spliterator(), false).filter(isNumeric()).collect(Collectors.toList());
+ List<Metric> metrics = StreamSupport.stream(metricRepository.getAll().spliterator(), false).filter(isNumeric()).collect(MoreCollectors.toList());
new DepthTraversalTypeAwareCrawler(new VariationMeasuresVisitor(dbSession, metrics))
.visit(treeRootHolder.getRoot());
}
// measures on files are currently purged, so past measures are not available on files
super(CrawlerDepthLimit.reportMaxDepth(DIRECTORY).withViewsMaxDepth(SUBVIEW), PRE_ORDER);
this.session = session;
- this.metricIds = metrics.stream().map(Metric::getId).collect(Collectors.toSet());
+ this.metricIds = metrics.stream().map(Metric::getId).collect(MoreCollectors.toSet());
this.metrics = metrics;
}
import javax.annotation.Nullable;
import org.sonar.api.utils.MessageException;
import org.sonar.ce.queue.CeTask;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationDto;
import static com.google.common.collect.Maps.transformValues;
import static java.lang.String.format;
import static org.apache.commons.lang.StringUtils.isNotEmpty;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
/**
* Feed analysis metadata holder with metadata from the analysis report.
String badKeys = profiles.stream()
.filter(p -> !p.getOrganizationUuid().equals(organization.getUuid()))
.map(QualityProfileDto::getKey)
- .collect(Collectors.join(Joiner.on(", ")));
+ .collect(MoreCollectors.join(Joiner.on(", ")));
if (!badKeys.isEmpty()) {
throw MessageException.of(format("Quality profiles with following keys don't exist in organization [%s]: %s", organization.getKey(), badKeys));
}
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.api.utils.System2;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
Set<String> uuids = dtos.stream()
.filter(ComponentDto::isEnabled)
.map(ComponentDto::uuid)
- .collect(Collectors.toSet(dtos.size()));
+ .collect(MoreCollectors.toSet(dtos.size()));
dbClient.componentDao().updateBEnabledToFalse(dbSession, uuids);
disabledComponentsHolder.setUuids(uuids);
}
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.measures.CoreMetrics;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.server.computation.task.projectanalysis.component.Component;
import org.sonar.server.computation.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.server.computation.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
}
private void updateMeasures(Component project, Set<Condition> conditions, QualityGateDetailsDataBuilder builder) {
- Multimap<Metric, Condition> conditionsPerMetric = conditions.stream().collect(Collectors.index(Condition::getMetric, java.util.function.Function.identity()));
+ Multimap<Metric, Condition> conditionsPerMetric = conditions.stream().collect(MoreCollectors.index(Condition::getMetric, java.util.function.Function.identity()));
for (Map.Entry<Metric, Collection<Condition>> entry : conditionsPerMetric.asMap().entrySet()) {
Metric metric = entry.getKey();
Optional<Measure> measure = measureRepository.getRawMeasure(project, metric);
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.core.config.WebhookProperties;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.server.computation.task.projectanalysis.component.SettingsRepository;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolder;
return Arrays.stream(webhookIds)
.map(webhookId -> format("%s.%s", propertyKey, webhookId))
.limit(MAX_WEBHOOKS_PER_TYPE)
- .collect(Collectors.toList(webhookIds.length));
+ .collect(MoreCollectors.toList(webhookIds.length));
}
private void process(Settings settings, ProjectAnalysis analysis, Iterable<String> webhookProperties) {
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.joda.time.format.ISODateTimeFormat;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static java.lang.String.format;
public static List<String> termsKeys(Terms terms) {
return terms.getBuckets().stream()
.map(Terms.Bucket::getKeyAsString)
- .collect(Collectors.toList(terms.getBuckets().size()));
+ .collect(MoreCollectors.toList(terms.getBuckets().size()));
}
import java.util.Arrays;
import java.util.function.Function;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static java.util.Objects.requireNonNull;
}
private static String[] getDetails(Function<? super IndexType, ? extends String> function, IndexType... indexTypes) {
- return Arrays.stream(indexTypes).map(function).collect(Collectors.toSet(indexTypes.length)).toArray(new String[0]);
+ return Arrays.stream(indexTypes).map(function).collect(MoreCollectors.toSet(indexTypes.length)).toArray(new String[0]);
}
@Override
import org.sonar.server.user.UserSession;
import static java.util.Collections.emptyList;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
import static org.sonar.server.favorite.FavoriteUpdater.PROP_FAVORITE_KEY;
public class FavoriteFinder {
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.Paging;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
try (DbSession dbSession = dbClient.openSession(false)) {
List<ComponentDto> authorizedFavorites = favoriteFinder.list().stream()
.filter(isAuthorized(dbSession))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
Paging paging = Paging.forPageIndex(request.getPage()).withPageSize(request.getPageSize()).andTotal(authorizedFavorites.size());
List<ComponentDto> displayedFavorites = authorizedFavorites.stream()
.skip(paging.offset())
.limit(paging.pageSize())
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
Map<String, OrganizationDto> organizationsByUuid = getOrganizationsOfComponents(dbSession, displayedFavorites);
return new SearchResults(paging, displayedFavorites, organizationsByUuid);
}
Collection<String> rootProjectsUuids = dbClient.authorizationDao().selectAuthorizedRootProjectsUuids(dbSession, userSession.getUserId(), UserRole.USER);
Set<String> authorizedProjectUuids = rootProjectsUuids
.stream()
- .collect(Collectors.toSet(rootProjectsUuids.size()));
+ .collect(MoreCollectors.toSet(rootProjectsUuids.size()));
return dto -> authorizedProjectUuids.contains(dto.projectUuid());
}
private Map<String, OrganizationDto> getOrganizationsOfComponents(DbSession dbSession, List<ComponentDto> displayedFavorites) {
Set<String> organizationUuids = displayedFavorites.stream()
.map(ComponentDto::getOrganizationUuid)
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
return dbClient.organizationDao().selectByUuids(dbSession, organizationUuids)
.stream()
- .collect(Collectors.uniqueIndex(OrganizationDto::getUuid));
+ .collect(MoreCollectors.uniqueIndex(OrganizationDto::getUuid));
}
private static class SearchResults {
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.DefaultIssueComment;
import org.sonar.core.issue.IssueChangeContext;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.user.UserDto;
import static com.google.common.base.Preconditions.checkState;
.filter(Objects::nonNull)
.filter(tag -> !tag.isEmpty())
.map(tag -> RuleTagFormat.validate(tag.toLowerCase(Locale.ENGLISH)))
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
Set<String> oldTags = Sets.newHashSet(issue.tags());
if (!oldTags.equals(newTags)) {
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
return;
}
- Set<String> qualifiers = components.stream().map(ComponentDto::qualifier).collect(Collectors.toHashSet());
+ Set<String> qualifiers = components.stream().map(ComponentDto::qualifier).collect(MoreCollectors.toHashSet());
if (qualifiers.size() > 1) {
throw new IllegalArgumentException("All components must have the same qualifier, found " + Joiner.on(',').join(qualifiers));
}
}
private Collection<String> convertComponentKeysToUuids(DbSession dbSession, Collection<String> componentKeys) {
- List<String> componentUuids = dbClient.componentDao().selectByKeys(dbSession, componentKeys).stream().map(ComponentDto::uuid).collect(Collectors.toList());
+ List<String> componentUuids = dbClient.componentDao().selectByKeys(dbSession, componentKeys).stream().map(ComponentDto::uuid).collect(MoreCollectors.toList());
// If unknown components are given, but no components are found, then all issues will be returned,
// so we add this hack in order to return no issue in this case.
if (!componentKeys.isEmpty() && componentUuids.isEmpty()) {
import java.util.Map;
import org.sonar.api.server.ServerSide;
import org.sonar.core.issue.DefaultIssue;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.server.issue.workflow.Transition;
import org.sonar.server.user.UserSession;
return transitionService.listTransitions(issue)
.stream()
.map(Transition::key)
- .collect(Collectors.toSet())
+ .collect(MoreCollectors.toSet())
.contains(transitionKey);
}
import java.util.List;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.server.issue.workflow.IssueWorkflow;
import org.sonar.server.issue.workflow.Transition;
import org.sonar.server.user.UserSession;
.stream()
.filter(transition -> (userSession.isLoggedIn() && isBlank(transition.requiredProjectPermission()))
|| userSession.hasComponentUuidPermission(transition.requiredProjectPermission(), projectUuid))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
public boolean doTransition(DefaultIssue defaultIssue, IssueChangeContext issueChangeContext, String transitionKey) {
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.core.util.NonNullInputFunction;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.EsUtils;
if (values == null) {
return Collections.emptyList();
}
- return values.stream().map(Pattern::quote).collect(Collectors.toArrayList(values.size()));
+ return values.stream().map(Pattern::quote).collect(MoreCollectors.toArrayList(values.size()));
}
private void addAssignedToMeFacetIfNeeded(SearchRequestBuilder builder, SearchOptions options, IssueQuery query, Map<String, QueryBuilder> filters, QueryBuilder queryBuilder) {
import org.sonar.api.web.UserRole;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.IssueChangeContext;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import static org.sonar.api.rules.RuleType.BUG;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_02;
-import static org.sonar.core.util.stream.Collectors.toList;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
import static org.sonar.server.es.SearchOptions.MAX_LIMIT;
import static org.sonar.server.issue.AbstractChangeTagsAction.TAGS_PARAMETER;
import static org.sonar.server.issue.AssignAction.ASSIGNEE_PARAMETER;
.map(loadData(dbSession))
.map(executeBulkChange())
.map(toWsResponse())
- .collect(Collectors.toOneElement());
+ .collect(MoreCollectors.toOneElement());
writeProtobuf(wsResponse, request, response);
}
}
List<DefaultIssue> items = bulkChangeData.issues.stream()
.filter(bulkChange(issueChangeContext, bulkChangeData, result))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
issueStorage.save(items);
items.forEach(sendNotification(issueChangeContext, bulkChangeData));
return result;
checkArgument(issueKeys.size() <= MAX_LIMIT, "Number of issues is limited to %s", MAX_LIMIT);
List<IssueDto> allIssues = dbClient.issueDao().selectByKeys(dbSession, issueKeys);
- List<ComponentDto> allProjects = getComponents(dbSession, allIssues.stream().map(IssueDto::getProjectUuid).collect(Collectors.toSet()));
+ List<ComponentDto> allProjects = getComponents(dbSession, allIssues.stream().map(IssueDto::getProjectUuid).collect(MoreCollectors.toSet()));
this.projectsByUuid = getAuthorizedProjects(dbSession, allProjects).stream().collect(uniqueIndex(ComponentDto::uuid, identity()));
this.issues = getAuthorizedIssues(allIssues);
this.componentsByUuid = getComponents(dbSession,
- issues.stream().map(DefaultIssue::componentUuid).collect(Collectors.toSet())).stream()
+ issues.stream().map(DefaultIssue::componentUuid).collect(MoreCollectors.toSet())).stream()
.collect(uniqueIndex(ComponentDto::uuid, identity()));
this.rulesByKey = dbClient.ruleDao().selectDefinitionByKeys(dbSession,
- issues.stream().map(DefaultIssue::ruleKey).collect(Collectors.toSet())).stream()
+ issues.stream().map(DefaultIssue::ruleKey).collect(MoreCollectors.toSet())).stream()
.collect(uniqueIndex(RuleDefinitionDto::getKey, identity()));
this.availableActions = actions.stream()
.filter(action -> propertiesByActions.containsKey(action.key()))
.filter(action -> action.verify(getProperties(action.key()), issues, userSession))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
private List<ComponentDto> getComponents(DbSession dbSession, Collection<String> componentUuids) {
userSession.getUserId(), UserRole.USER);
return projectDtos.stream()
.filter(project -> authorizedProjectIds.contains(projectIdsByUuids.get(project.projectUuid())))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
private List<DefaultIssue> getAuthorizedIssues(List<IssueDto> allIssues) {
- Set<String> projectUuids = projectsByUuid.values().stream().map(ComponentDto::uuid).collect(Collectors.toSet());
+ Set<String> projectUuids = projectsByUuid.values().stream().map(ComponentDto::uuid).collect(MoreCollectors.toSet());
return allIssues.stream()
.filter(issue -> projectUuids.contains(issue.getProjectUuid()))
.map(IssueDto::toDefaultIssue)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
Map<String, Object> getProperties(String actionKey) {
}
List<Action> getActionsWithoutComment() {
- return availableActions.stream().filter(action -> !action.key().equals(COMMENT_KEY)).collect(Collectors.toList());
+ return availableActions.stream().filter(action -> !action.key().equals(COMMENT_KEY)).collect(MoreCollectors.toList());
}
Optional<Action> getCommentAction() {
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.issue.FieldDiffs;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
ChangelogWsResponse wsResponse = Stream.of(request)
.map(searchChangelog(dbSession))
.map(buildResponse())
- .collect(Collectors.toOneElement());
+ .collect(MoreCollectors.toOneElement());
writeProtobuf(wsResponse, request, response);
}
}
return result -> Stream.of(ChangelogWsResponse.newBuilder())
.peek(addChanges(result))
.map(ChangelogWsResponse.Builder::build)
- .collect(Collectors.toOneElement());
+ .collect(MoreCollectors.toOneElement());
}
private Consumer<ChangelogWsResponse.Builder> addChanges(ChangeLogResults results) {
ChangeLogResults(DbSession dbSession, String issueKey) {
IssueDto dbIssue = issueFinder.getByKey(dbSession, issueKey);
this.changes = dbClient.issueChangeDao().selectChangelogByIssue(dbSession, dbIssue.getKey());
- List<String> logins = changes.stream().filter(change -> change.userLogin() != null).map(FieldDiffs::userLogin).collect(Collectors.toList());
- this.users = dbClient.userDao().selectByLogins(dbSession, logins).stream().collect(Collectors.uniqueIndex(UserDto::getLogin));
- this.files = dbClient.componentDao().selectByUuids(dbSession, getFileUuids(changes)).stream().collect(Collectors.uniqueIndex(ComponentDto::uuid, Function.identity()));
+ List<String> logins = changes.stream().filter(change -> change.userLogin() != null).map(FieldDiffs::userLogin).collect(MoreCollectors.toList());
+ this.users = dbClient.userDao().selectByLogins(dbSession, logins).stream().collect(MoreCollectors.uniqueIndex(UserDto::getLogin));
+ this.files = dbClient.componentDao().selectByUuids(dbSession, getFileUuids(changes)).stream().collect(MoreCollectors.uniqueIndex(ComponentDto::uuid, Function.identity()));
}
private Set<String> getFileUuids(List<FieldDiffs> changes) {
return changes.stream()
.filter(diffs -> diffs.diffs().containsKey(FILE))
.flatMap(diffs -> Stream.of(diffs.get(FILE).newValue().toString(), diffs.get(FILE).oldValue().toString()))
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
}
@CheckForNull
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueChangeDto;
IssueDto issueDto = Stream.of(request)
.map(loadCommentData(dbSession))
.peek(deleteComment(dbSession))
- .collect(Collectors.toOneElement())
+ .collect(MoreCollectors.toOneElement())
.getIssueDto();
responseWriter.write(issueDto.getKey(), request, response);
}
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.issue.IssueChangeDto;
.map(toWsRequest())
.map(loadCommentData(dbSession))
.peek(updateComment(dbSession))
- .collect(Collectors.toOneElement())
+ .collect(MoreCollectors.toOneElement())
.getIssueDto();
responseWriter.write(issueDto.getKey(), request, response);
}
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.Paging;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.server.es.Facets;
import org.sonar.server.es.SearchOptions;
import org.sonar.server.es.SearchResult;
// execute request
SearchResult<IssueDoc> result = issueIndex.search(query, options);
- List<String> issueKeys = result.getDocs().stream().map(IssueDoc::key).collect(Collectors.toList(result.getDocs().size()));
+ List<String> issueKeys = result.getDocs().stream().map(IssueDoc::key).collect(MoreCollectors.toList(result.getDocs().size()));
// load the additional information to be returned in response
SearchResponseLoader.Collector collector = new SearchResponseLoader.Collector(additionalFields, issueKeys);
import java.util.Set;
import javax.annotation.Nullable;
import org.sonar.core.issue.DefaultIssue;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
}
dbClient.organizationDao().selectByUuids(
dbSession,
- components.stream().map(ComponentDto::getOrganizationUuid).collect(Collectors.toSet()))
+ components.stream().map(ComponentDto::getOrganizationUuid).collect(MoreCollectors.toSet()))
.forEach(result::addOrganization);
}
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.setting.ws.Setting;
import static com.google.common.base.Strings.isNullOrEmpty;
import static org.sonar.api.CoreProperties.PERMANENT_SERVER_ID;
import static org.sonar.api.PropertyType.LICENSE;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.license.LicensesWsParameters.ACTION_LIST;
private ListWsResponse doHandle(DbSession dbSession) {
Map<String, PropertyDefinition> licenseDefinitionsByKeys = definitions.getAll().stream()
.filter(definition -> LICENSE.equals(definition.type()))
- .collect(Collectors.uniqueIndex(PropertyDefinition::key, Function.identity()));
+ .collect(MoreCollectors.uniqueIndex(PropertyDefinition::key, Function.identity()));
Set<String> settingsKeys = new HashSet<>(licenseDefinitionsByKeys.keySet());
settingsKeys.add(PERMANENT_SERVER_ID);
List<Setting> settings = settingsFinder.loadGlobalSettings(dbSession, settingsKeys);
import java.util.Map;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.server.es.BaseDoc;
import static org.sonar.api.measures.Metric.Level.ERROR;
.map(entry -> ImmutableMap.<String, Object>of(
FIELD_MEASURES_KEY, entry.getKey(),
FIELD_MEASURES_VALUE, entry.getValue()))
- .collect(Collectors.toList()));
+ .collect(MoreCollectors.toList()));
return this;
}
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.server.es.DefaultIndexSettingsElement;
import org.sonar.server.es.EsClient;
import org.sonar.server.es.SearchIdResult;
return aggregation.getBuckets().stream()
.map(Bucket::getKeyAsString)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
@FunctionalInterface
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
List<MetricDtoWithBestValue> metricWithBestValueList = metrics.stream()
.filter(MetricDtoFunctions.isOptimizedForBestValue())
.map(new MetricDtoToMetricDtoWithBestValueFunction())
- .collect(Collectors.toList(metrics.size()));
+ .collect(MoreCollectors.toList(metrics.size()));
Map<Integer, MeasureDto> measuresByMetricId = Maps.uniqueIndex(measures, MeasureDto::getMetricId);
for (MetricDtoWithBestValue metricWithBestValue : metricWithBestValueList) {
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceTypes;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
List<String> referenceComponentUUids = components.stream()
.map(ComponentDto::getCopyResourceUuid)
.filter(Objects::nonNull)
- .collect(Collectors.toList(components.size()));
+ .collect(MoreCollectors.toList(components.size()));
if (referenceComponentUUids.isEmpty()) {
return emptyMap();
}
List<MetricDtoWithBestValue> metricDtosWithBestValueMeasure = metrics.stream()
.filter(MetricDtoFunctions.isOptimizedForBestValue())
.map(new MetricDtoToMetricDtoWithBestValue())
- .collect(Collectors.toList(metrics.size()));
+ .collect(MoreCollectors.toList(metrics.size()));
if (metricDtosWithBestValueMeasure.isEmpty()) {
return;
}
return components
.stream()
.filter(new HasMeasure(measuresByComponentUuidAndMetric, metricToSort.get(), wsRequest))
- .collect(Collectors.toList(components.size()));
+ .collect(MoreCollectors.toList(components.size()));
}
private static boolean componentWithMeasuresOnly(ComponentTreeWsRequest wsRequest) {
return components.stream()
.skip(offset(wsRequest.getPage(), wsRequest.getPageSize()))
.limit(wsRequest.getPageSize())
- .collect(Collectors.toList(wsRequest.getPageSize()));
+ .collect(MoreCollectors.toList(wsRequest.getPageSize()));
}
@CheckForNull
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.api.resources.Qualifiers.SUBVIEW;
import static org.sonar.api.resources.Qualifiers.VIEW;
-import static org.sonar.core.util.stream.Collectors.toList;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
import static org.sonar.server.measure.ws.MeasureDtoToWsMeasure.dbToWsMeasure;
import static org.sonar.server.measure.ws.MeasuresWsParametersBuilder.createMetricKeysParameter;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
private List<ComponentDto> searchProjects() {
List<ComponentDto> componentDtos = searchByProjectKeys(dbSession, request.getProjectKeys());
- checkArgument(ALLOWED_QUALIFIERS.containsAll(componentDtos.stream().map(ComponentDto::qualifier).collect(Collectors.toSet())),
+ checkArgument(ALLOWED_QUALIFIERS.containsAll(componentDtos.stream().map(ComponentDto::qualifier).collect(MoreCollectors.toSet())),
"Only component of qualifiers %s are allowed", ALLOWED_QUALIFIERS);
return getAuthorizedProjects(componentDtos);
}
// Meanwhile root is explicitly handled.
return componentDtos;
}
- Set<String> projectUuids = componentDtos.stream().map(ComponentDto::projectUuid).collect(Collectors.toSet());
+ Set<String> projectUuids = componentDtos.stream().map(ComponentDto::projectUuid).collect(MoreCollectors.toSet());
List<ComponentDto> projectDtos = dbClient.componentDao().selectByUuids(dbSession, projectUuids);
Map<String, Long> projectIdsByUuids = projectDtos.stream().collect(uniqueIndex(ComponentDto::uuid, ComponentDto::getId));
Set<Long> authorizedProjectIds = dbClient.authorizationDao().keepAuthorizedProjectIds(dbSession,
userSession.getUserId(), UserRole.USER);
return componentDtos.stream()
.filter(component -> authorizedProjectIds.contains(projectIdsByUuids.get(component.projectUuid())))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
private List<MetricDto> searchMetrics() {
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
.map(SearchHistoryAction::toWsRequest)
.map(search())
.map(result -> new SearchHistoryResponseFactory(result).apply())
- .collect(Collectors.toOneElement());
+ .collect(MoreCollectors.toOneElement());
writeProtobuf(searchHistoryResponse, request, response);
}
Date to = parseEndingDateOrDateTime(request.getTo());
PastMeasureQuery dbQuery = new PastMeasureQuery(
result.getComponent().uuid(),
- result.getMetrics().stream().map(MetricDto::getId).collect(Collectors.toList()),
+ result.getMetrics().stream().map(MetricDto::getId).collect(MoreCollectors.toList()),
from == null ? null : from.getTime(),
to == null ? null : (to.getTime() + 1_000L));
return dbClient.measureDao().selectPastMeasures(dbSession, dbQuery);
private List<MetricDto> searchMetrics(DbSession dbSession, SearchHistoryRequest request) {
List<MetricDto> metrics = dbClient.metricDao().selectByKeys(dbSession, request.getMetrics());
if (request.getMetrics().size() > metrics.size()) {
- Set<String> requestedMetrics = request.getMetrics().stream().collect(Collectors.toSet());
- Set<String> foundMetrics = metrics.stream().map(MetricDto::getKey).collect(Collectors.toSet());
+ Set<String> requestedMetrics = request.getMetrics().stream().collect(MoreCollectors.toSet());
+ Set<String> foundMetrics = metrics.stream().map(MetricDto::getKey).collect(MoreCollectors.toSet());
Set<String> unfoundMetrics = Sets.difference(requestedMetrics, foundMetrics).immutableCopy();
throw new IllegalArgumentException(format("Metrics %s are not found", String.join(", ", unfoundMetrics)));
import java.util.function.Predicate;
import java.util.function.UnaryOperator;
import java.util.stream.Stream;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.MeasureDto;
import org.sonar.db.metric.MetricDto;
.map(addPaging())
.map(addMeasures())
.map(SearchHistoryResponse.Builder::build)
- .collect(Collectors.toOneElement());
+ .collect(MoreCollectors.toOneElement());
}
private UnaryOperator<SearchHistoryResponse.Builder> addPaging() {
}
private UnaryOperator<SearchHistoryResponse.Builder> addMeasures() {
- Map<Integer, MetricDto> metricsById = result.getMetrics().stream().collect(Collectors.uniqueIndex(MetricDto::getId));
- Map<String, SnapshotDto> analysesByUuid = result.getAnalyses().stream().collect(Collectors.uniqueIndex(SnapshotDto::getUuid));
+ Map<Integer, MetricDto> metricsById = result.getMetrics().stream().collect(MoreCollectors.uniqueIndex(MetricDto::getId));
+ Map<String, SnapshotDto> analysesByUuid = result.getAnalyses().stream().collect(MoreCollectors.uniqueIndex(SnapshotDto::getUuid));
Table<MetricDto, SnapshotDto, MeasureDto> measuresByMetricByAnalysis = HashBasedTable.create(result.getMetrics().size(), result.getAnalyses().size());
result.getMeasures().forEach(m -> measuresByMetricByAnalysis.put(metricsById.get(m.getMetricId()), analysesByUuid.get(m.getAnalysisUuid()), m));
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.MeasureDto;
SearchHistoryResult setAnalyses(List<SnapshotDto> analyses) {
this.paging = Common.Paging.newBuilder().setPageIndex(request.getPage()).setPageSize(request.getPageSize()).setTotal(analyses.size()).build();
- this.analyses = analyses.stream().skip(offset(request.getPage(), request.getPageSize())).limit(request.getPageSize()).collect(Collectors.toList());
+ this.analyses = analyses.stream().skip(offset(request.getPage(), request.getPageSize())).limit(request.getPageSize()).collect(MoreCollectors.toList());
return this;
}
}
SearchHistoryResult setMeasures(List<MeasureDto> measures) {
- Set<String> analysisUuids = analyses.stream().map(SnapshotDto::getUuid).collect(Collectors.toHashSet());
+ Set<String> analysisUuids = analyses.stream().map(SnapshotDto::getUuid).collect(MoreCollectors.toHashSet());
ImmutableList.Builder<MeasureDto> measuresBuilder = ImmutableList.builder();
List<MeasureDto> filteredMeasures = measures.stream()
.filter(measure -> analysisUuids.contains(measure.getAnalysisUuid()))
- .collect(Collectors.toArrayList());
+ .collect(MoreCollectors.toArrayList());
measuresBuilder.addAll(filteredMeasures);
measuresBuilder.addAll(computeBestValues(filteredMeasures));
import java.util.List;
import java.util.function.Predicate;
import javax.annotation.Nullable;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
.build(),
dbSession).stream()
.filter(notificationScope(project))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
checkArgument(existingNotification.isEmpty()
|| !PROP_NOTIFICATION_VALUE.equals(existingNotification.get(0).getValue()), "Notification already added");
.build(),
dbSession).stream()
.filter(notificationScope(project))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
checkArgument(!existingNotification.isEmpty() && PROP_NOTIFICATION_VALUE.equals(existingNotification.get(0).getValue()), "Notification doesn't exist");
dbClient.propertiesDao().delete(dbSession, new PropertyDto()
import static java.util.Optional.empty;
import static org.sonar.core.util.Protobuf.setNullable;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION;
import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION;
import static org.sonar.server.ws.WsUtils.checkRequest;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsFirst;
import static org.sonar.core.util.Protobuf.setNullable;
-import static org.sonar.core.util.stream.Collectors.toOneElement;
+import static org.sonar.core.util.stream.MoreCollectors.toOneElement;
import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION;
import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public ListAction(NotificationCenter notificationCenter, DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
- this.globalDispatchers = notificationCenter.getDispatcherKeysForProperty(GLOBAL_NOTIFICATION, "true").stream().sorted().collect(Collectors.toList());
- this.perProjectDispatchers = notificationCenter.getDispatcherKeysForProperty(PER_PROJECT_NOTIFICATION, "true").stream().sorted().collect(Collectors.toList());
- this.channels = notificationCenter.getChannels().stream().map(NotificationChannel::getKey).sorted().collect(Collectors.toList());
+ this.globalDispatchers = notificationCenter.getDispatcherKeysForProperty(GLOBAL_NOTIFICATION, "true").stream().sorted().collect(MoreCollectors.toList());
+ this.perProjectDispatchers = notificationCenter.getDispatcherKeysForProperty(PER_PROJECT_NOTIFICATION, "true").stream().sorted().collect(MoreCollectors.toList());
+ this.channels = notificationCenter.getChannels().stream().map(NotificationChannel::getKey).sorted().collect(MoreCollectors.toList());
}
@Override
Set<Long> componentIds = properties.stream()
.map(PropertyDto::getResourceId)
.filter(Objects::nonNull)
- .collect(Collectors.toSet(properties.size()));
+ .collect(MoreCollectors.toSet(properties.size()));
return dbClient.componentDao().selectByIds(dbSession, componentIds)
.stream()
.filter(c -> authorizedComponentUuids.contains(c.uuid()))
- .collect(Collectors.uniqueIndex(ComponentDto::getId));
+ .collect(MoreCollectors.uniqueIndex(ComponentDto::getId));
}
private Map<String, OrganizationDto> getOrganizations(DbSession dbSession, Collection<ComponentDto> values) {
Set<String> organizationUuids = values.stream()
.map(ComponentDto::getOrganizationUuid)
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
return dbClient.organizationDao().selectByUuids(dbSession, organizationUuids)
.stream()
- .collect(Collectors.uniqueIndex(OrganizationDto::getUuid));
+ .collect(MoreCollectors.uniqueIndex(OrganizationDto::getUuid));
}
private static Function<PropertyDto, Notification> toWsNotification(Notification.Builder notification,
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
List<QualityProfileDto> profiles = dbClient.qualityProfileDao().selectAll(dbSession, organization);
List<String> profileKeys = profiles.stream()
.map(QualityProfileDto::getKey)
- .collect(Collectors.toArrayList(profiles.size()));
+ .collect(MoreCollectors.toArrayList(profiles.size()));
qProfileFactory.deleteByKeys(dbSession, profileKeys);
dbSession.commit();
}
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.server.ws.WebService.SelectionMode;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationDto;
SearchOptions searchOptions = buildSearchOptions(request);
SearchResult<UserDoc> searchResults = userIndex.search(userQuery.build(), searchOptions);
- List<String> orderedLogins = searchResults.getDocs().stream().map(UserDoc::login).collect(Collectors.toList());
+ List<String> orderedLogins = searchResults.getDocs().stream().map(UserDoc::login).collect(MoreCollectors.toList());
List<UserDto> users = dbClient.userDao().selectByLogins(dbSession, orderedLogins).stream()
.sorted(Ordering.explicit(orderedLogins).onResultOf(UserDto::getLogin))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
Multiset<String> groupCountByLogin = null;
if (userSession.hasPermission(OrganizationPermission.ADMINISTER, organization)) {
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.server.ServerSide;
import org.sonar.core.component.ComponentKeys;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
copyPermissions(dbSession, template, project, null);
}
dbSession.commit();
- indexProjectPermissions(dbSession, projects.stream().map(ComponentDto::uuid).collect(Collectors.toList()));
+ indexProjectPermissions(dbSession, projects.stream().map(ComponentDto::uuid).collect(MoreCollectors.toList()));
}
/**
import java.util.stream.Stream;
import org.elasticsearch.action.index.IndexRequest;
import org.sonar.api.utils.DateUtils;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.es.BulkIndexer;
import org.sonar.server.permission.index.PermissionIndexerDao.Dto;
import static com.google.common.base.Preconditions.checkArgument;
-import static org.sonar.core.util.stream.Collectors.toSet;
+import static org.sonar.core.util.stream.MoreCollectors.toSet;
/**
* Manages the synchronization of indexes with authorization settings defined in database:
public PermissionIndexer(DbClient dbClient, EsClient esClient, NeedAuthorizationIndexer... needAuthorizationIndexers) {
this(dbClient, esClient, Arrays.stream(needAuthorizationIndexers)
.map(NeedAuthorizationIndexer::getAuthorizationScope)
- .collect(Collectors.toList(needAuthorizationIndexers.length)));
+ .collect(MoreCollectors.toList(needAuthorizationIndexers.length)));
}
@VisibleForTesting
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.Paging;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationDto;
if (groups.isEmpty()) {
return emptyList();
}
- List<Integer> ids = groups.stream().map(GroupDto::getId).collect(Collectors.toList(groups.size()));
+ List<Integer> ids = groups.stream().map(GroupDto::getId).collect(MoreCollectors.toList(groups.size()));
return dbClient.groupPermissionDao().selectByGroupIds(dbSession, org.getUuid(), ids, project.isPresent() ? project.get().getId() : null);
}
}
import org.sonar.api.platform.Server;
import org.sonar.api.security.SecurityRealm;
import org.sonar.api.server.authentication.IdentityProvider;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.process.ProcessProperties;
import org.sonar.server.authentication.IdentityProviderRepository;
import org.sonar.server.platform.ServerId;
.stream()
.filter(IdentityProvider::isEnabled)
.map(IdentityProvider::getName)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
private List<String> getAllowsToSignUpEnabledIdentityProviders() {
.filter(IdentityProvider::isEnabled)
.filter(IdentityProvider::allowsUsersToSignUp)
.map(IdentityProvider::getName)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
private boolean getForceAuthentication() {
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static java.lang.String.format;
Predicate<Redirect> match = redirect -> redirect.test(path);
List<Redirect> redirects = REDIRECTS.stream()
.filter(match)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
switch (redirects.size()) {
case 0:
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.process.ProcessId;
import org.sonar.server.platform.ServerLogging;
import org.sonar.server.user.UserSession;
.setPossibleValues(stream(ProcessId.values())
.map(ProcessId::getKey)
.sorted()
- .collect(Collectors.toList(ProcessId.values().length)))
+ .collect(MoreCollectors.toList(ProcessId.values().length)))
.setDefaultValue(ProcessId.APP.getKey())
.setSince("6.2")
.setDescription("Process to get logs from");
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.text.JsonWriter;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import static java.util.Optional.ofNullable;
import static org.sonar.api.web.UserRole.USER;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.ACTION_INDEX;
// Meanwhile root is explicitly handled.
return components;
}
- Set<String> projectUuids = components.stream().map(ComponentDto::projectUuid).collect(Collectors.toSet());
+ Set<String> projectUuids = components.stream().map(ComponentDto::projectUuid).collect(MoreCollectors.toSet());
List<ComponentDto> projects = dbClient.componentDao().selectByUuids(dbSession, projectUuids);
Map<String, Long> projectIdsByUuids = projects.stream().collect(uniqueIndex(ComponentDto::uuid, ComponentDto::getId));
Collection<Long> authorizedProjectIds = dbClient.authorizationDao().keepAuthorizedProjectIds(dbSession, projectIdsByUuids.values(), userSession.getUserId(), USER);
return components.stream()
.filter(component -> authorizedProjectIds.contains(projectIdsByUuids.get(component.projectUuid())))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
private static void addProject(JsonWriter json, ComponentDto project) {
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonarqube.ws.client.projectanalysis.SearchRequest;
import static com.google.common.base.Preconditions.checkArgument;
-import static org.sonar.core.util.stream.Collectors.toOneElement;
+import static org.sonar.core.util.stream.MoreCollectors.toOneElement;
import static org.sonar.db.component.SnapshotQuery.SORT_FIELD.BY_DATE;
import static org.sonar.db.component.SnapshotQuery.SORT_ORDER.DESC;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
private Consumer<SearchResults.Builder> addEvents() {
return data -> {
- List<String> analyses = data.getAnalyses().stream().map(SnapshotDto::getUuid).collect(Collectors.toList());
+ List<String> analyses = data.getAnalyses().stream().map(SnapshotDto::getUuid).collect(MoreCollectors.toList());
data.setEvents(dbClient.eventDao().selectByAnalysisUuids(data.getDbSession(), analyses));
};
}
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Stream;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.event.EventDto;
import org.sonarqube.ws.ProjectAnalyses.Analysis;
.peek(addAnalyses(searchResults))
.peek(addPagination(searchResults))
.map(SearchResponse.Builder::build)
- .collect(Collectors.toOneElement());
+ .collect(MoreCollectors.toOneElement());
}
private Consumer<SearchResponse.Builder> addAnalyses(SearchResults searchResults) {
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.sonar.api.utils.Paging;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
}
private ListMultimap<String, EventDto> buildEvents(List<EventDto> events) {
- return events.stream().collect(Collectors.index(EventDto::getAnalysisUuid));
+ return events.stream().collect(MoreCollectors.index(EventDto::getAnalysisUuid));
}
static Builder builder(DbSession dbSession, SearchRequest request) {
.limit(request.getPageSize());
}
- this.analyses = stream.collect(Collectors.toList());
+ this.analyses = stream.collect(MoreCollectors.toList());
this.countAnalyses = analyses.size();
return this;
}
private void filterByCategory() {
ListMultimap<String, String> eventCategoriesByAnalysisUuid = events.stream()
- .collect(Collectors.index(EventDto::getAnalysisUuid, EventDto::getCategory));
+ .collect(MoreCollectors.index(EventDto::getAnalysisUuid, EventDto::getCategory));
Predicate<SnapshotDto> byCategory = a -> eventCategoriesByAnalysisUuid.get(a.getUuid()).contains(request.getCategory().getLabel());
this.countAnalyses = (int) analyses.stream().filter(byCategory).count();
this.analyses = analyses.stream()
.filter(byCategory)
.skip(Paging.offset(request.getPage(), request.getPageSize()))
.limit(request.getPageSize())
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
SearchResults build() {
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
.map(t -> t.toLowerCase(Locale.ENGLISH))
.map(SetAction::checkTag)
.distinct()
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
try (DbSession dbSession = dbClient.openSession(false)) {
ComponentDto project = componentFinder.getByKey(dbSession, projectKey);
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.Paging;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualitygate.ProjectQgateAssociation;
}
private static List<ProjectQgateAssociationDto> getPaginatedProjects(List<ProjectQgateAssociationDto> projects, Paging paging) {
- return projects.stream().skip(paging.offset()).limit(paging.pageSize()).collect(Collectors.toList());
+ return projects.stream().skip(paging.offset()).limit(paging.pageSize()).collect(MoreCollectors.toList());
}
private static List<ProjectQgateAssociation> toProjectAssociations(List<ProjectQgateAssociationDto> dtos) {
- return dtos.stream().map(ProjectQgateAssociationDto::toQgateAssociation).collect(Collectors.toList());
+ return dtos.stream().map(ProjectQgateAssociationDto::toQgateAssociation).collect(MoreCollectors.toList());
}
private List<ProjectQgateAssociationDto> keepAuthorizedProjects(DbSession dbSession, List<ProjectQgateAssociationDto> projects) {
// Meanwhile root is explicitly handled.
return projects;
}
- List<Long> projectIds = projects.stream().map(ProjectQgateAssociationDto::getId).collect(Collectors.toList());
+ List<Long> projectIds = projects.stream().map(ProjectQgateAssociationDto::getId).collect(MoreCollectors.toList());
Collection<Long> authorizedProjectIds = dbClient.authorizationDao().keepAuthorizedProjectIds(dbSession, projectIds, userSession.getUserId(), UserRole.USER);
- return projects.stream().filter(project -> authorizedProjectIds.contains(project.getId())).collect(Collectors.toList());
+ return projects.stream().filter(project -> authorizedProjectIds.contains(project.getId())).collect(MoreCollectors.toList());
}
public static class Association {
import org.sonar.api.measures.CoreMetrics;
import static org.sonar.api.measures.Metric.ValueType.RATING;
-import static org.sonar.core.util.stream.Collectors.toSet;
+import static org.sonar.core.util.stream.MoreCollectors.toSet;
public class ValidRatingMetrics {
import java.util.concurrent.ExecutionException;
import org.picocontainer.Startable;
import org.sonar.api.rule.RuleKey;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDto;
private Map<RuleKey, ActiveRuleDto> loadActiveRulesOfQualityProfile(DbSession session, String profileKey) {
return dbClient.activeRuleDao().selectByProfileKey(session, profileKey).stream()
- .collect(Collectors.uniqueIndex(dto -> dto.getKey().ruleKey()));
+ .collect(MoreCollectors.uniqueIndex(dto -> dto.getKey().ruleKey()));
}
}
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
Map<String, List<DefinedQProfile.Builder>> buildersByLanguage = Multimaps.asMap(rulesProfilesByLanguage)
.entrySet()
.stream()
- .collect(Collectors.uniqueIndex(Map.Entry::getKey, DefinedQProfileRepositoryImpl::toQualityProfileBuilders));
+ .collect(MoreCollectors.uniqueIndex(Map.Entry::getKey, DefinedQProfileRepositoryImpl::toQualityProfileBuilders));
return buildersByLanguage
.entrySet()
.stream()
.filter(DefinedQProfileRepositoryImpl::ensureAtMostOneDeclaredDefault)
- .collect(Collectors.uniqueIndex(Map.Entry::getKey, entry -> toQualityProfiles(entry.getValue()), buildersByLanguage.size()));
+ .collect(MoreCollectors.uniqueIndex(Map.Entry::getKey, entry -> toQualityProfiles(entry.getValue()), buildersByLanguage.size()));
}
/**
Set<String> declaredDefaultProfileNames = entry.getValue().stream()
.filter(DefinedQProfile.Builder::isDeclaredDefault)
.map(DefinedQProfile.Builder::getName)
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
checkState(declaredDefaultProfileNames.size() <= 1, "Several Quality profiles are flagged as default for the language %s: %s", entry.getKey(), declaredDefaultProfileNames);
return true;
}
MessageDigest md5Digest = DigestUtils.getMd5Digest();
return builders.stream()
.map(builder -> builder.build(md5Digest))
- .collect(Collectors.toList(builders.size()));
+ .collect(MoreCollectors.toList(builders.size()));
}
}
import org.sonar.core.util.UtcDateUtils;
import static java.util.function.Function.identity;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
/**
* Represents the array of JSON objects stored in the value of the
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.sonar.api.utils.System2;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleKey;
deleteKeys(changes.stream()
.filter(c -> c.getType().equals(ActiveRuleChange.Type.DEACTIVATED))
.map(ActiveRuleChange::getKey)
- .collect(Collectors.toList(changes.size())));
+ .collect(MoreCollectors.toList(changes.size())));
index();
}
import javax.annotation.Nullable;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.server.ServerSide;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QProfileChangeDto;
List<QProfileChangeDto> dtos = dbClient.qProfileChangeDao().selectByQuery(dbSession, query);
List<Change> changes = dtos.stream()
.map(Change::from)
- .collect(Collectors.toList(dtos.size()));
+ .collect(MoreCollectors.toList(dtos.size()));
completeUserAndRuleNames(dbSession, changes);
int total = dbClient.qProfileChangeDao().countForProfileKey(dbSession, query.getProfileKey());
}
private void completeUserAndRuleNames(DbSession dbSession, List<Change> changes) {
- Set<String> logins = changes.stream().filter(c -> c.userLogin != null).map(c -> c.userLogin).collect(Collectors.toSet());
+ Set<String> logins = changes.stream().filter(c -> c.userLogin != null).map(c -> c.userLogin).collect(MoreCollectors.toSet());
Map<String, String> userNamesByLogins = dbClient.userDao()
.selectByLogins(dbSession, logins)
.stream()
.collect(java.util.stream.Collectors.toMap(UserDto::getLogin, UserDto::getName));
- Set<RuleKey> ruleKeys = changes.stream().filter(c -> c.ruleKey != null).map(c -> c.ruleKey).collect(Collectors.toSet());
+ Set<RuleKey> ruleKeys = changes.stream().filter(c -> c.ruleKey != null).map(c -> c.ruleKey).collect(MoreCollectors.toSet());
Map<RuleKey, String> ruleNamesByKeys = dbClient.ruleDao()
.selectDefinitionByKeys(dbSession, Lists.newArrayList(ruleKeys))
.stream()
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.NewController;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.QualityProfileDto;
private static List<String> toKeys(QualityProfileDto profile, List<QualityProfileDto> descendants) {
return Stream.concat(Stream.of(profile), descendants.stream())
.map(QualityProfileDto::getKee)
- .collect(Collectors.toList(descendants.size() + 1));
+ .collect(MoreCollectors.toList(descendants.size() + 1));
}
}
import org.sonar.api.server.ws.Response.Stream;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.NewAction;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationDto;
.map(language -> exporters.exportersForLanguage(language.getKey()))
.flatMap(Collection::stream)
.map(ProfileExporter::getKey)
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
if (!exporterKeys.isEmpty()) {
action.createParam(PARAM_FORMAT)
.setDescription("Output format. If left empty, the same format as api/qualityprofiles/backup is used. " +
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.Uuids;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
.setExampleValue("Sonar way");
action.createParam(PARAM_LANGUAGE)
.setDescription("A quality profile language. If this parameter is set, profileKey must not be set and profileName must be set to disambiguate.")
- .setPossibleValues(Arrays.stream(languages.all()).map(Language::getKey).collect(Collectors.toSet()));
+ .setPossibleValues(Arrays.stream(languages.all()).map(Language::getKey).collect(MoreCollectors.toSet()));
}
}
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
import org.sonar.api.utils.log.Profiler;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationDto;
session.commit();
persistRepositories(session, context.repositories());
- ruleIndexer.delete(removedRules.stream().map(RuleDefinitionDto::getKey).collect(Collectors.toList(removedRules.size())));
+ ruleIndexer.delete(removedRules.stream().map(RuleDefinitionDto::getKey).collect(MoreCollectors.toList(removedRules.size())));
ruleIndexer.index(getDefaultOrganization(), keysToIndex);
activeRuleIndexer.index(changes);
profiler.stopDebug();
List<RuleRepositoryDto> dtos = repositories
.stream()
.map(r -> new RuleRepositoryDto(r.key(), r.language(), r.name()))
- .collect(Collectors.toList(repositories.size()));
+ .collect(MoreCollectors.toList(repositories.size()));
dbClient.ruleRepositoryDao().insert(dbSession, dtos);
dbSession.commit();
}
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.qualityprofile.ActiveRuleDto;
if (profileKey != null) {
// Load details of active rules on the selected profile
List<ActiveRuleDto> activeRuleDtos = dbClient.activeRuleDao().selectByProfileKey(dbSession, profileKey);
- Map<RuleKey, ActiveRuleDto> activeRuleByRuleKey = activeRuleDtos.stream().collect(Collectors.uniqueIndex(d -> d.getKey().ruleKey()));
+ Map<RuleKey, ActiveRuleDto> activeRuleByRuleKey = activeRuleDtos.stream().collect(MoreCollectors.uniqueIndex(d -> d.getKey().ruleKey()));
ListMultimap<ActiveRuleKey, ActiveRuleParamDto> activeRuleParamsByActiveRuleKey = activeRuleDtosToActiveRuleParamDtos(dbSession, activeRuleDtos);
for (RuleDto rule : rules) {
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.text.JsonWriter;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.rule.RuleRepositoryDto;
return selectFromDb(languageKey).stream()
.filter(r -> pattern.matcher(r.getKey()).matches() || pattern.matcher(r.getName()).matches())
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
private Collection<RuleRepositoryDto> selectFromDb(@Nullable String language) {
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.rule.RuleDefinitionDto;
rules.add(rule);
}
}
- List<Integer> ruleIds = rules.stream().map(RuleDto::getId).collect(Collectors.toList());
+ List<Integer> ruleIds = rules.stream().map(RuleDto::getId).collect(MoreCollectors.toList());
List<Integer> templateRuleIds = rules.stream()
.map(RuleDto::getTemplateId)
.filter(Objects::nonNull)
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
List<RuleDefinitionDto> templateRules = dbClient.ruleDao().selectDefinitionByIds(dbSession, templateRuleIds);
List<RuleParamDto> ruleParamDtos = dbClient.ruleDao().selectRuleParamsByRuleIds(dbSession, ruleIds);
return new SearchResult()
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.property.PropertyDto;
userSession.checkIsSystemAdministrator();
try (DbSession dbSession = dbClient.openSession(true)) {
Map<String, PropertyDto> properties = dbClient.propertiesDao().selectGlobalPropertiesByKeys(dbSession, SETTINGS_KEYS).stream()
- .collect(Collectors.uniqueIndex(PropertyDto::getKey, Function.identity()));
+ .collect(MoreCollectors.uniqueIndex(PropertyDto::getKey, Function.identity()));
writeProtobuf(doHandle(properties), request, response);
}
}
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
PropertyDefinition definition = definitions.get(key);
return definition != null ? definition.key() : key;
})
- .collect(Collectors.toSet()));
+ .collect(MoreCollectors.toSet()));
}
private static ResetRequest toWsRequest(Request request) {
import java.util.Optional;
import java.util.function.Function;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.protobuf.DbFileSources;
.filter(line -> line.hasLine() && line.getLine() >= from)
.limit((toInclusive - from) + 1L)
.map(function)
- .collect(Collectors.toList()));
+ .collect(MoreCollectors.toList()));
}
private static void verifyLine(int line) {
import org.sonar.api.web.page.Page.Scope;
import org.sonar.api.web.page.PageDefinition;
import org.sonar.core.platform.PluginRepository;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Collections.emptyList;
.peek(checkWellFormed())
.peek(checkPluginExists())
.sorted(comparing(Page::getKey))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
@Override
.filter(p -> p.getScope().equals(scope))
.filter(p -> p.isAdmin() == isAdmin)
.filter(p -> GLOBAL.equals(p.getScope()) || p.getComponentQualifiers().contains(qualifier))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
}
@VisibleForTesting
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
}
return permissionKeys.stream()
.map(OrganizationPermission::fromKey)
- .collect(Collectors.toSet(permissionKeys.size()));
+ .collect(MoreCollectors.toSet(permissionKeys.size()));
}
@Override
import org.sonar.api.platform.NewUserHandler;
import org.sonar.api.server.ServerSide;
import org.sonar.api.utils.System2;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationMemberDto;
private static List<String> sanitizeScmAccounts(@Nullable List<String> scmAccounts) {
if (scmAccounts != null) {
- return scmAccounts.stream().filter(s -> !Strings.isNullOrEmpty(s)).collect(Collectors.toList());
+ return scmAccounts.stream().filter(s -> !Strings.isNullOrEmpty(s)).collect(MoreCollectors.toList());
}
return Collections.emptyList();
}
import org.sonar.api.server.ws.WebService.NewController;
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.text.JsonWriter;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationDto;
int limit = dbClient.groupDao().countByQuery(dbSession, organization.getUuid(), query);
List<GroupDto> groups = dbClient.groupDao().selectByQuery(dbSession, organization.getUuid(), query, options.getOffset(), pageSize);
- List<Integer> groupIds = groups.stream().map(GroupDto::getId).collect(Collectors.toList(groups.size()));
+ List<Integer> groupIds = groups.stream().map(GroupDto::getId).collect(MoreCollectors.toList(groups.size()));
Map<String, Integer> userCountByGroup = dbClient.groupMembershipDao().countUsersByGroups(dbSession, groupIds);
JsonWriter json = response.newJsonWriter().beginObject();
import javax.servlet.http.HttpServletResponse;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.web.ServletFilter;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static java.util.stream.Stream.concat;
import static org.sonar.server.property.ws.PropertiesWs.CONTROLLER_PROPERTIES;
webServiceEngine.controllers().stream()
.flatMap(controller -> controller.actions().stream())
.map(toPath()))
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
this.excludeUrls = concat(concat(
Stream.of("/" + CONTROLLER_PROPERTIES + "*"),
MOVED_WEB_SERVICES.stream()),
.flatMap(controller -> controller.actions().stream())
.filter(action -> action.handler() instanceof ServletFilterHandler)
.map(toPath()))
- .collect(Collectors.toSet());
+ .collect(MoreCollectors.toSet());
}
@Override
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.text.JsonWriter;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static com.google.common.base.Preconditions.checkState;
}
private static void writeParameters(JsonWriter writer, WebService.Action action, boolean includeInternals) {
- List<WebService.Param> params = action.params().stream().filter(p -> includeInternals || !p.isInternal()).collect(Collectors.toList());
+ List<WebService.Param> params = action.params().stream().filter(p -> includeInternals || !p.isInternal()).collect(MoreCollectors.toList());
if (!params.isEmpty()) {
// sort parameters by key
Ordering<WebService.Param> ordering = Ordering.natural().onResultOf(WebService.Param::key);
import org.sonar.api.config.Settings;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.internal.AlwaysIncreasingSystem2;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbTester;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
if (expectedGroups.length == 0) {
assertThat(db.users().selectGroupIdsOfUser(userDto)).isEmpty();
} else {
- assertThat(db.users().selectGroupIdsOfUser(userDto)).containsOnly(stream(expectedGroups).map(GroupDto::getId).collect(Collectors.toList()).toArray(new Integer[] {}));
+ assertThat(db.users().selectGroupIdsOfUser(userDto)).containsOnly(stream(expectedGroups).map(GroupDto::getId).collect(MoreCollectors.toList()).toArray(new Integer[] {}));
}
}
import org.sonar.api.server.authentication.UserIdentity;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.internal.AlwaysIncreasingSystem2;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbTester;
import org.sonar.db.organization.OrganizationDto;
import org.sonar.db.user.GroupDto;
.setLogin(login)
.setName("John")
// No group
- .setGroups(Arrays.stream(groups).collect(Collectors.toSet()))
+ .setGroups(Arrays.stream(groups).collect(MoreCollectors.toSet()))
.build(), IDENTITY_PROVIDER, Source.sso());
}
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.SORT;
import static org.sonar.api.utils.DateUtils.formatDateTime;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
import static org.sonar.db.component.ComponentTesting.newDeveloper;
import static org.sonar.db.component.ComponentTesting.newDirectory;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
tester.get(PermissionUpdater.class).apply(session, Arrays.stream(permissions)
// TODO correctly feed default organization. Not a problem as long as issues search does not support "anyone" for each organization
.map(permission -> new GroupPermissionChange(PermissionChange.Operation.ADD, permission, new ProjectId(project), GroupIdOrAnyone.forAnyone(project.getOrganizationUuid())))
- .collect(Collectors.toList()));
+ .collect(MoreCollectors.toList()));
}
private ComponentDto insertComponent(ComponentDto component) {
import org.sonar.api.server.ws.WebService.Param;
import org.sonar.api.utils.System2;
import org.sonar.api.web.UserRole;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
.mapToObj(i -> dbClient.snapshotDao().insert(dbSession, newAnalysis(project).setCreatedAt(i * 1_000_000_000)))
.peek(a -> dbClient.measureDao().insert(dbSession, newMeasureDto(complexityMetric, project, a).setValue(101d)))
.map(a -> formatDateTime(a.getCreatedAt()))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
db.commit();
wsRequest.setComponent(project.getKey()).setPage(2).setPageSize(3);
.mapToObj(i -> dbClient.snapshotDao().insert(dbSession, newAnalysis(project).setCreatedAt(System2.INSTANCE.now() + i * 1_000_000_000L)))
.peek(a -> dbClient.measureDao().insert(dbSession, newMeasureDto(complexityMetric, project, a).setValue(Double.valueOf(a.getCreatedAt()))))
.map(a -> formatDateTime(a.getCreatedAt()))
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
db.commit();
wsRequest.setComponent(project.getKey()).setFrom(analysisDates.get(1)).setTo(analysisDates.get(3));
import java.util.List;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHits;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.server.es.EsClient;
import static org.sonar.server.permission.index.FooIndexDefinition.FOO_INDEX;
.getHits();
List<String> names = Arrays.stream(hits.hits())
.map(h -> h.getSource().get(FooIndexDefinition.FIELD_NAME).toString())
- .collect(Collectors.toList());
+ .collect(MoreCollectors.toList());
return names.size() == 2 && names.contains("bar") && names.contains("baz");
}
}
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
Map<String, PermissionIndexerDao.Dto> dtos = underTest.selectByUuids(dbClient, dbSession, asList(project1.uuid(), project2.uuid(), view1.uuid(), view2.uuid()))
.stream()
- .collect(Collectors.uniqueIndex(PermissionIndexerDao.Dto::getProjectUuid, Function.identity()));
+ .collect(MoreCollectors.uniqueIndex(PermissionIndexerDao.Dto::getProjectUuid, Function.identity()));
assertThat(dtos).hasSize(4);
PermissionIndexerDao.Dto project1Authorization = dtos.get(project1.uuid());
Map<String, PermissionIndexerDao.Dto> dtos = underTest.selectByUuids(dbClient, dbSession, projects)
.stream()
- .collect(Collectors.uniqueIndex(PermissionIndexerDao.Dto::getProjectUuid, Function.identity()));
+ .collect(MoreCollectors.uniqueIndex(PermissionIndexerDao.Dto::getProjectUuid, Function.identity()));
assertThat(dtos).hasSize(350);
}
import org.sonar.api.rules.RulePriority;
import org.sonar.api.utils.System2;
import org.sonar.core.util.UuidFactory;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
rule.setParams(Arrays.stream(parameters)
.filter(new EvenElementPredicate())
.map(s -> new RuleParam(rule, s, "desc of s", "type of s"))
- .collect(Collectors.toList(parameters.length / 2)));
+ .collect(MoreCollectors.toList(parameters.length / 2)));
ActiveRule res = new ActiveRule(
new RulesProfile("rule_profile_name_" + id, "language_" + id),
rule.setSeverity(rulePriority),
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.rules.ExternalResource;
import org.sonar.api.resources.Language;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import static com.google.common.base.Preconditions.checkState;
-import static org.sonar.core.util.stream.Collectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
public class DefinedQProfileRepositoryRule extends ExternalResource implements DefinedQProfileRepository {
private boolean initializeCalled = false;
if (existing == null) {
return ImmutableList.of(definedQProfile);
}
- return Stream.concat(existing.stream(), Stream.of(definedQProfile)).collect(Collectors.toList(existing.size() + 1));
+ return Stream.concat(existing.stream(), Stream.of(definedQProfile)).collect(MoreCollectors.toList(existing.size() + 1));
});
return definedQProfile;
}
import org.sonar.api.rule.Severity;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.utils.System2;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
RuleDto rule2 = createRule();
createActiveRule(rule1, parent1);
createActiveRule(rule2, parent2);
- ruleIndexer.index(organization, Stream.of(rule1, rule2).map(RuleDto::getKey).collect(Collectors.toList()));
+ ruleIndexer.index(organization, Stream.of(rule1, rule2).map(RuleDto::getKey).collect(MoreCollectors.toList()));
activeRuleIndexer.index();
// Set parent 1
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.server.ws.WebService;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.organization.OrganizationDto;
ruleDao.insertOrUpdate(session, rule2.getMetadata().setRuleId(rule2.getId()));
session.commit();
- ruleIndexer.index(defaultOrganization, Stream.of(rule, rule2).map(RuleDto::getKey).collect(Collectors.toList()));
+ ruleIndexer.index(defaultOrganization, Stream.of(rule, rule2).map(RuleDto::getKey).collect(MoreCollectors.toList()));
tester.wsTester().newGetRequest(API_ENDPOINT, API_TAGS_METHOD).execute().assertJson(this.getClass(), "get_tags.json");
tester.wsTester().newGetRequest(API_ENDPOINT, API_TAGS_METHOD)
import static org.sonar.api.measures.CoreMetrics.TEST_FAILURES;
import static org.sonar.api.measures.CoreMetrics.UNCOVERED_CONDITIONS;
import static org.sonar.api.measures.CoreMetrics.UNCOVERED_LINES;
-import static org.sonar.core.util.stream.Collectors.toSet;
+import static org.sonar.core.util.stream.MoreCollectors.toSet;
/**
* This class is used to know the list of metrics that can be sent in the analysis report.
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2017 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.util.stream;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableListMultimap;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.function.BiConsumer;
-import java.util.function.BinaryOperator;
-import java.util.function.Function;
-import java.util.function.Supplier;
-import java.util.stream.Collector;
-
-import static java.util.Objects.requireNonNull;
-
-public final class Collectors {
-
- private static final int DEFAULT_HASHMAP_CAPACITY = 0;
-
- private Collectors() {
- // prevents instantiation
- }
-
- /**
- * A Collector into an {@link ImmutableList}.
- */
- public static <T> Collector<T, List<T>, List<T>> toList() {
- return Collector.of(
- ArrayList::new,
- List::add,
- (left, right) -> {
- left.addAll(right);
- return left;
- },
- ImmutableList::copyOf);
- }
-
- /**
- * A Collector into an {@link ImmutableList} of the specified expected size.
- *
- * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
- * processing threads will use a List with a capacity large enough for the final size.</p>
- */
- public static <T> Collector<T, List<T>, List<T>> toList(int expectedSize) {
- // use ArrayList rather than ImmutableList.Builder because initial capacity of builder can not be specified
- return Collector.of(
- () -> new ArrayList<>(expectedSize),
- List::add,
- (left, right) -> {
- left.addAll(right);
- return left;
- },
- ImmutableList::copyOf);
- }
-
- /**
- * A Collector into an {@link ImmutableSet}.
- */
- public static <T> Collector<T, Set<T>, Set<T>> toSet() {
- return Collector.of(
- HashSet::new,
- Set::add,
- (left, right) -> {
- left.addAll(right);
- return left;
- },
- ImmutableSet::copyOf);
- }
-
- /**
- * A Collector into an {@link ImmutableSet} of the specified expected size.
- *
- * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
- * processing threads will use a Set with a capacity large enough for the final size.</p>
- */
- public static <T> Collector<T, Set<T>, Set<T>> toSet(int expectedSize) {
- // use HashSet rather than ImmutableSet.Builder because initial capacity of builder can not be specified
- return Collector.of(
- () -> new HashSet<>(expectedSize),
- Set::add,
- (left, right) -> {
- left.addAll(right);
- return left;
- },
- ImmutableSet::copyOf);
- }
-
- /**
- * Delegates to {@link java.util.stream.Collectors#toCollection(Supplier)}.
- */
- public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
- return java.util.stream.Collectors.toCollection(ArrayList::new);
- }
-
- /**
- * Does {@code java.util.stream.Collectors.toCollection(() -> new ArrayList<>(size));} which is equivalent to
- * {@link #toArrayList()} but avoiding array copies when the size of the resulting list is already known.
- *
- * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
- * processing threads will use a ArrayList with a capacity large enough for the final size.</p>
- *
- * @see java.util.stream.Collectors#toList()
- * @see java.util.stream.Collectors#toCollection(Supplier)
- */
- public static <T> Collector<T, ?, ArrayList<T>> toArrayList(int size) {
- return java.util.stream.Collectors.toCollection(() -> new ArrayList<>(size));
- }
-
- /**
- * Delegates to {@link java.util.stream.Collectors#toCollection(Supplier)}.
- */
- public static <T> Collector<T, ?, HashSet<T>> toHashSet() {
- return java.util.stream.Collectors.toCollection(HashSet::new);
- }
-
- /**
- * Does {@code java.util.stream.Collectors.toCollection(() -> new HashSet<>(size));} which is equivalent to
- * {@link #toHashSet()} but avoiding array copies when the size of the resulting set is already known.
- *
- * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
- * processing threads will use a HashSet with a capacity large enough for the final size.</p>
- *
- * @see java.util.stream.Collectors#toSet()
- * @see java.util.stream.Collectors#toCollection(Supplier)
- */
- public static <T> Collector<T, ?, HashSet<T>> toHashSet(int size) {
- return java.util.stream.Collectors.toCollection(() -> new HashSet<>(size));
- }
-
- /**
- * Creates an {@link ImmutableMap} from the stream where the values are the values in the stream and the keys are the
- * result of the provided {@link Function keyFunction} applied to each value in the stream.
- *
- * <p>
- * The {@link Function keyFunction} must return a unique (according to the key's type {@link Object#equals(Object)}
- * and/or {@link Comparable#compareTo(Object)} implementations) value for each of them, otherwise a
- * {@link IllegalArgumentException} will be thrown.
- * </p>
- *
- * <p>
- * {@link Function keyFunction} can't return {@code null}, otherwise a {@link NullPointerException} will be thrown.
- * </p>
- *
- * @throws NullPointerException if {@code keyFunction} is {@code null}.
- * @throws NullPointerException if result of {@code keyFunction} is {@code null}.
- * @throws IllegalArgumentException if {@code keyFunction} returns the same value for multiple entries in the stream.
- */
- public static <K, E> Collector<E, Map<K, E>, ImmutableMap<K, E>> uniqueIndex(Function<? super E, K> keyFunction) {
- return uniqueIndex(keyFunction, Function.<E>identity());
- }
-
- /**
- * Same as {@link #uniqueIndex(Function)} but using an underlying {@link Map} initialized with a capacity for the
- * specified expected size.
- *
- * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
- * processing threads will use a Map with a capacity large enough for the final size.</p>
- *
- * <p>
- * {@link Function keyFunction} can't return {@code null}, otherwise a {@link NullPointerException} will be thrown.
- * </p>
- *
- * @throws NullPointerException if {@code keyFunction} is {@code null}.
- * @throws NullPointerException if result of {@code keyFunction} is {@code null}.
- * @throws IllegalArgumentException if {@code keyFunction} returns the same value for multiple entries in the stream.
- * @see #uniqueIndex(Function)
- */
- public static <K, E> Collector<E, Map<K, E>, ImmutableMap<K, E>> uniqueIndex(Function<? super E, K> keyFunction, int expectedSize) {
- return uniqueIndex(keyFunction, Function.<E>identity(), expectedSize);
- }
-
- /**
- * Creates an {@link ImmutableMap} from the stream where the values are the result of {@link Function valueFunction}
- * applied to the values in the stream and the keys are the result of the provided {@link Function keyFunction}
- * applied to each value in the stream.
- *
- * <p>
- * The {@link Function keyFunction} must return a unique (according to the key's type {@link Object#equals(Object)}
- * and/or {@link Comparable#compareTo(Object)} implementations) value for each of them, otherwise a
- * {@link IllegalArgumentException} will be thrown.
- * </p>
- *
- * <p>
- * Neither {@link Function keyFunction} nor {@link Function valueFunction} can return {@code null}, otherwise a
- * {@link NullPointerException} will be thrown.
- * </p>
- *
- * @throws NullPointerException if {@code keyFunction} or {@code valueFunction} is {@code null}.
- * @throws NullPointerException if result of {@code keyFunction} or {@code valueFunction} is {@code null}.
- * @throws IllegalArgumentException if {@code keyFunction} returns the same value for multiple entries in the stream.
- */
- public static <K, E, V> Collector<E, Map<K, V>, ImmutableMap<K, V>> uniqueIndex(Function<? super E, K> keyFunction,
- Function<? super E, V> valueFunction) {
- return uniqueIndex(keyFunction, valueFunction, DEFAULT_HASHMAP_CAPACITY);
- }
-
- /**
- * Same as {@link #uniqueIndex(Function, Function)} but using an underlying {@link Map} initialized with a capacity
- * for the specified expected size.
- *
- * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
- * processing threads will use a Map with a capacity large enough for the final size.</p>
- *
- * <p>
- * Neither {@link Function keyFunction} nor {@link Function valueFunction} can return {@code null}, otherwise a
- * {@link NullPointerException} will be thrown.
- * </p>
- *
- * @throws NullPointerException if {@code keyFunction} or {@code valueFunction} is {@code null}.
- * @throws NullPointerException if result of {@code keyFunction} or {@code valueFunction} is {@code null}.
- * @throws IllegalArgumentException if {@code keyFunction} returns the same value for multiple entries in the stream.
- * @see #uniqueIndex(Function, Function)
- */
- public static <K, E, V> Collector<E, Map<K, V>, ImmutableMap<K, V>> uniqueIndex(Function<? super E, K> keyFunction,
- Function<? super E, V> valueFunction, int expectedSize) {
- requireNonNull(keyFunction, "Key function can't be null");
- requireNonNull(valueFunction, "Value function can't be null");
- BiConsumer<Map<K, V>, E> accumulator = (map, element) -> {
- K key = requireNonNull(keyFunction.apply(element), "Key function can't return null");
- V value = requireNonNull(valueFunction.apply(element), "Value function can't return null");
-
- putAndFailOnDuplicateKey(map, key, value);
- };
- BinaryOperator<Map<K, V>> merger = (m1, m2) -> {
- for (Map.Entry<K, V> entry : m2.entrySet()) {
- putAndFailOnDuplicateKey(m1, entry.getKey(), entry.getValue());
- }
- return m1;
- };
- return Collector.of(
- newHashMapSupplier(expectedSize),
- accumulator,
- merger,
- ImmutableMap::copyOf,
- Collector.Characteristics.UNORDERED);
- }
-
- /**
- * For stream of one expected element, return the element
- *
- * @throws IllegalArgumentException if stream has no element or more than 1 element
- */
- public static <T> Collector<T, ?, T> toOneElement() {
- return java.util.stream.Collectors.collectingAndThen(
- java.util.stream.Collectors.toList(),
- list -> {
- if (list.size() != 1) {
- throw new IllegalStateException("Stream should have only one element");
- }
- return list.get(0);
- });
- }
-
- private static <K, V> Supplier<Map<K, V>> newHashMapSupplier(int expectedSize) {
- return () -> expectedSize == DEFAULT_HASHMAP_CAPACITY ? new HashMap<>() : new HashMap<>(expectedSize);
- }
-
- private static <K, V> void putAndFailOnDuplicateKey(Map<K, V> map, K key, V value) {
- V existingValue = map.put(key, value);
- if (existingValue != null) {
- throw new IllegalArgumentException(String.format("Duplicate key %s", key));
- }
- }
-
- /**
- * Creates an {@link com.google.common.collect.ImmutableListMultimap} from the stream where the values are the values
- * in the stream and the keys are the result of the provided {@link Function keyFunction} applied to each value in the
- * stream.
- *
- * <p>
- * Neither {@link Function keyFunction} nor {@link Function valueFunction} can return {@code null}, otherwise a
- * {@link NullPointerException} will be thrown.
- * </p>
- *
- * @throws NullPointerException if {@code keyFunction} or {@code valueFunction} is {@code null}.
- * @throws NullPointerException if result of {@code keyFunction} or {@code valueFunction} is {@code null}.
- */
- public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) {
- return index(keyFunction, Function.<E>identity());
- }
-
- /**
- * Creates an {@link com.google.common.collect.ImmutableListMultimap} from the stream where the values are the result
- * of {@link Function valueFunction} applied to the values in the stream and the keys are the result of the provided
- * {@link Function keyFunction} applied to each value in the stream.
- *
- * <p>
- * Neither {@link Function keyFunction} nor {@link Function valueFunction} can return {@code null}, otherwise a
- * {@link NullPointerException} will be thrown.
- * </p>
- *
- * @throws NullPointerException if {@code keyFunction} or {@code valueFunction} is {@code null}.
- * @throws NullPointerException if result of {@code keyFunction} or {@code valueFunction} is {@code null}.
- */
- public static <K, E, V> Collector<E, ImmutableListMultimap.Builder<K, V>, ImmutableListMultimap<K, V>> index(Function<? super E, K> keyFunction,
- Function<? super E, V> valueFunction) {
- requireNonNull(keyFunction, "Key function can't be null");
- requireNonNull(valueFunction, "Value function can't be null");
- BiConsumer<ImmutableListMultimap.Builder<K, V>, E> accumulator = (map, element) -> {
- K key = requireNonNull(keyFunction.apply(element), "Key function can't return null");
- V value = requireNonNull(valueFunction.apply(element), "Value function can't return null");
-
- map.put(key, value);
- };
- BinaryOperator<ImmutableListMultimap.Builder<K, V>> merger = (m1, m2) -> {
- for (Map.Entry<K, V> entry : m2.build().entries()) {
- m1.put(entry.getKey(), entry.getValue());
- }
- return m1;
- };
- return Collector.of(
- ImmutableListMultimap::builder,
- accumulator,
- merger,
- ImmutableListMultimap.Builder::build);
- }
-
- /**
- * Applies the specified {@link Joiner} to the current stream.
- *
- * @throws NullPointerException of {@code joiner} is {@code null}
- * @throws IllegalStateException if a merge operation happens because parallel processing has been enabled on the current stream
- */
- public static <E> Collector<E, List<E>, String> join(Joiner joiner) {
- requireNonNull(joiner, "Joiner can't be null");
-
- return Collector.of(
- ArrayList::new,
- List::add,
- mergeNotSupportedMerger(),
- joiner::join);
- }
-
- private static <R> BinaryOperator<R> mergeNotSupportedMerger() {
- return (m1, m2) -> {
- throw new IllegalStateException("Parallel processing is not supported");
- };
- }
-}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.core.util.stream;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableListMultimap;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.function.BinaryOperator;
+import java.util.function.Function;
+import java.util.function.Supplier;
+import java.util.stream.Collector;
+
+import static java.util.Objects.requireNonNull;
+
+public final class MoreCollectors {
+
+ private static final int DEFAULT_HASHMAP_CAPACITY = 0;
+
+ private MoreCollectors() {
+ // prevents instantiation
+ }
+
+ /**
+ * A Collector into an {@link ImmutableList}.
+ */
+ public static <T> Collector<T, List<T>, List<T>> toList() {
+ return Collector.of(
+ ArrayList::new,
+ List::add,
+ (left, right) -> {
+ left.addAll(right);
+ return left;
+ },
+ ImmutableList::copyOf);
+ }
+
+ /**
+ * A Collector into an {@link ImmutableList} of the specified expected size.
+ *
+ * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
+ * processing threads will use a List with a capacity large enough for the final size.</p>
+ */
+ public static <T> Collector<T, List<T>, List<T>> toList(int expectedSize) {
+ // use ArrayList rather than ImmutableList.Builder because initial capacity of builder can not be specified
+ return Collector.of(
+ () -> new ArrayList<>(expectedSize),
+ List::add,
+ (left, right) -> {
+ left.addAll(right);
+ return left;
+ },
+ ImmutableList::copyOf);
+ }
+
+ /**
+ * A Collector into an {@link ImmutableSet}.
+ */
+ public static <T> Collector<T, Set<T>, Set<T>> toSet() {
+ return Collector.of(
+ HashSet::new,
+ Set::add,
+ (left, right) -> {
+ left.addAll(right);
+ return left;
+ },
+ ImmutableSet::copyOf);
+ }
+
+ /**
+ * A Collector into an {@link ImmutableSet} of the specified expected size.
+ *
+ * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
+ * processing threads will use a Set with a capacity large enough for the final size.</p>
+ */
+ public static <T> Collector<T, Set<T>, Set<T>> toSet(int expectedSize) {
+ // use HashSet rather than ImmutableSet.Builder because initial capacity of builder can not be specified
+ return Collector.of(
+ () -> new HashSet<>(expectedSize),
+ Set::add,
+ (left, right) -> {
+ left.addAll(right);
+ return left;
+ },
+ ImmutableSet::copyOf);
+ }
+
+ /**
+ * Delegates to {@link java.util.stream.Collectors#toCollection(Supplier)}.
+ */
+ public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
+ return java.util.stream.Collectors.toCollection(ArrayList::new);
+ }
+
+ /**
+ * Does {@code java.util.stream.MoreCollectors.toCollection(() -> new ArrayList<>(size));} which is equivalent to
+ * {@link #toArrayList()} but avoiding array copies when the size of the resulting list is already known.
+ *
+ * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
+ * processing threads will use a ArrayList with a capacity large enough for the final size.</p>
+ *
+ * @see java.util.stream.Collectors#toList()
+ * @see java.util.stream.Collectors#toCollection(Supplier)
+ */
+ public static <T> Collector<T, ?, ArrayList<T>> toArrayList(int size) {
+ return java.util.stream.Collectors.toCollection(() -> new ArrayList<>(size));
+ }
+
+ /**
+ * Delegates to {@link java.util.stream.Collectors#toCollection(Supplier)}.
+ */
+ public static <T> Collector<T, ?, HashSet<T>> toHashSet() {
+ return java.util.stream.Collectors.toCollection(HashSet::new);
+ }
+
+ /**
+ * Does {@code java.util.stream.MoreCollectors.toCollection(() -> new HashSet<>(size));} which is equivalent to
+ * {@link #toHashSet()} but avoiding array copies when the size of the resulting set is already known.
+ *
+ * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
+ * processing threads will use a HashSet with a capacity large enough for the final size.</p>
+ *
+ * @see java.util.stream.Collectors#toSet()
+ * @see java.util.stream.Collectors#toCollection(Supplier)
+ */
+ public static <T> Collector<T, ?, HashSet<T>> toHashSet(int size) {
+ return java.util.stream.Collectors.toCollection(() -> new HashSet<>(size));
+ }
+
+ /**
+ * Creates an {@link ImmutableMap} from the stream where the values are the values in the stream and the keys are the
+ * result of the provided {@link Function keyFunction} applied to each value in the stream.
+ *
+ * <p>
+ * The {@link Function keyFunction} must return a unique (according to the key's type {@link Object#equals(Object)}
+ * and/or {@link Comparable#compareTo(Object)} implementations) value for each of them, otherwise a
+ * {@link IllegalArgumentException} will be thrown.
+ * </p>
+ *
+ * <p>
+ * {@link Function keyFunction} can't return {@code null}, otherwise a {@link NullPointerException} will be thrown.
+ * </p>
+ *
+ * @throws NullPointerException if {@code keyFunction} is {@code null}.
+ * @throws NullPointerException if result of {@code keyFunction} is {@code null}.
+ * @throws IllegalArgumentException if {@code keyFunction} returns the same value for multiple entries in the stream.
+ */
+ public static <K, E> Collector<E, Map<K, E>, ImmutableMap<K, E>> uniqueIndex(Function<? super E, K> keyFunction) {
+ return uniqueIndex(keyFunction, Function.<E>identity());
+ }
+
+ /**
+ * Same as {@link #uniqueIndex(Function)} but using an underlying {@link Map} initialized with a capacity for the
+ * specified expected size.
+ *
+ * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
+ * processing threads will use a Map with a capacity large enough for the final size.</p>
+ *
+ * <p>
+ * {@link Function keyFunction} can't return {@code null}, otherwise a {@link NullPointerException} will be thrown.
+ * </p>
+ *
+ * @throws NullPointerException if {@code keyFunction} is {@code null}.
+ * @throws NullPointerException if result of {@code keyFunction} is {@code null}.
+ * @throws IllegalArgumentException if {@code keyFunction} returns the same value for multiple entries in the stream.
+ * @see #uniqueIndex(Function)
+ */
+ public static <K, E> Collector<E, Map<K, E>, ImmutableMap<K, E>> uniqueIndex(Function<? super E, K> keyFunction, int expectedSize) {
+ return uniqueIndex(keyFunction, Function.<E>identity(), expectedSize);
+ }
+
+ /**
+ * Creates an {@link ImmutableMap} from the stream where the values are the result of {@link Function valueFunction}
+ * applied to the values in the stream and the keys are the result of the provided {@link Function keyFunction}
+ * applied to each value in the stream.
+ *
+ * <p>
+ * The {@link Function keyFunction} must return a unique (according to the key's type {@link Object#equals(Object)}
+ * and/or {@link Comparable#compareTo(Object)} implementations) value for each of them, otherwise a
+ * {@link IllegalArgumentException} will be thrown.
+ * </p>
+ *
+ * <p>
+ * Neither {@link Function keyFunction} nor {@link Function valueFunction} can return {@code null}, otherwise a
+ * {@link NullPointerException} will be thrown.
+ * </p>
+ *
+ * @throws NullPointerException if {@code keyFunction} or {@code valueFunction} is {@code null}.
+ * @throws NullPointerException if result of {@code keyFunction} or {@code valueFunction} is {@code null}.
+ * @throws IllegalArgumentException if {@code keyFunction} returns the same value for multiple entries in the stream.
+ */
+ public static <K, E, V> Collector<E, Map<K, V>, ImmutableMap<K, V>> uniqueIndex(Function<? super E, K> keyFunction,
+ Function<? super E, V> valueFunction) {
+ return uniqueIndex(keyFunction, valueFunction, DEFAULT_HASHMAP_CAPACITY);
+ }
+
+ /**
+ * Same as {@link #uniqueIndex(Function, Function)} but using an underlying {@link Map} initialized with a capacity
+ * for the specified expected size.
+ *
+ * <p>Note: using this method with a parallel stream will likely not have the expected memory usage benefit as all
+ * processing threads will use a Map with a capacity large enough for the final size.</p>
+ *
+ * <p>
+ * Neither {@link Function keyFunction} nor {@link Function valueFunction} can return {@code null}, otherwise a
+ * {@link NullPointerException} will be thrown.
+ * </p>
+ *
+ * @throws NullPointerException if {@code keyFunction} or {@code valueFunction} is {@code null}.
+ * @throws NullPointerException if result of {@code keyFunction} or {@code valueFunction} is {@code null}.
+ * @throws IllegalArgumentException if {@code keyFunction} returns the same value for multiple entries in the stream.
+ * @see #uniqueIndex(Function, Function)
+ */
+ public static <K, E, V> Collector<E, Map<K, V>, ImmutableMap<K, V>> uniqueIndex(Function<? super E, K> keyFunction,
+ Function<? super E, V> valueFunction, int expectedSize) {
+ requireNonNull(keyFunction, "Key function can't be null");
+ requireNonNull(valueFunction, "Value function can't be null");
+ BiConsumer<Map<K, V>, E> accumulator = (map, element) -> {
+ K key = requireNonNull(keyFunction.apply(element), "Key function can't return null");
+ V value = requireNonNull(valueFunction.apply(element), "Value function can't return null");
+
+ putAndFailOnDuplicateKey(map, key, value);
+ };
+ BinaryOperator<Map<K, V>> merger = (m1, m2) -> {
+ for (Map.Entry<K, V> entry : m2.entrySet()) {
+ putAndFailOnDuplicateKey(m1, entry.getKey(), entry.getValue());
+ }
+ return m1;
+ };
+ return Collector.of(
+ newHashMapSupplier(expectedSize),
+ accumulator,
+ merger,
+ ImmutableMap::copyOf,
+ Collector.Characteristics.UNORDERED);
+ }
+
+ /**
+ * For stream of one expected element, return the element
+ *
+ * @throws IllegalArgumentException if stream has no element or more than 1 element
+ */
+ public static <T> Collector<T, ?, T> toOneElement() {
+ return java.util.stream.Collectors.collectingAndThen(
+ java.util.stream.Collectors.toList(),
+ list -> {
+ if (list.size() != 1) {
+ throw new IllegalStateException("Stream should have only one element");
+ }
+ return list.get(0);
+ });
+ }
+
+ private static <K, V> Supplier<Map<K, V>> newHashMapSupplier(int expectedSize) {
+ return () -> expectedSize == DEFAULT_HASHMAP_CAPACITY ? new HashMap<>() : new HashMap<>(expectedSize);
+ }
+
+ private static <K, V> void putAndFailOnDuplicateKey(Map<K, V> map, K key, V value) {
+ V existingValue = map.put(key, value);
+ if (existingValue != null) {
+ throw new IllegalArgumentException(String.format("Duplicate key %s", key));
+ }
+ }
+
+ /**
+ * Creates an {@link com.google.common.collect.ImmutableListMultimap} from the stream where the values are the values
+ * in the stream and the keys are the result of the provided {@link Function keyFunction} applied to each value in the
+ * stream.
+ *
+ * <p>
+ * Neither {@link Function keyFunction} nor {@link Function valueFunction} can return {@code null}, otherwise a
+ * {@link NullPointerException} will be thrown.
+ * </p>
+ *
+ * @throws NullPointerException if {@code keyFunction} or {@code valueFunction} is {@code null}.
+ * @throws NullPointerException if result of {@code keyFunction} or {@code valueFunction} is {@code null}.
+ */
+ public static <K, E> Collector<E, ImmutableListMultimap.Builder<K, E>, ImmutableListMultimap<K, E>> index(Function<? super E, K> keyFunction) {
+ return index(keyFunction, Function.<E>identity());
+ }
+
+ /**
+ * Creates an {@link com.google.common.collect.ImmutableListMultimap} from the stream where the values are the result
+ * of {@link Function valueFunction} applied to the values in the stream and the keys are the result of the provided
+ * {@link Function keyFunction} applied to each value in the stream.
+ *
+ * <p>
+ * Neither {@link Function keyFunction} nor {@link Function valueFunction} can return {@code null}, otherwise a
+ * {@link NullPointerException} will be thrown.
+ * </p>
+ *
+ * @throws NullPointerException if {@code keyFunction} or {@code valueFunction} is {@code null}.
+ * @throws NullPointerException if result of {@code keyFunction} or {@code valueFunction} is {@code null}.
+ */
+ public static <K, E, V> Collector<E, ImmutableListMultimap.Builder<K, V>, ImmutableListMultimap<K, V>> index(Function<? super E, K> keyFunction,
+ Function<? super E, V> valueFunction) {
+ requireNonNull(keyFunction, "Key function can't be null");
+ requireNonNull(valueFunction, "Value function can't be null");
+ BiConsumer<ImmutableListMultimap.Builder<K, V>, E> accumulator = (map, element) -> {
+ K key = requireNonNull(keyFunction.apply(element), "Key function can't return null");
+ V value = requireNonNull(valueFunction.apply(element), "Value function can't return null");
+
+ map.put(key, value);
+ };
+ BinaryOperator<ImmutableListMultimap.Builder<K, V>> merger = (m1, m2) -> {
+ for (Map.Entry<K, V> entry : m2.build().entries()) {
+ m1.put(entry.getKey(), entry.getValue());
+ }
+ return m1;
+ };
+ return Collector.of(
+ ImmutableListMultimap::builder,
+ accumulator,
+ merger,
+ ImmutableListMultimap.Builder::build);
+ }
+
+ /**
+ * Applies the specified {@link Joiner} to the current stream.
+ *
+ * @throws NullPointerException of {@code joiner} is {@code null}
+ * @throws IllegalStateException if a merge operation happens because parallel processing has been enabled on the current stream
+ */
+ public static <E> Collector<E, List<E>, String> join(Joiner joiner) {
+ requireNonNull(joiner, "Joiner can't be null");
+
+ return Collector.of(
+ ArrayList::new,
+ List::add,
+ mergeNotSupportedMerger(),
+ joiner::join);
+ }
+
+ private static <R> BinaryOperator<R> mergeNotSupportedMerger() {
+ return (m1, m2) -> {
+ throw new IllegalStateException("Parallel processing is not supported");
+ };
+ }
+}
+++ /dev/null
-/*
- * SonarQube
- * Copyright (C) 2009-2017 SonarSource SA
- * mailto:info AT sonarsource DOT com
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.util.stream;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Multimap;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.IntStream;
-import java.util.stream.Stream;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-
-import static java.util.function.Function.identity;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.entry;
-import static org.sonar.core.util.stream.Collectors.index;
-import static org.sonar.core.util.stream.Collectors.join;
-import static org.sonar.core.util.stream.Collectors.toArrayList;
-import static org.sonar.core.util.stream.Collectors.toHashSet;
-import static org.sonar.core.util.stream.Collectors.toList;
-import static org.sonar.core.util.stream.Collectors.toSet;
-import static org.sonar.core.util.stream.Collectors.uniqueIndex;
-
-public class CollectorsTest {
-
- private static final List<String> HUGE_LIST = IntStream.range(0, 2_000).mapToObj(String::valueOf).collect(java.util.stream.Collectors.toList());
- private static final Set<String> HUGE_SET = new HashSet<>(HUGE_LIST);
- private static final MyObj MY_OBJ_1_A = new MyObj(1, "A");
- private static final MyObj MY_OBJ_1_C = new MyObj(1, "C");
- private static final MyObj MY_OBJ_2_B = new MyObj(2, "B");
- private static final MyObj MY_OBJ_3_C = new MyObj(3, "C");
- private static final List<MyObj> SINGLE_ELEMENT_LIST = Arrays.asList(MY_OBJ_1_A);
- private static final List<MyObj> LIST_WITH_DUPLICATE_ID = Arrays.asList(MY_OBJ_1_A, MY_OBJ_2_B, MY_OBJ_1_C);
- private static final List<MyObj> LIST = Arrays.asList(MY_OBJ_1_A, MY_OBJ_2_B, MY_OBJ_3_C);
-
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
- @Test
- public void toList_builds_an_ImmutableList() {
- List<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toList());
- assertThat(res).isInstanceOf(ImmutableList.class)
- .containsExactly(1, 2, 3, 4, 5);
- }
-
- @Test
- public void toList_parallel_stream() {
- assertThat(HUGE_LIST.parallelStream().collect(toList())).isEqualTo(HUGE_LIST);
- }
-
- @Test
- public void toList_with_size_builds_an_ImmutableList() {
- List<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toList(30));
- assertThat(res).isInstanceOf(ImmutableList.class)
- .containsExactly(1, 2, 3, 4, 5);
- }
-
- @Test
- public void toList_with_size_parallel_stream() {
- assertThat(HUGE_LIST.parallelStream().collect(toList(HUGE_LIST.size()))).isEqualTo(HUGE_LIST);
- }
-
- @Test
- public void toSet_builds_an_ImmutableSet() {
- Set<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toSet());
- assertThat(res).isInstanceOf(ImmutableSet.class)
- .containsExactly(1, 2, 3, 4, 5);
- }
-
- @Test
- public void toSet_parallel_stream() {
- assertThat(HUGE_SET.parallelStream().collect(toSet())).isEqualTo(HUGE_SET);
- }
-
- @Test
- public void toSet_with_size_builds_an_ImmutableSet() {
- Set<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toSet(30));
- assertThat(res).isInstanceOf(ImmutableSet.class)
- .containsExactly(1, 2, 3, 4, 5);
- }
-
- @Test
- public void toSet_with_size_parallel_stream() {
- assertThat(HUGE_SET.parallelStream().collect(toSet(HUGE_SET.size()))).isEqualTo(HUGE_SET);
- }
-
- @Test
- public void toArrayList_builds_an_ArrayList() {
- List<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toArrayList());
- assertThat(res).isInstanceOf(ArrayList.class)
- .containsExactly(1, 2, 3, 4, 5);
- }
-
- @Test
- public void toArrayList_parallel_stream() {
- assertThat(HUGE_LIST.parallelStream().collect(toArrayList())).isEqualTo(HUGE_LIST);
- }
-
- @Test
- public void toArrayList_with_size_builds_an_ArrayList() {
- List<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toArrayList(30));
- assertThat(res).isInstanceOf(ArrayList.class)
- .containsExactly(1, 2, 3, 4, 5);
- }
-
- @Test
- public void toArrayList_with_size_parallel_stream() {
- assertThat(HUGE_LIST.parallelStream().collect(toArrayList(HUGE_LIST.size()))).isEqualTo(HUGE_LIST);
- }
-
- @Test
- public void toHashSet_builds_an_HashSet() {
- Set<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toHashSet());
- assertThat(res).isInstanceOf(HashSet.class)
- .containsExactly(1, 2, 3, 4, 5);
- }
-
- @Test
- public void toHashSet_parallel_stream() {
- assertThat(HUGE_SET.parallelStream().collect(toHashSet())).isEqualTo(HUGE_SET);
- }
-
- @Test
- public void toHashSet_with_size_builds_an_ArrayList() {
- Set<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toHashSet(30));
- assertThat(res).isInstanceOf(HashSet.class)
- .containsExactly(1, 2, 3, 4, 5);
- }
-
- @Test
- public void toHashSet_with_size_parallel_stream() {
- assertThat(HUGE_SET.parallelStream().collect(toHashSet(HUGE_SET.size()))).isEqualTo(HUGE_SET);
- }
-
- @Test
- public void uniqueIndex_empty_stream_returns_empty_map() {
- assertThat(Collections.<MyObj>emptyList().stream().collect(uniqueIndex(MyObj::getId))).isEmpty();
- assertThat(Collections.<MyObj>emptyList().stream().collect(uniqueIndex(MyObj::getId, 6))).isEmpty();
- assertThat(Collections.<MyObj>emptyList().stream().collect(uniqueIndex(MyObj::getId, MyObj::getText))).isEmpty();
- assertThat(Collections.<MyObj>emptyList().stream().collect(uniqueIndex(MyObj::getId, MyObj::getText, 10))).isEmpty();
- }
-
- @Test
- public void uniqueIndex_fails_when_there_is_duplicate_keys() {
- Stream<MyObj> stream = LIST_WITH_DUPLICATE_ID.stream();
-
- expectedDuplicateKey1IAE();
-
- stream.collect(uniqueIndex(MyObj::getId));
- }
-
- @Test
- public void uniqueIndex_with_expected_size_fails_when_there_is_duplicate_keys() {
- Stream<MyObj> stream = LIST_WITH_DUPLICATE_ID.stream();
-
- expectedDuplicateKey1IAE();
-
- stream.collect(uniqueIndex(MyObj::getId, 1));
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_fails_when_there_is_duplicate_keys() {
- Stream<MyObj> stream = LIST_WITH_DUPLICATE_ID.stream();
-
- expectedDuplicateKey1IAE();
-
- stream.collect(uniqueIndex(MyObj::getId, MyObj::getText));
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_and_expected_size_fails_when_there_is_duplicate_keys() {
- Stream<MyObj> stream = LIST_WITH_DUPLICATE_ID.stream();
-
- expectedDuplicateKey1IAE();
-
- stream.collect(uniqueIndex(MyObj::getId, MyObj::getText, 10));
- }
-
- @Test
- public void uniqueIndex_fails_if_key_function_is_null() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Key function can't be null");
-
- uniqueIndex(null);
- }
-
- @Test
- public void uniqueIndex_with_expected_size_fails_if_key_function_is_null() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Key function can't be null");
-
- uniqueIndex(null, 2);
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_fails_if_key_function_is_null() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Key function can't be null");
-
- uniqueIndex(null, MyObj::getText);
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_and_expected_size_fails_if_key_function_is_null() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Key function can't be null");
-
- uniqueIndex(null, MyObj::getText, 9);
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_fails_if_value_function_is_null() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Value function can't be null");
-
- uniqueIndex(MyObj::getId, null);
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_and_expected_size_fails_if_value_function_is_null() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Value function can't be null");
-
- uniqueIndex(MyObj::getId, null, 9);
- }
-
- @Test
- public void uniqueIndex_fails_if_key_function_returns_null() {
- expectKeyFunctionCantReturnNullNPE();
-
- SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(s -> null));
- }
-
- @Test
- public void uniqueIndex_with_expected_size_fails_if_key_function_returns_null() {
- expectKeyFunctionCantReturnNullNPE();
-
- SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(s -> null, 90));
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_fails_if_key_function_returns_null() {
- expectKeyFunctionCantReturnNullNPE();
-
- SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(s -> null, MyObj::getText));
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_and_expected_size_fails_if_key_function_returns_null() {
- expectKeyFunctionCantReturnNullNPE();
-
- SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(s -> null, MyObj::getText, 9));
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_fails_if_value_function_returns_null() {
- expectValueFunctionCantReturnNullNPE();
-
- SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(MyObj::getId, s -> null));
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_and_expected_size_fails_if_value_function_returns_null() {
- expectValueFunctionCantReturnNullNPE();
-
- SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(MyObj::getId, s -> null, 9));
- }
-
- @Test
- public void uniqueIndex_returns_map() {
- assertThat(LIST.stream().collect(uniqueIndex(MyObj::getId))).containsOnly(entry(1, MY_OBJ_1_A), entry(2, MY_OBJ_2_B), entry(3, MY_OBJ_3_C));
- }
-
- @Test
- public void uniqueIndex_with_expected_size_returns_map() {
- assertThat(LIST.stream().collect(uniqueIndex(MyObj::getId, 3))).containsOnly(entry(1, MY_OBJ_1_A), entry(2, MY_OBJ_2_B), entry(3, MY_OBJ_3_C));
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_returns_map() {
- assertThat(LIST.stream().collect(uniqueIndex(MyObj::getId, MyObj::getText))).containsOnly(entry(1, "A"), entry(2, "B"), entry(3, "C"));
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_and_expected_size_returns_map() {
- assertThat(LIST.stream().collect(uniqueIndex(MyObj::getId, MyObj::getText, 9))).containsOnly(entry(1, "A"), entry(2, "B"), entry(3, "C"));
- }
-
- @Test
- public void uniqueIndex_parallel_stream() {
- Map<String, String> map = HUGE_LIST.parallelStream().collect(uniqueIndex(identity()));
- assertThat(map.keySet()).isEqualTo(HUGE_SET);
- assertThat(map.values()).containsExactlyElementsOf(HUGE_SET);
- }
-
- @Test
- public void uniqueIndex_with_expected_size_parallel_stream() {
- Map<String, String> map = HUGE_LIST.parallelStream().collect(uniqueIndex(identity(), HUGE_LIST.size()));
- assertThat(map.keySet()).isEqualTo(HUGE_SET);
- assertThat(map.values()).containsExactlyElementsOf(HUGE_SET);
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_parallel_stream() {
- Map<String, String> map = HUGE_LIST.parallelStream().collect(uniqueIndex(identity(), identity()));
- assertThat(map.keySet()).isEqualTo(HUGE_SET);
- assertThat(map.values()).containsExactlyElementsOf(HUGE_SET);
- }
-
- @Test
- public void uniqueIndex_with_valueFunction_and_expected_size_parallel_stream() {
- Map<String, String> map = HUGE_LIST.parallelStream().collect(uniqueIndex(identity(), identity(), HUGE_LIST.size()));
- assertThat(map.keySet()).isEqualTo(HUGE_SET);
- assertThat(map.values()).containsExactlyElementsOf(HUGE_SET);
- }
-
- @Test
- public void index_empty_stream_returns_empty_map() {
- assertThat(Collections.<MyObj>emptyList().stream().collect(index(MyObj::getId)).size()).isEqualTo(0);
- assertThat(Collections.<MyObj>emptyList().stream().collect(index(MyObj::getId, MyObj::getText)).size()).isEqualTo(0);
- }
-
- @Test
- public void index_fails_if_key_function_is_null() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Key function can't be null");
-
- index(null);
- }
-
- @Test
- public void index_with_valueFunction_fails_if_key_function_is_null() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Key function can't be null");
-
- index(null, MyObj::getText);
- }
-
- @Test
- public void index_with_valueFunction_fails_if_value_function_is_null() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Value function can't be null");
-
- index(MyObj::getId, null);
- }
-
- @Test
- public void index_fails_if_key_function_returns_null() {
- expectKeyFunctionCantReturnNullNPE();
-
- SINGLE_ELEMENT_LIST.stream().collect(index(s -> null));
- }
-
- @Test
- public void index_with_valueFunction_fails_if_key_function_returns_null() {
- expectKeyFunctionCantReturnNullNPE();
-
- SINGLE_ELEMENT_LIST.stream().collect(index(s -> null, MyObj::getText));
- }
-
- @Test
- public void index_with_valueFunction_fails_if_value_function_returns_null() {
- expectValueFunctionCantReturnNullNPE();
-
- SINGLE_ELEMENT_LIST.stream().collect(index(MyObj::getId, s -> null));
- }
-
- @Test
- public void index_supports_duplicate_keys() {
- Multimap<Integer, MyObj> multimap = LIST_WITH_DUPLICATE_ID.stream().collect(index(MyObj::getId));
-
- assertThat(multimap.keySet()).containsOnly(1, 2);
- assertThat(multimap.get(1)).containsOnly(MY_OBJ_1_A, MY_OBJ_1_C);
- assertThat(multimap.get(2)).containsOnly(MY_OBJ_2_B);
- }
-
- @Test
- public void uniqueIndex_supports_duplicate_keys() {
- Multimap<Integer, String> multimap = LIST_WITH_DUPLICATE_ID.stream().collect(index(MyObj::getId, MyObj::getText));
-
- assertThat(multimap.keySet()).containsOnly(1, 2);
- assertThat(multimap.get(1)).containsOnly("A", "C");
- assertThat(multimap.get(2)).containsOnly("B");
- }
-
- @Test
- public void index_returns_multimap() {
- Multimap<Integer, MyObj> multimap = LIST.stream().collect(index(MyObj::getId));
-
- assertThat(multimap.size()).isEqualTo(3);
- Map<Integer, Collection<MyObj>> map = multimap.asMap();
- assertThat(map.get(1)).containsOnly(MY_OBJ_1_A);
- assertThat(map.get(2)).containsOnly(MY_OBJ_2_B);
- assertThat(map.get(3)).containsOnly(MY_OBJ_3_C);
- }
-
- @Test
- public void index_with_valueFunction_returns_multimap() {
- Multimap<Integer, String> multimap = LIST.stream().collect(index(MyObj::getId, MyObj::getText));
-
- assertThat(multimap.size()).isEqualTo(3);
- Map<Integer, Collection<String>> map = multimap.asMap();
- assertThat(map.get(1)).containsOnly("A");
- assertThat(map.get(2)).containsOnly("B");
- assertThat(map.get(3)).containsOnly("C");
- }
-
- @Test
- public void index_parallel_stream() {
- Multimap<String, String> multimap = HUGE_LIST.parallelStream().collect(index(identity()));
-
- assertThat(multimap.keySet()).isEqualTo(HUGE_SET);
- }
-
- @Test
- public void index_with_valueFunction_parallel_stream() {
- Multimap<String, String> multimap = HUGE_LIST.parallelStream().collect(index(identity(), identity()));
-
- assertThat(multimap.keySet()).isEqualTo(HUGE_SET);
- }
-
- @Test
- public void join_on_empty_stream_returns_empty_string() {
- assertThat(Collections.emptyList().stream().collect(join(Joiner.on(",")))).isEmpty();
- }
-
- @Test
- public void join_fails_with_NPE_if_joiner_is_null() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Joiner can't be null");
-
- join(null);
- }
-
- @Test
- public void join_applies_joiner_to_stream() {
- assertThat(Arrays.asList("1", "2", "3", "4").stream().collect(join(Joiner.on(","))))
- .isEqualTo("1,2,3,4");
- }
-
- @Test
- public void join_does_not_support_parallel_stream_and_fails_with_ISE() {
- Stream<String> hugeStream = HUGE_LIST.parallelStream();
-
- expectedException.expect(IllegalStateException.class);
- expectedException.expectMessage("Parallel processing is not supported");
-
- hugeStream.collect(join(Joiner.on(" ")));
- }
-
- @Test
- public void join_supports_null_if_joiner_does() {
- Stream<String> stream = Arrays.asList("1", null).stream();
-
- expectedException.expect(NullPointerException.class);
-
- stream.collect(join(Joiner.on(",")));
- }
-
- private void expectedDuplicateKey1IAE() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("Duplicate key 1");
- }
-
- private void expectKeyFunctionCantReturnNullNPE() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Key function can't return null");
- }
-
- private void expectValueFunctionCantReturnNullNPE() {
- expectedException.expect(NullPointerException.class);
- expectedException.expectMessage("Value function can't return null");
- }
-
- private static final class MyObj {
- private final int id;
- private final String text;
-
- public MyObj(int id, String text) {
- this.id = id;
- this.text = text;
- }
-
- public int getId() {
- return id;
- }
-
- public String getText() {
- return text;
- }
- }
-}
--- /dev/null
+/*
+ * SonarQube
+ * Copyright (C) 2009-2017 SonarSource SA
+ * mailto:info AT sonarsource DOT com
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this program; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+ */
+package org.sonar.core.util.stream;
+
+import com.google.common.base.Joiner;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Multimap;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.IntStream;
+import java.util.stream.Stream;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+
+import static java.util.function.Function.identity;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.entry;
+import static org.sonar.core.util.stream.MoreCollectors.index;
+import static org.sonar.core.util.stream.MoreCollectors.join;
+import static org.sonar.core.util.stream.MoreCollectors.toArrayList;
+import static org.sonar.core.util.stream.MoreCollectors.toHashSet;
+import static org.sonar.core.util.stream.MoreCollectors.toList;
+import static org.sonar.core.util.stream.MoreCollectors.toSet;
+import static org.sonar.core.util.stream.MoreCollectors.uniqueIndex;
+
+public class MoreCollectorsTest {
+
+ private static final List<String> HUGE_LIST = IntStream.range(0, 2_000).mapToObj(String::valueOf).collect(java.util.stream.Collectors.toList());
+ private static final Set<String> HUGE_SET = new HashSet<>(HUGE_LIST);
+ private static final MyObj MY_OBJ_1_A = new MyObj(1, "A");
+ private static final MyObj MY_OBJ_1_C = new MyObj(1, "C");
+ private static final MyObj MY_OBJ_2_B = new MyObj(2, "B");
+ private static final MyObj MY_OBJ_3_C = new MyObj(3, "C");
+ private static final List<MyObj> SINGLE_ELEMENT_LIST = Arrays.asList(MY_OBJ_1_A);
+ private static final List<MyObj> LIST_WITH_DUPLICATE_ID = Arrays.asList(MY_OBJ_1_A, MY_OBJ_2_B, MY_OBJ_1_C);
+ private static final List<MyObj> LIST = Arrays.asList(MY_OBJ_1_A, MY_OBJ_2_B, MY_OBJ_3_C);
+
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Test
+ public void toList_builds_an_ImmutableList() {
+ List<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toList());
+ assertThat(res).isInstanceOf(ImmutableList.class)
+ .containsExactly(1, 2, 3, 4, 5);
+ }
+
+ @Test
+ public void toList_parallel_stream() {
+ assertThat(HUGE_LIST.parallelStream().collect(toList())).isEqualTo(HUGE_LIST);
+ }
+
+ @Test
+ public void toList_with_size_builds_an_ImmutableList() {
+ List<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toList(30));
+ assertThat(res).isInstanceOf(ImmutableList.class)
+ .containsExactly(1, 2, 3, 4, 5);
+ }
+
+ @Test
+ public void toList_with_size_parallel_stream() {
+ assertThat(HUGE_LIST.parallelStream().collect(toList(HUGE_LIST.size()))).isEqualTo(HUGE_LIST);
+ }
+
+ @Test
+ public void toSet_builds_an_ImmutableSet() {
+ Set<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toSet());
+ assertThat(res).isInstanceOf(ImmutableSet.class)
+ .containsExactly(1, 2, 3, 4, 5);
+ }
+
+ @Test
+ public void toSet_parallel_stream() {
+ assertThat(HUGE_SET.parallelStream().collect(toSet())).isEqualTo(HUGE_SET);
+ }
+
+ @Test
+ public void toSet_with_size_builds_an_ImmutableSet() {
+ Set<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toSet(30));
+ assertThat(res).isInstanceOf(ImmutableSet.class)
+ .containsExactly(1, 2, 3, 4, 5);
+ }
+
+ @Test
+ public void toSet_with_size_parallel_stream() {
+ assertThat(HUGE_SET.parallelStream().collect(toSet(HUGE_SET.size()))).isEqualTo(HUGE_SET);
+ }
+
+ @Test
+ public void toArrayList_builds_an_ArrayList() {
+ List<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toArrayList());
+ assertThat(res).isInstanceOf(ArrayList.class)
+ .containsExactly(1, 2, 3, 4, 5);
+ }
+
+ @Test
+ public void toArrayList_parallel_stream() {
+ assertThat(HUGE_LIST.parallelStream().collect(toArrayList())).isEqualTo(HUGE_LIST);
+ }
+
+ @Test
+ public void toArrayList_with_size_builds_an_ArrayList() {
+ List<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toArrayList(30));
+ assertThat(res).isInstanceOf(ArrayList.class)
+ .containsExactly(1, 2, 3, 4, 5);
+ }
+
+ @Test
+ public void toArrayList_with_size_parallel_stream() {
+ assertThat(HUGE_LIST.parallelStream().collect(toArrayList(HUGE_LIST.size()))).isEqualTo(HUGE_LIST);
+ }
+
+ @Test
+ public void toHashSet_builds_an_HashSet() {
+ Set<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toHashSet());
+ assertThat(res).isInstanceOf(HashSet.class)
+ .containsExactly(1, 2, 3, 4, 5);
+ }
+
+ @Test
+ public void toHashSet_parallel_stream() {
+ assertThat(HUGE_SET.parallelStream().collect(toHashSet())).isEqualTo(HUGE_SET);
+ }
+
+ @Test
+ public void toHashSet_with_size_builds_an_ArrayList() {
+ Set<Integer> res = Arrays.asList(1, 2, 3, 4, 5).stream().collect(toHashSet(30));
+ assertThat(res).isInstanceOf(HashSet.class)
+ .containsExactly(1, 2, 3, 4, 5);
+ }
+
+ @Test
+ public void toHashSet_with_size_parallel_stream() {
+ assertThat(HUGE_SET.parallelStream().collect(toHashSet(HUGE_SET.size()))).isEqualTo(HUGE_SET);
+ }
+
+ @Test
+ public void uniqueIndex_empty_stream_returns_empty_map() {
+ assertThat(Collections.<MyObj>emptyList().stream().collect(uniqueIndex(MyObj::getId))).isEmpty();
+ assertThat(Collections.<MyObj>emptyList().stream().collect(uniqueIndex(MyObj::getId, 6))).isEmpty();
+ assertThat(Collections.<MyObj>emptyList().stream().collect(uniqueIndex(MyObj::getId, MyObj::getText))).isEmpty();
+ assertThat(Collections.<MyObj>emptyList().stream().collect(uniqueIndex(MyObj::getId, MyObj::getText, 10))).isEmpty();
+ }
+
+ @Test
+ public void uniqueIndex_fails_when_there_is_duplicate_keys() {
+ Stream<MyObj> stream = LIST_WITH_DUPLICATE_ID.stream();
+
+ expectedDuplicateKey1IAE();
+
+ stream.collect(uniqueIndex(MyObj::getId));
+ }
+
+ @Test
+ public void uniqueIndex_with_expected_size_fails_when_there_is_duplicate_keys() {
+ Stream<MyObj> stream = LIST_WITH_DUPLICATE_ID.stream();
+
+ expectedDuplicateKey1IAE();
+
+ stream.collect(uniqueIndex(MyObj::getId, 1));
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_fails_when_there_is_duplicate_keys() {
+ Stream<MyObj> stream = LIST_WITH_DUPLICATE_ID.stream();
+
+ expectedDuplicateKey1IAE();
+
+ stream.collect(uniqueIndex(MyObj::getId, MyObj::getText));
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_and_expected_size_fails_when_there_is_duplicate_keys() {
+ Stream<MyObj> stream = LIST_WITH_DUPLICATE_ID.stream();
+
+ expectedDuplicateKey1IAE();
+
+ stream.collect(uniqueIndex(MyObj::getId, MyObj::getText, 10));
+ }
+
+ @Test
+ public void uniqueIndex_fails_if_key_function_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Key function can't be null");
+
+ uniqueIndex(null);
+ }
+
+ @Test
+ public void uniqueIndex_with_expected_size_fails_if_key_function_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Key function can't be null");
+
+ uniqueIndex(null, 2);
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_fails_if_key_function_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Key function can't be null");
+
+ uniqueIndex(null, MyObj::getText);
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_and_expected_size_fails_if_key_function_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Key function can't be null");
+
+ uniqueIndex(null, MyObj::getText, 9);
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_fails_if_value_function_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Value function can't be null");
+
+ uniqueIndex(MyObj::getId, null);
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_and_expected_size_fails_if_value_function_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Value function can't be null");
+
+ uniqueIndex(MyObj::getId, null, 9);
+ }
+
+ @Test
+ public void uniqueIndex_fails_if_key_function_returns_null() {
+ expectKeyFunctionCantReturnNullNPE();
+
+ SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(s -> null));
+ }
+
+ @Test
+ public void uniqueIndex_with_expected_size_fails_if_key_function_returns_null() {
+ expectKeyFunctionCantReturnNullNPE();
+
+ SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(s -> null, 90));
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_fails_if_key_function_returns_null() {
+ expectKeyFunctionCantReturnNullNPE();
+
+ SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(s -> null, MyObj::getText));
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_and_expected_size_fails_if_key_function_returns_null() {
+ expectKeyFunctionCantReturnNullNPE();
+
+ SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(s -> null, MyObj::getText, 9));
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_fails_if_value_function_returns_null() {
+ expectValueFunctionCantReturnNullNPE();
+
+ SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(MyObj::getId, s -> null));
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_and_expected_size_fails_if_value_function_returns_null() {
+ expectValueFunctionCantReturnNullNPE();
+
+ SINGLE_ELEMENT_LIST.stream().collect(uniqueIndex(MyObj::getId, s -> null, 9));
+ }
+
+ @Test
+ public void uniqueIndex_returns_map() {
+ assertThat(LIST.stream().collect(uniqueIndex(MyObj::getId))).containsOnly(entry(1, MY_OBJ_1_A), entry(2, MY_OBJ_2_B), entry(3, MY_OBJ_3_C));
+ }
+
+ @Test
+ public void uniqueIndex_with_expected_size_returns_map() {
+ assertThat(LIST.stream().collect(uniqueIndex(MyObj::getId, 3))).containsOnly(entry(1, MY_OBJ_1_A), entry(2, MY_OBJ_2_B), entry(3, MY_OBJ_3_C));
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_returns_map() {
+ assertThat(LIST.stream().collect(uniqueIndex(MyObj::getId, MyObj::getText))).containsOnly(entry(1, "A"), entry(2, "B"), entry(3, "C"));
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_and_expected_size_returns_map() {
+ assertThat(LIST.stream().collect(uniqueIndex(MyObj::getId, MyObj::getText, 9))).containsOnly(entry(1, "A"), entry(2, "B"), entry(3, "C"));
+ }
+
+ @Test
+ public void uniqueIndex_parallel_stream() {
+ Map<String, String> map = HUGE_LIST.parallelStream().collect(uniqueIndex(identity()));
+ assertThat(map.keySet()).isEqualTo(HUGE_SET);
+ assertThat(map.values()).containsExactlyElementsOf(HUGE_SET);
+ }
+
+ @Test
+ public void uniqueIndex_with_expected_size_parallel_stream() {
+ Map<String, String> map = HUGE_LIST.parallelStream().collect(uniqueIndex(identity(), HUGE_LIST.size()));
+ assertThat(map.keySet()).isEqualTo(HUGE_SET);
+ assertThat(map.values()).containsExactlyElementsOf(HUGE_SET);
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_parallel_stream() {
+ Map<String, String> map = HUGE_LIST.parallelStream().collect(uniqueIndex(identity(), identity()));
+ assertThat(map.keySet()).isEqualTo(HUGE_SET);
+ assertThat(map.values()).containsExactlyElementsOf(HUGE_SET);
+ }
+
+ @Test
+ public void uniqueIndex_with_valueFunction_and_expected_size_parallel_stream() {
+ Map<String, String> map = HUGE_LIST.parallelStream().collect(uniqueIndex(identity(), identity(), HUGE_LIST.size()));
+ assertThat(map.keySet()).isEqualTo(HUGE_SET);
+ assertThat(map.values()).containsExactlyElementsOf(HUGE_SET);
+ }
+
+ @Test
+ public void index_empty_stream_returns_empty_map() {
+ assertThat(Collections.<MyObj>emptyList().stream().collect(index(MyObj::getId)).size()).isEqualTo(0);
+ assertThat(Collections.<MyObj>emptyList().stream().collect(index(MyObj::getId, MyObj::getText)).size()).isEqualTo(0);
+ }
+
+ @Test
+ public void index_fails_if_key_function_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Key function can't be null");
+
+ index(null);
+ }
+
+ @Test
+ public void index_with_valueFunction_fails_if_key_function_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Key function can't be null");
+
+ index(null, MyObj::getText);
+ }
+
+ @Test
+ public void index_with_valueFunction_fails_if_value_function_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Value function can't be null");
+
+ index(MyObj::getId, null);
+ }
+
+ @Test
+ public void index_fails_if_key_function_returns_null() {
+ expectKeyFunctionCantReturnNullNPE();
+
+ SINGLE_ELEMENT_LIST.stream().collect(index(s -> null));
+ }
+
+ @Test
+ public void index_with_valueFunction_fails_if_key_function_returns_null() {
+ expectKeyFunctionCantReturnNullNPE();
+
+ SINGLE_ELEMENT_LIST.stream().collect(index(s -> null, MyObj::getText));
+ }
+
+ @Test
+ public void index_with_valueFunction_fails_if_value_function_returns_null() {
+ expectValueFunctionCantReturnNullNPE();
+
+ SINGLE_ELEMENT_LIST.stream().collect(index(MyObj::getId, s -> null));
+ }
+
+ @Test
+ public void index_supports_duplicate_keys() {
+ Multimap<Integer, MyObj> multimap = LIST_WITH_DUPLICATE_ID.stream().collect(index(MyObj::getId));
+
+ assertThat(multimap.keySet()).containsOnly(1, 2);
+ assertThat(multimap.get(1)).containsOnly(MY_OBJ_1_A, MY_OBJ_1_C);
+ assertThat(multimap.get(2)).containsOnly(MY_OBJ_2_B);
+ }
+
+ @Test
+ public void uniqueIndex_supports_duplicate_keys() {
+ Multimap<Integer, String> multimap = LIST_WITH_DUPLICATE_ID.stream().collect(index(MyObj::getId, MyObj::getText));
+
+ assertThat(multimap.keySet()).containsOnly(1, 2);
+ assertThat(multimap.get(1)).containsOnly("A", "C");
+ assertThat(multimap.get(2)).containsOnly("B");
+ }
+
+ @Test
+ public void index_returns_multimap() {
+ Multimap<Integer, MyObj> multimap = LIST.stream().collect(index(MyObj::getId));
+
+ assertThat(multimap.size()).isEqualTo(3);
+ Map<Integer, Collection<MyObj>> map = multimap.asMap();
+ assertThat(map.get(1)).containsOnly(MY_OBJ_1_A);
+ assertThat(map.get(2)).containsOnly(MY_OBJ_2_B);
+ assertThat(map.get(3)).containsOnly(MY_OBJ_3_C);
+ }
+
+ @Test
+ public void index_with_valueFunction_returns_multimap() {
+ Multimap<Integer, String> multimap = LIST.stream().collect(index(MyObj::getId, MyObj::getText));
+
+ assertThat(multimap.size()).isEqualTo(3);
+ Map<Integer, Collection<String>> map = multimap.asMap();
+ assertThat(map.get(1)).containsOnly("A");
+ assertThat(map.get(2)).containsOnly("B");
+ assertThat(map.get(3)).containsOnly("C");
+ }
+
+ @Test
+ public void index_parallel_stream() {
+ Multimap<String, String> multimap = HUGE_LIST.parallelStream().collect(index(identity()));
+
+ assertThat(multimap.keySet()).isEqualTo(HUGE_SET);
+ }
+
+ @Test
+ public void index_with_valueFunction_parallel_stream() {
+ Multimap<String, String> multimap = HUGE_LIST.parallelStream().collect(index(identity(), identity()));
+
+ assertThat(multimap.keySet()).isEqualTo(HUGE_SET);
+ }
+
+ @Test
+ public void join_on_empty_stream_returns_empty_string() {
+ assertThat(Collections.emptyList().stream().collect(join(Joiner.on(",")))).isEmpty();
+ }
+
+ @Test
+ public void join_fails_with_NPE_if_joiner_is_null() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Joiner can't be null");
+
+ join(null);
+ }
+
+ @Test
+ public void join_applies_joiner_to_stream() {
+ assertThat(Arrays.asList("1", "2", "3", "4").stream().collect(join(Joiner.on(","))))
+ .isEqualTo("1,2,3,4");
+ }
+
+ @Test
+ public void join_does_not_support_parallel_stream_and_fails_with_ISE() {
+ Stream<String> hugeStream = HUGE_LIST.parallelStream();
+
+ expectedException.expect(IllegalStateException.class);
+ expectedException.expectMessage("Parallel processing is not supported");
+
+ hugeStream.collect(join(Joiner.on(" ")));
+ }
+
+ @Test
+ public void join_supports_null_if_joiner_does() {
+ Stream<String> stream = Arrays.asList("1", null).stream();
+
+ expectedException.expect(NullPointerException.class);
+
+ stream.collect(join(Joiner.on(",")));
+ }
+
+ private void expectedDuplicateKey1IAE() {
+ expectedException.expect(IllegalArgumentException.class);
+ expectedException.expectMessage("Duplicate key 1");
+ }
+
+ private void expectKeyFunctionCantReturnNullNPE() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Key function can't return null");
+ }
+
+ private void expectValueFunctionCantReturnNullNPE() {
+ expectedException.expect(NullPointerException.class);
+ expectedException.expectMessage("Value function can't return null");
+ }
+
+ private static final class MyObj {
+ private final int id;
+ private final String text;
+
+ public MyObj(int id, String text) {
+ this.id = id;
+ this.text = text;
+ }
+
+ public int getId() {
+ return id;
+ }
+
+ public String getText() {
+ return text;
+ }
+ }
+}
import org.sonar.api.batch.sensor.measure.internal.DefaultMeasure;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.utils.KeyValueFormat;
-import org.sonar.core.util.stream.Collectors;
+import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.scanner.scan.measure.MeasureCache;
import org.sonar.scanner.sensor.coverage.CoverageExclusions;
private boolean isCoverageMeasuresAlreadyDefined(InputFile f) {
Set<String> metricKeys = StreamSupport.stream(measureCache.byComponentKey(f.key()).spliterator(), false)
- .map(new MeasureToMetricKey()).collect(Collectors.toSet());
+ .map(new MeasureToMetricKey()).collect(MoreCollectors.toSet());
Function<Metric, String> metricToKey = new MetricToKey();
- Set<String> allCoverageMetricKeys = CoverageType.UNIT.allMetrics().stream().map(metricToKey).collect(Collectors.toSet());
+ Set<String> allCoverageMetricKeys = CoverageType.UNIT.allMetrics().stream().map(metricToKey).collect(MoreCollectors.toSet());
return !Sets.intersection(metricKeys, allCoverageMetricKeys).isEmpty();
}