import org.sonar.db.ce.CeActivityDto;
import org.sonar.db.ce.CeQueueDto;
import org.sonar.db.component.ComponentDto;
-import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
+import org.sonar.server.ws.WsUtils;
import org.sonarqube.ws.WsCe;
import static org.sonar.core.permission.GlobalPermissions.SCAN_EXECUTION;
checkPermission(component);
wsTaskResponse.setTask(wsTaskFormatter.formatQueue(dbSession, queueDto.get(), component));
} else {
- Optional<CeActivityDto> activityDto = dbClient.ceActivityDao().selectByUuid(dbSession, taskUuid);
- if (activityDto.isPresent()) {
- CeActivityDto ceActivityDto = activityDto.get();
- Optional<ComponentDto> component = loadComponent(dbSession, ceActivityDto.getComponentUuid());
- checkPermission(component);
- Set<AdditionalField> additionalFields = AdditionalField.getFromRequest(wsRequest);
- maskErrorStacktrace(ceActivityDto, additionalFields);
- wsTaskResponse.setTask(
- wsTaskFormatter.formatActivity(dbSession, ceActivityDto, component, extractScannerContext(dbSession, ceActivityDto, additionalFields)));
- } else {
- throw new NotFoundException();
- }
+ CeActivityDto ceActivityDto = WsUtils.checkFoundWithOptional(dbClient.ceActivityDao().selectByUuid(dbSession, taskUuid), "No activity found for task '%s'", taskUuid);
+ Optional<ComponentDto> component = loadComponent(dbSession, ceActivityDto.getComponentUuid());
+ checkPermission(component);
+ Set<AdditionalField> additionalFields = AdditionalField.getFromRequest(wsRequest);
+ maskErrorStacktrace(ceActivityDto, additionalFields);
+ wsTaskResponse.setTask(
+ wsTaskFormatter.formatActivity(dbSession, ceActivityDto, component, extractScannerContext(dbSession, ceActivityDto, additionalFields)));
}
writeProtobuf(wsTaskResponse.build(), wsRequest, wsResponse);
}
public class NotFoundException extends ServerException {
- public NotFoundException() {
- super(HTTP_NOT_FOUND);
- }
-
public NotFoundException(String message) {
super(HTTP_NOT_FOUND, message);
}
public class ServerException extends RuntimeException {
private final int httpCode;
- public ServerException(int httpCode) {
- this.httpCode = httpCode;
- }
-
public ServerException(int httpCode, String message) {
super(requireNonNull(message, "Error message cannot be null"));
this.httpCode = httpCode;
*/
public class UnauthorizedException extends ServerException {
- public UnauthorizedException() {
- super(HTTP_UNAUTHORIZED);
- }
-
public UnauthorizedException(String message) {
super(HTTP_UNAUTHORIZED, message);
}
*/
package org.sonar.server.source;
-import com.google.common.base.Function;
-import com.google.common.base.Functions;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.collect.FluentIterable;
-import javax.annotation.Nonnull;
+import java.util.Optional;
+import java.util.function.Function;
+import org.sonar.core.util.stream.Collectors;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.db.source.FileSourceDto;
+import static com.google.common.base.Preconditions.checkArgument;
+
public class SourceService {
private final DbClient dbClient;
* @param toInclusive starts from 1, must be greater than or equal param {@code from}
*/
public Optional<Iterable<DbFileSources.Line>> getLines(DbSession dbSession, String fileUuid, int from, int toInclusive) {
- return getLines(dbSession, fileUuid, from, toInclusive, Functions.identity());
+ return getLines(dbSession, fileUuid, from, toInclusive, Function.identity());
}
/**
* @see #getLines(DbSession, String, int, int)
*/
public Optional<Iterable<String>> getLinesAsRawText(DbSession dbSession, String fileUuid, int from, int toInclusive) {
- return getLines(dbSession, fileUuid, from, toInclusive, LineToRaw.INSTANCE);
+ return getLines(dbSession, fileUuid, from, toInclusive, DbFileSources.Line::getSource);
}
public Optional<Iterable<String>> getLinesAsHtml(DbSession dbSession, String fileUuid, int from, int toInclusive) {
private <E> Optional<Iterable<E>> getLines(DbSession dbSession, String fileUuid, int from, int toInclusive, Function<DbFileSources.Line, E> function) {
verifyLine(from);
- Preconditions.checkArgument(toInclusive >= from, String.format("Line number must greater than or equal to %d, got %d", from, toInclusive));
+ checkArgument(toInclusive >= from, String.format("Line number must greater than or equal to %d, got %d", from, toInclusive));
FileSourceDto dto = dbClient.fileSourceDao().selectSourceByFileUuid(dbSession, fileUuid);
if (dto == null) {
- return Optional.absent();
+ return Optional.empty();
}
- DbFileSources.Data data = dto.getSourceData();
- return Optional.of(FluentIterable.from(data.getLinesList())
- .filter(new IsGreaterOrEqualThanLine(from))
- .limit(toInclusive - from + 1)
- .transform(function));
+ return Optional.of(dto.getSourceData().getLinesList().stream()
+ .filter(line -> line.hasLine() && line.getLine() >= from)
+ .limit((toInclusive - from) + 1L)
+ .map(function)
+ .collect(Collectors.toList()));
}
private static void verifyLine(int line) {
- Preconditions.checkArgument(line >= 1, String.format("Line number must start at 1, got %d", line));
+ checkArgument(line >= 1, String.format("Line number must start at 1, got %d", line));
}
private Function<DbFileSources.Line, String> lineToHtml() {
return line -> htmlDecorator.getDecoratedSourceAsHtml(line.getSource(), line.getHighlighting(), line.getSymbols());
}
- private enum LineToRaw implements Function<DbFileSources.Line, String> {
- INSTANCE;
- @Override
- public String apply(@Nonnull DbFileSources.Line line) {
- return line.getSource();
- }
-
- }
-
- private static class IsGreaterOrEqualThanLine implements Predicate<DbFileSources.Line> {
- private final int from;
-
- IsGreaterOrEqualThanLine(int from) {
- this.from = from;
- }
-
- @Override
- public boolean apply(@Nonnull DbFileSources.Line line) {
- return line.hasLine() && line.getLine() >= from;
- }
- }
}
*/
package org.sonar.server.source.ws;
-import com.google.common.base.Optional;
import com.google.common.io.Resources;
+import java.util.Optional;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.server.component.ComponentFinder;
-import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.HtmlSourceDecorator;
import org.sonar.server.source.SourceService;
import org.sonar.server.user.UserSession;
import static org.sonar.server.component.ComponentFinder.ParamNames.UUID_AND_KEY;
import static org.sonar.server.ws.KeyExamples.KEY_FILE_EXAMPLE_001;
+import static org.sonar.server.ws.WsUtils.checkFoundWithOptional;
public class LinesAction implements SourcesWsAction {
@Override
public void handle(Request request, Response response) {
- DbSession dbSession = dbClient.openSession(false);
- try {
+ try (DbSession dbSession = dbClient.openSession(false)) {
ComponentDto file = componentFinder.getByUuidOrKey(dbSession, request.param(PARAM_UUID), request.param(PARAM_KEY), UUID_AND_KEY);
userSession.checkComponentPermission(UserRole.CODEVIEWER, file);
int from = request.mandatoryParamAsInt(PARAM_FROM);
int to = MoreObjects.firstNonNull(request.paramAsInt(PARAM_TO), Integer.MAX_VALUE);
- com.google.common.base.Optional<Iterable<DbFileSources.Line>> lines = sourceService.getLines(dbSession, file.uuid(), from, to);
- if (!lines.isPresent()) {
- throw new NotFoundException();
- }
-
+ Iterable<DbFileSources.Line> lines = checkFoundWithOptional(sourceService.getLines(dbSession, file.uuid(), from, to), "No source found for file '%s'", file.key());
JsonWriter json = response.newJsonWriter().beginObject();
- writeSource(lines.get(), json);
+ writeSource(lines, json);
json.endObject().close();
- } finally {
- dbClient.closeSession(dbSession);
}
}
*/
package org.sonar.server.source.ws;
-import com.google.common.base.Optional;
import com.google.common.io.Resources;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
+import java.util.Optional;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
*/
package org.sonar.server.source.ws;
-import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.io.Resources;
import java.util.Date;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.server.component.ComponentFinder;
-import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.SourceService;
import org.sonar.server.user.UserSession;
+import static org.sonar.server.ws.WsUtils.checkFoundWithOptional;
+
public class ScmAction implements SourcesWsAction {
private final DbClient dbClient;
try {
ComponentDto file = componentFinder.getByKey(dbSession, fileKey);
userSession.checkComponentPermission(UserRole.CODEVIEWER, file);
- Optional<Iterable<DbFileSources.Line>> sourceLines = sourceService.getLines(dbSession, file.uuid(), from, to);
- if (!sourceLines.isPresent()) {
- throw new NotFoundException(String.format("File '%s' has no sources", fileKey));
- }
+ Iterable<DbFileSources.Line> sourceLines = checkFoundWithOptional(sourceService.getLines(dbSession, file.uuid(), from, to), "File '%s' has no sources", fileKey);
JsonWriter json = response.newJsonWriter().beginObject();
- writeSource(sourceLines.get(), commitsByLine, json);
+ writeSource(sourceLines, commitsByLine, json);
json.endObject().close();
} finally {
dbClient.closeSession(dbSession);
*/
package org.sonar.server.source.ws;
-import com.google.common.base.Optional;
import com.google.common.io.Resources;
import org.apache.commons.lang.ObjectUtils;
import org.sonar.api.server.ws.Request;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.server.component.ComponentFinder;
-import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.source.SourceService;
import org.sonar.server.user.UserSession;
+import static org.sonar.server.ws.WsUtils.checkFoundWithOptional;
+
public class ShowAction implements SourcesWsAction {
private final SourceService sourceService;
int from = Math.max(request.paramAsInt("from"), 1);
int to = (Integer) ObjectUtils.defaultIfNull(request.paramAsInt("to"), Integer.MAX_VALUE);
- DbSession dbSession = dbClient.openSession(false);
- try {
+ try (DbSession dbSession = dbClient.openSession(false)) {
ComponentDto file = componentFinder.getByKey(dbSession, fileKey);
userSession.checkComponentPermission(UserRole.CODEVIEWER, file);
- Optional<Iterable<String>> linesHtml = sourceService.getLinesAsHtml(dbSession, file.uuid(), from, to);
- if (linesHtml.isPresent()) {
- JsonWriter json = response.newJsonWriter().beginObject();
- writeSource(linesHtml.get(), from, json);
- json.endObject().close();
- } else {
- throw new NotFoundException();
- }
+ Iterable<String> linesHtml = checkFoundWithOptional(sourceService.getLinesAsHtml(dbSession, file.uuid(), from, to), "No source found for file '%s'", fileKey);
+ JsonWriter json = response.newJsonWriter().beginObject();
+ writeSource(linesHtml, from, json);
+ json.endObject().close();
- } finally {
- dbClient.closeSession(dbSession);
}
}
- private void writeSource(Iterable<String> lines, int from, JsonWriter json) {
+ private static void writeSource(Iterable<String> lines, int from, JsonWriter json) {
json.name("sources").beginArray();
long index = 0L;
for (String line : lines) {
if (session != null) {
return session;
}
- throw new UnauthorizedException();
+ throw new UnauthorizedException("User is not authenticate");
}
public void set(UserSession session) {
@Test
public void return_authorized_code_when_unauthorized_exception_is_thrown() throws Exception {
- doThrow(new UnauthorizedException()).when(credentialsAuthenticator).authenticate(LOGIN, PASSWORD, request, FORM);
+ doThrow(new UnauthorizedException("error !")).when(credentialsAuthenticator).authenticate(LOGIN, PASSWORD, request, FORM);
executeRequest(LOGIN, PASSWORD);
*/
package org.sonar.server.source;
-import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.util.List;
+import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
*/
package org.sonar.server.source.ws;
-import com.google.common.base.Optional;
+import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public void get_json() throws Exception {
String fileKey = "src/Foo.java";
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
- when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
+ when(componentDao.selectByKey(session, fileKey)).thenReturn(com.google.common.base.Optional.of(file));
- when(sourceService.getLinesAsRawText(session, file.uuid(), 1, Integer.MAX_VALUE)).thenReturn(Optional.of((Iterable<String>) newArrayList(
+ when(sourceService.getLinesAsRawText(session, file.uuid(), 1, Integer.MAX_VALUE)).thenReturn(Optional.of(newArrayList(
"public class HelloWorld {",
"}")));
public void limit_range() throws Exception {
String fileKey = "src/Foo.java";
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
- when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
+ when(componentDao.selectByKey(session, fileKey)).thenReturn(com.google.common.base.Optional.of(file));
- when(sourceService.getLinesAsRawText(session, file.uuid(), 1, 2)).thenReturn(Optional.of((Iterable<String>) newArrayList(
+ when(sourceService.getLinesAsRawText(session, file.uuid(), 1, 2)).thenReturn(Optional.of(newArrayList(
"public class HelloWorld {",
"}")));
@Test(expected = ForbiddenException.class)
public void requires_code_viewer_permission() throws Exception {
- when(componentDao.selectByKey(session, "foo")).thenReturn(Optional.of(file));
+ when(componentDao.selectByKey(session, "foo")).thenReturn(com.google.common.base.Optional.of(file));
tester.newGetRequest("api/sources", "index").setParam("resource", "foo").execute();
}
public void close_db_session() throws Exception {
String fileKey = "src/Foo.java";
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
- when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.<ComponentDto>absent());
+ when(componentDao.selectByKey(session, fileKey)).thenReturn(com.google.common.base.Optional.<ComponentDto>absent());
WsTester.TestRequest request = tester.newGetRequest("api/sources", "index").setParam("resource", fileKey);
try {
*/
package org.sonar.server.source.ws;
-import com.google.common.base.Optional;
+import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public void get_txt() throws Exception {
String fileKey = "src/Foo.java";
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
- when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
+ when(componentDao.selectByKey(session, fileKey)).thenReturn(com.google.common.base.Optional.of(file));
Iterable<String> lines = newArrayList(
"public class HelloWorld {",
@Test(expected = ForbiddenException.class)
public void requires_code_viewer_permission() throws Exception {
- when(componentDao.selectByKey(session, "src/Foo.java")).thenReturn(Optional.of(file));
+ when(componentDao.selectByKey(session, "src/Foo.java")).thenReturn(com.google.common.base.Optional.of(file));
tester.newGetRequest("api/sources", "raw").setParam("key", "src/Foo.java").execute();
}
}
*/
package org.sonar.server.source.ws;
-import com.google.common.base.Optional;
+import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public void show_source() throws Exception {
String fileKey = "src/Foo.java";
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
- when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
- when(sourceService.getLinesAsHtml(eq(session), eq(file.uuid()), anyInt(), anyInt())).thenReturn(Optional.of((Iterable<String>) newArrayList(
+ when(componentDao.selectByKey(session, fileKey)).thenReturn(com.google.common.base.Optional.of(file));
+ when(sourceService.getLinesAsHtml(eq(session), eq(file.uuid()), anyInt(), anyInt())).thenReturn(Optional.of(newArrayList(
"/*",
" * Header",
" */",
public void show_source_with_from_and_to_params() throws Exception {
String fileKey = "src/Foo.java";
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
- when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
- when(sourceService.getLinesAsHtml(session, file.uuid(), 3, 5)).thenReturn(Optional.of((Iterable<String>) newArrayList(
+ when(componentDao.selectByKey(session, fileKey)).thenReturn(com.google.common.base.Optional.of(file));
+ when(sourceService.getLinesAsHtml(session, file.uuid(), 3, 5)).thenReturn(Optional.of(newArrayList(
" */",
"",
"public class <span class=\"sym-31 sym\">HelloWorld</span> {")));
public void show_source_accept_from_less_than_one() throws Exception {
String fileKey = "src/Foo.java";
userSessionRule.addProjectUuidPermissions(UserRole.CODEVIEWER, project.uuid());
- when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
- when(sourceService.getLinesAsHtml(session, file.uuid(), 1, 5)).thenReturn(Optional.of((Iterable<String>) newArrayList(
+ when(componentDao.selectByKey(session, fileKey)).thenReturn(com.google.common.base.Optional.of(file));
+ when(sourceService.getLinesAsHtml(session, file.uuid(), 1, 5)).thenReturn(Optional.of(newArrayList(
" */",
"",
"public class <span class=\"sym-31 sym\">HelloWorld</span> {")));
@Test(expected = ForbiddenException.class)
public void require_code_viewer() throws Exception {
String fileKey = "src/Foo.java";
- when(componentDao.selectByKey(session, fileKey)).thenReturn(Optional.of(file));
+ when(componentDao.selectByKey(session, fileKey)).thenReturn(com.google.common.base.Optional.of(file));
tester.newGetRequest("api/sources", "show").setParam("key", fileKey).execute();
}
}