repo stringlengths 1 191 ⌀ | file stringlengths 23 351 | code stringlengths 0 5.32M | file_length int64 0 5.32M | avg_line_length float64 0 2.9k | max_line_length int64 0 288k | extension_type stringclasses 1 value |
|---|---|---|---|---|---|---|
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/SarifVersionValidator.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.sarif;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import static java.lang.String.format;
import static org.sonar.core.sarif.Sarif210.SARIF_VERSION;
public class SarifVersionValidator {
public static final Set<String> SUPPORTED_SARIF_VERSIONS = Set.of(SARIF_VERSION);
public static final String UNSUPPORTED_VERSION_MESSAGE_TEMPLATE = "Version [%s] of SARIF is not supported";
private SarifVersionValidator() {}
public static void validateSarifVersion(@Nullable String version) {
if (!isSupportedSarifVersion(version)) {
throw new IllegalStateException(composeUnsupportedVersionMessage(version));
}
}
private static boolean isSupportedSarifVersion(@Nullable String version) {
return Optional.ofNullable(version)
.filter(SUPPORTED_SARIF_VERSIONS::contains)
.isPresent();
}
private static String composeUnsupportedVersionMessage(@Nullable String version) {
return format(UNSUPPORTED_VERSION_MESSAGE_TEMPLATE, version);
}
}
| 1,884 | 35.960784 | 109 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/ThreadFlow.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.sarif;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class ThreadFlow {
@SerializedName("locations")
private final List<LocationWrapper> locations;
private ThreadFlow(List<LocationWrapper> locations) {
this.locations = locations;
}
public static ThreadFlow of(List<LocationWrapper> locations) {
return new ThreadFlow(locations);
}
public List<LocationWrapper> getLocations() {
return locations;
}
}
| 1,333 | 31.536585 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/Tool.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.sarif;
import com.google.gson.annotations.SerializedName;
import java.util.Set;
public class Tool {
@SerializedName("driver")
private final Driver driver;
@SerializedName("extensions")
private Set<Extension> extensions;
public Tool(Driver driver) {
this.driver = driver;
}
public Driver getDriver() {
return driver;
}
public Set<Extension> getExtensions() {
return extensions;
}
}
| 1,284 | 28.883721 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/WrappedText.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.sarif;
import com.google.gson.annotations.SerializedName;
import java.util.Objects;
public class WrappedText {
@SerializedName("text")
private final String text;
private WrappedText(String textToWrap) {
this.text = textToWrap;
}
public static WrappedText of(String textToWrap) {
return new WrappedText(textToWrap);
}
public String getText() {
return text;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WrappedText that = (WrappedText) o;
return Objects.equals(text, that.text);
}
@Override
public int hashCode() {
return Objects.hash(text);
}
}
| 1,593 | 26.482759 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.core.sarif;
import javax.annotation.ParametersAreNonnullByDefault;
| 960 | 39.041667 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/telemetry/TelemetryExtension.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.telemetry;
import org.sonar.api.utils.text.JsonWriter;
public interface TelemetryExtension {
void write(JsonWriter json);
}
| 994 | 35.851852 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/telemetry/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
/**
* Provides support of DI (Dependency Injection) container and management of plugins.
*/
@ParametersAreNonnullByDefault
package org.sonar.core.telemetry;
import javax.annotation.ParametersAreNonnullByDefault;
| 1,059 | 36.857143 | 85 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/user/DefaultUser.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.user;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.sonar.api.user.User;
/**
* @since 3.6
*/
public class DefaultUser implements User {
private String login;
private String name;
private String email;
private boolean active;
@Override
public String login() {
return login;
}
@Override
public String name() {
return name;
}
@Override
@CheckForNull
public String email() {
return email;
}
@Override
public boolean active() {
return active;
}
public DefaultUser setLogin(String login) {
this.login = login;
return this;
}
public DefaultUser setName(String name) {
this.name = name;
return this;
}
public DefaultUser setEmail(@Nullable String s) {
this.email = StringUtils.defaultIfBlank(s, null);
return this;
}
public DefaultUser setActive(boolean b) {
this.active = b;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DefaultUser that = (DefaultUser) o;
return login.equals(that.login);
}
@Override
public int hashCode() {
return login.hashCode();
}
}
| 2,410 | 22.871287 | 86 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/user/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.core.user;
import javax.annotation.ParametersAreNonnullByDefault;
| 960 | 37.44 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/CloseableIterator.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import javax.annotation.CheckForNull;
import org.apache.commons.lang.ArrayUtils;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
public abstract class CloseableIterator<O> implements Iterator<O>, AutoCloseable {
private O nextObject = null;
boolean isClosed = false;
private static final CloseableIterator<?> EMPTY_CLOSEABLE_ITERATOR = new CloseableIterator<Object>() {
@Override
public boolean hasNext() {
return false;
}
@Override
protected Object doNext() {
// never called anyway
throw new NoSuchElementException("Empty closeable Iterator has no element");
}
@Override
protected void doClose() {
// do nothing
}
};
@SuppressWarnings("unchecked")
public static <T> CloseableIterator<T> emptyCloseableIterator() {
return (CloseableIterator<T>) EMPTY_CLOSEABLE_ITERATOR;
}
/**
* Creates a CloseableIterator from a regular {@link Iterator}.
*
* @throws IllegalArgumentException if the specified {@link Iterator} is a CloseableIterator
*/
public static <T> CloseableIterator<T> from(Iterator<T> iterator) {
// early fail
requireNonNull(iterator);
checkArgument(!(iterator instanceof AutoCloseable), "This method does not support creating a CloseableIterator from an Iterator which is Closeable");
return new RegularIteratorWrapper<>(iterator);
}
/**
* Wraps a {@code CloseableIterator} and optionally other instances of {@code AutoCloseable} that must be closed
* at the same time. The wrapped iterator is closed first then the other {@code AutoCloseable} in the defined order.
*
* @throws IllegalArgumentException if the parameter {@code otherCloseables} contains the wrapped iterator
*/
public static <T> CloseableIterator<T> wrap(CloseableIterator<T> iterator, AutoCloseable... otherCloseables) {
return new CloseablesIteratorWrapper<>(iterator, otherCloseables);
}
@Override
public boolean hasNext() {
// Optimization to not call bufferNext() when already closed
if (isClosed) {
return false;
}
boolean hasNext = nextObject != null || bufferNext() != null;
if (!hasNext) {
close();
}
return hasNext;
}
private O bufferNext() {
try {
nextObject = doNext();
return nextObject;
} catch (RuntimeException e) {
close();
throw e;
}
}
/**
* Reads next item and returns {@code null} if no more items.
*/
@CheckForNull
protected abstract O doNext();
@Override
public O next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
O result = nextObject;
nextObject = null;
return result;
}
@Override
public final void remove() {
try {
doRemove();
} catch (RuntimeException e) {
close();
throw e;
}
}
/**
* By default it throws an UnsupportedOperationException. Override this method
* to change behavior.
*/
protected void doRemove() {
throw new UnsupportedOperationException("remove() is not supported by default. Override doRemove() if needed.");
}
/**
* Do not declare "throws IOException"
*/
@Override
public final void close() {
try {
doClose();
isClosed = true;
} catch (Exception e) {
Throwables.propagate(e);
}
}
protected abstract void doClose() throws Exception;
private static class RegularIteratorWrapper<T> extends CloseableIterator<T> {
private final Iterator<T> iterator;
public RegularIteratorWrapper(Iterator<T> iterator) {
this.iterator = iterator;
}
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public T next() {
return iterator.next();
}
@Override
protected T doNext() {
throw new UnsupportedOperationException("hasNext has been override, doNext is never called");
}
@Override
protected void doClose() {
// do nothing
}
}
private static class CloseablesIteratorWrapper<T> extends CloseableIterator<T> {
private final CloseableIterator<T> iterator;
private final List<AutoCloseable> otherCloseables;
private CloseablesIteratorWrapper(CloseableIterator<T> iterator, AutoCloseable... otherCloseables) {
requireNonNull(iterator);
checkArgument(!ArrayUtils.contains(otherCloseables, iterator));
this.iterator = iterator;
// the advantage of using ImmutableList is that it does not accept null elements, so it fails fast, during
// construction of the wrapper, but not in close()
this.otherCloseables = ImmutableList.copyOf(otherCloseables);
}
@Override
protected T doNext() {
return iterator.hasNext() ? iterator.next() : null;
}
@Override
protected void doClose() throws Exception {
// iterator can be already closed by doNext(), but closing here ensures
// that iterator is closed when it is not fully traversed.
iterator.close();
for (AutoCloseable otherCloseable : otherCloseables) {
otherCloseable.close();
}
}
}
}
| 6,195 | 28.364929 | 153 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/ContextException.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import com.google.common.base.Joiner;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import java.util.Iterator;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
/**
* A runtime exception that provides contextual information as a list of key-value
* pairs. This information is added to the message and stack trace.
* <p>
* Example:
* <pre>
* try {
*
* } catch (Exception e) {
* throw ContextException.of("Unable to assign issue", e)
* .addContext("projectUuid", "P1")
* .addContext("issueUuid", "I1")
* .addContext("login", "felix");
* }
* </pre>
* </p>
* <p>
* Contexts of nested {@link ContextException}s are merged:
* <pre>
* try {
* throw ContextException.of("Something wrong").addContext("login", "josette");
* } catch (Exception e) {
* throw ContextException.of("Unable to assign issue", e)
* .addContext("issueUuid", "I1")
* .addContext("login", "felix");
* }
* </pre>
* </p>
* <p>
* The generated message, usually written to a log with stack trace, looks like:
* <pre>
* Unable to assign issue | issueUuid=I1 | login=[josette,felix]
* </pre>
* </p>
*/
public class ContextException extends RuntimeException {
private static final Joiner COMMA_JOINER = Joiner.on(',');
// LinkedListMultimap is used to keep order of keys and values
private final transient ListMultimap<String, Object> context = LinkedListMultimap.create();
private ContextException(Throwable t) {
super(t);
}
private ContextException(String message, Throwable t) {
super(message, t);
}
private ContextException(String message) {
super(message);
}
private ContextException addContext(ContextException e) {
this.context.putAll(e.context);
return this;
}
public ContextException addContext(String key, @Nullable Object value) {
context.put(key, value);
return this;
}
public ContextException clearContext(String key) {
context.removeAll(key);
return this;
}
public ContextException setContext(String key, @Nullable Object value) {
clearContext(key);
return addContext(key, value);
}
/**
* Returns the values associated with {@code key}, if any, else returns an
* empty list.
*/
public List<Object> getContext(String key) {
return context.get(key);
}
public static ContextException of(Throwable t) {
if (t instanceof ContextException) {
return new ContextException(t.getCause()).addContext((ContextException) t);
}
return new ContextException(t);
}
public static ContextException of(String message, Throwable t) {
if (t instanceof ContextException) {
return new ContextException(message, t.getCause()).addContext((ContextException) t);
}
return new ContextException(message, t);
}
public static ContextException of(String message) {
return new ContextException(message);
}
@Override
@Nonnull
public String getMessage() {
return format(super.getMessage());
}
/**
* Provides the message explaining the exception without the contextual data.
*/
@CheckForNull
public String getRawMessage() {
return super.getMessage();
}
private String format(@Nullable String baseMessage) {
StringBuilder sb = new StringBuilder();
Iterator<String> keyIt = context.keySet().iterator();
if (StringUtils.isNotBlank(baseMessage)) {
sb.append(baseMessage);
if (keyIt.hasNext()) {
sb.append(" | ");
}
}
while (keyIt.hasNext()) {
String key = keyIt.next();
sb.append(key).append("=");
List<Object> values = getContext(key);
if (values.size() > 1) {
sb.append("[").append(COMMA_JOINER.join(values)).append("]");
} else if (values.size() == 1) {
sb.append(values.get(0));
}
if (keyIt.hasNext()) {
sb.append(" | ");
}
}
return sb.toString();
}
}
| 4,950 | 27.953216 | 93 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/DefaultHttpDownloader.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import com.google.common.io.ByteStreams;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.inject.Inject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.io.IOUtils;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Configuration;
import org.sonar.api.platform.Server;
import org.sonar.api.utils.HttpDownloader;
import org.sonar.api.utils.SonarException;
import org.sonarqube.ws.client.OkHttpClientBuilder;
import static org.apache.commons.io.FileUtils.copyInputStreamToFile;
import static org.sonar.core.util.FileUtils.deleteQuietly;
/**
* This component downloads HTTP files
*
* @since 2.2
*/
public class DefaultHttpDownloader extends HttpDownloader {
private final OkHttpClient client;
@Inject
public DefaultHttpDownloader(Server server, Configuration config) {
this(server, config, null, null);
}
public DefaultHttpDownloader(Server server, Configuration config, @Nullable Integer connectTimeout, @Nullable Integer readTimeout) {
client = buildHttpClient(server, config, connectTimeout, readTimeout);
}
private static OkHttpClient buildHttpClient(Server server, Configuration config, @Nullable Integer connectTimeout,
@Nullable Integer readTimeout) {
OkHttpClientBuilder clientBuilder = new OkHttpClientBuilder()
.setFollowRedirects(true)
.setUserAgent(getUserAgent(server, config));
if (connectTimeout != null) {
clientBuilder
.setConnectTimeoutMs(connectTimeout);
}
if (readTimeout != null) {
clientBuilder
.setReadTimeoutMs(readTimeout);
}
return clientBuilder.build();
}
private static String getUserAgent(Server server, Configuration config) {
Optional<String> serverId = config.get(CoreProperties.SERVER_ID);
if (serverId.isEmpty()) {
return String.format("SonarQube %s #", server.getVersion());
}
return String.format("SonarQube %s # %s", server.getVersion(), serverId.get());
}
@Override
protected String description(URI uri) {
return uri.toString();
}
@Override
protected String[] getSupportedSchemes() {
return new String[] {"http", "https"};
}
@Override
protected byte[] readBytes(URI uri) {
return download(uri);
}
@Override
protected String readString(URI uri, Charset charset) {
try (Response response = executeCall(uri)) {
return IOUtils.toString(response.body().byteStream(), charset);
} catch (IOException e) {
throw failToDownload(uri, e);
}
}
@Override
public String downloadPlainText(URI uri, String encoding) {
return readString(uri, Charset.forName(encoding));
}
@Override
public byte[] download(URI uri) {
try (Response response = executeCall(uri)) {
return ByteStreams.toByteArray(response.body().byteStream());
} catch (IOException e) {
throw failToDownload(uri, e);
}
}
@Override
public InputStream openStream(URI uri) {
try {
Response response = executeCall(uri);
return response.body().byteStream();
} catch (IOException e) {
throw failToDownload(uri, e);
}
}
@Override
public void download(URI uri, File toFile) {
try (Response response = executeCall(uri)) {
copyInputStreamToFile(response.body().byteStream(), toFile);
} catch (IOException e) {
deleteQuietly(toFile);
throw failToDownload(uri, e);
}
}
private Response executeCall(URI uri) throws IOException {
Request request = new Request.Builder().url(uri.toURL()).get().build();
return client.newCall(request).execute();
}
private static SonarException failToDownload(URI uri, IOException e) {
throw new SonarException(String.format("Fail to download: %s", uri), e);
}
}
| 4,791 | 29.916129 | 134 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/FileUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.EnumSet;
import java.util.Locale;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
/**
* This utility class provides Java NIO based replacement for some methods of
* {@link org.apache.commons.io.FileUtils Common IO FileUtils} class.
*/
public final class FileUtils {
private static final String DIRECTORY_CAN_NOT_BE_NULL = "Directory can not be null";
private static final EnumSet<FileVisitOption> FOLLOW_LINKS = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
private FileUtils() {
// prevents instantiation
}
/**
* Deletes a directory recursively.
*
* @param directory directory to delete
* @throws IOException in case deletion is unsuccessful
*/
public static void deleteDirectory(File directory) throws IOException {
requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL);
deleteDirectoryImpl(directory.toPath());
}
/**
* Deletes a directory recursively.
*
* @param directory directory to delete
* @throws IOException in case deletion is unsuccessful
*/
public static void deleteDirectory(Path directory) throws IOException {
requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL);
deleteDirectoryImpl(directory);
}
/**
* Cleans a directory recursively.
*
* @param directory directory to delete
* @throws IOException in case deletion is unsuccessful
*/
public static void cleanDirectory(File directory) throws IOException {
requireNonNull(directory, DIRECTORY_CAN_NOT_BE_NULL);
Path path = directory.toPath();
if (!path.toFile().exists()) {
return;
}
cleanDirectoryImpl(path);
}
/**
* Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
* <p>
* The difference between File.delete() and this method are:
* <ul>
* <li>A directory to be deleted does not have to be empty.</li>
* <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
* </ul>
*
* @param file file or directory to delete, can be {@code null}
* @return {@code true} if the file or directory was deleted, otherwise {@code false}
*/
public static boolean deleteQuietly(@Nullable File file) {
if (file == null) {
return false;
}
return deleteQuietly(file.toPath());
}
/**
* Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
* <p>
* The difference between File.delete() and this method are:
* <ul>
* <li>A directory to be deleted does not have to be empty.</li>
* <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
* </ul>
*
* @param path file or directory to delete, can be {@code null}
* @return {@code true} if the file or directory was deleted, otherwise {@code false}
*/
public static boolean deleteQuietly(@Nullable Path path) {
if (path == null) {
return false;
}
try {
if (path.toFile().isDirectory()) {
deleteDirectory(path);
} else {
Files.delete(path);
}
return true;
} catch (IOException | SecurityException ignored) {
return false;
}
}
private static void checkIO(boolean condition, String pattern, Object... arguments) throws IOException {
if (!condition) {
throw new IOException(format(pattern, arguments));
}
}
private static void cleanDirectoryImpl(Path path) throws IOException {
checkArgument(path.toFile().isDirectory(), "'%s' is not a directory", path);
Files.walkFileTree(path, FOLLOW_LINKS, CleanDirectoryFileVisitor.VISIT_MAX_DEPTH, new CleanDirectoryFileVisitor(path));
}
private static void deleteDirectoryImpl(Path path) throws IOException {
requireNonNull(path, DIRECTORY_CAN_NOT_BE_NULL);
File file = path.toFile();
if (!file.exists()) {
return;
}
checkIO(!Files.isSymbolicLink(path), "Directory '%s' is a symbolic link", path);
checkIO(!file.isFile(), "Directory '%s' is a file", path);
Files.walkFileTree(path, DeleteRecursivelyFileVisitor.INSTANCE);
checkIO(!file.exists(), "Unable to delete directory '%s'", path);
}
/**
* Replaces the use of Apache Commons FileUtils #byteCountToDisplaySize (see SONAR-14917)
* @param bytes number of bytes
* @return human readable byte count, with 1 decimal place
*/
public static String humanReadableByteCountSI(long bytes) {
if (-1000 < bytes && bytes < 1000) {
if (bytes == 1) {
return bytes + " byte";
}
return bytes + " bytes";
}
CharacterIterator ci = new StringCharacterIterator("kMGTPE");
while (bytes <= -999_950 || bytes >= 999_950) {
bytes /= 1000;
ci.next();
}
return String.format(Locale.ENGLISH, "%.1f %cB", bytes / 1000.0, ci.current());
}
/**
* This visitor is intended to be used to visit direct children of directory <strong>or a symLink to a directory</strong>,
* so, with a max depth of {@link #VISIT_MAX_DEPTH 1}. Each direct children will either be directly deleted (if file)
* or recursively deleted (if directory).
*/
private static class CleanDirectoryFileVisitor extends SimpleFileVisitor<Path> {
private static final int VISIT_MAX_DEPTH = 1;
private final Path path;
private final boolean symLink;
private CleanDirectoryFileVisitor(Path path) {
this.path = path;
this.symLink = Files.isSymbolicLink(path);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (file.toFile().isDirectory()) {
deleteDirectoryImpl(file);
} else if (!symLink || !file.equals(path)) {
Files.delete(file);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (!dir.equals(path)) {
deleteDirectoryImpl(dir);
}
return FileVisitResult.CONTINUE;
}
}
private static final class DeleteRecursivelyFileVisitor extends SimpleFileVisitor<Path> {
public static final DeleteRecursivelyFileVisitor INSTANCE = new DeleteRecursivelyFileVisitor();
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
}
}
| 7,910 | 32.100418 | 124 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/LineReaderIterator.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
/**
* Read lines from a {@link Reader}
* @see BufferedReader
*/
public class LineReaderIterator extends CloseableIterator<String> {
private final BufferedReader reader;
public LineReaderIterator(Reader reader) {
if (reader instanceof BufferedReader) {
this.reader = (BufferedReader) reader;
} else {
this.reader = new BufferedReader(reader);
}
}
@Override
protected String doNext() {
try {
return reader.readLine();
} catch (IOException e) {
throw new IllegalStateException("Fail to read line", e);
}
}
@Override
protected void doClose() throws IOException {
reader.close();
}
}
| 1,612 | 27.803571 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/MacAddressProvider.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import com.google.common.annotations.VisibleForTesting;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.SecureRandom;
import java.util.Enumeration;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Used by {@link UuidFactoryImpl}. Heavily inspired by https://github.com/elastic/elasticsearch/blob/master/core/src/main/java/org/elasticsearch/common/MacAddressProvider.java
*/
class MacAddressProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(MacAddressProvider.class);
public static final int BYTE_SIZE = 6;
private MacAddressProvider() {
// only static stuff
}
public static byte[] getSecureMungedAddress() {
byte[] address = null;
try {
address = getMacAddress();
} catch (SocketException se) {
LOGGER.warn("Unable to get mac address, will use a dummy address", se);
// address will be set below
}
if (!isValidAddress(address)) {
LOGGER.warn("Unable to get a valid mac address, will use a dummy address");
address = constructDummyMulticastAddress();
}
byte[] mungedBytes = new byte[BYTE_SIZE];
new SecureRandom().nextBytes(mungedBytes);
for (int i = 0; i < BYTE_SIZE; ++i) {
mungedBytes[i] ^= address[i];
}
return mungedBytes;
}
private static boolean isValidAddress(@Nullable byte[] address) {
if (address == null || address.length != BYTE_SIZE) {
return false;
}
for (byte b : address) {
if (b != 0x00) {
// If any of the bytes are non zero assume a good address
return true;
}
}
return false;
}
@CheckForNull
private static byte[] getMacAddress() throws SocketException {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
if (en != null) {
while (en.hasMoreElements()) {
NetworkInterface nint = en.nextElement();
if (!nint.isLoopback()) {
// Pick the first valid non loopback address we find
byte[] address = nint.getHardwareAddress();
if (isValidAddress(address)) {
return address;
}
}
}
}
// Could not find a mac address
return null;
}
@VisibleForTesting
static byte[] constructDummyMulticastAddress() {
byte[] dummy = new byte[BYTE_SIZE];
new SecureRandom().nextBytes(dummy);
// Set the broadcast bit to indicate this is not a _real_ mac address
dummy[0] |= (byte) 0x01;
return dummy;
}
}
| 3,449 | 30.651376 | 176 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/NonNullInputFunction.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import com.google.common.base.Function;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Guava Function that does not accept null input elements
* @since 5.1
*/
public abstract class NonNullInputFunction<F, T> implements Function<F, T> {
@Override
public final T apply(@Nullable F input) {
checkArgument(input != null, "Null inputs are not allowed in this function");
return doApply(input);
}
/**
* This method is the same as {@link #apply(Object)} except that the input argument
* is not marked as nullable
*/
protected abstract T doApply(F input);
}
| 1,516 | 32.711111 | 85 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/ParamChange.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.io.Serializable;
public class ParamChange implements Serializable {
String key;
String value;
public ParamChange(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public String getValue() {
return value;
}
}
| 1,184 | 27.902439 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/ProgressLogger.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Background thread that logs the state of a counter at fixed intervals.
*/
public class ProgressLogger {
public static final long DEFAULT_PERIOD_MS = 60_000L;
private final Timer timer;
private final LoggerTimerTask task;
private long periodMs = DEFAULT_PERIOD_MS;
public ProgressLogger(String threadName, AtomicLong counter, Logger logger) {
this.timer = new Timer(threadName);
this.task = new LoggerTimerTask(counter, logger);
}
public static ProgressLogger create(Class clazz, AtomicLong counter) {
String threadName = String.format("ProgressLogger[%s]", clazz.getSimpleName());
Logger logger = LoggerFactory.getLogger(clazz);
return new ProgressLogger(threadName, counter, logger);
}
/**
* Warning, does not check if already started.
*/
public void start() {
// first log after {periodMs} milliseconds
timer.schedule(task, periodMs, periodMs);
}
public void stop() {
timer.cancel();
timer.purge();
}
/**
* Default is 1 minute
*/
public ProgressLogger setPeriodMs(long l) {
this.periodMs = l;
return this;
}
public long getPeriodMs() {
return periodMs;
}
/**
* For example "issues", "measures", ... Default is "rows".
*/
public ProgressLogger setPluralLabel(String s) {
task.pluralLabel = s;
return this;
}
public String getPluralLabel() {
return task.pluralLabel;
}
public void log() {
task.log();
}
private class LoggerTimerTask extends TimerTask {
private final AtomicLong counter;
private final Logger logger;
private String pluralLabel = "rows";
private long previousCounter = 0L;
private LoggerTimerTask(AtomicLong counter, Logger logger) {
this.counter = counter;
this.logger = logger;
}
@Override
public void run() {
log();
}
private void log() {
long current = counter.get();
logger.info(String.format("%d %s processed (%d items/sec)", current, pluralLabel, 1000 * (current - previousCounter) / periodMs));
previousCounter = current;
}
}
}
| 3,120 | 26.377193 | 136 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/Protobuf.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.Parser;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.IOUtils;
/**
* Utility to read and write Protocol Buffers messages
*/
public class Protobuf {
private Protobuf() {
// only static stuff
}
/**
* Returns the message contained in {@code file}. Throws an unchecked exception
* if the file does not exist, is empty or does not contain message with the
* expected type.
*/
public static <MSG extends Message> MSG read(File file, Parser<MSG> parser) {
InputStream input = null;
try {
input = new BufferedInputStream(new FileInputStream(file));
return parser.parseFrom(input);
} catch (Exception e) {
throw ContextException.of("Unable to read message", e).addContext("file", file);
} finally {
IOUtils.closeQuietly(input);
}
}
public static <MSG extends Message> MSG read(InputStream input, Parser<MSG> parser) {
try {
return parser.parseFrom(input);
} catch (Exception e) {
throw ContextException.of("Unable to read message", e);
} finally {
IOUtils.closeQuietly(input);
}
}
/**
* Writes a single message to {@code file}. Existing content is replaced, the message is not
* appended.
*/
public static void write(Message message, File toFile) {
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(toFile, false));
message.writeTo(out);
} catch (Exception e) {
throw ContextException.of("Unable to write message", e).addContext("file", toFile);
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* Writes a single message to {@code file}, compressed with gzip. Existing content is replaced, the message is not
* appended.
*/
public static void writeGzip(Message message, File toFile) {
OutputStream out = null;
try {
out = new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(toFile, false)));
message.writeTo(out);
} catch (Exception e) {
throw ContextException.of("Unable to write message", e).addContext("file", toFile);
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* Streams multiple messages to {@code file}. Reading the messages back requires to
* call methods {@code readStream(...)}.
* <p>
* See https://developers.google.com/protocol-buffers/docs/techniques#streaming
* </p>
*/
public static <MSG extends Message> void writeStream(Iterable<MSG> messages, File toFile, boolean append) {
OutputStream out = null;
try {
out = new BufferedOutputStream(new FileOutputStream(toFile, append));
writeStream(messages, out);
} catch (Exception e) {
throw ContextException.of("Unable to write messages", e).addContext("file", toFile);
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* Streams multiple messages to {@code output}. Reading the messages back requires to
* call methods {@code readStream(...)}.
* <p>
* See https://developers.google.com/protocol-buffers/docs/techniques#streaming
* </p>
*/
public static <MSG extends Message> void writeStream(Iterable<MSG> messages, OutputStream output) {
try {
for (Message message : messages) {
message.writeDelimitedTo(output);
}
} catch (Exception e) {
throw ContextException.of("Unable to write messages", e);
}
}
/**
* Reads a stream of messages. This method returns an empty iterator if there are no messages. An
* exception is raised on IO error, if file does not exist or if messages have a different type than {@code parser}.
*/
public static <MSG extends Message> CloseableIterator<MSG> readStream(File file, Parser<MSG> parser) {
try {
// the input stream is closed by the CloseableIterator
BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
return readStream(input, parser);
} catch (Exception e) {
throw ContextException.of("Unable to read messages", e).addContext("file", file);
}
}
/**
* Reads a stream of messages from a gzip file. This method returns an empty iterator if there are no messages. An
* exception is raised on IO error, if file does not exist or if messages have a different type than {@code parser}.
*/
public static <MSG extends Message> CloseableIterator<MSG> readGzipStream(File file, Parser<MSG> parser) {
try {
// the input stream is closed by the CloseableIterator
InputStream input = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file)));
return readStream(input, parser);
} catch (Exception e) {
throw ContextException.of("Unable to read messages", e).addContext("file", file);
}
}
/**
* Reads a stream of messages. This method returns an empty iterator if there are no messages. An
* exception is raised on IO error or if messages have a different type than {@code parser}.
* <p>
* The stream is not closed by this method. It is closed when {@link CloseableIterator} traverses
* all messages or when {@link CloseableIterator#close()} is called.
* </p>
*/
public static <MSG extends Message> CloseableIterator<MSG> readStream(InputStream input, Parser<MSG> parser) {
// the stream is closed by the CloseableIterator
return new StreamIterator<>(parser, input);
}
private static class StreamIterator<MSG extends Message> extends CloseableIterator<MSG> {
private final Parser<MSG> parser;
private final InputStream input;
private StreamIterator(Parser<MSG> parser, InputStream input) {
this.parser = parser;
this.input = input;
}
@Override
protected MSG doNext() {
try {
return parser.parsePartialDelimitedFrom(input);
} catch (InvalidProtocolBufferException e) {
throw ContextException.of(e);
}
}
@Override
protected void doClose() {
IOUtils.closeQuietly(input);
}
}
}
| 7,211 | 34.352941 | 118 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/ProtobufJsonFormat.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import com.google.protobuf.Descriptors;
import com.google.protobuf.MapEntry;
import com.google.protobuf.Message;
import java.io.StringWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.sonar.api.utils.text.JsonWriter;
/**
* Converts a Protocol Buffers message to JSON. Unknown fields, binary fields and groups
* are not supported. Absent fields are ignored, so it's possible to distinguish
* null strings (field is absent) and empty strings (field is present with value {@code ""}).
*
* <h3>Example</h3>
* <pre>
* // protobuf specification
* message Foo {
* string name = 1;
* int32 count = 2;
* repeated string colors = 3;
* }
*
* // generated JSON
* {
* "name": "hello",
* "count": 32,
* "colors": ["blue", "red"]
* }
* </pre>
*
* <h3>Absent versus empty arrays</h3>
* <p>
* Protobuf does not support absent repeated field. The default value is empty. A pattern
* is defined by {@link ProtobufJsonFormat} to support the difference between absent and
* empty arrays when generating JSON. An intermediary message wrapping the array must be defined.
* It is automatically inlined and does not appear in the generated JSON. This wrapper message must:
* </p>
* <ul>
* <li>contain a single repeated field</li>
* <li>has the same name (case-insensitive) as the field</li>
* </ul>
*
*
* <p>Example:</p>
* <pre>
* // protobuf specification
* message Continent {
* string name = 1;
* Countries countries = 2;
* }
*
* // the message name ("Countries") is the same as the field 1 ("countries")
* message Countries {
* repeated string countries = 1;
* }
*
* // example of generated JSON if field 2 is not present
* {
* "name": "Europe",
* }
*
* // example of generated JSON if field 2 is present but inner array is empty.
* // The intermediary "countries" message is inline.
* {
* "name": "Europe",
* "countries": []
* }
*
* // example of generated JSON if field 2 is present and inner array is not empty
* // The intermediary "countries" message is inline.
* {
* "name": "Europe",
* "countries": ["Spain", "Denmark"]
* }
* </pre>
*
* <h3>Array or map in map values</h3>
* <p>
* Map fields cannot be repeated. Values are scalar types or messages, but not arrays nor maps. In order
* to support multimaps (maps of lists) and maps of maps in JSON, the same pattern as for absent arrays
* can be used:
* </p>
* <p>Example:</p>
* <pre>
* // protobuf specification
* message Continent {
* string name = 1;
* map<string,Countries> countries_by_currency = 2;
* }
*
* // the message name ("Countries") is the same as the field 1 ("countries")
* message Countries {
* repeated string countries = 1;
* }
*
* // example of generated JSON. The intermediary "countries" message is inline.
* {
* "name": "Europe",
* "countries_by_currency": {
* "eur": ["Spain", "France"],
* "dkk": ["Denmark"]
* }
* }
* </pre>
*/
public class ProtobufJsonFormat {
private ProtobufJsonFormat() {
// only statics
}
static class MessageType {
private static final Map<Class<? extends Message>, MessageType> TYPES_BY_CLASS = new HashMap<>();
private final Descriptors.FieldDescriptor[] fieldDescriptors;
private final boolean doesWrapRepeated;
private MessageType(Descriptors.Descriptor descriptor) {
this.fieldDescriptors = descriptor.getFields().toArray(new Descriptors.FieldDescriptor[descriptor.getFields().size()]);
this.doesWrapRepeated = fieldDescriptors.length == 1 && fieldDescriptors[0].isRepeated() && descriptor.getName().equalsIgnoreCase(fieldDescriptors[0].getName());
}
static MessageType of(Message message) {
MessageType type = TYPES_BY_CLASS.get(message.getClass());
if (type == null) {
type = new MessageType(message.getDescriptorForType());
TYPES_BY_CLASS.put(message.getClass(), type);
}
return type;
}
}
public static void write(Message message, JsonWriter writer) {
writer.setSerializeNulls(false).setSerializeEmptys(true);
writer.beginObject();
writeMessage(message, writer);
writer.endObject();
}
public static String toJson(Message message) {
StringWriter json = new StringWriter();
try (JsonWriter jsonWriter = JsonWriter.of(json)) {
write(message, jsonWriter);
}
return json.toString();
}
private static void writeMessage(Message message, JsonWriter writer) {
MessageType type = MessageType.of(message);
for (Descriptors.FieldDescriptor fieldDescriptor : type.fieldDescriptors) {
if (fieldDescriptor.isRepeated()) {
writer.name(fieldDescriptor.getName());
if (fieldDescriptor.isMapField()) {
writeMap((Collection<MapEntry>) message.getField(fieldDescriptor), writer);
} else {
writeArray(writer, fieldDescriptor, (Collection) message.getField(fieldDescriptor));
}
} else if (message.hasField(fieldDescriptor)) {
writer.name(fieldDescriptor.getName());
Object fieldValue = message.getField(fieldDescriptor);
writeFieldValue(fieldDescriptor, fieldValue, writer);
}
}
}
private static void writeArray(JsonWriter writer, Descriptors.FieldDescriptor fieldDescriptor, Collection array) {
writer.beginArray();
for (Object o : array) {
writeFieldValue(fieldDescriptor, o, writer);
}
writer.endArray();
}
private static void writeMap(Collection<MapEntry> mapEntries, JsonWriter writer) {
writer.beginObject();
for (MapEntry mapEntry : mapEntries) {
// Key fields are always double-quoted in json
writer.name(mapEntry.getKey().toString());
Descriptors.FieldDescriptor valueDescriptor = mapEntry.getDescriptorForType().findFieldByName("value");
writeFieldValue(valueDescriptor, mapEntry.getValue(), writer);
}
writer.endObject();
}
private static void writeFieldValue(Descriptors.FieldDescriptor fieldDescriptor, Object value, JsonWriter writer) {
switch (fieldDescriptor.getJavaType()) {
case INT:
writer.value((Integer) value);
break;
case LONG:
writer.value((Long) value);
break;
case DOUBLE:
writer.value((Double) value);
break;
case BOOLEAN:
writer.value((Boolean) value);
break;
case STRING:
writer.value((String) value);
break;
case ENUM:
writer.value(((Descriptors.EnumValueDescriptor) value).getName());
break;
case MESSAGE:
writeMessageValue((Message) value, writer);
break;
default:
throw new IllegalStateException(String.format("JSON format does not support type '%s' of field '%s'", fieldDescriptor.getJavaType(), fieldDescriptor.getName()));
}
}
private static void writeMessageValue(Message message, JsonWriter writer) {
MessageType messageType = MessageType.of(message);
if (messageType.doesWrapRepeated) {
Descriptors.FieldDescriptor repeatedDescriptor = messageType.fieldDescriptors[0];
if (repeatedDescriptor.isMapField()) {
writeMap((Collection<MapEntry>) message.getField(repeatedDescriptor), writer);
} else {
writeArray(writer, repeatedDescriptor, (Collection) message.getField(repeatedDescriptor));
}
} else {
writer.beginObject();
writeMessage(message, writer);
writer.endObject();
}
}
}
| 8,456 | 32.693227 | 169 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/SequenceUuidFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Only for tests. This implementation of {@link UuidFactory} generates
* ids as a sequence of integers ("1", "2", ...). It starts with "1".
*/
public class SequenceUuidFactory implements UuidFactory {
private final AtomicInteger id = new AtomicInteger(1);
@Override
public String create() {
return String.valueOf(id.getAndIncrement());
}
}
| 1,285 | 33.756757 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/SettingFormatter.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.util.Locale;
import org.apache.commons.lang.StringUtils;
import static org.apache.commons.lang.StringUtils.trim;
public final class SettingFormatter {
private SettingFormatter() {
// util class
}
public static String fromJavaPropertyToEnvVariable(String property) {
return property.toUpperCase(Locale.ENGLISH).replace('.', '_').replace('-', '_');
}
/**
* Value is split and trimmed.
*/
public static String[] getStringArrayBySeparator(String value, String separator) {
String[] strings = StringUtils.splitByWholeSeparator(value, separator);
String[] result = new String[strings.length];
for (int index = 0; index < strings.length; index++) {
result[index] = trim(strings[index]);
}
return result;
}
}
| 1,644 | 33.270833 | 84 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/Slug.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.text.Normalizer;
import java.util.Locale;
import java.util.regex.Pattern;
public class Slug {
private static final String DASH = "-";
private static final Pattern NON_ASCII_CHARS = Pattern.compile("[^\\p{ASCII}]");
private static final Pattern NON_WORD_CHARS = Pattern.compile("[^\\w+]");
private static final Pattern WHITESPACES_CHARS = Pattern.compile("\\s+");
private static final Pattern DASHES_IN_ROWS = Pattern.compile("[-]+");
private String in;
private Slug(String in) {
this.in = in;
}
public static String slugify(String s) {
Slug slug = new Slug(s);
return slug
.normalize()
.removeNonAsciiChars()
.dashifyNonWordChars()
.dashifyWhitespaceChars()
.collapseDashes()
.removeHeadingDash()
.removeTrailingDash()
.toLowerCase();
}
private Slug normalize() {
this.in = Normalizer.normalize(in, Normalizer.Form.NFD);
return this;
}
private Slug removeNonAsciiChars() {
this.in = removeAll(NON_ASCII_CHARS, in);
return this;
}
private Slug dashifyNonWordChars() {
this.in = dashify(NON_WORD_CHARS, in);
return this;
}
private Slug dashifyWhitespaceChars() {
this.in = dashify(WHITESPACES_CHARS, in);
return this;
}
private Slug collapseDashes() {
this.in = dashify(DASHES_IN_ROWS, in);
return this;
}
private Slug removeHeadingDash() {
if (this.in.startsWith(DASH)) {
this.in = this.in.substring(1);
}
return this;
}
private Slug removeTrailingDash() {
if (this.in.endsWith(DASH)) {
this.in = this.in.substring(0, this.in.length() - 1);
}
return this;
}
private String toLowerCase() {
return in.toLowerCase(Locale.ENGLISH);
}
private static String removeAll(Pattern pattern, String in) {
return replaceAll(pattern, in, "");
}
private static String dashify(Pattern pattern, String in) {
return replaceAll(pattern, in, DASH);
}
private static String replaceAll(Pattern pattern, String str, String replacement) {
return pattern.matcher(str).replaceAll(replacement);
}
}
| 2,986 | 26.915888 | 85 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/UtcDateUtils.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import org.sonar.api.utils.DateUtils;
public class UtcDateUtils {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateUtils.DATETIME_FORMAT).withZone(ZoneOffset.UTC);
private UtcDateUtils() {
// only static stuff
}
public static String formatDateTime(Date date) {
return formatter.format(date.toInstant());
}
public static Date parseDateTime(String s) {
try {
return Date.from(OffsetDateTime.parse(s, formatter).toInstant());
} catch (DateTimeParseException e) {
throw new IllegalArgumentException("Fail to parse date: " + s, e);
}
}
}
| 1,667 | 33.040816 | 133 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/UuidFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
public interface UuidFactory {
/**
* Create a universally unique identifier. Underlying algorithm, so format and max length,
* can vary over SonarQube versions.
* <p/>
* UUID is a base64 ASCII encoded string and is URL-safe. It does not contain - and + characters
* but only letters, digits, dash (-) and underscore (_). Length can vary but does
* not exceed {@link Uuids#MAX_LENGTH} characters (arbitrary value).
*/
String create();
}
| 1,336 | 37.2 | 98 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/UuidFactoryFast.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.security.SecureRandom;
/**
* NOT thread safe
* About 10x faster than {@link UuidFactoryImpl}
* It does not take into account the MAC address to calculate the ids, so it is machine-independent.
*/
public class UuidFactoryFast implements UuidFactory {
private static UuidFactoryFast instance = new UuidFactoryFast();
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private static int sequenceNumber = new SecureRandom().nextInt();
private UuidFactoryFast() {
//
}
@Override
public String create() {
long timestamp = System.currentTimeMillis();
byte[] uuidBytes = new byte[9];
// Only use lower 6 bytes of the timestamp (this will suffice beyond the year 10000):
putLong(uuidBytes, timestamp, 0, 6);
// Sequence number adds 3 bytes:
putLong(uuidBytes, getSequenceNumber(), 6, 3);
return byteArrayToHex(uuidBytes);
}
public static UuidFactoryFast getInstance() {
return instance;
}
private static int getSequenceNumber() {
return sequenceNumber++;
}
/** Puts the lower numberOfLongBytes from l into the array, starting index pos. */
private static void putLong(byte[] array, long l, int pos, int numberOfLongBytes) {
for (int i = 0; i < numberOfLongBytes; ++i) {
array[pos + numberOfLongBytes - i - 1] = (byte) (l >>> (i * 8));
}
}
public static String byteArrayToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
}
| 2,559 | 31.405063 | 100 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/UuidFactoryImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import org.apache.commons.codec.binary.Base64;
/**
*/
public enum UuidFactoryImpl implements UuidFactory {
/**
* Should be removed as long {@link Uuids} is not used anymore. {@code UuidFactoryImpl}
* should be injected by the ioc container through a public constructor.
*/
INSTANCE;
private final UuidGenerator uuidGenerator = new UuidGeneratorImpl();
@Override
public String create() {
return Base64.encodeBase64URLSafeString(uuidGenerator.generate());
}
}
| 1,362 | 31.452381 | 89 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/UuidGenerator.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
/**
* A generator of UUID as a byte array which is made of two parts:
* <ul>
* <li>a base, which is machine and time dependant and therefor will change with time</li>
* <li>an increment</li>
* </ul>
*
* <p>
* This generator can be used in two ways:
* <ul>
* <li>either the base and the increment are changed for each UUID (with time for the base, with each call to
* {@link #generate()} for the increment) and {@link #generate()} should be used</li>
* <li>or the increment can be the only changing part (for performance boost and less concurrency) and
* {@link #withFixedBase()} should be used.</li>
* </ul>
* </p>
*
* <p>
* <strong>Warning:</strong> {@link WithFixedBase#generate(int)} can be considerably faster than {@link #generate()} but
* is limited to generate only 2^23-1 unique values.
* </p>
*
* <p>
* Heavily inspired from Elasticsearch {@code TimeBasedUUIDGenerator}, which could be directly
* used the day {@code UuidFactoryImpl} is moved outside module sonar-core.
* See https://github.com/elastic/elasticsearch/blob/master/core/src/main/java/org/elasticsearch/common/TimeBasedUUIDGenerator.java
* </p>
*/
public interface UuidGenerator {
/**
* Generates a UUID which base and increment are always different from any other value provided by this method.
*/
byte[] generate();
/**
* Provide a new UUID generating instance which will allow generation of UUIDs which base is constant and can
* vary according to a provided increment value (see {@link WithFixedBase#generate(int)}).
*/
WithFixedBase withFixedBase();
@FunctionalInterface
interface WithFixedBase {
/**
* Generate a new unique universal identifier using the last 3 bytes of the specified int.
* <p>
* <strong>This implies that this method of a given {@link WithFixedBase} instance can only generate up to
* 2^23-1 unique values if provided with unique int arguments.</strong>
* </p>
* <p>
* This is up to the caller to ensure that unique int values are provided to a given instance's {@link #generate(int)}
* method.
* </p>
* <p>
* This method is faster than {@link UuidGenerator#generate()} due to less computation and less internal concurrency.
* </p>
*/
byte[] generate(int increment);
}
}
| 3,184 | 38.320988 | 131 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/UuidGeneratorImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.security.SecureRandom;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
public final class UuidGeneratorImpl implements UuidGenerator {
private final FullNewUuidGenerator fullNewUuidGenerator = new FullNewUuidGenerator();
@Override
public byte[] generate() {
return fullNewUuidGenerator.get();
}
@Override
public WithFixedBase withFixedBase() {
return new FixedBasedUuidGenerator();
}
private static class UuidGeneratorBase {
// We only use bottom 3 bytes for the sequence number. Paranoia: init with random int so that if JVM/OS/machine goes down, clock slips
// backwards, and JVM comes back up, we are less likely to be on the same sequenceNumber at the same time:
private final AtomicInteger sequenceNumber = new AtomicInteger(new SecureRandom().nextInt());
private final byte[] secureMungedAddress = MacAddressProvider.getSecureMungedAddress();
// Used to ensure clock moves forward
private long lastTimestamp = 0L;
void initBase(byte[] buffer, int sequenceId) {
long timestamp = System.currentTimeMillis();
synchronized (this) {
// Don't let timestamp go backwards, at least "on our watch" (while this JVM is running). We are still vulnerable if we are
// shut down, clock goes backwards, and we restart... for this we randomize the sequenceNumber on init to decrease chance of
// collision:
timestamp = Math.max(lastTimestamp, timestamp);
if (sequenceId == 0) {
// Always force the clock to increment whenever sequence number is 0, in case we have a long time-slip backwards:
timestamp++;
}
lastTimestamp = timestamp;
}
// Only use lower 6 bytes of the timestamp (this will suffice beyond the year 10000):
putLong(buffer, timestamp, 0, 6);
// MAC address adds 6 bytes:
System.arraycopy(secureMungedAddress, 0, buffer, 6, secureMungedAddress.length);
}
protected byte[] generate(byte[] buffer, int increment) {
// Sequence number adds 3 bytes
putLong(buffer, increment, 12, 3);
return buffer;
}
int getSequenceId() {
return sequenceNumber.incrementAndGet() & 0xffffff;
}
/** Puts the lower numberOfLongBytes from l into the array, starting index pos. */
private static void putLong(byte[] array, long l, int pos, int numberOfLongBytes) {
for (int i = 0; i < numberOfLongBytes; ++i) {
array[pos + numberOfLongBytes - i - 1] = (byte) (l >>> (i * 8));
}
}
}
private static final class FullNewUuidGenerator extends UuidGeneratorBase implements Supplier<byte[]> {
@Override
public byte[] get() {
byte[] buffer = new byte[15];
int sequenceId = getSequenceId();
initBase(buffer, sequenceId);
return super.generate(buffer, sequenceId);
}
}
private static class FixedBasedUuidGenerator extends UuidGeneratorBase implements WithFixedBase {
private final byte[] base = new byte[15];
FixedBasedUuidGenerator() {
int sequenceId = getSequenceId();
initBase(base, sequenceId);
}
@Override
public byte[] generate(int increment) {
byte[] buffer = new byte[15];
System.arraycopy(base, 0, buffer, 0, buffer.length);
return super.generate(buffer, increment);
}
}
}
| 4,239 | 34.932203 | 138 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/Uuids.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
public class Uuids {
public static final int MAX_LENGTH = 40;
public static final String UUID_EXAMPLE_01 = "AU-Tpxb--iU5OvuD2FLy";
public static final String UUID_EXAMPLE_02 = "AU-TpxcA-iU5OvuD2FLz";
public static final String UUID_EXAMPLE_03 = "AU-TpxcA-iU5OvuD2FL0";
public static final String UUID_EXAMPLE_04 = "AU-TpxcA-iU5OvuD2FL1";
public static final String UUID_EXAMPLE_05 = "AU-TpxcA-iU5OvuD2FL2";
public static final String UUID_EXAMPLE_06 = "AU-TpxcA-iU5OvuD2FL3";
public static final String UUID_EXAMPLE_07 = "AU-TpxcA-iU5OvuD2FL4";
public static final String UUID_EXAMPLE_08 = "AU-TpxcA-iU5OvuD2FL5";
public static final String UUID_EXAMPLE_09 = "AU-TpxcB-iU5OvuD2FL6";
public static final String UUID_EXAMPLE_10 = "AU-TpxcB-iU5OvuD2FL7";
private Uuids() {
// only static fields
}
/**
* Create a universally unique identifier. It's recommended to use the non-static way
* through {@link UuidFactory} which is available in IoC container.
* @see UuidFactory#create()
*/
public static String create() {
return UuidFactoryImpl.INSTANCE.create();
}
public static String createFast() {
return UuidFactoryFast.getInstance().create();
}
}
| 2,081 | 38.283019 | 87 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.core.util;
import javax.annotation.ParametersAreNonnullByDefault;
| 960 | 37.44 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/issue/Issue.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.issue;
import java.io.Serializable;
public class Issue implements Serializable {
private String issueKey;
private String branchName;
public Issue(String issueKey, String branchName) {
this.issueKey = issueKey;
this.branchName = branchName;
}
public String getIssueKey() {
return issueKey;
}
public String getBranchName() {
return branchName;
}
}
| 1,254 | 29.609756 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/issue/IssueChangedEvent.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.issue;
import java.io.Serializable;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
public class IssueChangedEvent implements Serializable {
private static final String EVENT = "IssueChanged";
private final String projectKey;
private final Issue[] issues;
@CheckForNull
private final Boolean resolved;
@CheckForNull
private final String userSeverity;
@CheckForNull
private final String userType;
public IssueChangedEvent(String projectKey, Issue[] issues, @Nullable Boolean resolved, @Nullable String userSeverity,
@Nullable String userType) {
if (issues.length == 0) {
throw new IllegalArgumentException("Can't create IssueChangedEvent without any issues that have changed");
}
this.projectKey = projectKey;
this.issues = issues;
this.resolved = resolved;
this.userSeverity = userSeverity;
this.userType = userType;
}
public String getEvent() {
return EVENT;
}
public String getProjectKey() {
return projectKey;
}
public Issue[] getIssues() {
return issues;
}
@CheckForNull
public Boolean getResolved() {
return resolved;
}
@CheckForNull
public String getUserSeverity() {
return userSeverity;
}
@CheckForNull
public String getUserType() {
return userType;
}
}
| 2,181 | 26.974359 | 120 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/issue/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.core.util.issue;
import javax.annotation.ParametersAreNonnullByDefault;
| 966 | 37.68 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/logs/DefaultProfiler.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.logs;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.utils.System2;
import org.slf4j.Logger;
import org.sonar.api.utils.log.LoggerLevel;
class DefaultProfiler extends Profiler {
private static final String CONTEXT_SEPARATOR = " | ";
private static final String NO_MESSAGE_SUFFIX = "";
private final LinkedHashMap<String, Object> context = new LinkedHashMap<>();
private final Logger logger;
private long startTime = 0L;
private String startMessage = null;
private Object[] args = null;
private boolean logTimeLast = false;
public DefaultProfiler(Logger logger) {
this.logger = logger;
}
@Override
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override
public boolean isTraceEnabled() {
return logger.isTraceEnabled();
}
@Override
public Profiler start() {
this.startTime = System2.INSTANCE.now();
this.startMessage = null;
return this;
}
@Override
public Profiler startTrace(String message) {
return doStart(LoggerLevel.TRACE, message);
}
@Override
public Profiler startTrace(String message, Object... args) {
return doStart(LoggerLevel.TRACE, message, args);
}
@Override
public Profiler startDebug(String message) {
return doStart(LoggerLevel.DEBUG, message);
}
@Override
public Profiler startDebug(String message, Object... args) {
return doStart(LoggerLevel.DEBUG, message, args);
}
@Override
public Profiler startInfo(String message) {
return doStart(LoggerLevel.INFO, message);
}
@Override
public Profiler startInfo(String message, Object... args) {
return doStart(LoggerLevel.INFO, message, args);
}
@Override
public long stopTrace() {
return doStopWithoutMessage(LoggerLevel.TRACE);
}
@Override
public long stopDebug() {
return doStopWithoutMessage(LoggerLevel.DEBUG);
}
@Override
public long stopInfo() {
return doStopWithoutMessage(LoggerLevel.INFO);
}
@Override
public long stopTrace(String message) {
return doStop(LoggerLevel.TRACE, message, null, NO_MESSAGE_SUFFIX);
}
@Override
public long stopTrace(String message, Object... args) {
return doStop(LoggerLevel.TRACE, message, args, NO_MESSAGE_SUFFIX);
}
@Override
public long stopDebug(String message) {
return doStop(LoggerLevel.DEBUG, message, null, NO_MESSAGE_SUFFIX);
}
@Override
public long stopDebug(String message, Object... args) {
return doStop(LoggerLevel.DEBUG, message, args, NO_MESSAGE_SUFFIX);
}
@Override
public long stopInfo(String message) {
return doStop(LoggerLevel.INFO, message, null, NO_MESSAGE_SUFFIX);
}
@Override
public long stopInfo(String message, Object... args) {
return doStop(LoggerLevel.INFO, message, args, NO_MESSAGE_SUFFIX);
}
@Override
public long stopError(String message, Object... args) {
return doStop(LoggerLevel.ERROR, message, args, NO_MESSAGE_SUFFIX);
}
private Profiler doStart(LoggerLevel logLevel, String message, Object... args) {
init(message, args);
logStartMessage(logLevel, message, args);
return this;
}
private void init(String message, Object... args) {
this.startTime = System2.INSTANCE.now();
this.startMessage = message;
this.args = args;
}
private void reset() {
this.startTime = 0L;
this.startMessage = null;
this.args = null;
this.context.clear();
}
private void logStartMessage(LoggerLevel loggerLevel, String message, Object... args) {
if (shouldLog(logger, loggerLevel)) {
StringBuilder sb = new StringBuilder();
sb.append(message);
appendContext(sb);
log(loggerLevel, sb.toString(), args);
}
}
private long doStopWithoutMessage(LoggerLevel level) {
if (startMessage == null) {
throw new IllegalStateException("Profiler#stopXXX() can't be called without any message defined in start methods");
}
return doStop(level, startMessage, this.args, " (done)");
}
private long doStop(LoggerLevel level, @Nullable String message, @Nullable Object[] args, String messageSuffix) {
if (startTime == 0L) {
throw new IllegalStateException("Profiler must be started before being stopped");
}
long duration = System2.INSTANCE.now() - startTime;
if (shouldLog(logger, level)) {
StringBuilder sb = new StringBuilder();
if (!StringUtils.isEmpty(message)) {
sb.append(message);
sb.append(messageSuffix);
}
if (logTimeLast) {
appendContext(sb);
appendTime(sb, duration);
} else {
appendTime(sb, duration);
appendContext(sb);
}
log(level, sb.toString(), args);
}
reset();
return duration;
}
private static void appendTime(StringBuilder sb, long duration) {
if (sb.length() > 0) {
sb.append(CONTEXT_SEPARATOR);
}
sb.append("time=").append(duration).append("ms");
}
private void appendContext(StringBuilder sb) {
for (Map.Entry<String, Object> entry : context.entrySet()) {
if (sb.length() > 0) {
sb.append(CONTEXT_SEPARATOR);
}
sb.append(entry.getKey()).append("=").append(entry.getValue());
}
}
void log(LoggerLevel level, String msg, @Nullable Object[] args) {
switch (level) {
case TRACE:
logTrace(msg, args);
break;
case DEBUG:
logDebug(msg, args);
break;
case INFO:
logInfo(msg, args);
break;
case WARN:
logWarn(msg, args);
break;
case ERROR:
logError(msg, args);
break;
default:
throw new IllegalArgumentException("Unsupported LoggerLevel value: " + level);
}
}
private void logTrace(String msg, @Nullable Object[] args) {
if (args == null) {
logger.trace(msg);
} else {
logger.trace(msg, args);
}
}
private void logDebug(String msg, @Nullable Object[] args) {
if (args == null) {
logger.debug(msg);
} else {
logger.debug(msg, args);
}
}
private void logInfo(String msg, @Nullable Object[] args) {
if (args == null) {
logger.info(msg);
} else {
logger.info(msg, args);
}
}
private void logWarn(String msg, @Nullable Object[] args) {
if (args == null) {
logger.warn(msg);
} else {
logger.warn(msg, args);
}
}
private void logError(String msg, @Nullable Object[] args) {
if (args == null) {
logger.error(msg);
} else {
logger.error(msg, args);
}
}
private static boolean shouldLog(Logger logger, LoggerLevel level) {
if (level == LoggerLevel.TRACE && !logger.isTraceEnabled()) {
return false;
}
return level != LoggerLevel.DEBUG || logger.isDebugEnabled();
}
@Override
public Profiler addContext(String key, @Nullable Object value) {
if (value == null) {
context.remove(key);
} else {
context.put(key, value);
}
return this;
}
@Override
public boolean hasContext(String key) {
return context.containsKey(key);
}
@Override
public Profiler logTimeLast(boolean flag) {
this.logTimeLast = flag;
return this;
}
}
| 8,136 | 25.333333 | 121 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/logs/NullProfiler.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.logs;
import javax.annotation.Nullable;
class NullProfiler extends Profiler {
static final NullProfiler NULL_INSTANCE = new NullProfiler();
private NullProfiler() {
}
@Override
public boolean isDebugEnabled() {
return false;
}
@Override
public boolean isTraceEnabled() {
return false;
}
@Override
public Profiler start() {
return this;
}
@Override
public Profiler startTrace(String message) {
return this;
}
@Override
public Profiler startTrace(String message, Object... args) {
return this;
}
@Override
public Profiler startDebug(String message) {
return this;
}
@Override
public Profiler startDebug(String message, Object... args) {
return this;
}
@Override
public Profiler startInfo(String message) {
return this;
}
@Override
public Profiler startInfo(String message, Object... args) {
return this;
}
@Override
public long stopTrace() {
return 0;
}
@Override
public long stopDebug() {
return 0;
}
@Override
public long stopInfo() {
return 0;
}
@Override
public long stopTrace(String message) {
return 0;
}
@Override
public long stopTrace(String message, Object... args) {
return 0;
}
@Override
public long stopDebug(String message) {
return 0;
}
@Override
public long stopDebug(String message, Object... args) {
return 0;
}
@Override
public long stopInfo(String message) {
return 0;
}
@Override
public long stopInfo(String message, Object... args) {
return 0;
}
@Override
public long stopError(String message, Object... args) {
return 0;
}
@Override
public Profiler addContext(String key, @Nullable Object value) {
// nothing to do
return this;
}
@Override
public boolean hasContext(String key) {
return false;
}
@Override
public Profiler logTimeLast(boolean flag) {
return this;
}
}
| 2,814 | 18.823944 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/logs/Profiler.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.logs;
import javax.annotation.Nullable;
import org.slf4j.Logger;
/**
*
* @since 5.1
*/
public abstract class Profiler {
public static Profiler create(Logger logger) {
return new DefaultProfiler(logger);
}
public static Profiler createIfTrace(Logger logger) {
if (logger.isTraceEnabled()) {
return create(logger);
}
return NullProfiler.NULL_INSTANCE;
}
public static Profiler createIfDebug(Logger logger) {
if (logger.isDebugEnabled()) {
return create(logger);
}
return NullProfiler.NULL_INSTANCE;
}
public abstract boolean isDebugEnabled();
public abstract boolean isTraceEnabled();
public abstract Profiler start();
public abstract Profiler startTrace(String message);
public abstract Profiler startTrace(String message, Object... args);
public abstract Profiler startDebug(String message);
public abstract Profiler startDebug(String message, Object... args);
public abstract Profiler startInfo(String message);
public abstract Profiler startInfo(String message, Object... args);
/**
* Works only if a message have been set in startXXX() methods.
*/
public abstract long stopTrace();
public abstract long stopDebug();
public abstract long stopInfo();
public abstract long stopTrace(String message);
public abstract long stopTrace(String message, Object... args);
public abstract long stopDebug(String message);
public abstract long stopDebug(String message, Object... args);
public abstract long stopInfo(String message);
public abstract long stopInfo(String message, Object... args);
public abstract long stopError(String message, Object... args);
/**
* Context information is removed if value is <code>null</code>.
*/
public abstract Profiler addContext(String key, @Nullable Object value);
public abstract boolean hasContext(String key);
/**
* Defines whether time is added to stop messages before or after context (if any).
* <p>{@code flag} is {@code false} by default.</p>
*/
public abstract Profiler logTimeLast(boolean flag);
}
| 2,961 | 27.757282 | 85 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/logs/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.core.util.logs;
import javax.annotation.ParametersAreNonnullByDefault;
| 965 | 37.64 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/rule/RuleChange.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.rule;
import java.io.Serializable;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.core.util.ParamChange;
public class RuleChange implements Serializable {
private String key;
private String language;
private String templateKey;
private String severity;
private ParamChange[] params = new ParamChange[0];
public String getKey() {
return key;
}
public RuleChange setKey(String key) {
this.key = key;
return this;
}
@CheckForNull
public String getLanguage() {
return language;
}
public RuleChange setLanguage(@Nullable String language) {
this.language = language;
return this;
}
public String getTemplateKey() {
return templateKey;
}
public RuleChange setTemplateKey(String templateKey) {
this.templateKey = templateKey;
return this;
}
@CheckForNull
public String getSeverity() {
return severity;
}
public RuleChange setSeverity(@Nullable String severity) {
this.severity = severity;
return this;
}
public ParamChange[] getParams() {
return params;
}
public RuleChange setParams(ParamChange[] params) {
this.params = params;
return this;
}
}
| 2,078 | 24.666667 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/rule/RuleSetChangedEvent.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.rule;
import java.io.Serializable;
public class RuleSetChangedEvent implements Serializable {
private final String[] projects;
private final RuleChange[] activatedRules;
private final String[] deactivatedRules;
public RuleSetChangedEvent(String projectKey, RuleChange[] activatedRules, String[] deactivatedRules) {
this.projects = new String[]{projectKey};
this.activatedRules = activatedRules;
this.deactivatedRules = deactivatedRules;
if (activatedRules.length == 0 && deactivatedRules.length == 0) {
throw new IllegalArgumentException("Can't create RuleSetChangedEvent without any rules that have changed");
}
}
public String[] getProjects() {
return projects;
}
public RuleChange[] getActivatedRules() {
return activatedRules;
}
public String[] getDeactivatedRules() {
return deactivatedRules;
}
}
| 1,739 | 33.8 | 113 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/rule/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.core.util.rule;
import javax.annotation.ParametersAreNonnullByDefault;
| 965 | 37.64 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/stream/MoreCollectors.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSetMultimap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collector;
import java.util.stream.Stream;
import static java.util.Objects.requireNonNull;
public final class MoreCollectors {
private static final String KEY_FUNCTION_CANT_RETURN_NULL_MESSAGE = "Key function can't return null";
private static final String VALUE_FUNCTION_CANT_RETURN_NULL_MESSAGE = "Value function can't return null";
private MoreCollectors() {
// prevents instantiation
}
/**
* 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.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) {
verifyKeyAndValueFunctions(keyFunction, valueFunction);
BiConsumer<ImmutableListMultimap.Builder<K, V>, E> accumulator = (map, element) -> {
K key = requireNonNull(keyFunction.apply(element), KEY_FUNCTION_CANT_RETURN_NULL_MESSAGE);
V value = requireNonNull(valueFunction.apply(element), VALUE_FUNCTION_CANT_RETURN_NULL_MESSAGE);
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);
}
/**
* Creates an {@link com.google.common.collect.ImmutableSetMultimap} 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, ImmutableSetMultimap.Builder<K, E>, ImmutableSetMultimap<K, E>> unorderedIndex(Function<? super E, K> keyFunction) {
return unorderedIndex(keyFunction, Function.identity());
}
/**
* Creates an {@link com.google.common.collect.ImmutableSetMultimap} 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, ImmutableSetMultimap.Builder<K, V>, ImmutableSetMultimap<K, V>> unorderedIndex(Function<? super E, K> keyFunction,
Function<? super E, V> valueFunction) {
verifyKeyAndValueFunctions(keyFunction, valueFunction);
BiConsumer<ImmutableSetMultimap.Builder<K, V>, E> accumulator = (map, element) -> {
K key = requireNonNull(keyFunction.apply(element), KEY_FUNCTION_CANT_RETURN_NULL_MESSAGE);
V value = requireNonNull(valueFunction.apply(element), VALUE_FUNCTION_CANT_RETURN_NULL_MESSAGE);
map.put(key, value);
};
BinaryOperator<ImmutableSetMultimap.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(
ImmutableSetMultimap::builder,
accumulator,
merger,
ImmutableSetMultimap.Builder::build);
}
/**
* A Collector similar to {@link #unorderedIndex(Function, Function)} except that it expects the {@code valueFunction}
* to return a {@link Stream} which content will be flatten into the returned {@link ImmutableSetMultimap}.
*
* @see #unorderedIndex(Function, Function)
*/
public static <K, E, V> Collector<E, ImmutableSetMultimap.Builder<K, V>, ImmutableSetMultimap<K, V>> unorderedFlattenIndex(
Function<? super E, K> keyFunction, Function<? super E, Stream<V>> valueFunction) {
verifyKeyAndValueFunctions(keyFunction, valueFunction);
BiConsumer<ImmutableSetMultimap.Builder<K, V>, E> accumulator = (map, element) -> {
K key = requireNonNull(keyFunction.apply(element), KEY_FUNCTION_CANT_RETURN_NULL_MESSAGE);
Stream<V> valueStream = requireNonNull(valueFunction.apply(element), VALUE_FUNCTION_CANT_RETURN_NULL_MESSAGE);
valueStream.forEach(value -> map.put(key, value));
};
BinaryOperator<ImmutableSetMultimap.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(
ImmutableSetMultimap::builder,
accumulator,
merger,
ImmutableSetMultimap.Builder::build);
}
private static void verifyKeyAndValueFunctions(Function<?, ?> keyFunction, Function<?, ?> valueFunction) {
requireNonNull(keyFunction, "Key function can't be null");
requireNonNull(valueFunction, "Value function can't be null");
}
}
| 8,192 | 43.770492 | 153 | java |
sonarqube | sonarqube-master/sonar-core/src/main/java/org/sonar/core/util/stream/package-info.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.core.util.stream;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 37.72 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/com/sonarsource/plugins/license/api/FooBar.java | /*
* SonarQube
* Copyright (C) 2009-2023 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 com.sonarsource.plugins.license.api;
public interface FooBar {
}
| 917 | 37.25 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/component/ComponentKeysSanitizationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.component;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(Parameterized.class)
public class ComponentKeysSanitizationTest {
@Parameterized.Parameters(name = "{index}: input {0}, expected output {1}")
public static Collection<String[]> data() {
return Arrays.asList(new String[][] {
{"/a/b/c/", "_a_b_c_"},
{".a.b:c:", ".a.b:c:"},
{"_1_2_3_", "_1_2_3_"},
{"fully_valid_-name2", "fully_valid_-name2"},
{"°+\"*ç%&\\/()=?`^“#Ç[]|{}≠¿ ~", "___________________________"},
});
}
private final String inputString;
private final String expectedOutputString;
public ComponentKeysSanitizationTest(String inputString, String expectedOutputString) {
this.inputString = inputString;
this.expectedOutputString = expectedOutputString;
}
@Test
public void sanitizeProjectKey() {
assertThat(ComponentKeys.sanitizeProjectKey(inputString)).isEqualTo(expectedOutputString);
}
}
| 1,971 | 33 | 94 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/component/ComponentKeysTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.component;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ComponentKeysTest {
@Test
public void create_key_from_module_key_path_and_branch() {
assertThat(ComponentKeys.createKey("module_key", "file", "origin/master")).isEqualTo("module_key:origin/master:file");
assertThat(ComponentKeys.createKey("module_key", "file", null)).isEqualTo("module_key:file");
assertThat(ComponentKeys.createKey("module_key", null, null)).isEqualTo("module_key");
}
@Test
public void valid_project_key() {
assertThat(ComponentKeys.isValidProjectKey("abc")).isTrue();
assertThat(ComponentKeys.isValidProjectKey("ab_12")).isTrue();
}
@Test
public void invalid_project_key() {
assertThat(ComponentKeys.isValidProjectKey("0123")).isFalse();
assertThat(ComponentKeys.isValidProjectKey("ab/12")).isFalse();
assertThat(ComponentKeys.isValidProjectKey("코드품질")).isFalse();
assertThat(ComponentKeys.isValidProjectKey("")).isFalse();
assertThat(ComponentKeys.isValidProjectKey(" ")).isFalse();
assertThat(ComponentKeys.isValidProjectKey("ab 12")).isFalse();
assertThat(ComponentKeys.isValidProjectKey(" ab")).isFalse();
assertThat(ComponentKeys.isValidProjectKey("ab ")).isFalse();
}
@Test
public void checkProjectKey_with_correct_keys() {
ComponentKeys.checkProjectKey("abc");
ComponentKeys.checkProjectKey("a-b_1.:2");
}
@Test
public void checkProjectKey_fail_if_key_is_empty() {
assertThatThrownBy(() -> ComponentKeys.checkProjectKey(""))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void checkProjectKey_fail_if_space() {
assertThatThrownBy(() -> ComponentKeys.checkProjectKey("ab 12"))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
public void checkProjectKey_fail_if_only_digit() {
assertThatThrownBy(() -> ComponentKeys.checkProjectKey("0123"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Malformed key for '0123'. Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.");
}
@Test
public void checkProjectKey_fail_if_special_characters_not_allowed() {
assertThatThrownBy(() -> ComponentKeys.checkProjectKey("0123"))
.isInstanceOf(IllegalArgumentException.class);
}
}
| 3,263 | 36.517241 | 136 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/component/DefaultResourceTypesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.component;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.ResourceTypeTree;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultResourceTypesTest {
@Test
public void provide_types() {
ResourceTypeTree tree = DefaultResourceTypes.get();
assertThat(tree.getTypes()).hasSize(5);
assertThat(tree.getChildren(Qualifiers.PROJECT)).containsExactly(Qualifiers.DIRECTORY);
}
}
| 1,332 | 35.027027 | 91 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/config/CorePropertyDefinitionsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.config;
import java.util.List;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinition;
import static org.assertj.core.api.Assertions.assertThat;
public class CorePropertyDefinitionsTest {
@Test
public void all() {
List<PropertyDefinition> defs = CorePropertyDefinitions.all();
assertThat(defs).isNotEmpty();
}
@Test
public void all_includes_scanner_properties() {
List<PropertyDefinition> defs = CorePropertyDefinitions.all();
assertThat(defs.stream()
.filter(def -> def.key().equals(ScannerProperties.BRANCH_NAME))
.findFirst()).isPresent();
}
}
| 1,474 | 31.777778 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/config/MaxTokenLifetimeOptionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.config;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.sonar.core.config.MaxTokenLifetimeOption.NINETY_DAYS;
import static org.sonar.core.config.MaxTokenLifetimeOption.NO_EXPIRATION;
import static org.sonar.core.config.MaxTokenLifetimeOption.ONE_YEAR;
import static org.sonar.core.config.MaxTokenLifetimeOption.THIRTY_DAYS;
public class MaxTokenLifetimeOptionTest {
@Test
public void all_options_present() {
assertThat(MaxTokenLifetimeOption.values()).hasSize(4);
}
@Test
public void when_get_by_name_then_the_enum_value_is_returned() {
assertThat(MaxTokenLifetimeOption.get("30 days")).isEqualTo(THIRTY_DAYS);
assertThat(MaxTokenLifetimeOption.get("90 days")).isEqualTo(NINETY_DAYS);
assertThat(MaxTokenLifetimeOption.get("1 year")).isEqualTo(ONE_YEAR);
assertThat(MaxTokenLifetimeOption.get("No expiration")).isEqualTo(NO_EXPIRATION);
}
@Test
public void when_get_by_name_nonexistant_then_exception_is_thrown() {
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> MaxTokenLifetimeOption.get("wrong lifetime"))
.withMessage("No token expiration interval with name \"wrong lifetime\" found.");
}
@Test
public void lifetime_options_days() {
assertThat(THIRTY_DAYS.getDays()).hasValue(30);
assertThat(NINETY_DAYS.getDays()).hasValue(90);
assertThat(ONE_YEAR.getDays()).hasValue(365);
assertThat(NO_EXPIRATION.getDays()).isEmpty();
}
}
| 2,432 | 38.885246 | 87 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/config/PurgePropertiesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.config;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class PurgePropertiesTest {
@Test
public void shouldGetExtensions() {
assertThat(PurgeProperties.all()).hasSize(6);
}
}
| 1,096 | 32.242424 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/config/SecurityPropertiesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.config;
import java.util.Optional;
import org.junit.Test;
import org.sonar.api.config.PropertyDefinition;
import static org.assertj.core.api.Assertions.assertThat;
public class SecurityPropertiesTest {
@Test
public void creates_properties() {
assertThat(SecurityProperties.all()).isNotEmpty();
Optional<PropertyDefinition> propertyDefinition = SecurityProperties.all().stream()
.filter(d -> d.key().equals("sonar.forceAuthentication")).findFirst();
assertThat(propertyDefinition)
.isNotEmpty()
.get()
.extracting(PropertyDefinition::defaultValue)
.isEqualTo("true");
}
}
| 1,490 | 33.674419 | 87 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/documentation/DefaultDocumentationLinkGeneratorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.documentation;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.sonar.api.config.Configuration;
import org.sonar.core.platform.SonarQubeVersion;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.sonar.core.config.CorePropertyDefinitions.DOCUMENTATION_BASE_URL;
import static org.sonar.core.documentation.DefaultDocumentationLinkGenerator.DOCUMENTATION_PUBLIC_URL;
@RunWith(MockitoJUnitRunner.class)
public class DefaultDocumentationLinkGeneratorTest {
private static final String TEST_SUFFIX = "/documentation/analyzing-source-code/scm-integration/";
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
private SonarQubeVersion sonarQubeVersion;
@Mock
private Configuration configuration;
private DefaultDocumentationLinkGenerator documentationLinkGenerator;
@Before
public void setUp() {
when(sonarQubeVersion.get().major()).thenReturn(100);
when(sonarQubeVersion.get().minor()).thenReturn(1000);
when(sonarQubeVersion.get().qualifier()).thenReturn("");
when(configuration.get(DOCUMENTATION_BASE_URL)).thenReturn(Optional.empty());
documentationLinkGenerator = new DefaultDocumentationLinkGenerator(sonarQubeVersion, configuration);
}
@Test
public void getDocumentationLink_whenSuffixProvided_concatenatesIt() {
String generatedLink = documentationLinkGenerator.getDocumentationLink(TEST_SUFFIX);
assertThat(generatedLink).isEqualTo(DOCUMENTATION_PUBLIC_URL + "100.1000/documentation/analyzing-source-code/scm-integration/");
}
@Test
public void getDocumentationLink_whenSnapshot_returnLatest() {
when(sonarQubeVersion.get().qualifier()).thenReturn("SNAPSHOT");
documentationLinkGenerator = new DefaultDocumentationLinkGenerator(sonarQubeVersion, configuration);
String generatedLink = documentationLinkGenerator.getDocumentationLink(TEST_SUFFIX);
assertThat(generatedLink).isEqualTo(DOCUMENTATION_PUBLIC_URL + "latest/documentation/analyzing-source-code/scm-integration/");
}
@Test
public void getDocumentationLink_whenSuffixNotProvided_returnsBaseUrl() {
String generatedLink = documentationLinkGenerator.getDocumentationLink(null);
assertThat(generatedLink).isEqualTo(DOCUMENTATION_PUBLIC_URL + "100.1000");
}
@Test
public void getDocumentationLink_suffixProvided_withPropertyOverride() {
String propertyValue = "https://new-url.sonarqube.org/";
when(configuration.get(DOCUMENTATION_BASE_URL)).thenReturn(Optional.of(propertyValue));
documentationLinkGenerator = new DefaultDocumentationLinkGenerator(sonarQubeVersion, configuration);
String generatedLink = documentationLinkGenerator.getDocumentationLink(TEST_SUFFIX);
assertThat(generatedLink).isEqualTo(propertyValue + "100.1000/documentation/analyzing-source-code/scm-integration/");
}
@Test
public void getDocumentationLink_suffixNotProvided_withPropertyOverride() {
String propertyValue = "https://new-url.sonarqube.org/";
when(configuration.get(DOCUMENTATION_BASE_URL)).thenReturn(Optional.of(propertyValue));
documentationLinkGenerator = new DefaultDocumentationLinkGenerator(sonarQubeVersion, configuration);
String generatedLink = documentationLinkGenerator.getDocumentationLink(null);
assertThat(generatedLink).isEqualTo(propertyValue + "100.1000");
}
@Test
public void getDocumentationLink_suffixNotProvided_withPropertyOverride_missingSlash() {
String propertyValue = "https://new-url.sonarqube.org";
when(configuration.get(DOCUMENTATION_BASE_URL)).thenReturn(Optional.of(propertyValue));
documentationLinkGenerator = new DefaultDocumentationLinkGenerator(sonarQubeVersion, configuration);
String generatedLink = documentationLinkGenerator.getDocumentationLink(null);
assertThat(generatedLink).isEqualTo(propertyValue + "/100.1000");
}
}
| 4,884 | 41.850877 | 132 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/extension/CoreExtensionRepositoryImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.extension;
import com.google.common.collect.ImmutableSet;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
import org.junit.runner.RunWith;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@RunWith(DataProviderRunner.class)
public class CoreExtensionRepositoryImplTest {
private CoreExtensionRepositoryImpl underTest = new CoreExtensionRepositoryImpl();
@Test
public void loadedCoreExtensions_fails_with_ISE_if_called_before_setLoadedCoreExtensions() {
assertThatThrownBy(() -> underTest.loadedCoreExtensions())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Repository has not been initialized yet");
}
@Test
@UseDataProvider("coreExtensionsSets")
public void loadedCoreExtensions_returns_CoreExtensions_from_setLoadedCoreExtensions(Set<CoreExtension> coreExtensions) {
underTest.setLoadedCoreExtensions(coreExtensions);
assertThat(underTest.loadedCoreExtensions().collect(Collectors.toSet()))
.isEqualTo(coreExtensions);
}
@Test
public void setLoadedCoreExtensions_fails_with_NPE_if_argument_is_null() {
assertThatThrownBy(() -> underTest.setLoadedCoreExtensions(null))
.isInstanceOf(NullPointerException.class);
}
@Test
@UseDataProvider("coreExtensionsSets")
public void setLoadedCoreExtensions_fails_with_ISE_if_called_twice(Set<CoreExtension> coreExtensions) {
underTest.setLoadedCoreExtensions(coreExtensions);
assertThatThrownBy(() -> underTest.setLoadedCoreExtensions(coreExtensions))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Repository has already been initialized");
}
@Test
public void installed_fails_with_ISE_if_called_before_setLoadedCoreExtensions() {
CoreExtension coreExtension = newCoreExtension();
assertThatThrownBy(() -> underTest.installed(coreExtension))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Repository has not been initialized yet");
}
@Test
@UseDataProvider("coreExtensionsSets")
public void installed_fails_with_IAE_if_CoreExtension_is_not_loaded(Set<CoreExtension> coreExtensions) {
underTest.setLoadedCoreExtensions(coreExtensions);
CoreExtension coreExtension = newCoreExtension();
assertThatThrownBy(() -> underTest.installed(coreExtension))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Specified CoreExtension has not been loaded first");
}
@Test
@UseDataProvider("coreExtensionsSets")
public void installed_fails_with_NPE_if_CoreExtension_is_null(Set<CoreExtension> coreExtensions) {
underTest.setLoadedCoreExtensions(coreExtensions);
assertThatThrownBy(() -> underTest.installed(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("coreExtension can't be null");
}
@Test
public void isInstalled_fails_with_ISE_if_called_before_setLoadedCoreExtensions() {
assertThatThrownBy(() -> underTest.isInstalled("foo"))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Repository has not been initialized yet");
}
@Test
@UseDataProvider("coreExtensionsSets")
public void isInstalled_returns_false_for_not_loaded_CoreExtension(Set<CoreExtension> coreExtensions) {
underTest.setLoadedCoreExtensions(coreExtensions);
assertThat(underTest.isInstalled("not loaded")).isFalse();
}
@Test
public void isInstalled_returns_false_for_loaded_but_not_installed_CoreExtension() {
CoreExtension coreExtension = newCoreExtension();
underTest.setLoadedCoreExtensions(singleton(coreExtension));
assertThat(underTest.isInstalled(coreExtension.getName())).isFalse();
}
@Test
public void isInstalled_returns_true_for_loaded_and_installed_CoreExtension() {
CoreExtension coreExtension = newCoreExtension();
underTest.setLoadedCoreExtensions(singleton(coreExtension));
underTest.installed(coreExtension);
assertThat(underTest.isInstalled(coreExtension.getName())).isTrue();
}
@DataProvider
public static Object[][] coreExtensionsSets() {
return new Object[][] {
{emptySet()},
{singleton(newCoreExtension())},
{ImmutableSet.of(newCoreExtension(), newCoreExtension())},
};
}
private static int nameCounter = 0;
private static CoreExtension newCoreExtension() {
String name = "name_" + nameCounter;
nameCounter++;
return newCoreExtension(name);
}
private static CoreExtension newCoreExtension(String name) {
return new CoreExtension() {
@Override
public String getName() {
return name;
}
@Override
public void load(Context context) {
throw new UnsupportedOperationException("load should not be called");
}
};
}
}
| 5,927 | 34.710843 | 123 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/extension/CoreExtensionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.extension;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CoreExtensionTest {
private CoreExtension underTest = new CoreExtension() {
@Override
public String getName() {
return "fake";
}
@Override
public void load(Context context) {
// nothing to do here
}
};
@Test
public void getExtensionProperties_by_default_does_not_contain_any_overridden_property_defaults() {
assertThat(underTest.getExtensionProperties()).isEmpty();
}
}
| 1,397 | 30.066667 | 101 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/extension/CoreExtensionsInstallerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.extension;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Collection;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mockito;
import org.sonar.api.Property;
import org.sonar.api.SonarRuntime;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.internal.MapSettings;
import org.sonar.core.platform.ExtensionContainer;
import org.sonar.core.platform.ListContainer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.core.extension.CoreExtensionsInstaller.noAdditionalSideFilter;
import static org.sonar.core.extension.CoreExtensionsInstaller.noExtensionFilter;
@RunWith(DataProviderRunner.class)
public class CoreExtensionsInstallerTest {
private final SonarRuntime sonarRuntime = mock(SonarRuntime.class);
private final CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class);
private final CoreExtensionsInstaller underTest = new CoreExtensionsInstaller(sonarRuntime, coreExtensionRepository, WestSide.class) {
};
private final ArgumentCaptor<CoreExtension.Context> contextCaptor = ArgumentCaptor.forClass(CoreExtension.Context.class);
private static int name_counter = 0;
@Test
public void install_has_no_effect_if_CoreExtensionRepository_has_no_loaded_CoreExtension() {
ListContainer container = new ListContainer();
underTest.install(container, noExtensionFilter(), noAdditionalSideFilter());
assertAddedExtensions(container, 0);
}
@Test
public void install_calls_load_method_on_all_loaded_CoreExtension() {
CoreExtension coreExtension1 = newCoreExtension();
CoreExtension coreExtension2 = newCoreExtension();
CoreExtension coreExtension3 = newCoreExtension();
CoreExtension coreExtension4 = newCoreExtension();
List<CoreExtension> coreExtensions = ImmutableList.of(coreExtension1, coreExtension2, coreExtension3, coreExtension4);
InOrder inOrder = Mockito.inOrder(coreExtension1, coreExtension2, coreExtension3, coreExtension4);
when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(coreExtensions.stream());
ListContainer container = new ListContainer();
underTest.install(container, noExtensionFilter(), noAdditionalSideFilter());
inOrder.verify(coreExtension1).load(contextCaptor.capture());
inOrder.verify(coreExtension2).load(contextCaptor.capture());
inOrder.verify(coreExtension3).load(contextCaptor.capture());
inOrder.verify(coreExtension4).load(contextCaptor.capture());
// verify each core extension gets its own Context
assertThat(contextCaptor.getAllValues())
.hasSameElementsAs(ImmutableSet.copyOf(contextCaptor.getAllValues()));
}
@Test
public void install_provides_runtime_from_constructor_in_context() {
CoreExtension coreExtension1 = newCoreExtension();
CoreExtension coreExtension2 = newCoreExtension();
when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(Stream.of(coreExtension1, coreExtension2));
ListContainer container = new ListContainer();
underTest.install(container, noExtensionFilter(), noAdditionalSideFilter());
verify(coreExtension1).load(contextCaptor.capture());
verify(coreExtension2).load(contextCaptor.capture());
assertThat(contextCaptor.getAllValues())
.extracting(CoreExtension.Context::getRuntime)
.containsOnly(sonarRuntime);
}
@Test
public void install_provides_new_Configuration_when_getBootConfiguration_is_called_and_there_is_none_in_container() {
CoreExtension coreExtension1 = newCoreExtension();
CoreExtension coreExtension2 = newCoreExtension();
when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(Stream.of(coreExtension1, coreExtension2));
ListContainer container = new ListContainer();
underTest.install(container, noExtensionFilter(), noAdditionalSideFilter());
verify(coreExtension1).load(contextCaptor.capture());
verify(coreExtension2).load(contextCaptor.capture());
// verify each core extension gets its own configuration
assertThat(contextCaptor.getAllValues())
.hasSameElementsAs(ImmutableSet.copyOf(contextCaptor.getAllValues()));
}
@Test
public void install_provides_Configuration_from_container_when_getBootConfiguration_is_called() {
CoreExtension coreExtension1 = newCoreExtension();
CoreExtension coreExtension2 = newCoreExtension();
when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(Stream.of(coreExtension1, coreExtension2));
Configuration configuration = new MapSettings().asConfig();
ExtensionContainer container = mock(ExtensionContainer.class);
when(container.getComponentByType(Configuration.class)).thenReturn(configuration);
underTest.install(container, noExtensionFilter(), noAdditionalSideFilter());
verify(coreExtension1).load(contextCaptor.capture());
verify(coreExtension2).load(contextCaptor.capture());
assertThat(contextCaptor.getAllValues())
.extracting(CoreExtension.Context::getBootConfiguration)
.containsOnly(configuration);
}
@Test
@UseDataProvider("allMethodsToAddExtension")
public void install_installs_extensions_annotated_with_expected_annotation(BiConsumer<CoreExtension.Context, Collection<Object>> extensionAdder) {
List<Object> extensions = ImmutableList.of(WestSideClass.class, EastSideClass.class, OtherSideClass.class, Latitude.class);
CoreExtension coreExtension = newCoreExtension(context -> extensionAdder.accept(context, extensions));
when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(Stream.of(coreExtension));
ExtensionContainer container = mock(ExtensionContainer.class);
underTest.install(container, noExtensionFilter(), noAdditionalSideFilter());
verify(container).addExtension(coreExtension.getName(), WestSideClass.class);
verify(container).declareExtension(coreExtension.getName(), OtherSideClass.class);
verify(container).declareExtension(coreExtension.getName(), EastSideClass.class);
verify(container).addExtension(coreExtension.getName(), Latitude.class);
verifyNoMoreInteractions(container);
}
@Test
@UseDataProvider("allMethodsToAddExtension")
public void install_does_not_install_extensions_annotated_with_expected_annotation_but_filtered_out(BiConsumer<CoreExtension.Context, Collection<Object>> extensionAdder) {
List<Object> extensions = ImmutableList.of(WestSideClass.class, EastSideClass.class, OtherSideClass.class, Latitude.class);
CoreExtension coreExtension = newCoreExtension(context -> extensionAdder.accept(context, extensions));
when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(Stream.of(coreExtension));
ExtensionContainer container = mock(ExtensionContainer.class);
underTest.install(container, noExtensionFilter(), t -> t != Latitude.class);
verify(container).addExtension(coreExtension.getName(), WestSideClass.class);
verify(container).declareExtension(coreExtension.getName(), OtherSideClass.class);
verify(container).declareExtension(coreExtension.getName(), EastSideClass.class);
verify(container).declareExtension(coreExtension.getName(), Latitude.class);
verifyNoMoreInteractions(container);
}
@Test
@UseDataProvider("allMethodsToAddExtension")
public void install_adds_PropertyDefinition_with_extension_name_as_default_category(BiConsumer<CoreExtension.Context, Collection<Object>> extensionAdder) {
PropertyDefinition propertyDefinitionNoCategory = PropertyDefinition.builder("fooKey").build();
PropertyDefinition propertyDefinitionWithCategory = PropertyDefinition.builder("barKey").category("donut").build();
List<Object> extensions = ImmutableList.of(propertyDefinitionNoCategory, propertyDefinitionWithCategory);
CoreExtension coreExtension = newCoreExtension(context -> extensionAdder.accept(context, extensions));
when(coreExtensionRepository.loadedCoreExtensions()).thenReturn(Stream.of(coreExtension));
ExtensionContainer container = mock(ExtensionContainer.class);
underTest.install(container, noExtensionFilter(), noAdditionalSideFilter());
verify(container).declareExtension(coreExtension.getName(), propertyDefinitionNoCategory);
verify(container).declareExtension(coreExtension.getName(), propertyDefinitionWithCategory);
verifyNoMoreInteractions(container);
}
@DataProvider
public static Object[][] allMethodsToAddExtension() {
BiConsumer<CoreExtension.Context, Collection<Object>> addExtension = (context, objects) -> objects.forEach(context::addExtension);
BiConsumer<CoreExtension.Context, Collection<Object>> addExtensionsVarArg = (context, objects) -> {
if (objects.isEmpty()) {
return;
}
if (objects.size() == 1) {
context.addExtensions(objects.iterator().next());
}
context.addExtensions(objects.iterator().next(), objects.stream().skip(1).toArray(Object[]::new));
};
BiConsumer<CoreExtension.Context, Collection<Object>> addExtensions = CoreExtension.Context::addExtensions;
return new Object[][] {
{addExtension},
{addExtensions},
{addExtensionsVarArg}
};
}
private static void assertAddedExtensions(ListContainer container, int addedExtensions) {
List<Object> adapters = container.getAddedObjects();
assertThat(adapters)
.hasSize(addedExtensions);
}
private static CoreExtension newCoreExtension() {
return newCoreExtension(t -> {
});
}
private static CoreExtension newCoreExtension(Consumer<CoreExtension.Context> loadImplementation) {
CoreExtension res = mock(CoreExtension.class);
when(res.getName()).thenReturn("name_" + name_counter);
name_counter++;
doAnswer(invocation -> {
CoreExtension.Context context = invocation.getArgument(0);
loadImplementation.accept(context);
return null;
}).when(res).load(any());
return res;
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WestSide {
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface EastSide {
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface OtherSide {
}
@WestSide
public static class WestSideClass {
}
@EastSide
public static class EastSideClass {
}
@OtherSide
public static class OtherSideClass {
}
@WestSide
@EastSide
public static class Latitude {
}
@Property(key = "eastKey", name = "eastName")
@EastSide
public static class EastSidePropertyDefinition {
}
@Property(key = "otherKey", name = "otherName")
@OtherSide
public static class OtherSidePropertyDefinition {
}
@Property(key = "blankKey", name = "blankName")
public static class BlankPropertyDefinition {
}
}
| 12,643 | 41.146667 | 173 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/extension/CoreExtensionsLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.extension;
import com.google.common.collect.ImmutableSet;
import java.util.Collections;
import java.util.Random;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class CoreExtensionsLoaderTest {
private CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class);
private ServiceLoaderWrapper serviceLoaderWrapper = mock(ServiceLoaderWrapper.class);
private CoreExtensionsLoader underTest = new CoreExtensionsLoader(coreExtensionRepository, serviceLoaderWrapper);
@Test
public void load_has_no_effect_if_there_is_no_ServiceLoader_for_CoreExtension_class() {
when(serviceLoaderWrapper.load(any())).thenReturn(Collections.emptySet());
underTest.load();
verify(serviceLoaderWrapper).load(CoreExtensionsLoader.class.getClassLoader());
verify(coreExtensionRepository).setLoadedCoreExtensions(Collections.emptySet());
verifyNoMoreInteractions(serviceLoaderWrapper, coreExtensionRepository);
}
@Test
public void load_sets_loaded_core_extensions_into_repository() {
Set<CoreExtension> coreExtensions = IntStream.range(0, 1 + new Random().nextInt(5))
.mapToObj(i -> newCoreExtension("core_ext_" + i))
.collect(Collectors.toSet());
when(serviceLoaderWrapper.load(any())).thenReturn(coreExtensions);
underTest.load();
verify(serviceLoaderWrapper).load(CoreExtensionsLoader.class.getClassLoader());
verify(coreExtensionRepository).setLoadedCoreExtensions(coreExtensions);
verifyNoMoreInteractions(serviceLoaderWrapper, coreExtensionRepository);
}
@Test
public void load_fails_with_ISE_if_multiple_core_extensions_declare_same_name() {
Set<CoreExtension> coreExtensions = ImmutableSet.of(newCoreExtension("a"), newCoreExtension("a"));
when(serviceLoaderWrapper.load(any())).thenReturn(coreExtensions);
assertThatThrownBy(() -> underTest.load())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Multiple core extensions declare the following names: a");
}
@Test
public void load_fails_with_ISE_if_multiple_core_extensions_declare_same_names() {
Set<CoreExtension> coreExtensions = ImmutableSet.of(newCoreExtension("a"), newCoreExtension("a"), newCoreExtension("b"), newCoreExtension("b"));
when(serviceLoaderWrapper.load(any())).thenReturn(coreExtensions);
assertThatThrownBy(() -> underTest.load())
.isInstanceOf(IllegalStateException.class)
.hasMessage("Multiple core extensions declare the following names: a, b");
}
private static CoreExtension newCoreExtension(String name) {
CoreExtension res = mock(CoreExtension.class);
when(res.getName()).thenReturn(name);
return res;
}
}
| 3,902 | 40.521277 | 148 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/hash/LineRangeTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.hash;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class LineRangeTest {
@Test
public void should_throw_ISE_if_range_is_invalid() {
assertThatThrownBy(() -> new LineRange(2, 1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Line range is not valid: 1 must be greater or equal than 2");
}
@Test
public void should_throw_ISE_if_startOffset_is_invalid() {
assertThatThrownBy(() -> new LineRange(-1, 1))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Start offset not valid: -1");
}
@Test
public void check_getters() {
LineRange range = new LineRange(1, 2);
assertThat(range.startOffset()).isOne();
assertThat(range.endOffset()).isEqualTo(2);
}
}
| 1,711 | 33.24 | 80 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/hash/SourceHashComputerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.hash;
import java.nio.charset.StandardCharsets;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class SourceHashComputerTest {
private static final String SOME_LINE = "some line";
@Test
public void hash_of_non_last_line_is_not_the_same_as_hash_of_last_line() {
assertThat(hashASingleLine(SOME_LINE, true)).isNotEqualTo(hashASingleLine(SOME_LINE, false));
}
@Test
public void hash_of_non_last_line_is_includes_an_added_line_return() {
assertThat(hashASingleLine(SOME_LINE, true)).isEqualTo(hashASingleLine(SOME_LINE + '\n', false));
}
@Test
public void hash_is_md5_digest_of_UTF8_character_array_in_hexa_encoding() {
String someLineWithAccents = "yopa l\u00e9l\u00e0";
assertThat(hashASingleLine(someLineWithAccents, false))
.isEqualTo(DigestUtils.md5Hex(someLineWithAccents.getBytes(StandardCharsets.UTF_8)));
}
private static String hashASingleLine(String line, boolean hasNextLine) {
SourceHashComputer sourceHashComputer = new SourceHashComputer();
sourceHashComputer.addLine(line, hasNextLine);
return sourceHashComputer.getHash();
}
}
| 2,066 | 35.263158 | 101 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/hash/SourceLinesHashesComputerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.hash;
import java.nio.charset.StandardCharsets;
import javax.annotation.Nullable;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class SourceLinesHashesComputerTest {
@Test
public void addLine_throws_NPE_is_line_null() {
assertThatThrownBy(() -> new SourceLineHashesComputer(1).addLine(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("line can not be null");
}
@Test
public void hash_of_empty_string_is_empty_string() {
assertThat(hashSingleLine("")).isEmpty();
}
@Test
public void tab_and_spaces_are_ignored_from_hash() {
assertThat(hashSingleLine(" ")).isEmpty();
assertThat(hashSingleLine("\t")).isEmpty();
assertThat(hashSingleLine("\t \t \t\t ")).isEmpty();
String abHash = hashSingleLine("ab");
assertThat(hashSingleLine("a b")).isEqualTo(abHash);
assertThat(hashSingleLine("a\tb")).isEqualTo(abHash);
assertThat(hashSingleLine("\t a\t \tb\t ")).isEqualTo(abHash);
}
@Test
public void hash_of_line_is_md5_of_UTF_char_array_as_an_hex_string() {
String lineWithAccentAndSpace = "Yolo lélà";
assertThat(hashSingleLine(lineWithAccentAndSpace)).isEqualTo(
DigestUtils.md5Hex("Yololélà".getBytes(StandardCharsets.UTF_8)));
}
@Test
public void getLineHashes_returns_line_hash_in_order_of_addLine_calls() {
String line1 = "line 1";
String line2 = "line 1 + 1";
String line3 = "line 10 - 7";
SourceLineHashesComputer underTest = new SourceLineHashesComputer();
underTest.addLine(line1);
underTest.addLine(line2);
underTest.addLine(line3);
assertThat(underTest.getLineHashes()).containsExactly(
hashSingleLine(line1), hashSingleLine(line2), hashSingleLine(line3));
}
private static String hashSingleLine(@Nullable String line) {
SourceLineHashesComputer sourceLinesHashesComputer = new SourceLineHashesComputer(1);
sourceLinesHashesComputer.addLine(line);
return sourceLinesHashesComputer.getLineHashes().iterator().next();
}
}
| 3,022 | 34.988095 | 89 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/i18n/DefaultI18nTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.i18n;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import org.junit.Before;
import org.junit.Test;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.api.utils.DateUtils;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultI18nTest {
private TestSystem2 system2 = new TestSystem2();
private DefaultI18n underTest;
@Before
public void before() {
PluginRepository pluginRepository = mock(PluginRepository.class);
List<PluginInfo> plugins = Arrays.asList(newPlugin("sqale"), newPlugin("frpack"), newPlugin("checkstyle"), newPlugin("other"));
when(pluginRepository.getPluginInfos()).thenReturn(plugins);
underTest = new DefaultI18n(pluginRepository, system2);
underTest.doStart(getClass().getClassLoader());
}
@Test
public void load_core_bundle() {
assertThat(underTest.message(Locale.ENGLISH, "any", null)).isEqualTo("Any");
}
@Test
public void introspect_all_available_properties() {
assertThat(underTest.getPropertyKeys().contains("any")).isTrue();
// Only in english
assertThat(underTest.getPropertyKeys().contains("assignee")).isTrue();
assertThat(underTest.getPropertyKeys().contains("sqale.page")).isTrue();
assertThat(underTest.getPropertyKeys().contains("bla_bla_bla")).isFalse();
}
@Test
public void all_core_metrics_are_in_core_bundle() {
List<Metric> coreMetrics = CoreMetrics.getMetrics();
List<String> incorrectMetricDefinitions = new ArrayList<>();
for (Metric metric : coreMetrics) {
if (metric.isHidden()) {
continue;
}
String metricNamePropertyKey = "metric." + metric.getKey() + ".name";
String l10nMetricName = underTest.message(Locale.ENGLISH, metricNamePropertyKey, null);
if (l10nMetricName == null) {
incorrectMetricDefinitions.add(metricNamePropertyKey + "=" + metric.getName());
} else if (!l10nMetricName.equals(metric.getName())) {
incorrectMetricDefinitions.add(metricNamePropertyKey + " is not consistent in core bundle and CoreMetrics");
}
String metricDescriptionPropertyKey = "metric." + metric.getKey() + ".description";
String l10nMetricDescription = underTest.message(Locale.ENGLISH, metricDescriptionPropertyKey, null);
if (l10nMetricDescription == null) {
incorrectMetricDefinitions.add(metricDescriptionPropertyKey + "=" + metric.getDescription());
} else if (!l10nMetricDescription.equals(metric.getDescription())) {
incorrectMetricDefinitions.add(metricDescriptionPropertyKey + " is not consistent in core bundle and CoreMetrics");
}
}
assertThat(incorrectMetricDefinitions).as("Metric definitions to fix in core bundle", incorrectMetricDefinitions.size()).isEmpty();
}
@Test
public void get_english_labels() {
assertThat(underTest.message(Locale.ENGLISH, "any", null)).isEqualTo("Any");
assertThat(underTest.message(Locale.ENGLISH, "sqale.page", null)).isEqualTo("Sqale page title");
assertThat(underTest.message(Locale.ENGLISH, "checkstyle.rule1.name", null)).isEqualTo("Rule one");
}
// SONAR-2927
@Test
public void get_english_labels_when_default_locale_is_not_english() {
Locale defaultLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.FRENCH);
assertThat(underTest.message(Locale.ENGLISH, "any", null)).isEqualTo("Any");
assertThat(underTest.message(Locale.ENGLISH, "sqale.page", null)).isEqualTo("Sqale page title");
assertThat(underTest.message(Locale.ENGLISH, "checkstyle.rule1.name", null)).isEqualTo("Rule one");
} finally {
Locale.setDefault(defaultLocale);
}
}
@Test
public void get_labels_from_french_pack() {
assertThat(underTest.message(Locale.FRENCH, "checkstyle.rule1.name", null)).isEqualTo("Rule un");
assertThat(underTest.message(Locale.FRENCH, "any", null)).isEqualTo("Tous");
// language pack
assertThat(underTest.message(Locale.FRENCH, "sqale.page", null)).isEqualTo("Titre de la page Sqale");
}
@Test
public void get_french_label_if_swiss_country() {
Locale swiss = new Locale("fr", "CH");
assertThat(underTest.message(swiss, "checkstyle.rule1.name", null)).isEqualTo("Rule un");
assertThat(underTest.message(swiss, "any", null)).isEqualTo("Tous");
// language pack
assertThat(underTest.message(swiss, "sqale.page", null)).isEqualTo("Titre de la page Sqale");
}
@Test
public void fallback_to_default_locale() {
assertThat(underTest.message(Locale.CHINA, "checkstyle.rule1.name", null)).isEqualTo("Rule one");
assertThat(underTest.message(Locale.CHINA, "any", null)).isEqualTo("Any");
assertThat(underTest.message(Locale.CHINA, "sqale.page", null)).isEqualTo("Sqale page title");
assertThat(underTest.getEffectiveLocale(Locale.CHINA)).isEqualTo(Locale.ENGLISH);
}
@Test
public void return_default_value_if_missing_key() {
assertThat(underTest.message(Locale.ENGLISH, "bla_bla_bla", "default")).isEqualTo("default");
assertThat(underTest.message(Locale.FRENCH, "bla_bla_bla", "default")).isEqualTo("default");
}
@Test
public void format_message_with_parameters() {
assertThat(underTest.message(Locale.ENGLISH, "x_results", null, "10")).isEqualTo("10 results");
}
@Test
public void use_default_locale_if_missing_value_in_localized_bundle() {
assertThat(underTest.message(Locale.FRENCH, "assignee", null)).isEqualTo("Assignee");
assertThat(underTest.message(Locale.CHINA, "assignee", null)).isEqualTo("Assignee");
}
@Test
public void return_null_if_file_not_found() {
String html = underTest.messageFromFile(Locale.ENGLISH, "UnknownRule.html", "checkstyle.rule1.name");
assertThat(html).isNull();
}
@Test
public void return_null_if_rule_not_internationalized() {
String html = underTest.messageFromFile(Locale.ENGLISH, "UnknownRule.html", "foo.rule1.name");
assertThat(html).isNull();
}
@Test
public void get_age_with_duration() {
assertThat(underTest.age(Locale.ENGLISH, 10)).isEqualTo("less than a minute");
}
@Test
public void get_age_with_dates() {
assertThat(underTest.age(Locale.ENGLISH, DateUtils.parseDate("2014-01-01"), DateUtils.parseDate("2014-01-02"))).isEqualTo("a day");
}
@Test
public void get_age_from_now() {
system2.setNow(DateUtils.parseDate("2014-01-02").getTime());
assertThat(underTest.ageFromNow(Locale.ENGLISH, DateUtils.parseDate("2014-01-01"))).isEqualTo("a day");
}
@Test
public void format_date_time() {
TimeZone initialTz = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("GMT+1"));
assertThat(underTest.formatDateTime(Locale.ENGLISH, DateUtils.parseDateTime("2014-01-22T19:10:03+0100"))).startsWith("Jan 22, 2014");
TimeZone.setDefault(initialTz);
}
@Test
public void format_date() {
TimeZone initialTz = TimeZone.getDefault();
TimeZone.setDefault(TimeZone.getTimeZone("GMT+1"));
assertThat(underTest.formatDate(Locale.ENGLISH, DateUtils.parseDateTime("2014-01-22T19:10:03+0100"))).isEqualTo("Jan 22, 2014");
TimeZone.setDefault(initialTz);
}
@Test
public void format_double() {
assertThat(underTest.formatDouble(Locale.FRENCH, 10.56)).isEqualTo("10,6");
assertThat(underTest.formatDouble(Locale.FRENCH, 10d)).isEqualTo("10,0");
}
@Test
public void format_integer() {
assertThat(underTest.formatInteger(Locale.ENGLISH, 10)).isEqualTo("10");
assertThat(underTest.formatInteger(Locale.ENGLISH, 100000)).isEqualTo("100,000");
}
private PluginInfo newPlugin(String key) {
PluginInfo plugin = mock(PluginInfo.class);
when(plugin.getKey()).thenReturn(key);
return plugin;
}
}
| 8,890 | 38.515556 | 137 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/i18n/DurationLabelTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.i18n;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(MockitoJUnitRunner.class)
public class DurationLabelTest {
// One second in milliseconds
private static final long SECOND = 1000;
// One minute in milliseconds
private static final long MINUTE = 60 * SECOND;
// One hour in milliseconds
private static final long HOUR = 60 * MINUTE;
// One day in milliseconds
private static final long DAY = 24 * HOUR;
// 30 days in milliseconds
private static final long MONTH = 30 * DAY;
// 365 days in milliseconds
private static final long YEAR = 365 * DAY;
@Test
public void age_in_seconds() {
long now = System.currentTimeMillis();
DurationLabel.Result result = DurationLabel.label(now - System.currentTimeMillis());
assertThat(result.key()).isEqualTo("duration.seconds");
assertThat(result.value()).isNull();
}
@Test
public void age_in_minute() {
DurationLabel.Result result = DurationLabel.label(now() - ago(MINUTE));
assertThat(result.key()).isEqualTo("duration.minute");
assertThat(result.value()).isNull();
}
@Test
public void age_in_minutes() {
long minutes = 2;
DurationLabel.Result result = DurationLabel.label(now() - ago(minutes * MINUTE));
assertThat(result.key()).isEqualTo("duration.minutes");
assertThat(result.value()).isEqualTo(minutes);
}
@Test
public void age_in_hour() {
DurationLabel.Result result = DurationLabel.label(now() - ago(HOUR));
assertThat(result.key()).isEqualTo("duration.hour");
assertThat(result.value()).isNull();
}
@Test
public void age_in_hours() {
long hours = 3;
DurationLabel.Result result = DurationLabel.label(now() - ago(hours * HOUR));
assertThat(result.key()).isEqualTo("duration.hours");
assertThat(result.value()).isEqualTo(hours);
}
@Test
public void age_in_day() {
DurationLabel.Result result = DurationLabel.label(now() - ago(30 * HOUR));
assertThat(result.key()).isEqualTo("duration.day");
assertThat(result.value()).isNull();
}
@Test
public void age_in_days() {
long days = 4;
DurationLabel.Result result = DurationLabel.label(now() - ago(days * DAY));
assertThat(result.key()).isEqualTo("duration.days");
assertThat(result.value()).isEqualTo(days);
}
@Test
public void age_in_month() {
DurationLabel.Result result = DurationLabel.label(now() - ago(35 * DAY));
assertThat(result.key()).isEqualTo("duration.month");
assertThat(result.value()).isNull();
}
@Test
public void age_in_months() {
long months = 2;
DurationLabel.Result result = DurationLabel.label(now() - ago(months * MONTH));
assertThat(result.key()).isEqualTo("duration.months");
assertThat(result.value()).isEqualTo(months);
}
@Test
public void year_ago() {
DurationLabel.Result result = DurationLabel.label(now() - ago(14 * MONTH));
assertThat(result.key()).isEqualTo("duration.year");
assertThat(result.value()).isNull();
}
@Test
public void years_ago() {
long years = 7;
DurationLabel.Result result = DurationLabel.label(now() - ago(years * YEAR));
assertThat(result.key()).isEqualTo("duration.years");
assertThat(result.value()).isEqualTo(years);
}
private long ago(long offset) {
return System.currentTimeMillis() - offset;
}
private long now() {
// Add 5 seconds in order to have zero false positive
return System.currentTimeMillis() + 5000;
}
}
| 4,437 | 30.034965 | 88 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/i18n/I18nClassloaderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.i18n;
import com.google.common.collect.Lists;
import java.net.URL;
import java.net.URLClassLoader;
import org.junit.Before;
import org.junit.Test;
import org.sonar.core.platform.PluginRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
public class I18nClassloaderTest {
private I18nClassloader i18nClassloader;
@Before
public void init() {
i18nClassloader = new I18nClassloader(mock(PluginRepository.class));
}
@Test
public void aggregate_plugin_classloaders() {
URLClassLoader checkstyle = newCheckstyleClassloader();
I18nClassloader i18nClassloader = new I18nClassloader(Lists.newArrayList(checkstyle));
assertThat(i18nClassloader.getResource("org/sonar/l10n/checkstyle.properties")).isNotNull();
assertThat(i18nClassloader.getResource("org/sonar/l10n/checkstyle.properties").getFile()).endsWith("checkstyle.properties");
}
@Test
public void contain_its_own_classloader() {
assertThat(i18nClassloader.getResource("org/sonar/l10n/core.properties")).isNotNull();
}
@Test
public void return_null_if_resource_not_found() {
assertThat(i18nClassloader.getResource("org/unknown.properties")).isNull();
}
@Test
public void not_support_lookup_of_java_classes() throws ClassNotFoundException {
assertThatThrownBy(() -> i18nClassloader.loadClass("java.lang.String"))
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void override_toString() {
assertThat(i18nClassloader).hasToString("i18n-classloader");
}
private static URLClassLoader newCheckstyleClassloader() {
return newClassLoader("/org/sonar/core/i18n/I18nClassloaderTest/");
}
private static URLClassLoader newClassLoader(String... resourcePaths) {
URL[] urls = new URL[resourcePaths.length];
for (int index = 0; index < resourcePaths.length; index++) {
urls[index] = I18nClassloaderTest.class.getResource(resourcePaths[index]);
}
return new URLClassLoader(urls);
}
}
| 2,952 | 34.578313 | 128 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/issue/DefaultIssueTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.issue;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.sonar.api.utils.Duration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DefaultIssueTest {
private final DefaultIssue issue = new DefaultIssue();
@Test
public void set_empty_dates() {
issue
.setCreationDate(null)
.setUpdateDate(null)
.setCloseDate(null)
.setSelectedAt(null);
assertThat(issue.creationDate()).isNull();
assertThat(issue.updateDate()).isNull();
assertThat(issue.closeDate()).isNull();
assertThat(issue.selectedAt()).isNull();
}
@Test
public void fail_on_empty_status() {
try {
issue.setStatus("");
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Status must be set");
}
}
@Test
public void fail_on_bad_severity() {
try {
issue.setSeverity("FOO");
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Not a valid severity: FOO");
}
}
@Test
public void message_should_be_abbreviated_if_too_long() {
issue.setMessage(StringUtils.repeat("a", 5_000));
assertThat(issue.message()).hasSize(1_333);
}
@Test
public void message_could_be_null() {
issue.setMessage(null);
assertThat(issue.message()).isNull();
}
@Test
public void test_nullable_fields() {
issue.setGap(null).setSeverity(null).setLine(null);
assertThat(issue.gap()).isNull();
assertThat(issue.severity()).isNull();
assertThat(issue.line()).isNull();
}
@Test
public void test_equals_and_hashCode() {
DefaultIssue a1 = new DefaultIssue().setKey("AAA");
DefaultIssue a2 = new DefaultIssue().setKey("AAA");
DefaultIssue b = new DefaultIssue().setKey("BBB");
assertThat(a1)
.isEqualTo(a1)
.isEqualTo(a2)
.isNotEqualTo(b)
.hasSameHashCodeAs(a1);
}
@Test
public void comments_should_not_be_modifiable() {
DefaultIssue issue = new DefaultIssue().setKey("AAA");
List<DefaultIssueComment> comments = issue.defaultIssueComments();
assertThat(comments).isEmpty();
DefaultIssueComment defaultIssueComment = new DefaultIssueComment();
try {
comments.add(defaultIssueComment);
fail();
} catch (UnsupportedOperationException e) {
// ok
} catch (Exception e) {
fail("Unexpected exception: " + e);
}
}
@Test
public void all_changes_contain_current_change() {
IssueChangeContext issueChangeContext = mock(IssueChangeContext.class);
when(issueChangeContext.getExternalUser()).thenReturn("toto");
when(issueChangeContext.getWebhookSource()).thenReturn("github");
DefaultIssue issue = new DefaultIssue()
.setKey("AAA")
.setFieldChange(issueChangeContext, "actionPlan", "1.0", "1.1");
assertThat(issue.changes()).hasSize(1);
FieldDiffs actualDiffs = issue.changes().iterator().next();
assertThat(actualDiffs.externalUser()).contains(issueChangeContext.getExternalUser());
assertThat(actualDiffs.webhookSource()).contains(issueChangeContext.getWebhookSource());
}
@Test
public void setFieldChange_whenAddingChange_shouldUpdateCurrentChange() {
IssueChangeContext issueChangeContext = mock(IssueChangeContext.class);
DefaultIssue issue = new DefaultIssue().setKey("AAA");
issue.setFieldChange(issueChangeContext, "actionPlan", "1.0", "1.1");
assertThat(issue.changes()).hasSize(1);
FieldDiffs currentChange = issue.currentChange();
assertThat(currentChange).isNotNull();
assertThat(currentChange.get("actionPlan")).isNotNull();
assertThat(currentChange.get("authorLogin")).isNull();
issue.setFieldChange(issueChangeContext, "authorLogin", null, "testuser");
assertThat(issue.changes()).hasSize(1);
assertThat(currentChange.get("actionPlan")).isNotNull();
assertThat(currentChange.get("authorLogin")).isNotNull();
assertThat(currentChange.get("authorLogin").newValue()).isEqualTo("testuser");
}
@Test
public void adding_null_change_has_no_effect() {
DefaultIssue issue = new DefaultIssue();
issue.addChange(null);
assertThat(issue.changes()).isEmpty();
}
@Test
public void test_isToBeMigratedAsNewCodeReferenceIssue_is_correctly_calculated() {
issue.setKey("ABCD")
.setIsOnChangedLine(true)
.setIsNewCodeReferenceIssue(false)
.setIsNoLongerNewCodeReferenceIssue(false);
assertThat(issue.isToBeMigratedAsNewCodeReferenceIssue()).isTrue();
issue.setKey("ABCD")
.setIsOnChangedLine(false)
.setIsNewCodeReferenceIssue(false)
.setIsNoLongerNewCodeReferenceIssue(false);
assertThat(issue.isToBeMigratedAsNewCodeReferenceIssue()).isFalse();
issue.setKey("ABCD")
.setIsOnChangedLine(true)
.setIsNewCodeReferenceIssue(true)
.setIsNoLongerNewCodeReferenceIssue(false);
assertThat(issue.isToBeMigratedAsNewCodeReferenceIssue()).isFalse();
issue.setKey("ABCD")
.setIsOnChangedLine(false)
.setIsNewCodeReferenceIssue(false)
.setIsNoLongerNewCodeReferenceIssue(true);
assertThat(issue.isToBeMigratedAsNewCodeReferenceIssue()).isFalse();
issue.setKey("ABCD")
.setIsOnChangedLine(true)
.setIsNewCodeReferenceIssue(true)
.setIsNoLongerNewCodeReferenceIssue(true);
assertThat(issue.isToBeMigratedAsNewCodeReferenceIssue()).isFalse();
issue.setKey("ABCD")
.setIsOnChangedLine(false)
.setIsNewCodeReferenceIssue(true)
.setIsNoLongerNewCodeReferenceIssue(true);
assertThat(issue.isToBeMigratedAsNewCodeReferenceIssue()).isFalse();
issue.setKey("ABCD")
.setIsOnChangedLine(true)
.setIsNewCodeReferenceIssue(false)
.setIsNoLongerNewCodeReferenceIssue(true);
assertThat(issue.isToBeMigratedAsNewCodeReferenceIssue()).isFalse();
}
@Test
public void isQuickFixAvailable_givenQuickFixAvailable_returnTrue() {
DefaultIssue defaultIssue = new DefaultIssue();
defaultIssue.setQuickFixAvailable(true);
assertThat(defaultIssue.isQuickFixAvailable()).isTrue();
defaultIssue.setQuickFixAvailable(false);
assertThat(defaultIssue.isQuickFixAvailable()).isFalse();
}
@Test
public void characteristic_shouldReturnNull() {
DefaultIssue defaultIssue = new DefaultIssue();
assertThat(defaultIssue.characteristic()).isNull();
}
@Test
public void setLine_whenLineIsNegative_shouldThrowException() {
int anyNegativeValue = Integer.MIN_VALUE;
assertThatThrownBy(() -> issue.setLine(anyNegativeValue))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("Line must be null or greater than zero (got %s)", anyNegativeValue));
}
@Test
public void setLine_whenLineIsZero_shouldThrowException() {
assertThatThrownBy(() -> issue.setLine(0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Line must be null or greater than zero (got 0)");
}
@Test
public void setGap_whenGapIsNegative_shouldThrowException() {
Double anyNegativeValue = -1.0;
assertThatThrownBy(() -> issue.setGap(anyNegativeValue))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage(String.format("Gap must be greater than or equal 0 (got %s)", anyNegativeValue));
}
@Test
public void setGap_whenGapIsZero_shouldWork() {
issue.setGap(0.0);
assertThat(issue.gap()).isEqualTo(0.0);
}
@Test
public void effortInMinutes_shouldConvertEffortToMinutes() {
issue.setEffort(Duration.create(60));
assertThat(issue.effortInMinutes()).isEqualTo(60L);
}
@Test
public void effortInMinutes_whenNull_shouldReturnNull() {
issue.setEffort(null);
assertThat(issue.effortInMinutes()).isNull();
}
@Test
public void tags_whenNull_shouldReturnEmptySet() {
assertThat(issue.tags()).isEmpty();
}
@Test
public void codeVariants_whenNull_shouldReturnEmptySet() {
assertThat(issue.codeVariants()).isEmpty();
}
}
| 9,030 | 30.576923 | 102 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/issue/FieldDiffsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.issue;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class FieldDiffsTest {
private static final String NAME_WITH_RESERVED_CHARS = "name,with|reserved=chars:";
private static final String ENCODED_NAME_WITH_RESERVED_CHARS = "{base64:bmFtZSx3aXRofHJlc2VydmVkPWNoYXJzOg==}";
private FieldDiffs diffs = new FieldDiffs();
@Test
public void diffs_should_be_empty_by_default() {
assertThat(diffs.diffs()).isEmpty();
}
@Test
public void test_diff() {
diffs.setDiff("severity", "BLOCKER", "INFO");
diffs.setDiff("resolution", "OPEN", "FIXED");
assertThat(diffs.diffs()).hasSize(2);
FieldDiffs.Diff diff = diffs.diffs().get("severity");
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("INFO");
diff = diffs.diffs().get("resolution");
assertThat(diff.oldValue()).isEqualTo("OPEN");
assertThat(diff.newValue()).isEqualTo("FIXED");
}
@Test
public void diff_with_long_values() {
diffs.setDiff("technicalDebt", 50L, "100");
FieldDiffs.Diff diff = diffs.diffs().get("technicalDebt");
assertThat(diff.oldValueLong()).isEqualTo(50L);
assertThat(diff.newValueLong()).isEqualTo(100L);
}
@Test
public void diff_with_empty_long_values() {
diffs.setDiff("technicalDebt", null, "");
FieldDiffs.Diff diff = diffs.diffs().get("technicalDebt");
assertThat(diff.oldValueLong()).isNull();
assertThat(diff.newValueLong()).isNull();
}
@Test
public void diff_with_assignee() {
diffs.setDiff("assignee", "oldAssignee", NAME_WITH_RESERVED_CHARS);
FieldDiffs.Diff diff = diffs.diffs().get("assignee");
assertThat(diff.oldValue()).isEqualTo("oldAssignee");
assertThat(diff.newValue()).isEqualTo(NAME_WITH_RESERVED_CHARS);
}
@Test
public void get() {
diffs.setDiff("severity", "BLOCKER", "INFO");
FieldDiffs.Diff diff = diffs.get("severity");
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("INFO");
}
@Test
public void get_with_assignee() {
diffs.setDiff("assignee", "oldAssignee", NAME_WITH_RESERVED_CHARS);
FieldDiffs.Diff diff = diffs.get("assignee");
assertThat(diff.oldValue()).isEqualTo("oldAssignee");
assertThat(diff.newValue()).isEqualTo(NAME_WITH_RESERVED_CHARS);
}
@Test
public void test_diff_by_key() {
diffs.setDiff("severity", "BLOCKER", "INFO");
diffs.setDiff("resolution", "OPEN", "FIXED");
assertThat(diffs.diffs()).hasSize(2);
FieldDiffs.Diff diff = diffs.diffs().get("severity");
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("INFO");
diff = diffs.diffs().get("resolution");
assertThat(diff.oldValue()).isEqualTo("OPEN");
assertThat(diff.newValue()).isEqualTo("FIXED");
}
@Test
public void should_keep_old_value() {
diffs.setDiff("severity", "BLOCKER", "INFO");
diffs.setDiff("severity", null, "MAJOR");
FieldDiffs.Diff diff = diffs.diffs().get("severity");
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("MAJOR");
}
@Test
public void test_toString() {
diffs.setWebhookSource("github");
diffs.setExternalUser("toto");
diffs.setDiff("severity", "BLOCKER", "INFO");
diffs.setDiff("resolution", "OPEN", "FIXED");
assertThat(diffs).hasToString("webhookSource=github,externalUser=toto,severity=BLOCKER|INFO,resolution=OPEN|FIXED");
}
@Test
public void test_toEncodedString() {
diffs.setDiff("assignee", "oldAssignee", NAME_WITH_RESERVED_CHARS);
diffs.setDiff("resolution", "OPEN", "FIXED");
assertThat(diffs.toEncodedString()).isEqualTo("assignee=oldAssignee|" + ENCODED_NAME_WITH_RESERVED_CHARS + ",resolution=OPEN|FIXED");
}
@Test
public void test_toString_with_null_values() {
diffs.setDiff("severity", null, "INFO");
diffs.setDiff("assignee", "user1", null);
assertThat(diffs).hasToString("severity=INFO,assignee=user1|");
}
@Test
public void test_parse() {
diffs = FieldDiffs.parse("severity=BLOCKER|INFO,webhookSource=github,resolution=OPEN|FIXED,donut=|new,gambas=miam,acme=old|,externalUser=charlie");
assertThat(diffs.diffs()).hasSize(5);
assertThat(diffs.webhookSource()).contains("github");
assertThat(diffs.externalUser()).contains("charlie");
FieldDiffs.Diff diff = diffs.diffs().get("severity");
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("INFO");
diff = diffs.diffs().get("resolution");
assertThat(diff.oldValue()).isEqualTo("OPEN");
assertThat(diff.newValue()).isEqualTo("FIXED");
diff = diffs.diffs().get("donut");
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("new");
diff = diffs.diffs().get("gambas");
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("miam");
diff = diffs.diffs().get("acme");
assertThat(diff.oldValue()).isEqualTo("old");
assertThat(diff.newValue()).isNull();
}
@Test
public void test_parse_encoded_assignee() {
diffs = FieldDiffs.parse("severity=BLOCKER|INFO,assignee=oldValue|" + ENCODED_NAME_WITH_RESERVED_CHARS);
assertThat(diffs.diffs()).hasSize(2);
FieldDiffs.Diff diff = diffs.diffs().get("severity");
assertThat(diff.oldValue()).isEqualTo("BLOCKER");
assertThat(diff.newValue()).isEqualTo("INFO");
diff = diffs.diffs().get("assignee");
assertThat(diff.oldValue()).isEqualTo("oldValue");
assertThat(diff.newValue()).isEqualTo(NAME_WITH_RESERVED_CHARS);
}
@Test
public void test_parse_empty_values() {
diffs = FieldDiffs.parse("severity=INFO,resolution=,webhookSource=,externalUser=");
assertThat(diffs.externalUser()).isEmpty();
assertThat(diffs.webhookSource()).isEmpty();
assertThat(diffs.diffs()).hasSize(2);
FieldDiffs.Diff diff = diffs.diffs().get("severity");
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isEqualTo("INFO");
diff = diffs.diffs().get("resolution");
assertThat(diff.oldValue()).isNull();
assertThat(diff.newValue()).isNull();
}
@Test
public void test_parse_null() {
diffs = FieldDiffs.parse(null);
assertThat(diffs.diffs()).isEmpty();
}
@Test
public void test_parse_empty() {
diffs = FieldDiffs.parse("");
assertThat(diffs.diffs()).isEmpty();
}
}
| 7,323 | 31.990991 | 151 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/issue/IssueChangeContextTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.issue;
import java.util.Date;
import java.util.Objects;
import javax.annotation.Nullable;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByScanBuilder;
import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder;
public class IssueChangeContextTest {
private static final Date NOW = new Date();
private static final String USER_UUID = "user_uuid";
private static final String EXTERNAL_USER = "toto@tata.com";
private static final String WEBHOOK_SOURCE = "github";
private IssueChangeContext context;
@Test
public void test_issueChangeContextByScanBuilder() {
context = issueChangeContextByScanBuilder(NOW).build();
verifyContext(true, false, null, null, null);
}
@Test
public void test_issueChangeContextByUserBuilder() {
context = issueChangeContextByUserBuilder(NOW, USER_UUID).build();
verifyContext(false, false, USER_UUID, null, null);
}
@Test
public void test_newBuilder() {
context = IssueChangeContext.newBuilder()
.withScan()
.withRefreshMeasures()
.setUserUuid(USER_UUID)
.setDate(NOW)
.setExternalUser(EXTERNAL_USER)
.setWebhookSource(WEBHOOK_SOURCE)
.build();
verifyContext(true, true, USER_UUID, EXTERNAL_USER, WEBHOOK_SOURCE);
}
@Test
public void test_equal() {
context = IssueChangeContext.newBuilder()
.setUserUuid(USER_UUID)
.setDate(NOW)
.setExternalUser(EXTERNAL_USER)
.setWebhookSource(WEBHOOK_SOURCE)
.build();
IssueChangeContext equalContext = IssueChangeContext.newBuilder()
.setUserUuid(USER_UUID)
.setDate(NOW)
.setExternalUser(EXTERNAL_USER)
.setWebhookSource(WEBHOOK_SOURCE)
.build();
IssueChangeContext notEqualContext = IssueChangeContext.newBuilder().setUserUuid("other_user_uuid").setDate(NOW).build();
assertThat(context).isEqualTo(context)
.isEqualTo(equalContext)
.isNotEqualTo(notEqualContext)
.isNotEqualTo(null)
.isNotEqualTo(new Object());
}
@Test
public void test_hashCode() {
context = IssueChangeContext.newBuilder().setUserUuid(USER_UUID).setDate(NOW).build();
assertThat(context.hashCode()).isEqualTo(Objects.hash(USER_UUID, NOW, false, false, null, null));
}
private void verifyContext(boolean scan, boolean refreshMeasures, @Nullable String userUuid, @Nullable String externalUser,
@Nullable String webhookSource) {
assertThat(context.userUuid()).isEqualTo(userUuid);
assertThat(context.date()).isEqualTo(NOW);
assertThat(context.scan()).isEqualTo(scan);
assertThat(context.refreshMeasures()).isEqualTo(refreshMeasures);
assertThat(context.getExternalUser()).isEqualTo(externalUser);
assertThat(context.getWebhookSource()).isEqualTo(webhookSource);
}
}
| 3,759 | 33.495413 | 125 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/issue/tracking/AbstractTrackerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.issue.tracking;
import java.util.function.Function;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import org.sonar.core.issue.tracking.AbstractTracker.LineAndLineHashAndMessage;
import org.sonar.core.issue.tracking.AbstractTracker.LineAndLineHashKey;
import org.sonar.core.issue.tracking.AbstractTracker.LineAndMessageKey;
import org.sonar.core.issue.tracking.AbstractTracker.LineHashAndMessageKey;
import org.sonar.core.issue.tracking.AbstractTracker.LineHashKey;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AbstractTrackerTest {
private final Trackable base = trackable(RuleKey.of("r1", "r1"), 0, "m1", "hash1");
private final Trackable same = trackable(RuleKey.of("r1", "r1"), 0, "m1", "hash1");
private final Trackable diffRule = trackable(RuleKey.of("r1", "r2"), 0, "m1", "hash1");
private final Trackable diffMessage = trackable(RuleKey.of("r1", "r1"), 0, null, "hash1");
private final Trackable diffLineHash = trackable(RuleKey.of("r1", "r1"), 0, "m1", null);
private final Trackable diffLine = trackable(RuleKey.of("r1", "r1"), null, "m1", "hash1");
@Test
public void lineAndLineHashKey() {
Comparator comparator = new Comparator(LineAndLineHashKey::new);
comparator.sameEqualsAndHashcode(base, same);
comparator.sameEqualsAndHashcode(base, diffMessage);
comparator.differentEquals(base, diffRule);
comparator.differentEquals(base, diffLineHash);
comparator.differentEquals(base, diffLine);
}
@Test
public void lineAndLineHashAndMessage() {
Comparator comparator = new Comparator(LineAndLineHashAndMessage::new);
comparator.sameEqualsAndHashcode(base, same);
comparator.differentEquals(base, diffMessage);
comparator.differentEquals(base, diffRule);
comparator.differentEquals(base, diffLineHash);
comparator.differentEquals(base, diffLine);
}
@Test
public void lineHashAndMessageKey() {
Comparator comparator = new Comparator(LineHashAndMessageKey::new);
comparator.sameEqualsAndHashcode(base, same);
comparator.sameEqualsAndHashcode(base, diffLine);
comparator.differentEquals(base, diffMessage);
comparator.differentEquals(base, diffRule);
comparator.differentEquals(base, diffLineHash);
}
@Test
public void lineAndMessageKey() {
Comparator comparator = new Comparator(LineAndMessageKey::new);
comparator.sameEqualsAndHashcode(base, same);
comparator.sameEqualsAndHashcode(base, diffLineHash);
comparator.differentEquals(base, diffMessage);
comparator.differentEquals(base, diffRule);
comparator.differentEquals(base, diffLine);
}
@Test
public void lineHashKey() {
Comparator comparator = new Comparator(LineHashKey::new);
comparator.sameEqualsAndHashcode(base, same);
comparator.sameEqualsAndHashcode(base, diffLine);
comparator.sameEqualsAndHashcode(base, diffMessage);
comparator.differentEquals(base, diffRule);
comparator.differentEquals(base, diffLineHash);
}
private static Trackable trackable(RuleKey ruleKey, Integer line, String message, String lineHash) {
Trackable trackable = mock(Trackable.class);
when(trackable.getRuleKey()).thenReturn(ruleKey);
when(trackable.getLine()).thenReturn(line);
when(trackable.getMessage()).thenReturn(message);
when(trackable.getLineHash()).thenReturn(lineHash);
return trackable;
}
private static class Comparator {
private final Function<Trackable, AbstractTracker.SearchKey> searchKeyFactory;
private Comparator(Function<Trackable, AbstractTracker.SearchKey> searchKeyFactory) {
this.searchKeyFactory = searchKeyFactory;
}
private void sameEqualsAndHashcode(Trackable t1, Trackable t2) {
AbstractTracker.SearchKey k1 = searchKeyFactory.apply(t1);
AbstractTracker.SearchKey k2 = searchKeyFactory.apply(t2);
assertThat(k1).isEqualTo(k1);
assertThat(k1).isEqualTo(k2);
assertThat(k2).isEqualTo(k1);
assertThat(k1).hasSameHashCodeAs(k1);
assertThat(k1).hasSameHashCodeAs(k2);
assertThat(k2).hasSameHashCodeAs(k1);
}
private void differentEquals(Trackable t1, Trackable t2) {
AbstractTracker.SearchKey k1 = searchKeyFactory.apply(t1);
AbstractTracker.SearchKey k2 = searchKeyFactory.apply(t2);
assertThat(k1).isNotEqualTo(k2);
assertThat(k2).isNotEqualTo(k1);
assertThat(k1).isNotEqualTo(new Object());
assertThat(k1).isNotNull();
}
}
}
| 5,403 | 39.939394 | 102 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/issue/tracking/BlockHashSequenceTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.issue.tracking;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class BlockHashSequenceTest {
@Test
public void test() {
BlockHashSequence a = new BlockHashSequence(LineHashSequence.createForLines(asList("line0", "line1", "line2")), 1);
BlockHashSequence b = new BlockHashSequence(LineHashSequence.createForLines(asList("line0", "line1", "line2", "line3")), 1);
assertThat(a.getBlockHashForLine(1)).isEqualTo(b.getBlockHashForLine(1));
assertThat(a.getBlockHashForLine(2)).isEqualTo(b.getBlockHashForLine(2));
assertThat(a.getBlockHashForLine(3)).isNotEqualTo(b.getBlockHashForLine(3));
BlockHashSequence c = new BlockHashSequence(LineHashSequence.createForLines(asList("line-1", "line0", "line1", "line2", "line3")), 1);
assertThat(a.getBlockHashForLine(1)).isNotEqualTo(c.getBlockHashForLine(2));
assertThat(a.getBlockHashForLine(2)).isEqualTo(c.getBlockHashForLine(3));
}
}
| 1,866 | 42.418605 | 138 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/issue/tracking/BlockRecognizerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.issue.tracking;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class BlockRecognizerTest {
@Test
public void lengthOfMaximalBlock() {
/**
* - line 4 of first sequence is "d"
* - line 4 of second sequence is "d"
* - in each sequence, the 3 lines before and the line after are similar -> block size is 5
*/
assertThat(compute(seq("abcde"), seq("abcde"), 4, 4)).isEqualTo(5);
assertThat(compute(seq("abcde"), seq("abcd"), 4, 4)).isEqualTo(4);
assertThat(compute(seq("bcde"), seq("abcde"), 4, 4)).isZero();
assertThat(compute(seq("bcde"), seq("abcde"), 3, 4)).isEqualTo(4);
}
@Test
public void isOverLimit() {
assertThat(BlockRecognizer.isOverLimit(20, 40)).isFalse();
assertThat(BlockRecognizer.isOverLimit(3, 100_000)).isTrue();
// multiplication of these two ints is higher than Integer.MAX_VALUE
assertThat(BlockRecognizer.isOverLimit(50_000, 60_000)).isTrue();
}
private int compute(LineHashSequence seqA, LineHashSequence seqB, int ai, int bi) {
return BlockRecognizer.lengthOfMaximalBlock(seqA, ai, seqB, bi);
}
private static LineHashSequence seq(String text) {
List<String> hashes = new ArrayList<>();
for (int i = 0; i < text.length(); i++) {
hashes.add("" + text.charAt(i));
}
return new LineHashSequence(hashes);
}
}
| 2,295 | 33.787879 | 95 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/issue/tracking/TrackerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.issue.tracking;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import static java.util.Arrays.asList;
import static org.apache.commons.lang.StringUtils.trim;
import static org.assertj.core.api.Assertions.assertThat;
public class TrackerTest {
public static final RuleKey RULE_SYSTEM_PRINT = RuleKey.of("java", "SystemPrint");
public static final RuleKey RULE_UNUSED_LOCAL_VARIABLE = RuleKey.of("java", "UnusedLocalVariable");
public static final RuleKey RULE_UNUSED_PRIVATE_METHOD = RuleKey.of("java", "UnusedPrivateMethod");
public static final RuleKey RULE_NOT_DESIGNED_FOR_EXTENSION = RuleKey.of("java", "NotDesignedForExtension");
public static final RuleKey RULE_USE_DIAMOND = RuleKey.of("java", "UseDiamond");
public static final RuleKey RULE_MISSING_PACKAGE_INFO = RuleKey.of("java", "MissingPackageInfo");
Tracker<Issue, Issue> tracker = new Tracker<>();
/**
* Of course rule must match
*/
@Test
public void similar_issues_except_rule_do_not_match() {
FakeInput baseInput = new FakeInput("H1");
baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg");
FakeInput rawInput = new FakeInput("H1");
Issue raw = rawInput.createIssueOnLine(1, RULE_UNUSED_LOCAL_VARIABLE, "msg");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw)).isNull();
}
@Test
public void line_hash_has_greater_priority_than_line() {
FakeInput baseInput = new FakeInput("H1", "H2", "H3");
Issue base1 = baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg");
Issue base2 = baseInput.createIssueOnLine(3, RULE_SYSTEM_PRINT, "msg");
FakeInput rawInput = new FakeInput("a", "b", "H1", "H2", "H3");
Issue raw1 = rawInput.createIssueOnLine(3, RULE_SYSTEM_PRINT, "msg");
Issue raw2 = rawInput.createIssueOnLine(5, RULE_SYSTEM_PRINT, "msg");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw1)).isSameAs(base1);
assertThat(tracking.baseFor(raw2)).isSameAs(base2);
}
/**
* SONAR-2928
*/
@Test
public void no_lines_and_different_messages_match() {
FakeInput baseInput = new FakeInput("H1", "H2", "H3");
Issue base = baseInput.createIssue(RULE_SYSTEM_PRINT, "msg1");
FakeInput rawInput = new FakeInput("H10", "H11", "H12");
Issue raw = rawInput.createIssue(RULE_SYSTEM_PRINT, "msg2");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw)).isSameAs(base);
}
@Test
public void similar_issues_except_message_match() {
FakeInput baseInput = new FakeInput("H1");
Issue base = baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg1");
FakeInput rawInput = new FakeInput("H1");
Issue raw = rawInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg2");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw)).isSameAs(base);
}
@Test
public void similar_issues_if_trimmed_messages_match() {
FakeInput baseInput = new FakeInput("H1");
Issue base = baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, " message ");
FakeInput rawInput = new FakeInput("H2");
Issue raw = rawInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "message");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw)).isSameAs(base);
}
/**
* Source code of this line was changed, but line and message still match
*/
@Test
public void similar_issues_except_line_hash_match() {
FakeInput baseInput = new FakeInput("H1");
Issue base = baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg");
FakeInput rawInput = new FakeInput("H2");
Issue raw = rawInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw)).isSameAs(base);
}
@Test
public void similar_issues_except_line_match() {
FakeInput baseInput = new FakeInput("H1", "H2");
Issue base = baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg");
FakeInput rawInput = new FakeInput("H2", "H1");
Issue raw = rawInput.createIssueOnLine(2, RULE_SYSTEM_PRINT, "msg");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw)).isSameAs(base);
}
/**
* SONAR-2812
*/
@Test
public void only_same_line_hash_match_match() {
FakeInput baseInput = new FakeInput("H1", "H2");
Issue base = baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg");
FakeInput rawInput = new FakeInput("H3", "H4", "H1");
Issue raw = rawInput.createIssueOnLine(3, RULE_SYSTEM_PRINT, "other message");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw)).isSameAs(base);
}
@Test
public void do_not_fail_if_base_issue_without_line() {
FakeInput baseInput = new FakeInput("H1", "H2");
Issue base = baseInput.createIssueOnLine(1, RULE_SYSTEM_PRINT, "msg1");
FakeInput rawInput = new FakeInput("H3", "H4", "H5");
Issue raw = rawInput.createIssue(RULE_UNUSED_LOCAL_VARIABLE, "msg2");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw)).isNull();
assertThat(tracking.getUnmatchedBases()).containsOnly(base);
}
@Test
public void do_not_fail_if_raw_issue_without_line() {
FakeInput baseInput = new FakeInput("H1", "H2");
Issue base = baseInput.createIssue(RULE_SYSTEM_PRINT, "msg1");
FakeInput rawInput = new FakeInput("H3", "H4", "H5");
Issue raw = rawInput.createIssueOnLine(1, RULE_UNUSED_LOCAL_VARIABLE, "msg2");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw)).isNull();
assertThat(tracking.getUnmatchedBases()).containsOnly(base);
}
// SONAR-15091
@Test
public void do_not_fail_if_message_is_null() {
FakeInput baseInput = new FakeInput("H1", "H2");
Issue base = baseInput.createIssueOnLine(1, RULE_UNUSED_LOCAL_VARIABLE, null);
FakeInput rawInput = new FakeInput("H1", "H2");
Issue raw = rawInput.createIssueOnLine(1, RULE_UNUSED_LOCAL_VARIABLE, null);
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw)).isNotNull();
}
@Test
public void do_not_fail_if_raw_line_does_not_exist() {
FakeInput baseInput = new FakeInput();
FakeInput rawInput = new FakeInput("H1").addIssue(new Issue(200, "H200", RULE_SYSTEM_PRINT, "msg", org.sonar.api.issue.Issue.STATUS_OPEN, new Date()));
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.getUnmatchedRaws()).hasSize(1);
}
/**
* SONAR-3072
*/
@Test
public void recognize_blocks_1() {
FakeInput baseInput = FakeInput.createForSourceLines(
"package example1;",
"",
"public class Toto {",
"",
" public void doSomething() {",
" // doSomething",
" }",
"",
" public void doSomethingElse() {",
" // doSomethingElse",
" }",
"}");
Issue base1 = baseInput.createIssueOnLine(7, RULE_SYSTEM_PRINT, "Indentation");
Issue base2 = baseInput.createIssueOnLine(11, RULE_SYSTEM_PRINT, "Indentation");
FakeInput rawInput = FakeInput.createForSourceLines(
"package example1;",
"",
"public class Toto {",
"",
" public Toto(){}",
"",
" public void doSomethingNew() {",
" // doSomethingNew",
" }",
"",
" public void doSomethingElseNew() {",
" // doSomethingElseNew",
" }",
"",
" public void doSomething() {",
" // doSomething",
" }",
"",
" public void doSomethingElse() {",
" // doSomethingElse",
" }",
"}");
Issue raw1 = rawInput.createIssueOnLine(9, RULE_SYSTEM_PRINT, "Indentation");
Issue raw2 = rawInput.createIssueOnLine(13, RULE_SYSTEM_PRINT, "Indentation");
Issue raw3 = rawInput.createIssueOnLine(17, RULE_SYSTEM_PRINT, "Indentation");
Issue raw4 = rawInput.createIssueOnLine(21, RULE_SYSTEM_PRINT, "Indentation");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw1)).isNull();
assertThat(tracking.baseFor(raw2)).isNull();
assertThat(tracking.baseFor(raw3)).isSameAs(base1);
assertThat(tracking.baseFor(raw4)).isSameAs(base2);
assertThat(tracking.getUnmatchedBases()).isEmpty();
}
// SONAR-10194
@Test
public void no_match_if_only_same_rulekey() {
FakeInput baseInput = FakeInput.createForSourceLines(
"package aa;",
"",
"/**",
" * Hello world",
" *",
" */",
"public class App {",
"",
" public static void main(String[] args) {",
"",
" int magicNumber = 42;",
"",
" String s = new String(\"Very long line that does not meet our maximum 120 character line length criteria and should be wrapped to avoid SonarQube issues.\");\r\n"
+
" }",
"}");
Issue base1 = baseInput.createIssueOnLine(11, RuleKey.of("java", "S109"), "Assign this magic number 42 to a well-named constant, and use the constant instead.");
Issue base2 = baseInput.createIssueOnLine(13, RuleKey.of("java", "S00103"), "Split this 163 characters long line (which is greater than 120 authorized).");
FakeInput rawInput = FakeInput.createForSourceLines(
"package aa;",
"",
"/**",
" * Hello world",
" *",
" */",
"public class App {",
"",
" public static void main(String[] args) {",
" ",
" System.out.println(\"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vel diam purus. Curabitur ut nisi lacus....\");",
" ",
" int a = 0;",
" ",
" int x = a + 123;",
" }",
"}");
Issue raw1 = rawInput.createIssueOnLine(11, RuleKey.of("java", "S00103"), "Split this 139 characters long line (which is greater than 120 authorized).");
Issue raw2 = rawInput.createIssueOnLine(15, RuleKey.of("java", "S109"), "Assign this magic number 123 to a well-named constant, and use the constant instead.");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw1)).isNull();
assertThat(tracking.baseFor(raw2)).isNull();
assertThat(tracking.getUnmatchedBases()).hasSize(2);
}
/**
* SONAR-3072
*/
@Test
public void recognize_blocks_2() {
FakeInput baseInput = FakeInput.createForSourceLines(
"package example2;",
"",
"public class Toto {",
" void method1() {",
" System.out.println(\"toto\");",
" }",
"}");
Issue base1 = baseInput.createIssueOnLine(5, RULE_SYSTEM_PRINT, "SystemPrintln");
FakeInput rawInput = FakeInput.createForSourceLines(
"package example2;",
"",
"public class Toto {",
"",
" void method2() {",
" System.out.println(\"toto\");",
" }",
"",
" void method1() {",
" System.out.println(\"toto\");",
" }",
"",
" void method3() {",
" System.out.println(\"toto\");",
" }",
"}");
Issue raw1 = rawInput.createIssueOnLine(6, RULE_SYSTEM_PRINT, "SystemPrintln");
Issue raw2 = rawInput.createIssueOnLine(10, RULE_SYSTEM_PRINT, "SystemPrintln");
Issue raw3 = rawInput.createIssueOnLine(14, RULE_SYSTEM_PRINT, "SystemPrintln");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(raw1)).isNull();
assertThat(tracking.baseFor(raw2)).isSameAs(base1);
assertThat(tracking.baseFor(raw3)).isNull();
}
@Test
public void recognize_blocks_3() {
FakeInput baseInput = FakeInput.createForSourceLines(
"package sample;",
"",
"public class Sample {",
"\t",
"\tpublic Sample(int i) {",
"\t\tint j = i+1;", // UnusedLocalVariable
"\t}",
"",
"\tpublic boolean avoidUtilityClass() {", // NotDesignedForExtension
"\t\treturn true;",
"\t}",
"",
"\tprivate String myMethod() {", // UnusedPrivateMethod
"\t\treturn \"hello\";",
"\t}",
"}");
Issue base1 = baseInput.createIssueOnLine(6, RULE_UNUSED_LOCAL_VARIABLE, "Avoid unused local variables such as 'j'.");
Issue base2 = baseInput.createIssueOnLine(13, RULE_UNUSED_PRIVATE_METHOD, "Avoid unused private methods such as 'myMethod()'.");
Issue base3 = baseInput.createIssueOnLine(9, RULE_NOT_DESIGNED_FOR_EXTENSION,
"Method 'avoidUtilityClass' is not designed for extension - needs to be abstract, final or empty.");
FakeInput rawInput = FakeInput.createForSourceLines(
"package sample;",
"",
"public class Sample {",
"",
"\tpublic Sample(int i) {",
"\t\tint j = i+1;", // UnusedLocalVariable is still there
"\t}",
"\t",
"\tpublic boolean avoidUtilityClass() {", // NotDesignedForExtension is still there
"\t\treturn true;",
"\t}",
"\t",
"\tprivate String myMethod() {", // issue UnusedPrivateMethod is fixed because it's called at line 18
"\t\treturn \"hello\";",
"\t}",
"",
" public void newIssue() {",
" String msg = myMethod();", // new issue UnusedLocalVariable
" }",
"}");
Issue newRaw = rawInput.createIssueOnLine(18, RULE_UNUSED_LOCAL_VARIABLE, "Avoid unused local variables such as 'msg'.");
Issue rawSameAsBase1 = rawInput.createIssueOnLine(6, RULE_UNUSED_LOCAL_VARIABLE, "Avoid unused local variables such as 'j'.");
Issue rawSameAsBase3 = rawInput.createIssueOnLine(9, RULE_NOT_DESIGNED_FOR_EXTENSION,
"Method 'avoidUtilityClass' is not designed for extension - needs to be abstract, final or empty.");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.baseFor(newRaw)).isNull();
assertThat(tracking.baseFor(rawSameAsBase1)).isSameAs(base1);
assertThat(tracking.baseFor(rawSameAsBase3)).isSameAs(base3);
assertThat(tracking.getUnmatchedBases()).containsOnly(base2);
}
/**
* https://jira.sonarsource.com/browse/SONAR-7595
*/
@Test
public void match_only_one_issue_when_multiple_blocks_match_the_same_block() {
FakeInput baseInput = FakeInput.createForSourceLines(
"public class Toto {",
" private final Deque<Set<DataItem>> one = new ArrayDeque<Set<DataItem>>();",
" private final Deque<Set<DataItem>> two = new ArrayDeque<Set<DataItem>>();",
" private final Deque<Integer> three = new ArrayDeque<Integer>();",
" private final Deque<Set<Set<DataItem>>> four = new ArrayDeque<Set<DataItem>>();");
Issue base1 = baseInput.createIssueOnLine(2, RULE_USE_DIAMOND, "Use diamond");
baseInput.createIssueOnLine(3, RULE_USE_DIAMOND, "Use diamond");
baseInput.createIssueOnLine(4, RULE_USE_DIAMOND, "Use diamond");
baseInput.createIssueOnLine(5, RULE_USE_DIAMOND, "Use diamond");
FakeInput rawInput = FakeInput.createForSourceLines(
"public class Toto {",
" // move all lines",
" private final Deque<Set<DataItem>> one = new ArrayDeque<Set<DataItem>>();",
" private final Deque<Set<DataItem>> two = new ArrayDeque<>();",
" private final Deque<Integer> three = new ArrayDeque<>();",
" private final Deque<Set<Set<DataItem>>> four = new ArrayDeque<>();");
Issue raw1 = rawInput.createIssueOnLine(3, RULE_USE_DIAMOND, "Use diamond");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.getUnmatchedBases()).hasSize(3);
assertThat(tracking.baseFor(raw1)).isEqualTo(base1);
}
@Test
public void match_issues_with_same_rule_key_on_project_level() {
FakeInput baseInput = new FakeInput();
Issue base1 = baseInput.createIssue(RULE_MISSING_PACKAGE_INFO, "[com.test:abc] Missing package-info.java in package.");
Issue base2 = baseInput.createIssue(RULE_MISSING_PACKAGE_INFO, "[com.test:abc/def] Missing package-info.java in package.");
FakeInput rawInput = new FakeInput();
Issue raw1 = rawInput.createIssue(RULE_MISSING_PACKAGE_INFO, "[com.test:abc/def] Missing package-info.java in package.");
Issue raw2 = rawInput.createIssue(RULE_MISSING_PACKAGE_INFO, "[com.test:abc] Missing package-info.java in package.");
Tracking<Issue, Issue> tracking = tracker.trackNonClosed(rawInput, baseInput);
assertThat(tracking.getUnmatchedBases()).isEmpty();
assertThat(tracking.baseFor(raw1)).isEqualTo(base2);
assertThat(tracking.baseFor(raw2)).isEqualTo(base1);
}
private static class Issue implements Trackable {
private final RuleKey ruleKey;
private final Integer line;
private final String message, lineHash;
private final String status;
private final Date updateDate;
Issue(@Nullable Integer line, String lineHash, RuleKey ruleKey, @Nullable String message, String status, Date updateDate) {
this.line = line;
this.lineHash = lineHash;
this.ruleKey = ruleKey;
this.status = status;
this.updateDate = updateDate;
this.message = trim(message);
}
@Override
public Integer getLine() {
return line;
}
@CheckForNull
@Override
public String getMessage() {
return message;
}
@Override
public String getLineHash() {
return lineHash;
}
@Override
public RuleKey getRuleKey() {
return ruleKey;
}
@Override
public String getStatus() {
return status;
}
@Override
public Date getUpdateDate() {
return updateDate;
}
}
private static class FakeInput implements Input<Issue> {
private final List<Issue> issues = new ArrayList<>();
private final List<String> lineHashes;
FakeInput(String... lineHashes) {
this.lineHashes = asList(lineHashes);
}
static FakeInput createForSourceLines(String... lines) {
String[] hashes = new String[lines.length];
for (int i = 0; i < lines.length; i++) {
hashes[i] = DigestUtils.md5Hex(lines[i].replaceAll("[\t ]", ""));
}
return new FakeInput(hashes);
}
Issue createIssueOnLine(int line, RuleKey ruleKey, String message) {
Issue issue = new Issue(line, lineHashes.get(line - 1), ruleKey, message, org.sonar.api.issue.Issue.STATUS_OPEN, new Date());
issues.add(issue);
return issue;
}
/**
* No line (line 0)
*/
Issue createIssue(RuleKey ruleKey, @Nullable String message) {
Issue issue = new Issue(null, "", ruleKey, message, org.sonar.api.issue.Issue.STATUS_OPEN, new Date());
issues.add(issue);
return issue;
}
FakeInput addIssue(Issue issue) {
this.issues.add(issue);
return this;
}
@Override
public LineHashSequence getLineHashSequence() {
return new LineHashSequence(lineHashes);
}
@Override
public BlockHashSequence getBlockHashSequence() {
return new BlockHashSequence(getLineHashSequence(), 2);
}
@Override
public Collection<Issue> getIssues() {
return issues;
}
}
}
| 20,698 | 35.830961 | 177 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/language/LanguagesProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.language;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.Languages;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
public class LanguagesProviderTest {
@Test
public void should_provide_default_instance_when_no_language() {
LanguagesProvider provider = new LanguagesProvider();
Languages languages = provider.provide(Optional.empty());
assertThat(languages).isNotNull();
assertThat(languages.all()).isEmpty();
}
@Test
public void should_provide_instance_when_languages() {
Language A = mock(Language.class);
when(A.getKey()).thenReturn("a");
Language B = mock(Language.class);
when(B.getKey()).thenReturn("b");
LanguagesProvider provider = new LanguagesProvider();
List<Language> languageList = Arrays.asList(A, B);
Languages languages = provider.provide(Optional.of(languageList));
assertThat(languages).isNotNull();
assertThat(languages.all())
.hasSize(2)
.contains(A, B);
}
}
| 2,043 | 31.967742 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/language/UnanalyzedLanguagesTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.language;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class UnanalyzedLanguagesTest {
@Test
public void test_toString() {
assertThat(UnanalyzedLanguages.C).hasToString("C");
assertThat(UnanalyzedLanguages.CPP).hasToString("C++");
}
}
| 1,162 | 33.205882 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/metric/ScannerMetricsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.metric;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import org.sonar.api.measures.Metric;
import org.sonar.api.measures.Metrics;
import static org.assertj.core.api.Assertions.assertThat;
public class ScannerMetricsTest {
// metrics that are always added, regardless of plugins
private static final List<Metric> SENSOR_METRICS_WITHOUT_METRIC_PLUGIN = metrics();
@Test
public void check_number_of_allowed_core_metrics() {
assertThat(SENSOR_METRICS_WITHOUT_METRIC_PLUGIN).hasSize(22);
}
@Test
public void check_metrics_from_plugin() {
List<Metric> metrics = metrics(new FakeMetrics());
metrics.removeAll(SENSOR_METRICS_WITHOUT_METRIC_PLUGIN);
assertThat(metrics).hasSize(2);
}
@Test
public void should_not_crash_on_null_metrics_from_faulty_plugins() {
Metrics faultyMetrics = () -> null;
Metrics okMetrics = new FakeMetrics();
List<Metric> metrics = metrics(okMetrics, faultyMetrics);
metrics.removeAll(SENSOR_METRICS_WITHOUT_METRIC_PLUGIN);
assertThat(metrics).isEqualTo(okMetrics.getMetrics());
}
private static List<Metric> metrics(Metrics... metrics) {
return new ArrayList<>(new ScannerMetrics(metrics).getMetrics());
}
private static class FakeMetrics implements Metrics {
@Override
public List<Metric> getMetrics() {
return Arrays.asList(
new Metric.Builder("key1", "name1", Metric.ValueType.INT).create(),
new Metric.Builder("key2", "name2", Metric.ValueType.FLOAT).create());
}
}
}
| 2,424 | 32.680556 | 85 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/ComponentKeysTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import org.junit.Test;
import org.slf4j.Logger;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.startsWith;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
public class ComponentKeysTest {
ComponentKeys keys = new ComponentKeys();
@Test
public void generate_key_of_object() {
assertThat(keys.of(FakeComponent.class)).isEqualTo(FakeComponent.class);
}
@Test
public void generate_key_of_instance() {
assertThat((String) keys.of(new FakeComponent())).endsWith("-org.sonar.core.platform.ComponentKeysTest.FakeComponent-fake");
}
@Test
public void generate_key_of_class() {
assertThat(keys.ofClass(FakeComponent.class)).endsWith("-org.sonar.core.platform.ComponentKeysTest.FakeComponent");
}
@Test
public void should_log_warning_if_toString_is_not_overridden() {
Logger log = mock(Logger.class);
keys.of(new Object(), log);
verifyNoInteractions(log);
// only on non-first runs, to avoid false-positives on singletons
keys.of(new Object(), log);
verify(log).warn(startsWith("Bad component key"));
}
@Test
public void should_generate_unique_key_when_toString_is_not_overridden() {
Object key = keys.of(new WrongToStringImpl());
assertThat(key).isNotEqualTo(WrongToStringImpl.KEY);
Object key2 = keys.of(new WrongToStringImpl());
assertThat(key2).isNotEqualTo(key);
}
static class FakeComponent {
@Override
public String toString() {
return "fake";
}
}
static class WrongToStringImpl {
static final String KEY = "my.Component@123a";
@Override
public String toString() {
return KEY;
}
}
}
| 2,645 | 29.767442 | 128 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/LazyUnlessStartableStrategyTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import org.junit.Test;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import static org.assertj.core.api.Assertions.assertThat;
public class LazyUnlessStartableStrategyTest {
private final LazyUnlessStartableStrategy postProcessor = new LazyUnlessStartableStrategy();
@Test
public void sets_all_beans_lazy() {
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.registerBeanDefinition("bean1", new RootBeanDefinition());
assertThat(beanFactory.getBeanDefinition("bean1").isLazyInit()).isFalse();
postProcessor.postProcessBeanFactory(beanFactory);
assertThat(beanFactory.getBeanDefinition("bean1").isLazyInit()).isTrue();
}
}
| 1,669 | 38.761905 | 94 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/ListContainerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import java.util.Arrays;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
public class ListContainerTest {
@Test
public void register_beans() {
ListContainer container = new ListContainer();
container.add(
A.class,
new VirtualModule(),
Arrays.asList(C.class, D.class)
);
assertThat(container.getAddedObjects()).contains(A.class, B.class, C.class, D.class);
}
@Test
public void addExtension_register_beans() {
ListContainer container = new ListContainer();
container
.addExtension("A", A.class)
.addExtension("B", B.class);
assertThat(container.getAddedObjects()).contains(A.class, B.class);
}
@Test
public void declareExtension_does_nothing() {
ListContainer container = new ListContainer();
assertThatNoException().isThrownBy(() -> container
.declareExtension("A", A.class)
.declareExtension(mock(PluginInfo.class), B.class));
}
@Test
public void unsupported_method_should_throw_exception() {
ListContainer container = new ListContainer();
container.add(A.class);
assertThatThrownBy(() -> container.getComponentByType(A.class)).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> container.getOptionalComponentByType(A.class)).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(() -> container.getComponentsByType(A.class)).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(container::getParent).isInstanceOf(UnsupportedOperationException.class);
}
class A {
}
class B {
}
class C {
}
class D {
}
class VirtualModule extends Module {
@Override protected void configureModule() {
add(B.class);
}
}
}
| 2,820 | 30.344444 | 126 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/ModuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ModuleTest {
private final ListContainer container = new ListContainer();
@Test(expected = NullPointerException.class)
public void configure_throws_NPE_if_container_is_empty() {
new Module() {
@Override
protected void configureModule() {
// empty
}
}.configure(null);
}
@Test
public void module_with_empty_configureModule_method_adds_no_component() {
new Module() {
@Override
protected void configureModule() {
// empty
}
}.configure(container);
assertThat(container.getAddedObjects()).isEmpty();
}
@Test
public void add_method_supports_null_and_adds_nothing_to_container() {
new Module() {
@Override
protected void configureModule() {
add((Object)null);
}
}.configure(container);
assertThat(container.getAddedObjects()).isEmpty();
}
@Test
public void add_method_filters_out_null_inside_vararg_parameter() {
new Module() {
@Override
protected void configureModule() {
add(new Object(), null, "");
}
}.configure(container);
assertThat(container.getAddedObjects()).hasSize(2);
}
private static int sizeOf(SpringComponentContainer container) {
return container.context.getBeanDefinitionCount();
}
}
| 2,259 | 27.607595 | 76 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/PlatformEditionProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.core.platform.EditionProvider.Edition.COMMUNITY;
public class PlatformEditionProviderTest {
@Test
public void returns_COMMUNITY() {
assertThat(new PlatformEditionProvider().get()).contains(COMMUNITY);
}
}
| 1,199 | 35.363636 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/PluginClassLoaderDefTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class PluginClassLoaderDefTest {
@Test
public void test_equals_and_hashCode() {
PluginClassLoaderDef one = new PluginClassLoaderDef("one");
PluginClassLoaderDef oneBis = new PluginClassLoaderDef("one");
PluginClassLoaderDef two = new PluginClassLoaderDef("two");
assertThat(one.equals(one)).isTrue();
assertThat(one.equals(oneBis)).isTrue();
assertThat(one)
.hasSameHashCodeAs(one)
.hasSameHashCodeAs(oneBis);
assertThat(one.equals(two)).isFalse();
assertThat(one.equals("one")).isFalse();
assertThat(one.equals(null)).isFalse();
}
}
| 1,558 | 33.644444 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/PluginClassLoaderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.assertj.core.data.MapEntry;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.updatecenter.common.Version;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;
import static org.mockito.Mockito.mock;
public class PluginClassLoaderTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public LogTester logTester = new LogTester();
private PluginClassloaderFactory classloaderFactory = mock(PluginClassloaderFactory.class);
private PluginClassLoader underTest = new PluginClassLoader(classloaderFactory);
@Test
public void define_classloader() throws Exception {
File jarFile = temp.newFile();
PluginInfo plugin = new PluginInfo("foo")
.setJarFile(jarFile)
.setMainClass("org.foo.FooPlugin")
.setMinimalSonarPluginApiVersion(Version.create("5.2"));
ExplodedPlugin explodedPlugin = createExplodedPlugin(plugin);
Collection<PluginClassLoaderDef> defs = underTest.defineClassloaders(
ImmutableMap.of("foo", explodedPlugin));
assertThat(defs).hasSize(1);
PluginClassLoaderDef def = defs.iterator().next();
assertThat(def.getBasePluginKey()).isEqualTo("foo");
assertThat(def.isSelfFirstStrategy()).isFalse();
assertThat(def.getFiles()).containsAll(explodedPlugin.getLibs());
assertThat(def.getMainClassesByPluginKey()).containsOnly(MapEntry.entry("foo", "org.foo.FooPlugin"));
}
/**
* A plugin (the "base" plugin) can be extended by other plugins. In this case they share the same classloader.
*/
@Test
public void test_plugins_sharing_the_same_classloader() throws Exception {
File baseJarFile = temp.newFile();
File extensionJar1 = temp.newFile();
File extensionJar2 = temp.newFile();
PluginInfo base = new PluginInfo("foo")
.setJarFile(baseJarFile)
.setMainClass("org.foo.FooPlugin")
.setUseChildFirstClassLoader(false);
PluginInfo extension1 = new PluginInfo("fooExtension1")
.setJarFile(extensionJar1)
.setMainClass("org.foo.Extension1Plugin")
.setBasePlugin("foo");
// This extension tries to change the classloader-ordering strategy of base plugin
// (see setUseChildFirstClassLoader(true)).
// That is not allowed and should be ignored -> strategy is still the one
// defined on base plugin (parent-first in this example)
PluginInfo extension2 = new PluginInfo("fooExtension2")
.setJarFile(extensionJar2)
.setMainClass("org.foo.Extension2Plugin")
.setBasePlugin("foo")
.setUseChildFirstClassLoader(true);
ExplodedPlugin baseExplodedPlugin = createExplodedPlugin(base);
ExplodedPlugin extension1ExplodedPlugin = createExplodedPlugin(extension1);
ExplodedPlugin extension2ExplodedPlugin = createExplodedPlugin(extension2);
Collection<PluginClassLoaderDef> defs = underTest.defineClassloaders(ImmutableMap.of(
base.getKey(), baseExplodedPlugin,
extension1.getKey(), extension1ExplodedPlugin,
extension2.getKey(), extension2ExplodedPlugin));
assertThat(defs).hasSize(1);
PluginClassLoaderDef def = defs.iterator().next();
assertThat(def.getBasePluginKey()).isEqualTo("foo");
assertThat(def.isSelfFirstStrategy()).isFalse();
assertThat(def.getFiles())
.containsAll(baseExplodedPlugin.getLibs())
.containsAll(extension1ExplodedPlugin.getLibs())
.containsAll(extension2ExplodedPlugin.getLibs());
assertThat(def.getMainClassesByPluginKey()).containsOnly(
entry("foo", "org.foo.FooPlugin"),
entry("fooExtension1", "org.foo.Extension1Plugin"),
entry("fooExtension2", "org.foo.Extension2Plugin"));
}
@Test
public void log_warning_if_plugin_uses_child_first_classloader() throws IOException {
File jarFile = temp.newFile();
PluginInfo info = new PluginInfo("foo")
.setJarFile(jarFile)
.setUseChildFirstClassLoader(true)
.setMainClass("org.foo.FooPlugin");
Collection<PluginClassLoaderDef> defs = underTest.defineClassloaders(
ImmutableMap.of("foo", createExplodedPlugin(info)));
assertThat(defs).extracting(PluginClassLoaderDef::getBasePluginKey).containsExactly("foo");
List<String> warnings = logTester.logs(Level.WARN);
assertThat(warnings).contains("Plugin foo [foo] uses a child first classloader which is deprecated");
}
@Test
public void log_warning_if_plugin_is_built_with_api_5_2_or_lower() throws Exception {
File jarFile = temp.newFile();
PluginInfo info = new PluginInfo("foo")
.setJarFile(jarFile)
.setMainClass("org.foo.FooPlugin")
.setMinimalSonarPluginApiVersion(Version.create("4.5.2"));
Collection<PluginClassLoaderDef> defs = underTest.defineClassloaders(
ImmutableMap.of("foo", createExplodedPlugin(info)));
assertThat(defs).extracting(PluginClassLoaderDef::getBasePluginKey).containsExactly("foo");
List<String> warnings = logTester.logs(Level.WARN);
assertThat(warnings).contains("API compatibility mode is no longer supported. In case of error, plugin foo [foo] should package its dependencies.");
}
private ExplodedPlugin createExplodedPlugin(PluginInfo plugin) {
return new ExplodedPlugin(plugin, plugin.getKey(), new File(plugin.getKey() + ".jar"), Collections
.singleton(new File(plugin.getKey() + "-lib.jar")));
}
}
| 6,540 | 40.138365 | 152 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/PluginClassloaderFactoryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import com.sonarsource.plugins.license.api.FooBar;
import java.io.File;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.sonar.api.server.rule.RulesDefinition;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
public class PluginClassloaderFactoryTest {
static final String BASE_PLUGIN_CLASSNAME = "org.sonar.plugins.base.BasePlugin";
static final String DEPENDENT_PLUGIN_CLASSNAME = "org.sonar.plugins.dependent.DependentPlugin";
static final String BASE_PLUGIN_KEY = "base";
static final String DEPENDENT_PLUGIN_KEY = "dependent";
PluginClassloaderFactory factory = new PluginClassloaderFactory();
@Test
public void create_isolated_classloader() {
PluginClassLoaderDef def = basePluginDef();
Map<PluginClassLoaderDef, ClassLoader> map = factory.create(asList(def));
assertThat(map).containsOnlyKeys(def);
ClassLoader classLoader = map.get(def);
// plugin can access to API classes, and of course to its own classes !
assertThat(canLoadClass(classLoader, RulesDefinition.class.getCanonicalName())).isTrue();
assertThat(canLoadClass(classLoader, BASE_PLUGIN_CLASSNAME)).isTrue();
// plugin can not access to core classes
assertThat(canLoadClass(classLoader, PluginClassloaderFactory.class.getCanonicalName())).isFalse();
assertThat(canLoadClass(classLoader, Test.class.getCanonicalName())).isFalse();
assertThat(canLoadClass(classLoader, StringUtils.class.getCanonicalName())).isFalse();
}
@Test
public void classloader_exports_resources_to_other_classloaders() {
PluginClassLoaderDef baseDef = basePluginDef();
PluginClassLoaderDef dependentDef = dependentPluginDef();
Map<PluginClassLoaderDef, ClassLoader> map = factory.create(asList(baseDef, dependentDef));
ClassLoader baseClassloader = map.get(baseDef);
ClassLoader dependentClassloader = map.get(dependentDef);
// base-plugin exports its API package to other plugins
assertThat(canLoadClass(dependentClassloader, "org.sonar.plugins.base.api.BaseApi")).isTrue();
assertThat(canLoadClass(dependentClassloader, BASE_PLUGIN_CLASSNAME)).isFalse();
assertThat(canLoadClass(dependentClassloader, DEPENDENT_PLUGIN_CLASSNAME)).isTrue();
// dependent-plugin does not export its classes
assertThat(canLoadClass(baseClassloader, DEPENDENT_PLUGIN_CLASSNAME)).isFalse();
assertThat(canLoadClass(baseClassloader, BASE_PLUGIN_CLASSNAME)).isTrue();
}
@Test
public void classloader_exposes_license_api_from_main_classloader() {
PluginClassLoaderDef def = basePluginDef();
Map<PluginClassLoaderDef, ClassLoader> map = factory.create(asList(def));
assertThat(map).containsOnlyKeys(def);
ClassLoader classLoader = map.get(def);
assertThat(canLoadClass(classLoader, FooBar.class.getCanonicalName())).isTrue();
}
private static PluginClassLoaderDef basePluginDef() {
PluginClassLoaderDef def = new PluginClassLoaderDef(BASE_PLUGIN_KEY);
def.addMainClass(BASE_PLUGIN_KEY, BASE_PLUGIN_CLASSNAME);
def.getExportMask().addInclusion("org/sonar/plugins/base/api/");
def.addFiles(asList(fakePluginJar("base-plugin/target/base-plugin-0.1-SNAPSHOT.jar")));
return def;
}
private static PluginClassLoaderDef dependentPluginDef() {
PluginClassLoaderDef def = new PluginClassLoaderDef(DEPENDENT_PLUGIN_KEY);
def.addMainClass(DEPENDENT_PLUGIN_KEY, DEPENDENT_PLUGIN_CLASSNAME);
def.getExportMask().addInclusion("org/sonar/plugins/dependent/api/");
def.addFiles(asList(fakePluginJar("dependent-plugin/target/dependent-plugin-0.1-SNAPSHOT.jar")));
return def;
}
private static File fakePluginJar(String path) {
// Maven way
File file = new File("src/test/projects/" + path);
if (!file.exists()) {
// Intellij way
file = new File("sonar-core/src/test/projects/" + path);
if (!file.exists()) {
throw new IllegalArgumentException("Fake projects are not built: " + path);
}
}
return file;
}
private static boolean canLoadClass(ClassLoader classloader, String classname) {
try {
classloader.loadClass(classname);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
}
| 5,167 | 40.015873 | 103 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/PluginInfoTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.io.FileUtils;
import org.assertj.core.api.Assertions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.ZipUtils;
import org.sonar.updatecenter.common.PluginManifest;
import org.sonar.updatecenter.common.Version;
import static com.google.common.collect.Ordering.natural;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.fail;
@RunWith(DataProviderRunner.class)
public class PluginInfoTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void test_RequiredPlugin() {
PluginInfo.RequiredPlugin plugin = PluginInfo.RequiredPlugin.parse("java:1.1");
assertThat(plugin.getKey()).isEqualTo("java");
assertThat(plugin.getMinimalVersion().getName()).isEqualTo("1.1");
assertThat(plugin).hasToString("java:1.1")
.isEqualTo(PluginInfo.RequiredPlugin.parse("java:1.2"))
.isNotEqualTo(PluginInfo.RequiredPlugin.parse("php:1.2"));
try {
PluginInfo.RequiredPlugin.parse("java");
fail();
} catch (IllegalArgumentException expected) {
// ok
}
}
@Test
public void test_comparison() {
PluginInfo java1 = new PluginInfo("java").setVersion(Version.create("1.0"));
PluginInfo java2 = new PluginInfo("java").setVersion(Version.create("2.0"));
PluginInfo javaNoVersion = new PluginInfo("java");
PluginInfo cobol = new PluginInfo("cobol").setVersion(Version.create("1.0"));
PluginInfo noVersion = new PluginInfo("noVersion");
List<PluginInfo> plugins = Arrays.asList(java1, cobol, javaNoVersion, noVersion, java2);
List<PluginInfo> ordered = natural().sortedCopy(plugins);
Assertions.assertThat(ordered.get(0)).isSameAs(cobol);
Assertions.assertThat(ordered.get(1)).isSameAs(javaNoVersion);
Assertions.assertThat(ordered.get(2)).isSameAs(java1);
Assertions.assertThat(ordered.get(3)).isSameAs(java2);
Assertions.assertThat(ordered.get(4)).isSameAs(noVersion);
}
@Test
public void test_equals() {
PluginInfo java1 = new PluginInfo("java").setVersion(Version.create("1.0"));
PluginInfo java2 = new PluginInfo("java").setVersion(Version.create("2.0"));
PluginInfo javaNoVersion = new PluginInfo("java");
PluginInfo cobol = new PluginInfo("cobol").setVersion(Version.create("1.0"));
assertThat(java1.equals(java1)).isTrue();
assertThat(java1.equals(java2)).isFalse();
assertThat(java1.equals(javaNoVersion)).isFalse();
assertThat(java1.equals(cobol)).isFalse();
assertThat(java1.equals("java:1.0")).isFalse();
assertThat(java1.equals(null)).isFalse();
assertThat(javaNoVersion.equals(javaNoVersion)).isTrue();
assertThat(java1).hasSameHashCodeAs(java1);
assertThat(javaNoVersion).hasSameHashCodeAs(javaNoVersion);
}
/**
* SNAPSHOT versions of SonarQube are built on local developer machines only.
* All other build environments have unique release versions (6.3.0.12345).
*/
@Test
public void test_compatibility_with_snapshot_version_of_sonarqube() {
// plugins compatible with 5.6 LTS
assertThat(withMinSqVersion("5.6").isCompatibleWith("6.3-SNAPSHOT")).isTrue();
assertThat(withMinSqVersion("5.6.1").isCompatibleWith("6.3-SNAPSHOT")).isTrue();
// plugin build with old release candidates of SonarQube (RC technical versions have been removed
// in SonarQube 6.3)
assertThat(withMinSqVersion("5.6-RC1").isCompatibleWith("6.3-SNAPSHOT")).isTrue();
assertThat(withMinSqVersion("6.2-RC1").isCompatibleWith("6.3-SNAPSHOT")).isTrue();
// plugin built with snapshot version of SonarQube
assertThat(withMinSqVersion("5.6-SNAPSHOT").isCompatibleWith("6.3-SNAPSHOT")).isTrue();
assertThat(withMinSqVersion("6.3-SNAPSHOT").isCompatibleWith("6.3-SNAPSHOT")).isTrue();
assertThat(withMinSqVersion("6.4-SNAPSHOT").isCompatibleWith("6.3-SNAPSHOT")).isFalse();
// plugin built with SonarQube releases
assertThat(withMinSqVersion("6.3.0.5000").isCompatibleWith("6.3-SNAPSHOT")).isTrue();
assertThat(withMinSqVersion("6.3.1.5000").isCompatibleWith("6.3-SNAPSHOT")).isTrue();
assertThat(withMinSqVersion("6.3.1.5000").isCompatibleWith("6.4-SNAPSHOT")).isTrue();
assertThat(withMinSqVersion("6.4.0.5000").isCompatibleWith("6.3-SNAPSHOT")).isFalse();
// no constraint
assertThat(withMinSqVersion(null).isCompatibleWith("6.3-SNAPSHOT")).isTrue();
}
/**
* @see #test_compatibility_with_snapshot_version_of_sonarqube
*/
@Test
public void test_compatibility_with_release_version_of_sonarqube() {
// plugins compatible with 5.6 LTS
assertThat(withMinSqVersion("5.6").isCompatibleWith("6.3.0.5000")).isTrue();
assertThat(withMinSqVersion("5.6.1").isCompatibleWith("6.3.0.5000")).isTrue();
// plugin build with old release candidates of SonarQube (RC technical versions have been removed
// in SonarQube 6.3)
assertThat(withMinSqVersion("5.6-RC1").isCompatibleWith("6.3.0.5000")).isTrue();
assertThat(withMinSqVersion("6.2-RC1").isCompatibleWith("6.3.0.5000")).isTrue();
// plugin built with snapshot version of SonarQube
assertThat(withMinSqVersion("5.6-SNAPSHOT").isCompatibleWith("6.3.0.5000")).isTrue();
assertThat(withMinSqVersion("6.3-SNAPSHOT").isCompatibleWith("6.3.0.5000")).isTrue();
assertThat(withMinSqVersion("6.3-SNAPSHOT").isCompatibleWith("6.3.1.6000")).isTrue();
assertThat(withMinSqVersion("6.4-SNAPSHOT").isCompatibleWith("6.3.0.5000")).isFalse();
// plugin built with SonarQube releases
assertThat(withMinSqVersion("6.3.0.5000").isCompatibleWith("6.3.0.4000")).isFalse();
assertThat(withMinSqVersion("6.3.0.5000").isCompatibleWith("6.3.0.5000")).isTrue();
assertThat(withMinSqVersion("6.3.0.5000").isCompatibleWith("6.3.1.6000")).isTrue();
assertThat(withMinSqVersion("6.4.0.7000").isCompatibleWith("6.3.0.5000")).isFalse();
// no constraint
assertThat(withMinSqVersion(null).isCompatibleWith("6.3.0.5000")).isTrue();
}
@Test
public void create_from_minimal_manifest() throws Exception {
PluginManifest manifest = new PluginManifest();
manifest.setKey("java");
manifest.setVersion("1.0");
manifest.setName("Java");
manifest.setMainClass("org.foo.FooPlugin");
File jarFile = temp.newFile();
PluginInfo pluginInfo = PluginInfo.create(jarFile, manifest);
assertThat(pluginInfo.getKey()).isEqualTo("java");
assertThat(pluginInfo.getName()).isEqualTo("Java");
assertThat(pluginInfo.getVersion().getName()).isEqualTo("1.0");
assertThat(pluginInfo.getJarFile()).isSameAs(jarFile);
assertThat(pluginInfo.getMainClass()).isEqualTo("org.foo.FooPlugin");
assertThat(pluginInfo.getBasePlugin()).isNull();
assertThat(pluginInfo.getDescription()).isNull();
assertThat(pluginInfo.getHomepageUrl()).isNull();
assertThat(pluginInfo.getImplementationBuild()).isNull();
assertThat(pluginInfo.getIssueTrackerUrl()).isNull();
assertThat(pluginInfo.getLicense()).isNull();
assertThat(pluginInfo.getOrganizationName()).isNull();
assertThat(pluginInfo.getOrganizationUrl()).isNull();
assertThat(pluginInfo.getMinimalSonarPluginApiVersion()).isNull();
assertThat(pluginInfo.getRequiredPlugins()).isEmpty();
assertThat(pluginInfo.isSonarLintSupported()).isFalse();
}
@Test
public void create_from_complete_manifest() throws Exception {
PluginManifest manifest = new PluginManifest();
manifest.setKey("fbcontrib");
manifest.setVersion("2.0");
manifest.setName("Java");
manifest.setMainClass("org.fb.FindbugsPlugin");
manifest.setBasePlugin("findbugs");
manifest.setSonarVersion("4.5.1");
manifest.setDescription("the desc");
manifest.setHomepage("http://fbcontrib.org");
manifest.setImplementationBuild("SHA1");
manifest.setLicense("LGPL");
manifest.setOrganization("SonarSource");
manifest.setOrganizationUrl("http://sonarsource.com");
manifest.setIssueTrackerUrl("http://jira.com");
manifest.setRequirePlugins(new String[] {"java:2.0", "pmd:1.3"});
manifest.setSonarLintSupported(true);
File jarFile = temp.newFile();
PluginInfo pluginInfo = PluginInfo.create(jarFile, manifest);
assertThat(pluginInfo.getBasePlugin()).isEqualTo("findbugs");
assertThat(pluginInfo.getDescription()).isEqualTo("the desc");
assertThat(pluginInfo.getHomepageUrl()).isEqualTo("http://fbcontrib.org");
assertThat(pluginInfo.getImplementationBuild()).isEqualTo("SHA1");
assertThat(pluginInfo.getIssueTrackerUrl()).isEqualTo("http://jira.com");
assertThat(pluginInfo.getLicense()).isEqualTo("LGPL");
assertThat(pluginInfo.getOrganizationName()).isEqualTo("SonarSource");
assertThat(pluginInfo.getOrganizationUrl()).isEqualTo("http://sonarsource.com");
assertThat(pluginInfo.getMinimalSonarPluginApiVersion().getName()).isEqualTo("4.5.1");
assertThat(pluginInfo.getRequiredPlugins()).extracting("key").containsOnly("java", "pmd");
assertThat(pluginInfo.isSonarLintSupported()).isTrue();
}
@Test
@UseDataProvider("licenseVersions")
public void requiredPlugin_license_is_ignored_when_reading_manifest(String version) throws IOException {
PluginManifest manifest = new PluginManifest();
manifest.setKey("java");
manifest.setVersion("1.0");
manifest.setName("Java");
manifest.setMainClass("org.foo.FooPlugin");
manifest.setRequirePlugins(new String[] {"license:" + version});
File jarFile = temp.newFile();
PluginInfo pluginInfo = PluginInfo.create(jarFile, manifest);
assertThat(pluginInfo.getRequiredPlugins()).isEmpty();
}
@Test
@UseDataProvider("licenseVersions")
public void requiredPlugin_license_among_others_is_ignored_when_reading_manifest(String version) throws IOException {
PluginManifest manifest = new PluginManifest();
manifest.setKey("java");
manifest.setVersion("1.0");
manifest.setName("Java");
manifest.setMainClass("org.foo.FooPlugin");
manifest.setRequirePlugins(new String[] {"java:2.0", "license:" + version, "pmd:1.3"});
File jarFile = temp.newFile();
PluginInfo pluginInfo = PluginInfo.create(jarFile, manifest);
assertThat(pluginInfo.getRequiredPlugins()).extracting("key").containsOnly("java", "pmd");
}
@DataProvider
public static Object[][] licenseVersions() {
return new Object[][] {
{"0.3"},
{"7.2.0.1253"}
};
}
@Test
public void create_from_file() {
File checkstyleJar = FileUtils.toFile(getClass().getResource("/org/sonar/core/platform/sonar-checkstyle-plugin-2.8.jar"));
PluginInfo checkstyleInfo = PluginInfo.create(checkstyleJar);
assertThat(checkstyleInfo.getName()).isEqualTo("Checkstyle");
assertThat(checkstyleInfo.getDocumentationPath()).isNull();
assertThat(checkstyleInfo.getMinimalSonarPluginApiVersion()).isEqualTo(Version.create("2.8"));
}
@Test
public void create_from_file_with_documentation() {
File jarWithDocs = FileUtils.toFile(getClass().getResource("/org/sonar/core/platform/jar_with_documentation.jar"));
PluginInfo checkstyleInfo = PluginInfo.create(jarWithDocs);
assertThat(checkstyleInfo.getDocumentationPath()).isNotBlank();
assertThat(checkstyleInfo.getDocumentationPath()).isEqualTo("static/documentation.md");
}
@Test
public void test_toString() {
PluginInfo pluginInfo = new PluginInfo("java").setVersion(Version.create("1.1"));
assertThat(pluginInfo).hasToString("[java / 1.1]");
pluginInfo.setImplementationBuild("SHA1");
assertThat(pluginInfo).hasToString("[java / 1.1 / SHA1]");
}
/**
* The English bundle plugin was removed in 5.2. L10n plugins do not need to declare
* it as base plugin anymore
*/
@Test
public void l10n_plugins_should_not_extend_english_plugin() {
PluginInfo pluginInfo = new PluginInfo("l10nfr").setBasePlugin("l10nen");
assertThat(pluginInfo.getBasePlugin()).isNull();
}
@Test
public void fail_when_jar_is_not_a_plugin() throws IOException {
// this JAR has a manifest but is not a plugin
File jarRootDir = temp.newFolder();
FileUtils.write(new File(jarRootDir, "META-INF/MANIFEST.MF"), "Build-Jdk: 1.6.0_15", StandardCharsets.UTF_8);
File jar = temp.newFile();
ZipUtils.zipDir(jarRootDir, jar);
assertThatThrownBy(() -> PluginInfo.create(jar))
.isInstanceOf(MessageException.class)
.hasMessage("File is not a plugin. Please delete it and restart: " + jar.getAbsolutePath());
}
PluginInfo withMinSqVersion(@Nullable String version) {
PluginInfo pluginInfo = new PluginInfo("foo");
if (version != null) {
pluginInfo.setMinimalSonarPluginApiVersion(Version.create(version));
}
return pluginInfo;
}
}
| 14,125 | 42.198777 | 126 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/PluginJarExploderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.utils.ZipUtils;
import static org.assertj.core.api.Assertions.assertThat;
public class PluginJarExploderTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void unzip_plugin_with_libs() throws Exception {
final File jarFile = getFile("sonar-checkstyle-plugin-2.8.jar");
final File toDir = temp.newFolder();
PluginInfo pluginInfo = new PluginInfo("checkstyle").setJarFile(jarFile);
PluginJarExploder exploder = new PluginJarExploder() {
@Override
public ExplodedPlugin explode(PluginInfo info) {
try {
ZipUtils.unzip(jarFile, toDir, newLibFilter());
return explodeFromUnzippedDir(info, info.getNonNullJarFile(), toDir);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
};
ExplodedPlugin exploded = exploder.explode(pluginInfo);
assertThat(exploded.getKey()).isEqualTo("checkstyle");
assertThat(exploded.getLibs()).extracting("name").containsOnly("antlr-2.7.6.jar", "checkstyle-5.1.jar", "commons-cli-1.0.jar");
assertThat(exploded.getMain()).isSameAs(jarFile);
}
@Test
public void unzip_plugin_without_libs() throws Exception {
File jarFile = temp.newFile();
final File toDir = temp.newFolder();
PluginInfo pluginInfo = new PluginInfo("foo").setJarFile(jarFile);
PluginJarExploder exploder = new PluginJarExploder() {
@Override
public ExplodedPlugin explode(PluginInfo info) {
return explodeFromUnzippedDir(pluginInfo, info.getNonNullJarFile(), toDir);
}
};
ExplodedPlugin exploded = exploder.explode(pluginInfo);
assertThat(exploded.getKey()).isEqualTo("foo");
assertThat(exploded.getLibs()).isEmpty();
assertThat(exploded.getMain()).isSameAs(jarFile);
}
private File getFile(String filename) {
return FileUtils.toFile(getClass().getResource("/org/sonar/core/platform/" + filename));
}
}
| 2,977 | 35.765432 | 131 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/PriorityBeanFactoryTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import javax.annotation.Priority;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.annotation.AnnotationAwareOrderComparator;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class PriorityBeanFactoryTest {
private final DefaultListableBeanFactory parentBeanFactory = new PriorityBeanFactory();
private final DefaultListableBeanFactory beanFactory = new PriorityBeanFactory();
@Before
public void setUp() {
// needed to support autowiring with @Inject
beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor());
//needed to read @Priority
beanFactory.setDependencyComparator(new AnnotationAwareOrderComparator());
beanFactory.setParentBeanFactory(parentBeanFactory);
}
@Test
public void give_priority_to_child_container() {
parentBeanFactory.registerBeanDefinition("A1", new RootBeanDefinition(A1.class));
beanFactory.registerBeanDefinition("A2", new RootBeanDefinition(A2.class));
beanFactory.registerBeanDefinition("B", new RootBeanDefinition(B.class));
assertThat(beanFactory.getBean(B.class).dep.getClass()).isEqualTo(A2.class);
}
@Test
public void follow_priority_annotations() {
parentBeanFactory.registerBeanDefinition("A3", new RootBeanDefinition(A3.class));
beanFactory.registerBeanDefinition("A1", new RootBeanDefinition(A1.class));
beanFactory.registerBeanDefinition("A2", new RootBeanDefinition(A2.class));
beanFactory.registerBeanDefinition("B", new RootBeanDefinition(B.class));
assertThat(beanFactory.getBean(B.class).dep.getClass()).isEqualTo(A3.class);
}
@Test
public void throw_NoUniqueBeanDefinitionException_if_cant_find_single_bean_with_higher_priority() {
beanFactory.registerBeanDefinition("A1", new RootBeanDefinition(A1.class));
beanFactory.registerBeanDefinition("A2", new RootBeanDefinition(A2.class));
beanFactory.registerBeanDefinition("B", new RootBeanDefinition(B.class));
assertThatThrownBy(() -> beanFactory.getBean(B.class))
.hasRootCauseInstanceOf(NoUniqueBeanDefinitionException.class);
}
private static class B {
private final A dep;
public B(A dep) {
this.dep = dep;
}
}
private interface A {
}
private static class A1 implements A {
}
private static class A2 implements A {
}
@Priority(1)
private static class A3 implements A {
}
}
| 3,657 | 34.173077 | 101 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/ServerIdTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.core.util.UuidFactoryImpl;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.StringUtils.repeat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.core.platform.ServerId.DATABASE_ID_LENGTH;
import static org.sonar.core.platform.ServerId.DEPRECATED_SERVER_ID_LENGTH;
import static org.sonar.core.platform.ServerId.Format.DEPRECATED;
import static org.sonar.core.platform.ServerId.Format.NO_DATABASE_ID;
import static org.sonar.core.platform.ServerId.Format.WITH_DATABASE_ID;
import static org.sonar.core.platform.ServerId.NOT_UUID_DATASET_ID_LENGTH;
import static org.sonar.core.platform.ServerId.SPLIT_CHARACTER;
import static org.sonar.core.platform.ServerId.UUID_DATASET_ID_LENGTH;
@RunWith(DataProviderRunner.class)
public class ServerIdTest {
@Test
public void parse_throws_NPE_if_argument_is_null() {
assertThatThrownBy(() -> ServerId.parse(null))
.isInstanceOf(NullPointerException.class);
}
@Test
@UseDataProvider("emptyAfterTrim")
public void parse_throws_IAE_if_parameter_is_empty_after_trim(String serverId) {
assertThatThrownBy(() -> ServerId.parse(serverId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("serverId can't be empty");
}
@DataProvider
public static Object[][] emptyAfterTrim() {
return new Object[][] {
{""},
{" "},
{" "}
};
}
@Test
@UseDataProvider("wrongFormatWithDatabaseId")
public void parse_throws_IAE_if_split_char_is_at_wrong_position(String emptyDatabaseId) {
assertThatThrownBy(() -> ServerId.parse(emptyDatabaseId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unrecognized serverId format. Parts have wrong length");
}
@DataProvider
public static Object[][] wrongFormatWithDatabaseId() {
String onlySplitChar = repeat(SPLIT_CHARACTER + "", DATABASE_ID_LENGTH);
String startWithSplitChar = SPLIT_CHARACTER + randomAlphabetic(DATABASE_ID_LENGTH - 1);
Stream<String> databaseIds = Stream.of(
UuidFactoryImpl.INSTANCE.create(),
randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH),
randomAlphabetic(UUID_DATASET_ID_LENGTH),
repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH),
repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH));
return databaseIds
.flatMap(datasetId -> Stream.of(
startWithSplitChar + SPLIT_CHARACTER + datasetId,
onlySplitChar + SPLIT_CHARACTER + datasetId,
startWithSplitChar + randomAlphabetic(1) + datasetId,
onlySplitChar + randomAlphabetic(1) + datasetId))
.flatMap(serverId -> Stream.of(
serverId,
" " + serverId,
" " + serverId))
.map(t -> new Object[] {t})
.toArray(Object[][]::new);
}
@Test
public void parse_parses_deprecated_format_serverId() {
String deprecated = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
ServerId serverId = ServerId.parse(deprecated);
assertThat(serverId.getFormat()).isEqualTo(DEPRECATED);
assertThat(serverId.getDatasetId()).isEqualTo(deprecated);
assertThat(serverId.getDatabaseId()).isEmpty();
assertThat(serverId).hasToString(deprecated);
}
@Test
@UseDataProvider("validOldFormatServerIds")
public void parse_parses_no_databaseId_format_serverId(String noDatabaseId) {
ServerId serverId = ServerId.parse(noDatabaseId);
assertThat(serverId.getFormat()).isEqualTo(NO_DATABASE_ID);
assertThat(serverId.getDatasetId()).isEqualTo(noDatabaseId);
assertThat(serverId.getDatabaseId()).isEmpty();
assertThat(serverId).hasToString(noDatabaseId);
}
@DataProvider
public static Object[][] validOldFormatServerIds() {
return new Object[][] {
{UuidFactoryImpl.INSTANCE.create()},
{randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH)},
{repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH)},
{randomAlphabetic(UUID_DATASET_ID_LENGTH)},
{repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH)}
};
}
@Test
@UseDataProvider("validServerIdWithDatabaseId")
public void parse_parses_serverId_with_database_id(String databaseId, String datasetId) {
String rawServerId = databaseId + SPLIT_CHARACTER + datasetId;
ServerId serverId = ServerId.parse(rawServerId);
assertThat(serverId.getFormat()).isEqualTo(WITH_DATABASE_ID);
assertThat(serverId.getDatasetId()).isEqualTo(datasetId);
assertThat(serverId.getDatabaseId()).contains(databaseId);
assertThat(serverId).hasToString(rawServerId);
}
@DataProvider
public static Object[][] validServerIdWithDatabaseId() {
return new Object[][] {
{randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(NOT_UUID_DATASET_ID_LENGTH)},
{randomAlphabetic(DATABASE_ID_LENGTH), randomAlphabetic(UUID_DATASET_ID_LENGTH)},
{randomAlphabetic(DATABASE_ID_LENGTH), repeat(SPLIT_CHARACTER + "", NOT_UUID_DATASET_ID_LENGTH)},
{randomAlphabetic(DATABASE_ID_LENGTH), repeat(SPLIT_CHARACTER + "", UUID_DATASET_ID_LENGTH)},
{randomAlphabetic(DATABASE_ID_LENGTH), UuidFactoryImpl.INSTANCE.create()},
};
}
@Test
public void parse_does_not_support_deprecated_server_id_with_database_id() {
assertThatThrownBy(() -> ServerId.parse(randomAlphabetic(DATABASE_ID_LENGTH) + SPLIT_CHARACTER + randomAlphabetic(DEPRECATED_SERVER_ID_LENGTH)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("serverId does not have a supported length");
}
@Test
public void of_throws_NPE_if_datasetId_is_null() {
assertThatThrownBy(() -> ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), null))
.isInstanceOf(NullPointerException.class);
}
@Test
public void of_throws_IAE_if_datasetId_is_empty() {
assertThatThrownBy(() -> ServerId.of(randomAlphabetic(DATABASE_ID_LENGTH), ""))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Illegal datasetId length (0)");
}
@Test
public void of_throws_IAE_if_databaseId_is_empty() {
assertThatThrownBy(() -> ServerId.of("", randomAlphabetic(UUID_DATASET_ID_LENGTH)))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Illegal databaseId length (0)");
}
@Test
@UseDataProvider("datasetIdSupportedLengths")
public void of_accepts_null_databaseId(int datasetIdLength) {
String datasetId = randomAlphabetic(datasetIdLength);
ServerId serverId = ServerId.of(null, datasetId);
assertThat(serverId.getDatabaseId()).isEmpty();
assertThat(serverId.getDatasetId()).isEqualTo(datasetId);
}
@Test
@UseDataProvider("illegalDatabaseIdLengths")
public void of_throws_IAE_if_databaseId_length_is_not_8(int illegalDatabaseIdLengths) {
String databaseId = randomAlphabetic(illegalDatabaseIdLengths);
String datasetId = randomAlphabetic(UUID_DATASET_ID_LENGTH);
assertThatThrownBy(() -> ServerId.of(databaseId, datasetId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Illegal databaseId length (" + illegalDatabaseIdLengths + ")");
}
@DataProvider
public static Object[][] illegalDatabaseIdLengths() {
return IntStream.range(1, 8 + new Random().nextInt(5))
.filter(i -> i != DATABASE_ID_LENGTH)
.mapToObj(i -> new Object[] {i})
.toArray(Object[][]::new);
}
@Test
@UseDataProvider("illegalDatasetIdLengths")
public void of_throws_IAE_if_datasetId_length_is_not_8(int illegalDatasetIdLengths) {
String datasetId = randomAlphabetic(illegalDatasetIdLengths);
String databaseId = randomAlphabetic(DATABASE_ID_LENGTH);
assertThatThrownBy(() -> ServerId.of(databaseId, datasetId))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Illegal datasetId length (" + illegalDatasetIdLengths + ")");
}
@DataProvider
public static Object[][] illegalDatasetIdLengths() {
return IntStream.range(1, UUID_DATASET_ID_LENGTH + new Random().nextInt(5))
.filter(i -> i != UUID_DATASET_ID_LENGTH)
.filter(i -> i != NOT_UUID_DATASET_ID_LENGTH)
.filter(i -> i != DEPRECATED_SERVER_ID_LENGTH)
.mapToObj(i -> new Object[] {i})
.toArray(Object[][]::new);
}
@Test
@UseDataProvider("datasetIdSupportedLengths")
public void equals_is_based_on_databaseId_and_datasetId(int datasetIdLength) {
String databaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'a';
String otherDatabaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'b';
String datasetId = randomAlphabetic(datasetIdLength - 1) + 'a';
String otherDatasetId = randomAlphabetic(datasetIdLength - 1) + 'b';
ServerId newServerId = ServerId.of(databaseId, datasetId);
assertThat(newServerId)
.isEqualTo(newServerId)
.isEqualTo(ServerId.of(databaseId, datasetId))
.isNotEqualTo(new Object())
.isNotNull()
.isNotEqualTo(ServerId.of(otherDatabaseId, datasetId))
.isNotEqualTo(ServerId.of(databaseId, otherDatasetId))
.isNotEqualTo(ServerId.of(otherDatabaseId, otherDatasetId));
ServerId oldServerId = ServerId.parse(datasetId);
assertThat(oldServerId)
.isEqualTo(oldServerId)
.isEqualTo(ServerId.parse(datasetId))
.isNotEqualTo(ServerId.parse(otherDatasetId))
.isNotEqualTo(ServerId.of(databaseId, datasetId));
}
@Test
@UseDataProvider("datasetIdSupportedLengths")
public void hashcode_is_based_on_databaseId_and_datasetId(int datasetIdLength) {
String databaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'a';
String otherDatabaseId = randomAlphabetic(DATABASE_ID_LENGTH - 1) + 'b';
String datasetId = randomAlphabetic(datasetIdLength - 1) + 'a';
String otherDatasetId = randomAlphabetic(datasetIdLength - 1) + 'b';
ServerId newServerId = ServerId.of(databaseId, datasetId);
assertThat(newServerId)
.hasSameHashCodeAs(newServerId)
.hasSameHashCodeAs(ServerId.of(databaseId, datasetId));
assertThat(newServerId.hashCode())
.isNotEqualTo(new Object().hashCode())
.isNotEqualTo(ServerId.of(otherDatabaseId, datasetId).hashCode())
.isNotEqualTo(ServerId.of(databaseId, otherDatasetId).hashCode())
.isNotEqualTo(ServerId.of(otherDatabaseId, otherDatasetId).hashCode());
ServerId oldServerId = ServerId.parse(datasetId);
assertThat(oldServerId)
.hasSameHashCodeAs(oldServerId)
.hasSameHashCodeAs(ServerId.parse(datasetId));
assertThat(oldServerId.hashCode())
.isNotEqualTo(ServerId.parse(otherDatasetId).hashCode())
.isNotEqualTo(ServerId.of(databaseId, datasetId).hashCode());
}
@DataProvider
public static Object[][] datasetIdSupportedLengths() {
return new Object[][] {
{ServerId.NOT_UUID_DATASET_ID_LENGTH},
{UUID_DATASET_ID_LENGTH},
};
}
}
| 12,097 | 38.927393 | 148 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/SonarQubeVersionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import org.junit.Test;
import org.sonar.api.utils.Version;
import static org.assertj.core.api.Assertions.assertThat;
public class SonarQubeVersionTest {
@Test
public void verify_methods() {
var version = Version.create(9, 5);
SonarQubeVersion underTest = new SonarQubeVersion(version);
assertThat(underTest).extracting(SonarQubeVersion::toString, SonarQubeVersion::get)
.containsExactly("9.5", version);
var otherVersion = Version.create(8, 5);
assertThat(underTest.isGreaterThanOrEqual(otherVersion)).isTrue();
}
}
| 1,429 | 34.75 | 87 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/SpringComponentContainerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.junit.Test;
import org.sonar.api.Property;
import org.sonar.api.Startable;
import org.sonar.api.config.PropertyDefinition;
import org.sonar.api.config.PropertyDefinitions;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertThrows;
public class SpringComponentContainerTest {
@Test
public void should_stop_after_failing() {
ApiStartable startStop = new ApiStartable();
SpringComponentContainer container = new SpringComponentContainer() {
@Override
public void doBeforeStart() {
add(startStop);
}
@Override
public void doAfterStart() {
getComponentByType(ApiStartable.class);
throw new IllegalStateException("doBeforeStart");
}
};
assertThrows("doBeforeStart", IllegalStateException.class, container::execute);
assertThat(startStop.start).isOne();
assertThat(startStop.stop).isOne();
}
@Test
public void add_registers_instance_with_toString() {
SpringComponentContainer container = new SimpleContainer(new ToString("a"), new ToString("b"));
container.startComponents();
assertThat(container.context.getBeanDefinitionNames())
.contains(
this.getClass().getClassLoader() + "-org.sonar.core.platform.SpringComponentContainerTest.ToString-a",
this.getClass().getClassLoader() + "-org.sonar.core.platform.SpringComponentContainerTest.ToString-b");
assertThat(container.getComponentsByType(ToString.class)).hasSize(2);
}
@Test
public void add_registers_class_with_classloader_and_fqcn() {
SpringComponentContainer container = new SimpleContainer(A.class, B.class);
container.startComponents();
assertThat(container.context.getBeanDefinitionNames())
.contains(
this.getClass().getClassLoader() + "-org.sonar.core.platform.SpringComponentContainerTest.A",
this.getClass().getClassLoader() + "-org.sonar.core.platform.SpringComponentContainerTest.B");
assertThat(container.getComponentByType(A.class)).isNotNull();
assertThat(container.getComponentByType(B.class)).isNotNull();
}
@Test
public void add_configures_module_instances() {
SpringComponentContainer container = new SpringComponentContainer();
container.add(new TestModule());
container.startComponents();
assertThat(container.getComponentByType(A.class)).isNotNull();
}
@Test
public void get_optional_component_by_type_should_return_correctly() {
SpringComponentContainer container = new SpringComponentContainer();
container.add(A.class);
container.startComponents();
assertThat(container.getOptionalComponentByType(A.class)).containsInstanceOf(A.class);
assertThat(container.getOptionalComponentByType(B.class)).isEmpty();
}
@Test
public void createChild_method_should_spawn_a_child_container(){
SpringComponentContainer parent = new SpringComponentContainer();
SpringComponentContainer child = parent.createChild();
assertThat(child).isNotEqualTo(parent);
assertThat(child.parent).isEqualTo(parent);
assertThat(parent.children).contains(child);
}
@Test
public void get_component_by_type_should_throw_exception_when_type_does_not_exist() {
SpringComponentContainer container = new SpringComponentContainer();
container.add(A.class);
container.startComponents();
assertThatThrownBy(() -> container.getComponentByType(B.class))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Unable to load component class org.sonar.core.platform.SpringComponentContainerTest$B");
}
@Test
public void add_fails_if_adding_module_class() {
SpringComponentContainer container = new SpringComponentContainer();
container.startComponents();
assertThatThrownBy(() -> container.add(TestModule.class))
.hasMessage("Modules should be added as instances")
.isInstanceOf(IllegalStateException.class);
}
@Test
public void should_throw_start_exception_if_stop_also_throws_exception() {
ErrorStopClass errorStopClass = new ErrorStopClass();
SpringComponentContainer container = new SpringComponentContainer() {
@Override
public void doBeforeStart() {
add(errorStopClass);
}
@Override
public void doAfterStart() {
getComponentByType(ErrorStopClass.class);
throw new IllegalStateException("doBeforeStart");
}
};
assertThrows("doBeforeStart", IllegalStateException.class, container::execute);
assertThat(errorStopClass.stopped).isTrue();
}
@Test
public void addExtension_supports_extensions_without_annotations() {
SpringComponentContainer container = new SimpleContainer(A.class, B.class);
container.addExtension("", ExtensionWithMultipleConstructorsAndNoAnnotations.class);
container.startComponents();
assertThat(container.getComponentByType(ExtensionWithMultipleConstructorsAndNoAnnotations.class).gotBothArgs).isTrue();
}
@Test
public void addExtension_supports_extension_instances_without_annotations() {
SpringComponentContainer container = new SpringComponentContainer();
container.addExtension("", new ExtensionWithMultipleConstructorsAndNoAnnotations(new A()));
container.startComponents();
assertThat(container.getComponentByType(ExtensionWithMultipleConstructorsAndNoAnnotations.class)).isNotNull();
}
@Test
public void addExtension_resolves_iterables() {
List<Class<?>> classes = Arrays.asList(A.class, B.class);
SpringComponentContainer container = new SpringComponentContainer();
container.addExtension("", classes);
container.startComponents();
assertThat(container.getComponentByType(A.class)).isNotNull();
assertThat(container.getComponentByType(B.class)).isNotNull();
}
@Test
public void addExtension_adds_property_with_PluginInfo() {
PluginInfo info = new PluginInfo("plugin1").setName("plugin1");
SpringComponentContainer container = new SpringComponentContainer();
container.addExtension(info, A.class);
container.startComponents();
PropertyDefinitions propertyDefinitions = container.getComponentByType(PropertyDefinitions.class);
PropertyDefinition propertyDefinition = propertyDefinitions.get("k");
assertThat(propertyDefinition.key()).isEqualTo("k");
assertThat(propertyDefinitions.getCategory("k")).isEqualTo("plugin1");
}
@Test
public void declareExtension_adds_property() {
SpringComponentContainer container = new SpringComponentContainer();
container.addExtension((PluginInfo) null, A.class);
container.startComponents();
PropertyDefinitions propertyDefinitions = container.getComponentByType(PropertyDefinitions.class);
PropertyDefinition propertyDefinition = propertyDefinitions.get("k");
assertThat(propertyDefinition.key()).isEqualTo("k");
assertThat(propertyDefinitions.getCategory("k")).isEmpty();
}
@Test
public void stop_should_stop_children() {
SpringComponentContainer parent = new SpringComponentContainer();
ApiStartable s1 = new ApiStartable();
parent.add(s1);
parent.startComponents();
SpringComponentContainer child = new SpringComponentContainer(parent);
assertThat(child.getParent()).isEqualTo(parent);
assertThat(parent.children).containsOnly(child);
ApiStartable s2 = new ApiStartable();
child.add(s2);
child.startComponents();
parent.stopComponents();
assertThat(s1.stop).isOne();
assertThat(s2.stop).isOne();
}
@Test
public void stop_should_remove_container_from_parent() {
SpringComponentContainer parent = new SpringComponentContainer();
SpringComponentContainer child = new SpringComponentContainer(parent);
assertThat(parent.children).containsOnly(child);
child.stopComponents();
assertThat(parent.children).isEmpty();
}
@Test
public void bean_create_fails_if_class_has_default_constructor_and_other_constructors() {
SpringComponentContainer container = new SpringComponentContainer();
container.add(ClassWithMultipleConstructorsIncNoArg.class);
container.startComponents();
assertThatThrownBy(() -> container.getComponentByType(ClassWithMultipleConstructorsIncNoArg.class))
.hasRootCauseMessage("Constructor annotations missing in: class org.sonar.core.platform.SpringComponentContainerTest$ClassWithMultipleConstructorsIncNoArg");
}
@Test
public void support_start_stop_callbacks() {
JsrLifecycleCallbacks jsr = new JsrLifecycleCallbacks();
ApiStartable api = new ApiStartable();
AutoClose closeable = new AutoClose();
SpringComponentContainer container = new SimpleContainer(jsr, api, closeable) {
@Override
public void doAfterStart() {
// force lazy instantiation
getComponentByType(JsrLifecycleCallbacks.class);
getComponentByType(ApiStartable.class);
getComponentByType(AutoClose.class);
}
};
container.execute();
assertThat(closeable.closed).isOne();
assertThat(jsr.postConstruct).isOne();
assertThat(jsr.preDestroy).isOne();
assertThat(api.start).isOne();
assertThat(api.stop).isOne();
}
private static class TestModule extends Module {
@Override
protected void configureModule() {
add(A.class);
}
}
private static class JsrLifecycleCallbacks {
private int postConstruct = 0;
private int preDestroy = 0;
@PostConstruct
public void postConstruct() {
postConstruct++;
}
@PreDestroy
public void preDestroy() {
preDestroy++;
}
}
private static class AutoClose implements AutoCloseable {
private int closed = 0;
@Override
public void close() {
closed++;
}
}
private static class ApiStartable implements Startable {
private int start = 0;
private int stop = 0;
public void start() {
start++;
}
public void stop() {
stop++;
}
}
private static class ToString {
private final String toString;
public ToString(String toString) {
this.toString = toString;
}
@Override
public String toString() {
return toString;
}
}
@Property(key = "k", name = "name")
private static class A {
}
private static class B {
}
private static class ClassWithMultipleConstructorsIncNoArg {
public ClassWithMultipleConstructorsIncNoArg() {
}
public ClassWithMultipleConstructorsIncNoArg(A a) {
}
}
private static class ExtensionWithMultipleConstructorsAndNoAnnotations {
private boolean gotBothArgs = false;
public ExtensionWithMultipleConstructorsAndNoAnnotations(A a) {
}
public ExtensionWithMultipleConstructorsAndNoAnnotations(A a, B b) {
gotBothArgs = true;
}
}
private static class ErrorStopClass implements Startable {
private boolean stopped = false;
@Override
public void start() {
}
@Override
public void stop() {
stopped = true;
throw new IllegalStateException("stop");
}
}
private static class SimpleContainer extends SpringComponentContainer {
public SimpleContainer(Object... objects) {
add(objects);
}
}
}
| 12,208 | 33.008357 | 163 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/platform/StartableBeanPostProcessorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.platform;
import org.junit.Test;
import org.sonar.api.Startable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
public class StartableBeanPostProcessorTest {
private final StartableBeanPostProcessor underTest = new StartableBeanPostProcessor();
@Test
public void starts_api_startable() {
Startable startable = mock(Startable.class);
underTest.postProcessBeforeInitialization(startable, "startable");
verify(startable).start();
verifyNoMoreInteractions(startable);
}
@Test
public void stops_api_startable() {
Startable startable = mock(Startable.class);
underTest.postProcessBeforeDestruction(startable, "startable");
verify(startable).stop();
verifyNoMoreInteractions(startable);
}
@Test
public void startable_and_autoCloseable_should_require_destruction(){
assertThat(underTest.requiresDestruction(mock(Startable.class))).isTrue();
assertThat(underTest.requiresDestruction(mock(org.sonar.api.Startable.class))).isTrue();
assertThat(underTest.requiresDestruction(mock(Object.class))).isFalse();
}
}
| 2,088 | 36.303571 | 92 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/sarif/RuleTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.sarif;
import java.util.Set;
import org.junit.Test;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
public class RuleTest {
@Test
public void equals_matchOnlyOnId() {
Rule rule1 = createRule();
Rule rule1Bis = createRule(rule1.getId()) ;
Rule rule2 = withRuleId(rule1, rule1.getId() + randomAlphanumeric(3));
assertThat(rule1).isEqualTo(rule1Bis).isNotEqualTo(rule2);
}
@Test
public void equals_notMatchWithNull(){
Rule rule1 = createRule();
assertThat(rule1).isNotEqualTo(null);
}
@Test
public void equals_matchWithSameObject(){
Rule rule1 = createRule();
assertThat(rule1).isEqualTo(rule1);
}
private static Rule withRuleId(Rule rule, String id) {
return Rule.builder()
.id(id)
.name(rule.getName())
.shortDescription(rule.getName())
.fullDescription(rule.getName())
.help(rule.getFullDescription().getText())
.properties(rule.getProperties())
.build();
}
private static Rule createRule() {
return createRule(randomAlphanumeric(5));
}
private static Rule createRule(String id) {
return Rule.builder()
.id(id)
.name(randomAlphanumeric(5))
.shortDescription(randomAlphanumeric(5))
.fullDescription(randomAlphanumeric(10))
.help(randomAlphanumeric(10))
.properties(PropertiesBag.of(randomAlphanumeric(3), Set.of(randomAlphanumeric(4))))
.build();
}
}
| 2,374 | 28.320988 | 89 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/sarif/Sarif210SerializationDeserializationTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.sarif;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.sonar.core.sarif.Sarif210;
import org.sonar.test.JsonAssert;
import static java.util.Objects.requireNonNull;
public class Sarif210SerializationDeserializationTest {
private static final String VALID_SARIF_210_FILE_JSON = "valid-sarif210.json";
@Test
public void verify_json_serialization_of_sarif210() throws IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String expectedJson = IOUtils.toString(requireNonNull(getClass().getResource(VALID_SARIF_210_FILE_JSON)), StandardCharsets.UTF_8);
Sarif210 deserializedJson = gson.fromJson(expectedJson, Sarif210.class);
String reserializedJson = gson.toJson(deserializedJson);
JsonAssert.assertJson(reserializedJson).isSimilarTo(expectedJson);
}
}
| 1,831 | 36.387755 | 134 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/sarif/SarifSerializerImplTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.sarif;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;
import static org.sonar.core.sarif.SarifVersionValidator.UNSUPPORTED_VERSION_MESSAGE_TEMPLATE;
@RunWith(MockitoJUnitRunner.class)
public class SarifSerializerImplTest {
private static final String SARIF_JSON = "{\"version\":\"2.1.0\",\"$schema\":\"http://json.schemastore.org/sarif-2.1.0-rtm.4\",\"runs\":[{\"results\":[]}]}";
private final SarifSerializerImpl serializer = new SarifSerializerImpl();
@Test
public void serialize() {
Run.builder().results(Set.of()).build();
Sarif210 sarif210 = new Sarif210("http://json.schemastore.org/sarif-2.1.0-rtm.4", Run.builder().results(Set.of()).build());
String result = serializer.serialize(sarif210);
assertThat(result).isEqualTo(SARIF_JSON);
}
@Test
public void deserialize() throws URISyntaxException, NoSuchFileException {
URL sarifResource = requireNonNull(getClass().getResource("eslint-sarif210.json"));
Path sarif = Paths.get(sarifResource.toURI());
Sarif210 deserializationResult = serializer.deserialize(sarif);
verifySarif(deserializationResult);
}
@Test
public void deserialize_shouldFail_whenFileCantBeFound() {
String file = "wrongPathToFile";
Path sarif = Paths.get(file);
assertThatThrownBy(() -> serializer.deserialize(sarif))
.isInstanceOf(NoSuchFileException.class);
}
@Test
public void deserialize_shouldFail_whenJsonSyntaxIsIncorrect() throws URISyntaxException {
URL sarifResource = requireNonNull(getClass().getResource("invalid-json-syntax.json"));
Path sarif = Paths.get(sarifResource.toURI());
assertThatThrownBy(() -> serializer.deserialize(sarif))
.isInstanceOf(IllegalStateException.class)
.hasMessage(format("Failed to read SARIF report at '%s': invalid JSON syntax or file is not UTF-8 encoded", sarif));
}
@Test
public void deserialize_whenFileIsNotUtf8encoded_shouldFail() throws URISyntaxException {
URL sarifResource = requireNonNull(getClass().getResource("sarif210-nonUtf8.json"));
Path sarif = Paths.get(sarifResource.toURI());
assertThatThrownBy(() -> serializer.deserialize(sarif))
.isInstanceOf(IllegalStateException.class)
.hasMessage(format("Failed to read SARIF report at '%s': invalid JSON syntax or file is not UTF-8 encoded", sarif));
}
@Test
public void deserialize_shouldFail_whenSarifVersionIsNotSupported() throws URISyntaxException {
URL sarifResource = requireNonNull(getClass().getResource("unsupported-sarif-version-abc.json"));
Path sarif = Paths.get(sarifResource.toURI());
assertThatThrownBy(() -> serializer.deserialize(sarif))
.isInstanceOf(IllegalStateException.class)
.hasMessage(format(UNSUPPORTED_VERSION_MESSAGE_TEMPLATE, "A.B.C"));
}
private void verifySarif(Sarif210 deserializationResult) {
Sarif210 expected = buildExpectedSarif210();
assertThat(deserializationResult).isNotNull();
assertThat(deserializationResult).usingRecursiveComparison().ignoringFields("runs").isEqualTo(expected);
Run run = getRun(deserializationResult);
Run expectedRun = getRun(expected);
assertThat(run).usingRecursiveComparison().ignoringFields("results", "tool.driver.rules").isEqualTo(expectedRun);
Result result = getResult(run);
Result expectedResult = getResult(expectedRun);
assertThat(result).usingRecursiveComparison().isEqualTo(expectedResult);
Rule rule = getRule(run);
Rule expectedRule = getRule(expectedRun);
assertThat(rule).usingRecursiveComparison().ignoringFields("properties").isEqualTo(expectedRule);
}
private static Sarif210 buildExpectedSarif210() {
return new Sarif210("http://json.schemastore.org/sarif-2.1.0-rtm.4", buildExpectedRun());
}
private static Run buildExpectedRun() {
Tool tool = new Tool(buildExpectedDriver());
return Run.builder()
.tool(tool)
.results(Set.of(buildExpectedResult())).build();
}
private static Driver buildExpectedDriver() {
return Driver.builder()
.name("ESLint")
.rules(Set.of(buildExpectedRule()))
.build();
}
private static Rule buildExpectedRule() {
return Rule.builder()
.id("no-unused-vars")
.shortDescription("disallow unused variables")
.build();
}
private static Result buildExpectedResult() {
return Result.builder()
.ruleId("no-unused-vars")
.locations(Set.of(buildExpectedLocation()))
.message("'x' is assigned a value but never used.")
.level("error")
.build();
}
private static Location buildExpectedLocation() {
ArtifactLocation artifactLocation = new ArtifactLocation(null, "file:///C:/dev/sarif/sarif-tutorials/samples/Introduction/simple-example.js");
PhysicalLocation physicalLocation = PhysicalLocation.of(artifactLocation, buildExpectedRegion());
return Location.of(physicalLocation);
}
private static Region buildExpectedRegion() {
return Region.builder()
.startLine(1)
.startColumn(5)
.build();
}
private static Run getRun(Sarif210 sarif210) {
return sarif210.getRuns().stream().findFirst().orElseGet(() -> fail("runs property is missing"));
}
private static Result getResult(Run run) {
return run.getResults().stream().findFirst().orElseGet(() -> fail("results property is missing"));
}
private static Rule getRule(Run run) {
return run.getTool().getDriver().getRules().stream().findFirst().orElseGet(() -> fail("rules property is missing"));
}
}
| 6,866 | 36.320652 | 159 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/sarif/SarifVersionValidatorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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.sarif;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
import static org.sonar.core.sarif.SarifVersionValidator.SUPPORTED_SARIF_VERSIONS;
import static org.sonar.core.sarif.SarifVersionValidator.UNSUPPORTED_VERSION_MESSAGE_TEMPLATE;
@RunWith(DataProviderRunner.class)
public class SarifVersionValidatorTest {
@Test
@UseDataProvider("unsupportedSarifVersions")
public void sarif_version_validation_fails_if_version_is_not_supported(String version) {
assertThatThrownBy(() -> SarifVersionValidator.validateSarifVersion(version))
.isExactlyInstanceOf(IllegalStateException.class)
.hasMessage(format(UNSUPPORTED_VERSION_MESSAGE_TEMPLATE, version));
}
@Test
@UseDataProvider("supportedSarifVersions")
public void sarif_version_validation_succeeds_if_version_is_supported(String version) {
assertThatCode(() -> SarifVersionValidator.validateSarifVersion(version))
.doesNotThrowAnyException();
}
@DataProvider
public static List<String> unsupportedSarifVersions() {
List<String> unsupportedVersions = generateRandomUnsupportedSemanticVersions(10);
unsupportedVersions.add(null);
return unsupportedVersions;
}
@DataProvider
public static Set<String> supportedSarifVersions() {
return SUPPORTED_SARIF_VERSIONS;
}
private static List<String> generateRandomUnsupportedSemanticVersions(int amount) {
return Stream
.generate(SarifVersionValidatorTest::generateRandomSemanticVersion)
.takeWhile(SarifVersionValidatorTest::isUnsupportedVersion)
.limit(amount)
.collect(Collectors.toList());
}
private static String generateRandomSemanticVersion() {
return IntStream
.rangeClosed(1, 3)
.mapToObj(x -> RandomStringUtils.randomNumeric(1))
.collect(Collectors.joining("."));
}
private static boolean isUnsupportedVersion(String version) {
return !SUPPORTED_SARIF_VERSIONS.contains(version);
}
}
| 3,354 | 36.277778 | 94 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/CloseableIteratorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.junit.Test;
import org.mockito.InOrder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
public class CloseableIteratorTest {
@Test
public void iterate() {
SimpleCloseableIterator it = new SimpleCloseableIterator();
assertThat(it.isClosed).isFalse();
// multiple calls to hasNext() moves only once the cursor
assertThat(it.hasNext()).isTrue();
assertThat(it.hasNext()).isTrue();
assertThat(it.hasNext()).isTrue();
assertThat(it.next()).isEqualTo(1);
assertThat(it.isClosed).isFalse();
assertThat(it.hasNext()).isTrue();
assertThat(it.next()).isEqualTo(2);
assertThat(it.isClosed).isFalse();
assertThat(it.hasNext()).isFalse();
// automatic close
assertThat(it.isClosed).isTrue();
// explicit close does not fail
it.close();
assertThat(it.isClosed).isTrue();
}
@Test
public void call_next_without_hasNext() {
SimpleCloseableIterator it = new SimpleCloseableIterator();
assertThat(it.next()).isEqualTo(1);
assertThat(it.next()).isEqualTo(2);
try {
it.next();
fail();
} catch (NoSuchElementException expected) {
}
}
@Test
public void automatic_close_if_traversal_error() {
FailureCloseableIterator it = new FailureCloseableIterator();
try {
it.next();
fail();
} catch (IllegalStateException expected) {
assertThat(expected).hasMessage("expected failure");
assertThat(it.isClosed).isTrue();
}
}
@Test
public void remove_is_not_supported_by_default() {
SimpleCloseableIterator it = new SimpleCloseableIterator();
try {
it.remove();
fail();
} catch (UnsupportedOperationException expected) {
assertThat(it.isClosed).isTrue();
}
}
@Test
public void remove_can_be_overridden() {
RemovableCloseableIterator it = new RemovableCloseableIterator();
it.remove();
assertThat(it.isRemoved).isTrue();
}
@Test
public void has_next_should_not_call_do_next_when_already_closed() {
DoNextShouldNotBeCalledWhenClosedIterator it = new DoNextShouldNotBeCalledWhenClosedIterator();
it.next();
it.next();
assertThat(it.hasNext()).isFalse();
// this call to hasNext close the stream
assertThat(it.hasNext()).isFalse();
assertThat(it.isClosed).isTrue();
// calling hasNext should not fail
it.hasNext();
}
@Test
public void emptyIterator_has_next_is_false() {
assertThat(CloseableIterator.emptyCloseableIterator().hasNext()).isFalse();
}
@Test(expected = NoSuchElementException.class)
public void emptyIterator_next_throws_NoSuchElementException() {
CloseableIterator.emptyCloseableIterator().next();
}
@Test(expected = NullPointerException.class)
public void from_iterator_throws_early_NPE_if_arg_is_null() {
CloseableIterator.from(null);
}
@Test(expected = IllegalArgumentException.class)
public void from_iterator_throws_IAE_if_arg_is_a_CloseableIterator() {
CloseableIterator.from(new SimpleCloseableIterator());
}
@Test(expected = IllegalArgumentException.class)
public void from_iterator_throws_IAE_if_arg_is_a_AutoCloseable() {
CloseableIterator.from(new CloseableIt());
}
@Test
public void wrap_closeables() throws Exception {
AutoCloseable closeable1 = mock(AutoCloseable.class);
AutoCloseable closeable2 = mock(AutoCloseable.class);
CloseableIterator iterator = new SimpleCloseableIterator();
CloseableIterator wrapper = CloseableIterator.wrap(iterator, closeable1, closeable2);
assertThat(wrapper.next()).isEqualTo(1);
assertThat(wrapper.next()).isEqualTo(2);
assertThat(wrapper.hasNext()).isFalse();
assertThat(wrapper.isClosed).isTrue();
assertThat(iterator.isClosed).isTrue();
InOrder order = inOrder(closeable1, closeable2);
order.verify(closeable1).close();
order.verify(closeable2).close();
}
@Test(expected = IllegalArgumentException.class)
public void wrap_fails_if_iterator_declared_in_other_closeables() {
CloseableIterator iterator = new SimpleCloseableIterator();
CloseableIterator.wrap(iterator, iterator);
}
@Test(expected = NullPointerException.class)
public void wrap_fails_if_null_closeable() {
CloseableIterator.wrap(new SimpleCloseableIterator(), (AutoCloseable)null);
}
private static class CloseableIt implements Iterator<String>, AutoCloseable {
private final Iterator<String> delegate = Collections.<String>emptyList().iterator();
@Override
public void remove() {
delegate.remove();
}
@Override
public String next() {
return delegate.next();
}
@Override
public boolean hasNext() {
return delegate.hasNext();
}
@Override
public void close() {
// no need to implement it for real
}
}
@Test
public void verify_has_next_from_iterator_with_empty_iterator() {
assertThat(CloseableIterator.from(Collections.<String>emptyList().iterator()).hasNext()).isFalse();
}
@Test(expected = NoSuchElementException.class)
public void verify_next_from_iterator_with_empty_iterator() {
CloseableIterator.from(Collections.<String>emptyList().iterator()).next();
}
static class SimpleCloseableIterator extends CloseableIterator<Object> {
int count = 0;
boolean isClosed = false;
@Override
protected Object doNext() {
count++;
if (count < 3) {
return count;
}
return null;
}
@Override
protected void doClose() {
isClosed = true;
}
}
static class FailureCloseableIterator extends CloseableIterator {
boolean isClosed = false;
@Override
protected Object doNext() {
throw new IllegalStateException("expected failure");
}
@Override
protected void doClose() {
isClosed = true;
}
}
static class RemovableCloseableIterator extends CloseableIterator {
boolean isClosed = false;
boolean isRemoved = false;
@Override
protected Object doNext() {
return "foo";
}
@Override
protected void doRemove() {
isRemoved = true;
}
@Override
protected void doClose() {
isClosed = true;
}
}
static class DoNextShouldNotBeCalledWhenClosedIterator extends SimpleCloseableIterator {
@Override
protected Object doNext() {
if (!isClosed) {
return super.doNext();
} else {
throw new IllegalStateException("doNext should not be called when already closed");
}
}
}
}
| 7,597 | 26.933824 | 103 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/ContextExceptionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ContextExceptionTest {
public static final String LABEL = "something wrong";
@Test
public void only_label() {
ContextException e = ContextException.of(LABEL);
assertThat(e.getMessage()).isEqualTo(LABEL);
assertThat(e.getRawMessage()).isEqualTo(LABEL);
assertThat(e.getCause()).isNull();
}
@Test
public void only_cause() {
Exception cause = new Exception("cause");
ContextException e = ContextException.of(cause);
assertThat(e.getMessage()).isEqualTo("java.lang.Exception: cause");
assertThat(e.getRawMessage()).isEqualTo("java.lang.Exception: cause");
assertThat(e.getCause()).isSameAs(cause);
}
@Test
public void cause_and_message() {
Exception cause = new Exception("cause");
ContextException e = ContextException.of(LABEL, cause);
assertThat(e.getMessage()).isEqualTo(LABEL);
assertThat(e.getRawMessage()).isEqualTo(LABEL);
assertThat(e.getCause()).isSameAs(cause);
}
@Test
public void addContext() {
ContextException e = ContextException.of(LABEL)
.addContext("K1", "V1")
.addContext("K2", "V2");
assertThat(e).hasMessage(LABEL + " | K1=V1 | K2=V2");
}
@Test
public void setContext() {
ContextException e = ContextException.of(LABEL)
.addContext("K1", "V1")
.setContext("K1", "V2");
assertThat(e).hasMessage(LABEL + " | K1=V2");
}
@Test
public void multiple_context_values() {
ContextException e = ContextException.of(LABEL)
.addContext("K1", "V1")
.addContext("K1", "V2");
assertThat(e).hasMessage(LABEL + " | K1=[V1,V2]");
}
@Test
public void merge_ContextException() {
ContextException cause = ContextException.of("cause").addContext("K1", "V1");
ContextException e = ContextException.of(cause)
.addContext("K1", "V11")
.addContext("K2", "V2");
assertThat(e.getContext("K1")).containsExactly("V1", "V11");
assertThat(e.getContext("K2")).containsOnly("V2");
assertThat(e).hasMessage("K1=[V1,V11] | K2=V2");
}
@Test
public void merge_ContextException_with_new_message() {
ContextException cause = ContextException.of("cause").addContext("K1", "V1");
ContextException e = ContextException.of(LABEL, cause).addContext("K2", "V2");
assertThat(e.getContext("K1")).containsOnly("V1");
assertThat(e.getContext("K2")).containsOnly("V2");
assertThat(e).hasMessage(LABEL + " | K1=V1 | K2=V2");
}
}
| 3,390 | 32.91 | 82 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/FileUtilsTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.BasicFileAttributes;
import javax.annotation.CheckForNull;
import org.apache.commons.lang.SystemUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assume.assumeTrue;
public class FileUtilsTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void cleanDirectory_throws_NPE_if_file_is_null() throws IOException {
assertThatThrownBy(() -> FileUtils.cleanDirectory(null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Directory can not be null");
}
@Test
public void cleanDirectory_does_nothing_if_argument_does_not_exist() throws IOException {
FileUtils.cleanDirectory(new File("/a/b/ToDoSSS"));
}
@Test
public void cleanDirectory_throws_IAE_if_argument_is_a_file() throws IOException {
File file = temporaryFolder.newFile();
assertThatThrownBy(() -> FileUtils.cleanDirectory(file))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("'" + file.getAbsolutePath() + "' is not a directory");
}
@Test
public void cleanDirectory_removes_directories_and_files_in_target_directory_but_not_target_directory() throws IOException {
Path target = temporaryFolder.newFolder().toPath();
Path childFile1 = Files.createFile(target.resolve("file1.txt"));
Path childDir1 = Files.createDirectory(target.resolve("subDir1"));
Path childFile2 = Files.createFile(childDir1.resolve("file2.txt"));
Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2"));
assertThat(target).isDirectory();
assertThat(childFile1).isRegularFile();
assertThat(childDir1).isDirectory();
assertThat(childFile2).isRegularFile();
assertThat(childDir2).isDirectory();
// on supporting FileSystem, target will change if directory is recreated
Object targetKey = getFileKey(target);
FileUtils.cleanDirectory(target.toFile());
assertThat(target).isDirectory();
assertThat(childFile1).doesNotExist();
assertThat(childDir1).doesNotExist();
assertThat(childFile2).doesNotExist();
assertThat(childDir2).doesNotExist();
assertThat(getFileKey(target)).isEqualTo(targetKey);
}
@Test
public void cleanDirectory_follows_symlink_to_target_directory() throws IOException {
assumeTrue(SystemUtils.IS_OS_UNIX);
Path target = temporaryFolder.newFolder().toPath();
Path symToDir = Files.createSymbolicLink(temporaryFolder.newFolder().toPath().resolve("sym_to_dir"), target);
Path childFile1 = Files.createFile(target.resolve("file1.txt"));
Path childDir1 = Files.createDirectory(target.resolve("subDir1"));
Path childFile2 = Files.createFile(childDir1.resolve("file2.txt"));
Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2"));
assertThat(target).isDirectory();
assertThat(symToDir).isSymbolicLink();
assertThat(childFile1).isRegularFile();
assertThat(childDir1).isDirectory();
assertThat(childFile2).isRegularFile();
assertThat(childDir2).isDirectory();
// on supporting FileSystem, target will change if directory is recreated
Object targetKey = getFileKey(target);
Object symLinkKey = getFileKey(symToDir);
FileUtils.cleanDirectory(symToDir.toFile());
assertThat(target).isDirectory();
assertThat(symToDir).isSymbolicLink();
assertThat(childFile1).doesNotExist();
assertThat(childDir1).doesNotExist();
assertThat(childFile2).doesNotExist();
assertThat(childDir2).doesNotExist();
assertThat(getFileKey(target)).isEqualTo(targetKey);
assertThat(getFileKey(symToDir)).isEqualTo(symLinkKey);
}
@Test
public void deleteQuietly_does_not_fail_if_argument_is_null() {
FileUtils.deleteQuietly((File) null);
FileUtils.deleteQuietly((Path) null);
}
@Test
public void deleteQuietly_does_not_fail_if_file_does_not_exist() throws IOException {
File file = new File(temporaryFolder.newFolder(), "blablabl");
assertThat(file).doesNotExist();
FileUtils.deleteQuietly(file);
}
@Test
public void deleteQuietly_deletes_directory_and_content() throws IOException {
Path target = temporaryFolder.newFolder().toPath();
Path childFile1 = Files.createFile(target.resolve("file1.txt"));
Path childDir1 = Files.createDirectory(target.resolve("subDir1"));
Path childFile2 = Files.createFile(childDir1.resolve("file2.txt"));
Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2"));
assertThat(target).isDirectory();
assertThat(childFile1).isRegularFile();
assertThat(childDir1).isDirectory();
assertThat(childFile2).isRegularFile();
assertThat(childDir2).isDirectory();
FileUtils.deleteQuietly(target.toFile());
assertThat(target).doesNotExist();
assertThat(childFile1).doesNotExist();
assertThat(childDir1).doesNotExist();
assertThat(childFile2).doesNotExist();
assertThat(childDir2).doesNotExist();
}
@Test
public void humanReadableByteCountSI_returns_bytes() {
assertThat(FileUtils.humanReadableByteCountSI(123)).isEqualTo("123 bytes");
assertThat(FileUtils.humanReadableByteCountSI(0)).isEqualTo("0 bytes");
assertThat(FileUtils.humanReadableByteCountSI(1)).isEqualTo("1 byte");
}
@Test
public void humanReadableByteCountSI_returns_kbs() {
assertThat(FileUtils.humanReadableByteCountSI(1_234)).isEqualTo("1.2 kB");
assertThat(FileUtils.humanReadableByteCountSI(1_000)).isEqualTo("1.0 kB");
assertThat(FileUtils.humanReadableByteCountSI(9_999)).isEqualTo("10.0 kB");
assertThat(FileUtils.humanReadableByteCountSI(999_949)).isEqualTo("999.9 kB");
}
@Test
public void humanReadableByteCountSI_returns_tbs() {
assertThat(FileUtils.humanReadableByteCountSI(1_234_000_000_000L)).isEqualTo("1.2 TB");
}
@Test
public void humanReadableByteCountSI_returns_mbs() {
assertThat(FileUtils.humanReadableByteCountSI(1234567)).isEqualTo("1.2 MB");
}
@Test
public void deleteQuietly_deletes_symbolicLink() throws IOException {
assumeTrue(SystemUtils.IS_OS_UNIX);
Path folder = temporaryFolder.newFolder().toPath();
Path file1 = Files.createFile(folder.resolve("file1.txt"));
Path symLink = Files.createSymbolicLink(folder.resolve("link1"), file1);
assertThat(file1).isRegularFile();
assertThat(symLink).isSymbolicLink();
FileUtils.deleteQuietly(symLink.toFile());
assertThat(symLink).doesNotExist();
assertThat(file1).isRegularFile();
}
@Test
public void deleteDirectory_throws_NPE_if_argument_is_null() throws IOException {
assertThatThrownBy(() -> FileUtils.deleteDirectory((File) null))
.isInstanceOf(NullPointerException.class)
.hasMessage("Directory can not be null");
}
@Test
public void deleteDirectory_does_not_fail_if_file_does_not_exist() throws IOException {
File file = new File(temporaryFolder.newFolder(), "foo.d");
FileUtils.deleteDirectory(file);
}
@Test
public void deleteDirectory_throws_IOE_if_argument_is_a_file() throws IOException {
File file = temporaryFolder.newFile();
assertThatThrownBy(() -> FileUtils.deleteDirectory(file))
.isInstanceOf(IOException.class)
.hasMessage("Directory '" + file.getAbsolutePath() + "' is a file");
}
@Test
public void deleteDirectory_throws_IOE_if_file_is_symbolicLink() throws IOException {
assumeTrue(SystemUtils.IS_OS_UNIX);
Path folder = temporaryFolder.newFolder().toPath();
Path file1 = Files.createFile(folder.resolve("file1.txt"));
Path symLink = Files.createSymbolicLink(folder.resolve("link1"), file1);
assertThat(file1).isRegularFile();
assertThat(symLink).isSymbolicLink();
assertThatThrownBy(() -> FileUtils.deleteDirectory(symLink.toFile()))
.isInstanceOf(IOException.class)
.hasMessage("Directory '" + symLink.toFile().getAbsolutePath() + "' is a symbolic link");
}
@Test
public void deleteDirectory_deletes_directory_and_content() throws IOException {
Path target = temporaryFolder.newFolder().toPath();
Path childFile1 = Files.createFile(target.resolve("file1.txt"));
Path childDir1 = Files.createDirectory(target.resolve("subDir1"));
Path childFile2 = Files.createFile(childDir1.resolve("file2.txt"));
Path childDir2 = Files.createDirectory(childDir1.resolve("subDir2"));
assertThat(target).isDirectory();
assertThat(childFile1).isRegularFile();
assertThat(childDir1).isDirectory();
assertThat(childFile2).isRegularFile();
assertThat(childDir2).isDirectory();
FileUtils.deleteQuietly(target.toFile());
assertThat(target).doesNotExist();
assertThat(childFile1).doesNotExist();
assertThat(childDir1).doesNotExist();
assertThat(childFile2).doesNotExist();
assertThat(childDir2).doesNotExist();
}
@CheckForNull
private static Object getFileKey(Path path) throws IOException {
BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
return attrs.fileKey();
}
}
| 10,133 | 36.955056 | 126 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/LineReaderIteratorTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class LineReaderIteratorTest {
@Test
public void read_lines() {
LineReaderIterator it = new LineReaderIterator(new StringReader("line1\nline2"));
assertThat(it.hasNext()).isTrue();
assertThat(it.next()).isEqualTo("line1");
assertThat(it.hasNext()).isTrue();
assertThat(it.next()).isEqualTo("line2");
assertThat(it.hasNext()).isFalse();
}
@Test
public void ignore_last_newline() {
LineReaderIterator it = new LineReaderIterator(new StringReader("line1\nline2\n"));
assertThat(it.hasNext()).isTrue();
assertThat(it.next()).isEqualTo("line1");
assertThat(it.hasNext()).isTrue();
assertThat(it.next()).isEqualTo("line2");
assertThat(it.hasNext()).isFalse();
}
@Test
public void no_lines() {
LineReaderIterator it = new LineReaderIterator(new StringReader(""));
assertThat(it.hasNext()).isFalse();
}
@Test
public void do_not_wrap_BufferedReader_in_BufferedReader() {
// TODO how to verify that constructor does not build new BufferedReader(BufferedReader) ?
LineReaderIterator it = new LineReaderIterator(new BufferedReader(new StringReader("line")));
assertThat(it.next()).isEqualTo("line");
assertThat(it.hasNext()).isFalse();
}
@Test
public void fail_if_cannot_read() throws IOException {
assertThatThrownBy(() -> {
BufferedReader reader = mock(BufferedReader.class);
when(reader.readLine()).thenThrow(new IOException());
LineReaderIterator it = new LineReaderIterator(reader);
it.hasNext();
})
.isInstanceOf(IllegalStateException.class)
.hasMessage("Fail to read line");
}
}
| 2,824 | 33.45122 | 97 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/MacAddressProviderTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MacAddressProviderTest {
@Test
public void getSecureMungedAddress() {
byte[] address = MacAddressProvider.getSecureMungedAddress();
assertThat(address)
.isNotEmpty()
.hasSize(6);
}
@Test
public void constructDummyMulticastAddress() {
byte[] address = MacAddressProvider.constructDummyMulticastAddress();
assertThat(address)
.isNotEmpty()
.hasSize(6);
}
}
| 1,378 | 30.340909 | 75 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/NonNullInputFunctionTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
public class NonNullInputFunctionTest {
NonNullInputFunction<String, Integer> underTest = new TestFunction();
@Test
public void fail_if_null_input() {
try {
underTest.apply(null);
fail();
} catch (IllegalArgumentException e) {
assertThat(e).hasMessage("Null inputs are not allowed in this function");
}
}
@Test
public void apply() {
assertThat(underTest.apply("foo")).isEqualTo(3);
}
private static class TestFunction extends NonNullInputFunction<String, Integer> {
@Override
protected Integer doApply(String input) {
return input.length();
}
}
}
| 1,614 | 29.471698 | 83 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/ProgressLoggerTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.slf4j.LoggerFactory;
import static org.assertj.core.api.Assertions.assertThat;
public class ProgressLoggerTest {
@Rule
public LogTester logTester = new LogTester();
@Test(timeout = 5_000L)
public void log_at_fixed_intervals() {
AtomicLong counter = new AtomicLong(42L);
ProgressLogger progress = new ProgressLogger("ProgressLoggerTest", counter, LoggerFactory.getLogger(getClass()));
progress.setPeriodMs(1L);
progress.start();
while (logTester.logs(Level.INFO).size()<2) {
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MILLISECONDS);
}
progress.stop();
assertThat(hasInfoLog("42 rows processed")).isTrue();
// ability to manual log, generally final status
counter.incrementAndGet();
progress.log();
assertThat(hasInfoLog("43 rows processed")).isTrue();
}
@Test
public void create() {
ProgressLogger progress = ProgressLogger.create(getClass(), new AtomicLong());
// default values
assertThat(progress.getPeriodMs()).isEqualTo(60000L);
assertThat(progress.getPluralLabel()).isEqualTo("rows");
// override values
progress.setPeriodMs(10L);
progress.setPluralLabel("issues");
assertThat(progress.getPeriodMs()).isEqualTo(10L);
assertThat(progress.getPluralLabel()).isEqualTo("issues");
}
private boolean hasInfoLog(String expectedLog) {
return logTester.logs(Level.INFO).stream().anyMatch(s -> s.startsWith(expectedLog));
}
}
| 2,604 | 33.733333 | 117 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/ProtobufJsonFormatTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import com.google.protobuf.ByteString;
import java.io.StringWriter;
import org.junit.Test;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.core.test.Test.Countries;
import org.sonar.core.test.Test.Country;
import org.sonar.core.test.Test.NestedMsg;
import org.sonar.core.test.Test.PrimitiveTypeMsg;
import org.sonar.core.test.Test.TestArray;
import org.sonar.core.test.Test.TestMap;
import org.sonar.core.test.Test.TestMapOfArray;
import org.sonar.core.test.Test.TestMapOfMap;
import org.sonar.core.test.Test.TestNullableArray;
import org.sonar.core.test.Test.TestNullableMap;
import org.sonar.core.test.Test.Translations;
import org.sonar.test.TestUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.core.util.ProtobufJsonFormat.toJson;
public class ProtobufJsonFormatTest {
@Test
public void test_primitive_types() {
PrimitiveTypeMsg protobuf = PrimitiveTypeMsg.newBuilder()
.setStringField("foo")
.setIntField(10)
.setLongField(100L)
.setDoubleField(3.14)
.setBooleanField(true)
.setEnumField(org.sonar.core.test.Test.FakeEnum.GREEN)
.build();
assertThat(toJson(protobuf)).isEqualTo(
"{\"stringField\":\"foo\",\"intField\":10,\"longField\":100,\"doubleField\":3.14,\"booleanField\":true,\"enumField\":\"GREEN\"}");
}
@Test
public void bytes_field_can_not_be_converted() {
assertThatThrownBy(() -> {
PrimitiveTypeMsg protobuf = PrimitiveTypeMsg.newBuilder()
.setBytesField(ByteString.copyFrom(new byte[]{2, 4}))
.build();
ProtobufJsonFormat.write(protobuf, JsonWriter.of(new StringWriter()));
})
.isInstanceOf(RuntimeException.class)
.hasMessage("JSON format does not support type 'BYTE_STRING' of field 'bytesField'");
}
@Test
public void do_not_write_null_primitive_fields() {
PrimitiveTypeMsg msg = PrimitiveTypeMsg.newBuilder().build();
// fields are absent
assertThat(msg.hasStringField()).isFalse();
assertThat(msg.hasIntField()).isFalse();
}
@Test
public void write_empty_string() {
PrimitiveTypeMsg msg = PrimitiveTypeMsg.newBuilder().setStringField("").build();
// field is present
assertThat(msg.hasStringField()).isTrue();
assertThat(msg.getStringField()).isEmpty();
assertThat(toJson(msg)).isEqualTo("{\"stringField\":\"\"}");
}
@Test
public void write_array() {
TestArray msg = TestArray.newBuilder()
.addStrings("one").addStrings("two")
.addNesteds(NestedMsg.newBuilder().setLabel("nestedOne")).addNesteds(NestedMsg.newBuilder().setLabel("nestedTwo"))
.build();
assertThat(toJson(msg))
.isEqualTo("{\"strings\":[\"one\",\"two\"],\"nesteds\":[{\"label\":\"nestedOne\"},{\"label\":\"nestedTwo\"}]}");
}
@Test
public void write_empty_array() {
TestArray msg = TestArray.newBuilder().build();
assertThat(toJson(msg)).isEqualTo("{\"strings\":[],\"nesteds\":[]}");
}
@Test
public void do_not_write_null_wrapper_of_array() {
TestNullableArray msg = TestNullableArray.newBuilder()
.setLabel("world")
.build();
assertThat(msg.hasCountries()).isFalse();
// array wrapper is null
assertThat(toJson(msg)).isEqualTo("{\"label\":\"world\"}");
}
@Test
public void inline_wrapper_of_array() {
TestNullableArray msg = TestNullableArray.newBuilder()
.setLabel("world")
.setCountries(Countries.newBuilder())
.build();
assertThat(msg.hasCountries()).isTrue();
assertThat(toJson(msg)).contains("\"label\":\"world\",\"countries\":[]");
msg = TestNullableArray.newBuilder()
.setLabel("world")
.setCountries(Countries.newBuilder().addCountries(Country.newBuilder().setName("France").setContinent("Europe")))
.build();
assertThat(msg.hasCountries()).isTrue();
assertThat(toJson(msg)).contains("\"label\":\"world\",\"countries\":[{\"name\":\"France\",\"continent\":\"Europe\"}]");
}
@Test
public void write_map() {
TestMap.Builder builder = TestMap.newBuilder();
builder.getMutableStringMap().put("one", "un");
builder.getMutableStringMap().put("two", "deux");
builder.getMutableNestedMap().put("three", NestedMsg.newBuilder().setLabel("trois").build());
builder.getMutableNestedMap().put("four", NestedMsg.newBuilder().setLabel("quatre").build());
assertThat(toJson(builder.build())).isEqualTo(
"{\"stringMap\":{\"one\":\"un\",\"two\":\"deux\"},\"nestedMap\":{\"three\":{\"label\":\"trois\"},\"four\":{\"label\":\"quatre\"}}}");
}
@Test
public void write_empty_map() {
TestMap.Builder builder = TestMap.newBuilder();
assertThat(toJson(builder.build())).isEqualTo("{\"stringMap\":{},\"nestedMap\":{}}");
}
@Test
public void do_not_write_null_wrapper_of_map() {
TestNullableMap msg = TestNullableMap.newBuilder()
.setLabel("world")
.build();
assertThat(toJson(msg)).isEqualTo("{\"label\":\"world\"}");
}
@Test
public void inline_wrapper_of_map() {
TestNullableMap msg = TestNullableMap.newBuilder()
.setLabel("world")
.setTranslations(Translations.newBuilder())
.build();
assertThat(toJson(msg)).isEqualTo("{\"label\":\"world\",\"translations\":{}}");
Translations.Builder translationsBuilder = Translations.newBuilder();
translationsBuilder.getMutableTranslations().put("one", "un");
translationsBuilder.getMutableTranslations().put("two", "deux");
msg = TestNullableMap.newBuilder()
.setLabel("world")
.setTranslations(translationsBuilder)
.build();
assertThat(toJson(msg)).isEqualTo("{\"label\":\"world\",\"translations\":{\"one\":\"un\",\"two\":\"deux\"}}");
}
@Test
public void write_map_of_arrays() {
// this is a trick to have arrays in map values
TestMapOfArray.Builder msg = TestMapOfArray.newBuilder();
// wrapper over array
Countries europe = Countries.newBuilder()
.addCountries(Country.newBuilder().setContinent("Europe").setName("France"))
.addCountries(Country.newBuilder().setContinent("Europe").setName("Germany"))
.build();
msg.getMutableMoneys().put("eur", europe);
assertThat(toJson(msg.build())).isEqualTo("{\"moneys\":{\"eur\":[{\"name\":\"France\",\"continent\":\"Europe\"},{\"name\":\"Germany\",\"continent\":\"Europe\"}]}}");
}
@Test
public void write_map_of_map() {
// this is a trick to have maps in map values
TestMapOfMap.Builder msg = TestMapOfMap.newBuilder();
// wrapper over map
Translations.Builder translationsBuilder = Translations.newBuilder();
translationsBuilder.getMutableTranslations().put("one", "un");
translationsBuilder.getMutableTranslations().put("two", "deux");
msg.getMutableCatalogs().put("numbers", translationsBuilder.build());
assertThat(toJson(msg.build())).isEqualTo("{\"catalogs\":{\"numbers\":{\"one\":\"un\",\"two\":\"deux\"}}}");
}
@Test
public void constructor_is_private() {
assertThat(TestUtils.hasOnlyPrivateConstructors(ProtobufJsonFormat.class)).isTrue();
}
}
| 7,992 | 36.00463 | 169 | java |
sonarqube | sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/ProtobufTest.java | /*
* SonarQube
* Copyright (C) 2009-2023 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;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.test.TestUtils;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.core.test.Test.Fake;
public class ProtobufTest {
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Test
public void only_utils() {
assertThat(TestUtils.hasOnlyPrivateConstructors(Protobuf.class)).isTrue();
}
@Test
public void read_file_fails_if_file_does_not_exist() throws Exception {
assertThatThrownBy(() -> {
File file = temp.newFile();
FileUtils.forceDelete(file);
Protobuf.read(file, Fake.parser());
}).isInstanceOf(ContextException.class)
.hasMessageContaining("Unable to read message");
}
@Test
public void read_file_returns_empty_message_if_file_is_empty() throws Exception {
File file = temp.newFile();
Fake msg = Protobuf.read(file, Fake.parser());
assertThat(msg).isNotNull();
assertThat(msg.isInitialized()).isTrue();
}
@Test
public void read_file_returns_message() throws Exception {
File file = temp.newFile();
Protobuf.write(Fake.getDefaultInstance(), file);
Fake message = Protobuf.read(file, Fake.parser());
assertThat(message).isNotNull();
assertThat(message.isInitialized()).isTrue();
}
@Test
public void fail_to_write_single_message() {
assertThatThrownBy(() -> {
File dir = temp.newFolder();
Protobuf.write(Fake.getDefaultInstance(), dir);
}).isInstanceOf(ContextException.class)
.hasMessageContaining("Unable to write message");
}
@Test
public void write_and_read_streams() throws Exception {
File file = temp.newFile();
Fake item1 = Fake.newBuilder().setLabel("one").setLine(1).build();
Fake item2 = Fake.newBuilder().setLabel("two").build();
Protobuf.writeStream(asList(item1, item2), file, false);
CloseableIterator<Fake> it = Protobuf.readStream(file, Fake.parser());
Fake read = it.next();
assertThat(read.getLabel()).isEqualTo("one");
assertThat(read.getLine()).isOne();
read = it.next();
assertThat(read.getLabel()).isEqualTo("two");
assertThat(read.hasLine()).isFalse();
assertThat(it.hasNext()).isFalse();
}
@Test
public void write_gzip_file() throws IOException {
File file = temp.newFile();
Fake item1 = Fake.newBuilder().setLabel("one").setLine(1).build();
Protobuf.writeGzip(item1, file);
try (InputStream is = new GZIPInputStream(new FileInputStream(file))) {
assertThat(Protobuf.read(is, Fake.parser()).getLabel()).isEqualTo("one");
}
}
@Test
public void read_gzip_stream() throws IOException {
File file = temp.newFile();
Fake item1 = Fake.newBuilder().setLabel("one").setLine(1).build();
Fake item2 = Fake.newBuilder().setLabel("two").setLine(2).build();
try (OutputStream os = new GZIPOutputStream(new FileOutputStream(file))) {
item1.writeDelimitedTo(os);
item2.writeDelimitedTo(os);
}
Iterable<Fake> it = () -> Protobuf.readGzipStream(file, Fake.parser());
assertThat(it).containsExactly(item1, item2);
}
@Test
public void fail_to_read_stream() {
assertThatThrownBy(() -> {
File dir = temp.newFolder();
Protobuf.readStream(dir, Fake.parser());
}).isInstanceOf(ContextException.class)
.hasMessageContaining("Unable to read messages");
}
@Test
public void read_empty_stream() throws Exception {
File file = temp.newFile();
CloseableIterator<Fake> it = Protobuf.readStream(file, Fake.parser());
assertThat(it).isNotNull();
assertThat(it.hasNext()).isFalse();
}
}
| 4,919 | 31.582781 | 83 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.