import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
-import org.sonar.api.server.ws.Request;
-import org.sonar.api.server.ws.RequestHandler;
-import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
public class BatchWs implements WebService {
.setInternal(true)
.setSince("4.4")
.setDescription("List the JAR files to be downloaded by source analyzer")
- .setHandler(new RequestHandler() {
- @Override
- public void handle(Request request, Response response) {
- try {
- response.stream().setMediaType("text/plain");
- IOUtils.write(batchIndex.getIndex(), response.stream().output());
- } catch (IOException e) {
- throw new IllegalStateException(e);
- }
+ .setHandler((request, response) -> {
+ try {
+ response.stream().setMediaType("text/plain");
+ IOUtils.write(batchIndex.getIndex(), response.stream().output());
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
}
})
.setResponseExample(getClass().getResource("batch-index-example.txt"));
.setSince("4.4")
.setDescription("Download a JAR file required by source analyzer")
.setResponseExample(getClass().getResource("batch-file-example.txt"))
- .setHandler(new RequestHandler() {
- @Override
- public void handle(Request request, Response response) {
- String filename = request.mandatoryParam("name");
- try {
- response.stream().setMediaType("application/java-archive");
- FileUtils.copyFile(batchIndex.getFile(filename), response.stream().output());
- } catch (IOException e) {
- throw new IllegalStateException(e);
- }
+ .setHandler((request, response) -> {
+ String filename = request.mandatoryParam("name");
+ try {
+ response.stream().setMediaType("application/java-archive");
+ FileUtils.copyFile(batchIndex.getFile(filename), response.stream().output());
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
}
});
action
throw new IllegalArgumentException("Cannot sort on field : " + sort);
}
- abstract static class ComponentProcessor {
- abstract Function sortFieldFunction();
+ interface ComponentProcessor {
+ Function sortFieldFunction();
- abstract Ordering sortFieldOrdering(boolean ascending);
+ Ordering sortFieldOrdering(boolean ascending);
- final List<? extends Component> sort(Collection<? extends Component> components, boolean ascending) {
+ default List<? extends Component> sort(Collection<? extends Component> components, boolean ascending) {
Ordering<Component> ordering = sortFieldOrdering(ascending).onResultOf(sortFieldFunction());
return ordering.immutableSortedCopy(components);
}
}
- abstract static class TextSort extends ComponentProcessor {
+ abstract static class TextSort implements ComponentProcessor {
@Override
- Function sortFieldFunction() {
+ public Function sortFieldFunction() {
return new Function<Component, String>() {
@Override
public String apply(Component component) {
abstract String sortField(Component component);
@Override
- Ordering sortFieldOrdering(boolean ascending) {
+ public Ordering sortFieldOrdering(boolean ascending) {
Ordering<String> ordering = Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsLast();
if (!ascending) {
ordering = ordering.reverse();
return newArrayList(Iterables.filter(allComponents, new MatchQuery(query)));
}
- abstract static class Filter {
+ interface Filter {
- abstract String field(Component component);
+ String field(Component component);
- final boolean accept(Component component, Collection<String> collections) {
+ default boolean accept(Component component, Collection<String> collections) {
if (!collections.isEmpty()) {
for (String item : collections) {
if (field(component).toLowerCase().contains(item.toLowerCase())) {
}
}
- static class NameFilter extends Filter {
+ static class NameFilter implements Filter {
@Override
- String field(Component component) {
+ public String field(Component component) {
return component.name();
}
}
- static class KeyFilter extends Filter {
+ static class KeyFilter implements Filter {
@Override
- String field(Component component) {
+ public String field(Component component) {
return component.key();
}
}
import java.util.List;
import java.util.Map;
import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.sonar.server.computation.task.step.ComputationStep;
import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.collect.FluentIterable.from;
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.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;
private final MetricRepository metricRepository;
private final MeasureRepository measureRepository;
- private final Function<PastMeasureDto, MeasureKey> pastMeasureToMeasureKey = new Function<PastMeasureDto, MeasureKey>() {
- @Nullable
- @Override
- public MeasureKey apply(@Nonnull PastMeasureDto input) {
- Metric metric = metricRepository.getById((long)input.getMetricId());
- return new MeasureKey(metric.getKey(), null);
- }
- };
-
public ComputeMeasureVariationsStep(DbClient dbClient, TreeRootHolder treeRootHolder, PeriodsHolder periodsHolder, MetricRepository metricRepository,
MeasureRepository measureRepository) {
this.dbClient = dbClient;
public void execute() {
DbSession dbSession = dbClient.openSession(false);
try {
- List<Metric> metrics = from(metricRepository.getAll()).filter(NumericMetric.INSTANCE).toList();
+ List<Metric> metrics = StreamSupport.stream(metricRepository.getAll().spliterator(), false).filter(NumericMetric.INSTANCE::apply).collect(Collectors.toList());
new DepthTraversalTypeAwareCrawler(new VariationMeasuresVisitor(dbSession, metrics))
.visit(treeRootHolder.getRoot());
} finally {
// 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 = from(metrics).transform(MetricDtoToMetricId.INSTANCE).toSet();
+ this.metricIds = metrics.stream().map(MetricDtoToMetricId.INSTANCE::apply).collect(Collectors.toSet());
this.metrics = metrics;
}
}
private void setVariationMeasures(Component component, List<PastMeasureDto> pastMeasures, int period, MeasuresWithVariationRepository measuresWithVariationRepository) {
- Map<MeasureKey, PastMeasureDto> pastMeasuresByMeasureKey = from(pastMeasures).uniqueIndex(pastMeasureToMeasureKey);
+ Map<MeasureKey, PastMeasureDto> pastMeasuresByMeasureKey = pastMeasures
+ .stream()
+ .collect(uniqueIndex(m -> new MeasureKey(metricRepository.getById((long) m.getMetricId()).getKey(), null), identity()));
for (Metric metric : metrics) {
Optional<Measure> measure = measureRepository.getRawMeasure(component, metric);
if (measure.isPresent() && !measure.get().hasVariations()) {
*/
package org.sonar.server.computation.task.projectanalysis.step;
-import com.google.common.base.Function;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.event.EventDto;
import org.sonar.server.computation.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.server.computation.task.projectanalysis.component.Component;
-import org.sonar.server.computation.task.projectanalysis.component.ComponentVisitor;
import org.sonar.server.computation.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.server.computation.task.projectanalysis.component.DepthTraversalTypeAwareCrawler;
import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolder;
import org.sonar.server.computation.task.projectanalysis.event.EventRepository;
import org.sonar.server.computation.task.step.ComputationStep;
-import static com.google.common.collect.Iterables.transform;
-
public class PersistEventsStep implements ComputationStep {
private final DbClient dbClient;
}
}
- private void processEvents(DbSession session, Component component, Long analysisDate) {
- Function<Event, EventDto> eventToEventDto = event -> newBaseEvent(component, analysisDate)
- .setName(event.getName())
- .setCategory(convertCategory(event.getCategory()))
- .setDescription(event.getDescription())
- .setData(event.getData());
- // FIXME bulk insert
- for (EventDto batchEventDto : transform(eventRepository.getEvents(component), eventToEventDto)) {
- dbClient.eventDao().insert(session, batchEventDto);
- }
- }
-
- private void saveVersionEvent(DbSession session, Component component, Long analysisDate) {
- String version = component.getReportAttributes().getVersion();
- if (version != null) {
- deletePreviousEventsHavingSameVersion(session, version, component);
- dbClient.eventDao().insert(session, newBaseEvent(component, analysisDate)
- .setName(version)
- .setCategory(EventDto.CATEGORY_VERSION));
- }
- }
-
- private void deletePreviousEventsHavingSameVersion(DbSession session, String version, Component component) {
- for (EventDto dto : dbClient.eventDao().selectByComponentUuid(session, component.getUuid())) {
- if (dto.getCategory().equals(EventDto.CATEGORY_VERSION) && dto.getName().equals(version)) {
- dbClient.eventDao().delete(session, dto.getId());
- }
- }
- }
-
- private EventDto newBaseEvent(Component component, Long analysisDate) {
- return new EventDto()
- .setAnalysisUuid(analysisMetadataHolder.getUuid())
- .setComponentUuid(component.getUuid())
- .setCreatedAt(system2.now())
- .setDate(analysisDate);
- }
-
- private static String convertCategory(Event.Category category) {
- switch (category) {
- case ALERT:
- return EventDto.CATEGORY_ALERT;
- case PROFILE:
- return EventDto.CATEGORY_PROFILE;
- default:
- throw new IllegalArgumentException(String.format("Unsupported category %s", category.name()));
- }
- }
-
@Override
public String getDescription() {
return "Persist events";
private final DbSession session;
private final long analysisDate;
- public PersistEventComponentVisitor(DbSession session, long analysisDate) {
- super(CrawlerDepthLimit.PROJECT, ComponentVisitor.Order.PRE_ORDER);
+ PersistEventComponentVisitor(DbSession session, long analysisDate) {
+ super(CrawlerDepthLimit.PROJECT, Order.PRE_ORDER);
this.session = session;
this.analysisDate = analysisDate;
}
saveVersionEvent(session, project, analysisDate);
}
+ private void processEvents(DbSession session, Component component, Long analysisDate) {
+ Function<Event, EventDto> eventToEventDto = event -> newBaseEvent(component, analysisDate)
+ .setName(event.getName())
+ .setCategory(convertCategory(event.getCategory()))
+ .setDescription(event.getDescription())
+ .setData(event.getData());
+ // FIXME bulk insert
+ for (EventDto batchEventDto : StreamSupport.stream(eventRepository.getEvents(component).spliterator(), false).map(eventToEventDto).collect(Collectors.toList())) {
+ dbClient.eventDao().insert(session, batchEventDto);
+ }
+ }
+
+ private void saveVersionEvent(DbSession session, Component component, Long analysisDate) {
+ String version = component.getReportAttributes().getVersion();
+ if (version != null) {
+ deletePreviousEventsHavingSameVersion(session, version, component);
+ dbClient.eventDao().insert(session, newBaseEvent(component, analysisDate)
+ .setName(version)
+ .setCategory(EventDto.CATEGORY_VERSION));
+ }
+ }
+
+ private void deletePreviousEventsHavingSameVersion(DbSession session, String version, Component component) {
+ for (EventDto dto : dbClient.eventDao().selectByComponentUuid(session, component.getUuid())) {
+ if (dto.getCategory().equals(EventDto.CATEGORY_VERSION) && dto.getName().equals(version)) {
+ dbClient.eventDao().delete(session, dto.getId());
+ }
+ }
+ }
+
+ private EventDto newBaseEvent(Component component, Long analysisDate) {
+ return new EventDto()
+ .setAnalysisUuid(analysisMetadataHolder.getUuid())
+ .setComponentUuid(component.getUuid())
+ .setCreatedAt(system2.now())
+ .setDate(analysisDate);
+ }
+
+ private String convertCategory(Event.Category category) {
+ switch (category) {
+ case ALERT:
+ return EventDto.CATEGORY_ALERT;
+ case PROFILE:
+ return EventDto.CATEGORY_PROFILE;
+ default:
+ throw new IllegalArgumentException(String.format("Unsupported category %s", category.name()));
+ }
+ }
+
}
}
*/
package org.sonar.server.computation.task.projectanalysis.step;
-import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
import java.util.List;
import java.util.Locale;
import java.util.Map;
+import java.util.Optional;
import java.util.Set;
-import javax.annotation.Nullable;
import org.sonar.api.i18n.I18n;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
throw new IllegalArgumentException(String.format("Link of type '%s' has already been declared on component '%s'", type, componentUuid));
}
- ComponentLinkDto previousLink = Iterables.find(previousLinks, new Predicate<ComponentLinkDto>() {
- @Override
- public boolean apply(@Nullable ComponentLinkDto input) {
- return input != null && input.getType().equals(convertType(link.getType()));
- }
- }, null);
- if (previousLink == null) {
+ Optional<ComponentLinkDto> previousLink = previousLinks.stream()
+ .filter(input -> input != null && input.getType().equals(convertType(link.getType())))
+ .findFirst();
+ if (previousLink.isPresent()) {
+ previousLink.get().setHref(link.getHref());
+ dbClient.componentLinkDao().update(session, previousLink.get());
+ } else {
dbClient.componentLinkDao().insert(session,
new ComponentLinkDto()
.setComponentUuid(componentUuid)
.setType(type)
.setName(i18n.message(Locale.ENGLISH, "project_links." + type, null))
.setHref(link.getHref()));
- } else {
- previousLink.setHref(link.getHref());
- dbClient.componentLinkDao().update(session, previousLink);
}
}
import java.util.List;
import java.util.Map;
import java.util.Set;
-import org.apache.ibatis.session.ResultContext;
-import org.apache.ibatis.session.ResultHandler;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.log.Logger;
import org.sonar.api.utils.log.Loggers;
this.projectKey = treeRootHolder.getRoot().getKey();
session.select("org.sonar.db.source.FileSourceMapper.selectHashesForProject",
ImmutableMap.of("projectUuid", treeRootHolder.getRoot().getUuid(), "dataType", Type.TEST),
- new ResultHandler() {
- @Override
- public void handleResult(ResultContext context) {
- FileSourceDto dto = (FileSourceDto) context.getResultObject();
- existingFileSourcesByUuid.put(dto.getFileUuid(), dto);
- }
+ context -> {
+ FileSourceDto dto = (FileSourceDto) context.getResultObject();
+ existingFileSourcesByUuid.put(dto.getFileUuid(), dto);
});
}
throw new IllegalArgumentException("Cannot sort on field : " + sort);
}
- abstract static class IssueProcessor {
- abstract Function sortFieldFunction();
+ interface IssueProcessor {
+ Function sortFieldFunction();
- abstract Ordering sortFieldOrdering(boolean ascending);
+ Ordering sortFieldOrdering(boolean ascending);
- final List<IssueDto> sort(Collection<IssueDto> issueDtos, boolean ascending) {
+ default List<IssueDto> sort(Collection<IssueDto> issueDtos, boolean ascending) {
Ordering<IssueDto> ordering = sortFieldOrdering(ascending).onResultOf(sortFieldFunction());
return ordering.immutableSortedCopy(issueDtos);
}
}
- abstract static class TextSortIssueProcessor extends IssueProcessor {
+ abstract static class TextSortIssueProcessor implements IssueProcessor {
@Override
- Function sortFieldFunction() {
+ public Function sortFieldFunction() {
return new Function<IssueDto, String>() {
@Override
public String apply(IssueDto issueDto) {
abstract String sortField(IssueDto issueDto);
@Override
- Ordering sortFieldOrdering(boolean ascending) {
+ public Ordering sortFieldOrdering(boolean ascending) {
Ordering<String> ordering = Ordering.from(String.CASE_INSENSITIVE_ORDER).nullsLast();
if (!ascending) {
ordering = ordering.reverse();
}
}
- static class SeveritySortIssueProcessor extends IssueProcessor {
+ static class SeveritySortIssueProcessor implements IssueProcessor {
@Override
- Function sortFieldFunction() {
+ public Function sortFieldFunction() {
return IssueDtoToSeverity.INSTANCE;
}
@Override
- Ordering sortFieldOrdering(boolean ascending) {
+ public Ordering sortFieldOrdering(boolean ascending) {
Ordering<Integer> ordering = Ordering.<Integer>natural().nullsLast();
if (!ascending) {
ordering = ordering.reverse();
}
}
- abstract static class DateSortRowProcessor extends IssueProcessor {
+ abstract static class DateSortRowProcessor implements IssueProcessor {
@Override
- Function sortFieldFunction() {
+ public Function sortFieldFunction() {
return new Function<IssueDto, Date>() {
@Override
public Date apply(IssueDto issueDto) {
abstract Date sortField(IssueDto issueDto);
@Override
- Ordering sortFieldOrdering(boolean ascending) {
+ public Ordering sortFieldOrdering(boolean ascending) {
Ordering<Date> ordering = Ordering.<Date>natural().nullsLast();
if (!ascending) {
ordering = ordering.reverse();
*/
package org.sonar.server.issue;
-import com.google.common.base.Predicate;
import com.google.common.base.Strings;
-import com.google.common.collect.Iterables;
import java.util.Collection;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.server.ServerSide;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.server.issue.workflow.IssueWorkflow;
-import org.sonar.server.issue.workflow.Transition;
import org.sonar.server.user.UserSession;
@ServerSide
private boolean canExecuteTransition(Issue issue, final String transition) {
final DefaultIssue defaultIssue = (DefaultIssue) issue;
- return Iterables.find(workflow.outTransitions(issue), new Predicate<Transition>() {
- @Override
- public boolean apply(Transition input) {
- return input.key().equals(transition) &&
- (StringUtils.isBlank(input.requiredProjectPermission()) ||
- userSession.hasComponentPermission(input.requiredProjectPermission(), defaultIssue.projectKey()));
- }
- }, null) != null;
+ return workflow.outTransitions(issue).stream()
+ .filter(input -> input.key().equals(transition) &&
+ (StringUtils.isBlank(input.requiredProjectPermission()) ||
+ userSession.hasComponentPermission(input.requiredProjectPermission(), defaultIssue.projectKey())))
+ .findFirst().orElseGet(() -> null) != null;
}
private static String transition(Map<String, Object> properties) {
return query.build();
}
- private WsPermissions.UsersWsResponse buildResponse(List<UserDto> users, List<PermissionTemplateUserDto> permissionTemplateUsers, Paging paging) {
+ private static WsPermissions.UsersWsResponse buildResponse(List<UserDto> users, List<PermissionTemplateUserDto> permissionTemplateUsers, Paging paging) {
Multimap<Long, String> permissionsByUserId = TreeMultimap.create();
permissionTemplateUsers.forEach(userPermission -> permissionsByUserId.put(userPermission.getUserId(), userPermission.getPermission()));
return responseBuilder.build();
}
- public List<UserDto> findUsers(DbSession dbSession, PermissionQuery query, PermissionTemplateDto template) {
+ private List<UserDto> findUsers(DbSession dbSession, PermissionQuery query, PermissionTemplateDto template) {
List<String> orderedLogins = dbClient.permissionTemplateDao().selectUserLoginsByQueryAndTemplate(dbSession, query, template.getId());
return Ordering.explicit(orderedLogins).onResultOf(UserDto::getLogin).immutableSortedCopy(dbClient.userDao().selectByLogins(dbSession, orderedLogins));
}
*/
package org.sonar.server.rule.ws;
-import org.apache.ibatis.session.ResultContext;
-import org.apache.ibatis.session.ResultHandler;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
final ListResponse.Builder listResponseBuilder = ListResponse.newBuilder();
final ListResponse.Rule.Builder ruleBuilder = ListResponse.Rule.newBuilder();
try {
- dbClient.ruleDao().selectEnabled(dbSession, new ResultHandler() {
- @Override
- public void handleResult(ResultContext resultContext) {
- RuleDto dto = (RuleDto) resultContext.getResultObject();
- ruleBuilder
- .clear()
- .setRepository(dto.getRepositoryKey())
- .setKey(dto.getRuleKey())
- .setName(nullToEmpty(dto.getName()))
- .setInternalKey(nullToEmpty(dto.getConfigKey()));
- listResponseBuilder.addRules(ruleBuilder.build());
- }
+ dbClient.ruleDao().selectEnabled(dbSession, resultContext -> {
+ RuleDto dto = (RuleDto) resultContext.getResultObject();
+ ruleBuilder
+ .clear()
+ .setRepository(dto.getRepositoryKey())
+ .setKey(dto.getRuleKey())
+ .setName(nullToEmpty(dto.getName()))
+ .setInternalKey(nullToEmpty(dto.getConfigKey()));
+ listResponseBuilder.addRules(ruleBuilder.build());
});
} finally {
dbClient.closeSession(dbSession);
*/
package org.sonar.server.usergroups.ws;
+import java.util.Objects;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewAction;
private void updateDefaultGroupIfNeeded(DbSession dbSession, String oldName, String newName) {
String defaultGroupName = persistentSettings.getString(CORE_DEFAULT_GROUP);
- if (defaultGroupName.equals(oldName)) {
+ if (Objects.equals(defaultGroupName, oldName)) {
persistentSettings.saveProperty(dbSession, CORE_DEFAULT_GROUP, newName);
}
}
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
verify(settings).saveProperty(any(DbSession.class), eq(DEFAULT_GROUP_NAME_KEY), eq("new-name"));
}
+ @Test
+ public void update_default_group_name_does_not_update_default_group_setting_when_null() throws Exception {
+ when(settings.getString(DEFAULT_GROUP_NAME_KEY)).thenReturn(null);
+ GroupDto existingGroup = groupDao.insert(dbSession, new GroupDto().setName(DEFAULT_GROUP_NAME_VALUE).setDescription("Default group name"));
+ dbSession.commit();
+
+ loginAsAdmin();
+ newRequest()
+ .setParam("id", existingGroup.getId().toString())
+ .setParam("name", "new-name")
+ .execute();
+
+ verify(settings, never()).saveProperty(any(DbSession.class), eq(DEFAULT_GROUP_NAME_KEY), eq("new-name"));
+ }
+
@Test
public void require_admin_permission() throws Exception {
expectedException.expect(ForbiddenException.class);
* The implementation should rather use a new column already containing the root project, see https://jira.sonarsource.com/browse/SONAR-5188.
*/
@CheckForNull
- private ResourceDto getRootProjectByComponentKey(DbSession session, String componentKey) {
+ private static ResourceDto getRootProjectByComponentKey(DbSession session, String componentKey) {
ResourceDto component = selectResource(ResourceQuery.create().setKey(componentKey), session);
if (component != null) {
String rootUuid = component.getRootUuid();
import org.sonar.db.DatabaseUtils;
import org.sonar.db.version.BaseDataChange;
import org.sonar.db.version.MassUpdate;
-import org.sonar.db.version.Select;
-import org.sonar.db.version.SqlStatement;
/**
* Used in the Active Record Migration 710
massUpdate.select("SELECT f.id, f.data FROM issue_filters f WHERE f.data like '%componentRoots=%'");
massUpdate.update("UPDATE issue_filters SET data=?, updated_at=? WHERE id=?");
final PreparedStatement finalPstmt = pstmt;
- massUpdate.execute(new MassUpdate.Handler() {
- @Override
- public boolean handle(Select.Row row, SqlStatement update) throws SQLException {
- Long id = row.getNullableLong(1);
- String data = row.getNullableString(2);
- if (data == null) {
- return false;
- }
- update.setString(1, convertData(finalPstmt, data));
- update.setDate(2, now);
- update.setLong(3, id);
- return true;
+ massUpdate.execute((row, update) -> {
+ Long id = row.getNullableLong(1);
+ String data = row.getNullableString(2);
+ if (data == null) {
+ return false;
}
+ update.setString(1, convertData(finalPstmt, data));
+ update.setDate(2, now);
+ update.setLong(3, id);
+ return true;
});
} finally {
DbUtils.closeQuietly(connection);
*/
package org.sonar.api.measures;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Iterables;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
-import javax.annotation.Nullable;
+import java.util.NoSuchElementException;
import org.sonar.api.test.MutableTestPlan;
import org.sonar.api.utils.SonarException;
* </duplications>
* }
* </pre>
- *
+ *
* @deprecated since 4.5. Internal storage of duplication is not an API.
*/
@Deprecated
}
public static Metric getMetric(final String key) {
- return Iterables.find(METRICS, new Predicate<Metric>() {
- @Override
- public boolean apply(@Nullable Metric input) {
- return input != null && input.getKey().equals(key);
- }
- });
+ return METRICS.stream().filter(metric -> metric != null && metric.getKey().equals(key)).findFirst().orElseThrow(NoSuchElementException::new);
}
}
package org.sonar.api.resources;
import java.util.List;
+import java.util.NoSuchElementException;
+import org.junit.Rule;
import org.junit.Test;
-import org.sonar.api.measures.CoreMetrics;
+import org.junit.rules.ExpectedException;
import org.sonar.api.measures.Metric;
import static org.assertj.core.api.Assertions.assertThat;
+import static org.sonar.api.measures.CoreMetrics.DIRECTORIES;
+import static org.sonar.api.measures.CoreMetrics.NCLOC;
+import static org.sonar.api.measures.CoreMetrics.getMetric;
+import static org.sonar.api.measures.CoreMetrics.getMetrics;
public class CoreMetricsTest {
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
@Test
public void read_metrics_from_class_reflection() {
- List<Metric> metrics = CoreMetrics.getMetrics();
+ List<Metric> metrics = getMetrics();
assertThat(metrics.size()).isGreaterThan(100);
- assertThat(metrics).contains(CoreMetrics.NCLOC, CoreMetrics.DIRECTORIES);
+ assertThat(metrics).contains(NCLOC, DIRECTORIES);
+ }
+
+ @Test
+ public void get_metric_by_key() throws Exception {
+ Metric metric = getMetric("ncloc");
+ assertThat(metric.getKey()).isEqualTo("ncloc");
+ }
+
+ @Test
+ public void fail_get_unknown_metric_by_key() throws Exception {
+ expectedException.expect(NoSuchElementException.class);
+ getMetric("unknown");
}
}