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/test/java/org/sonar/core/util/SequenceUuidFactoryTest.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 SequenceUuidFactoryTest { private SequenceUuidFactory underTest = new SequenceUuidFactory(); @Test public void generate_sequence_of_integer_ids() { for (int i = 1; i < 10; i++) { assertThat(underTest.create()).isEqualTo(String.valueOf(i)); } } }
1,240
31.657895
75
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/SettingFormatterTest.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 SettingFormatterTest { @Test public void fromJavaPropertyToEnvVariable() { String output = SettingFormatter.fromJavaPropertyToEnvVariable("some.randomProperty-123.test"); assertThat(output).isEqualTo("SOME_RANDOMPROPERTY_123_TEST"); } @Test public void test_getStringArrayBySeparator_on_input_with_separator() { String[] result = SettingFormatter.getStringArrayBySeparator(" abc, DeF , ghi", ","); assertThat(result).containsExactly("abc", "DeF", "ghi"); } @Test public void test_getStringArrayBySeparator_on_input_without_separator() { String[] result = SettingFormatter.getStringArrayBySeparator(" abc, DeF , ghi", ";"); assertThat(result).containsExactly("abc, DeF , ghi"); } }
1,698
35.934783
99
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/SlugTest.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 SlugTest { @Test public void slugify() { assertThat(Slug.slugify("foo")).isEqualTo("foo"); assertThat(Slug.slugify(" FOO ")).isEqualTo("foo"); assertThat(Slug.slugify("he's here")).isEqualTo("he-s-here"); assertThat(Slug.slugify("foo-bar")).isEqualTo("foo-bar"); assertThat(Slug.slugify("foo_bar")).isEqualTo("foo_bar"); assertThat(Slug.slugify("accents éà")).isEqualTo("accents-ea"); assertThat(Slug.slugify("<foo>")).isEqualTo("foo"); assertThat(Slug.slugify("<\"foo:\">")).isEqualTo("foo"); } }
1,507
36.7
75
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/UtcDateUtilsTest.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.Date; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class UtcDateUtilsTest { @Test public void parse_then_format() { Date date = UtcDateUtils.parseDateTime("2014-01-14T14:00:00+0200"); assertThat(UtcDateUtils.formatDateTime(date)).isEqualTo("2014-01-14T12:00:00+0000"); } @Test public void fail_if_bad_format() { try { UtcDateUtils.parseDateTime("2014-01-14"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Fail to parse date: 2014-01-14"); } } }
1,497
31.565217
88
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/UuidFactoryFastTest.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 UuidFactoryFastTest { UuidFactory underTest = UuidFactoryFast.getInstance(); @Test public void create_different_uuids() { // this test is not enough to ensure that generated strings are unique, // but it still does a simple and stupid verification assertThat(underTest.create()).isNotEqualTo(underTest.create()); } @Test public void test_format_of_uuid() { String uuid = underTest.create(); assertThat(uuid.length()).isGreaterThan(10).isLessThan(40); // URL-safe: only letters, digits, dash and underscore. assertThat(uuid).matches("^[\\w\\-_]+$"); } }
1,568
33.108696
75
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/UuidFactoryImplTest.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 UuidFactoryImplTest { UuidFactory underTest = UuidFactoryImpl.INSTANCE; @Test public void create_different_uuids() { // this test is not enough to ensure that generated strings are unique, // but it still does a simple and stupid verification assertThat(underTest.create()).isNotEqualTo(underTest.create()); } @Test public void test_format_of_uuid() { String uuid = underTest.create(); assertThat(uuid.length()).isGreaterThan(10).isLessThan(40); // URL-safe: only letters, digits, dash and underscore. assertThat(uuid).matches("^[\\w\\-_]+$"); } }
1,564
32.297872
75
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/UuidGeneratorImplTest.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.ArrayList; import java.util.Base64; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class UuidGeneratorImplTest { private UuidGeneratorImpl underTest = new UuidGeneratorImpl(); @Test public void generate_returns_unique_values_without_common_initial_letter_given_more_than_one_millisecond_between_generate_calls() throws InterruptedException { Base64.Encoder encoder = Base64.getEncoder(); int count = 30; Set<String> uuids = new HashSet<>(count); for (int i = 0; i < count; i++) { Thread.sleep(5); uuids.add(encoder.encodeToString(underTest.generate())); } assertThat(uuids).hasSize(count); Iterator<String> iterator = uuids.iterator(); String firstUuid = iterator.next(); String base = firstUuid.substring(0, firstUuid.length() - 4); for (int i = 1; i < count; i++) { assertThat(iterator.next()).describedAs("i=" + i).doesNotStartWith(base); } } @Test public void generate_concurrent_test() throws InterruptedException { int rounds = 500; List<byte[]> uuids1 = new ArrayList<>(rounds); List<byte[]> uuids2 = new ArrayList<>(rounds); Thread t1 = new Thread(() -> { for (int i = 0; i < rounds; i++) { uuids1.add(underTest.generate()); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < rounds; i++) { uuids2.add(underTest.generate()); } }); t1.start(); t2.start(); t1.join(); t2.join(); Base64.Encoder encoder = Base64.getEncoder(); Set<String> uuids = new HashSet<>(rounds * 2); uuids1.forEach(bytes -> uuids.add(encoder.encodeToString(bytes))); uuids2.forEach(bytes -> uuids.add(encoder.encodeToString(bytes))); assertThat(uuids).hasSize(rounds * 2); } @Test public void generate_from_FixedBase_returns_unique_values_where_only_last_4_later_letter_change() { Base64.Encoder encoder = Base64.getEncoder(); int count = 100_000; Set<String> uuids = new HashSet<>(count); UuidGenerator.WithFixedBase withFixedBase = underTest.withFixedBase(); for (int i = 0; i < count; i++) { uuids.add(encoder.encodeToString(withFixedBase.generate(i))); } assertThat(uuids).hasSize(count); Iterator<String> iterator = uuids.iterator(); String firstUuid = iterator.next(); String base = firstUuid.substring(0, firstUuid.length() - 4); while (iterator.hasNext()) { assertThat(iterator.next()).startsWith(base); } } @Test public void generate_from_FixedBase_concurrent_test() throws InterruptedException { UuidGenerator.WithFixedBase withFixedBase = underTest.withFixedBase(); int rounds = 500; List<byte[]> uuids1 = new ArrayList<>(rounds); List<byte[]> uuids2 = new ArrayList<>(rounds); AtomicInteger cnt = new AtomicInteger(); Thread t1 = new Thread(() -> { for (int i = 0; i < rounds; i++) { uuids1.add(withFixedBase.generate(cnt.getAndIncrement())); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < rounds; i++) { uuids2.add(withFixedBase.generate(cnt.getAndIncrement())); } }); t1.start(); t2.start(); t1.join(); t2.join(); Base64.Encoder encoder = Base64.getEncoder(); Set<String> uuids = new HashSet<>(rounds * 2); uuids1.forEach(bytes -> uuids.add(encoder.encodeToString(bytes))); uuids2.forEach(bytes -> uuids.add(encoder.encodeToString(bytes))); assertThat(uuids).hasSize(rounds * 2); } }
4,546
33.709924
161
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/UuidsTest.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.HashSet; import java.util.Set; import org.junit.Test; import org.sonar.test.TestUtils; import static org.assertj.core.api.Assertions.assertThat; public class UuidsTest { @Test public void create_unique() { Set<String> all = new HashSet<>(); for (int i = 0; i < 50; i++) { String uuid = Uuids.create(); assertThat(uuid).isNotEmpty(); all.add(uuid); } assertThat(all).hasSize(50); } @Test public void constructor_is_private() { TestUtils.hasOnlyPrivateConstructors(Uuids.class); } }
1,425
29.340426
75
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/issue/IssueChangedEventTest.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 org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class IssueChangedEventTest { private static final String BRANCH_NAME = "branch-name"; private static final String ISSUE_KEY = "issue-key"; private static final String PROJECT_KEY = "project-key"; @Test public void issueChangedEvent_instantiation_accepts_nulls() { Issue[] issues = new Issue[]{new Issue(ISSUE_KEY, BRANCH_NAME)}; IssueChangedEvent event = new IssueChangedEvent(PROJECT_KEY, issues, null, null, null); assertThat(event.getEvent()).isEqualTo("IssueChanged"); assertThat(event.getProjectKey()).isEqualTo(PROJECT_KEY); assertThat(event.getResolved()).isNull(); assertThat(event.getUserSeverity()).isNull(); assertThat(event.getUserType()).isNull(); assertThat(event.getIssues()).hasSize(1); } @Test public void issueChangedEvent_instantiation_accepts_actual_values() { Issue[] issues = new Issue[]{new Issue(ISSUE_KEY, BRANCH_NAME)}; IssueChangedEvent event = new IssueChangedEvent(PROJECT_KEY, issues, true, "BLOCKER", "BUG"); assertThat(event.getEvent()).isEqualTo("IssueChanged"); assertThat(event.getProjectKey()).isEqualTo(PROJECT_KEY); assertThat(event.getResolved()).isTrue(); assertThat(event.getUserSeverity()).isEqualTo("BLOCKER"); assertThat(event.getUserType()).isEqualTo("BUG"); assertThat(event.getIssues()).hasSize(1); } @Test public void issueChangedEvent_instantiation_doesNotAccept_emptyIssues() { Issue[] issues = new Issue[0]; assertThatThrownBy(() -> new IssueChangedEvent(PROJECT_KEY, issues, true, "BLOCKER", "BUG")) .isInstanceOf(IllegalArgumentException.class) .withFailMessage("Can't create IssueChangedEvent without any issues that have changed"); } }
2,742
39.338235
97
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/issue/IssueTest.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 org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class IssueTest { private static final String BRANCH_NAME = "branch-name"; private static final String ISSUE_KEY = "issue-key"; @Test public void issue_instantiation_accepts_values() { Issue issue = new Issue(ISSUE_KEY, BRANCH_NAME); assertThat(issue.getIssueKey()).isEqualTo(ISSUE_KEY); assertThat(issue.getBranchName()).isEqualTo(BRANCH_NAME); } }
1,343
34.368421
75
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/logs/DefaultProfilerTest.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 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 org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import org.slf4j.LoggerFactory; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; @RunWith(DataProviderRunner.class) public class DefaultProfilerTest { @Rule public LogTester tester = new LogTester(); Profiler underTest = Profiler.create(LoggerFactory.getLogger("DefaultProfilerTest")); @DataProvider public static Object[][] logTimeLastValues() { return new Object[][] { {true}, {false} }; } @Test public void test_levels() { // info by default assertThat(underTest.isDebugEnabled()).isFalse(); assertThat(underTest.isTraceEnabled()).isFalse(); tester.setLevel(LoggerLevel.DEBUG); assertThat(underTest.isDebugEnabled()).isTrue(); assertThat(underTest.isTraceEnabled()).isFalse(); tester.setLevel(LoggerLevel.TRACE); assertThat(underTest.isDebugEnabled()).isTrue(); assertThat(underTest.isTraceEnabled()).isTrue(); } @Test @UseDataProvider("logTimeLastValues") public void stop_reuses_start_message(boolean logTimeLast) throws InterruptedException { underTest.logTimeLast(logTimeLast); tester.setLevel(LoggerLevel.TRACE); // trace underTest.startTrace("Register rules {}", 1); Thread.sleep(2); assertThat(tester.logs()).containsOnly("Register rules 1"); long timing = underTest.stopTrace(); assertThat(timing).isPositive(); assertThat(tester.logs()).hasSize(2); assertThat(tester.logs().get(1)).startsWith("Register rules 1 (done) | time=" + timing); tester.clear(); // debug underTest.startDebug("Register rules"); Thread.sleep(2); assertThat(tester.logs()).containsOnly("Register rules"); timing = underTest.stopTrace(); assertThat(timing).isPositive(); assertThat(tester.logs()).hasSize(2); assertThat(tester.logs().get(1)).startsWith("Register rules (done) | time=" + timing); tester.clear(); // info underTest.startInfo("Register rules"); Thread.sleep(2); assertThat(tester.logs()).containsOnly("Register rules"); timing = underTest.stopTrace(); assertThat(timing).isPositive(); assertThat(tester.logs()).hasSize(2); assertThat(tester.logs().get(1)).startsWith("Register rules (done) | time=" + timing); } @Test @UseDataProvider("logTimeLastValues") public void different_start_and_stop_messages(boolean logTimeLast) { underTest.logTimeLast(logTimeLast); tester.setLevel(LoggerLevel.TRACE); // start TRACE and stop DEBUG underTest.startTrace("Register rules"); underTest.stopDebug("Rules registered"); assertThat(tester.logs()).hasSize(2); assertThat(tester.logs().get(0)).contains("Register rules"); assertThat(tester.logs().get(1)).startsWith("Rules registered | time="); tester.clear(); // start DEBUG and stop INFO underTest.startDebug("Register rules {}", 10); underTest.stopInfo("Rules registered"); assertThat(tester.logs()).hasSize(2); assertThat(tester.logs().get(0)).contains("Register rules 10"); assertThat(tester.logs().get(1)).startsWith("Rules registered | time="); tester.clear(); // start INFO and stop TRACE underTest.startInfo("Register rules"); underTest.stopTrace("Rules registered"); assertThat(tester.logs()).hasSize(2); assertThat(tester.logs().get(0)).contains("Register rules"); assertThat(tester.logs().get(1)).startsWith("Rules registered | time="); } @Test @UseDataProvider("logTimeLastValues") public void log_on_at_stop(boolean logTimeLast) { underTest.logTimeLast(logTimeLast); tester.setLevel(LoggerLevel.TRACE); // trace underTest.start(); underTest.stopTrace("Rules registered"); assertThat(tester.logs()).hasSize(1); assertThat(tester.logs().get(0)).startsWith("Rules registered | time="); tester.clear(); // debug underTest.start(); underTest.stopDebug("Rules registered {} on {}", 6, 10); assertThat(tester.logs()).hasSize(1); assertThat(tester.logs().get(0)).startsWith("Rules registered 6 on 10 | time="); tester.clear(); // info underTest.start(); underTest.stopInfo("Rules registered"); assertThat(tester.logs()).hasSize(1); assertThat(tester.logs().get(0)).startsWith("Rules registered | time="); } @Test public void start_writes_no_log_even_if_there_is_context() { underTest.addContext("a_string", "bar"); underTest.addContext("null_value", null); underTest.addContext("an_int", 42); underTest.start(); // do not write context as there's no message assertThat(tester.logs()).isEmpty(); } @Test public void startInfo_writes_log_with_context_appended_when_there_is_a_message() { addSomeContext(underTest); underTest.startInfo("Foo"); assertThat(tester.logs(Level.INFO)).containsOnly("Foo | a_string=bar | an_int=42 | after_start=true"); } @Test public void startDebug_writes_log_with_context_appended_when_there_is_a_message() { tester.setLevel(LoggerLevel.DEBUG); addSomeContext(underTest); underTest.startDebug("Foo"); assertThat(tester.logs(Level.DEBUG)).containsOnly("Foo | a_string=bar | an_int=42 | after_start=true"); } @Test public void startTrace_writes_log_with_context_appended_when_there_is_a_message() { tester.setLevel(LoggerLevel.TRACE); addSomeContext(underTest); underTest.startTrace("Foo"); assertThat(tester.logs(Level.TRACE)).containsOnly("Foo | a_string=bar | an_int=42 | after_start=true"); } @Test public void stopError_adds_context_after_time_by_default() { addSomeContext(underTest); underTest.start().stopError("Rules registered"); assertThat(tester.logs()).hasSize(1); assertThat(tester.logs(Level.ERROR).get(0)) .startsWith("Rules registered | time=") .endsWith("ms | a_string=bar | an_int=42 | after_start=true"); } @Test public void stopInfo_adds_context_after_time_by_default() { addSomeContext(underTest); underTest.start().stopInfo("Rules registered"); assertThat(tester.logs()).hasSize(1); assertThat(tester.logs(Level.INFO).get(0)) .startsWith("Rules registered | time=") .endsWith("ms | a_string=bar | an_int=42 | after_start=true"); } @Test public void stopTrace_adds_context_after_time_by_default() { tester.setLevel(LoggerLevel.TRACE); addSomeContext(underTest); underTest.start().stopTrace("Rules registered"); assertThat(tester.logs()).hasSize(1); assertThat(tester.logs(Level.TRACE).get(0)) .startsWith("Rules registered | time=") .endsWith("ms | a_string=bar | an_int=42 | after_start=true"); } @Test public void stopError_adds_context_before_time_if_logTimeLast_is_true() { addSomeContext(underTest); underTest.logTimeLast(true); underTest.start().stopError("Rules registered"); assertThat(tester.logs()).hasSize(1); assertThat(tester.logs(Level.ERROR).get(0)) .startsWith("Rules registered | a_string=bar | an_int=42 | after_start=true | time=") .endsWith("ms"); } @Test public void stopInfo_adds_context_before_time_if_logTimeLast_is_true() { addSomeContext(underTest); underTest.logTimeLast(true); underTest.start().stopInfo("Rules registered"); assertThat(tester.logs()).hasSize(1); assertThat(tester.logs(Level.INFO).get(0)) .startsWith("Rules registered | a_string=bar | an_int=42 | after_start=true | time=") .endsWith("ms"); } @Test public void stopTrace_adds_context_before_time_if_logTimeLast_is_true() { tester.setLevel(LoggerLevel.TRACE); addSomeContext(underTest); underTest.logTimeLast(true); underTest.start().stopTrace("Rules registered"); assertThat(tester.logs()).hasSize(1); assertThat(tester.logs(Level.TRACE).get(0)) .startsWith("Rules registered | a_string=bar | an_int=42 | after_start=true | time=") .endsWith("ms"); } @Test public void stopInfo_clears_context() { addSomeContext(underTest); underTest.logTimeLast(true); underTest.start().stopInfo("Foo"); underTest.start().stopInfo("Bar"); assertThat(tester.logs()).hasSize(2); List<String> logs = tester.logs(Level.INFO); assertThat(logs.get(0)) .startsWith("Foo | a_string=bar | an_int=42 | after_start=true | time=") .endsWith("ms"); assertThat(logs.get(1)) .startsWith("Bar | time=") .endsWith("ms"); } @Test public void stopDebug_clears_context() { tester.setLevel(LoggerLevel.DEBUG); addSomeContext(underTest); underTest.logTimeLast(true); underTest.start().stopDebug("Foo"); underTest.start().stopDebug("Bar"); assertThat(tester.logs()).hasSize(2); List<String> logs = tester.logs(Level.DEBUG); assertThat(logs.get(0)) .startsWith("Foo | a_string=bar | an_int=42 | after_start=true | time=") .endsWith("ms"); assertThat(logs.get(1)) .startsWith("Bar | time=") .endsWith("ms"); } @Test public void stopTrace_clears_context() { tester.setLevel(LoggerLevel.TRACE); addSomeContext(underTest); underTest.logTimeLast(true); underTest.start().stopTrace("Foo"); underTest.start().stopTrace("Bar"); assertThat(tester.logs()).hasSize(2); List<String> logs = tester.logs(Level.TRACE); assertThat(logs.get(0)) .startsWith("Foo | a_string=bar | an_int=42 | after_start=true | time=") .endsWith("ms"); assertThat(logs.get(1)) .startsWith("Bar | time=") .endsWith("ms"); } private static void addSomeContext(Profiler profiler) { profiler.addContext("a_string", "bar"); profiler.addContext("null_value", null); profiler.addContext("an_int", 42); profiler.addContext("after_start", true); } @Test public void empty_message() { underTest.addContext("foo", "bar"); underTest.startInfo(""); assertThat(tester.logs()).containsOnly("foo=bar"); underTest.addContext("after_start", true); underTest.stopInfo(""); assertThat(tester.logs()).hasSize(2); assertThat(tester.logs().get(1)) .startsWith("time=") .endsWith("ms | foo=bar | after_start=true"); } @Test public void fail_if_stop_without_message() { underTest.start(); try { underTest.stopInfo(); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Profiler#stopXXX() can't be called without any message defined in start methods"); } } @Test public void fail_if_stop_without_start() { try { underTest.stopDebug("foo"); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("Profiler must be started before being stopped"); } } @Test public void hasContext() { assertThat(underTest.hasContext("foo")).isFalse(); underTest.addContext("foo", "bar"); assertThat(underTest.hasContext("foo")).isTrue(); underTest.addContext("foo", null); assertThat(underTest.hasContext("foo")).isFalse(); } }
12,282
31.667553
114
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/logs/NullProfilerTest.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 org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class NullProfilerTest { NullProfiler underTest = NullProfiler.NULL_INSTANCE; @Test public void do_not_fail() { assertThat(underTest.start()).isSameAs(underTest); assertThat(underTest.startTrace("")).isSameAs(underTest); assertThat(underTest.startDebug("")).isSameAs(underTest); assertThat(underTest.startInfo("")).isSameAs(underTest); assertThat(underTest.isDebugEnabled()).isFalse(); assertThat(underTest.isTraceEnabled()).isFalse(); assertThat(underTest.addContext("foo", "bar")).isSameAs(underTest); assertThat(underTest.logTimeLast(true)).isSameAs(underTest); assertThat(underTest.logTimeLast(false)).isSameAs(underTest); } @Test public void stop_methods_returns_0() { underTest.start(); assertThat(underTest.stopInfo()).isZero(); assertThat(underTest.stopInfo("msg")).isZero(); assertThat(underTest.stopDebug()).isZero(); assertThat(underTest.stopDebug("msg")).isZero(); assertThat(underTest.stopTrace()).isZero(); assertThat(underTest.stopTrace("msg")).isZero(); assertThat(underTest.stopError("msg")).isZero(); } }
2,078
35.473684
75
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/logs/ProfilerTest.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 org.junit.Rule; import org.junit.Test; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import org.slf4j.LoggerFactory; import static org.assertj.core.api.Assertions.assertThat; public class ProfilerTest { @Rule public LogTester tester = new LogTester(); @Test public void create() { Profiler profiler = Profiler.create(LoggerFactory.getLogger("foo")); assertThat(profiler).isInstanceOf(DefaultProfiler.class); } @Test public void create_null_profiler_if_trace_level_is_disabled() { tester.setLevel(LoggerLevel.TRACE); Profiler profiler = Profiler.createIfTrace(LoggerFactory.getLogger("foo")); assertThat(profiler).isInstanceOf(DefaultProfiler.class); tester.setLevel(LoggerLevel.DEBUG); profiler = Profiler.createIfTrace(LoggerFactory.getLogger("foo")); assertThat(profiler).isInstanceOf(NullProfiler.class); } @Test public void create_null_profiler_if_debug_level_is_disabled() { tester.setLevel(LoggerLevel.TRACE); Profiler profiler = Profiler.createIfDebug(LoggerFactory.getLogger("foo")); assertThat(profiler).isInstanceOf(DefaultProfiler.class); tester.setLevel(LoggerLevel.INFO); profiler = Profiler.createIfDebug(LoggerFactory.getLogger("foo")); assertThat(profiler).isInstanceOf(NullProfiler.class); } }
2,228
34.951613
79
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/rule/RuleSetChangedEventTest.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 org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RuleSetChangedEventTest { @Test public void getDeactivatedAndActivatedRules() { String project = "sonarqube"; RuleChange[] activatedRules = { new RuleChange()}; String[] deactivatedRules = {"ruleKey"}; RuleSetChangedEvent event = new RuleSetChangedEvent(project, activatedRules, deactivatedRules); assertThat(event.getActivatedRules()).isEqualTo(activatedRules); assertThat(event.getDeactivatedRules()).isEqualTo(deactivatedRules); } @Test public void getLanguage_givenBothArraysEmpty_throwException() { String project = "sonarqube"; RuleChange[] activatedRules = {}; String[] deactivatedRules = {}; assertThatThrownBy(() -> new RuleSetChangedEvent(project, activatedRules, deactivatedRules)) .isInstanceOf(IllegalArgumentException.class); } private RuleChange createRuleChange(String language) { RuleChange ruleChange = new RuleChange(); ruleChange.setLanguage(language); return ruleChange; } }
2,015
35
99
java
sonarqube
sonarqube-master/sonar-core/src/test/java/org/sonar/core/util/stream/MoreCollectorsTest.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.ListMultimap; import com.google.common.collect.SetMultimap; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Test; import static java.util.function.Function.identity; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.core.util.stream.MoreCollectors.index; import static org.sonar.core.util.stream.MoreCollectors.unorderedFlattenIndex; import static org.sonar.core.util.stream.MoreCollectors.unorderedIndex; public class MoreCollectorsTest { private static final List<String> HUGE_LIST = IntStream.range(0, 2_000).mapToObj(String::valueOf).collect(java.util.stream.Collectors.toList()); private static final Set<String> HUGE_SET = new HashSet<>(HUGE_LIST); private static final MyObj MY_OBJ_1_A = new MyObj(1, "A"); private static final MyObj MY_OBJ_1_C = new MyObj(1, "C"); private static final MyObj MY_OBJ_2_B = new MyObj(2, "B"); private static final MyObj MY_OBJ_3_C = new MyObj(3, "C"); private static final MyObj2 MY_OBJ2_1_A_X = new MyObj2(1, "A", "X"); private static final MyObj2 MY_OBJ2_1_C = new MyObj2(1, "C"); private static final MyObj2 MY_OBJ2_2_B = new MyObj2(2, "B"); private static final MyObj2 MY_OBJ2_3_C = new MyObj2(3, "C"); private static final List<MyObj> SINGLE_ELEMENT_LIST = Arrays.asList(MY_OBJ_1_A); private static final List<MyObj2> SINGLE_ELEMENT2_LIST = Arrays.asList(MY_OBJ2_1_A_X); private static final List<MyObj> LIST_WITH_DUPLICATE_ID = Arrays.asList(MY_OBJ_1_A, MY_OBJ_2_B, MY_OBJ_1_C); private static final List<MyObj2> LIST2_WITH_DUPLICATE_ID = Arrays.asList(MY_OBJ2_1_A_X, MY_OBJ2_2_B, MY_OBJ2_1_C); private static final List<MyObj> LIST = Arrays.asList(MY_OBJ_1_A, MY_OBJ_2_B, MY_OBJ_3_C); private static final List<MyObj2> LIST2 = Arrays.asList(MY_OBJ2_1_A_X, MY_OBJ2_2_B, MY_OBJ2_3_C); @Test public void index_empty_stream_returns_empty_map() { assertThat(Stream.<MyObj>empty().collect(index(MyObj::getId)).size()).isZero(); assertThat(Stream.<MyObj>empty().collect(index(MyObj::getId, MyObj::getText)).size()).isZero(); } @Test public void index_fails_if_key_function_is_null() { assertThatThrownBy(() -> index(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't be null"); } @Test public void index_with_valueFunction_fails_if_key_function_is_null() { assertThatThrownBy(() -> index(null, MyObj::getText)) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't be null"); } @Test public void index_with_valueFunction_fails_if_value_function_is_null() { assertThatThrownBy(() -> index(MyObj::getId, null)) .isInstanceOf(NullPointerException.class) .hasMessage("Value function can't be null"); } @Test public void index_fails_if_key_function_returns_null() { assertThatThrownBy(() -> SINGLE_ELEMENT_LIST.stream().collect(index(s -> null))) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't return null"); } @Test public void index_with_valueFunction_fails_if_key_function_returns_null() { assertThatThrownBy(() -> SINGLE_ELEMENT_LIST.stream().collect(index(s -> null, MyObj::getText))) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't return null"); } @Test public void index_with_valueFunction_fails_if_value_function_returns_null() { assertThatThrownBy(() -> SINGLE_ELEMENT_LIST.stream().collect(index(MyObj::getId, s -> null))) .isInstanceOf(NullPointerException.class) .hasMessage("Value function can't return null"); } @Test public void index_supports_duplicate_keys() { ListMultimap<Integer, MyObj> multimap = LIST_WITH_DUPLICATE_ID.stream().collect(index(MyObj::getId)); assertThat(multimap.keySet()).containsOnly(1, 2); assertThat(multimap.get(1)).containsOnly(MY_OBJ_1_A, MY_OBJ_1_C); assertThat(multimap.get(2)).containsOnly(MY_OBJ_2_B); } @Test public void index_returns_ListMultimap() { ListMultimap<Integer, MyObj> multimap = LIST.stream().collect(index(MyObj::getId)); assertThat(multimap.size()).isEqualTo(3); Map<Integer, Collection<MyObj>> map = multimap.asMap(); assertThat(map.get(1)).containsOnly(MY_OBJ_1_A); assertThat(map.get(2)).containsOnly(MY_OBJ_2_B); assertThat(map.get(3)).containsOnly(MY_OBJ_3_C); } @Test public void index_with_valueFunction_returns_ListMultimap() { ListMultimap<Integer, String> multimap = LIST.stream().collect(index(MyObj::getId, MyObj::getText)); assertThat(multimap.size()).isEqualTo(3); Map<Integer, Collection<String>> map = multimap.asMap(); assertThat(map.get(1)).containsOnly("A"); assertThat(map.get(2)).containsOnly("B"); assertThat(map.get(3)).containsOnly("C"); } @Test public void index_parallel_stream() { ListMultimap<String, String> multimap = HUGE_LIST.parallelStream().collect(index(identity())); assertThat(multimap.keySet()).isEqualTo(HUGE_SET); } @Test public void index_with_valueFunction_parallel_stream() { ListMultimap<String, String> multimap = HUGE_LIST.parallelStream().collect(index(identity(), identity())); assertThat(multimap.keySet()).isEqualTo(HUGE_SET); } @Test public void unorderedIndex_empty_stream_returns_empty_map() { assertThat(Stream.<MyObj>empty().collect(unorderedIndex(MyObj::getId)).size()).isZero(); assertThat(Stream.<MyObj>empty().collect(unorderedIndex(MyObj::getId, MyObj::getText)).size()).isZero(); } @Test public void unorderedIndex_fails_if_key_function_is_null() { assertThatThrownBy(() -> unorderedIndex(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't be null"); } @Test public void unorderedIndex_with_valueFunction_fails_if_key_function_is_null() { assertThatThrownBy(() -> unorderedIndex(null, MyObj::getText)) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't be null"); } @Test public void unorderedIndex_with_valueFunction_fails_if_value_function_is_null() { assertThatThrownBy(() -> unorderedIndex(MyObj::getId, null)) .isInstanceOf(NullPointerException.class) .hasMessage("Value function can't be null"); } @Test public void unorderedIndex_fails_if_key_function_returns_null() { assertThatThrownBy(() -> SINGLE_ELEMENT_LIST.stream().collect(unorderedIndex(s -> null))) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't return null"); } @Test public void unorderedIndex_with_valueFunction_fails_if_key_function_returns_null() { assertThatThrownBy(() -> SINGLE_ELEMENT_LIST.stream().collect(unorderedIndex(s -> null, MyObj::getText))) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't return null"); } @Test public void unorderedIndex_with_valueFunction_fails_if_value_function_returns_null() { assertThatThrownBy(() -> SINGLE_ELEMENT_LIST.stream().collect(unorderedIndex(MyObj::getId, s -> null))) .isInstanceOf(NullPointerException.class) .hasMessage("Value function can't return null"); } @Test public void unorderedIndex_supports_duplicate_keys() { SetMultimap<Integer, MyObj> multimap = LIST_WITH_DUPLICATE_ID.stream().collect(unorderedIndex(MyObj::getId)); assertThat(multimap.keySet()).containsOnly(1, 2); assertThat(multimap.get(1)).containsOnly(MY_OBJ_1_A, MY_OBJ_1_C); assertThat(multimap.get(2)).containsOnly(MY_OBJ_2_B); } @Test public void unorderedIndex_returns_SetMultimap() { SetMultimap<Integer, MyObj> multimap = LIST.stream().collect(unorderedIndex(MyObj::getId)); assertThat(multimap.size()).isEqualTo(3); Map<Integer, Collection<MyObj>> map = multimap.asMap(); assertThat(map.get(1)).containsOnly(MY_OBJ_1_A); assertThat(map.get(2)).containsOnly(MY_OBJ_2_B); assertThat(map.get(3)).containsOnly(MY_OBJ_3_C); } @Test public void unorderedIndex_with_valueFunction_returns_SetMultimap() { SetMultimap<Integer, String> multimap = LIST.stream().collect(unorderedIndex(MyObj::getId, MyObj::getText)); assertThat(multimap.size()).isEqualTo(3); Map<Integer, Collection<String>> map = multimap.asMap(); assertThat(map.get(1)).containsOnly("A"); assertThat(map.get(2)).containsOnly("B"); assertThat(map.get(3)).containsOnly("C"); } @Test public void unorderedIndex_parallel_stream() { SetMultimap<String, String> multimap = HUGE_LIST.parallelStream().collect(unorderedIndex(identity())); assertThat(multimap.keySet()).isEqualTo(HUGE_SET); } @Test public void unorderedIndex_with_valueFunction_parallel_stream() { SetMultimap<String, String> multimap = HUGE_LIST.parallelStream().collect(unorderedIndex(identity(), identity())); assertThat(multimap.keySet()).isEqualTo(HUGE_SET); } @Test public void unorderedFlattenIndex_empty_stream_returns_empty_map() { assertThat(Stream.<MyObj2>empty() .collect(unorderedFlattenIndex(MyObj2::getId, MyObj2::getTexts)) .size()).isZero(); } @Test public void unorderedFlattenIndex_with_valueFunction_fails_if_key_function_is_null() { assertThatThrownBy(() -> unorderedFlattenIndex(null, MyObj2::getTexts)) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't be null"); } @Test public void unorderedFlattenIndex_with_valueFunction_fails_if_value_function_is_null() { assertThatThrownBy(() -> unorderedFlattenIndex(MyObj2::getId, null)) .isInstanceOf(NullPointerException.class) .hasMessage("Value function can't be null"); } @Test public void unorderedFlattenIndex_with_valueFunction_fails_if_key_function_returns_null() { assertThatThrownBy(() -> SINGLE_ELEMENT2_LIST.stream().collect(unorderedFlattenIndex(s -> null, MyObj2::getTexts))) .isInstanceOf(NullPointerException.class) .hasMessage("Key function can't return null"); } @Test public void unorderedFlattenIndex_with_valueFunction_fails_if_value_function_returns_null() { assertThatThrownBy(() -> SINGLE_ELEMENT2_LIST.stream().collect(unorderedFlattenIndex(MyObj2::getId, s -> null))) .isInstanceOf(NullPointerException.class) .hasMessage("Value function can't return null"); } @Test public void unorderedFlattenIndex_supports_duplicate_keys() { SetMultimap<Integer, String> multimap = LIST2_WITH_DUPLICATE_ID.stream() .collect(unorderedFlattenIndex(MyObj2::getId, MyObj2::getTexts)); assertThat(multimap.keySet()).containsOnly(1, 2); assertThat(multimap.get(1)).containsOnly("A", "X", "C"); assertThat(multimap.get(2)).containsOnly("B"); } @Test public void unorderedFlattenIndex_with_valueFunction_returns_SetMultimap() { SetMultimap<Integer, String> multimap = LIST2.stream() .collect(unorderedFlattenIndex(MyObj2::getId, MyObj2::getTexts)); assertThat(multimap.size()).isEqualTo(4); Map<Integer, Collection<String>> map = multimap.asMap(); assertThat(map.get(1)).containsOnly("A", "X"); assertThat(map.get(2)).containsOnly("B"); assertThat(map.get(3)).containsOnly("C"); } @Test public void unorderedFlattenIndex_with_valueFunction_parallel_stream() { SetMultimap<String, String> multimap = HUGE_LIST.parallelStream().collect(unorderedFlattenIndex(identity(), Stream::of)); assertThat(multimap.keySet()).isEqualTo(HUGE_SET); } private static final class MyObj { private final int id; private final String text; public MyObj(int id, String text) { this.id = id; this.text = text; } public int getId() { return id; } public String getText() { return text; } } private static final class MyObj2 { private final int id; private final List<String> texts; public MyObj2(int id, String... texts) { this.id = id; this.texts = Arrays.stream(texts).collect(Collectors.toList()); } public int getId() { return id; } public Stream<String> getTexts() { return texts.stream(); } } private enum MyEnum { ONE, TWO, THREE } }
13,347
36.920455
146
java
sonarqube
sonarqube-master/sonar-core/src/test/projects/base-plugin/src/org/sonar/plugins/base/BasePlugin.java
package org.sonar.plugins.base; import java.util.Collections; import java.util.List; import org.sonar.api.Plugin; public class BasePlugin implements Plugin { public void define(Plugin.Context context) { } }
215
15.615385
46
java
sonarqube
sonarqube-master/sonar-core/src/test/projects/base-plugin/src/org/sonar/plugins/base/api/BaseApi.java
package org.sonar.plugins.base.api; public class BaseApi { public void doNothing() { } }
94
12.571429
35
java
sonarqube
sonarqube-master/sonar-core/src/test/projects/dependent-plugin/src/org/sonar/plugins/dependent/DependentPlugin.java
package org.sonar.plugins.dependent; import java.util.Collections; import java.util.List; import org.sonar.api.Plugin; import org.sonar.plugins.base.api.BaseApi; public class DependentPlugin implements Plugin { public DependentPlugin() { // uses a class that is exported by base-plugin new BaseApi().doNothing(); } public void define(Plugin.Context context) { } }
385
19.315789
51
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/DuplicationsException.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.duplications; public class DuplicationsException extends RuntimeException { public DuplicationsException(String message) { super(message); } public DuplicationsException(String message, Throwable cause) { super(message, cause); } }
1,112
33.78125
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/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.duplications; import javax.annotation.ParametersAreNonnullByDefault;
963
37.56
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/block/Block.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.duplications.block; /** * Represents part of source code between two lines. * If two blocks have the same {@link #getBlockHash() hash}, then we assume that there is a duplication in a code, which they represent. */ public final class Block { private final String resourceId; private final ByteArray blockHash; private final int indexInFile; private final int startLine; private final int endLine; private final int startUnit; private final int endUnit; /** * Cache for hash code. */ private int hash; private Block(Builder builder) { this.resourceId = builder.resourceId; this.blockHash = builder.blockHash; this.indexInFile = builder.indexInFile; this.startLine = builder.startLine; this.endLine = builder.endLine; this.startUnit = builder.startUnit; this.endUnit = builder.endUnit; } /** * @since 2.14 */ public static Builder builder() { return new Builder(); } /** * <p>Instances can be reused - it is safe to call {@link #build} * multiple times to build multiple blocks in series.</p> * * @since 2.14 */ public static final class Builder { private String resourceId; private ByteArray blockHash; private int indexInFile; private int startLine; private int endLine; private int startUnit; private int endUnit; public Builder setResourceId(String resourceId) { this.resourceId = resourceId; return this; } public Builder setBlockHash(ByteArray blockHash) { this.blockHash = blockHash; return this; } public Builder setIndexInFile(int index) { this.indexInFile = index; return this; } public Builder setLines(int start, int end) { this.startLine = start; this.endLine = end; return this; } public Builder setUnit(int start, int end) { this.startUnit = start; this.endUnit = end; return this; } public Block build() { return new Block(this); } } public String getHashHex() { return getBlockHash().toString(); } public String getResourceId() { return resourceId; } public ByteArray getBlockHash() { return blockHash; } public int getIndexInFile() { return indexInFile; } public int getStartLine() { return startLine; } public int getEndLine() { return endLine; } /** * @since 2.14 */ public int getStartUnit() { return startUnit; } /** * @since 2.14 */ public int getEndUnit() { return endUnit; } @Override public boolean equals(Object obj) { if (!(obj instanceof Block)) { return false; } Block other = (Block) obj; return resourceId.equals(other.resourceId) && blockHash.equals(other.blockHash) && indexInFile == other.indexInFile && startLine == other.startLine && endLine == other.endLine; } @Override public int hashCode() { int h = hash; if (h == 0) { h = resourceId.hashCode(); h = 31 * h + blockHash.hashCode(); h = 31 * h + indexInFile; h = 31 * h + startLine; h = 31 * h + endLine; hash = h; } return h; } @Override public String toString() { return "'" + resourceId + "'[" + indexInFile + "|" + startLine + "-" + endLine + "]:" + blockHash; } }
4,199
21.95082
136
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/block/BlockChunker.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.duplications.block; import java.util.ArrayList; import org.sonar.duplications.statement.Statement; import java.util.Collections; import java.util.List; /** * Creates blocks from statements, each block will contain specified number of statements (<code>blockSize</code>) and 64-bits (8-bytes) hash value. * Hash value computed using * <a href="http://en.wikipedia.org/wiki/Rolling_hash#Rabin-Karp_rolling_hash">Rabin-Karp rolling hash</a> : * <blockquote><pre> * s[0]*31^(blockSize-1) + s[1]*31^(blockSize-2) + ... + s[blockSize-1] * </pre></blockquote> * using <code>long</code> arithmetic, where <code>s[i]</code> * is the hash code of <code>String</code> (which is cached) for statement with number i. * Thus running time - O(N), where N - number of statements. * Implementation fully thread-safe. */ public class BlockChunker { private static final long PRIME_BASE = 31; private final int blockSize; private final long power; public BlockChunker(int blockSize) { this.blockSize = blockSize; long pow = 1; for (int i = 0; i < blockSize - 1; i++) { pow = pow * PRIME_BASE; } this.power = pow; } public List<Block> chunk(String resourceId, List<Statement> statements) { List<Statement> filtered = new ArrayList<>(); int i = 0; while (i < statements.size()) { Statement first = statements.get(i); int j = i + 1; while (j < statements.size() && statements.get(j).getValue().equals(first.getValue())) { j++; } filtered.add(statements.get(i)); if (i < j - 1) { filtered.add(statements.get(j - 1)); } i = j; } statements = filtered; if (statements.size() < blockSize) { return Collections.emptyList(); } Statement[] statementsArr = statements.toArray(new Statement[statements.size()]); List<Block> blocks = new ArrayList<>(statementsArr.length - blockSize + 1); long hash = 0; int first = 0; int last = 0; for (; last < blockSize - 1; last++) { hash = hash * PRIME_BASE + statementsArr[last].getValue().hashCode(); } Block.Builder blockBuilder = Block.builder().setResourceId(resourceId); for (; last < statementsArr.length; last++, first++) { Statement firstStatement = statementsArr[first]; Statement lastStatement = statementsArr[last]; // add last statement to hash hash = hash * PRIME_BASE + lastStatement.getValue().hashCode(); // create block Block block = blockBuilder.setBlockHash(new ByteArray(hash)) .setIndexInFile(first) .setLines(firstStatement.getStartLine(), lastStatement.getEndLine()) .build(); blocks.add(block); // remove first statement from hash hash -= power * firstStatement.getValue().hashCode(); } return blocks; } public int getBlockSize() { return blockSize; } }
3,749
33.722222
148
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/block/ByteArray.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.duplications.block; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.Arrays; /** * Represents hash for {@link Block}. Immutable. * * TODO Godin: would be better to rename to BlockHash, * also maybe we can incorporate it into Block to reduce memory footprint during detection of duplicates */ public final class ByteArray { private static final String HEXES = "0123456789abcdef"; private final byte[] bytes; /** * Cache for hash code. */ private int hash; public ByteArray(String hexString) { int len = hexString.length(); this.bytes = new byte[len / 2]; for (int i = 0; i < len; i += 2) { bytes[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16)); } } public ByteArray(byte[] bytes) { this.bytes = new byte[bytes.length]; System.arraycopy(bytes, 0, this.bytes, 0, bytes.length); } public ByteArray(long value) { this.bytes = new byte[] { (byte) (value >>> 56), (byte) (value >>> 48), (byte) (value >>> 40), (byte) (value >>> 32), (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; } public ByteArray(int value) { this.bytes = new byte[] { (byte) (value >>> 24), (byte) (value >>> 16), (byte) (value >>> 8), (byte) value}; } public ByteArray(int[] intArray) { ByteBuffer bb = ByteBuffer.allocate(intArray.length * 4); for (int i : intArray) { bb.putInt(i); } this.bytes = bb.array(); } public byte[] getBytes() { return bytes; } public int[] toIntArray() { // Pad the size to multiple of 4 int size = (bytes.length / 4) + (bytes.length % 4 == 0 ? 0 : 1); ByteBuffer bb = ByteBuffer.allocate(size * 4); bb.put(bytes); // see https://github.com/mongodb/mongo-java-driver/commit/21c91bd364d38489e0bbe2e390efdb3746ee3fff // The Java 9 ByteBuffer classes introduces overloaded methods with covariant return types for the following methods used by the driver: // Without casting, exceptions like this are thrown when executing on Java 8 and lower: // java.lang.NoSuchMethodError: java.nio.ByteBuffer.limit(I)Ljava/nio/ByteBuffer //This is because the generated byte code includes the static return type of the method, which is not found on Java 8 and lower because //the overloaded methods with covariant return types don't exist. bb.rewind(); IntBuffer ib = bb.asIntBuffer(); int[] result = new int[size]; ib.get(result); return result; } public String toHexString() { StringBuilder hex = new StringBuilder(2 * bytes.length); for (byte b : bytes) { hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(HEXES.charAt(b & 0x0F)); } return hex.toString(); } @Override public String toString() { return toHexString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ByteArray other = (ByteArray) o; return Arrays.equals(bytes, other.bytes); } @Override public int hashCode() { int h = hash; int len = bytes.length; if (h == 0 && len > 0) { h = Arrays.hashCode(bytes); hash = h; } return h; } }
4,223
28.333333
140
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/block/FileBlocks.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.duplications.block; import java.util.List; /** * Represents all blocks in a file. */ public final class FileBlocks { private final String resourceId; private final List<Block> blocks; public FileBlocks(String resourceId, List<Block> blocks) { this.resourceId = resourceId; this.blocks = blocks; } public String resourceId() { return resourceId; } public List<Block> blocks() { return blocks; } }
1,298
27.23913
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/block/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.duplications.block; import javax.annotation.ParametersAreNonnullByDefault;
969
37.8
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/ContainsInComparator.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.duplications.detector; import java.util.Comparator; import org.sonar.duplications.index.ClonePart; import org.sonar.duplications.utils.FastStringComparator; /** * Allows to determine if ClonePart includes another ClonePart. * Inclusion is the partial order, so in fact this class violates contracts of {@link Comparator}, * however it allows to use {@link org.sonar.duplications.utils.SortedListsUtils} for efficient filtering. */ public final class ContainsInComparator implements Comparator<ClonePart> { /** * Defines order by resourceId. */ public static final Comparator<ClonePart> RESOURCE_ID_COMPARATOR = (o1, o2) -> FastStringComparator.INSTANCE.compare(o1.getResourceId(), o2.getResourceId()); /** * Defines order by resourceId and by unitStart. */ public static final Comparator<ClonePart> CLONEPART_COMPARATOR = (o1, o2) -> { int c = RESOURCE_ID_COMPARATOR.compare(o1, o2); if (c == 0) { return o1.getUnitStart() - o2.getUnitStart(); } return c; }; private final int l1; private final int l2; /** * Constructs new comparator for two parts with lengths {@code l1} and {@code l2} respectively. */ public ContainsInComparator(int l1, int l2) { this.l1 = l1; this.l2 = l2; } /** * Compares two parts on inclusion. * part1 includes part2 if {@code (part1.resourceId == part2.resourceId) && (part1.unitStart <= part2.unitStart) && (part2.unitEnd <= part1.unitEnd)}. * * @return 0 if part1 includes part2, * 1 if resourceId of part1 is greater than resourceId of part2 or if unitStart of part1 is greater than unitStart of part2, * -1 in all other cases */ @Override public int compare(ClonePart part1, ClonePart part2) { int c = RESOURCE_ID_COMPARATOR.compare(part1, part2); if (c == 0) { if (part1.getUnitStart() <= part2.getUnitStart()) { if (part2.getUnitStart() + l2 <= part1.getUnitStart() + l1) { // part1 contains part2 return 0; } else { // SortedListsUtils#contains should continue search return -1; } } else { // unitStart of part1 is less than unitStart of part2 - SortedListsUtils#contains should stop search return 1; } } else { return c; } } }
3,170
33.846154
159
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/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.duplications.detector; import javax.annotation.ParametersAreNonnullByDefault;
972
37.92
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/original/BlocksGroup.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.duplications.detector.original; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import javax.annotation.CheckForNull; import org.sonar.duplications.block.Block; import org.sonar.duplications.utils.FastStringComparator; /** * Set of {@link Block}s, which internally stored as a sorted list. */ final class BlocksGroup { private static final Comparator<String> RESOURCE_ID_COMPARATOR = FastStringComparator.INSTANCE; final List<Block> blocks; private BlocksGroup() { this.blocks = new ArrayList<>(); } /** * Factory method. * * @return new empty group */ public static BlocksGroup empty() { return new BlocksGroup(); } public int size() { return blocks.size(); } /** * @return true, if this group subsumed by specified group * @see #subsumedBy(BlocksGroup, BlocksGroup, int) */ public boolean subsumedBy(BlocksGroup other, int indexCorrection) { return subsumedBy(this, other, indexCorrection); } /** * @return intersection of this group with specified * @see #intersect(BlocksGroup, BlocksGroup) */ public BlocksGroup intersect(BlocksGroup other) { return intersect(this, other); } public List<Block[]> pairs(BlocksGroup other, int len) { return pairs(this, other, len); } /** * First block from this group with specified resource id. */ @CheckForNull public Block first(String resourceId) { for (Block block : blocks) { if (resourceId.equals(block.getResourceId())) { return block; } } return null; } @Override public String toString() { return blocks.toString(); } /** * Intersection of two groups is a group, which contains blocks from second group that have corresponding block from first group * with same resource id and with corrected index. */ private static BlocksGroup intersect(BlocksGroup group1, BlocksGroup group2) { BlocksGroup intersection = new BlocksGroup(); List<Block> list1 = group1.blocks; List<Block> list2 = group2.blocks; int i = 0; int j = 0; while (i < list1.size() && j < list2.size()) { Block block1 = list1.get(i); Block block2 = list2.get(j); int c = RESOURCE_ID_COMPARATOR.compare(block1.getResourceId(), block2.getResourceId()); if (c > 0) { j++; continue; } if (c < 0) { i++; continue; } if (c == 0) { c = block1.getIndexInFile() + 1 - block2.getIndexInFile(); } if (c == 0) { // list1[i] == list2[j] i++; j++; intersection.blocks.add(block2); } if (c > 0) { // list1[i] > list2[j] j++; } if (c < 0) { // list1[i] < list2[j] i++; } } return intersection; } /** * One group is subsumed by another group, when each block from first group has corresponding block from second group * with same resource id and with corrected index. */ private static boolean subsumedBy(BlocksGroup group1, BlocksGroup group2, int indexCorrection) { List<Block> list1 = group1.blocks; List<Block> list2 = group2.blocks; int i = 0; int j = 0; while (i < list1.size() && j < list2.size()) { Block block1 = list1.get(i); Block block2 = list2.get(j); int c = RESOURCE_ID_COMPARATOR.compare(block1.getResourceId(), block2.getResourceId()); if (c != 0) { j++; continue; } c = block1.getIndexInFile() - indexCorrection - block2.getIndexInFile(); if (c < 0) { // list1[i] < list2[j] break; } if (c != 0) { // list1[i] != list2[j] j++; } if (c == 0) { // list1[i] == list2[j] i++; j++; } } return i == list1.size(); } private static List<Block[]> pairs(BlocksGroup beginGroup, BlocksGroup endGroup, int len) { List<Block[]> result = new ArrayList<>(); List<Block> beginBlocks = beginGroup.blocks; List<Block> endBlocks = endGroup.blocks; int i = 0; int j = 0; while (i < beginBlocks.size() && j < endBlocks.size()) { Block beginBlock = beginBlocks.get(i); Block endBlock = endBlocks.get(j); int c = RESOURCE_ID_COMPARATOR.compare(beginBlock.getResourceId(), endBlock.getResourceId()); if (c == 0) { c = beginBlock.getIndexInFile() + len - 1 - endBlock.getIndexInFile(); } if (c == 0) { result.add(new Block[] {beginBlock, endBlock}); i++; j++; } if (c > 0) { j++; } if (c < 0) { i++; } } return result; } /** * Compares {@link Block}s first using {@link Block#getResourceId() resource id} and then using {@link Block#getIndexInFile() index in file}. */ public static class BlockComparator implements Comparator<Block> { public static final BlockComparator INSTANCE = new BlockComparator(); @Override public int compare(Block b1, Block b2) { int c = RESOURCE_ID_COMPARATOR.compare(b1.getResourceId(), b2.getResourceId()); if (c == 0) { return b1.getIndexInFile() - b2.getIndexInFile(); } return c; } } }
6,100
27.24537
143
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/original/Filter.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.duplications.detector.original; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.sonar.duplications.detector.ContainsInComparator; import org.sonar.duplications.index.CloneGroup; import org.sonar.duplications.index.ClonePart; import org.sonar.duplications.utils.SortedListsUtils; /** * Performs incremental and brute force algorithm in order to filter clones, which are fully covered by other clones. * All clones for filtering must be of the same origin - there is no sanity check on this. * In a worst case it performs O(N*N) comparisons. * <p> * Godin: This implementation was chosen because it simple. * And I wasn't able to find big difference in performance with an interval tree, which we had for the moment of testing. * Whereas in fact I expected that interval tree would be better for this task. * Moreover with interval tree we also can use incremental approach, * but we did not had an implementation with remove operation for the moment of testing. * </p> */ final class Filter { /** * Note that LinkedList should provide better performance here, because of use of operation remove. * * @see #add(CloneGroup) */ private final List<CloneGroup> filtered = new LinkedList<>(); /** * @return current results of filtering */ public List<CloneGroup> getResult() { return filtered; } /** * Running time - O(N*2*C), where N - number of clones, which was found earlier and C - time of {@link #containsIn(CloneGroup, CloneGroup)}. */ public void add(CloneGroup current) { Iterator<CloneGroup> i = filtered.iterator(); while (i.hasNext()) { CloneGroup earlier = i.next(); // Note that following two conditions cannot be true together - proof by contradiction: // let C be the current clone and A and B were found earlier // then since relation is transitive - (A in C) and (C in B) => (A in B) // so A should be filtered earlier if (Filter.containsIn(current, earlier)) { // current clone fully covered by clone, which was found earlier return; } if (Filter.containsIn(earlier, current)) { // current clone fully covers clone, which was found earlier i.remove(); } } filtered.add(current); } /** * Checks that second clone contains first one. * <p> * Clone A is contained in another clone B, if every part pA from A has part pB in B, * which satisfy the conditions: * <pre> * (pA.resourceId == pB.resourceId) and (pB.unitStart <= pA.unitStart) and (pA.unitEnd <= pB.unitEnd) * </pre> * And all resourcesId from B exactly the same as all resourceId from A, which means that also every part pB from B has part pA in A, * which satisfy the condition: * <pre> * pB.resourceId == pA.resourceId * </pre> * So this relation is: * <ul> * <li>reflexive - A in A</li> * <li>transitive - (A in B) and (B in C) => (A in C)</li> * <li>antisymmetric - (A in B) and (B in A) <=> (A = B)</li> * </ul> * </p> * <p> * <strong>Important: this method relies on fact that all parts were already sorted by resourceId and unitStart by using * {@link BlocksGroup.BlockComparator}, which uses {@link org.sonar.duplications.utils.FastStringComparator} for comparison by resourceId.</strong> * </p> * <p> * Running time - O(|A|+|B|). * </p> */ static boolean containsIn(CloneGroup first, CloneGroup second) { if (first.getCloneUnitLength() > second.getCloneUnitLength()) { return false; } List<ClonePart> firstParts = first.getCloneParts(); List<ClonePart> secondParts = second.getCloneParts(); return SortedListsUtils.contains(secondParts, firstParts, new ContainsInComparator(second.getCloneUnitLength(), first.getCloneUnitLength())) && SortedListsUtils.contains(firstParts, secondParts, ContainsInComparator.RESOURCE_ID_COMPARATOR); } }
4,801
39.016667
149
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/original/OriginalCloneDetectionAlgorithm.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.duplications.detector.original; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.sonar.duplications.block.Block; import org.sonar.duplications.block.ByteArray; import org.sonar.duplications.index.CloneGroup; import org.sonar.duplications.index.CloneIndex; import org.sonar.duplications.index.ClonePart; /** * Implementation of algorithm described in paper * <a href="http://www4.in.tum.de/~juergens/publications/icsm2010_crc.pdf">Index-Based Code Clone Detection: Incremental, Distributed, Scalable</a> * by Benjamin Hummel, Elmar Juergens, Michael Conradt and Lars Heinemann. */ public final class OriginalCloneDetectionAlgorithm { private final CloneIndex cloneIndex; private final Filter filter = new Filter(); private String originResourceId; private OriginalCloneDetectionAlgorithm(CloneIndex cloneIndex) { this.cloneIndex = cloneIndex; } private BlocksGroup[] createGroups(Collection<Block> fileBlocks) { // 2: let f be the list of tuples corresponding to filename sorted by statement index // either read from the index or calculated on the fly int size = fileBlocks.size(); // Godin: create one group per unique hash // TODO Godin: can we create map with expected size? Map<ByteArray, BlocksGroup> groupsByHash = new HashMap<>(); for (Block fileBlock : fileBlocks) { ByteArray hash = fileBlock.getBlockHash(); BlocksGroup sameHash = groupsByHash.get(hash); if (sameHash == null) { sameHash = BlocksGroup.empty(); groupsByHash.put(hash, sameHash); } sameHash.blocks.add(fileBlock); } // Godin: retrieve blocks from index for (Map.Entry<ByteArray, BlocksGroup> entry : groupsByHash.entrySet()) { ByteArray hash = entry.getKey(); BlocksGroup group = entry.getValue(); for (Block blockFromIndex : cloneIndex.getBySequenceHash(hash)) { // Godin: skip blocks for this file if they come from index if (!originResourceId.equals(blockFromIndex.getResourceId())) { group.blocks.add(blockFromIndex); } } Collections.sort(group.blocks, BlocksGroup.BlockComparator.INSTANCE); } // 3: let c be a list with c(0) = empty BlocksGroup[] sameHashBlocksGroups = new BlocksGroup[size + 2]; sameHashBlocksGroups[0] = BlocksGroup.empty(); // 4: for i := 1 to length(f) do for (Block fileBlock : fileBlocks) { ByteArray hash = fileBlock.getBlockHash(); int i = fileBlock.getIndexInFile() + 1; // 5: retrieve tuples with same sequence hash as f(i) // 6: store this set as c(i) sameHashBlocksGroups[i] = groupsByHash.get(hash); } // Godin: allows to report clones at the end of file, because condition at line 13 would be evaluated as true sameHashBlocksGroups[size + 1] = BlocksGroup.empty(); return sameHashBlocksGroups; } private void findClones(Collection<Block> fileBlocks) { originResourceId = fileBlocks.iterator().next().getResourceId(); BlocksGroup[] sameHashBlocksGroups = createGroups(fileBlocks); // 7: for i := 1 to length(c) do for (int i = 1; i < sameHashBlocksGroups.length; i++) { // In the main loop (starting from Line 7), we first check // whether any new clones might start at this position. If there // is only a single tuple with this hash (which has to belong // to the inspected file at the current location) we skip this loop // iteration. The same holds if all tuples at position i have already // been present at position i − 1, as in this case any clone group // found at position i would be included in a clone group starting // at position i − 1. // Although we use the subset operator in the // algorithm description, this is not really a subset operation, // as of course the statement index of the tuples in c(i) will be // increased by 1 compared to the corresponding ones in c(i − 1) // and the hash and info fields will differ. // 8: if |c(i)| < 2 or c(i) subsumed by c(i - 1) then if (sameHashBlocksGroups[i].size() < 2 || sameHashBlocksGroups[i].subsumedBy(sameHashBlocksGroups[i - 1], 1)) { // 9: continue with next loop iteration continue; } // The set a introduced in Line 10 is called the active set and // contains all tuples corresponding to clones which have not yet // been reported. At each iteration of the inner loop the set a // is reduced to tuples which are also present in c(j); again the // intersection operator has to account for the increased statement // index and different hash and info fields. The new value is // stored in a0. Clones are only reported, if tuples are lost in // Line 12, as otherwise all current clones could be prolonged // by one statement. Clone reporting matches tuples that, after // correction of the statement index, appear in both c(i) and a, // each matched pair corresponds to a single clone. Its location // can be extracted from the filename and info fields. // 10: let a := c(i) BlocksGroup currentBlocksGroup = sameHashBlocksGroups[i]; // 11: for j := i + 1 to length(c) do for (int j = i + 1; j < sameHashBlocksGroups.length; j++) { // 12: let a0 := a intersect c(j) BlocksGroup intersectedBlocksGroup = currentBlocksGroup.intersect(sameHashBlocksGroups[j]); // 13: if |a0| < |a| then if (intersectedBlocksGroup.size() < currentBlocksGroup.size()) { // 14: report clones from c(i) to a (see text) // One problem of this algorithm is that clone classes with // multiple instances in the same file are encountered and // reported multiple times. Furthermore, when calculating the clone // groups for all files in a system, clone groups will be reported // more than once as well. Both cases can be avoided, by // checking whether the first element of a0 (with respect to a // fixed order) is equal to f(j) and only report in this case. Block first = currentBlocksGroup.first(originResourceId); if (first != null && first.getIndexInFile() == j - 2) { // Godin: We report clones, which start in i-1 and end in j-2, so length is j-2-(i-1)+1=j-i reportClones(sameHashBlocksGroups[i], currentBlocksGroup, j - i); } } // 15: a := a0 currentBlocksGroup = intersectedBlocksGroup; // Line 16 early exits the inner loop if either no more clones are starting // from position i (i.e., a is too small), or if all tuples from a // have already been in c(i − 1), corrected for statement index. // In this case they have already been reported in the previous // iteration of the outer loop. // IMPORTANT Godin: note that difference in indexes between "a" and "c(i-1)" greater than one, // so method subsumedBy should take this into account // 16: if |a| < 2 or a subsumed by c(i-1) then if (currentBlocksGroup.size() < 2 || currentBlocksGroup.subsumedBy(sameHashBlocksGroups[i - 1], j - i + 1)) { // 17: break inner loop break; } } } } private void reportClones(BlocksGroup beginGroup, BlocksGroup endGroup, int cloneLength) { List<Block[]> pairs = beginGroup.pairs(endGroup, cloneLength); ClonePart origin = null; List<ClonePart> parts = new ArrayList<>(); for (int i = 0; i < pairs.size(); i++) { Block[] pair = pairs.get(i); Block firstBlock = pair[0]; Block lastBlock = pair[1]; ClonePart part = new ClonePart(firstBlock.getResourceId(), firstBlock.getIndexInFile(), firstBlock.getStartLine(), lastBlock.getEndLine()); if (originResourceId.equals(part.getResourceId())) { if (origin == null || part.getUnitStart() < origin.getUnitStart()) { origin = part; } } parts.add(part); } filter.add(CloneGroup.builder().setLength(cloneLength).setOrigin(origin).setParts(parts).build()); } /** * Performs detection and returns list of clone groups between file (which represented as a collection of blocks) and index. * Note that this method ignores blocks for this file, that will be retrieved from index. */ public static List<CloneGroup> detect(CloneIndex cloneIndex, Collection<Block> fileBlocks) { if (fileBlocks.isEmpty()) { return Collections.emptyList(); } OriginalCloneDetectionAlgorithm reporter = new OriginalCloneDetectionAlgorithm(cloneIndex); reporter.findClones(fileBlocks); return reporter.filter.getResult(); } }
9,725
42.226667
147
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/original/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.duplications.detector.original; import javax.annotation.ParametersAreNonnullByDefault;
981
38.28
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/AbstractText.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.duplications.detector.suffixtree; import java.util.ArrayList; import java.util.List; public abstract class AbstractText implements Text { protected final List<Object> symbols; public AbstractText(int size) { this.symbols = new ArrayList<>(size); } public AbstractText(List<Object> symbols) { this.symbols = symbols; } @Override public int length() { return symbols.size(); } @Override public Object symbolAt(int index) { return symbols.get(index); } @Override public List<Object> sequence(int fromIndex, int toIndex) { return symbols.subList(fromIndex, toIndex); } }
1,485
27.037736
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/DuplicationsCollector.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.duplications.detector.suffixtree; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.sonar.duplications.block.Block; import org.sonar.duplications.detector.ContainsInComparator; import org.sonar.duplications.index.CloneGroup; import org.sonar.duplications.index.ClonePart; import org.sonar.duplications.utils.SortedListsUtils; /** * Implementation of {@link Search.Collector}, which constructs {@link CloneGroup}s. */ public class DuplicationsCollector extends Search.Collector { private final TextSet text; private final String originResourceId; private final List<CloneGroup> filtered = new ArrayList<>(); private int length; private int count; private int[][] blockNumbers; public DuplicationsCollector(TextSet text) { this.text = text; this.originResourceId = text.getBlock(0).getResourceId(); } /** * @return current result */ public List<CloneGroup> getResult() { return filtered; } @Override public void startOfGroup(int size, int length) { this.blockNumbers = new int[size][2]; this.length = length; } /** * Constructs ClonePart and saves it for future processing in {@link #endOfGroup()}. * * @param start number of first block from text for this part * @param end number of last block from text for this part */ @Override public void part(int start, int end) { blockNumbers[count][0] = start; blockNumbers[count][1] = end - 1; count++; } /** * Constructs CloneGroup and saves it. */ @Override public void endOfGroup() { ClonePart origin = null; CloneGroup.Builder builder = CloneGroup.builder().setLength(length); List<ClonePart> parts = new ArrayList<>(count); for (int[] b : blockNumbers) { Block firstBlock = text.getBlock(b[0]); Block lastBlock = text.getBlock(b[1]); ClonePart part = new ClonePart( firstBlock.getResourceId(), firstBlock.getIndexInFile(), firstBlock.getStartLine(), lastBlock.getEndLine()); // TODO Godin: maybe use FastStringComparator here ? if (originResourceId.equals(part.getResourceId())) { // part from origin if (origin == null) { origin = part; // To calculate length important to use the origin, because otherwise block may come from DB without required data builder.setLengthInUnits(lastBlock.getEndUnit() - firstBlock.getStartUnit() + 1); } else if (part.getUnitStart() < origin.getUnitStart()) { origin = part; } } parts.add(part); } Collections.sort(parts, ContainsInComparator.CLONEPART_COMPARATOR); builder.setOrigin(origin).setParts(parts); filter(builder.build()); reset(); } /** * Prepare for processing of next duplication. */ private void reset() { blockNumbers = null; count = 0; } /** * Saves CloneGroup, if it is not included into previously saved. * <p> * Current CloneGroup can not include none of CloneGroup, which were constructed before. * Proof: * According to an order of visiting nodes in suffix tree - length of earlier >= length of current. * If length of earlier > length of current, then earlier not contained in current. * If length of earlier = length of current, then earlier can be contained in current only * when current has exactly the same and maybe some additional CloneParts as earlier, * what in his turn will mean that two inner-nodes on same depth will satisfy condition * current.startSize <= earlier.startSize <= earlier.endSize <= current.endSize , which is not possible for different inner-nodes on same depth. * </p> * Thus this method checks only that none of CloneGroup, which was constructed before, does not include current CloneGroup. */ private void filter(CloneGroup current) { for (CloneGroup earlier : filtered) { if (containsIn(current, earlier)) { return; } } filtered.add(current); } /** * Checks that second CloneGroup includes first one. * <p> * CloneGroup A is included in another CloneGroup B, if every part pA from A has part pB in B, * which satisfy the conditions: * <pre> * (pA.resourceId == pB.resourceId) and (pB.unitStart <= pA.unitStart) and (pA.unitEnd <= pB.unitEnd) * </pre> * And all resourcesId from B exactly the same as all resourceId from A, which means that also every part pB from B has part pA in A, * which satisfy the condition: * <pre> * pB.resourceId == pA.resourceId * </pre> * Inclusion is the partial order, thus this relation is: * <ul> * <li>reflexive - A in A</li> * <li>transitive - (A in B) and (B in C) => (A in C)</li> * <li>antisymmetric - (A in B) and (B in A) <=> (A = B)</li> * </ul> * </p> * <p> * This method uses the fact that all parts already sorted by resourceId and unitStart (see {@link ContainsInComparator#CLONEPART_COMPARATOR}), * so running time - O(|A|+|B|). * </p> */ private static boolean containsIn(CloneGroup first, CloneGroup second) { List<ClonePart> firstParts = first.getCloneParts(); List<ClonePart> secondParts = second.getCloneParts(); // TODO Godin: according to tests seems that if first part of condition is true, then second part can not be false // if this can be proved, then second part can be removed return SortedListsUtils.contains(secondParts, firstParts, new ContainsInComparator(second.getCloneUnitLength(), first.getCloneUnitLength())) && SortedListsUtils.contains(firstParts, secondParts, ContainsInComparator.RESOURCE_ID_COMPARATOR); } }
6,529
34.48913
146
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/Edge.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.duplications.detector.suffixtree; public final class Edge { // can't be changed private int beginIndex; private int endIndex; private Node startNode; // can't be changed, could be used as edge id private Node endNode; // each time edge is created, a new end node is created public Edge(int beginIndex, int endIndex, Node startNode) { this.beginIndex = beginIndex; this.endIndex = endIndex; this.startNode = startNode; this.endNode = new Node(startNode, null); } public Node splitEdge(Suffix suffix) { remove(); Edge newEdge = new Edge(beginIndex, beginIndex + suffix.getSpan(), suffix.getOriginNode()); newEdge.insert(); newEdge.endNode.setSuffixNode(suffix.getOriginNode()); beginIndex += suffix.getSpan() + 1; startNode = newEdge.getEndNode(); insert(); return newEdge.getEndNode(); } public void insert() { startNode.addEdge(beginIndex, this); } public void remove() { startNode.removeEdge(beginIndex); } /** * @return length of this edge in symbols */ public int getSpan() { return endIndex - beginIndex; } public int getBeginIndex() { return beginIndex; } public int getEndIndex() { return endIndex; } public Node getStartNode() { return startNode; } public Node getEndNode() { return endNode; } }
2,213
25.357143
95
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/Node.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.duplications.detector.suffixtree; import java.util.Map; import java.util.HashMap; import java.util.Collection; public final class Node { private final SuffixTree suffixTree; private final Map<Object, Edge> edges; /** * Node represents string s[i],s[i+1],...,s[j], * suffix-link is a link to node, which represents string s[i+1],...,s[j]. */ private Node suffixNode; /** * Number of symbols from the root to this node. * <p> * Note that this is not equal to number of nodes from root to this node, * because in a compact suffix-tree edge can span multiple symbols - see {@link Edge#getSpan()}. * </p><p> * Depth of {@link #suffixNode} is always equal to this depth minus one. * </p> */ int depth; int startSize; int endSize; public Node(Node node, Node suffixNode) { this(node.suffixTree, suffixNode); } public Node(SuffixTree suffixTree, Node suffixNode) { this.suffixTree = suffixTree; this.suffixNode = suffixNode; edges = new HashMap<>(); } public Object symbolAt(int index) { return suffixTree.symbolAt(index); } public void addEdge(int charIndex, Edge edge) { edges.put(symbolAt(charIndex), edge); } public void removeEdge(int charIndex) { edges.remove(symbolAt(charIndex)); } public Edge findEdge(Object ch) { return edges.get(ch); } public Node getSuffixNode() { return suffixNode; } public void setSuffixNode(Node suffixNode) { this.suffixNode = suffixNode; } public Collection<Edge> getEdges() { return edges.values(); } }
2,439
26.111111
98
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/Search.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.duplications.detector.suffixtree; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; public final class Search { private final SuffixTree tree; private final TextSet text; private final Collector reporter; private final List<Integer> list = new ArrayList<>(); private final List<Node> innerNodes = new ArrayList<>(); private static final Comparator<Node> DEPTH_COMPARATOR = (o1, o2) -> o2.depth - o1.depth; private Search(SuffixTree tree, TextSet text, Collector reporter) { this.tree = tree; this.text = text; this.reporter = reporter; } public static void perform(TextSet text, Collector reporter) { new Search(SuffixTree.create(text), text, reporter).compute(); } private void compute() { // O(N) dfs(); // O(N * log(N)) Collections.sort(innerNodes, DEPTH_COMPARATOR); // O(N) visitInnerNodes(); } /** * Depth-first search (DFS). */ private void dfs() { Deque<Node> stack = new LinkedList<>(); stack.add(tree.getRootNode()); while (!stack.isEmpty()) { Node node = stack.removeLast(); node.startSize = list.size(); if (node.getEdges().isEmpty()) { // leaf list.add(node.depth); node.endSize = list.size(); } else { if (!node.equals(tree.getRootNode())) { // inner node = not leaf and not root innerNodes.add(node); } for (Edge edge : node.getEdges()) { Node endNode = edge.getEndNode(); endNode.depth = node.depth + edge.getSpan() + 1; stack.addLast(endNode); } } } // At this point all inner nodes are ordered by the time of entering, so we visit them from last to first ListIterator<Node> iterator = innerNodes.listIterator(innerNodes.size()); while (iterator.hasPrevious()) { Node node = iterator.previous(); int max = -1; for (Edge edge : node.getEdges()) { max = Math.max(edge.getEndNode().endSize, max); } node.endSize = max; } } /** * Each inner-node represents prefix of some suffixes, thus substring of text. */ private void visitInnerNodes() { for (Node node : innerNodes) { if (containsOrigin(node)) { report(node); } } } /** * TODO Godin: in fact computations here are the same as in {@link #report(Node)}, * so maybe would be better to remove this duplication, * however it should be noted that this check can't be done in {@link Collector#endOfGroup()}, * because it might lead to creation of unnecessary new objects */ private boolean containsOrigin(Node node) { for (int i = node.startSize; i < node.endSize; i++) { int start = tree.text.length() - list.get(i); int end = start + node.depth; if (text.isInsideOrigin(end)) { return true; } } return false; } private void report(Node node) { reporter.startOfGroup(node.endSize - node.startSize, node.depth); for (int i = node.startSize; i < node.endSize; i++) { int start = tree.text.length() - list.get(i); int end = start + node.depth; reporter.part(start, end); } reporter.endOfGroup(); } public abstract static class Collector { /** * Invoked at the beginning of processing for current node. * <p> * Length - is a depth of node. And nodes are visited in descending order of depth, * thus we guaranty that length will not increase between two sequential calls of this method * (can be equal or less than previous value). * </p> * * @param size number of parts in group * @param length length of each part in group */ abstract void startOfGroup(int size, int length); /** * Invoked as many times as leaves in the subtree, where current node is root. * * @param start start position in generalised text * @param end end position in generalised text */ abstract void part(int start, int end); /** * Invoked at the end of processing for current node. */ abstract void endOfGroup(); } }
5,117
29.464286
109
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/Suffix.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.duplications.detector.suffixtree; public final class Suffix { private Node originNode; private int beginIndex; private int endIndex; public Suffix(Node originNode, int beginIndex, int endIndex) { this.originNode = originNode; this.beginIndex = beginIndex; this.endIndex = endIndex; } public boolean isExplicit() { return beginIndex > endIndex; } public boolean isImplicit() { return !isExplicit(); } public void canonize() { if (isImplicit()) { Edge edge = originNode.findEdge(originNode.symbolAt(beginIndex)); int edgeSpan = edge.getSpan(); while (edgeSpan <= getSpan()) { beginIndex += edgeSpan + 1; originNode = edge.getEndNode(); if (beginIndex <= endIndex) { edge = edge.getEndNode().findEdge(originNode.symbolAt(beginIndex)); edgeSpan = edge.getSpan(); } } } } public int getSpan() { return endIndex - beginIndex; } public Node getOriginNode() { return originNode; } public int getBeginIndex() { return beginIndex; } public void incBeginIndex() { beginIndex++; } public void changeOriginNode() { originNode = originNode.getSuffixNode(); } public int getEndIndex() { return endIndex; } public void incEndIndex() { endIndex++; } }
2,193
24.218391
77
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/SuffixTree.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.duplications.detector.suffixtree; import java.util.Objects; /** * Provides algorithm to construct suffix tree. * <p> * Suffix tree for the string S of length n is defined as a tree such that: * <ul> * <li>the paths from the root to the leaves have a one-to-one relationship with the suffixes of S,</li> * <li>edges spell non-empty strings,</li> * <li>and all internal nodes (except perhaps the root) have at least two children.</li> * </ul> * Since such a tree does not exist for all strings, S is padded with a terminal symbol not seen in the string (usually denoted $). * This ensures that no suffix is a prefix of another, and that there will be n leaf nodes, one for each of the n suffixes of S. * Since all internal non-root nodes are branching, there can be at most n − 1 such nodes, and n + (n − 1) + 1 = 2n nodes in total. * All internal nodes and leaves have incoming edge, so number of edges equal to number of leaves plus number of inner nodes, * thus at most 2n - 1. * Construction takes O(n) time. * </p><p> * This implementation was adapted from <a href="http://illya-keeplearning.blogspot.com/search/label/suffix%20tree">Java-port</a> of * <a href="http://marknelson.us/1996/08/01/suffix-trees/">Mark Nelson's C++ implementation of Ukkonen's algorithm</a>. * </p> */ public final class SuffixTree { final Text text; private final Node root; private SuffixTree(Text text) { this.text = text; root = new Node(this, null); } public static SuffixTree create(Text text) { SuffixTree tree = new SuffixTree(text); Suffix active = new Suffix(tree.root, 0, -1); for (int i = 0; i < text.length(); i++) { tree.addPrefix(active, i); } return tree; } private void addPrefix(Suffix active, int endIndex) { Node lastParentNode = null; Node parentNode; while (true) { Edge edge; parentNode = active.getOriginNode(); // Step 1 is to try and find a matching edge for the given node. // If a matching edge exists, we are done adding edges, so we break out of this big loop. if (active.isExplicit()) { edge = active.getOriginNode().findEdge(symbolAt(endIndex)); if (edge != null) { break; } } else { // implicit node, a little more complicated edge = active.getOriginNode().findEdge(symbolAt(active.getBeginIndex())); int span = active.getSpan(); if (Objects.equals(symbolAt(edge.getBeginIndex() + span + 1), symbolAt(endIndex))) { break; } parentNode = edge.splitEdge(active); } // We didn't find a matching edge, so we create a new one, add it to the tree at the parent node position, // and insert it into the hash table. When we create a new node, it also means we need to create // a suffix link to the new node from the last node we visited. Edge newEdge = new Edge(endIndex, text.length() - 1, parentNode); newEdge.insert(); updateSuffixNode(lastParentNode, parentNode); lastParentNode = parentNode; // This final step is where we move to the next smaller suffix if (active.getOriginNode() == root) { active.incBeginIndex(); } else { active.changeOriginNode(); } active.canonize(); } updateSuffixNode(lastParentNode, parentNode); active.incEndIndex(); // Now the endpoint is the next active point active.canonize(); } private void updateSuffixNode(Node node, Node suffixNode) { if ((node != null) && (!node.equals(root))) { node.setSuffixNode(suffixNode); } } public Object symbolAt(int index) { return text.symbolAt(index); } public Node getRootNode() { return root; } }
4,613
35.619048
132
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/SuffixTreeCloneDetectionAlgorithm.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.duplications.detector.suffixtree; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.sonar.duplications.block.Block; import org.sonar.duplications.block.ByteArray; import org.sonar.duplications.index.CloneGroup; import org.sonar.duplications.index.CloneIndex; public final class SuffixTreeCloneDetectionAlgorithm { private static final Comparator<Block> BLOCK_COMPARATOR = (o1, o2) -> o1.getIndexInFile() - o2.getIndexInFile(); private SuffixTreeCloneDetectionAlgorithm() { // only statics } public static List<CloneGroup> detect(CloneIndex cloneIndex, Collection<Block> fileBlocks) { if (fileBlocks.isEmpty()) { return Collections.emptyList(); } TextSet text = createTextSet(cloneIndex, fileBlocks); if (text == null) { return Collections.emptyList(); } DuplicationsCollector reporter = new DuplicationsCollector(text); Search.perform(text, reporter); return reporter.getResult(); } private static TextSet createTextSet(CloneIndex index, Collection<Block> fileBlocks) { Set<ByteArray> hashes = new HashSet<>(); for (Block fileBlock : fileBlocks) { hashes.add(fileBlock.getBlockHash()); } String originResourceId = fileBlocks.iterator().next().getResourceId(); Map<String, List<Block>> fromIndex = retrieveFromIndex(index, originResourceId, hashes); if (fromIndex.isEmpty() && hashes.size() == fileBlocks.size()) { // optimization for the case when there is no duplications return null; } return createTextSet(fileBlocks, fromIndex); } private static TextSet createTextSet(Collection<Block> fileBlocks, Map<String, List<Block>> fromIndex) { TextSet.Builder textSetBuilder = TextSet.builder(); // TODO Godin: maybe we can reduce size of tree and so memory consumption by removing non-repeatable blocks List<Block> sortedFileBlocks = new ArrayList<>(fileBlocks); Collections.sort(sortedFileBlocks, BLOCK_COMPARATOR); textSetBuilder.add(sortedFileBlocks); for (List<Block> list : fromIndex.values()) { Collections.sort(list, BLOCK_COMPARATOR); int i = 0; while (i < list.size()) { int j = i + 1; while ((j < list.size()) && (list.get(j).getIndexInFile() == list.get(j - 1).getIndexInFile() + 1)) { j++; } textSetBuilder.add(list.subList(i, j)); i = j; } } return textSetBuilder.build(); } private static Map<String, List<Block>> retrieveFromIndex(CloneIndex index, String originResourceId, Set<ByteArray> hashes) { Map<String, List<Block>> collection = new HashMap<>(); for (ByteArray hash : hashes) { Collection<Block> blocks = index.getBySequenceHash(hash); for (Block blockFromIndex : blocks) { // Godin: skip blocks for this file if they come from index String resourceId = blockFromIndex.getResourceId(); if (!originResourceId.equals(resourceId)) { List<Block> list = collection.get(resourceId); if (list == null) { list = new ArrayList<>(); collection.put(resourceId, list); } list.add(blockFromIndex); } } } return collection; } }
4,264
34.840336
127
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/Text.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.duplications.detector.suffixtree; import java.util.List; /** * Represents text. */ public interface Text { /** * @return length of the sequence of symbols represented by this object */ int length(); /** * @return symbol at the specified index */ Object symbolAt(int index); List<Object> sequence(int fromIndex, int toIndex); }
1,218
28.02381
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/TextSet.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.duplications.detector.suffixtree; import java.util.ArrayList; import java.util.List; import org.sonar.duplications.block.Block; /** * Simplifies construction of <a href="http://en.wikipedia.org/wiki/Generalised_suffix_tree">generalised suffix-tree</a>. */ public final class TextSet extends AbstractText { private final int lengthOfOrigin; private TextSet(List<Object> symbols, int lengthOfOrigin) { super(symbols); this.lengthOfOrigin = lengthOfOrigin; } public static final class Builder { private final List<Object> symbols = new ArrayList<>(); private Integer lengthOfOrigin; private int count; private Builder() { } public void add(List<Block> list) { symbols.addAll(list); symbols.add(new Terminator(count)); count++; if (lengthOfOrigin == null) { lengthOfOrigin = symbols.size(); } } public TextSet build() { return new TextSet(symbols, lengthOfOrigin); } } public static Builder builder() { return new Builder(); } public boolean isInsideOrigin(int pos) { return pos < lengthOfOrigin; } @Override public Object symbolAt(int index) { Object obj = super.symbolAt(index); if (obj instanceof Block) { return ((Block) obj).getBlockHash(); } return obj; } public Block getBlock(int index) { return (Block) super.symbolAt(index); } public static class Terminator { private final int stringNumber; public Terminator(int i) { this.stringNumber = i; } @Override public boolean equals(Object obj) { return obj != null && getClass() == obj.getClass() && ((Terminator) obj).stringNumber == stringNumber; } @Override public int hashCode() { return stringNumber; } @Override public String toString() { return "$" + stringNumber; } } }
2,736
24.820755
121
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/detector/suffixtree/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.duplications.detector.suffixtree; import javax.annotation.ParametersAreNonnullByDefault;
983
38.36
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/index/AbstractCloneIndex.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.duplications.index; public abstract class AbstractCloneIndex implements CloneIndex { }
950
37.04
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/index/CloneGroup.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.duplications.index; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * Groups a set of related {@link ClonePart}s. */ public class CloneGroup { private final ClonePart originPart; private final int cloneLength; private final List<ClonePart> parts; private int length; /** * Cache for hash code. */ private int hash; /** * @since 2.14 */ public static Builder builder() { return new Builder(); } /** * @since 2.14 */ public static final class Builder { private ClonePart origin; private int length; private int lengthInUnits; private List<ClonePart> parts = new ArrayList<>(); public Builder setLength(int length) { this.length = length; return this; } public Builder setOrigin(ClonePart origin) { this.origin = origin; return this; } public Builder setParts(List<ClonePart> parts) { this.parts = new ArrayList<>(parts); return this; } public Builder addPart(ClonePart part) { Objects.requireNonNull(part); this.parts.add(part); return this; } public Builder setLengthInUnits(int length) { this.lengthInUnits = length; return this; } public CloneGroup build() { return new CloneGroup(this); } } private CloneGroup(Builder builder) { this.cloneLength = builder.length; this.originPart = builder.origin; this.parts = builder.parts; this.length = builder.lengthInUnits; } public ClonePart getOriginPart() { return originPart; } /** * Length of duplication measured in original units, e.g. for token-based detection - in tokens. * * @since 2.14 */ public int getLengthInUnits() { return length; } /** * @return clone length in {@link org.sonar.duplications.block.Block}s */ public int getCloneUnitLength() { return cloneLength; } public List<ClonePart> getCloneParts() { return parts; } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (ClonePart part : parts) { builder.append(part).append(" - "); } builder.append(cloneLength); return builder.toString(); } /** * Two groups are equal, if they have same length, same origins and contain same parts in same order. */ @Override public boolean equals(Object object) { if (object == null || getClass() != object.getClass()) { return false; } CloneGroup another = (CloneGroup) object; if (another.cloneLength != cloneLength || parts.size() != another.parts.size()) { return false; } if (!originPart.equals(another.originPart)) { return false; } boolean result = true; for (int i = 0; i < parts.size(); i++) { result &= another.parts.get(i).equals(parts.get(i)); } return result; } @Override public int hashCode() { int h = hash; if (h == 0 && cloneLength != 0) { for (ClonePart part : parts) { h = 31 * h + part.hashCode(); } h = 31 * h + originPart.hashCode(); h = 31 * h + cloneLength; hash = h; } return h; } }
4,038
23.331325
103
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/index/CloneIndex.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.duplications.index; import java.util.Collection; import java.util.Iterator; import org.sonar.duplications.block.Block; import org.sonar.duplications.block.ByteArray; import org.sonar.duplications.index.PackedMemoryCloneIndex.ResourceBlocks; public interface CloneIndex { /** * Performs search of blocks for specified resource. * * @return collection of blocks from index for specified resource and empty collection if nothing found */ Collection<Block> getByResourceId(String resourceId); /** * Performs search of blocks for specified hash value. * * @return collection of blocks from index with specified hash and empty collection if nothing found */ Collection<Block> getBySequenceHash(ByteArray hash); /** * Adds specified block into index. */ void insert(Block block); /** * Iterators through the resources, providing the list of blocks for each resource. */ Iterator<ResourceBlocks> iterator(); int noResources(); }
1,849
30.896552
105
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/index/ClonePart.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.duplications.index; public class ClonePart { private final String resourceId; private final int startUnit; private final int startLine; private final int endLine; /** * Cache for hash code. */ private int hash; public ClonePart(String resourceId, int startUnit, int startLine, int endLine) { this.resourceId = resourceId; this.startUnit = startUnit; this.startLine = startLine; this.endLine = endLine; } public String getResourceId() { return resourceId; } public int getUnitStart() { return startUnit; } public int getStartLine() { return startLine; } public int getEndLine() { return endLine; } public int getLines() { return endLine - startLine + 1; } @Override public boolean equals(Object obj) { if (obj != null && getClass() == obj.getClass()) { ClonePart another = (ClonePart) obj; return another.resourceId.equals(resourceId) && another.startLine == startLine && another.endLine == endLine && another.startUnit == startUnit; } return false; } @Override public int hashCode() { int h = hash; if (h == 0) { h = resourceId.hashCode(); h = 31 * h + startLine; h = 31 * h + endLine; h = 31 * h + startUnit; hash = h; } return h; } @Override public String toString() { return "'" + resourceId + "':[" + startUnit + "|" + startLine + "-" + endLine + "]"; } }
2,328
24.315217
88
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/index/DataUtils.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.duplications.index; public final class DataUtils { public interface Sortable { /** * @return the number of elements. */ int size(); /** * Swaps elements in positions i and j. */ void swap(int i, int j); /** * @return true if element in position i less than in position j. */ boolean isLess(int i, int j); } /** * Value for search must be stored in position {@link Sortable#size() size}. */ public static int binarySearch(Sortable data) { int value = data.size(); int lower = 0; int upper = data.size(); while (lower < upper) { int mid = (lower + upper) >> 1; if (data.isLess(mid, value)) { lower = mid + 1; } else { upper = mid; } } return lower; } public static void sort(Sortable data) { quickSort(data, 0, data.size() - 1); } private static void bubbleSort(Sortable data, int left, int right) { for (int i = right; i > left; i--) { for (int j = left; j < i; j++) { if (data.isLess(j + 1, j)) { data.swap(j, j + 1); } } } } private static int partition(Sortable data, int i, int j) { // can be selected randomly int pivot = i + (j - i) / 2; while (i <= j) { while (data.isLess(i, pivot)) { i++; } while (data.isLess(pivot, j)) { j--; } if (i <= j) { data.swap(i, j); if (i == pivot) { pivot = j; } else if (j == pivot) { pivot = i; } i++; j--; } } return i; } private static void quickSort(Sortable data, int low, int high) { if (high - low < 5) { bubbleSort(data, low, high); return; } int i = partition(data, low, high); if (low < i - 1) { quickSort(data, low, i - 1); } if (i < high) { quickSort(data, i, high); } } private DataUtils() { } }
2,817
23.08547
78
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/index/MemoryCloneIndex.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.duplications.index; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.sonar.duplications.block.Block; import org.sonar.duplications.block.ByteArray; import org.sonar.duplications.index.PackedMemoryCloneIndex.ResourceBlocks; public class MemoryCloneIndex implements CloneIndex { private Map<String, List<Block>> byResource = new LinkedHashMap<>(); private Map<ByteArray, List<Block>> byHash = new LinkedHashMap<>(); @Override public Collection<Block> getByResourceId(String resourceId) { return byResource.computeIfAbsent(resourceId, k -> new ArrayList<>()); } @Override public Collection<Block> getBySequenceHash(ByteArray sequenceHash) { return byHash.computeIfAbsent(sequenceHash, k -> new ArrayList<>()); } @Override public void insert(Block block) { getByResourceId(block.getResourceId()).add(block); getBySequenceHash(block.getBlockHash()).add(block); } @Override public Iterator<ResourceBlocks> iterator() { throw new UnsupportedOperationException(); } @Override public int noResources() { return byResource.keySet().size(); } }
2,085
31.59375
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/index/PackedMemoryCloneIndex.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.duplications.index; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import org.sonar.duplications.block.Block; import org.sonar.duplications.block.ByteArray; import org.sonar.duplications.utils.FastStringComparator; import javax.annotation.Nullable; /** * Provides an index optimized by memory. * <p> * Each object in Java has an overhead - see * <a href="http://devblog.streamy.com/2009/07/24/determine-size-of-java-object-class/">"HOWTO: Determine the size of a Java Object or Class"</a>. * So to optimize memory consumption, we use flat arrays, however this increases time of queries. * During usual detection of duplicates most time consuming method is a {@link #getByResourceId(String)}: * around 50% of time spent in this class and number of invocations of this method is 1% of total invocations, * however total time spent in this class less than 1 second for small projects and around 2 seconds for projects like JDK. * </p> * <p> * Note that this implementation currently does not support deletion, however it's possible to implement. * </p> */ public class PackedMemoryCloneIndex extends AbstractCloneIndex { private static final int DEFAULT_INITIAL_CAPACITY = 1024; private static final int BLOCK_INTS = 5; private final int hashInts; private final int blockInts; /** * Indicates that index requires sorting to perform queries. */ private boolean sorted; /** * Current number of blocks in index. */ private int size; private String[] resourceIds; private int[] blockData; private int[] resourceIdsIndex; private final Block.Builder blockBuilder = Block.builder(); public PackedMemoryCloneIndex() { this(8, DEFAULT_INITIAL_CAPACITY); } /** * @param hashBytes size of hash in bytes * @param initialCapacity the initial capacity */ public PackedMemoryCloneIndex(int hashBytes, int initialCapacity) { this.sorted = false; this.hashInts = hashBytes / 4; this.blockInts = hashInts + BLOCK_INTS; this.size = 0; this.resourceIds = new String[initialCapacity]; this.blockData = new int[initialCapacity * blockInts]; this.resourceIdsIndex = new int[initialCapacity]; } /** * {@inheritDoc} * <p> * <strong>Note that this implementation does not guarantee that blocks would be sorted by index.</strong> * </p> */ @Override public Collection<Block> getByResourceId(String resourceId) { ensureSorted(); // prepare resourceId for binary search resourceIds[size] = resourceId; resourceIdsIndex[size] = size; int index = DataUtils.binarySearch(byResourceId); List<Block> result = new ArrayList<>(); int realIndex = resourceIdsIndex[index]; while (index < size && FastStringComparator.INSTANCE.compare(resourceIds[realIndex], resourceId) == 0) { result.add(getBlock(realIndex, resourceId)); index++; realIndex = resourceIdsIndex[index]; } return result; } private Block createBlock(int index, String resourceId, @Nullable ByteArray byteHash) { int offset = index * blockInts; ByteArray blockHash; if (byteHash == null) { int[] hash = new int[hashInts]; for (int j = 0; j < hashInts; j++) { hash[j] = blockData[offset++]; } blockHash = new ByteArray(hash); } else { blockHash = byteHash; offset += hashInts; } int indexInFile = blockData[offset++]; int firstLineNumber = blockData[offset++]; int lastLineNumber = blockData[offset++]; int startUnit = blockData[offset++]; int endUnit = blockData[offset]; return blockBuilder .setResourceId(resourceId) .setBlockHash(blockHash) .setIndexInFile(indexInFile) .setLines(firstLineNumber, lastLineNumber) .setUnit(startUnit, endUnit) .build(); } private Block getBlock(int index, String resourceId) { return createBlock(index, resourceId, null); } private class ResourceIterator implements Iterator<ResourceBlocks> { private int index = 0; @Override public boolean hasNext() { return index < size; } @Override public ResourceBlocks next() { if (!hasNext()) { throw new NoSuchElementException(); } String resourceId = resourceIds[resourceIdsIndex[index]]; List<Block> blocks = new ArrayList<>(); // while we are at the same resource, keep going do { blocks.add(getBlock(resourceIdsIndex[index], resourceId)); index++; } while (hasNext() && FastStringComparator.INSTANCE.compare(resourceIds[resourceIdsIndex[index]], resourceId) == 0); return new ResourceBlocks(resourceId, blocks); } @Override public void remove() { throw new UnsupportedOperationException(); } } public static class ResourceBlocks { private Collection<Block> blocks; private String resourceId; public ResourceBlocks(String resourceId, Collection<Block> blocks) { this.resourceId = resourceId; this.blocks = blocks; } public Collection<Block> blocks() { return blocks; } public String resourceId() { return resourceId; } } /** * {@inheritDoc} */ @Override public Iterator<ResourceBlocks> iterator() { ensureSorted(); return new ResourceIterator(); } /** * {@inheritDoc} */ @Override public Collection<Block> getBySequenceHash(ByteArray sequenceHash) { ensureSorted(); // prepare hash for binary search int[] hash = sequenceHash.toIntArray(); if (hash.length != hashInts) { throw new IllegalArgumentException("Expected " + hashInts + " ints in hash, but got " + hash.length); } int offset = size * blockInts; for (int i = 0; i < hashInts; i++) { blockData[offset++] = hash[i]; } int index = DataUtils.binarySearch(byBlockHash); List<Block> result = new ArrayList<>(); while (index < size && !isLessByHash(size, index)) { // extract block (note that there is no need to extract hash) String resourceId = resourceIds[index]; result.add(createBlock(index, resourceId, sequenceHash)); index++; } return result; } /** * {@inheritDoc} * <p> * <strong>Note that this implementation allows insertion of two blocks with same index for one resource.</strong> * </p> */ @Override public void insert(Block block) { sorted = false; ensureCapacity(); resourceIds[size] = block.getResourceId(); int[] hash = block.getBlockHash().toIntArray(); if (hash.length != hashInts) { throw new IllegalArgumentException("Expected " + hashInts + " ints in hash, but got " + hash.length); } int offset = size * blockInts; for (int i = 0; i < hashInts; i++) { blockData[offset++] = hash[i]; } blockData[offset++] = block.getIndexInFile(); blockData[offset++] = block.getStartLine(); blockData[offset++] = block.getEndLine(); blockData[offset++] = block.getStartUnit(); blockData[offset] = block.getEndUnit(); size++; } /** * Increases the capacity, if necessary. */ private void ensureCapacity() { if (size < resourceIds.length) { return; } int newCapacity = (resourceIds.length * 3) / 2 + 1; // Increase size of resourceIds String[] oldResourceIds = resourceIds; resourceIds = new String[newCapacity]; System.arraycopy(oldResourceIds, 0, resourceIds, 0, oldResourceIds.length); // Increase size of blockData int[] oldBlockData = blockData; blockData = new int[newCapacity * blockInts]; System.arraycopy(oldBlockData, 0, blockData, 0, oldBlockData.length); // Increase size of byResourceIndices (no need to copy old, because would be restored in method ensureSorted) resourceIdsIndex = new int[newCapacity]; sorted = false; } /** * Performs sorting, if necessary. */ private void ensureSorted() { if (sorted) { return; } ensureCapacity(); DataUtils.sort(byBlockHash); for (int i = 0; i < size; i++) { resourceIdsIndex[i] = i; } DataUtils.sort(byResourceId); sorted = true; } private boolean isLessByHash(int i, int j) { int i2 = i * blockInts; int j2 = j * blockInts; for (int k = 0; k < hashInts; k++, i2++, j2++) { if (blockData[i2] < blockData[j2]) { return true; } if (blockData[i2] > blockData[j2]) { return false; } } return false; } private final DataUtils.Sortable byBlockHash = new DataUtils.Sortable() { @Override public void swap(int i, int j) { String tmp = resourceIds[i]; resourceIds[i] = resourceIds[j]; resourceIds[j] = tmp; i *= blockInts; j *= blockInts; for (int k = 0; k < blockInts; k++, i++, j++) { int x = blockData[i]; blockData[i] = blockData[j]; blockData[j] = x; } } @Override public boolean isLess(int i, int j) { return isLessByHash(i, j); } @Override public int size() { return size; } }; private final DataUtils.Sortable byResourceId = new DataUtils.Sortable() { @Override public void swap(int i, int j) { int tmp = resourceIdsIndex[i]; resourceIdsIndex[i] = resourceIdsIndex[j]; resourceIdsIndex[j] = tmp; } @Override public boolean isLess(int i, int j) { String s1 = resourceIds[resourceIdsIndex[i]]; String s2 = resourceIds[resourceIdsIndex[j]]; return FastStringComparator.INSTANCE.compare(s1, s2) < 0; } @Override public int size() { return size; } }; @Override /** * Computation is O(N) */ public int noResources() { ensureSorted(); int count = 0; String lastResource = null; for (int i = 0; i < size; i++) { String resource = resourceIds[resourceIdsIndex[i]]; if (resource != null && !resource.equals(lastResource)) { count++; lastResource = resource; } } return count; } }
10,995
26.979644
146
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/index/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.duplications.index; import javax.annotation.ParametersAreNonnullByDefault;
969
37.8
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/internal/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. */ /** * Internals. */ package org.sonar.duplications.internal;
906
36.791667
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/internal/pmd/PmdBlockChunker.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.duplications.internal.pmd; import java.util.ArrayList; import java.util.List; import javax.annotation.concurrent.Immutable; import org.sonar.api.batch.sensor.cpd.internal.TokensLine; import org.sonar.duplications.block.Block; import org.sonar.duplications.block.ByteArray; /** * Differences with {@link org.sonar.duplications.block.BlockChunker}: * works with {@link TokensLine}, * sets {@link Block#getStartUnit() startUnit} and {@link Block#getEndUnit() endUnit} - indexes of first and last token for this block. */ @Immutable public class PmdBlockChunker { private static final long PRIME_BASE = 31; private final int blockSize; private final long power; public PmdBlockChunker(int blockSize) { this.blockSize = blockSize; long pow = 1; for (int i = 0; i < blockSize - 1; i++) { pow = pow * PRIME_BASE; } this.power = pow; } /** * @return ArrayList as we need a serializable object */ public List<Block> chunk(String resourceId, List<TokensLine> fragments) { List<TokensLine> filtered = new ArrayList<>(); int i = 0; while (i < fragments.size()) { TokensLine first = fragments.get(i); int j = i + 1; while (j < fragments.size() && fragments.get(j).getValue().equals(first.getValue())) { j++; } filtered.add(fragments.get(i)); if (i < j - 1) { filtered.add(fragments.get(j - 1)); } i = j; } fragments = filtered; if (fragments.size() < blockSize) { return new ArrayList<>(); } TokensLine[] fragmentsArr = fragments.toArray(new TokensLine[fragments.size()]); List<Block> blocks = new ArrayList<>(fragmentsArr.length - blockSize + 1); long hash = 0; int first = 0; int last = 0; for (; last < blockSize - 1; last++) { hash = hash * PRIME_BASE + fragmentsArr[last].getHashCode(); } Block.Builder blockBuilder = Block.builder().setResourceId(resourceId); for (; last < fragmentsArr.length; last++, first++) { TokensLine firstFragment = fragmentsArr[first]; TokensLine lastFragment = fragmentsArr[last]; // add last statement to hash hash = hash * PRIME_BASE + lastFragment.getHashCode(); // create block Block block = blockBuilder .setBlockHash(new ByteArray(hash)) .setIndexInFile(first) .setLines(firstFragment.getStartLine(), lastFragment.getEndLine()) .setUnit(firstFragment.getStartUnit(), lastFragment.getEndUnit()) .build(); blocks.add(block); // remove first statement from hash hash -= power * firstFragment.getHashCode(); } return blocks; } }
3,515
32.807692
135
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/internal/pmd/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 a basic framework to create list of statements from list of tokens. * * The entry point of this framework is the {@link org.sonar.duplications.statement.StatementChunker} class. */ @ParametersAreNonnullByDefault package org.sonar.duplications.internal.pmd; import javax.annotation.ParametersAreNonnullByDefault;
1,176
38.233333
108
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/java/BridgeWithExceptionTokenMatcher.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.duplications.java; import java.util.List; import org.sonar.duplications.statement.matcher.TokenMatcher; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; public class BridgeWithExceptionTokenMatcher extends TokenMatcher { private final String lToken; private final String rToken; private final String except; public BridgeWithExceptionTokenMatcher(String lToken, String rToken, String except) { if (lToken == null || rToken == null || except == null) { throw new IllegalArgumentException(); } this.lToken = lToken; this.rToken = rToken; this.except = except; } @Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { if (!tokenQueue.isNextTokenValue(lToken)) { return false; } int stack = 0; while (tokenQueue.peek() != null) { Token token = tokenQueue.poll(); matchedTokenList.add(token); if (lToken.equals(token.getValue())) { stack++; } else if (rToken.equals(token.getValue())) { stack--; } else if (except.equals(token.getValue())) { return false; } if (stack == 0) { return true; } } return false; } }
2,104
30.41791
87
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/java/JavaStatementBuilder.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.duplications.java; import static org.sonar.duplications.statement.TokenMatcherFactory.*; import org.sonar.duplications.statement.StatementChunker; public final class JavaStatementBuilder { private JavaStatementBuilder() { } public static StatementChunker build() { return StatementChunker.builder() .ignore(from("import"), to(";")) .ignore(from("package"), to(";")) .statement(new BridgeWithExceptionTokenMatcher("{", "}", ";")) .ignore(token("}")) .ignore(token("{")) .ignore(token(";")) .statement(from("@"), anyToken(), opt(bridge("(", ")"))) .statement(from("do")) .statement(from("if"), bridge("(", ")")) .statement(from("else"), token("if"), bridge("(", ")")) .statement(from("else")) .statement(from("for"), bridge("(", ")")) .statement(from("while"), bridge("(", ")")) .statement(from("try"), bridge("(", ")")) .statement(from("case"), to(";", "{", "}"), forgetLastToken()) .statement(from("default"), to(";", "{", "}"), forgetLastToken()) .statement(to(";", "{", "}"), forgetLastToken()) .build(); } }
2,034
36.685185
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/java/JavaTokenProducer.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.duplications.java; import org.sonar.duplications.token.TokenChunker; /** * See <a href="http://java.sun.com/docs/books/jls/third_edition/html/lexical.html">The Java Language Specification, Third Edition: Lexical Structure</a> * and <a href="http://www.jcp.org/en/jsr/detail?id=334">JSR334 (Java 7 - binary integral literals and underscores in numeric literals)</a>. * * <p> * We decided to use dollar sign as a prefix for normalization, even if it can be a part of an identifier, * because according to Java Language Specification it supposed to be used only in mechanically generated source code. * Thus probability to find it within a normal code should be low. * </p> */ public final class JavaTokenProducer { private static final String NORMALIZED_CHARACTER_LITERAL = "$CHARS"; private static final String NORMALIZED_NUMERIC_LITERAL = "$NUMBER"; private static final String EXP = "([Ee][+-]?+[0-9_]++)"; private static final String BINARY_EXP = "([Pp][+-]?+[0-9_]++)"; private static final String FLOAT_SUFFIX = "[fFdD]"; private static final String INT_SUFFIX = "[lL]"; private JavaTokenProducer() { } public static TokenChunker build() { return TokenChunker.builder() // White Space .ignore("\\s") // Comments .ignore("//[^\\n\\r]*+") .ignore("/\\*[\\s\\S]*?\\*/") // String Literals .token("\"([^\"\\\\]*+(\\\\[\\s\\S])?+)*+\"", NORMALIZED_CHARACTER_LITERAL) // Character Literals .token("'([^'\\n\\\\]*+(\\\\.)?+)*+'", NORMALIZED_CHARACTER_LITERAL) // Identifiers, Keywords, Boolean Literals, The Null Literal .token("\\p{javaJavaIdentifierStart}++\\p{javaJavaIdentifierPart}*+") // Floating-Point Literals // Decimal .token("[0-9_]++\\.([0-9_]++)?+" + EXP + "?+" + FLOAT_SUFFIX + "?+", NORMALIZED_NUMERIC_LITERAL) // Decimal .token("\\.[0-9_]++" + EXP + "?+" + FLOAT_SUFFIX + "?+", NORMALIZED_NUMERIC_LITERAL) // Decimal .token("[0-9_]++" + EXP + FLOAT_SUFFIX + "?+", NORMALIZED_NUMERIC_LITERAL) // Hexadecimal .token("0[xX][0-9a-fA-F_]++\\.[0-9a-fA-F_]*+" + BINARY_EXP + "?+" + FLOAT_SUFFIX + "?+", NORMALIZED_NUMERIC_LITERAL) // Hexadecimal .token("0[xX][0-9a-fA-F_]++" + BINARY_EXP + FLOAT_SUFFIX + "?+", NORMALIZED_NUMERIC_LITERAL) // Integer Literals // Hexadecimal .token("0[xX][0-9a-fA-F_]++" + INT_SUFFIX + "?+", NORMALIZED_NUMERIC_LITERAL) // Binary (Java 7) .token("0[bB][01_]++" + INT_SUFFIX + "?+", NORMALIZED_NUMERIC_LITERAL) // Decimal and Octal .token("[0-9_]++" + INT_SUFFIX + "?+", NORMALIZED_NUMERIC_LITERAL) // Any other character .token(".") .build(); } }
3,643
42.380952
153
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/java/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 a basic framework to create list of statements from list of tokens. * * The entry point of this framework is the {@link org.sonar.duplications.statement.StatementChunker} class. */ @ParametersAreNonnullByDefault package org.sonar.duplications.java; import javax.annotation.ParametersAreNonnullByDefault;
1,168
37.966667
108
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/Statement.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.duplications.statement; import java.util.List; import javax.annotation.Nullable; import org.sonar.duplications.token.Token; public class Statement { private final int startLine; private final int endLine; private final String value; /** * Cache for hash code. */ private int hash; public Statement(int startLine, int endLine, String value) { this.startLine = startLine; this.endLine = endLine; this.value = value; } public Statement(@Nullable List<Token> tokens) { if (tokens == null || tokens.isEmpty()) { throw new IllegalArgumentException("A statement can't be initialized with an empty list of tokens"); } StringBuilder sb = new StringBuilder(); for (Token token : tokens) { sb.append(token.getValue()); } this.value = sb.toString(); this.startLine = tokens.get(0).getLine(); this.endLine = tokens.get(tokens.size() - 1).getLine(); } public int getStartLine() { return startLine; } public int getEndLine() { return endLine; } public String getValue() { return value; } @Override public int hashCode() { int h = hash; if (h == 0) { h = value.hashCode(); h = 31 * h + startLine; h = 31 * h + endLine; hash = h; } return h; } @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } Statement other = (Statement) obj; return startLine == other.startLine && endLine == other.endLine && value.equals(other.value); } @Override public String toString() { return "[" + getStartLine() + "-" + getEndLine() + "] [" + getValue() + "]"; } }
2,563
25.43299
106
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/StatementChannel.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.duplications.statement; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import org.sonar.duplications.statement.matcher.TokenMatcher; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; public final class StatementChannel { private final TokenMatcher[] tokenMatchers; private final boolean blackHole; private StatementChannel(boolean blackHole, @Nullable TokenMatcher... tokenMatchers) { if (tokenMatchers == null || tokenMatchers.length == 0) { throw new IllegalArgumentException(); } this.blackHole = blackHole; this.tokenMatchers = tokenMatchers; } public static StatementChannel create(TokenMatcher... tokenMatchers) { return new StatementChannel(false, tokenMatchers); } public static StatementChannel createBlackHole(TokenMatcher... tokenMatchers) { return new StatementChannel(true, tokenMatchers); } public boolean consume(TokenQueue tokenQueue, List<Statement> output) { List<Token> matchedTokenList = new ArrayList<>(); for (TokenMatcher tokenMatcher : tokenMatchers) { if (!tokenMatcher.matchToken(tokenQueue, matchedTokenList)) { tokenQueue.pushForward(matchedTokenList); return false; } } // all matchers were successful, so now build the statement // matchedTokenList.size() check is for case with ForgiveLastTokenMatcher if (!blackHole && !matchedTokenList.isEmpty()) { output.add(new Statement(matchedTokenList)); } return true; } }
2,411
34.470588
88
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/StatementChannelDisptacher.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.duplications.statement; import java.util.List; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; public class StatementChannelDisptacher { private final StatementChannel[] channels; public StatementChannelDisptacher(List<StatementChannel> channels) { this.channels = channels.toArray(new StatementChannel[channels.size()]); } public boolean consume(TokenQueue tokenQueue, List<Statement> statements) { Token nextToken = tokenQueue.peek(); while (nextToken != null) { boolean channelConsumed = false; for (StatementChannel channel : channels) { if (channel.consume(tokenQueue, statements)) { channelConsumed = true; break; } } if (!channelConsumed) { throw new IllegalStateException("None of the statement channel has been able to consume token: " + nextToken); } nextToken = tokenQueue.peek(); } return true; } }
1,832
32.944444
118
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/StatementChunker.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.duplications.statement; import java.util.ArrayList; import java.util.List; import javax.annotation.Nullable; import org.sonar.duplications.DuplicationsException; import org.sonar.duplications.statement.matcher.TokenMatcher; import org.sonar.duplications.token.TokenQueue; public final class StatementChunker { private final StatementChannelDisptacher channelDispatcher; private StatementChunker(Builder builder) { this.channelDispatcher = builder.getChannelDispatcher(); } public static Builder builder() { return new Builder(); } public List<Statement> chunk(@Nullable TokenQueue tokenQueue) { if (tokenQueue == null) { throw new IllegalArgumentException(); } List<Statement> statements = new ArrayList<>(); try { channelDispatcher.consume(tokenQueue, statements); return statements; } catch (Exception e) { throw new DuplicationsException("Unable to build statement from token : " + tokenQueue.peek(), e); } } /** * Note that order is important, e.g. * <code>statement(token(A)).ignore(token(A))</code> for the input sequence "A" will produce statement, whereas * <code>ignore(token(A)).statement(token(A))</code> will not. */ public static final class Builder { private List<StatementChannel> channels = new ArrayList<>(); private Builder() { } public StatementChunker build() { return new StatementChunker(this); } /** * Defines that sequence of tokens must be ignored, if it matches specified list of matchers. * * @see TokenMatcherFactory */ public Builder ignore(TokenMatcher... matchers) { channels.add(StatementChannel.createBlackHole(matchers)); return this; } /** * Defines that sequence of tokens, which is matched specified list of matchers, is a statement. * * @see TokenMatcherFactory */ public Builder statement(TokenMatcher... matchers) { channels.add(StatementChannel.create(matchers)); return this; } private StatementChannelDisptacher getChannelDispatcher() { return new StatementChannelDisptacher(channels); } } }
3,028
30.552083
113
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/TokenMatcherFactory.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.duplications.statement; import org.sonar.duplications.statement.matcher.AnyTokenMatcher; import org.sonar.duplications.statement.matcher.BridgeTokenMatcher; import org.sonar.duplications.statement.matcher.ExactTokenMatcher; import org.sonar.duplications.statement.matcher.ForgetLastTokenMatcher; import org.sonar.duplications.statement.matcher.OptTokenMatcher; import org.sonar.duplications.statement.matcher.TokenMatcher; import org.sonar.duplications.statement.matcher.UptoTokenMatcher; public final class TokenMatcherFactory { private TokenMatcherFactory() { } public static TokenMatcher from(String token) { return new ExactTokenMatcher(token); } public static TokenMatcher to(String... tokens) { return new UptoTokenMatcher(tokens); } public static TokenMatcher bridge(String lToken, String rToken) { return new BridgeTokenMatcher(lToken, rToken); } public static TokenMatcher anyToken() { // TODO Godin: we can return singleton instance return new AnyTokenMatcher(); } public static TokenMatcher opt(TokenMatcher optMatcher) { return new OptTokenMatcher(optMatcher); } public static TokenMatcher forgetLastToken() { // TODO Godin: we can return singleton instance return new ForgetLastTokenMatcher(); } public static TokenMatcher token(String token) { return new ExactTokenMatcher(token); } }
2,239
32.939394
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/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 a basic framework to create list of statements from list of tokens. * * The entry point of this framework is the {@link org.sonar.duplications.statement.StatementChunker} class. */ @ParametersAreNonnullByDefault package org.sonar.duplications.statement; import javax.annotation.ParametersAreNonnullByDefault;
1,173
38.133333
108
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/matcher/AnyTokenMatcher.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.duplications.statement.matcher; import java.util.List; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; /** * Consumes any token, but only one. */ public class AnyTokenMatcher extends TokenMatcher { /** * @return always true */ @Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { matchedTokenList.add(tokenQueue.poll()); return true; } }
1,309
30.190476
82
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/matcher/BridgeTokenMatcher.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.duplications.statement.matcher; import java.util.List; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; /** * Consumes everything between pair of tokens. */ public class BridgeTokenMatcher extends TokenMatcher { private final String lToken; private final String rToken; public BridgeTokenMatcher(String lToken, String rToken) { if (lToken == null || rToken == null) { throw new IllegalArgumentException(); } this.lToken = lToken; this.rToken = rToken; } @Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { if (!tokenQueue.isNextTokenValue(lToken)) { return false; } int stack = 0; while (tokenQueue.peek() != null) { Token token = tokenQueue.poll(); if (lToken.equals(token.getValue())) { stack++; } else if (rToken.equals(token.getValue())) { stack--; } matchedTokenList.add(token); if (stack == 0) { return true; } } return false; } }
1,920
28.553846
82
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/matcher/ExactTokenMatcher.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.duplications.statement.matcher; import java.util.List; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; /** * Consumes only one specified token. */ public class ExactTokenMatcher extends TokenMatcher { private final String tokenToMatch; public ExactTokenMatcher(String tokenToMatch) { if (tokenToMatch == null) { throw new IllegalArgumentException(); } this.tokenToMatch = tokenToMatch; } @Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { if (tokenQueue.isNextTokenValue(tokenToMatch)) { matchedTokenList.add(tokenQueue.poll()); return true; } return false; } }
1,569
29.784314
82
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/matcher/ForgetLastTokenMatcher.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.duplications.statement.matcher; import java.util.Collections; import java.util.List; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; /** * Last token would be returned to the queue. */ public class ForgetLastTokenMatcher extends TokenMatcher { /** * @return always true */ @Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { int last = matchedTokenList.size() - 1; tokenQueue.pushForward(Collections.singletonList(matchedTokenList.get(last))); matchedTokenList.remove(last); return true; } }
1,472
31.733333
82
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/matcher/OptTokenMatcher.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.duplications.statement.matcher; import java.util.List; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; /** * Delegates consumption to another matcher. */ public class OptTokenMatcher extends TokenMatcher { private final TokenMatcher matcher; public OptTokenMatcher(TokenMatcher matcher) { if (matcher == null) { throw new IllegalArgumentException(); } this.matcher = matcher; } /** * @return always true */ @Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { matcher.matchToken(tokenQueue, matchedTokenList); return true; } }
1,524
28.901961
82
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/matcher/TokenMatcher.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.duplications.statement.matcher; import java.util.List; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; public abstract class TokenMatcher { /** * @param tokenQueue queue of tokens for consumption, which contains at least one element * @param matchedTokenList list to populate by tokens, which were consumed * @return true if tokens were consumed successfully */ public abstract boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList); }
1,378
36.27027
91
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/matcher/UptoTokenMatcher.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.duplications.statement.matcher; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.sonar.duplications.token.Token; import org.sonar.duplications.token.TokenQueue; /** * Consumes everything up to one of the specified tokens. */ public class UptoTokenMatcher extends TokenMatcher { private final Set<String> uptoMatchTokens = new HashSet<>(); public UptoTokenMatcher(String[] uptoMatchTokens) { if (uptoMatchTokens == null) { throw new IllegalArgumentException(); } if (uptoMatchTokens.length == 0) { // otherwise we will always try to consume everything, but will never succeed throw new IllegalArgumentException(); } this.uptoMatchTokens.addAll(Arrays.asList(uptoMatchTokens)); } @Override public boolean matchToken(TokenQueue tokenQueue, List<Token> matchedTokenList) { do { Token token = tokenQueue.poll(); matchedTokenList.add(token); if (uptoMatchTokens.contains(token.getValue())) { return true; } } while (tokenQueue.peek() != null); return false; } }
1,978
31.442623
83
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/statement/matcher/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 a basic framework to create list of statements from list of tokens. * * The entry point of this framework is the {@link org.sonar.duplications.statement.StatementChunker} class. */ @ParametersAreNonnullByDefault package org.sonar.duplications.statement.matcher; import javax.annotation.ParametersAreNonnullByDefault;
1,181
38.4
108
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/token/BlackHoleTokenChannel.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.duplications.token; import org.sonar.channel.RegexChannel; class BlackHoleTokenChannel extends RegexChannel<TokenQueue> { public BlackHoleTokenChannel(String regex) { super(regex); } @Override protected void consume(CharSequence token, TokenQueue output) { // do nothing } }
1,159
31.222222
75
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/token/Token.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.duplications.token; public class Token { private final int line; private final int column; private final String value; /** * Cache for hash code. */ private int hash; public Token(String value, int line, int column) { this.value = value; this.column = column; this.line = line; } public int getLine() { return line; } public int getColumn() { return column; } public String getValue() { return value; } @Override public boolean equals(Object object) { if (object != null && getClass() == object.getClass()) { Token anotherToken = (Token) object; return anotherToken.line == line && anotherToken.column == column && anotherToken.value.equals(value); } return false; } @Override public int hashCode() { int h = hash; if (h == 0) { h = value.hashCode(); h = 31 * h + line; h = 31 * h + column; hash = h; } return h; } @Override public String toString() { return "'" + value + "'[" + line + "," + column + "]"; } }
1,925
23.692308
108
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/token/TokenChannel.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.duplications.token; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.sonar.channel.Channel; import org.sonar.channel.CodeBuffer.Cursor; import org.sonar.channel.CodeReader; class TokenChannel extends Channel<TokenQueue> { private final StringBuilder tmpBuilder = new StringBuilder(); private final Matcher matcher; private String normalizationValue; public TokenChannel(String regex) { matcher = Pattern.compile(regex).matcher(""); } public TokenChannel(String regex, String normalizationValue) { this(regex); this.normalizationValue = normalizationValue; } @Override public boolean consume(CodeReader code, TokenQueue output) { if (code.popTo(matcher, tmpBuilder) > 0) { // see SONAR-2499 Cursor previousCursor = code.getPreviousCursor(); if (normalizationValue != null) { output.add(new Token(normalizationValue, previousCursor.getLine(), previousCursor.getColumn())); } else { output.add(new Token(tmpBuilder.toString(), previousCursor.getLine(), previousCursor.getColumn())); } // Godin: note that other channels use method delete in order to do the same thing tmpBuilder.setLength(0); return true; } return false; } }
2,126
33.306452
107
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/token/TokenChunker.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.duplications.token; import java.io.Reader; import java.io.StringReader; import org.sonar.channel.ChannelDispatcher; import org.sonar.channel.CodeReader; import org.sonar.duplications.DuplicationsException; public final class TokenChunker { private final ChannelDispatcher<TokenQueue> channelDispatcher; public static Builder builder() { return new Builder(); } private TokenChunker(Builder builder) { this.channelDispatcher = builder.getChannelDispatcher(); } public TokenQueue chunk(String sourceCode) { return chunk(new StringReader(sourceCode)); } public TokenQueue chunk(Reader reader) { CodeReader code = new CodeReader(reader); TokenQueue queue = new TokenQueue(); try { channelDispatcher.consume(code, queue); return queue; } catch (Exception e) { throw new DuplicationsException("Unable to lex source code at line : " + code.getLinePosition() + " and column : " + code.getColumnPosition(), e); } } /** * Note that order is important, e.g. * <code>token("A").ignore("A")</code> for the input string "A" will produce token, whereas * <code>ignore("A").token("A")</code> will not. */ public static final class Builder { private ChannelDispatcher.Builder channelDispatcherBuilder = ChannelDispatcher.builder(); private Builder() { } public TokenChunker build() { return new TokenChunker(this); } /** * Defines that sequence of characters must be ignored, if it matches specified regular expression. */ public Builder ignore(String regularExpression) { channelDispatcherBuilder.addChannel(new BlackHoleTokenChannel(regularExpression)); return this; } /** * Defines that sequence of characters, which is matched specified regular expression, is a token. */ public Builder token(String regularExpression) { channelDispatcherBuilder.addChannel(new TokenChannel(regularExpression)); return this; } /** * Defines that sequence of characters, which is matched specified regular expression, is a token with specified value. */ public Builder token(String regularExpression, String normalizationValue) { channelDispatcherBuilder.addChannel(new TokenChannel(regularExpression, normalizationValue)); return this; } private ChannelDispatcher<TokenQueue> getChannelDispatcher() { return channelDispatcherBuilder.build(); } } }
3,325
31.291262
152
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/token/TokenQueue.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.duplications.token; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; public class TokenQueue implements Iterable<Token> { private final Deque<Token> tokenQueue; public TokenQueue(List<Token> tokenList) { tokenQueue = new LinkedList<>(tokenList); } public TokenQueue() { tokenQueue = new LinkedList<>(); } /** * Retrieves, but does not remove, token from this queue. * * @return token from this queue, or <tt>null</tt> if this queue is empty. */ public Token peek() { return tokenQueue.peek(); } /** * Retrieves and removes token from this queue. * * @return token from this queue, or <tt>null</tt> if this queue is empty. */ public Token poll() { return tokenQueue.poll(); } public int size() { return tokenQueue.size(); } public void add(Token token) { tokenQueue.addLast(token); } public boolean isNextTokenValue(String expectedValue) { Token nextToken = tokenQueue.peek(); if (nextToken == null) { // queue is empty return false; } return nextToken.getValue().equals(expectedValue); } @Override public Iterator<Token> iterator() { return tokenQueue.iterator(); } public void pushForward(List<Token> matchedTokenList) { ListIterator<Token> iter = matchedTokenList.listIterator(matchedTokenList.size()); while (iter.hasPrevious()) { tokenQueue.addFirst(iter.previous()); } } }
2,381
26.068182
86
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/token/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 a basic framework to sequentially read any kind of character stream and create list of tokens. * * The entry point of this framework is the {@link org.sonar.duplications.token.TokenChunker} class. */ @ParametersAreNonnullByDefault package org.sonar.duplications.token; import javax.annotation.ParametersAreNonnullByDefault;
1,188
38.633333
106
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/utils/FastStringComparator.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.duplications.utils; import java.util.Comparator; /** * More efficient (in terms of performance) implementation of a String comparator. * Speed is gained by using hash code as a primary comparison attribute, which is cached for String. * Be aware that this ordering is not lexicographic, however stable. */ public final class FastStringComparator implements Comparator<String> { public static final FastStringComparator INSTANCE = new FastStringComparator(); /** * Compares two strings (not lexicographically). */ @Override public int compare(String s1, String s2) { if (s1 == s2) { // NOSONAR false-positive: Compare Objects With Equals return 0; } int h1 = s1.hashCode(); int h2 = s2.hashCode(); if (h1 < h2) { return -1; } else if (h1 > h2) { return 1; } else { return s1.compareTo(s2); } } /** * Enforce use of a singleton instance. */ private FastStringComparator() { } }
1,831
30.050847
100
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/utils/SortedListsUtils.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.duplications.utils; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * Provides utility methods for sorted lists. */ public final class SortedListsUtils { /** * Returns true if {@code container} contains all elements from {@code list}. * Both lists must be sorted in consistency with {@code comparator}, * that is for any two sequential elements x and y: * {@code (comparator.compare(x, y) <= 0) && (comparator.compare(y, x) >= 0)}. * Running time - O(|container| + |list|). */ public static <T> boolean contains(List<T> container, List<T> list, Comparator<T> comparator) { Iterator<T> listIterator = list.iterator(); Iterator<T> containerIterator = container.iterator(); T listElement = listIterator.next(); T containerElement = containerIterator.next(); while (true) { int r = comparator.compare(containerElement, listElement); if (r == 0) { // current element from list is equal to current element from container if (!listIterator.hasNext()) { // no elements remaining in list - all were matched return true; } // next element from list also can be equal to current element from container listElement = listIterator.next(); } else if (r < 0) { // current element from list is greater than current element from container // need to check next element from container if (!containerIterator.hasNext()) { return false; } containerElement = containerIterator.next(); } else { // current element from list is less than current element from container // stop search, because current element from list would be less than any next element from container return false; } } } private SortedListsUtils() { } }
2,719
36.777778
108
java
sonarqube
sonarqube-master/sonar-duplications/src/main/java/org/sonar/duplications/utils/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.duplications.utils; import javax.annotation.ParametersAreNonnullByDefault;
969
37.8
75
java
sonarqube
sonarqube-master/sonar-duplications/src/test/files/java/MessageResources.java
/* * $Id: MessageResources.java 471754 2006-11-06 14:55:09Z husted $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.struts.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.Serializable; import java.text.MessageFormat; import java.util.HashMap; import java.util.Locale; /** * General purpose abstract class that describes an API for retrieving * Locale-sensitive messages from underlying resource locations of an * unspecified design, and optionally utilizing the <code>MessageFormat</code> * class to produce internationalized messages with parametric replacement. * <p> Calls to <code>getMessage()</code> variants without a * <code>Locale</code> argument are presumed to be requesting a message string * in the default <code>Locale</code> for this JVM. <p> Calls to * <code>getMessage()</code> with an unknown key, or an unknown * <code>Locale</code> will return <code>null</code> if the * <code>returnNull</code> property is set to <code>true</code>. Otherwise, a * suitable error message will be returned instead. <p> <strong>IMPLEMENTATION * NOTE</strong> - Classes that extend this class must be Serializable so that * instances may be used in distributable application server environments. * * @version $Rev: 471754 $ $Date: 2005-08-29 23:57:50 -0400 (Mon, 29 Aug 2005) * $ */ public abstract class MessageResources implements Serializable { // ------------------------------------------------------------- Properties /** * Commons Logging instance. */ protected static Log log = LogFactory.getLog(MessageResources.class); // --------------------------------------------------------- Static Methods /** * The default MessageResourcesFactory used to create MessageResources * instances. */ protected static MessageResourcesFactory defaultFactory = null; /** * The configuration parameter used to initialize this MessageResources. */ protected String config = null; /** * The default Locale for our environment. */ protected Locale defaultLocale = Locale.getDefault(); /** * The <code>MessageResourcesFactory</code> that created this instance. */ protected MessageResourcesFactory factory = null; /** * The set of previously created MessageFormat objects, keyed by the key * computed in <code>messageKey()</code>. */ protected HashMap formats = new HashMap(); /** * Indicate is a <code>null</code> is returned instead of an error message * string when an unknown Locale or key is requested. */ protected boolean returnNull = false; /** * Indicates whether 'escape processing' should be performed on the error * message string. */ private boolean escape = true; // ----------------------------------------------------------- Constructors /** * Construct a new MessageResources according to the specified * parameters. * * @param factory The MessageResourcesFactory that created us * @param config The configuration parameter for this MessageResources */ public MessageResources(MessageResourcesFactory factory, String config) { this(factory, config, false); } /** * Construct a new MessageResources according to the specified * parameters. * * @param factory The MessageResourcesFactory that created us * @param config The configuration parameter for this * MessageResources * @param returnNull The returnNull property we should initialize with */ public MessageResources(MessageResourcesFactory factory, String config, boolean returnNull) { super(); this.factory = factory; this.config = config; this.returnNull = returnNull; } /** * The configuration parameter used to initialize this MessageResources. * * @return parameter used to initialize this MessageResources */ public String getConfig() { return (this.config); } /** * The <code>MessageResourcesFactory</code> that created this instance. * * @return <code>MessageResourcesFactory</code> that created instance */ public MessageResourcesFactory getFactory() { return (this.factory); } /** * Indicates that a <code>null</code> is returned instead of an error * message string if an unknown Locale or key is requested. * * @return true if null is returned if unknown key or locale is requested */ public boolean getReturnNull() { return (this.returnNull); } /** * Indicates that a <code>null</code> is returned instead of an error * message string if an unknown Locale or key is requested. * * @param returnNull true Indicates that a <code>null</code> is returned * if an unknown Locale or key is requested. */ public void setReturnNull(boolean returnNull) { this.returnNull = returnNull; } /** * Indicates whether 'escape processing' should be performed on the error * message string. * * @since Struts 1.2.8 */ public boolean isEscape() { return escape; } /** * Set whether 'escape processing' should be performed on the error * message string. * * @since Struts 1.2.8 */ public void setEscape(boolean escape) { this.escape = escape; } // --------------------------------------------------------- Public Methods /** * Returns a text message for the specified key, for the default Locale. * * @param key The message key to look up */ public String getMessage(String key) { return this.getMessage((Locale) null, key, null); } /** * Returns a text message after parametric replacement of the specified * parameter placeholders. * * @param key The message key to look up * @param args An array of replacement parameters for placeholders */ public String getMessage(String key, Object[] args) { return this.getMessage((Locale) null, key, args); } /** * Returns a text message after parametric replacement of the specified * parameter placeholders. * * @param key The message key to look up * @param arg0 The replacement for placeholder {0} in the message */ public String getMessage(String key, Object arg0) { return this.getMessage((Locale) null, key, arg0); } /** * Returns a text message after parametric replacement of the specified * parameter placeholders. * * @param key The message key to look up * @param arg0 The replacement for placeholder {0} in the message * @param arg1 The replacement for placeholder {1} in the message */ public String getMessage(String key, Object arg0, Object arg1) { return this.getMessage((Locale) null, key, arg0, arg1); } /** * Returns a text message after parametric replacement of the specified * parameter placeholders. * * @param key The message key to look up * @param arg0 The replacement for placeholder {0} in the message * @param arg1 The replacement for placeholder {1} in the message * @param arg2 The replacement for placeholder {2} in the message */ public String getMessage(String key, Object arg0, Object arg1, Object arg2) { return this.getMessage((Locale) null, key, arg0, arg1, arg2); } /** * Returns a text message after parametric replacement of the specified * parameter placeholders. * * @param key The message key to look up * @param arg0 The replacement for placeholder {0} in the message * @param arg1 The replacement for placeholder {1} in the message * @param arg2 The replacement for placeholder {2} in the message * @param arg3 The replacement for placeholder {3} in the message */ public String getMessage(String key, Object arg0, Object arg1, Object arg2, Object arg3) { return this.getMessage((Locale) null, key, arg0, arg1, arg2, arg3); } /** * Returns a text message for the specified key, for the default Locale. A * null string result will be returned by this method if no relevant * message resource is found for this key or Locale, if the * <code>returnNull</code> property is set. Otherwise, an appropriate * error message will be returned. <p> This method must be implemented by * a concrete subclass. * * @param locale The requested message Locale, or <code>null</code> for * the system default Locale * @param key The message key to look up */ public abstract String getMessage(Locale locale, String key); /** * Returns a text message after parametric replacement of the specified * parameter placeholders. A null string result will be returned by this * method if no resource bundle has been configured. * * @param locale The requested message Locale, or <code>null</code> for * the system default Locale * @param key The message key to look up * @param args An array of replacement parameters for placeholders */ public String getMessage(Locale locale, String key, Object[] args) { // Cache MessageFormat instances as they are accessed if (locale == null) { locale = defaultLocale; } MessageFormat format = null; String formatKey = messageKey(locale, key); synchronized (formats) { format = (MessageFormat) formats.get(formatKey); if (format == null) { String formatString = getMessage(locale, key); if (formatString == null) { return returnNull ? null : ("???" + formatKey + "???"); } format = new MessageFormat(escape(formatString)); format.setLocale(locale); formats.put(formatKey, format); } } return format.format(args); } /** * Returns a text message after parametric replacement of the specified * parameter placeholders. A null string result will never be returned by * this method. * * @param locale The requested message Locale, or <code>null</code> for * the system default Locale * @param key The message key to look up * @param arg0 The replacement for placeholder {0} in the message */ public String getMessage(Locale locale, String key, Object arg0) { return this.getMessage(locale, key, new Object[]{arg0}); } /** * Returns a text message after parametric replacement of the specified * parameter placeholders. A null string result will never be returned by * this method. * * @param locale The requested message Locale, or <code>null</code> for * the system default Locale * @param key The message key to look up * @param arg0 The replacement for placeholder {0} in the message * @param arg1 The replacement for placeholder {1} in the message */ public String getMessage(Locale locale, String key, Object arg0, Object arg1) { return this.getMessage(locale, key, new Object[]{arg0, arg1}); } /** * Returns a text message after parametric replacement of the specified * parameter placeholders. A null string result will never be returned by * this method. * * @param locale The requested message Locale, or <code>null</code> for * the system default Locale * @param key The message key to look up * @param arg0 The replacement for placeholder {0} in the message * @param arg1 The replacement for placeholder {1} in the message * @param arg2 The replacement for placeholder {2} in the message */ public String getMessage(Locale locale, String key, Object arg0, Object arg1, Object arg2) { return this.getMessage(locale, key, new Object[]{arg0, arg1, arg2}); } /** * Returns a text message after parametric replacement of the specified * parameter placeholders. A null string result will never be returned by * this method. * * @param locale The requested message Locale, or <code>null</code> for * the system default Locale * @param key The message key to look up * @param arg0 The replacement for placeholder {0} in the message * @param arg1 The replacement for placeholder {1} in the message * @param arg2 The replacement for placeholder {2} in the message * @param arg3 The replacement for placeholder {3} in the message */ public String getMessage(Locale locale, String key, Object arg0, Object arg1, Object arg2, Object arg3) { return this.getMessage(locale, key, new Object[]{arg0, arg1, arg2, arg3}); } /** * Return <code>true</code> if there is a defined message for the * specified key in the system default locale. * * @param key The message key to look up */ public boolean isPresent(String key) { return this.isPresent(null, key); } /** * Return <code>true</code> if there is a defined message for the * specified key in the specified Locale. * * @param locale The requested message Locale, or <code>null</code> for * the system default Locale * @param key The message key to look up */ public boolean isPresent(Locale locale, String key) { String message = getMessage(locale, key); if (message == null) { return false; } else if (message.startsWith("???") && message.endsWith("???")) { return false; // FIXME - Only valid for default implementation } else { return true; } } // ------------------------------------------------------ Protected Methods /** * Escape any single quote characters that are included in the specified * message string. * * @param string The string to be escaped */ protected String escape(String string) { if (!isEscape()) { return string; } if ((string == null) || (string.indexOf('\'') < 0)) { return string; } int n = string.length(); StringBuffer sb = new StringBuffer(n); for (int i = 0; i < n; i++) { char ch = string.charAt(i); if (ch == '\'') { sb.append('\''); } sb.append(ch); } return sb.toString(); } /** * Compute and return a key to be used in caching information by a Locale. * <strong>NOTE</strong> - The locale key for the default Locale in our * environment is a zero length String. * * @param locale The locale for which a key is desired */ protected String localeKey(Locale locale) { return (locale == null) ? "" : locale.toString(); } /** * Compute and return a key to be used in caching information by Locale * and message key. * * @param locale The Locale for which this format key is calculated * @param key The message key for which this format key is calculated */ protected String messageKey(Locale locale, String key) { return (localeKey(locale) + "." + key); } /** * Compute and return a key to be used in caching information by locale * key and message key. * * @param localeKey The locale key for which this cache key is calculated * @param key The message key for which this cache key is * calculated */ protected String messageKey(String localeKey, String key) { return (localeKey + "." + key); } /** * Create and return an instance of <code>MessageResources</code> for the * created by the default <code>MessageResourcesFactory</code>. * * @param config Configuration parameter for this message bundle. */ public synchronized static MessageResources getMessageResources( String config) { if (defaultFactory == null) { defaultFactory = MessageResourcesFactory.createFactory(); } return defaultFactory.createResources(config); } /** * Log a message to the Writer that has been configured for our use. * * @param message The message to be logged */ public void log(String message) { log.debug(message); } /** * Log a message and exception to the Writer that has been configured for * our use. * * @param message The message to be logged * @param throwable The exception to be logged */ public void log(String message, Throwable throwable) { log.debug(message, throwable); } }
16,986
32.373281
81
java
sonarqube
sonarqube-master/sonar-duplications/src/test/files/java/RequestUtils.java
/* * $Id: RequestUtils.java 727180 2008-12-16 21:54:10Z niallp $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.struts.util; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.Globals; import org.apache.struts.action.*; import org.apache.struts.config.ActionConfig; import org.apache.struts.config.FormBeanConfig; import org.apache.struts.config.ForwardConfig; import org.apache.struts.config.ModuleConfig; import org.apache.struts.upload.FormFile; import org.apache.struts.upload.MultipartRequestHandler; import org.apache.struts.upload.MultipartRequestWrapper; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.*; /** * <p>General purpose utility methods related to processing a servlet request * in the Struts controller framework.</p> * * @version $Rev: 727180 $ $Date: 2008-12-17 00:54:10 +0300 (Ср., 17 дек. 2008) $ */ public class RequestUtils { // ------------------------------------------------------- Static Variables /** * <p>Commons Logging instance.</p> */ protected static Log log = LogFactory.getLog(RequestUtils.class); // --------------------------------------------------------- Public Methods /** * <p>Create and return an absolute URL for the specified context-relative * path, based on the server and context information in the specified * request.</p> * * @param request The servlet request we are processing * @param path The context-relative path (must start with '/') * @return absolute URL based on context-relative path * @throws MalformedURLException if we cannot create an absolute URL */ public static URL absoluteURL(HttpServletRequest request, String path) throws MalformedURLException { return (new URL(serverURL(request), request.getContextPath() + path)); } /** * <p>Return the <code>Class</code> object for the specified fully * qualified class name, from this web application's class loader.</p> * * @param className Fully qualified class name to be loaded * @return Class object * @throws ClassNotFoundException if the class cannot be found */ public static Class applicationClass(String className) throws ClassNotFoundException { return applicationClass(className, null); } /** * <p>Return the <code>Class</code> object for the specified fully * qualified class name, from this web application's class loader.</p> * * @param className Fully qualified class name to be loaded * @param classLoader The desired classloader to use * @return Class object * @throws ClassNotFoundException if the class cannot be found */ public static Class applicationClass(String className, ClassLoader classLoader) throws ClassNotFoundException { if (classLoader == null) { // Look up the class loader to be used classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = RequestUtils.class.getClassLoader(); } } // Attempt to load the specified class return (classLoader.loadClass(className)); } /** * <p>Return a new instance of the specified fully qualified class name, * after loading the class from this web application's class loader. The * specified class <strong>MUST</strong> have a public zero-arguments * constructor.</p> * * @param className Fully qualified class name to use * @return new instance of class * @throws ClassNotFoundException if the class cannot be found * @throws IllegalAccessException if the class or its constructor is not * accessible * @throws InstantiationException if this class represents an abstract * class, an interface, an array class, a * primitive type, or void * @throws InstantiationException if this class has no zero-arguments * constructor */ public static Object applicationInstance(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException { return applicationInstance(className, null); } /** * <p>Return a new instance of the specified fully qualified class name, * after loading the class from this web application's class loader. The * specified class <strong>MUST</strong> have a public zero-arguments * constructor.</p> * * @param className Fully qualified class name to use * @param classLoader The desired classloader to use * @return new instance of class * @throws ClassNotFoundException if the class cannot be found * @throws IllegalAccessException if the class or its constructor is not * accessible * @throws InstantiationException if this class represents an abstract * class, an interface, an array class, a * primitive type, or void * @throws InstantiationException if this class has no zero-arguments * constructor */ public static Object applicationInstance(String className, ClassLoader classLoader) throws ClassNotFoundException, IllegalAccessException, InstantiationException { return (applicationClass(className, classLoader).newInstance()); } /** * <p>Create (if necessary) and return an <code>ActionForm</code> instance * appropriate for this request. If no <code>ActionForm</code> instance * is required, return <code>null</code>.</p> * * @param request The servlet request we are processing * @param mapping The action mapping for this request * @param moduleConfig The configuration for this module * @param servlet The action servlet * @return ActionForm instance associated with this request */ public static ActionForm createActionForm(HttpServletRequest request, ActionMapping mapping, ModuleConfig moduleConfig, ActionServlet servlet) { // Is there a form bean associated with this mapping? String attribute = mapping.getAttribute(); if (attribute == null) { return (null); } // Look up the form bean configuration information to use String name = mapping.getName(); FormBeanConfig config = moduleConfig.findFormBeanConfig(name); if (config == null) { log.warn("No FormBeanConfig found under '" + name + "'"); return (null); } ActionForm instance = lookupActionForm(request, attribute, mapping.getScope()); // Can we recycle the existing form bean instance (if there is one)? if ((instance != null) && config.canReuse(instance)) { return (instance); } return createActionForm(config, servlet); } private static ActionForm lookupActionForm(HttpServletRequest request, String attribute, String scope) { // Look up any existing form bean instance if (log.isDebugEnabled()) { log.debug(" Looking for ActionForm bean instance in scope '" + scope + "' under attribute key '" + attribute + "'"); } ActionForm instance = null; HttpSession session = null; if ("request".equals(scope)) { instance = (ActionForm) request.getAttribute(attribute); } else { session = request.getSession(); instance = (ActionForm) session.getAttribute(attribute); } return (instance); } /** * <p>Create and return an <code>ActionForm</code> instance appropriate to * the information in <code>config</code>.</p> * <p/> * <p>Does not perform any checks to see if an existing ActionForm exists * which could be reused.</p> * * @param config The configuration for the Form bean which is to be * created. * @param servlet The action servlet * @return ActionForm instance associated with this request */ public static ActionForm createActionForm(FormBeanConfig config, ActionServlet servlet) { if (config == null) { return (null); } ActionForm instance = null; // Create and return a new form bean instance try { instance = config.createActionForm(servlet); if (log.isDebugEnabled()) { log.debug(" Creating new " + (config.getDynamic() ? "DynaActionForm" : "ActionForm") + " instance of type '" + config.getType() + "'"); log.trace(" --> " + instance); } } catch (Throwable t) { log.error(servlet.getInternal().getMessage("formBean", config.getType()), t); } return (instance); } /** * <p>Retrieves the servlet mapping pattern for the specified {@link ActionServlet}.</p> * * @return the servlet mapping * @see Globals#SERVLET_KEY * @since Struts 1.3.6 */ public static String getServletMapping(ActionServlet servlet) { ServletContext servletContext = servlet.getServletConfig().getServletContext(); return (String) servletContext.getAttribute(Globals.SERVLET_KEY); } /** * <p>Look up and return current user locale, based on the specified * parameters.</p> * * @param request The request used to lookup the Locale * @param locale Name of the session attribute for our user's Locale. If * this is <code>null</code>, the default locale key is * used for the lookup. * @return current user locale * @since Struts 1.2 */ public static Locale getUserLocale(HttpServletRequest request, String locale) { Locale userLocale = null; HttpSession session = request.getSession(false); if (locale == null) { locale = Globals.LOCALE_KEY; } // Only check session if sessions are enabled if (session != null) { userLocale = (Locale) session.getAttribute(locale); } if (userLocale == null) { // Returns Locale based on Accept-Language header or the server default userLocale = request.getLocale(); } return userLocale; } /** * <p>Populate the properties of the specified JavaBean from the specified * HTTP request, based on matching each parameter name against the * corresponding JavaBeans "property setter" methods in the bean's class. * Suitable conversion is done for argument types as described under * <code>convert()</code>.</p> * * @param bean The JavaBean whose properties are to be set * @param request The HTTP request whose parameters are to be used to * populate bean properties * @throws ServletException if an exception is thrown while setting * property values */ public static void populate(Object bean, HttpServletRequest request) throws ServletException { populate(bean, null, null, request); } /** * <p>Populate the properties of the specified JavaBean from the specified * HTTP request, based on matching each parameter name (plus an optional * prefix and/or suffix) against the corresponding JavaBeans "property * setter" methods in the bean's class. Suitable conversion is done for * argument types as described under <code>setProperties</code>.</p> * <p/> * <p>If you specify a non-null <code>prefix</code> and a non-null * <code>suffix</code>, the parameter name must match * <strong>both</strong> conditions for its value(s) to be used in * populating bean properties. If the request's content type is * "multipart/form-data" and the method is "POST", the * <code>HttpServletRequest</code> object will be wrapped in a * <code>MultipartRequestWrapper</code object.</p> * * @param bean The JavaBean whose properties are to be set * @param prefix The prefix (if any) to be prepend to bean property names * when looking for matching parameters * @param suffix The suffix (if any) to be appended to bean property * names when looking for matching parameters * @param request The HTTP request whose parameters are to be used to * populate bean properties * @throws ServletException if an exception is thrown while setting * property values */ public static void populate(Object bean, String prefix, String suffix, HttpServletRequest request) throws ServletException { // Build a list of relevant request parameters from this request HashMap properties = new HashMap(); // Iterator of parameter names Enumeration names = null; // Map for multipart parameters Map multipartParameters = null; String contentType = request.getContentType(); String method = request.getMethod(); boolean isMultipart = false; if (bean instanceof ActionForm) { ((ActionForm) bean).setMultipartRequestHandler(null); } MultipartRequestHandler multipartHandler = null; if ((contentType != null) && (contentType.startsWith("multipart/form-data")) && (method.equalsIgnoreCase("POST"))) { // Get the ActionServletWrapper from the form bean ActionServletWrapper servlet; if (bean instanceof ActionForm) { servlet = ((ActionForm) bean).getServletWrapper(); } else { throw new ServletException("bean that's supposed to be " + "populated from a multipart request is not of type " + "\"org.apache.struts.action.ActionForm\", but type " + "\"" + bean.getClass().getName() + "\""); } // Obtain a MultipartRequestHandler multipartHandler = getMultipartHandler(request); if (multipartHandler != null) { isMultipart = true; // Set servlet and mapping info servlet.setServletFor(multipartHandler); multipartHandler.setMapping((ActionMapping) request .getAttribute(Globals.MAPPING_KEY)); // Initialize multipart request class handler multipartHandler.handleRequest(request); //stop here if the maximum length has been exceeded Boolean maxLengthExceeded = (Boolean) request.getAttribute(MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED); if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) { ((ActionForm) bean).setMultipartRequestHandler(multipartHandler); return; } //retrieve form values and put into properties multipartParameters = getAllParametersForMultipartRequest(request, multipartHandler); names = Collections.enumeration(multipartParameters.keySet()); } } if (!isMultipart) { names = request.getParameterNames(); } while (names.hasMoreElements()) { String name = (String) names.nextElement(); String stripped = name; if (prefix != null) { if (!stripped.startsWith(prefix)) { continue; } stripped = stripped.substring(prefix.length()); } if (suffix != null) { if (!stripped.endsWith(suffix)) { continue; } stripped = stripped.substring(0, stripped.length() - suffix.length()); } Object parameterValue = null; if (isMultipart) { parameterValue = multipartParameters.get(name); parameterValue = rationalizeMultipleFileProperty(bean, name, parameterValue); } else { parameterValue = request.getParameterValues(name); } // Populate parameters, except "standard" struts attributes // such as 'org.apache.struts.action.CANCEL' if (!(stripped.startsWith("org.apache.struts."))) { properties.put(stripped, parameterValue); } } // Set the corresponding properties of our bean try { BeanUtils.populate(bean, properties); } catch (Exception e) { throw new ServletException("BeanUtils.populate", e); } finally { if (multipartHandler != null) { // Set the multipart request handler for our ActionForm. // If the bean isn't an ActionForm, an exception would have been // thrown earlier, so it's safe to assume that our bean is // in fact an ActionForm. ((ActionForm) bean).setMultipartRequestHandler(multipartHandler); } } } /** * <p>Populates the parameters of the specified ActionRedirect from * the specified HTTP request.</p> * * @param redirect The ActionRedirect whose parameters are to be set * @param request The HTTP request whose parameters are to be used * @since Struts 1.4 */ public static void populate(ActionRedirect redirect, HttpServletRequest request) { assert (redirect != null) : "redirect is required"; assert (request != null) : "request is required"; Enumeration e = request.getParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String[] values = request.getParameterValues(name); redirect.addParameter(name, values); } } /** * <p>If the given form bean can accept multiple FormFile objects but the user only uploaded a single, then * the property will not match the form bean type. This method performs some simple checks to try to accommodate * that situation.</p> * * @param bean * @param name * @param parameterValue * @return * @throws ServletException if the introspection has any errors. */ private static Object rationalizeMultipleFileProperty(Object bean, String name, Object parameterValue) throws ServletException { if (!(parameterValue instanceof FormFile)) { return parameterValue; } FormFile formFileValue = (FormFile) parameterValue; try { Class propertyType = PropertyUtils.getPropertyType(bean, name); if (propertyType == null) { return parameterValue; } if (List.class.isAssignableFrom(propertyType)) { ArrayList list = new ArrayList(1); list.add(formFileValue); return list; } if (propertyType.isArray() && propertyType.getComponentType().equals(FormFile.class)) { return new FormFile[]{formFileValue}; } } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { throw new ServletException(e); } catch (NoSuchMethodException e) { throw new ServletException(e); } // no changes return parameterValue; } /** * <p>Try to locate a multipart request handler for this request. First, * look for a mapping-specific handler stored for us under an attribute. * If one is not present, use the global multipart handler, if there is * one.</p> * * @param request The HTTP request for which the multipart handler should * be found. * @return the multipart handler to use, or null if none is found. * @throws ServletException if any exception is thrown while attempting to * locate the multipart handler. */ private static MultipartRequestHandler getMultipartHandler( HttpServletRequest request) throws ServletException { MultipartRequestHandler multipartHandler = null; String multipartClass = (String) request.getAttribute(Globals.MULTIPART_KEY); request.removeAttribute(Globals.MULTIPART_KEY); // Try to initialize the mapping specific request handler if (multipartClass != null) { try { multipartHandler = (MultipartRequestHandler) applicationInstance(multipartClass); } catch (ClassNotFoundException cnfe) { log.error("MultipartRequestHandler class \"" + multipartClass + "\" in mapping class not found, " + "defaulting to global multipart class"); } catch (InstantiationException ie) { log.error("InstantiationException when instantiating " + "MultipartRequestHandler \"" + multipartClass + "\", " + "defaulting to global multipart class, exception: " + ie.getMessage()); } catch (IllegalAccessException iae) { log.error("IllegalAccessException when instantiating " + "MultipartRequestHandler \"" + multipartClass + "\", " + "defaulting to global multipart class, exception: " + iae.getMessage()); } if (multipartHandler != null) { return multipartHandler; } } ModuleConfig moduleConfig = ModuleUtils.getInstance().getModuleConfig(request); multipartClass = moduleConfig.getControllerConfig().getMultipartClass(); // Try to initialize the global request handler if (multipartClass != null) { try { multipartHandler = (MultipartRequestHandler) applicationInstance(multipartClass); } catch (ClassNotFoundException cnfe) { throw new ServletException("Cannot find multipart class \"" + multipartClass + "\"", cnfe); } catch (InstantiationException ie) { throw new ServletException( "InstantiationException when instantiating " + "multipart class \"" + multipartClass + "\"", ie); } catch (IllegalAccessException iae) { throw new ServletException( "IllegalAccessException when instantiating " + "multipart class \"" + multipartClass + "\"", iae); } if (multipartHandler != null) { return multipartHandler; } } return multipartHandler; } /** * <p>Create a <code>Map</code> containing all of the parameters supplied * for a multipart request, keyed by parameter name. In addition to text * and file elements from the multipart body, query string parameters are * included as well.</p> * * @param request The (wrapped) HTTP request whose parameters are * to be added to the map. * @param multipartHandler The multipart handler used to parse the * request. * @return the map containing all parameters for this multipart request. */ private static Map getAllParametersForMultipartRequest( HttpServletRequest request, MultipartRequestHandler multipartHandler) { Map parameters = new HashMap(); Hashtable elements = multipartHandler.getAllElements(); Enumeration e = elements.keys(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); parameters.put(key, elements.get(key)); } if (request instanceof MultipartRequestWrapper) { request = (HttpServletRequest) ((MultipartRequestWrapper) request) .getRequest(); e = request.getParameterNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); parameters.put(key, request.getParameterValues(key)); } } else { log.debug("Gathering multipart parameters for unwrapped request"); } return parameters; } /** * <p>Compute the printable representation of a URL, leaving off the * scheme/host/port part if no host is specified. This will typically be * the case for URLs that were originally created from relative or * context-relative URIs.</p> * * @param url URL to render in a printable representation * @return printable representation of a URL */ public static String printableURL(URL url) { if (url.getHost() != null) { return (url.toString()); } String file = url.getFile(); String ref = url.getRef(); if (ref == null) { return (file); } else { StringBuffer sb = new StringBuffer(file); sb.append('#'); sb.append(ref); return (sb.toString()); } } /** * <p>Return the context-relative URL that corresponds to the specified * {@link ActionConfig}, relative to the module associated with the * current modules's {@link ModuleConfig}.</p> * * @param request The servlet request we are processing * @param action ActionConfig to be evaluated * @param pattern URL pattern used to map the controller servlet * @return context-relative URL relative to the module * @since Struts 1.1 */ public static String actionURL(HttpServletRequest request, ActionConfig action, String pattern) { StringBuffer sb = new StringBuffer(); if (pattern.endsWith("/*")) { sb.append(pattern.substring(0, pattern.length() - 2)); sb.append(action.getPath()); } else if (pattern.startsWith("*.")) { ModuleConfig appConfig = ModuleUtils.getInstance().getModuleConfig(request); sb.append(appConfig.getPrefix()); sb.append(action.getPath()); sb.append(pattern.substring(1)); } else { throw new IllegalArgumentException(pattern); } return sb.toString(); } /** * <p>Return the context-relative URL that corresponds to the specified * <code>ForwardConfig</code>. The URL is calculated based on the * properties of the {@link ForwardConfig} instance as follows:</p> * <p/> * <ul> * <p/> * <p/> * <li>If the <code>contextRelative</code> property is set, it is assumed * that the <code>path</code> property contains a path that is already * context-relative: * <p/> * <ul> * <p/> * <li>If the <code>path</code> property value starts with a slash, it is * returned unmodified.</li> <li>If the <code>path</code> property value * does not start with a slash, a slash is prepended.</li> * <p/> * </ul></li> * <p/> * <li>Acquire the <code>forwardPattern</code> property from the * <code>ControllerConfig</code> for the application module used to * process this request. If no pattern was configured, default to a * pattern of <code>$M$P</code>, which is compatible with the hard-coded * mapping behavior in Struts 1.0.</li> * <p/> * <li>Process the acquired <code>forwardPattern</code>, performing the * following substitutions: * <p/> * <ul> * <p/> * <li><strong>$M</strong> - Replaced by the module prefix for the * application module processing this request.</li> * <p/> * <li><strong>$P</strong> - Replaced by the <code>path</code> property of * the specified {@link ForwardConfig}, prepended with a slash if it does * not start with one.</li> * <p/> * <li><strong>$$</strong> - Replaced by a single dollar sign * character.</li> * <p/> * <li><strong>$x</strong> (where "x" is any charater not listed above) - * Silently omit these two characters from the result value. (This has * the side effect of causing all other $+letter combinations to be * reserved.)</li> * <p/> * </ul></li> * <p/> * </ul> * * @param request The servlet request we are processing * @param forward ForwardConfig to be evaluated * @return context-relative URL * @since Struts 1.1 */ public static String forwardURL(HttpServletRequest request, ForwardConfig forward) { return forwardURL(request, forward, null); } /** * <p>Return the context-relative URL that corresponds to the specified * <code>ForwardConfig</code>. The URL is calculated based on the * properties of the {@link ForwardConfig} instance as follows:</p> * <p/> * <ul> * <p/> * <li>If the <code>contextRelative</code> property is set, it is assumed * that the <code>path</code> property contains a path that is already * context-relative: <ul> * <p/> * <li>If the <code>path</code> property value starts with a slash, it is * returned unmodified.</li> <li>If the <code>path</code> property value * does not start with a slash, a slash is prepended.</li> * <p/> * </ul></li> * <p/> * <li>Acquire the <code>forwardPattern</code> property from the * <code>ControllerConfig</code> for the application module used to * process this request. If no pattern was configured, default to a * pattern of <code>$M$P</code>, which is compatible with the hard-coded * mapping behavior in Struts 1.0.</li> * <p/> * <li>Process the acquired <code>forwardPattern</code>, performing the * following substitutions: <ul> <li><strong>$M</strong> - Replaced by the * module prefix for the application module processing this request.</li> * <p/> * <li><strong>$P</strong> - Replaced by the <code>path</code> property of * the specified {@link ForwardConfig}, prepended with a slash if it does * not start with one.</li> * <p/> * <li><strong>$$</strong> - Replaced by a single dollar sign * character.</li> * <p/> * <li><strong>$x</strong> (where "x" is any charater not listed above) - * Silently omit these two characters from the result value. (This has * the side effect of causing all other $+letter combinations to be * reserved.)</li> * <p/> * </ul></li></ul> * * @param request The servlet request we are processing * @param forward ForwardConfig to be evaluated * @param moduleConfig Base forward on this module config. * @return context-relative URL * @since Struts 1.2 */ public static String forwardURL(HttpServletRequest request, ForwardConfig forward, ModuleConfig moduleConfig) { //load the current moduleConfig, if null if (moduleConfig == null) { moduleConfig = ModuleUtils.getInstance().getModuleConfig(request); } String path = forward.getPath(); //load default prefix String prefix = moduleConfig.getPrefix(); //override prefix if supplied by forward if (forward.getModule() != null) { prefix = forward.getModule(); if ("/".equals(prefix)) { prefix = ""; } } StringBuffer sb = new StringBuffer(); // Calculate a context relative path for this ForwardConfig String forwardPattern = moduleConfig.getControllerConfig().getForwardPattern(); if (forwardPattern == null) { // Performance optimization for previous default behavior sb.append(prefix); // smoothly insert a '/' if needed if (!path.startsWith("/")) { sb.append("/"); } sb.append(path); } else { boolean dollar = false; for (int i = 0; i < forwardPattern.length(); i++) { char ch = forwardPattern.charAt(i); if (dollar) { switch (ch) { case 'M': sb.append(prefix); break; case 'P': // add '/' if needed if (!path.startsWith("/")) { sb.append("/"); } sb.append(path); break; case '$': sb.append('$'); break; default: ; // Silently swallow } dollar = false; continue; } else if (ch == '$') { dollar = true; } else { sb.append(ch); } } } return (sb.toString()); } /** * <p>Return the URL representing the current request. This is equivalent * to <code>HttpServletRequest.getRequestURL</code> in Servlet 2.3.</p> * * @param request The servlet request we are processing * @return URL representing the current request * @throws MalformedURLException if a URL cannot be created */ public static URL requestURL(HttpServletRequest request) throws MalformedURLException { StringBuffer url = requestToServerUriStringBuffer(request); return (new URL(url.toString())); } /** * <p>Return the URL representing the scheme, server, and port number of * the current request. Server-relative URLs can be created by simply * appending the server-relative path (starting with '/') to this.</p> * * @param request The servlet request we are processing * @return URL representing the scheme, server, and port number of the * current request * @throws MalformedURLException if a URL cannot be created */ public static URL serverURL(HttpServletRequest request) throws MalformedURLException { StringBuffer url = requestToServerStringBuffer(request); return (new URL(url.toString())); } /** * <p>Return the string representing the scheme, server, and port number * of the current request. Server-relative URLs can be created by simply * appending the server-relative path (starting with '/') to this.</p> * * @param request The servlet request we are processing * @return URL representing the scheme, server, and port number of the * current request * @since Struts 1.2.0 */ public static StringBuffer requestToServerUriStringBuffer( HttpServletRequest request) { StringBuffer serverUri = createServerUriStringBuffer(request.getScheme(), request.getServerName(), request.getServerPort(), request.getRequestURI()); return serverUri; } /** * <p>Return <code>StringBuffer</code> representing the scheme, server, * and port number of the current request. Server-relative URLs can be * created by simply appending the server-relative path (starting with * '/') to this.</p> * * @param request The servlet request we are processing * @return URL representing the scheme, server, and port number of the * current request * @since Struts 1.2.0 */ public static StringBuffer requestToServerStringBuffer( HttpServletRequest request) { return createServerStringBuffer(request.getScheme(), request.getServerName(), request.getServerPort()); } /** * <p>Return <code>StringBuffer</code> representing the scheme, server, * and port number of the current request.</p> * * @param scheme The scheme name to use * @param server The server name to use * @param port The port value to use * @return StringBuffer in the form scheme: server: port * @since Struts 1.2.0 */ public static StringBuffer createServerStringBuffer(String scheme, String server, int port) { StringBuffer url = new StringBuffer(); if (port < 0) { port = 80; // Work around java.net.URL bug } url.append(scheme); url.append("://"); url.append(server); if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) { url.append(':'); url.append(port); } return url; } /** * <p>Return <code>StringBuffer</code> representing the scheme, server, * and port number of the current request.</p> * * @param scheme The scheme name to use * @param server The server name to use * @param port The port value to use * @param uri The uri value to use * @return StringBuffer in the form scheme: server: port * @since Struts 1.2.0 */ public static StringBuffer createServerUriStringBuffer(String scheme, String server, int port, String uri) { StringBuffer serverUri = createServerStringBuffer(scheme, server, port); serverUri.append(uri); return serverUri; } /** * <p>Returns the true path of the destination action if the specified forward * is an action-aliased URL. This method version forms the URL based on * the current request; selecting the current module if the forward does not * explicitly contain a module path.</p> * * @param forward the forward config * @param request the current request * @param servlet the servlet handling the current request * @return the context-relative URL of the action if the forward has an action identifier; otherwise <code>null</code>. * @since Struts 1.3.6 */ public static String actionIdURL(ForwardConfig forward, HttpServletRequest request, ActionServlet servlet) { ModuleConfig moduleConfig = null; if (forward.getModule() != null) { String prefix = forward.getModule(); moduleConfig = ModuleUtils.getInstance().getModuleConfig(prefix, servlet.getServletContext()); } else { moduleConfig = ModuleUtils.getInstance().getModuleConfig(request); } return actionIdURL(forward.getPath(), moduleConfig, servlet); } /** * <p>Returns the true path of the destination action if the specified forward * is an action-aliased URL. This method version forms the URL based on * the specified module. * * @param originalPath the action-aliased path * @param moduleConfig the module config for this request * @param servlet the servlet handling the current request * @return the context-relative URL of the action if the path has an action identifier; otherwise <code>null</code>. * @since Struts 1.3.6 */ public static String actionIdURL(String originalPath, ModuleConfig moduleConfig, ActionServlet servlet) { if (originalPath.startsWith("http") || originalPath.startsWith("/")) { return null; } // Split the forward path into the resource and query string; // it is possible a forward (or redirect) has added parameters. String actionId = null; String qs = null; int qpos = originalPath.indexOf("?"); if (qpos == -1) { actionId = originalPath; } else { actionId = originalPath.substring(0, qpos); qs = originalPath.substring(qpos); } // Find the action of the given actionId ActionConfig actionConfig = moduleConfig.findActionConfigId(actionId); if (actionConfig == null) { if (log.isDebugEnabled()) { log.debug("No actionId found for " + actionId); } return null; } String path = actionConfig.getPath(); String mapping = RequestUtils.getServletMapping(servlet); StringBuffer actionIdPath = new StringBuffer(); // Form the path based on the servlet mapping pattern if (mapping.startsWith("*")) { actionIdPath.append(path); actionIdPath.append(mapping.substring(1)); } else if (mapping.startsWith("/")) { // implied ends with a * mapping = mapping.substring(0, mapping.length() - 1); if (mapping.endsWith("/") && path.startsWith("/")) { actionIdPath.append(mapping); actionIdPath.append(path.substring(1)); } else { actionIdPath.append(mapping); actionIdPath.append(path); } } else { log.warn("Unknown servlet mapping pattern"); actionIdPath.append(path); } // Lastly add any query parameters (the ? is part of the query string) if (qs != null) { actionIdPath.append(qs); } // Return the path if (log.isDebugEnabled()) { log.debug(originalPath + " unaliased to " + actionIdPath.toString()); } return actionIdPath.toString(); } /** * Determines whether the current request is forwarded. * * @param request current HTTP request * @return true if the request is forwarded; otherwise false * @since Struts 1.4 */ public static boolean isRequestForwarded(HttpServletRequest request) { return (request.getAttribute("javax.servlet.forward.request_uri") != null); } /** * Determines whether the current request is included. * * @param request current HTTP request * @return true if the request is included; otherwise false * @since Struts 1.4 */ public static boolean isRequestIncluded(HttpServletRequest request) { return (request.getAttribute("javax.servlet.include.request_uri") != null); } /** * Verifies whether current request is forwarded from one action to * another or not. * * @param request current HTTP request * @return true if the request is chained; otherwise false * @since Struts 1.4 */ public static boolean isRequestChained(HttpServletRequest request) { return (request.getAttribute(Globals.CHAIN_KEY) != null); } }
41,139
34.404475
130
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/DuplicationsTestUtil.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.duplications; import java.io.File; public class DuplicationsTestUtil { public static File findFile(String relativePathToFile) { File file = new File("src/test/files/", relativePathToFile); if (!file.exists()) { // IntellijIDEA resolves path from root module basedir file = new File("sonar-duplications/src/test/files/", relativePathToFile); } return file; } }
1,257
33.944444
80
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/block/BlockChunkerTest.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.duplications.block; import java.util.List; import org.junit.Test; import org.sonar.duplications.statement.Statement; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class BlockChunkerTest extends BlockChunkerTestCase { @Override protected BlockChunker createChunkerWithBlockSize(int blockSize) { return new BlockChunker(blockSize); } /** * Rolling hash must produce exactly the same values as without rolling behavior. * Moreover those values must always be the same (without dependency on JDK). */ @Test public void shouldCalculateHashes() { List<Statement> statements = createStatementsFromStrings("aaaaaa", "bbbbbb", "cccccc", "dddddd", "eeeeee"); BlockChunker blockChunker = createChunkerWithBlockSize(3); List<Block> blocks = blockChunker.chunk("resource", statements); assertThat(blocks.get(0).getBlockHash(), equalTo(hash("aaaaaa", "bbbbbb", "cccccc"))); assertThat(blocks.get(1).getBlockHash(), equalTo(hash("bbbbbb", "cccccc", "dddddd"))); assertThat(blocks.get(2).getBlockHash(), equalTo(hash("cccccc", "dddddd", "eeeeee"))); assertThat(blocks.get(0).getBlockHash().toString(), is("fffffeb6ae1af4c0")); assertThat(blocks.get(1).getBlockHash().toString(), is("fffffebd8512d120")); assertThat(blocks.get(2).getBlockHash().toString(), is("fffffec45c0aad80")); } private ByteArray hash(String... statements) { long hash = 0; for (String statement : statements) { hash = hash * 31 + statement.hashCode(); } return new ByteArray(hash); } }
2,496
38.634921
111
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/block/BlockChunkerTestCase.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.duplications.block; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Test; import org.sonar.duplications.statement.Statement; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; /** * Any implementation of {@link BlockChunker} should pass these test scenarios. */ public abstract class BlockChunkerTestCase { /** * Factory method. */ protected abstract BlockChunker createChunkerWithBlockSize(int blockSize); /** * Given: * <pre> * String[][] data = { * {"a", "a"}, * {"a", "a"}, * {"a"}, * {"a", "a"}, * {"a", "a"} * }; * * Statements (where L - literal, C - comma): "LCL", "C", "LCL", "C", "L", "C", "LCL", "C", "LCL" * Block size is 5. * First block: "LCL", "C", "LCL", "C", "L" * Last block: "L", "C", "LCL", "C", "LCL" * </pre> * Expected: different hashes for first and last blocks */ @Test public void testSameChars() { List<Statement> statements = createStatementsFromStrings("LCL", "C", "LCL", "C", "L", "C", "LCL", "C", "LCL"); BlockChunker chunker = createChunkerWithBlockSize(5); List<Block> blocks = chunker.chunk("resource", statements); assertThat("first and last block should have different hashes", blocks.get(0).getBlockHash(), not(equalTo(blocks.get(blocks.size() - 1).getBlockHash()))); } /** * TODO Godin: should we allow empty statements in general? */ @Test public void testEmptyStatements() { List<Statement> statements = createStatementsFromStrings("1", "", "1", "1", ""); BlockChunker chunker = createChunkerWithBlockSize(3); List<Block> blocks = chunker.chunk("resource", statements); assertThat("first and last block should have different hashes", blocks.get(0).getBlockHash(), not(equalTo(blocks.get(blocks.size() - 1).getBlockHash()))); } /** * Given: 5 statements, block size is 3 * Expected: 4 blocks with correct index and with line numbers */ @Test public void shouldBuildBlocksFromStatements() { List<Statement> statements = createStatementsFromStrings("1", "2", "3", "4", "5", "6"); BlockChunker chunker = createChunkerWithBlockSize(3); List<Block> blocks = chunker.chunk("resource", statements); assertThat(blocks.size(), is(4)); assertThat(blocks.get(0).getIndexInFile(), is(0)); assertThat(blocks.get(0).getStartLine(), is(0)); assertThat(blocks.get(0).getEndLine(), is(2)); assertThat(blocks.get(1).getIndexInFile(), is(1)); assertThat(blocks.get(1).getStartLine(), is(1)); assertThat(blocks.get(1).getEndLine(), is(3)); } @Test public void testHashes() { List<Statement> statements = createStatementsFromStrings("1", "2", "1", "2"); BlockChunker chunker = createChunkerWithBlockSize(2); List<Block> blocks = chunker.chunk("resource", statements); assertThat("blocks 0 and 2 should have same hash", blocks.get(0).getBlockHash(), equalTo(blocks.get(2).getBlockHash())); assertThat("blocks 0 and 1 should have different hash", blocks.get(0).getBlockHash(), not(equalTo(blocks.get(1).getBlockHash()))); } /** * Given: 0 statements * Expected: 0 blocks */ @Test public void shouldNotBuildBlocksWhenNoStatements() { List<Statement> statements = Collections.emptyList(); BlockChunker blockChunker = createChunkerWithBlockSize(2); List<Block> blocks = blockChunker.chunk("resource", statements); assertThat(blocks, sameInstance(Collections.EMPTY_LIST)); } /** * Given: 1 statement, block size is 2 * Expected: 0 blocks */ @Test public void shouldNotBuildBlocksWhenNotEnoughStatements() { List<Statement> statements = createStatementsFromStrings("statement"); BlockChunker blockChunker = createChunkerWithBlockSize(2); List<Block> blocks = blockChunker.chunk("resource", statements); assertThat(blocks, sameInstance(Collections.EMPTY_LIST)); } /** * Creates list of statements from Strings, each statement on a new line starting from 0. */ protected static List<Statement> createStatementsFromStrings(String... values) { List<Statement> result = new ArrayList<>(); for (int i = 0; i < values.length; i++) { result.add(new Statement(i, i, values[i])); } return result; } }
5,319
35.944444
158
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/block/BlockTest.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.duplications.block; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertThat; public class BlockTest { @Test public void testBuilder() { ByteArray hash = new ByteArray(1); Block block = Block.builder() .setResourceId("resource") .setBlockHash(hash) .setIndexInFile(1) .setLines(2, 3) .setUnit(4, 5) .build(); assertThat(block.getResourceId(), is("resource")); assertThat(block.getBlockHash(), sameInstance(hash)); assertThat(block.getIndexInFile(), is(1)); assertThat(block.getStartLine(), is(2)); assertThat(block.getEndLine(), is(3)); assertThat(block.getStartUnit(), is(4)); assertThat(block.getEndUnit(), is(5)); } }
1,686
30.830189
75
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/block/ByteArrayTest.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.duplications.block; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; public class ByteArrayTest { @Test public void shouldCreateFromInt() { int value = 0x12FF8413; ByteArray byteArray = new ByteArray(value); assertThat(byteArray.toString(), is(Integer.toHexString(value))); } @Test public void shouldCreateFromLong() { long value = 0x12FF841344567899L; ByteArray byteArray = new ByteArray(value); assertThat(byteArray.toString(), is(Long.toHexString(value))); } @Test public void shouldCreateFromHexString() { String value = "12FF841344567899"; ByteArray byteArray = new ByteArray(value); assertThat(byteArray.toString(), is(value.toLowerCase())); } @Test public void shouldCreateFromIntArray() { ByteArray byteArray = new ByteArray(new int[] { 0x04121986 }); assertThat(byteArray.toString(), is("04121986")); } @Test public void shouldConvertToIntArray() { // number of bytes is enough to create exactly one int (4 bytes) ByteArray byteArray = new ByteArray(new byte[] { 0x04, 0x12, 0x19, (byte) 0x86 }); assertThat(byteArray.toIntArray(), is(new int[] { 0x04121986 })); // number of bytes is more than 4, but less than 8, so anyway 2 ints byteArray = new ByteArray(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x31 }); assertThat(byteArray.toIntArray(), is(new int[] { 0x00000000, 0x31000000 })); } }
2,324
33.701493
86
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/CloneGroupMatcher.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.duplications.detector; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.sonar.duplications.index.CloneGroup; import org.sonar.duplications.index.ClonePart; import static org.hamcrest.CoreMatchers.hasItem; public class CloneGroupMatcher extends TypeSafeMatcher<CloneGroup> { public static Matcher<Iterable<? super CloneGroup>> hasCloneGroup(int expectedLen, ClonePart... expectedParts) { return hasItem(new CloneGroupMatcher(expectedLen, expectedParts)); } private final int expectedLen; private final ClonePart[] expectedParts; private CloneGroupMatcher(int expectedLen, ClonePart... expectedParts) { this.expectedLen = expectedLen; this.expectedParts = expectedParts; } @Override public boolean matchesSafely(CloneGroup cloneGroup) { // Check length if (expectedLen != cloneGroup.getCloneUnitLength()) { return false; } // Check number of parts if (expectedParts.length != cloneGroup.getCloneParts().size()) { return false; } // Check origin if (!expectedParts[0].equals(cloneGroup.getOriginPart())) { return false; } // Check parts for (ClonePart expectedPart : expectedParts) { boolean matched = false; for (ClonePart part : cloneGroup.getCloneParts()) { if (part.equals(expectedPart)) { matched = true; break; } } if (!matched) { return false; } } return true; } public void describeTo(Description description) { StringBuilder builder = new StringBuilder(); for (ClonePart part : expectedParts) { builder.append(part).append(" - "); } builder.append(expectedLen); description.appendText(builder.toString()); } }
2,651
30.571429
114
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/ContainsInComparatorTest.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.duplications.detector; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; import java.util.Comparator; import org.junit.Test; import org.sonar.duplications.index.ClonePart; public class ContainsInComparatorTest { @Test public void shouldCompareByResourceId() { Comparator<ClonePart> comparator = ContainsInComparator.RESOURCE_ID_COMPARATOR; assertThat(comparator.compare(newClonePart("a", 0), newClonePart("b", 0)), is(-1)); assertThat(comparator.compare(newClonePart("b", 0), newClonePart("a", 0)), is(1)); assertThat(comparator.compare(newClonePart("a", 0), newClonePart("a", 0)), is(0)); } @Test public void shouldCompareByResourceIdAndUnitStart() { Comparator<ClonePart> comparator = ContainsInComparator.CLONEPART_COMPARATOR; assertThat(comparator.compare(newClonePart("a", 0), newClonePart("b", 0)), is(-1)); assertThat(comparator.compare(newClonePart("b", 0), newClonePart("a", 0)), is(1)); assertThat(comparator.compare(newClonePart("a", 0), newClonePart("a", 0)), is(0)); assertThat(comparator.compare(newClonePart("a", 0), newClonePart("a", 1)), is(-1)); assertThat(comparator.compare(newClonePart("a", 1), newClonePart("a", 0)), is(1)); } @Test public void shouldCompare() { assertThat(compare("a", 0, 0, "b", 0, 0), is(-1)); assertThat(compare("b", 0, 0, "a", 0, 0), is(1)); assertThat(compare("a", 0, 0, "a", 0, 0), is(0)); assertThat(compare("a", 1, 0, "a", 0, 0), is(1)); assertThat(compare("a", 0, 0, "a", 0, 1), is(-1)); } private static int compare(String resourceId1, int start1, int end1, String resourceId2, int start2, int end2) { return new ContainsInComparator(end1 - start1, end2 - start2) .compare(newClonePart(resourceId1, start1), newClonePart(resourceId2, start2)); } private static ClonePart newClonePart(String resourceId, int unitStart) { return new ClonePart(resourceId, unitStart, 0, 0); } }
2,828
38.84507
114
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/DetectorTestCase.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.duplications.detector; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.sonar.duplications.block.Block; import org.sonar.duplications.block.ByteArray; import org.sonar.duplications.index.CloneGroup; import org.sonar.duplications.index.CloneIndex; import org.sonar.duplications.index.ClonePart; import org.sonar.duplications.index.MemoryCloneIndex; import org.sonar.duplications.junit.TestNamePrinter; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.sonar.duplications.detector.CloneGroupMatcher.hasCloneGroup; public abstract class DetectorTestCase { @Rule public TestNamePrinter testNamePrinter = new TestNamePrinter(); protected static int LINES_PER_BLOCK = 5; /** * To simplify testing we assume that each block starts from a new line and contains {@link #LINES_PER_BLOCK} lines, * so we can simply use index and hash. */ protected static Block newBlock(String resourceId, ByteArray hash, int index) { return Block.builder() .setResourceId(resourceId) .setBlockHash(hash) .setIndexInFile(index) .setLines(index, index + LINES_PER_BLOCK) .build(); } protected static ClonePart newClonePart(String resourceId, int unitStart, int cloneUnitLength) { return new ClonePart(resourceId, unitStart, unitStart, unitStart + cloneUnitLength + LINES_PER_BLOCK - 1); } protected abstract List<CloneGroup> detect(CloneIndex index, Block[] fileBlocks); /** * Given: * <pre> * y: 2 3 4 5 * z: 3 4 * x: 1 2 3 4 5 6 * </pre> * Expected: * <pre> * x-y (2 3 4 5) * x-y-z (3 4) * </pre> */ @Test public void exampleFromPaper() { CloneIndex index = createIndex( newBlocks("y", "2 3 4 5"), newBlocks("z", "3 4")); Block[] fileBlocks = newBlocks("x", "1 2 3 4 5 6"); List<CloneGroup> result = detect(index, fileBlocks); print(result); assertEquals(2, result.size()); assertThat(result, hasCloneGroup(4, newClonePart("x", 1, 4), newClonePart("y", 0, 4))); assertThat(result, hasCloneGroup(2, newClonePart("x", 2, 2), newClonePart("y", 1, 2), newClonePart("z", 0, 2))); } /** * Given: * <pre> * a: 2 3 4 5 * b: 3 4 * c: 1 2 3 4 5 6 * </pre> * Expected: * <pre> * c-a (2 3 4 5) * c-a-b (3 4) * </pre> */ @Test public void exampleFromPaperWithModifiedResourceIds() { CloneIndex cloneIndex = createIndex( newBlocks("a", "2 3 4 5"), newBlocks("b", "3 4")); Block[] fileBlocks = newBlocks("c", "1 2 3 4 5 6"); List<CloneGroup> clones = detect(cloneIndex, fileBlocks); print(clones); assertThat(clones.size(), is(2)); assertThat(clones, hasCloneGroup(4, newClonePart("c", 1, 4), newClonePart("a", 0, 4))); assertThat(clones, hasCloneGroup(2, newClonePart("c", 2, 2), newClonePart("a", 1, 2), newClonePart("b", 0, 2))); } /** * Given: * <pre> * b: 3 4 5 6 * c: 5 6 7 * a: 1 2 3 4 5 6 7 8 9 * </pre> * Expected: * <pre> * a-b (3 4 5 6) * a-b-c (5 6) * a-c (5 6 7) * </pre> */ @Test public void example1() { CloneIndex index = createIndex( newBlocks("b", "3 4 5 6"), newBlocks("c", "5 6 7")); Block[] fileBlocks = newBlocks("a", "1 2 3 4 5 6 7 8 9"); List<CloneGroup> result = detect(index, fileBlocks); print(result); assertThat(result.size(), is(3)); assertThat(result, hasCloneGroup(4, newClonePart("a", 2, 4), newClonePart("b", 0, 4))); assertThat(result, hasCloneGroup(3, newClonePart("a", 4, 3), newClonePart("c", 0, 3))); assertThat(result, hasCloneGroup(2, newClonePart("a", 4, 2), newClonePart("b", 2, 2), newClonePart("c", 0, 2))); } /** * Given: * <pre> * b: 1 2 3 4 1 2 3 4 1 2 3 4 * c: 1 2 3 4 * a: 1 2 3 5 * </pre> * Expected: * <pre> * a-b-b-b-c (1 2 3) * </pre> */ @Test public void example2() { CloneIndex index = createIndex( newBlocks("b", "1 2 3 4 1 2 3 4 1 2 3 4"), newBlocks("c", "1 2 3 4")); Block[] fileBlocks = newBlocks("a", "1 2 3 5"); List<CloneGroup> result = detect(index, fileBlocks); print(result); assertThat(result.size(), is(1)); assertThat(result, hasCloneGroup(3, newClonePart("a", 0, 3), newClonePart("b", 0, 3), newClonePart("b", 4, 3), newClonePart("b", 8, 3), newClonePart("c", 0, 3))); } /** * Test for problem, which was described in original paper - same clone would be reported twice. * Given: * <pre> * a: 1 2 3 1 2 4 * </pre> * Expected only one clone: * <pre> * a-a (1 2) * </pre> */ @Test public void clonesInFileItself() { CloneIndex index = createIndex(); Block[] fileBlocks = newBlocks("a", "1 2 3 1 2 4"); List<CloneGroup> result = detect(index, fileBlocks); print(result); assertThat(result.size(), is(1)); assertThat(result, hasCloneGroup(2, newClonePart("a", 0, 2), newClonePart("a", 3, 2))); } /** * Given: * <pre> * b: 1 2 1 2 * a: 1 2 1 * </pre> * Expected: * <pre> * a-b-b (1 2) * a-b (1 2 1) * </pre> * "a-a-b-b (1)" should not be reported, because fully covered by "a-b (1 2 1)" */ @Test public void covered() { CloneIndex index = createIndex( newBlocks("b", "1 2 1 2")); Block[] fileBlocks = newBlocks("a", "1 2 1"); List<CloneGroup> result = detect(index, fileBlocks); print(result); assertThat(result.size(), is(2)); assertThat(result, hasCloneGroup(3, newClonePart("a", 0, 3), newClonePart("b", 0, 3))); assertThat(result, hasCloneGroup(2, newClonePart("a", 0, 2), newClonePart("b", 0, 2), newClonePart("b", 2, 2))); } /** * Given: * <pre> * b: 1 2 1 2 1 2 1 * a: 1 2 1 2 1 2 * </pre> * Expected: * <pre> * a-b-b (1 2 1 2 1) - note that there is overlapping among parts for "b" * a-b (1 2 1 2 1 2) * </pre> */ @Test public void problemWithNestedCloneGroups() { CloneIndex index = createIndex( newBlocks("b", "1 2 1 2 1 2 1")); Block[] fileBlocks = newBlocks("a", "1 2 1 2 1 2"); List<CloneGroup> result = detect(index, fileBlocks); print(result); assertThat(result.size(), is(2)); assertThat(result, hasCloneGroup(6, newClonePart("a", 0, 6), newClonePart("b", 0, 6))); assertThat(result, hasCloneGroup(5, newClonePart("a", 0, 5), newClonePart("b", 0, 5), newClonePart("b", 2, 5))); } /** * Given: * <pre> * a: 1 2 3 * b: 1 2 4 * a: 1 2 5 * </pre> * Expected: * <pre> * a-b (1 2) - instead of "a-a-b", which will be the case if file from index not ignored * </pre> */ @Test public void fileAlreadyInIndex() { CloneIndex index = createIndex( newBlocks("a", "1 2 3"), newBlocks("b", "1 2 4")); // Note about blocks with hashes "3", "4" and "5": those blocks here in order to not face another problem - with EOF (see separate test) Block[] fileBlocks = newBlocks("a", "1 2 5"); List<CloneGroup> result = detect(index, fileBlocks); print(result); assertThat(result.size(), is(1)); assertThat(result, hasCloneGroup(2, newClonePart("a", 0, 2), newClonePart("b", 0, 2))); } /** * Given: file with repeated hashes * Expected: only one query of index for each unique hash */ @Test public void only_one_query_of_index_for_each_unique_hash() { CloneIndex index = spy(createIndex()); Block[] fileBlocks = newBlocks("a", "1 2 1 2"); detect(index, fileBlocks); verify(index).getBySequenceHash(new ByteArray("01")); verify(index).getBySequenceHash(new ByteArray("02")); verifyNoMoreInteractions(index); } /** * Given: empty list of blocks for file * Expected: {@link Collections#EMPTY_LIST} */ @Test public void shouldReturnEmptyListWhenNoBlocksForFile() { List<CloneGroup> result = detect(null, new Block[0]); assertThat(result, sameInstance(Collections.EMPTY_LIST)); } /** * Given: * <pre> * b: 1 2 3 4 * a: 1 2 3 * </pre> * Expected clone which ends at the end of file "a": * <pre> * a-b (1 2 3) * </pre> */ @Test public void problemWithEndOfFile() { CloneIndex cloneIndex = createIndex( newBlocks("b", "1 2 3 4")); Block[] fileBlocks = newBlocks("a", "1 2 3"); List<CloneGroup> clones = detect(cloneIndex, fileBlocks); print(clones); assertThat(clones.size(), is(1)); assertThat(clones, hasCloneGroup(3, newClonePart("a", 0, 3), newClonePart("b", 0, 3))); } /** * Given file with two lines, containing following statements: * <pre> * 0: A,B,A,B * 1: A,B,A * </pre> * with block size 5 each block will span both lines, and hashes will be: * <pre> * A,B,A,B,A=1 * B,A,B,A,B=2 * A,B,A,B,A=1 * </pre> * Expected: one clone with two parts, which contain exactly the same lines */ @Test public void same_lines_but_different_indexes() { CloneIndex cloneIndex = createIndex(); Block.Builder block = Block.builder() .setResourceId("a") .setLines(0, 1); Block[] fileBlocks = new Block[] { block.setBlockHash(new ByteArray("1".getBytes())).setIndexInFile(0).build(), block.setBlockHash(new ByteArray("2".getBytes())).setIndexInFile(1).build(), block.setBlockHash(new ByteArray("1".getBytes())).setIndexInFile(2).build() }; List<CloneGroup> clones = detect(cloneIndex, fileBlocks); print(clones); assertThat(clones.size(), is(1)); Iterator<CloneGroup> clonesIterator = clones.iterator(); CloneGroup clone = clonesIterator.next(); assertThat(clone.getCloneUnitLength(), is(1)); assertThat(clone.getCloneParts().size(), is(2)); assertThat(clone.getOriginPart(), is(new ClonePart("a", 0, 0, 1))); assertThat(clone.getCloneParts(), hasItem(new ClonePart("a", 0, 0, 1))); assertThat(clone.getCloneParts(), hasItem(new ClonePart("a", 2, 0, 1))); } protected static void print(List<CloneGroup> clones) { for (CloneGroup clone : clones) { System.out.println(clone); } System.out.println(); } protected static Block[] newBlocks(String resourceId, String hashes) { List<Block> result = new ArrayList<>(); int indexInFile = 0; for (int i = 0; i < hashes.length(); i += 2) { Block block = newBlock(resourceId, new ByteArray("0" + hashes.charAt(i)), indexInFile); result.add(block); indexInFile++; } return result.toArray(new Block[result.size()]); } protected static CloneIndex createIndex(Block[]... blocks) { CloneIndex cloneIndex = new MemoryCloneIndex(); for (Block[] b : blocks) { for (Block block : b) { cloneIndex.insert(block); } } return cloneIndex; } }
12,254
26.354911
140
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/original/BlocksGroupTest.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.duplications.detector.original; import java.util.Arrays; import org.junit.Test; import org.sonar.duplications.block.Block; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class BlocksGroupTest { /** * {@link BlocksGroup} uses only resourceId and index from block, thus we can simplify testing. */ private static Block newBlock(String resourceId, int indexInFile) { return Block.builder() .setResourceId(resourceId) .setIndexInFile(indexInFile) .setLines(indexInFile, indexInFile) .build(); } public static BlocksGroup newBlocksGroup(Block... blocks) { BlocksGroup result = BlocksGroup.empty(); result.blocks.addAll(Arrays.asList(blocks)); return result; } @Test public void shouldReturnSize() { BlocksGroup group = newBlocksGroup(newBlock("a", 1), newBlock("b", 2)); assertThat(group.size(), is(2)); } @Test public void shouldCreateEmptyGroup() { assertThat(BlocksGroup.empty().size(), is(0)); } @Test public void testSubsumedBy() { BlocksGroup group1 = newBlocksGroup(newBlock("a", 1), newBlock("b", 2)); BlocksGroup group2 = newBlocksGroup(newBlock("a", 2), newBlock("b", 3), newBlock("c", 4)); // block "c" from group2 does not have corresponding block in group1 assertThat(group2.subsumedBy(group1, 1), is(false)); } @Test public void testSubsumedBy2() { BlocksGroup group1 = newBlocksGroup(newBlock("a", 1), newBlock("b", 2)); BlocksGroup group2 = newBlocksGroup(newBlock("a", 2), newBlock("b", 3)); BlocksGroup group3 = newBlocksGroup(newBlock("a", 3), newBlock("b", 4)); BlocksGroup group4 = newBlocksGroup(newBlock("a", 4), newBlock("b", 5)); assertThat(group2.subsumedBy(group1, 1), is(true)); // correction of index - 1 assertThat(group3.subsumedBy(group1, 2), is(true)); // correction of index - 2 assertThat(group3.subsumedBy(group2, 1), is(true)); // correction of index - 1 assertThat(group4.subsumedBy(group1, 3), is(true)); // correction of index - 3 assertThat(group4.subsumedBy(group2, 2), is(true)); // correction of index - 2 assertThat(group4.subsumedBy(group3, 1), is(true)); // correction of index - 1 } @Test public void testIntersect() { BlocksGroup group1 = newBlocksGroup(newBlock("a", 1), newBlock("b", 2)); BlocksGroup group2 = newBlocksGroup(newBlock("a", 2), newBlock("b", 3)); BlocksGroup intersection = group1.intersect(group2); assertThat(intersection.size(), is(2)); } /** * Results for this test taken from results of work of naive implementation. */ @Test public void testSubsumedBy3() { // ['a'[2|2-7]:3, 'b'[0|0-5]:3] subsumedBy ['a'[1|1-6]:2] false assertThat(newBlocksGroup(newBlock("a", 2), newBlock("b", 0)) .subsumedBy(newBlocksGroup(newBlock("a", 1)), 1), is(false)); // ['a'[3|3-8]:4, 'b'[1|1-6]:4] subsumedBy ['a'[1|1-6]:2] false assertThat(newBlocksGroup(newBlock("a", 3), newBlock("b", 1)) .subsumedBy(newBlocksGroup(newBlock("a", 1)), 1), is(false)); // ['a'[4|4-9]:5, 'b'[2|2-7]:5] subsumedBy ['a'[1|1-6]:2] false assertThat(newBlocksGroup(newBlock("a", 4), newBlock("b", 2)) .subsumedBy(newBlocksGroup(newBlock("a", 1)), 1), is(false)); // ['a'[5|5-10]:6, 'b'[3|3-8]:6] subsumedBy ['a'[1|1-6]:2] false assertThat(newBlocksGroup(newBlock("a", 5), newBlock("b", 3)) .subsumedBy(newBlocksGroup(newBlock("a", 1)), 1), is(false)); // ['a'[3|3-8]:4, 'b'[1|1-6]:4] subsumedBy ['a'[2|2-7]:3, 'b'[0|0-5]:3] true assertThat(newBlocksGroup(newBlock("a", 3), newBlock("b", 1)) .subsumedBy(newBlocksGroup(newBlock("a", 2), newBlock("b", 0)), 1), is(true)); // ['a'[4|4-9]:5, 'b'[2|2-7]:5, 'c'[0|0-5]:5] subsumedBy ['a'[3|3-8]:4, 'b'[1|1-6]:4] false assertThat(newBlocksGroup(newBlock("a", 4), newBlock("b", 2), newBlock("c", 0)) .subsumedBy(newBlocksGroup(newBlock("a", 3), newBlock("b", 1)), 1), is(false)); // ['a'[5|5-10]:6, 'b'[3|3-8]:6, 'c'[1|1-6]:6] subsumedBy ['a'[3|3-8]:4, 'b'[1|1-6]:4] false assertThat(newBlocksGroup(newBlock("a", 5), newBlock("b", 3), newBlock("c", 1)) .subsumedBy(newBlocksGroup(newBlock("a", 3), newBlock("b", 1)), 1), is(false)); // ['a'[6|6-11]:7, 'c'[2|2-7]:7] subsumedBy ['a'[3|3-8]:4, 'b'[1|1-6]:4] false assertThat(newBlocksGroup(newBlock("a", 6), newBlock("c", 2)) .subsumedBy(newBlocksGroup(newBlock("a", 3), newBlock("b", 1)), 1), is(false)); // ['a'[5|5-10]:6, 'b'[3|3-8]:6, 'c'[1|1-6]:6] subsumedBy ['a'[4|4-9]:5, 'b'[2|2-7]:5, 'c'[0|0-5]:5] true assertThat(newBlocksGroup(newBlock("a", 5), newBlock("b", 3), newBlock("c", 1)) .subsumedBy(newBlocksGroup(newBlock("a", 4), newBlock("b", 2), newBlock("c", 0)), 1), is(true)); // ['a'[6|6-11]:7, 'c'[2|2-7]:7] subsumedBy ['a'[5|5-10]:6, 'b'[3|3-8]:6, 'c'[1|1-6]:6] true assertThat(newBlocksGroup(newBlock("a", 6), newBlock("c", 2)) .subsumedBy(newBlocksGroup(newBlock("a", 5), newBlock("b", 3), newBlock("c", 1)), 1), is(true)); } /** * Results for this test taken from results of work of naive implementation. */ @Test public void testIntersect2() { // ['a'[2|2-7]:3, 'b'[0|0-5]:3] // intersect ['a'[3|3-8]:4, 'b'[1|1-6]:4] // as ['a'[3|3-8]:4, 'b'[1|1-6]:4] assertThat(newBlocksGroup(newBlock("a", 2), newBlock("b", 0)) .intersect(newBlocksGroup(newBlock("a", 3), newBlock("b", 1))) .size(), is(2)); // ['a'[3|3-8]:4, 'b'[1|1-6]:4] // intersect ['a'[4|4-9]:5, 'b'[2|2-7]:5, 'c'[0|0-5]:5] // as ['a'[4|4-9]:5, 'b'[2|2-7]:5] assertThat(newBlocksGroup(newBlock("a", 3), newBlock("b", 1)) .intersect(newBlocksGroup(newBlock("a", 4), newBlock("b", 2), newBlock("c", 0))) .size(), is(2)); // ['a'[4|4-9]:5, 'b'[2|2-7]:5] // intersect ['a'[5|5-10]:6, 'b'[3|3-8]:6, 'c'[1|1-6]:6] // as ['a'[5|5-10]:6, 'b'[3|3-8]:6] assertThat(newBlocksGroup(newBlock("a", 4), newBlock("b", 2)) .intersect(newBlocksGroup(newBlock("a", 5), newBlock("b", 3), newBlock("c", 1))) .size(), is(2)); // ['a'[5|5-10]:6, 'b'[3|3-8]:6] // intersect ['a'[6|6-11]:7, 'c'[2|2-7]:7] // as ['a'[6|6-11]:7] assertThat(newBlocksGroup(newBlock("a", 5), newBlock("b", 3)) .intersect(newBlocksGroup(newBlock("a", 6), newBlock("c", 2))) .size(), is(1)); // ['a'[4|4-9]:5, 'b'[2|2-7]:5, 'c'[0|0-5]:5] // intersect ['a'[5|5-10]:6, 'b'[3|3-8]:6, 'c'[1|1-6]:6] // as ['a'[5|5-10]:6, 'b'[3|3-8]:6, 'c'[1|1-6]:6] assertThat(newBlocksGroup(newBlock("a", 4), newBlock("b", 2), newBlock("c", 0)) .intersect(newBlocksGroup(newBlock("a", 5), newBlock("b", 3), newBlock("c", 1))) .size(), is(3)); // ['a'[5|5-10]:6, 'b'[3|3-8]:6, 'c'[1|1-6]:6] // intersect ['a'[6|6-11]:7, 'c'[2|2-7]:7] // as ['a'[6|6-11]:7, 'c'[2|2-7]:7] assertThat(newBlocksGroup(newBlock("a", 5), newBlock("b", 3), newBlock("c", 1)) .intersect(newBlocksGroup(newBlock("a", 6), newBlock("c", 2))) .size(), is(2)); // ['a'[6|6-11]:7, 'c'[2|2-7]:7] // intersect ['a'[7|7-12]:8] // as ['a'[7|7-12]:8] assertThat(newBlocksGroup(newBlock("a", 6), newBlock("c", 7)) .intersect(newBlocksGroup(newBlock("a", 7))) .size(), is(1)); } }
8,275
39.568627
109
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/original/FilterTest.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.duplications.detector.original; import org.junit.Test; import org.sonar.duplications.index.CloneGroup; import org.sonar.duplications.index.ClonePart; import java.util.Arrays; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.*; public class FilterTest { /** * Given: * <pre> * c1: a[1-1] * c2: a[1-1] * </pre> * Expected: * reflexive - c1 in c1, * antisymmetric - c1 in c2, c2 in c1, because c1 = c2 */ @Test public void reflexive_and_antisymmetric() { CloneGroup c1 = newCloneGroup(1, newClonePart("a", 1)); CloneGroup c2 = newCloneGroup(1, newClonePart("a", 1)); assertThat(Filter.containsIn(c1, c1), is(true)); assertThat(Filter.containsIn(c1, c2), is(true)); assertThat(Filter.containsIn(c2, c1), is(true)); } /** * Given: * <pre> * c1: a[1-1] * c2: a[2-2] * </pre> * Expected: c1 not in c2, c2 not in c1 */ @Test public void start_index_in_C1_less_than_in_C2() { CloneGroup c1 = newCloneGroup(1, newClonePart("a", 1)); CloneGroup c2 = newCloneGroup(1, newClonePart("a", 2)); assertThat(Filter.containsIn(c1, c2), is(false)); } /** * Given: * <pre> * c1: a[0-0], a[2-2], b[0-0], b[2-2] * c2: a[0-2], b[0-2] * </pre> * Expected: * <pre> * c1 in c2 (all parts of c1 covered by parts of c2 and all resources the same) * c2 not in c1 (not all parts of c2 covered by parts of c1 and all resources the same) * </pre> */ @Test public void one_part_of_C2_covers_two_parts_of_C1() { // Note that line numbers don't matter for method which we test. CloneGroup c1 = newCloneGroup(1, newClonePart("a", 0), newClonePart("a", 2), newClonePart("b", 0), newClonePart("b", 2)); CloneGroup c2 = newCloneGroup(3, newClonePart("a", 0), newClonePart("b", 0)); assertThat(Filter.containsIn(c1, c2), is(true)); assertThat(Filter.containsIn(c2, c1), is(false)); } /** * Given: * <pre> * c1: a[0-0], a[2-2] * c2: a[0-2], b[0-2] * </pre> * Expected: * <pre> * c1 not in c2 (all parts of c1 covered by parts of c2, but different resources) * c2 not in c1 (not all parts of c2 covered by parts of c1 and different resources) * </pre> */ @Test public void different_resources() { CloneGroup c1 = newCloneGroup(1, newClonePart("a", 0), newClonePart("a", 2)); CloneGroup c2 = newCloneGroup(3, newClonePart("a", 0), newClonePart("b", 0)); assertThat(Filter.containsIn(c1, c2), is(false)); assertThat(Filter.containsIn(c2, c1), is(false)); } /** * Given: * <pre> * c1: a[2-2] * c2: a[0-1], a[2-3] * </pre> * Expected: * <pre> * c1 in c2 * c2 not in c1 * </pre> */ @Test public void second_part_of_C2_covers_first_part_of_C1() { CloneGroup c1 = newCloneGroup(1, newClonePart("a", 2)); CloneGroup c2 = newCloneGroup(2, newClonePart("a", 0), newClonePart("a", 2)); assertThat(Filter.containsIn(c1, c2), is(true)); assertThat(Filter.containsIn(c2, c1), is(false)); } /** * Given: * <pre> * c1: a[0-2] * c2: a[0-0] * </pre> * Expected: * <pre> * c1 not in c2 * </pre> */ @Test public void length_of_C1_bigger_than_length_of_C2() { CloneGroup c1 = spy(newCloneGroup(3, newClonePart("a", 0))); CloneGroup c2 = spy(newCloneGroup(1, newClonePart("a", 0))); assertThat(Filter.containsIn(c1, c2), is(false)); // containsIn method should check only origin and length - no need to compare all parts verify(c1).getCloneUnitLength(); verify(c2).getCloneUnitLength(); verifyNoMoreInteractions(c1); verifyNoMoreInteractions(c2); } /** * Creates new part with specified resourceId and unitStart, and 0 for lineStart and lineEnd. */ private ClonePart newClonePart(String resourceId, int unitStart) { return new ClonePart(resourceId, unitStart, 0, 0); } /** * Creates new group from list of parts, origin - is a first part from list. */ private CloneGroup newCloneGroup(int len, ClonePart... parts) { return CloneGroup.builder().setLength(len).setOrigin(parts[0]).setParts(Arrays.asList(parts)).build(); } }
5,235
26.270833
106
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/original/OriginalCloneDetectionAlgorithmTest.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.duplications.detector.original; import java.util.Arrays; import java.util.List; import org.sonar.duplications.block.Block; import org.sonar.duplications.detector.DetectorTestCase; import org.sonar.duplications.index.CloneGroup; import org.sonar.duplications.index.CloneIndex; public class OriginalCloneDetectionAlgorithmTest extends DetectorTestCase { @Override protected List<CloneGroup> detect(CloneIndex index, Block[] fileBlocks) { return OriginalCloneDetectionAlgorithm.detect(index, Arrays.asList(fileBlocks)); } }
1,397
35.789474
84
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/suffixtree/StringSuffixTree.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.duplications.detector.suffixtree; import java.util.LinkedList; import java.util.Objects; import java.util.Queue; public class StringSuffixTree { private final SuffixTree suffixTree; private int numberOfEdges; private int numberOfInnerNodes; private int numberOfLeaves; public static StringSuffixTree create(String text) { return new StringSuffixTree(text); } private StringSuffixTree(String text) { suffixTree = SuffixTree.create(new StringText(text)); Queue<Node> queue = new LinkedList<>(); queue.add(suffixTree.getRootNode()); while (!queue.isEmpty()) { Node node = queue.remove(); if (node.getEdges().isEmpty()) { numberOfLeaves++; } else { numberOfInnerNodes++; for (Edge edge : node.getEdges()) { numberOfEdges++; queue.add(edge.getEndNode()); } } } numberOfInnerNodes--; // without root } public int getNumberOfEdges() { return numberOfEdges; } public int getNumberOfInnerNodes() { return numberOfInnerNodes; } // FIXME should be renamed getNumberOfLeaves() public int getNumberOfLeafs() { return numberOfLeaves; } public int indexOf(String str) { return indexOf(suffixTree, new StringText(str)); } public boolean contains(String str) { return contains(suffixTree, new StringText(str)); } public SuffixTree getSuffixTree() { return suffixTree; } public static boolean contains(SuffixTree tree, Text str) { return indexOf(tree, str) >= 0; } public static int indexOf(SuffixTree tree, Text str) { if (str.length() == 0) { return -1; } int index = -1; Node node = tree.getRootNode(); int i = 0; while (i < str.length()) { if (node == null) { return -1; } if (i == tree.text.length()) { return -1; } Edge edge = node.findEdge(str.symbolAt(i)); if (edge == null) { return -1; } index = edge.getBeginIndex() - i; i++; for (int j = edge.getBeginIndex() + 1; j <= edge.getEndIndex(); j++) { if (i == str.length()) { break; } if (!Objects.equals(tree.symbolAt(j), str.symbolAt(i))) { return -1; } i++; } node = edge.getEndNode(); } return index; } }
3,205
24.444444
76
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/suffixtree/StringText.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.duplications.detector.suffixtree; import org.sonar.duplications.detector.suffixtree.AbstractText; import org.sonar.duplications.detector.suffixtree.Text; /** * Implementation of {@link Text} based on {@link String}. */ public class StringText extends AbstractText { public StringText(String text) { super(text.length()); for (int i = 0; i < text.length(); i++) { symbols.add(Character.valueOf(text.charAt(i))); } } }
1,306
33.394737
75
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/suffixtree/SuffixTreeCloneDetectionAlgorithmTest.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.duplications.detector.suffixtree; import org.junit.Test; import org.sonar.duplications.block.Block; import org.sonar.duplications.block.ByteArray; import org.sonar.duplications.detector.DetectorTestCase; import org.sonar.duplications.index.CloneGroup; import org.sonar.duplications.index.CloneIndex; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.hamcrest.CoreMatchers.sameInstance; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.sonar.duplications.detector.CloneGroupMatcher.hasCloneGroup; public class SuffixTreeCloneDetectionAlgorithmTest extends DetectorTestCase { /** * Given: file without duplications * Expected: {@link Collections#EMPTY_LIST} (no need to construct suffix-tree) */ @Test public void noDuplications() { CloneIndex index = createIndex(); Block[] fileBlocks = newBlocks("a", "1 2 3"); List<CloneGroup> result = detect(index, fileBlocks); assertThat(result, sameInstance(Collections.EMPTY_LIST)); } /** * See SONAR-3060 * <p> * In case when file contains a lot of duplicated blocks suffix-tree works better than original algorithm, * which works more than 5 minutes for this example. * </p><p> * However should be noted that current implementation with suffix-tree also is not optimal, * even if it works for this example couple of seconds, * because duplications should be filtered in order to remove fully-covered. * But such cases nearly never appear in real-world, so current implementation is acceptable for the moment. * </p> */ @Test public void huge() { CloneIndex index = createIndex(); Block[] fileBlocks = new Block[5000]; for (int i = 0; i < 5000; i++) { fileBlocks[i] = newBlock("x", new ByteArray("01"), i); } List<CloneGroup> result = detect(index, fileBlocks); assertEquals(1, result.size()); } /** * Given: * <pre> * x: a 2 b 2 c 2 2 2 * </pre> * Expected: * <pre> * x-x (2 2) * x-x-x-x-x (2) * <pre> * TODO Godin: however would be better to receive only (2) */ @Test public void myTest() { CloneIndex index = createIndex(); Block[] fileBlocks = newBlocks("x", "a 2 b 2 c 2 2 2"); List<CloneGroup> result = detect(index, fileBlocks); print(result); assertEquals(2, result.size()); assertThat(result, hasCloneGroup(2, newClonePart("x", 5, 2), newClonePart("x", 6, 2))); assertThat(result, hasCloneGroup(1, newClonePart("x", 1, 1), newClonePart("x", 3, 1), newClonePart("x", 5, 1), newClonePart("x", 6, 1), newClonePart("x", 7, 1))); } /** * This test and associated with it suffix-tree demonstrates that without filtering in {@link DuplicationsCollector#endOfGroup()} * possible to construct {@link CloneGroup}, which is fully covered by another {@link CloneGroup}. * * Given: * <pre> * x: a 2 3 b 2 3 c 2 3 d 2 3 2 3 2 3 * </pre> * Expected: * <pre> * x-x (2 3 2 3) * x-x-x-x-x-x (2 3) * <pre> * TODO Godin: however would be better to receive only (2 3) */ @Test public void myTest2() { CloneIndex index = createIndex(); Block[] fileBlocks = newBlocks("x", "a 2 3 b 2 3 c 2 3 d 2 3 2 3 2 3"); List<CloneGroup> result = detect(index, fileBlocks); print(result); assertEquals(2, result.size()); assertThat(result, hasCloneGroup(4, newClonePart("x", 10, 4), newClonePart("x", 12, 4))); assertThat(result, hasCloneGroup(2, newClonePart("x", 1, 2), newClonePart("x", 4, 2), newClonePart("x", 7, 2), newClonePart("x", 10, 2), newClonePart("x", 12, 2), newClonePart("x", 14, 2))); } /** * This test and associated with it suffix-tree demonstrates that without check of origin in {@link Search} * possible to construct {@link CloneGroup} with a wrong origin. * * Given: * <pre> * a: 1 2 3 4 * b: 4 3 2 * c: 4 3 1 * </pre> * Expected: * <pre> * a-c (1) * a-b (2) * a-b-c (3) * a-b-c (4) * <pre> */ @Test public void myTest3() { CloneIndex index = createIndex( newBlocks("b", "4 3 2"), newBlocks("c", "4 3 1") ); Block[] fileBlocks = newBlocks("a", "1 2 3 4"); List<CloneGroup> result = detect(index, fileBlocks); print(result); assertEquals(4, result.size()); assertThat(result, hasCloneGroup(1, newClonePart("a", 0, 1), newClonePart("c", 2, 1))); assertThat(result, hasCloneGroup(1, newClonePart("a", 1, 1), newClonePart("b", 2, 1))); assertThat(result, hasCloneGroup(1, newClonePart("a", 2, 1), newClonePart("b", 1, 1), newClonePart("c", 1, 1))); assertThat(result, hasCloneGroup(1, newClonePart("a", 3, 1), newClonePart("b", 0, 1), newClonePart("c", 0, 1))); } @Override protected List<CloneGroup> detect(CloneIndex index, Block[] fileBlocks) { return SuffixTreeCloneDetectionAlgorithm.detect(index, Arrays.asList(fileBlocks)); } }
6,037
29.039801
131
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/suffixtree/SuffixTreeTest.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.duplications.detector.suffixtree; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.Arrays; import java.util.Collection; import static org.assertj.core.api.Assertions.assertThat; @RunWith(Parameterized.class) public class SuffixTreeTest { @Parameters public static Collection<Object[]> generateData() { return Arrays.asList(new Object[][] { {"banana"}, {"mississippi"}, {"book"}, {"bookke"}, {"cacao"}, {"googol"}, {"abababc"}, {"aaaaa"}}); } private final String data; public SuffixTreeTest(String data) { this.data = data; } @Test public void test() { String text = this.data + "$"; StringSuffixTree tree = StringSuffixTree.create(text); assertThat(tree.getNumberOfLeafs()).as("number of leaves").isEqualTo(text.length()); assertThat(tree.getNumberOfInnerNodes()).as("number of inner nodes").isLessThan(text.length() - 1); assertThat(tree.getNumberOfEdges()).as("number of edges").isEqualTo(tree.getNumberOfInnerNodes() + tree.getNumberOfLeafs()); for (int beginIndex = 0; beginIndex < text.length(); beginIndex++) { for (int endIndex = beginIndex + 1; endIndex < text.length() + 1; endIndex++) { String substring = text.substring(beginIndex, endIndex); assertThat(tree.indexOf(substring)).as("index of " + substring + " in " + text).isEqualTo(text.indexOf(substring)); } } } }
2,348
35.703125
141
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/detector/suffixtree/TextSetTest.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.duplications.detector.suffixtree; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class TextSetTest { @Test public void test_terminator_equals() { TextSet.Terminator terminator = new TextSet.Terminator(1); assertThat(terminator) .isEqualTo(terminator) .isNotEqualTo(null) .isNotEqualTo(new TextSet.Terminator(0)) .isEqualTo(new TextSet.Terminator(1)); } }
1,300
32.358974
75
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/index/CloneGroupTest.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.duplications.index; import java.util.List; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class CloneGroupTest { @Test public void test_equals() { ClonePart clone = new ClonePart("id", 1, 1, 2); CloneGroup group = composeGroup(1, 1, clone, List.of(clone)); assertThat(group) .isEqualTo(group) .isNotEqualTo(null) .isNotEqualTo(new Object()) .isNotEqualTo(composeGroup(1, 1, clone, List.of())) .isNotEqualTo(composeGroup(1, 1, new ClonePart("", 1, 1, 2), List.of(clone))) .isNotEqualTo(composeGroup(0, 1, clone, List.of(clone))) .isEqualTo(composeGroup(1, 1, clone, List.of(new ClonePart("id", 1, 1, 2)))); } private static CloneGroup composeGroup(int length, int lengthInUnits, ClonePart origin, List<ClonePart> parts) { return CloneGroup.builder() .setLength(length) .setLengthInUnits(lengthInUnits) .setOrigin(origin) .setParts(parts) .build(); } }
1,858
34.075472
114
java
sonarqube
sonarqube-master/sonar-duplications/src/test/java/org/sonar/duplications/index/ClonePartTest.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.duplications.index; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ClonePartTest { @Test public void test_equals() { ClonePart part = new ClonePart("id_1", 1, 2, 3); assertThat(part) .isEqualTo(part) .isNotEqualTo(null) .isNotEqualTo(new Object()) .isNotEqualTo(new ClonePart("id_1", 1, 2, 0)) .isNotEqualTo(new ClonePart("id_1", 1, 0, 3)) .isNotEqualTo(new ClonePart("id_1", 0, 2, 3)) .isNotEqualTo(new ClonePart("id_2", 1, 2, 3)) .isEqualTo(new ClonePart("id_1", 1, 2, 3)); } }
1,455
32.860465
75
java