Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions java-frontend-semsitter/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,21 @@
<description>Code Analyzer for Java :: Front-end based on SemSitter</description>

<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>java-frontend</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.sonarsource.api.plugin</groupId>
<artifactId>sonar-plugin-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.sonarsource.semsitter</groupId>
<artifactId>analyzer-wire</artifactId>
Expand All @@ -22,6 +37,21 @@
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>org.sonarsource.scanner.engine</groupId>
<artifactId>plugin-api-scanner-impl</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.sonarsource.scanner.engine</groupId>
<artifactId>sensor-test-fixtures</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* 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 Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.semsitter;

import com.google.gson.JsonObject;
import java.util.Set;
import java.util.function.Function;
import org.sonar.java.model.JParseResult;
import org.sonarsource.semsitter.wire.Document;

/**
* Turns the document a SemSitter server answered for one file into the tree the checks run on. The loaders give the
* declarations of the named types and whether a package exists, as the server answers them while the session is open.
*/
@FunctionalInterface
public interface DocumentTranslator {

JParseResult translate(Document document, Function<Set<String>, JsonObject> types, Function<String, Boolean> packages, boolean noLibraries,

Check warning on line 32 in java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/DocumentTranslator.java

View check run for this annotation

SonarQube-Next / SonarQube Code Analysis

Refactor this code to use the more specialised Functional Interface 'Predicate<String>'

[S4276] Functional Interfaces should be as specialised as possible See more on https://next.sonarqube.com/sonarqube/project/issues?id=org.sonarsource.java%3Ajava&pullRequest=6547&issues=bfb24bc7-c375-4958-abcd-ddb904a70868&open=bfb24bc7-c375-4958-abcd-ddb904a70868
int javaVersion);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* 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 Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.semsitter;

/**
* Remote switches that decide which behavior an analysis gets.
*/
public interface FeatureFlags {

/** Opens a flag service for one project. */
@FunctionalInterface
interface Connector {

Check warning on line 26 in java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/FeatureFlags.java

View check run for this annotation

SonarQube-Next / SonarQube Code Analysis

Drop this interface in favor of "java.util.function.BiFunction<String,String,FeatureFlags>".

[S1711] Standard functional interfaces should not be redefined See more on https://next.sonarqube.com/sonarqube/project/issues?id=org.sonarsource.java%3Ajava&pullRequest=6547&issues=9b907729-9741-46c7-9b02-db9f73ddfdd0&open=9b907729-9741-46c7-9b02-db9f73ddfdd0
FeatureFlags connect(String clientSideId, String projectKey);
}

/**
* @return the value of the flag, or {@code defaultValue} when the service cannot tell
*/
boolean isEnabled(String flagKey, boolean defaultValue);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* 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 Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.semsitter;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
* {@link FeatureFlags} read from LaunchDarkly through its client-side evaluation endpoint, which keeps the plugin free of
* the LaunchDarkly SDK and of everything the SDK drags along. The flags of a project are fetched once when the service
* is opened, no analytics event is sent, and a service that does not answer in time leaves every flag at its default.
*/
public final class LaunchDarklyFeatureFlags implements FeatureFlags {

static final String PROJECT_KIND = "project";
static final String ENDPOINT = "https://clientsdk.launchdarkly.com";
static final Duration TIMEOUT = Duration.ofSeconds(3);

private static final Logger LOG = LoggerFactory.getLogger(LaunchDarklyFeatureFlags.class);

private final JsonObject flags;

LaunchDarklyFeatureFlags(JsonObject flags) {
this.flags = flags;
}

public static FeatureFlags connect(String clientSideId, String projectKey) {
return connect(URI.create(ENDPOINT), clientSideId, projectKey);
}

static FeatureFlags connect(URI endpoint, String clientSideId, String projectKey) {
try {
return new LaunchDarklyFeatureFlags(fetch(endpoint, clientSideId, projectKey));
} catch (IOException | RuntimeException e) {
LOG.debug("LaunchDarkly is not reachable, every flag keeps its default value: {}", e.getMessage());
return new LaunchDarklyFeatureFlags(new JsonObject());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return new LaunchDarklyFeatureFlags(new JsonObject());
}
}

private static JsonObject fetch(URI endpoint, String clientSideId, String projectKey) throws IOException, InterruptedException {
JsonObject context = new JsonObject();
context.addProperty("kind", PROJECT_KIND);
context.addProperty("key", projectKey);
String encodedContext = Base64.getUrlEncoder().encodeToString(context.toString().getBytes(StandardCharsets.UTF_8));
URI uri = URI.create(endpoint + "/sdk/evalx/" + clientSideId + "/contexts/" + encodedContext);
HttpRequest request = HttpRequest.newBuilder(uri).timeout(TIMEOUT).GET().build();
HttpClient client = HttpClient.newBuilder().connectTimeout(TIMEOUT).build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (response.statusCode() != 200) {
throw new IOException("unexpected status " + response.statusCode());
}
return JsonParser.parseString(response.body()).getAsJsonObject();
}

@Override
public boolean isEnabled(String flagKey, boolean defaultValue) {
JsonElement flag = flags.get(flagKey);
if (flag == null || !flag.isJsonObject()) {
return defaultValue;
}
JsonElement value = flag.getAsJsonObject().get("value");
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isBoolean()) {
return defaultValue;
}
return value.getAsBoolean();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* 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 Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.semsitter;

import java.nio.file.Path;
import java.util.Collection;

/**
* The directory a SemSitter server is started on.
*/
final class ProjectRoot {

private ProjectRoot() {
}

/**
* @return the deepest directory that contains every file, or the file system root of the first file when they share none
*/
static Path commonAncestor(Collection<Path> files) {
Path common = null;
for (Path file : files) {
Path directory = file.toAbsolutePath().normalize().getParent();
common = common == null ? directory : shared(common, directory);
}
if (common == null) {
throw new IllegalArgumentException("No file to find a project root for");
}
return common;
}

private static Path shared(Path first, Path second) {
Path candidate = first;
while (candidate != null && !second.startsWith(candidate)) {
candidate = candidate.getParent();
}
return candidate == null ? first.getRoot() : candidate;
}

/**
* @return the path of {@code file} below {@code root}, written with {@code /} on every platform, as the server names files
*/
static String relative(Path root, Path file) {
return root.relativize(file.toAbsolutePath().normalize()).toString().replace('\\', '/');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* SonarQube Java
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* 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 Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
package org.sonar.java.semsitter;

import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.sonarsource.semsitter.wire.Document;

/**
* What the SemSitter frontend asks of a running SemSitter server. {@link SemSitterClient} answers it over a process.
*/
public interface SemSitterApi extends AutoCloseable {

void setSettings(Map<String, List<String>> settings) throws IOException;

int fullGen(Collection<String> files) throws IOException;

Document getFile(String path, int ahead) throws IOException;

/**
* @return the JSON object of declarations, as {@code types.schema.json} describes it
*/
byte[] getTypes(Collection<String> names) throws IOException;

Map<String, Boolean> hasPackage(Collection<String> names) throws IOException;

@Override
void close();
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
* carries a {@link Document} and a {@code get-types} answer carries a JSON object, each prefixed by the byte count
* the header names. The process starts with the client and ends with {@link #close()}.
*/
public final class SemSitterClient implements AutoCloseable {
public final class SemSitterClient implements SemSitterApi {

static final String PROTOCOL_MAJOR = "2";

Expand All @@ -68,7 +68,7 @@

static SemSitterClient start(List<String> command) throws IOException {
Process process = new ProcessBuilder(command).redirectError(ProcessBuilder.Redirect.INHERIT).start();
SemSitterClient client = new SemSitterClient(process);

Check failure on line 71 in java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java

View check run for this annotation

SonarQube-Next / SonarQube Code Analysis

Use try-with-resources or close this "SemSitterClient" in a "finally" clause.

[S2095] Resources should be closed See more on https://next.sonarqube.com/sonarqube/project/issues?id=org.sonarsource.java%3Ajava&pullRequest=6547&issues=64924cf4-4bc2-4e46-a02b-f2491f83a00a&open=64924cf4-4bc2-4e46-a02b-f2491f83a00a
try {
String protocol = client.send(client.command("hello")).get("protocol").getAsString();
if (!protocol.startsWith(PROTOCOL_MAJOR + ".")) {
Expand All @@ -89,6 +89,7 @@
return command;
}

@Override
public void setSettings(Map<String, List<String>> settings) throws IOException {
JsonObject request = command("set-settings");
JsonObject values = new JsonObject();
Expand All @@ -105,6 +106,7 @@
* Scans {@code files}, or the source roots when empty.
* @return how many files the server scanned
*/
@Override
public int fullGen(Collection<String> files) throws IOException {
JsonObject request = command("full-gen");
if (!files.isEmpty()) {
Expand All @@ -115,6 +117,7 @@
return send(request).get("files").getAsInt();
}

@Override
public Document getFile(String path, int ahead) throws IOException {
JsonObject request = command("get-file");
request.addProperty("path", path);
Expand All @@ -127,6 +130,7 @@
/**
* @return the JSON object of declarations, as {@code types.schema.json} describes it
*/
@Override
public byte[] getTypes(Collection<String> names) throws IOException {
JsonObject request = command("get-types");
JsonArray array = new JsonArray();
Expand All @@ -135,6 +139,7 @@
return exchange(request).payload;
}

@Override
public Map<String, Boolean> hasPackage(Collection<String> names) throws IOException {
JsonObject request = command("has-package");
JsonArray array = new JsonArray();
Expand All @@ -147,7 +152,7 @@
return found;
}

private JsonObject command(String name) {

Check warning on line 155 in java-frontend-semsitter/src/main/java/org/sonar/java/semsitter/SemSitterClient.java

View check run for this annotation

SonarQube-Next / SonarQube Code Analysis

Make "command" a "static" method.

[S2325] "private" and "final" methods that don't access instance data should be "static" See more on https://next.sonarqube.com/sonarqube/project/issues?id=org.sonarsource.java%3Ajava&pullRequest=6547&issues=42523be0-b347-413c-aa93-1386e34b9c78&open=42523be0-b347-413c-aa93-1386e34b9c78
JsonObject request = new JsonObject();
request.addProperty("cmd", name);
return request;
Expand Down
Loading
Loading