Skip to main content
aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAndrey Loskutov2021-07-03 12:22:46 +0000
committerAndrey Loskutov2021-07-03 13:49:40 +0000
commitc76360ce103b080113533446245f1cc293f0a2fb (patch)
tree5ec08f1e09d963f555062fb555ca36faf1557f54
parent9caccf56f3e879b209fa461aabf64754fac603ca (diff)
downloadeclipse.jdt.core-c76360ce103b080113533446245f1cc293f0a2fb.tar.gz
eclipse.jdt.core-c76360ce103b080113533446245f1cc293f0a2fb.tar.xz
eclipse.jdt.core-c76360ce103b080113533446245f1cc293f0a2fb.zip
Bug 572978 - Remove "new index" tests
Change-Id: I9763e6de7c79f46d94080eb5e7a5fe730d7e5967 Signed-off-by: Andrey Loskutov <loskutov@gmx.de> Reviewed-on: https://git.eclipse.org/r/c/jdt/eclipse.jdt.core/+/182734 Tested-by: JDT Bot <jdt-bot@eclipse.org>
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/BTreeExpensiveTests.java60
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/BTreeTests.java267
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/ChunkWriterTests.java129
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/DatabaseTest.java337
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/DatabaseTestUtil.java77
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldBackPointerTest.java416
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldListTest.java323
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldOneToOneTest.java260
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/InheritenceTests.java247
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/LargeBlockTest.java409
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/Package.java80
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/RunIndexTests.java73
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/SearchKeyTests.java167
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/indexer/IndexerTest.java288
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/indexer/JavaIndexTestUtil.java27
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/BaseTestCase.java272
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/Package.java80
-rw-r--r--org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/ResourceHelper.java576
18 files changed, 0 insertions, 4088 deletions
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/BTreeExpensiveTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/BTreeExpensiveTests.java
deleted file mode 100644
index b06dd4380a..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/BTreeExpensiveTests.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2007, 2016 Symbian Software Systems and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Symbian - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import junit.framework.Test;
-
-/**
- * Tests which are too expensive to run as part of normal testing, but
- * should be run after B-tree related development.
- * <p>
- * The 'Full Checking' tests perform a full validation of the B-tree
- * invariants after each B-tree operation, and so are especially
- * expensive and cpu hungry.
- */
-public class BTreeExpensiveTests extends BTreeTests {
-
- public static Test suite() {
- return suite(BTreeExpensiveTests.class);
- }
-
- public void testBySortedSetMirror() throws Exception {
- sortedMirrorTest(100);
- }
-
- // @Override
- @Override
- public void testInsertion() throws Exception {
- super.testInsertion();
- }
-
- /*
- * N.B. Each of the following tests are quite expensive (i.e. > 10mins each on a 2Ghz machine)
- */
-
- public void testBySortedSetMirror1682762087() throws Exception {
- System.out.println("1682762087 Full Checking");
- trial(1682762087, true); // exposed bugs in 2a,b
- }
-
- public void testBySortedSetMirror322922974() throws Exception {
- System.out.println("322922974 Full Checking");
- trial(322922974, true); // exposed bugs in 3b(ii)
- }
-
- public void testBySortedSetMirror_588448152() throws Exception {
- System.out.println("-588448152 Full Checking");
- trial(-588448152, true); // exposed root-delete-on-merge problems
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/BTreeTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/BTreeTests.java
deleted file mode 100644
index b0a76df86a..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/BTreeTests.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2021 Symbian Software Systems and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Symbian - Initial implementation
- * Markus Schorn (Wind River Systems)
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import junit.framework.Test;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.tests.nd.util.BaseTestCase;
-import org.eclipse.jdt.internal.core.nd.Nd;
-import org.eclipse.jdt.internal.core.nd.db.BTree;
-import org.eclipse.jdt.internal.core.nd.db.Database;
-import org.eclipse.jdt.internal.core.nd.db.IBTreeComparator;
-import org.eclipse.jdt.internal.core.nd.db.IBTreeVisitor;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Random;
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-/**
- * Test insertion/deletion of records of a mock record type in a B-tree.
- *
- * @author aferguso
- */
-public class BTreeTests extends BaseTestCase {
- private static int DEBUG= 0;
- protected File dbFile;
- protected Nd nd;
- protected Database db;
- protected BTree btree;
- protected int rootRecord;
- protected IBTreeComparator comparator;
-
- public static Test suite() {
- return suite(BTreeTests.class);
- }
-
- // setUp is not used since we need to parameterize this method,
- // and invoke it multiple times per Junit test
- protected void init(int degree) throws Exception {
- this.dbFile = File.createTempFile("ndtest", "db");
- this.nd = DatabaseTestUtil.createEmptyNd(getName());
- this.db = this.nd.getDB();
- this.db.setExclusiveLock();
- this.rootRecord = Database.DATA_AREA_OFFSET;
- this.comparator = new BTMockRecordComparator();
- this.btree = new BTree(this.nd, this.rootRecord, degree, this.comparator);
- }
-
- // tearDown is not used for the same reason as above
- protected void finish() throws Exception {
- this.db.close();
- this.dbFile.deleteOnExit();
- }
-
-
- public void testBySortedSetMirrorLite() throws Exception {
- sortedMirrorTest(8);
- }
-
- /**
- * Test random (but reproducible via known seed) sequences of insertions/deletions
- * and use TreeSet as a reference implementation to check behaviour against.
- * @throws Exception
- */
- protected void sortedMirrorTest(int noTrials) throws Exception {
- Random seeder = new Random(90210);
-
- for (int i = 0; i < noTrials; i++) {
- int seed = seeder.nextInt();
- if (DEBUG > 0)
- System.out.println("Iteration #" + i);
- trial(seed, false);
- }
- }
-
- /**
- * Test random (but reproducible via known seed) sequence of insertions
- * and use TreeSet as a reference implementation to check behaviour against.
- * @throws Exception
- */
- public void testInsertion() throws Exception {
- Random seeder = new Random();
-
- for (int i = 0; i < 6; i++) {
- int seed = seeder.nextInt();
- if (DEBUG > 0)
- System.out.println("Iteration #" + i);
- trialImp(seed, false, new Random(seed * 2), 1);
- }
- }
-
- /**
- * Bug 402177: BTree.insert should return the matching record if the new record was not inserted.
- */
- public void testEquivalentRecordInsert_Bug402177() throws Exception {
- init(8);
- try {
- BTMockRecord value1 = new BTMockRecord(this.db, 42);
- BTMockRecord value2 = new BTMockRecord(this.db, 42);
-
- long insert1 = this.btree.insert(value1.getRecord());
- long insert2 = this.btree.insert(value2.getRecord());
- assertEquals(insert1, insert2);
- } finally {
- finish();
- }
- }
-
- /**
- * Insert/Delete a random number of records into/from the B-tree
- * @param seed the seed for obtaining the deterministic random testing
- * @param checkCorrectnessEachIteration if true, then on every single insertion/deletion check that the B-tree invariants
- * still hold
- * @throws Exception
- */
- protected void trial(int seed, final boolean checkCorrectnessEachIteration) throws Exception {
- Random random = new Random(seed);
-
- // the probabilty that a particular iterations action will be an insertion
- double pInsert = Math.min(0.5 + random.nextDouble(), 1);
-
- trialImp(seed, checkCorrectnessEachIteration, random, pInsert);
- }
-
- private void trialImp(int seed, final boolean checkCorrectnessEachIteration, Random random,
- double pInsert) throws Exception {
- final int degree = 2 + random.nextInt(11);
- final int nIterations = random.nextInt(100000);
- final SortedSet<Integer> expected = new TreeSet<>();
- final List<BTMockRecord> history = new ArrayList<>();
-
- init(degree);
-
- if (DEBUG > 0)
- System.out.print("\t " + seed + " " + (nIterations/1000) + "K: ");
- for (int i = 0; i < nIterations; i++) {
- if (random.nextDouble() < pInsert) {
- Integer value = Integer.valueOf(random.nextInt(Integer.MAX_VALUE));
- boolean newEntry = expected.add(value);
- if (newEntry) {
- BTMockRecord btValue = new BTMockRecord(this.db, value.intValue());
- history.add(btValue);
- if (DEBUG > 1)
- System.out.println("Add: " + value + " @ " + btValue.record);
- this.btree.insert(btValue.getRecord());
- }
- } else {
- if (!history.isEmpty()) {
- int index = random.nextInt(history.size());
- BTMockRecord btValue = history.get(index);
- history.remove(index);
- expected.remove(Integer.valueOf(btValue.intValue()));
- if (DEBUG > 1)
- System.out.println("Remove: " + btValue.intValue() + " @ " + btValue.record);
- this.btree.delete(btValue.getRecord());
- }
- }
- if (i % 1000 == 0 && DEBUG > 0) {
- System.out.print(".");
- }
- if (checkCorrectnessEachIteration) {
- assertBTreeMatchesSortedSet("[iteration " + i + "] ", this.btree, expected);
- assertBTreeInvariantsHold("[iteration " + i + "] ");
- }
- }
- if (DEBUG > 0)
- System.out.println();
-
- assertBTreeMatchesSortedSet("[Trial end] ", this.btree, expected);
- assertBTreeInvariantsHold("[Trial end]");
-
- finish();
- }
-
- public void assertBTreeInvariantsHold(String msg) throws CoreException {
- String errorReport = this.btree.getInvariantsErrorReport();
- if (!errorReport.equals("")) {
- fail("Invariants do not hold: " + errorReport);
- }
- }
-
- public void assertBTreeMatchesSortedSet(final String msg, BTree actual, SortedSet<Integer> expected) throws CoreException {
- final Iterator<Integer> i = expected.iterator();
- this.btree.accept(new IBTreeVisitor() {
- int k;
- @Override
- public int compare(long record) {
- return 0;
- }
-
- @Override
- public boolean visit(long record) {
- if (record != 0) {
- BTMockRecord btValue = new BTMockRecord(record, BTreeTests.this.db);
- if (i.hasNext()) {
- Integer exp = i.next();
- assertEquals(msg + " Differ at index: " + this.k, btValue.intValue(), exp.intValue());
- this.k++;
- } else {
- fail("Sizes different");
- return false;
- }
- }
- return true;
- }
- });
- }
-
- private static class BTMockRecord {
- public static final int VALUE_PTR = 0;
- public static final int RECORD_SIZE = Database.INT_SIZE;
- long record;
- Database db;
-
- /**
- * Make a new record
- */
- public BTMockRecord(Database db, int value) throws CoreException {
- this.db = db;
- this.record = db.malloc(BTMockRecord.RECORD_SIZE, Database.POOL_MISC);
- db.putInt(this.record + VALUE_PTR, value);
- }
-
- /**
- * Get an existing record
- */
- public BTMockRecord(long record, Database db) {
- this.db = db;
- this.record = record;
- }
-
- public int intValue() {
- return this.db.getInt(this.record);
- }
-
- public long getRecord() {
- return this.record;
- }
- }
-
- private static class BTMockRecordComparator implements IBTreeComparator {
- public BTMockRecordComparator() {
- }
-
- @Override
- public int compare(Nd ndToCompare, long record1, long record2) {
- Database dbToCompare = ndToCompare.getDB();
- return dbToCompare.getInt(record1) - dbToCompare.getInt(record2);
- }
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/ChunkWriterTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/ChunkWriterTests.java
deleted file mode 100644
index 565cf86c0f..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/ChunkWriterTests.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2016 QNX Software Systems and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * QNX Software Systems - initial API and implementation
- * Andrew Ferguson (Symbian)
- * Markus Schorn (Wind River Systems)
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-
-import org.eclipse.jdt.core.tests.nd.util.BaseTestCase;
-import org.eclipse.jdt.internal.core.nd.db.ChunkWriter;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-
-/**
- * Tests for the {@link ChunkWriter} class.
- */
-public class ChunkWriterTests extends BaseTestCase {
- private ChunkWriter writer;
- private long sleepTime;
- private long[] desiredPosition;
- private int[] desiredLength;
- private boolean wasInterrupted;
- private int writeCount;
-
- @FunctionalInterface
- private interface IoExceptionRunnable {
- public void run() throws IOException;
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- this.writer = new ChunkWriter(0x1000, 1, this::write);
- this.writer.setSleepFunction(this::sleepFunction);
- this.sleepTime = 0;
- }
-
- public static Test suite() {
- return BaseTestCase.suite(ChunkWriterTests.class);
- }
-
- @Override
- protected void tearDown() throws Exception {
- this.writer = null;
- }
-
- private void sleepFunction(long milliseconds) {
- this.sleepTime += milliseconds;
- }
-
- private boolean write(ByteBuffer data, long position) throws IOException {
- if (this.writeCount > this.desiredLength.length) {
- throw new AssertionFailedError("Too many calls to write");
- }
- assertEquals(this.desiredPosition[this.writeCount], position);
- assertEquals(this.desiredLength[this.writeCount], data.limit());
-
- this.writeCount++;
- return this.wasInterrupted;
- }
-
- private void runTest(IoExceptionRunnable runnable, long[] positions, int[] lengths, int expectedElapsed,
- boolean expectedReturnValue) throws IOException {
- this.desiredPosition = positions;
- this.desiredLength = lengths;
- this.wasInterrupted = expectedReturnValue;
- long startTime = System.currentTimeMillis();
- runnable.run();
- long elapsed = System.currentTimeMillis() - startTime;
- assertTrue("Insufficient sleep time", elapsed + this.sleepTime >= expectedElapsed);
- assertEquals("Incorrect number of writes", positions.length, this.writeCount);
- }
-
- public void testNoWritesIfNoFlush() throws Exception {
- runTest(() -> {
- this.writer.write(100, new byte[200]);
- }, new long[0], new int[0], 0, false);
- }
-
- public void testNoWritesIfFlushWithNoData() throws Exception {
- runTest(() -> {
- this.writer.flush();
- }, new long[0], new int[0], 0, false);
- }
-
- public void testWriteAfterFlush() throws Exception {
- runTest(() -> {
- this.writer.write(100, new byte[200]);
- this.writer.flush();
- }, new long[] {100}, new int[] {200}, 200, false);
- }
-
- public void testWriteAfterBufferFull() throws Exception {
- runTest(() -> {
- this.writer.write(0x100, new byte[0x200]);
- this.writer.write(0x300, new byte[0x1000]);
- this.writer.flush();
- }, new long[] {0x100, 0x300}, new int[] {0x200, 0x1000}, 0x1200, false);
- }
-
- public void testSequentialWritesCombined() throws Exception {
- runTest(() -> {
- this.writer.write(100, new byte[200]);
- this.writer.write(300, new byte[100]);
- this.writer.flush();
- }, new long[] {100}, new int[] {300}, 300, false);
- }
-
- public void testNonSequentialWrites() throws Exception {
- runTest(() -> {
- this.writer.write(100, new byte[200]);
- this.writer.write(400, new byte[100]);
- this.writer.flush();
- }, new long[] {100, 400}, new int[] {200, 100}, 300, true);
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/DatabaseTest.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/DatabaseTest.java
deleted file mode 100644
index d67ebe1ae0..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/DatabaseTest.java
+++ /dev/null
@@ -1,337 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2017 QNX Software Systems and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * QNX Software Systems - initial API and implementation
- * Andrew Ferguson (Symbian)
- * Markus Schorn (Wind River Systems)
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import java.io.File;
-import java.util.Random;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.tests.nd.util.BaseTestCase;
-import org.eclipse.jdt.internal.core.nd.Nd;
-import org.eclipse.jdt.internal.core.nd.db.BTree;
-import org.eclipse.jdt.internal.core.nd.db.ChunkCache;
-import org.eclipse.jdt.internal.core.nd.db.Database;
-import org.eclipse.jdt.internal.core.nd.db.IBTreeComparator;
-import org.eclipse.jdt.internal.core.nd.db.IBTreeVisitor;
-import org.eclipse.jdt.internal.core.nd.db.IString;
-import org.eclipse.jdt.internal.core.nd.db.IndexException;
-import org.eclipse.jdt.internal.core.nd.db.ShortString;
-
-import junit.framework.Test;
-
-/**
- * Tests for the {@link Database} class.
- */
-public class DatabaseTest extends BaseTestCase {
- // This constant can be used to run the test with very large databases.
- // Try, for example, setting it to Integer.MAX_VALUE * 7L;
- private static final long TEST_OFFSET = 0;
- private Nd nd;
- protected Database db;
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- String testName = getName();
- this.nd = DatabaseTestUtil.createWithoutNodeRegistry(testName);
- this.db = this.nd.getDB();
- this.db.setExclusiveLock();
-
- // Allocate all database chunks up to TEST_OFFSET.
- int count = 0;
- for (long offset = 0; offset < TEST_OFFSET;) {
- offset = this.db.malloc(Database.MAX_SINGLE_BLOCK_MALLOC_SIZE, Database.POOL_MISC);
- if (++count >= 1000) {
- this.db.flush();
- count = 0;
- }
- }
- this.db.flush();
- }
-
- public static Test suite() {
- return BaseTestCase.suite(DatabaseTest.class);
- }
-
- @Override
- protected void tearDown() throws Exception {
- DatabaseTestUtil.deleteDatabase(this.db);
- this.db = null;
- }
-
- public void testBytesNeededForChunks() throws Exception {
- int numChunks = 10;
- long bytes = Database.getBytesThatFitInChunks(numChunks);
- int measuredChunks = Database.getChunksNeededForBytes(bytes);
- assertEquals(numChunks, measuredChunks);
- }
-
- public void testBlockSizeAndFirstBlock() throws Exception {
- assertEquals(DatabaseTestUtil.CURRENT_VERSION, this.db.getVersion());
-
- final int realsize = 42;
- final int deltas = (realsize + Database.BLOCK_HEADER_SIZE + Database.BLOCK_SIZE_DELTA - 1)
- / Database.BLOCK_SIZE_DELTA;
- final int blocksize = deltas * Database.BLOCK_SIZE_DELTA;
- final int freeDeltas = Database.MAX_BLOCK_DELTAS - deltas;
-
- long mem = this.db.malloc(realsize, Database.POOL_MISC);
- assertEquals(-blocksize, this.db.getShort(mem - Database.BLOCK_HEADER_SIZE));
- this.db.free(mem, Database.POOL_MISC);
- assertEquals(blocksize, this.db.getShort(mem - Database.BLOCK_HEADER_SIZE));
- assertEquals(mem, this.db
- .getRecPtr((deltas - Database.MIN_BLOCK_DELTAS) * Database.PTR_SIZE + Database.MALLOC_TABLE_OFFSET));
- assertEquals(mem + blocksize, this.db.getRecPtr(
- (freeDeltas - Database.MIN_BLOCK_DELTAS) * Database.PTR_SIZE + Database.MALLOC_TABLE_OFFSET));
- }
-
- public void testBug192437() throws Exception {
- File tmp= File.createTempFile("readOnlyEmpty", ".db");
- try {
- tmp.setReadOnly();
-
- /* check opening a readonly file for rw access fails */
- try {
- new Database(tmp, ChunkCache.getSharedInstance(), 0, false);
- fail("A readonly file should not be openable with write-access");
- } catch (IndexException e) {
- // we expect to get a failure here
- }
-
- /* check opening a readonly file for read access does not fail */
- try {
- new Database(tmp, ChunkCache.getSharedInstance(), 0, true);
- } catch (IndexException e) {
- fail("A readonly file should be readable by a permanently readonly database " + e);
- }
- } finally {
- tmp.delete(); // this may be pointless on some platforms
- }
- }
-
- public void testFreeBlockLinking() throws Exception {
- final int realsize = 42;
- final int deltas = (realsize + Database.BLOCK_HEADER_SIZE + Database.BLOCK_SIZE_DELTA - 1) / Database.BLOCK_SIZE_DELTA;
-
- long mem1 = this.db.malloc(realsize, Database.POOL_MISC);
- long mem2 = this.db.malloc(realsize, Database.POOL_MISC);
- this.db.free(mem1, Database.POOL_MISC);
- this.db.free(mem2, Database.POOL_MISC);
- assertEquals(mem2, this.db.getRecPtr((deltas - Database.MIN_BLOCK_DELTAS + 1) * Database.INT_SIZE));
- assertEquals(0, this.db.getRecPtr(mem2));
- assertEquals(mem1, this.db.getRecPtr(mem2 + Database.INT_SIZE));
- assertEquals(mem2, this.db.getRecPtr(mem1));
- assertEquals(0, this.db.getRecPtr(mem1 + Database.INT_SIZE));
- }
-
- public void testSimpleAllocationLifecycle() throws Exception {
- long mem1 = this.db.malloc(42, Database.POOL_MISC);
- this.db.free(mem1, Database.POOL_MISC);
- long mem2 = this.db.malloc(42, Database.POOL_MISC);
- assertEquals(mem2, mem1);
- }
-
- private static class FindVisitor implements IBTreeVisitor {
- private Database db;
- private String key;
- private long address;
-
- public FindVisitor(Database db, String key) {
- this.db = db;
- this.key = key;
- }
-
- @Override
- public int compare(long toCompare) {
- return this.db.getString(this.db.getRecPtr(toCompare + 4)).compare(this.key, true);
- }
-
- @Override
- public boolean visit(long toCompare) {
- this.address = toCompare;
- return false;
- }
-
- public long getRecord() {
- return this.address;
- }
- }
-
- public void testStringsInBTree() throws Exception {
- String[] names = {
- "ARLENE",
- "BRET",
- "CINDY",
- "DENNIS",
- "EMILY",
- "FRANKLIN",
- "GERT",
- "HARVEY",
- "IRENE",
- "JOSE",
- "KATRINA",
- "LEE",
- "MARIA",
- "NATE",
- "OPHELIA",
- "PHILIPPE",
- "RITA",
- "STAN",
- "TAMMY",
- "VINCE",
- "WILMA",
- "ALPHA",
- "BETA"
- };
-
- IBTreeComparator comparator = new IBTreeComparator() {
- @Override
- public int compare(Nd ndToCompare, long record1, long record2) {
- IString string1 = DatabaseTest.this.db.getString(DatabaseTest.this.db.getRecPtr(record1 + 4));
- IString string2 = DatabaseTest.this.db.getString(DatabaseTest.this.db.getRecPtr(record2 + 4));
- return string1.compare(string2, true);
- }
- };
-
- BTree btree = new BTree(this.nd, Database.DATA_AREA_OFFSET, comparator);
- for (int i = 0; i < names.length; ++i) {
- String name = names[i];
- long record = this.db.malloc(8, Database.POOL_MISC);
- this.db.putInt(record + 0, i);
- IString string = this.db.newString(name);
- this.db.putRecPtr(record + 4, string.getRecord());
- btree.insert(record);
- }
-
- for (int i = 0; i < names.length; ++i) {
- String name = names[i];
- FindVisitor finder = new FindVisitor(this.db, name);
- btree.accept(finder);
- long record = finder.getRecord();
- assertTrue(record != 0);
- assertEquals(i, this.db.getInt(record));
- IString rname = this.db.getString(this.db.getRecPtr(record + 4));
- assertTrue(rname.toString().equals(name));
- }
- }
-
- private final int GT = 1, LT = -1, EQ = 0;
-
- public void testShortStringComparison() throws CoreException {
- Random r= new Random(90210);
-
- assertCMP("", this.EQ, "", true);
- assertCMP("", this.EQ, "", false);
-
- doTrials(1000, 1, ShortString.MAX_BYTE_LENGTH / 2, r, true);
- doTrials(1000, 1, ShortString.MAX_BYTE_LENGTH / 2, r, false);
- doTrials(1000, 1, ShortString.MAX_BYTE_LENGTH, r, true);
- doTrials(1000, 1, ShortString.MAX_BYTE_LENGTH, r, false);
-
- assertCMP("a", this.LT, "b", true);
- assertCMP("aa", this.LT, "ab", true);
- assertCMP("a", this.EQ, "a", true);
-
- assertCMP("a", this.GT, "A", true);
- assertCMP("aa", this.GT, "aA", true);
- assertCMP("a", this.GT, "B", true);
-
- assertCMP("a", this.EQ, "a", false);
- assertCMP("a", this.EQ, "A", false);
- }
-
- public void testLongStringComparison() throws CoreException {
- Random r= new Random(314159265);
- doTrials(100, ShortString.MAX_BYTE_LENGTH + 1, ShortString.MAX_BYTE_LENGTH * 2, r, true);
- doTrials(100, ShortString.MAX_BYTE_LENGTH + 1, ShortString.MAX_BYTE_LENGTH * 2, r, false);
- }
-
- private void doTrials(int n, int min, int max, Random r, boolean caseSensitive) throws CoreException {
-// long start = System.currentTimeMillis();
- for (int i= 0; i < n; i++) {
- String a = randomString(min, max, r);
- String b = randomString(min, max, r);
- int expected = caseSensitive ? a.compareTo(b) : a.compareToIgnoreCase(b);
- assertCMP(a, expected, b, caseSensitive);
- }
-// System.out.print("Trials: " + n + " Max length: " + max + " ignoreCase: " + !caseSensitive);
-// System.out.println(" Time: " + (System.currentTimeMillis() - start));
- }
-
- private String randomString(int min, int max, Random r) {
- int len = min + r.nextInt(max - min);
- return randomString(len, r);
- }
-
- private String randomString(int len, Random r) {
- StringBuilder result = new StringBuilder(len);
- for (int i= 0; i < len; i++) {
- result.append(randomChar(r));
- }
- return result.toString();
- }
-
- private char randomChar(Random r) {
- // We only match String.compareToIgnoreCase behavior within this limited range.
- return (char) (32 + r.nextInt(40));
- }
-
- private void assertCMP(String a, int expected, String b, boolean caseSensitive) throws CoreException {
- char[] acs = a.toCharArray();
- char[] bcs = b.toCharArray();
- IString aiss = this.db.newString(a);
- IString biss = this.db.newString(b);
- IString aisc = this.db.newString(acs);
- IString bisc = this.db.newString(bcs);
-
- assertEquals(a.hashCode(), aiss.hashCode());
- assertEquals(a.hashCode(), aisc.hashCode());
- assertEquals(b.hashCode(), biss.hashCode());
- assertEquals(b.hashCode(), bisc.hashCode());
-
- assertEquals(aiss, a);
- assertEquals(aisc, a);
- assertEquals(biss, b);
- assertEquals(bisc, b);
-
- assertSignEquals(expected, aiss.compare(bcs, caseSensitive));
- assertSignEquals(expected, aiss.compare(biss, caseSensitive));
- assertSignEquals(expected, aiss.compare(bisc, caseSensitive));
- assertSignEquals(expected, aiss.compare(b, caseSensitive));
- assertSignEquals(expected, aiss.comparePrefix(bcs, caseSensitive));
-
- assertSignEquals(expected, -biss.compare(acs, caseSensitive));
- assertSignEquals(expected, -biss.compare(aiss, caseSensitive));
- assertSignEquals(expected, -biss.compare(aisc, caseSensitive));
- assertSignEquals(expected, -biss.compare(a, caseSensitive));
- assertSignEquals(expected, -biss.comparePrefix(acs, caseSensitive));
-
- if (!caseSensitive && expected != 0) {
- assertSignEquals(expected, aiss.compareCompatibleWithIgnoreCase(bcs));
- assertSignEquals(expected, aiss.compareCompatibleWithIgnoreCase(biss));
- assertSignEquals(expected, aiss.compareCompatibleWithIgnoreCase(bisc));
-
- assertSignEquals(expected, -biss.compareCompatibleWithIgnoreCase(acs));
- assertSignEquals(expected, -biss.compareCompatibleWithIgnoreCase(aiss));
- assertSignEquals(expected, -biss.compareCompatibleWithIgnoreCase(aisc));
- }
- }
-
- private void assertSignEquals(int a, int b) {
- a= a < 0 ? -1 : (a > 0 ? 1 : 0);
- b= b < 0 ? -1 : (b > 0 ? 1 : 0);
- assertEquals(a, b);
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/DatabaseTestUtil.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/DatabaseTestUtil.java
deleted file mode 100644
index b1201f022f..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/DatabaseTestUtil.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2016 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import java.io.File;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Plugin;
-import org.eclipse.jdt.core.tests.Activator;
-import org.eclipse.jdt.internal.core.nd.Nd;
-import org.eclipse.jdt.internal.core.nd.NdNode;
-import org.eclipse.jdt.internal.core.nd.NdNodeTypeRegistry;
-import org.eclipse.jdt.internal.core.nd.db.ChunkCache;
-import org.eclipse.jdt.internal.core.nd.db.Database;
-
-/**
- *
- */
-public class DatabaseTestUtil {
-
- public static IPath getTestDir() {
- Plugin plugin = Activator.getInstance();
-
- IPath path = plugin.getStateLocation().append("tests/");
- File file = path.toFile();
- if (!file.exists())
- file.mkdir();
- return path;
- }
-
- public static File getTempDbName(String testName) {
- return DatabaseTestUtil.getTestDir().append(testName + System.currentTimeMillis() + ".dat").toFile();
- }
-
- /**
- * Creates an empty {@link Nd} with an empty type registry and randomly-named
- * database for the given test name
- *
- * @param testName
- * @return the new {@link Nd}
- */
- public static Nd createEmptyNd(String testName) {
- NdNodeTypeRegistry<NdNode> registry = new NdNodeTypeRegistry<>();
- return new Nd(DatabaseTestUtil.getTempDbName(testName), new ChunkCache(), registry, 0, 0, 0);
- }
-
- public static Nd createEmptyNd(String testName, NdNodeTypeRegistry<NdNode> registry) {
- return new Nd(DatabaseTestUtil.getTempDbName(testName), new ChunkCache(), registry, 0, 0, 0);
- }
-
- static Nd createWithoutNodeRegistry(String testName) {
- NdNodeTypeRegistry<NdNode> registry = new NdNodeTypeRegistry<>();
- Nd tempNd = new Nd(getTempDbName(testName), new ChunkCache(), registry, 0, 100,
- DatabaseTestUtil.CURRENT_VERSION);
- return tempNd;
- }
-
- static final int CURRENT_VERSION = 10;
-
- static void deleteDatabase(Database db) {
- db.close();
- if (!db.getLocation().delete()) {
- db.getLocation().deleteOnExit();
- }
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldBackPointerTest.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldBackPointerTest.java
deleted file mode 100644
index 5c475f29b0..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldBackPointerTest.java
+++ /dev/null
@@ -1,416 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2015, 2016 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-
-import org.eclipse.jdt.core.tests.nd.util.BaseTestCase;
-import org.eclipse.jdt.internal.core.nd.Nd;
-import org.eclipse.jdt.internal.core.nd.NdNode;
-import org.eclipse.jdt.internal.core.nd.NdNodeTypeRegistry;
-import org.eclipse.jdt.internal.core.nd.RawGrowableArray;
-import org.eclipse.jdt.internal.core.nd.db.Database;
-import org.eclipse.jdt.internal.core.nd.field.FieldInt;
-import org.eclipse.jdt.internal.core.nd.field.FieldManyToOne;
-import org.eclipse.jdt.internal.core.nd.field.FieldOneToMany;
-import org.eclipse.jdt.internal.core.nd.field.StructDef;
-
-import junit.framework.Test;
-
-public class FieldBackPointerTest extends BaseTestCase {
- public static class ForwardPointerStruct extends NdNode {
- public static final FieldManyToOne<BackPointerStruct> FORWARD;
- public static final FieldManyToOne<BackPointerStruct> OWNER;
-
- @SuppressWarnings("hiding")
- public static final StructDef<ForwardPointerStruct> type;
-
- static {
- type = StructDef.create(ForwardPointerStruct.class, NdNode.type);
-
- FORWARD = FieldManyToOne.create(type, BackPointerStruct.BACK);
- OWNER = FieldManyToOne.createOwner(type, BackPointerStruct.OWNED);
- type.done();
- }
-
- public ForwardPointerStruct(Nd nd) {
- super(nd);
- }
-
- public ForwardPointerStruct(Nd nd, long record) {
- super(nd, record);
- }
-
- public void setBp(BackPointerStruct toSet) {
- FORWARD.put(getNd(), this.address, toSet);
- }
-
- public BackPointerStruct getBp() {
- return FORWARD.get(getNd(), this.address);
- }
-
- public void setOwner(BackPointerStruct owner) {
- OWNER.put(getNd(), this.address, owner);
- }
-
- public BackPointerStruct getOwner() {
- return OWNER.get(getNd(), this.address);
- }
- }
-
- public static class BackPointerStruct extends NdNode {
- public static final FieldOneToMany<ForwardPointerStruct> BACK;
- public static final FieldOneToMany<ForwardPointerStruct> OWNED;
- public static final FieldInt SOMEINT;
-
- @SuppressWarnings("hiding")
- public static final StructDef<BackPointerStruct> type;
-
- static {
- type = StructDef.create(BackPointerStruct.class, NdNode.type);
-
- BACK = FieldOneToMany.create(type, ForwardPointerStruct.FORWARD, 2);
- OWNED = FieldOneToMany.create(type, ForwardPointerStruct.OWNER, 0);
- SOMEINT = type.addInt();
- type.done();
- }
-
- public BackPointerStruct(Nd nd) {
- super(nd);
-
- // Fill with nonzero values to ensure that "OWNED" doesn't read beyond its boundary
- SOMEINT.put(nd, this.address, 0xf0f0f0f0);
- }
-
- public BackPointerStruct(Nd nd, long record) {
- super(nd, record);
- }
-
- public void ensureBackPointerCapacity(int capacity) {
- BACK.ensureCapacity(getNd(), this.address, capacity);
- }
-
- public int getBackPointerCapacity() {
- return BACK.getCapacity(getNd(), this.address);
- }
-
- public long getBackpointerAddress(int idx) {
- return BACK.getAddressOf(getNd(), this.address, idx);
- }
-
- public List<ForwardPointerStruct> getBackPointers() {
- return BACK.asList(getNd(), this.address);
- }
-
- public List<ForwardPointerStruct> getOwned() {
- return OWNED.asList(getNd(), this.address);
- }
-
- public int backPointerSize() {
- return BACK.size(getNd(), this.address);
- }
-
- public boolean backPointersAreEmpty() {
- return BACK.isEmpty(getNd(), this.address);
- }
-
- public boolean ownedPointersAreEmpty() {
- return OWNED.isEmpty(getNd(), this.address);
- }
-
- public ForwardPointerStruct getBackPointer(int i) {
- return BACK.get(getNd(), this.address, i);
- }
- }
-
- ForwardPointerStruct fa;
- ForwardPointerStruct fb;
- ForwardPointerStruct fc;
- ForwardPointerStruct fd;
- BackPointerStruct ba;
- BackPointerStruct bb;
- private Nd nd;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- NdNodeTypeRegistry<NdNode> registry = new NdNodeTypeRegistry<>();
- registry.register(0, BackPointerStruct.type.getFactory());
- registry.register(1, ForwardPointerStruct.type.getFactory());
- this.nd = DatabaseTestUtil.createEmptyNd(getName(), registry);
- this.nd.getDB().setExclusiveLock();
- this.ba = new BackPointerStruct(this.nd);
- this.bb = new BackPointerStruct(this.nd);
- this.fa = new ForwardPointerStruct(this.nd);
- this.fb = new ForwardPointerStruct(this.nd);
- this.fc = new ForwardPointerStruct(this.nd);
- this.fd = new ForwardPointerStruct(this.nd);
- }
-
- public static Test suite() {
- return BaseTestCase.suite(FieldBackPointerTest.class);
- }
-
- void assertBackPointers(BackPointerStruct bp, ForwardPointerStruct... fp) {
- HashSet<ForwardPointerStruct> backPointers = new HashSet<>(bp.getBackPointers());
- HashSet<ForwardPointerStruct> desired = new HashSet<>();
-
- desired.addAll(Arrays.asList(fp));
- assertEquals(desired, backPointers);
- }
-
- public void testLargeBlockBackPointerTest() throws Exception {
- this.nd.getDB().giveUpExclusiveLock();
- // Allocate enough entries to cause the metablock array to resize twice
- int totalSize = Database.CHUNK_SIZE * 0x400;
-
- long initialAllocations = this.nd.getDB().getBytesAllocated() - this.nd.getDB().getBytesFreed();
- this.nd.acquireWriteLock(null);
- ForwardPointerStruct[] forwardPointer = new ForwardPointerStruct[totalSize];
- for (int idx = 0; idx < totalSize; idx++) {
- forwardPointer[idx] = new ForwardPointerStruct(this.nd);
- forwardPointer[idx].setBp(this.ba);
- }
-
- for (int idx = 0; idx < totalSize; idx++) {
- assertEquals(forwardPointer[idx].getAddress(), this.ba.getBackpointerAddress(idx));
- }
-
- for (int idx = 0; idx < totalSize; idx++) {
- forwardPointer[idx].delete();
- }
-
- this.nd.releaseWriteLock();
-
- long finalAllocations = this.nd.getDB().getBytesAllocated() - this.nd.getDB().getBytesFreed();
-
- // Verify no memory leaks
- assertEquals(initialAllocations, finalAllocations);
- }
-
- public void testWriteFollowedByReadReturnsSameThing() throws Exception {
- this.fa.setBp(this.ba);
- BackPointerStruct backpointer = this.fa.getBp();
-
- assertEquals(this.ba, backpointer);
- }
-
- public void testListWithoutInlineElementsCanBeEmpty() throws Exception {
- assertTrue(this.ba.ownedPointersAreEmpty());
- }
-
- public void testReadNull() throws Exception {
- assertEquals(null, this.fa.getBp());
- }
-
- public void testAssigningTheSamePointerTwiceIsANoop() throws Exception {
- this.fa.setBp(this.ba);
-
- assertBackPointers(this.ba, this.fa);
-
- // Now do the same thing again
- this.fa.setBp(this.ba);
-
- assertBackPointers(this.ba, this.fa);
- }
-
- public void testAssigningForwardPointerInsertsBackPointer() throws Exception {
- this.fa.setBp(this.ba);
-
- assertEquals(Arrays.asList(this.fa), this.ba.getBackPointers());
- assertEquals(1, this.ba.backPointerSize());
- }
-
- public void testRemovesInlineElement() throws Exception {
- this.fa.setBp(this.ba);
- this.fb.setBp(this.ba);
- this.fc.setBp(this.ba);
- this.fd.setBp(this.ba);
-
- assertEquals(4, this.ba.backPointerSize());
- this.fb.setBp(null);
- assertEquals(3, this.ba.backPointerSize());
-
- assertBackPointers(this.ba, this.fa, this.fc, this.fd);
- }
-
- public void testRemovesElementFromGrowableBlock() throws Exception {
- this.fa.setBp(this.ba);
- this.fb.setBp(this.ba);
- this.fc.setBp(this.ba);
- this.fd.setBp(this.ba);
-
- assertEquals(4, this.ba.backPointerSize());
- this.fc.setBp(null);
- assertEquals(3, this.ba.backPointerSize());
-
- assertBackPointers(this.ba, this.fa, this.fb, this.fd);
- }
-
- public void testDestructingForwardPointerRemovesBackPointer() throws Exception {
- this.fa.setBp(this.ba);
- this.fb.setBp(this.ba);
- this.fc.setBp(this.ba);
-
- this.fb.delete();
- this.nd.processDeletions();
-
- assertBackPointers(this.ba, this.fa, this.fc);
- }
-
- public void testDestructingBackPointerClearsForwardPointers() throws Exception {
- this.fa.setBp(this.ba);
- this.fb.setBp(this.ba);
- this.fc.setBp(this.ba);
-
- this.ba.delete();
- this.nd.processDeletions();
-
- assertEquals(null, this.fa.getBp());
- assertEquals(null, this.fb.getBp());
- assertEquals(null, this.fc.getBp());
- }
-
- public void testElementsRemainInInsertionOrderIfNoRemovals() throws Exception {
- this.fa.setBp(this.ba);
- this.fb.setBp(this.ba);
- this.fc.setBp(this.ba);
- this.fd.setBp(this.ba);
-
- assertEquals(Arrays.asList(this.fa, this.fb, this.fc, this.fd), this.ba.getBackPointers());
- }
-
- public void testDeletingOwnerDeletesOwned() throws Exception {
- this.fa.setBp(this.ba);
- this.fa.setOwner(this.bb);
-
- this.fb.setBp(this.ba);
- this.fb.setOwner(this.bb);
-
- this.fc.setBp(this.ba);
-
- this.bb.delete();
- this.nd.processDeletions();
-
- assertBackPointers(this.ba, this.fc);
- }
-
- public void testEnsureCapacityDoesNothingIfLessThanInlineElements() throws Exception {
- this.ba.ensureBackPointerCapacity(1);
- assertEquals(2, this.ba.getBackPointerCapacity());
- }
-
- public void testEnsureCapacityAllocatesPowersOfTwoPlusInlineSize() throws Exception {
- this.ba.ensureBackPointerCapacity(60);
- assertEquals(66, this.ba.getBackPointerCapacity());
- }
-
- public void testEnsureCapacityAllocatesMinimumSize() throws Exception {
- this.ba.ensureBackPointerCapacity(3);
- assertEquals(4, this.ba.getBackPointerCapacity());
- }
-
- public void testEnsureCapacityClampsToChunkSize() throws Exception {
- this.ba.ensureBackPointerCapacity(RawGrowableArray.getMaxGrowableBlockSize() - 40);
- assertEquals(RawGrowableArray.getMaxGrowableBlockSize() + 2, this.ba.getBackPointerCapacity());
- }
-
- public void testEnsureCapacityGrowsByMultiplesOfMaxBlockSizeOnceMetablockInUse() throws Exception {
- int maxBlockSize = RawGrowableArray.getMaxGrowableBlockSize();
- this.ba.ensureBackPointerCapacity(maxBlockSize * 3 - 100);
- assertEquals(maxBlockSize * 3 + 2, this.ba.getBackPointerCapacity());
- }
-
- public void testAdditionsWontReduceCapacity() throws Exception {
- int maxBlockSize = RawGrowableArray.getMaxGrowableBlockSize();
- this.ba.ensureBackPointerCapacity(maxBlockSize);
-
- this.fa.setBp(this.ba);
- this.fb.setBp(this.ba);
- this.fc.setBp(this.ba);
- this.fd.setBp(this.ba);
-
- assertEquals(maxBlockSize + 2, this.ba.getBackPointerCapacity());
- }
-
- public void testIsEmpty() throws Exception {
- assertTrue(this.ba.backPointersAreEmpty());
- this.fa.setBp(this.ba);
- assertFalse(this.ba.backPointersAreEmpty());
- this.fb.setBp(this.ba);
- this.fc.setBp(this.ba);
- this.fd.setBp(this.ba);
- assertFalse(this.ba.backPointersAreEmpty());
- }
-
- public void testRemovalsReduceCapacity() throws Exception {
- int maxBlockSize = RawGrowableArray.getMaxGrowableBlockSize();
- this.ba.ensureBackPointerCapacity(maxBlockSize);
-
- this.fa.setBp(this.ba);
- this.fb.setBp(this.ba);
- this.fc.setBp(this.ba);
- assertEquals(maxBlockSize + 2, this.ba.getBackPointerCapacity());
-
- this.fb.setBp(null);
- this.fc.setBp(null);
-
- assertEquals(2, this.ba.getBackPointerCapacity());
- }
-
- public void testInsertEnoughToUseMetablock() throws Exception {
- // We need enough instances to fill several full blocks since we don't reclaim
- // memory until there are two unused blocks.
- int numToAllocate = RawGrowableArray.getMaxGrowableBlockSize() * 4 + 1;
-
- List<ForwardPointerStruct> allocated = new ArrayList<>();
-
- for (int count = 0; count < numToAllocate; count++) {
- ForwardPointerStruct next = new ForwardPointerStruct(this.nd);
-
- next.setBp(this.ba);
- assertEquals(next, this.ba.getBackPointer(count));
- allocated.add(next);
- assertEquals(count + 1, this.ba.backPointerSize());
- }
-
- assertEquals(allocated.get(numToAllocate - 1), this.ba.getBackPointer(numToAllocate - 1));
- assertEquals(numToAllocate, this.ba.backPointerSize());
-
- int correctSize = numToAllocate;
- for (ForwardPointerStruct next : allocated) {
- next.setBp(null);
- assertEquals(--correctSize, this.ba.backPointerSize());
- }
-
- assertEquals(0, this.ba.backPointerSize());
- assertEquals(2, this.ba.getBackPointerCapacity());
- }
-
- public void testGrowExistingMetablock() throws Exception {
- int blockSize = RawGrowableArray.getMaxGrowableBlockSize();
-
- this.ba.ensureBackPointerCapacity(2 * blockSize);
-
- assertEquals(2 * blockSize + 2, this.ba.getBackPointerCapacity());
-
- this.ba.ensureBackPointerCapacity(6 * blockSize);
-
- assertEquals(6 * blockSize + 2, this.ba.getBackPointerCapacity());
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldListTest.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldListTest.java
deleted file mode 100644
index bacff5f389..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldListTest.java
+++ /dev/null
@@ -1,323 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2017 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import java.util.List;
-
-import org.eclipse.jdt.core.tests.nd.util.BaseTestCase;
-import org.eclipse.jdt.internal.core.nd.IDestructable;
-import org.eclipse.jdt.internal.core.nd.Nd;
-import org.eclipse.jdt.internal.core.nd.NdNode;
-import org.eclipse.jdt.internal.core.nd.NdNodeTypeRegistry;
-import org.eclipse.jdt.internal.core.nd.NdStruct;
-import org.eclipse.jdt.internal.core.nd.db.IString;
-import org.eclipse.jdt.internal.core.nd.field.FieldByte;
-import org.eclipse.jdt.internal.core.nd.field.FieldList;
-import org.eclipse.jdt.internal.core.nd.field.FieldManyToOne;
-import org.eclipse.jdt.internal.core.nd.field.FieldOneToMany;
-import org.eclipse.jdt.internal.core.nd.field.FieldString;
-import org.eclipse.jdt.internal.core.nd.field.StructDef;
-
-import junit.framework.Test;
-
-public class FieldListTest extends BaseTestCase {
- static int nodeDeletions;
- static int structDeletions;
-
- public static class ElementNode extends NdNode {
- public static final FieldString NAME;
- public static final FieldOneToMany<TestStruct> RELATED_STRUCTS;
- public static final FieldManyToOne<TestStruct> PARENT_NODE;
- public static final FieldList<TestStruct> LIST_CONTENTS;
-
- @SuppressWarnings("hiding")
- public static final StructDef<ElementNode> type;
-
- static {
- type = StructDef.create(ElementNode.class, NdNode.type);
-
- NAME = type.addString();
- RELATED_STRUCTS = FieldOneToMany.create(type, TestStruct.RELATED_NODE);
- PARENT_NODE = FieldManyToOne.createOwner(type, TestStruct.CHILD_NODES);
- LIST_CONTENTS = FieldList.create(type, TestStruct.type, 3);
- type.done();
- }
-
- public ElementNode(Nd nd, long record) {
- super(nd, record);
- }
-
- public ElementNode(Nd nd, String name, TestStruct parent) {
- super(nd);
-
- NAME.put(nd, this.address, name);
- PARENT_NODE.put(nd, this.address, parent);
- }
-
- public TestStruct createChild(String name) {
- TestStruct result = LIST_CONTENTS.append(this.nd, this.address);
- result.setName(name);
- return result;
- }
-
- public List<TestStruct> getChildren() {
- return LIST_CONTENTS.asList(getNd(), getAddress());
- }
-
- @Override
- public void destruct() {
- super.destruct();
-
- FieldListTest.nodeDeletions++;
- }
-
- public IString getName() {
- return NAME.get(getNd(), getAddress());
- }
-
- public String toString() {
- StringBuilder builder = new StringBuilder();
- printStringTo(builder);
- return builder.toString();
- }
-
- public void printStringTo(StringBuilder builder) {
- builder.append(getName().getString());
- if (!RELATED_STRUCTS.isEmpty(getNd(), getAddress())) {
- builder.append("->[");
- boolean isFirst = true;
- for (TestStruct struct : getRelatedStructs()) {
- if (!isFirst) {
- builder.append(", ");
- }
- isFirst = false;
- builder.append(struct.getName());
- }
- builder.append("]");
- }
-
- List<TestStruct> children = getChildren();
- if (!children.isEmpty()) {
- builder.append("(");
- boolean isFirst = true;
- for (TestStruct struct : children) {
- if (!isFirst) {
- builder.append(", ");
- }
- isFirst = false;
- struct.printStringTo(builder);
- }
- builder.append(")");
- }
- }
-
- public List<TestStruct> getRelatedStructs() {
- return RELATED_STRUCTS.asList(getNd(), getAddress());
- }
- }
-
- public static class TestStruct extends NdStruct implements IDestructable {
- public static final FieldString NAME;
- public static final FieldOneToMany<ElementNode> CHILD_NODES;
- public static final FieldManyToOne<ElementNode> RELATED_NODE;
- public static final FieldByte EXTRA_BYTE;
-
- @SuppressWarnings("hiding")
- public static final StructDef<TestStruct> type;
-
- static {
- type = StructDef.create(TestStruct.class, NdStruct.type);
-
- NAME = type.addString();
- CHILD_NODES = FieldOneToMany.create(type, ElementNode.PARENT_NODE);
- RELATED_NODE = FieldManyToOne.create(type, ElementNode.RELATED_STRUCTS);
- EXTRA_BYTE = type.addByte();
- type.done();
- }
-
- public TestStruct(Nd nd, long record) {
- super(nd, record);
- }
-
- public void printStringTo(StringBuilder builder) {
- builder.append(getName().getString());
- ElementNode related = RELATED_NODE.get(getNd(), getAddress());
- if (related != null) {
- builder.append("->[");
- builder.append(related.getName().getString());
- builder.append("]");
- }
-
- List<ElementNode> children = getChildren();
- if (!children.isEmpty()) {
- builder.append("(");
- boolean isFirst = true;
- for (ElementNode struct : children) {
- if (!isFirst) {
- builder.append(", ");
- }
- isFirst = false;
- struct.printStringTo(builder);
- }
- builder.append(")");
- }
- }
-
- public String toString() {
- StringBuilder builder = new StringBuilder();
- printStringTo(builder);
- return builder.toString();
- }
-
- public IString getName() {
- return NAME.get(getNd(), getAddress());
- }
-
- public void setRelatedNode(ElementNode elementNode) {
- RELATED_NODE.put(getNd(), getAddress(), elementNode);
- }
-
- public ElementNode getRelatedNode() {
- return RELATED_NODE.get(getNd(), getAddress());
- }
-
- public void setName(String name) {
- NAME.put(getNd(), getAddress(), name);
- }
-
- public List<ElementNode> getChildren() {
- return CHILD_NODES.asList(getNd(), getAddress());
- }
-
- public ElementNode createChild(String name) {
- return new ElementNode(getNd(), name, this);
- }
-
- @Override
- public void destruct() {
- FieldListTest.structDeletions++;
- }
- }
-
- TestStruct referencer;
- TestStruct owner;
- private Nd nd;
- private ElementNode root;
- private boolean nodeDeleted;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- structDeletions = 0;
- nodeDeletions = 0;
- NdNodeTypeRegistry<NdNode> registry = new NdNodeTypeRegistry<>();
- registry.register(0, ElementNode.type.getFactory());
- this.nd = DatabaseTestUtil.createEmptyNd(getName(), registry);
- this.nd.getDB().setExclusiveLock();
- this.root = new ElementNode(this.nd, "root", null);
- }
-
- protected void freeAllMemory() throws Exception {
- if (this.nodeDeleted) {
- return;
- }
- this.nodeDeleted = true;
- this.root.delete();
- this.nd.processDeletions();
- long freed = this.nd.getDB().getBytesFreed();
- long allocated = this.nd.getDB().getBytesAllocated();
- assertEquals("We should have freed all the bytes we allocated and no more", allocated, freed);
- }
-
- @Override
- protected void tearDown() throws Exception {
- freeAllMemory();
- super.tearDown();
- }
-
- public void testEmptyList() throws Exception {
- assertTrue("isEmpty() should return true if no children inserted",
- this.root.getChildren().isEmpty());
- freeAllMemory();
- assertEquals("No structs should have been disposed during this test", 0, structDeletions);
- assertEquals("One node should have been disposed during this test", 1, nodeDeletions);
- }
-
- public void testOneChild() throws Exception {
- TestStruct testStruct = this.root.createChild("child");
- assertEquals("root should be initialized properly", "child", testStruct.getName().getString());
- assertEquals("root should have correct contents", "root(child)", this.root.toString());
- freeAllMemory();
- assertEquals("No structs should have been disposed during this test", 1, structDeletions);
- assertEquals("One node should have been disposed during this test", 1, nodeDeletions);
- }
-
- public void testElementsInBlock() throws Exception {
- this.root.createChild("child1");
- this.root.createChild("child2");
- assertEquals("root should have correct contents", "root(child1, child2)", this.root.toString());
- this.root.createChild("child3");
- assertEquals("root should have correct contents", "root(child1, child2, child3)",
- this.root.toString());
- this.root.createChild("child4");
- assertEquals("root should have correct contents", "root(child1, child2, child3, child4)",
- this.root.toString());
- this.root.createChild("child5");
- assertEquals("root should have correct contents", "root(child1, child2, child3, child4, child5)",
- this.root.toString());
- freeAllMemory();
- assertEquals("No structs should have been disposed during this test", 5, structDeletions);
- assertEquals("One node should have been disposed during this test", 1, nodeDeletions);
- }
-
- public void testDestructorInPartiallyFilledBlock() throws Exception {
- this.root.createChild("child1");
- this.root.createChild("child2");
- this.root.createChild("child3");
- this.root.createChild("child4");
- freeAllMemory();
- assertEquals("No structs should have been disposed during this test", 4, structDeletions);
- assertEquals("One node should have been disposed during this test", 1, nodeDeletions);
- }
-
- public void testListOwningNode() throws Exception {
- TestStruct child1 = this.root.createChild("child1");
- child1.createChild("grandchild1");
-
- assertEquals("root should have correct contents", "root(child1(grandchild1))", this.root.toString());
-
- freeAllMemory();
- assertEquals("No structs should have been disposed during this test", 1, structDeletions);
- assertEquals("One node should have been disposed during this test", 2, nodeDeletions);
- }
-
- public void testListWithManyToOneNode() throws Exception {
- TestStruct child1 = this.root.createChild("child1");
- ElementNode relatedNode = new ElementNode(this.nd, "relatedNode", null);
- child1.setRelatedNode(relatedNode);
-
- assertEquals("Related node should have been set", relatedNode, child1.getRelatedNode());
- assertEquals("root should have correct contents", "root(child1->[relatedNode])", this.root.toString());
-
- this.root.delete();
- this.nodeDeleted = true;
-
- assertEquals("Related node should be cleared", null, child1.getRelatedNode());
- }
-
- public static Test suite() {
- return BaseTestCase.suite(FieldListTest.class);
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldOneToOneTest.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldOneToOneTest.java
deleted file mode 100644
index c171f1b997..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/FieldOneToOneTest.java
+++ /dev/null
@@ -1,260 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2015, 2016 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import org.eclipse.jdt.core.tests.nd.util.BaseTestCase;
-import org.eclipse.jdt.internal.core.nd.Nd;
-import org.eclipse.jdt.internal.core.nd.NdNode;
-import org.eclipse.jdt.internal.core.nd.NdNodeTypeRegistry;
-import org.eclipse.jdt.internal.core.nd.field.FieldOneToOne;
-import org.eclipse.jdt.internal.core.nd.field.StructDef;
-
-import junit.framework.Test;
-
-public class FieldOneToOneTest extends BaseTestCase {
- static int struct2Deletions;
- static int structDeletions;
-
- public static class TestStruct extends NdNode {
- public static final FieldOneToOne<TestStruct2> ANOTHER_STRUCT;
- public static final FieldOneToOne<TestStruct2> OWNED;
-
- @SuppressWarnings("hiding")
- public static final StructDef<TestStruct> type;
-
- static {
- type = StructDef.create(TestStruct.class, NdNode.type);
-
- ANOTHER_STRUCT = FieldOneToOne.create(type, TestStruct2.type, TestStruct2.ANOTHER_STRUCT);
- OWNED = FieldOneToOne.create(type, TestStruct2.type, TestStruct2.OWNER);
- type.done();
- }
-
- public TestStruct(Nd nd) {
- super(nd);
- }
-
- public TestStruct(Nd nd, long record) {
- super(nd, record);
- }
-
- public void setAnother(TestStruct2 toSet) {
- ANOTHER_STRUCT.put(getNd(), this.address, toSet);
- }
-
- public TestStruct2 getAnother() {
- return ANOTHER_STRUCT.get(getNd(), this.address);
- }
-
- public void setOwned(TestStruct2 owned) {
- OWNED.put(getNd(), this.address, owned);
- }
-
- public TestStruct2 getOwned() {
- return OWNED.get(getNd(), this.address);
- }
-
- @Override
- public void destruct() {
- super.destruct();
- FieldOneToOneTest.structDeletions++;
- }
- }
-
- public static class TestStruct2 extends NdNode {
- public static final FieldOneToOne<TestStruct> OWNER;
- public static final FieldOneToOne<TestStruct> ANOTHER_STRUCT;
-
- @SuppressWarnings("hiding")
- public static final StructDef<TestStruct2> type;
-
- static {
- type = StructDef.create(TestStruct2.class, NdNode.type);
-
- OWNER = FieldOneToOne.createOwner(type, TestStruct.type, TestStruct.OWNED);
- ANOTHER_STRUCT = FieldOneToOne.create(type, TestStruct.type, TestStruct.ANOTHER_STRUCT);
-
- type.done();
- }
-
- public TestStruct2(Nd nd) {
- super(nd);
- }
-
- public TestStruct2(Nd nd, long record) {
- super(nd, record);
- }
-
- public void setAnother(TestStruct toSet) {
- ANOTHER_STRUCT.put(getNd(), this.address, toSet);
- }
-
- public TestStruct getAnother() {
- return ANOTHER_STRUCT.get(getNd(), this.address);
- }
-
- public void setOwner(TestStruct owner) {
- OWNER.put(getNd(), this.address, owner);
- }
-
- public TestStruct getOwner() {
- return OWNER.get(getNd(), this.address);
- }
-
- @Override
- public void destruct() {
- super.destruct();
- FieldOneToOneTest.struct2Deletions++;
- }
- }
-
- TestStruct referencer;
- TestStruct owner;
- TestStruct2 referenced;
- TestStruct2 owned;
- private Nd nd;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- structDeletions = 0;
- struct2Deletions = 0;
- NdNodeTypeRegistry<NdNode> registry = new NdNodeTypeRegistry<>();
- registry.register(0, TestStruct2.type.getFactory());
- registry.register(1, TestStruct.type.getFactory());
- this.nd = DatabaseTestUtil.createEmptyNd(getName(), registry);
- this.nd.getDB().setExclusiveLock();
- this.referencer = new TestStruct(this.nd);
- this.owner = new TestStruct(this.nd);
- this.referenced = new TestStruct2(this.nd);
- this.owned = new TestStruct2(this.nd);
-
- this.owner.setOwned(this.owned);
- this.referencer.setAnother(this.referenced);
- }
-
- public static Test suite() {
- return BaseTestCase.suite(FieldOneToOneTest.class);
- }
-
- public void testPointersSetCorrectly() {
- assertEquals(this.owner.address, this.owned.getOwner().address);
- assertEquals(this.owned.address, this.owner.getOwned().address);
- assertEquals(this.referencer.address, this.referenced.getAnother().address);
- assertEquals(this.referenced.address, this.referencer.getAnother().address);
- }
-
- public void testClearingOwnerDeletesOwned() {
- long freed = this.nd.getDB().getBytesFreed();
-
- this.owner.setOwned(null);
-
- this.nd.processDeletions();
-
- assertEquals(null, this.owner.getOwned());
- assertTrue(this.nd.getDB().getBytesFreed() - freed >= TestStruct2.type.size());
- assertEquals(1, struct2Deletions);
- }
-
- public void testDeletingOwnerDeletesOwned() {
- long freed = this.nd.getDB().getBytesFreed();
-
- this.owner.delete();
-
- this.nd.processDeletions();
-
- assertTrue(this.nd.getDB().getBytesFreed() - freed >= TestStruct2.type.size() + TestStruct.type.size());
- assertEquals(1, struct2Deletions);
- assertEquals(1, structDeletions);
- }
-
- public void testReassignedOwnerDeletesOwned() {
- long freed = this.nd.getDB().getBytesFreed();
- TestStruct2 newOwned = new TestStruct2(this.nd);
-
- this.owner.setOwned(newOwned);
-
- this.nd.processDeletions();
-
- long freed2 = this.nd.getDB().getBytesFreed();
-
- assertEquals(newOwned, this.owner.getOwned());
- assertTrue(freed2 - freed >= TestStruct2.type.size());
- assertEquals(1, struct2Deletions);
- }
-
- public void testMovingToNewOwnerDoesntDeleteOwned() {
- long freed = this.nd.getDB().getBytesFreed();
- TestStruct newOwner = new TestStruct(this.nd);
-
- this.owned.setOwner(newOwner);
-
- this.nd.processDeletions();
-
- long freed2 = this.nd.getDB().getBytesFreed();
-
- assertEquals(freed, freed2);
- assertEquals(null, this.owner.getOwned());
- assertEquals(this.owned, newOwner.getOwned());
- assertEquals(0, struct2Deletions);
- assertEquals(0, structDeletions);
- }
-
- public void testMovingToNewOwnerAfterClearingOwnerPointerDoesntDeleteOwned() {
- long freed = this.nd.getDB().getBytesFreed();
- TestStruct newOwner = new TestStruct(this.nd);
-
- this.owner.setOwned(null);
- this.owned.setOwner(newOwner);
-
- this.nd.processDeletions();
-
- long freed2 = this.nd.getDB().getBytesFreed();
-
- assertEquals(freed, freed2);
- assertEquals(null, this.owner.getOwned());
- assertEquals(this.owned, newOwner.getOwned());
- assertEquals(0, struct2Deletions);
- assertEquals(0, structDeletions);
- }
-
- public void testClearingOwnerPointerDeletesOwned() {
- long freed = this.nd.getDB().getBytesFreed();
-
- this.owned.setOwner(null);
-
- this.nd.processDeletions();
-
- long freed2 = this.nd.getDB().getBytesFreed();
-
- assertTrue(freed2 - freed >= TestStruct2.type.size());
- assertEquals(null, this.owner.getOwned());
- assertEquals(1, struct2Deletions);
- assertEquals(0, structDeletions);
- }
-
- public void testMovingReferenceClearsOldBackPointer() {
- TestStruct2 newTarget = new TestStruct2(this.nd);
-
- long freed = this.nd.getDB().getBytesFreed();
- this.referencer.setAnother(newTarget);
- this.nd.processDeletions();
-
- long freed2 = this.nd.getDB().getBytesFreed();
- assertEquals(newTarget, this.referencer.getAnother());
- assertEquals(null, this.referenced.getAnother());
- assertEquals(freed, freed2);
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/InheritenceTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/InheritenceTests.java
deleted file mode 100644
index ceb2a6c422..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/InheritenceTests.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2015, 2016 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import org.eclipse.jdt.core.tests.nd.util.BaseTestCase;
-import org.eclipse.jdt.internal.core.nd.Nd;
-import org.eclipse.jdt.internal.core.nd.NdNode;
-import org.eclipse.jdt.internal.core.nd.NdNodeTypeRegistry;
-import org.eclipse.jdt.internal.core.nd.field.FieldManyToOne;
-import org.eclipse.jdt.internal.core.nd.field.FieldOneToMany;
-import org.eclipse.jdt.internal.core.nd.field.StructDef;
-
-import junit.framework.Test;
-
-public class InheritenceTests extends BaseTestCase {
- /**
- * Every other object in this test has a pointer to the deletion detector, so we can detect
- * which objects have been deleted by looking for the object in the backpointer list.
- */
- public static class AllObjects extends NdNode {
- public static final FieldOneToMany<BaseClass> BASE_CLASS_INSTANCES;
- public static final FieldOneToMany<Reference> REFERENCE_INSTANCES;
-
- @SuppressWarnings("hiding")
- public static final StructDef<AllObjects> type;
-
- static {
- type = StructDef.create(AllObjects.class, NdNode.type);
-
- BASE_CLASS_INSTANCES = FieldOneToMany.create(type, BaseClass.DELETION_DETECTOR, 0);
- REFERENCE_INSTANCES = FieldOneToMany.create(type, Reference.DELETION_DETECTOR, 0);
- type.done();
- }
-
- public AllObjects(Nd nd, long record) {
- super(nd, record);
- }
-
- public AllObjects(Nd nd) {
- super(nd);
- }
-
- boolean contains(BaseClass toTest) {
- return BASE_CLASS_INSTANCES.asList(getNd(), this.address).contains(toTest);
- }
-
- boolean contains(Reference toTest) {
- return REFERENCE_INSTANCES.asList(getNd(), this.address).contains(toTest);
- }
- }
-
- public static class BaseClass extends NdNode {
- public static final FieldOneToMany<Reference> INCOMING_REFERENCES;
- public static final FieldOneToMany<Reference> OWNED_REFERENCES;
- public static final FieldManyToOne<AllObjects> DELETION_DETECTOR;
-
- @SuppressWarnings("hiding")
- public static final StructDef<BaseClass> type;
-
- static {
- type = StructDef.create(BaseClass.class, NdNode.type);
-
- INCOMING_REFERENCES = FieldOneToMany.create(type, Reference.BASE_CLASS_REFERENCE, 0);
- OWNED_REFERENCES = FieldOneToMany.create(type, Reference.OWNER, 0);
- DELETION_DETECTOR = FieldManyToOne.create(type, AllObjects.BASE_CLASS_INSTANCES);
- type.useStandardRefCounting().done();
- }
-
- public BaseClass(Nd nd, AllObjects deletionDetector) {
- super(nd);
-
- DELETION_DETECTOR.put(nd, this.address, deletionDetector);
- }
-
- public BaseClass(Nd nd, long record) {
- super(nd, record);
- }
- }
-
- public static class SubClass extends BaseClass {
- public static final FieldOneToMany<Reference> MORE_REFERENCES;
-
- @SuppressWarnings("hiding")
- public static final StructDef<SubClass> type;
-
- static {
- type = StructDef.create(SubClass.class, BaseClass.type);
-
- MORE_REFERENCES = FieldOneToMany.create(type, Reference.SUB_CLASS_REFERENCE, 0);
- type.useStandardRefCounting().done();
- }
-
- public SubClass(Nd nd, long record) {
- super(nd, record);
- }
-
- public SubClass(Nd nd, AllObjects deletionDetector) {
- super(nd, deletionDetector);
- }
- }
-
- public static class Reference extends NdNode {
- public static final FieldManyToOne<BaseClass> BASE_CLASS_REFERENCE;
- public static final FieldManyToOne<BaseClass> OWNER;
- public static final FieldManyToOne<SubClass> SUB_CLASS_REFERENCE;
- public static final FieldManyToOne<AllObjects> DELETION_DETECTOR;
-
- @SuppressWarnings("hiding")
- public static StructDef<Reference> type;
-
- static {
- type = StructDef.create(Reference.class, NdNode.type);
-
- BASE_CLASS_REFERENCE = FieldManyToOne.create(type, BaseClass.INCOMING_REFERENCES);
- OWNER = FieldManyToOne.createOwner(type, BaseClass.OWNED_REFERENCES);
- SUB_CLASS_REFERENCE = FieldManyToOne.create(type, SubClass.MORE_REFERENCES);
- DELETION_DETECTOR = FieldManyToOne.create(type, AllObjects.REFERENCE_INSTANCES);
- type.done();
- }
-
- public Reference(Nd nd, long record) {
- super(nd, record);
- }
-
- public Reference(Nd nd, AllObjects deletionDetector) {
- super(nd);
-
- DELETION_DETECTOR.put(nd, this.address, deletionDetector);
- }
-
- public void setBaseClassReference(BaseClass target) {
- BASE_CLASS_REFERENCE.put(getNd(), this.address, target);
- }
-
- public void setOwner(BaseClass target) {
- OWNER.put(getNd(), this.address, target);
- }
-
- public void setSubClassReference(SubClass target) {
- SUB_CLASS_REFERENCE.put(getNd(), this.address, target);
- }
- }
-
- AllObjects allObjects;
- BaseClass baseClass;
- SubClass subClass;
- Reference refA;
- Reference refB;
- Reference refC;
- private Nd nd;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- NdNodeTypeRegistry<NdNode> registry = new NdNodeTypeRegistry<>();
- registry.register(0, BaseClass.type.getFactory());
- registry.register(1, SubClass.type.getFactory());
- registry.register(2, Reference.type.getFactory());
- registry.register(3, AllObjects.type.getFactory());
- this.nd = DatabaseTestUtil.createEmptyNd(getName(), registry);
- this.nd.getDB().setExclusiveLock();
-
- this.allObjects = new AllObjects(this.nd);
- this.baseClass = new BaseClass(this.nd, this.allObjects);
- this.subClass = new SubClass(this.nd, this.allObjects);
-
- this.refA = new Reference(this.nd, this.allObjects);
- this.refB = new Reference(this.nd, this.allObjects);
- this.refC = new Reference(this.nd, this.allObjects);
- }
-
- public static Test suite() {
- return BaseTestCase.suite(InheritenceTests.class);
- }
-
- public void testRemovingOnlyRefcountDeletesObject() {
- assertTrue(this.allObjects.contains(this.subClass));
- this.refA.setSubClassReference(this.subClass);
- this.refA.setSubClassReference(null);
- this.nd.processDeletions();
- assertFalse(this.allObjects.contains(this.subClass));
- }
-
- public void testReferencesToBaseClassIncludedInRefCountA() {
- // Test what happens when the subclass reference is removed first.
- this.refA.setSubClassReference(this.subClass);
- this.refB.setBaseClassReference(this.subClass);
- assertTrue(this.allObjects.contains(this.subClass));
- this.refA.setSubClassReference(null);
- this.nd.processDeletions();
- assertTrue(this.allObjects.contains(this.subClass));
- this.refB.setBaseClassReference(null);
- this.nd.processDeletions();
- assertFalse(this.allObjects.contains(this.subClass));
- }
-
- public void testReferencesToBaseClassIncludedInRefCountB() {
- // Test what happens when the base class reference is removed first.
- this.refA.setSubClassReference(this.subClass);
- this.refB.setBaseClassReference(this.subClass);
- this.nd.processDeletions();
- assertTrue(this.allObjects.contains(this.subClass));
- this.refB.setBaseClassReference(null);
- this.nd.processDeletions();
- assertTrue(this.allObjects.contains(this.subClass));
- this.refA.setSubClassReference(null);
- this.nd.processDeletions();
- assertFalse(this.allObjects.contains(this.subClass));
- }
-
- public void testOwnedPointersDontCountTowardsRefCount() {
- this.refA.setOwner(this.subClass);
- this.nd.processDeletions();
- assertTrue(this.allObjects.contains(this.subClass));
- this.refB.setBaseClassReference(this.subClass);
- this.nd.processDeletions();
- assertTrue(this.allObjects.contains(this.subClass));
- assertTrue(this.allObjects.contains(this.refA));
- this.refB.setBaseClassReference(null);
- this.nd.processDeletions();
- assertFalse(this.allObjects.contains(this.subClass));
- assertFalse(this.allObjects.contains(this.refA));
- }
-
- public void testMultipleReferences() {
- this.refA.setBaseClassReference(this.subClass);
- this.refB.setBaseClassReference(this.subClass);
- this.refA.setBaseClassReference(null);
- this.nd.processDeletions();
- assertTrue(this.allObjects.contains(this.subClass));
- this.refB.setBaseClassReference(null);
- this.nd.processDeletions();
- assertFalse(this.allObjects.contains(this.subClass));
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/LargeBlockTest.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/LargeBlockTest.java
deleted file mode 100644
index d239287ffc..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/LargeBlockTest.java
+++ /dev/null
@@ -1,409 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2016 QNX Software Systems and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * QNX Software Systems - initial API and implementation
- * Andrew Ferguson (Symbian)
- * Markus Schorn (Wind River Systems)
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import org.eclipse.jdt.core.tests.nd.util.BaseTestCase;
-import org.eclipse.jdt.internal.core.nd.Nd;
-import org.eclipse.jdt.internal.core.nd.db.Database;
-
-import junit.framework.Test;
-
-/**
- * Tests for the {@link Database} class.
- */
-public class LargeBlockTest extends BaseTestCase {
- private Nd nd;
- protected Database db;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- String testName = getName();
- this.nd = DatabaseTestUtil.createWithoutNodeRegistry(testName);
- this.db = this.nd.getDB();
- this.db.setExclusiveLock();
- this.db.flush();
- }
-
- public static Test suite() {
- return BaseTestCase.suite(LargeBlockTest.class);
- }
-
- @Override
- protected void tearDown() throws Exception {
- DatabaseTestUtil.deleteDatabase(this.db);
- this.db = null;
- }
-
- private long mallocChunks(int chunks) {
- return malloc(Database.getBytesThatFitInChunks(chunks));
- }
-
- private long malloc(long bytes) {
- return this.db.malloc(bytes, Database.POOL_MISC);
- }
-
- private void free(long address) {
- this.db.free(address, Database.POOL_MISC);
- }
-
- /**
- * Allocate the maximum number of bytes that can fit in 3 chunks and verify
- * that it doesn't overflow.
- */
- public void testAllocationThatFillsMultipleChunksDoesntOverflow() throws Exception {
- int chunkCount = this.db.getChunkCount();
-
- int numChunks = 5;
- mallocChunks(numChunks);
-
- assertEquals("The database should not allocate more (or less) memory than is needed", numChunks + chunkCount,
- this.db.getChunkCount());
- }
-
- /**
- * Allocates a few blocks, frees them, then allocates more blocks. Verifies
- * that the database reuses the chunks from the first allocation when it
- * tries to allocate the larger block later.
- */
- public void testLastChunkIsReused() throws Exception {
- int chunkCount = this.db.getChunkCount();
-
- int numChunks = 10;
- long temporaryBlockAddress = mallocChunks(3);
- free(temporaryBlockAddress);
- mallocChunks(numChunks);
-
- assertEquals("If the last chunk is free, it should be resized if necessary when a new chunk is requested",
- numChunks + chunkCount, this.db.getChunkCount());
- }
-
- /**
- * Tests that if there is a single large free block available, that block
- * will be split and reused if necessary to satisfy a number of smaller
- * requests.
- *
- * @throws Exception
- */
- public void testLargeAllocationIsSplitAndReused() throws Exception {
- long tempAddress = malloc(Database.getBytesThatFitInChunks(10));
- // Use some space at the end of the database to prevent the allocator
- // from using the end of the database, where stuff can be easily resized
- mallocChunks(1);
- free(tempAddress);
-
- // Keep track of how much memory we are currently using, so we can
- // ensure that any further allocations come from the freed block rather
- // than the end of the database.
- int chunkCount = this.db.getChunkCount();
-
- long firstAllocation = mallocChunks(7);
-
- assertEquals("The freed chunk should be reused (there should be 10 chunks available)", chunkCount,
- this.db.getChunkCount());
-
- long secondAllocation = mallocChunks(1);
-
- assertEquals("The freed chunk should be reused (there should be 3 chunks available)", chunkCount,
- this.db.getChunkCount());
-
- long thirdAllocation = mallocChunks(2);
-
- assertEquals("The freed chunk should be reused (there should be exactly 2 chunks available)", chunkCount,
- this.db.getChunkCount());
- assertTrue(
- "Allocations should happen from the start of the database if it makes no difference to fragmentation",
- secondAllocation > firstAllocation);
- assertTrue("Free space should have been kept next to the largest block for as long as possible",
- secondAllocation > thirdAllocation);
-
- // Do another allocation when there are no free chunks
- mallocChunks(1);
-
- assertEquals("New chunks should be allocated when the database is out of free blocks", chunkCount + 1,
- this.db.getChunkCount());
- }
-
- /**
- * Verifies that if a block is freed and the previous block is also free,
- * the two free blocks will be combined into a single larger block.
- */
- public void testFreeBlockMergesWithPrevious() throws Exception {
- long firstBlock = mallocChunks(1);
- long secondBlock = mallocChunks(1);
- mallocChunks(1);
-
- free(firstBlock);
- free(secondBlock);
-
- int chunkCount = this.db.getChunkCount();
-
- mallocChunks(2);
- assertEquals("The merged block should have been used", chunkCount, this.db.getChunkCount());
- }
-
- /**
- * Verifies that if a block is freed and the next block is also free, the
- * two free blocks will be combined into a single larger block.
- */
- public void testFreeBlockMergesWithNext() throws Exception {
- long firstBlock = mallocChunks(1);
- long secondBlock = mallocChunks(1);
- mallocChunks(1);
-
- free(secondBlock);
- free(firstBlock);
-
- int chunkCount = this.db.getChunkCount();
-
- mallocChunks(2);
- assertEquals("The merged block should have been used", chunkCount, this.db.getChunkCount());
- }
-
- /**
- * Verifies that if a block is freed and the blocks on both sides are also
- * free, the three free blocks will be combined into a single larger block.
- */
- public void testFreeBlockMergesWithBothNextAndPrevious() throws Exception {
- long firstBlock = mallocChunks(1);
- long secondBlock = mallocChunks(1);
- long thirdBlock = mallocChunks(1);
- mallocChunks(1);
-
- free(firstBlock);
- free(thirdBlock);
- free(secondBlock);
-
- int chunkCount = this.db.getChunkCount();
-
- mallocChunks(3);
- assertEquals("The merged block should have been used", chunkCount, this.db.getChunkCount());
- }
-
- /**
- * Tests removal of a chunk from the free space trie when there are
- * duplicate free space nodes with the same size and the node being removed
- * isn't the one with the embedded trie node.
- */
- public void testRemoveFreeSpaceNodeFromDuplicateList() throws Exception {
- long chunk1 = mallocChunks(1);
- mallocChunks(1);
- long chunk3 = mallocChunks(1);
- long chunk4 = mallocChunks(1);
- mallocChunks(1);
-
- int chunkCount = this.db.getChunkCount();
-
- free(chunk1);
- free(chunk3);
- // At this point chunks 1 and 3 should be in the same linked list. Chunk
- // 1 contains the embedded trie.
-
- free(chunk4);
- // Should merge with chunk3, causing it to be removed from the list
-
- // Verify that we can allocate the merged chunk 3+4
- mallocChunks(2);
-
- assertEquals("Chunks 3 and 4 should have been merged", chunkCount, this.db.getChunkCount());
- }
-
- /**
- * Tests removal of a chunk from the free space trie when the node being
- * removed was part of the embedded trie and it has a non-empty list of
- * other nodes of the same size.
- */
- public void testRemoveFreeSpaceNodeFromTrieWithDuplicates() throws Exception {
- long chunk1 = mallocChunks(1);
- mallocChunks(1);
- long chunk3 = mallocChunks(1);
- long chunk4 = mallocChunks(1);
- mallocChunks(1);
-
- int chunkCount = this.db.getChunkCount();
-
- free(chunk3);
- free(chunk1);
- // At this point chunks 1 and 3 should be in the same linked list. Chunk
- // 3 contains the embedded trie.
-
- free(chunk4);
- // Should merge with chunk3, causing it to be removed from the list
-
- // Verify that we can allocate the merged chunk 3+4
- mallocChunks(2);
-
- assertEquals("Chunks 3 and 4 should have been merged", chunkCount, this.db.getChunkCount());
- }
-
- /**
- * Tests reusing a chunk from the free space trie when it contains
- * duplicates.
- */
- public void testReuseDeallocatedChunksWithMultipleFreeSpaceNodesOfTheSameSize() throws Exception {
- long chunk1 = mallocChunks(2);
- mallocChunks(1);
- long chunk3 = mallocChunks(2);
- mallocChunks(1);
- long chunk5 = mallocChunks(2);
- mallocChunks(1);
-
- int chunkCount = this.db.getChunkCount();
-
- free(chunk1);
- free(chunk3);
- free(chunk5);
-
- mallocChunks(2);
-
- assertEquals("A chunk should have been reused", chunkCount, this.db.getChunkCount());
- }
-
- public void testEndOfFreeBlockIsUsedIfThePreviousBlockIsLargerThanTheNextBlock() throws Exception {
- long prevChunk = mallocChunks(4);
- long middleChunk = mallocChunks(4);
- long nextChunk = mallocChunks(2);
-
- free(middleChunk);
- // This should be taken from the end of "middleChunk", since that's closer to the smaller neighbor
- long smallChunk1 = mallocChunks(1);
- // This should also be taken from the end of the remaining portion of "middleChunk"
- long smallChunk2 = mallocChunks(1);
-
- assertTrue("The small chunks should have been allocated from space after 'prevChunk'",
- prevChunk < smallChunk2);
- assertTrue("The small chunks should have been allocated from the end of the free block",
- smallChunk2 < smallChunk1);
- assertTrue("The small chunks should have been allocated from space before 'nextChunk'",
- smallChunk1 < nextChunk);
- }
-
- /**
- * Tests various corner cases in the trie map.
- */
- public void testTriesOfVariousSize() throws Exception {
- long chunk1 = mallocChunks(1);
- mallocChunks(1);
- long chunk2 = mallocChunks(2);
- mallocChunks(1);
- long chunk3 = mallocChunks(3);
- mallocChunks(1);
- long chunk4 = mallocChunks(5);
- mallocChunks(1);
- long chunk5 = mallocChunks(6);
- mallocChunks(1);
- long chunk6 = mallocChunks(6);
- mallocChunks(1);
- long chunk7 = mallocChunks(10);
- mallocChunks(1);
- long chunk8 = mallocChunks(20);
- mallocChunks(1);
-
- int chunkCount = this.db.getChunkCount();
-
- free(chunk7);
- free(chunk4);
- free(chunk1);
- free(chunk3);
- free(chunk8);
- free(chunk5);
- free(chunk2);
- free(chunk6);
-
- mallocChunks(4);
- mallocChunks(10);
-
- assertEquals("A chunk should have been reused", chunkCount, this.db.getChunkCount());
- }
-
- /**
- * Tests that if there are multiple free blocks of different sizes and of
- * exactly one of the requested size, that one is always selected.
- */
- public void testBestBlockIsAlwaysSelected() throws Exception {
- int[] sizes = { 11, 2, 6, 1, 9, 10, 7, 8, 12, 20, 15, 3 };
- long[] pointers = new long[sizes.length];
-
- for (int idx = 0; idx < sizes.length; idx++) {
- pointers[idx] = mallocChunks(sizes[idx]);
- mallocChunks(1);
- }
-
- int chunkCount = this.db.getChunkCount();
-
- for (int idx = 0; idx < pointers.length; idx++) {
- free(pointers[idx]);
- }
-
- for (int idx = 0; idx < sizes.length; idx++) {
- long nextPointer = mallocChunks(sizes[idx]);
- assertEquals("Returned wrong pointer for malloc of " + sizes[idx] + " chunks", pointers[idx], nextPointer);
- assertEquals("A chunk should have been reused", chunkCount, this.db.getChunkCount());
- }
- }
-
- /**
- * Tests removals from the large chunk sibling list. Ensures that such removals don't interfere with
- * the trie itself.
- */
- public void testUnlinkedBlockNotInTrieGetsRelinked() throws Exception {
- long rootChunk = mallocChunks(1);
- mallocChunks(1);
- long unusedChunk = mallocChunks(1);
- mallocChunks(1);
- long chunkToBeMerged = mallocChunks(1);
- long chunkThatWillCauseMerging = mallocChunks(1);
- mallocChunks(1);
- long followingChunkInFreeSpaceList = mallocChunks(1);
- mallocChunks(1);
- long chunkOfSize2 = mallocChunks(2);
- mallocChunks(1);
-
- int chunkCount = this.db.getChunkCount();
-
- free(rootChunk);
- free(unusedChunk);
- free(chunkToBeMerged);
- free(followingChunkInFreeSpaceList);
- free(chunkOfSize2);
-
- // At this point, the free space trie looks like this:
- //
- // size 1: rootChunk -> unusedChunk -> chunkToBeMerged -> followingChunkInFreeSpaceList
- // -> size 2: chunkOfSize2
- //
- // By freeing chunkThatWillCauseMerging, chunkToBeMerged will be removed from the
- // list of size 1 and inserted into the list of size 2. This test verifies that the
- // code won't mess with the root pointer by inserting unusedChunk or chunk into the root
-
- // This call will corrupt the database if we don't do the removal correctly
- free(chunkThatWillCauseMerging);
-
- // Now reallocate the original chunks to ensure they can all be found in the list
- long firstDoubleChunk = mallocChunks(2);
- long secondDoubleChunk = mallocChunks(2);
-
- mallocChunks(1);
- mallocChunks(1);
- mallocChunks(1);
-
- assertEquals("A chunk should have been reused", chunkCount, this.db.getChunkCount());
- assertNotSame("Both new chunks should have been unique", firstDoubleChunk, secondDoubleChunk);
- assertNotSame("The first chunk should not be null", 0, firstDoubleChunk);
- assertNotSame("The second chunk should not be null", 0, secondDoubleChunk);
- this.db.validateFreeSpace();
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/Package.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/Package.java
deleted file mode 100644
index 92a7f0e159..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/Package.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2015, 2016 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import org.eclipse.core.runtime.ILog;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Plugin;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jdt.core.JavaCore;
-
-/**
- * @noreference This class is not intended to be referenced by clients
- */
-/* package */ class Package {
- public static String PLUGIN_ID = JavaCore.PLUGIN_ID;
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public static void log(Throwable e) {
- String msg= e.getMessage();
- if (msg == null) {
- log("Error", e); //$NON-NLS-1$
- } else {
- log("Error: " + msg, e); //$NON-NLS-1$
- }
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public static void log(String message, Throwable e) {
- log(createStatus(message, e));
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public static IStatus createStatus(String msg, Throwable e) {
- return new Status(IStatus.ERROR, PLUGIN_ID, msg, e);
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public static IStatus createStatus(String msg) {
- return new Status(IStatus.ERROR, PLUGIN_ID, msg);
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- *
- * Returns the appropriate ILog for this package
- */
- public static ILog getLog() {
- Plugin plugin = JavaCore.getPlugin();
- if (plugin == null) {
- return null;
- }
- return plugin.getLog();
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public static void log(IStatus status) {
- getLog().log(status);
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/RunIndexTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/RunIndexTests.java
deleted file mode 100644
index 28ad856271..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/RunIndexTests.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2015, 2016 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-
-import org.eclipse.jdt.core.tests.junit.extension.TestCase;
-import org.eclipse.jdt.core.tests.nd.indexer.IndexerTest;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-@SuppressWarnings({"rawtypes", "unchecked"})
-public class RunIndexTests extends junit.framework.TestCase {
-public RunIndexTests(String name) {
- super(name);
-}
-public static Class[] getAllTestClasses() {
- return new Class[] {
- BTreeTests.class,
- ChunkWriterTests.class,
- DatabaseTest.class,
- FieldBackPointerTest.class,
- FieldListTest.class,
- FieldOneToOneTest.class,
- IndexerTest.class,
- InheritenceTests.class,
- LargeBlockTest.class,
- SearchKeyTests.class
- };
-}
-public static Test suite() {
- TestSuite ts = new TestSuite(RunIndexTests.class.getName());
-
- Class[] testClasses = getAllTestClasses();
- // Reset forgotten subsets of tests
- TestCase.TESTS_PREFIX = null;
- TestCase.TESTS_NAMES = null;
- TestCase.TESTS_NUMBERS = null;
- TestCase.TESTS_RANGE = null;
- TestCase.RUN_ONLY_ID = null;
-
- for (int i = 0; i < testClasses.length; i++) {
- Class testClass = testClasses[i];
-
- // call the suite() method and add the resulting suite to the suite
- try {
- Method suiteMethod = testClass.getDeclaredMethod("suite", new Class[0]); //$NON-NLS-1$
- Test suite = (Test)suiteMethod.invoke(null, new Object[0]);
- ts.addTest(suite);
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- e.getTargetException().printStackTrace();
- } catch (NoSuchMethodException e) {
- e.printStackTrace();
- }
- }
- return ts;
-}
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/SearchKeyTests.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/SearchKeyTests.java
deleted file mode 100644
index b50cc0fe64..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/SearchKeyTests.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2015, 2016 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd;
-
-import org.eclipse.jdt.core.tests.nd.util.BaseTestCase;
-import org.eclipse.jdt.internal.core.nd.Nd;
-import org.eclipse.jdt.internal.core.nd.NdNode;
-import org.eclipse.jdt.internal.core.nd.NdNodeTypeRegistry;
-import org.eclipse.jdt.internal.core.nd.db.Database;
-import org.eclipse.jdt.internal.core.nd.field.FieldSearchIndex;
-import org.eclipse.jdt.internal.core.nd.field.FieldSearchKey;
-import org.eclipse.jdt.internal.core.nd.field.StructDef;
-
-import junit.framework.Test;
-
-public class SearchKeyTests extends BaseTestCase {
- private static final String SEARCH_STRING_B = "Yo";
- private static final String SEARCH_STRING_A = "Heyguyswhatshappening";
- private static final String SEARCH_STRING_C = "Shnoogins";
-
- public static class TestSearchIndex {
- public static final FieldSearchIndex<Element> NICKNAME_INDEX;
- public static final FieldSearchIndex<Element> NAME_INDEX;
-
- public static final StructDef<TestSearchIndex> type;
-
- static {
- type = StructDef.create(TestSearchIndex.class);
- NICKNAME_INDEX = FieldSearchIndex.create(type, Element.NICKNAME);
- NAME_INDEX = FieldSearchIndex.create(type, Element.NAME);
- type.done();
- }
-
- private final long address;
- private Nd nd;
-
- public TestSearchIndex(Nd dom, long address) {
- this.address = address;
- this.nd = dom;
- }
-
- public static TestSearchIndex getIndex(Nd nd) {
- return new TestSearchIndex(nd, Database.DATA_AREA_OFFSET);
- }
-
- public Element findName(String searchString) {
- return NAME_INDEX.findFirst(this.nd, this.address,
- FieldSearchIndex.SearchCriteria.create(searchString.toCharArray()));
- }
-
- public Element findNickName(String searchString) {
- return NICKNAME_INDEX.findFirst(this.nd, this.address,
- FieldSearchIndex.SearchCriteria.create(searchString.toCharArray()));
- }
- }
-
- public static class Element extends NdNode {
- public static final FieldSearchKey<TestSearchIndex> NAME;
- public static final FieldSearchKey<TestSearchIndex> NICKNAME;
-
- @SuppressWarnings("hiding")
- public static StructDef<Element> type;
-
- static {
- type = StructDef.create(Element.class, NdNode.type);
-
- NAME = FieldSearchKey.create(type, TestSearchIndex.NAME_INDEX);
- NICKNAME = FieldSearchKey.create(type, TestSearchIndex.NICKNAME_INDEX);
- type.done();
- }
-
- public Element(Nd nd, long record) {
- super(nd, record);
- }
-
- public Element(Nd nd) {
- super(nd);
- }
-
- public void setName(String searchStringA) {
- NAME.put(getNd(), this.address, searchStringA);
- }
-
- public void setNickName(String searchStringA) {
- NICKNAME.put(getNd(), this.address, searchStringA);
- }
- }
-
- private Nd nd;
- private Element elementA;
- private Element elementB;
- private TestSearchIndex index;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- NdNodeTypeRegistry<NdNode> registry = new NdNodeTypeRegistry<>();
- registry.register(0, Element.type.getFactory());
- this.nd = DatabaseTestUtil.createEmptyNd(getName(), registry);
- this.nd.getDB().setExclusiveLock();
-
- this.elementA = new Element(this.nd);
- this.elementB = new Element(this.nd);
-
- this.index = TestSearchIndex.getIndex(this.nd);
- }
-
- public static Test suite() {
- return BaseTestCase.suite(SearchKeyTests.class);
- }
-
- public void testSettingKeyCausesInsertionInSearchIndex() {
- this.elementA.setName(SEARCH_STRING_A);
- this.elementB.setName(SEARCH_STRING_B);
-
- Element foundElementA = this.index.findName(SEARCH_STRING_A);
- Element foundElementB = this.index.findName(SEARCH_STRING_B);
- Element foundElementC = this.index.findName(SEARCH_STRING_C);
-
- assertEquals(this.elementA, foundElementA);
- assertEquals(this.elementB, foundElementB);
- assertEquals(null, foundElementC);
- }
-
- public void testChangingSearchKeyAffectsIndex() {
- this.elementA.setName(SEARCH_STRING_A);
-
- Element foundElementA = this.index.findName(SEARCH_STRING_A);
- Element foundElementB = this.index.findName(SEARCH_STRING_B);
-
- assertEquals(null, foundElementB);
- assertEquals(this.elementA, foundElementA);
-
- this.elementA.setName(SEARCH_STRING_B);
-
- foundElementA = this.index.findName(SEARCH_STRING_A);
- foundElementB = this.index.findName(SEARCH_STRING_B);
-
- assertEquals(this.elementA, foundElementB);
- assertEquals(null, foundElementA);
- }
-
- public void testDeletingElementRemovesFromIndex() {
- this.elementA.setName(SEARCH_STRING_A);
- this.elementA.setNickName(SEARCH_STRING_B);
-
- assertEquals(this.elementA, this.index.findName(SEARCH_STRING_A));
- assertEquals(this.elementA, this.index.findNickName(SEARCH_STRING_B));
-
- this.elementA.delete();
- this.nd.processDeletions();
- assertEquals(null, this.index.findName(SEARCH_STRING_A));
- assertEquals(null, this.index.findNickName(SEARCH_STRING_B));
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/indexer/IndexerTest.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/indexer/IndexerTest.java
deleted file mode 100644
index 72873001be..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/indexer/IndexerTest.java
+++ /dev/null
@@ -1,288 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2015, 2016 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd.indexer;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Objects;
-import java.util.concurrent.Semaphore;
-import java.util.function.Function;
-import java.util.stream.Collectors;
-
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubMonitor;
-import org.eclipse.jdt.core.IClassFile;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IOrdinaryClassFile;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.IParent;
-import org.eclipse.jdt.core.tests.model.AbstractJavaModelTests;
-import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
-import org.eclipse.jdt.internal.core.nd.IReader;
-import org.eclipse.jdt.internal.core.nd.db.ChunkCache;
-import org.eclipse.jdt.internal.core.nd.db.Database;
-import org.eclipse.jdt.internal.core.nd.indexer.IndexTester;
-import org.eclipse.jdt.internal.core.nd.indexer.Indexer;
-import org.eclipse.jdt.internal.core.nd.java.JavaIndex;
-import org.eclipse.jdt.internal.core.nd.java.NdType;
-import org.eclipse.jdt.internal.core.nd.java.NdTypeId;
-import org.eclipse.jdt.internal.core.nd.java.model.BinaryTypeDescriptor;
-import org.eclipse.jdt.internal.core.nd.java.model.BinaryTypeFactory;
-import org.eclipse.jdt.internal.core.nd.java.model.IndexBinaryType;
-
-import junit.framework.Test;
-
-/**
- * Tests for the {@link Database} class.
- */
-public class IndexerTest extends AbstractJavaModelTests {
-
- public IndexerTest(String name) {
- super(name);
- }
-
- private static final String PROJECT_NAME = "IndexerTest";
- private static JavaIndex index;
-
- @Override
- protected void setUp() throws Exception {
- String testName = getName();
- index = JavaIndexTestUtil.createTempIndex(testName);
- super.setUp();
- }
-
- @Override
- protected void tearDown() throws Exception {
- deleteProject(PROJECT_NAME);
- index.getNd().getPath().delete();
- index = null;
- super.tearDown();
- }
-
- public static Test suite() {
- return buildModelTestSuite(IndexerTest.class);
- }
-
- /**
- * Verifies that if the index fails a read due to call to {@link Thread#interrupt()}, subsequent reads will
- * still succeed.
- */
- public void testInterruptedException() throws Exception {
- createJavaProject(PROJECT_NAME, new String[] {"src"}, new String[] {"JCL18_FULL"}, "bin", "1.8", true);
- // Create an indexfa
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- Indexer indexer = new Indexer(index.getNd(), root);
- indexer.rescan(SubMonitor.convert(null));
- // Ensure we're starting with an empty page cache by creating a new
- // Index accessor object on the same database
- JavaIndex testIndex = JavaIndex
- .getIndex(JavaIndex.createNd(index.getNd().getDB().getLocation(), new ChunkCache()));
-
- Semaphore semaphore = new Semaphore(0);
-
- boolean[] wasInterrupted = new boolean[1];
- Thread newThread = new Thread(() -> {
- try (IReader reader = testIndex.getNd().acquireReadLock()) {
- Thread.currentThread().interrupt();
- testIndex.findType("Ljava/util/List;".toCharArray());
- } catch (OperationCanceledException e) {
- wasInterrupted[0] = true;
- } finally {
- semaphore.release();
- }
- });
-
- newThread.start();
-
- semaphore.acquire();
-
- assertTrue(wasInterrupted[0]);
- try (IReader reader = testIndex.getNd().acquireReadLock()) {
- NdTypeId type = testIndex.findType("Ljava/util/List;".toCharArray());
- assertNotNull(type);
- }
- }
-
- public void testSubclassesOfGenericTypeCanBeFound() throws Exception {
- createJavaProject(PROJECT_NAME, new String[] {"src"}, new String[] {"JCL18_FULL"}, "bin", "1.8", true);
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- Indexer indexer = new Indexer(index.getNd(), root);
-
- indexer.rescan(SubMonitor.convert(null));
-
- try (IReader reader = IndexerTest.index.getNd().acquireReadLock()) {
- NdTypeId javaUtilList = IndexerTest.index.findType("Ljava/util/List;".toCharArray());
- NdTypeId javaUtilArrayList = IndexerTest.index.findType("Ljava/util/ArrayList;".toCharArray());
-
- boolean found = false;
- List<NdType> subtypes = javaUtilList.getSubTypes();
- for (NdType next : subtypes) {
- if (Objects.equals(next.getTypeId(), javaUtilArrayList)) {
- found = true;
- }
- }
-
- assertTrue("ArrayList was found as a subtype of List", found);
- }
- }
-
- private void collectAllClassFiles(List<? super IClassFile> result, IParent nextRoot) throws CoreException {
- for (IJavaElement child : nextRoot.getChildren()) {
- int type = child.getElementType();
-
- if (type == IJavaElement.CLASS_FILE) {
- result.add((IClassFile) child);
- } else if (child instanceof IParent) {
- IParent parent = (IParent) child;
-
- collectAllClassFiles(result, parent);
- }
- }
- }
-
- public void testReadingAllClassesInIndexAreEquivalentToOriginalJarFiles() throws Exception {
- IJavaProject javaProject = createJavaProject(PROJECT_NAME, new String[] {"src"}, new String[] {"JCL18_FULL"}, "bin", "1.8", true);
- addClassFolder(javaProject, "lib", new String[] {
- "p/Outer.java",
- "import java.lang.annotation.*;\n" +
- "\n" +
- "@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE_USE) @interface A0 {}\n" +
- "@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE_USE) @interface A {}\n" +
- "@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface M {}\n" +
- "@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) @interface P {}\n" +
- "\n" +
- "class Outer {\n" +
- " class Middle1 {\n" +
- " class Inner {}\n" +
- " }\n" +
- " static class Middle2 {\n" +
- " class Inner {}\n" +
- " static class Middle3 {\n" +
- " class Inner2{};\n" +
- " }\n" +
- " }\n" +
- " Middle1.@A Inner e1;\n" +
- " Middle2.@A Inner e2;\n" +
- " Middle2.Middle3.@A Inner2 e3;\n" +
- " @M void foo(@A0 Object p0, @P Middle2.Middle3.@A Inner2 e3) {};\n" +
- " class Middle4 extends @A Middle1 {}\n" +
- "}\n",
- }, "1.8");
-
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- Indexer indexer = new Indexer(index.getNd(), root);
-
- indexer.rescan(SubMonitor.convert(null));
-
- boolean foundAtLeastOneClass = false;
- SubMonitor subMonitor = SubMonitor.convert(null);
- JavaIndex localIndex = IndexerTest.index;
- try (IReader reader = localIndex.getNd().acquireReadLock()) {
- IPackageFragmentRoot[] roots = javaProject.getAllPackageFragmentRoots();
- subMonitor.setWorkRemaining(roots.length);
- for (IPackageFragmentRoot next : roots) {
- SubMonitor iterationMon = subMonitor.split(1);
- if (next.getKind() == IPackageFragmentRoot.K_BINARY) {
- List<IClassFile> result = new ArrayList<>();
- collectAllClassFiles(result, next);
- iterationMon.setWorkRemaining(result.size());
- for (IClassFile nextClass : result) {
- if (!(nextClass instanceof IOrdinaryClassFile)) continue;
- SubMonitor classMon = iterationMon.split(1);
- BinaryTypeDescriptor descriptor = BinaryTypeFactory.createDescriptor(nextClass);
- IndexBinaryType indexedBinaryType = (IndexBinaryType)BinaryTypeFactory.readFromIndex(localIndex, descriptor, classMon);
- ClassFileReader originalBinaryType = BinaryTypeFactory.rawReadType(descriptor, true);
-
- if (!indexedBinaryType.exists()) {
- throw new IllegalStateException("Unable to find class in index " + new String(descriptor.indexPath));
- }
- IndexTester.testType(originalBinaryType, indexedBinaryType);
- foundAtLeastOneClass = true;
- }
- }
- }
- }
- assertTrue("No classes found in the index", foundAtLeastOneClass);
- }
-
- public void testFindTypesBySimpleName() throws CoreException {
- createJavaProject(PROJECT_NAME, new String[] {"src"}, new String[] {"JCL18_FULL"}, "bin", "1.8", true);
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- Indexer indexer = new Indexer(index.getNd(), root);
-
- indexer.rescan(SubMonitor.convert(null));
-
- try (IReader reader = IndexerTest.index.getNd().acquireReadLock()) {
- List<Object> javaUtilList = IndexerTest.index.findTypesBySimpleName("ArrayList".toCharArray()).stream()
- .map(new Function<NdTypeId, String>() {
- @Override
- public String apply(NdTypeId typeId) {
- return typeId.toString();
- }
- }).collect(Collectors.toList());
- System.out.println(javaUtilList);
- assertTrue("Test failed", javaUtilList.contains("Ljava/util/ArrayList;"));
- }
- }
-
- public void testFindTypesBySimpleNameFirstWord() throws CoreException {
- createJavaProject(PROJECT_NAME, new String[] {"src"}, new String[] {"JCL18_FULL"}, "bin", "1.8", true);
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- Indexer indexer = new Indexer(index.getNd(), root);
-
- indexer.rescan(SubMonitor.convert(null));
-
- try (IReader reader = IndexerTest.index.getNd().acquireReadLock()) {
- List<Object> javaUtilList = IndexerTest.index.findTypesBySimpleName("Array".toCharArray()).stream()
- .map(new Function<NdTypeId, String>() {
- @Override
- public String apply(NdTypeId typeId) {
- return typeId.toString();
- }
- }).collect(Collectors.toList());
- System.out.println(javaUtilList);
- assertTrue("Test failed",
- javaUtilList.containsAll(Arrays.asList("Ljava/sql/Array;", "Ljava/lang/reflect/Array;",
- "Ljava/util/concurrent/ArrayBlockingQueue;", "Ljava/util/ArrayDeque;",
- "Ljava/lang/ArrayIndexOutOfBoundsException;", "Ljava/util/ArrayList;",
- "Ljava/util/ArrayPrefixHelpers;", "Ljava/util/Arrays;",
- "Ljava/util/ArraysParallelSortHelpers;", "Ljava/lang/ArrayStoreException;")));
- }
- }
-
- public void testFindTypesBySimpleNameFirstLetterCount10() throws CoreException {
- createJavaProject(PROJECT_NAME, new String[] {"src"}, new String[] {"JCL18_FULL"}, "bin", "1.8", true);
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- Indexer indexer = new Indexer(index.getNd(), root);
-
- indexer.rescan(SubMonitor.convert(null));
-
- try (IReader reader = IndexerTest.index.getNd().acquireReadLock()) {
- List<Object> javaUtilList = IndexerTest.index.findTypesBySimpleName("A".toCharArray(), 10).stream()
- .map(new Function<NdTypeId, String>() {
- @Override
- public String apply(NdTypeId typeId) {
- return typeId.toString();
- }
- }).collect(Collectors.toList());
- System.out.println(javaUtilList);
- assertTrue("Test failed", javaUtilList.size() == 10);
- }
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/indexer/JavaIndexTestUtil.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/indexer/JavaIndexTestUtil.java
deleted file mode 100644
index 5333623cdd..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/indexer/JavaIndexTestUtil.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2015, 2016 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd.indexer;
-
-import java.io.File;
-
-import org.eclipse.jdt.core.tests.nd.DatabaseTestUtil;
-import org.eclipse.jdt.internal.core.nd.db.ChunkCache;
-import org.eclipse.jdt.internal.core.nd.java.JavaIndex;
-
-public class JavaIndexTestUtil {
- public static JavaIndex createTempIndex(String id) {
- File dbName = DatabaseTestUtil.getTempDbName(id);
- return JavaIndex.getIndex(JavaIndex.createNd(dbName, new ChunkCache()));
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/BaseTestCase.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/BaseTestCase.java
deleted file mode 100644
index 6a9ef260b3..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/BaseTestCase.java
+++ /dev/null
@@ -1,272 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2006, 2016 Wind River Systems, Inc. and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Markus Schorn - initial API and implementation
- * Andrew Ferguson (Symbian)
- * Sergey Prigogin (Google)
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd.util;
-
-import junit.framework.AssertionFailedError;
-import junit.framework.Test;
-import junit.framework.TestCase;
-import junit.framework.TestFailure;
-import junit.framework.TestResult;
-import junit.framework.TestSuite;
-
-import org.eclipse.core.resources.IResourceStatus;
-import org.eclipse.core.runtime.ILog;
-import org.eclipse.core.runtime.ILogListener;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.MultiStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-
-import java.io.File;
-import java.io.IOException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Deque;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-public class BaseTestCase extends TestCase {
- private static final String DEFAULT_INDEXER_TIMEOUT_SEC = "10";
- private static final String INDEXER_TIMEOUT_PROPERTY = "indexer.timeout";
- /**
- * Indexer timeout used by tests. To avoid this timeout expiring during debugging add
- * -Dindexer.timeout=some_large_number to VM arguments of the test launch configuration.
- */
- protected static final int INDEXER_TIMEOUT_SEC =
- Integer.parseInt(System.getProperty(INDEXER_TIMEOUT_PROPERTY, DEFAULT_INDEXER_TIMEOUT_SEC));
- protected static final int INDEXER_TIMEOUT_MILLISEC= INDEXER_TIMEOUT_SEC * 1000;
-
- private boolean fExpectFailure;
- private int fBugNumber;
- private int fExpectedLoggedNonOK;
- private Deque<File> filesToDeleteOnTearDown= new ArrayDeque<>();
-
- public BaseTestCase() {
- super();
- }
-
- public BaseTestCase(String name) {
- super(name);
- }
-
- public static NullProgressMonitor npm() {
- return new NullProgressMonitor();
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- //CModelListener.sSuppressUpdateOfLastRecentlyUsed= true;
- }
-
- @Override
- protected void tearDown() throws Exception {
- for (File file; (file = this.filesToDeleteOnTearDown.pollLast()) != null;) {
- file.delete();
- }
- ResourceHelper.cleanUp();
- //TestScannerProvider.clear();
- super.tearDown();
- }
-
- protected void deleteOnTearDown(File file) {
- this.filesToDeleteOnTearDown.add(file);
- }
-
- protected File createTempFile(String prefix, String suffix) throws IOException {
- File file = File.createTempFile(prefix, suffix);
- this.filesToDeleteOnTearDown.add(file);
- return file;
- }
-
- protected File nonExistentTempFile(String prefix, String suffix) {
- File file= new File(System.getProperty("java.io.tmpdir"),
- prefix + System.currentTimeMillis() + suffix);
- this.filesToDeleteOnTearDown.add(file);
- return file;
- }
-
- public static TestSuite suite(Class<? extends BaseTestCase> clazz) {
- return suite(clazz, null);
- }
-
- protected static TestSuite suite(Class<? extends BaseTestCase> clazz, String failingTestPrefix) {
- TestSuite suite= new TestSuite(clazz);
- Test failing= getFailingTests(clazz, failingTestPrefix);
- if (failing != null) {
- suite.addTest(failing);
- }
- return suite;
- }
-
- private static Test getFailingTests(Class<? extends BaseTestCase> clazz, String prefix) {
- TestSuite suite= new TestSuite("Failing Tests");
- HashSet<String> names= new HashSet<>();
- Class<?> superClass= clazz;
- while (Test.class.isAssignableFrom(superClass) && !TestCase.class.equals(superClass)) {
- Method[] methods= superClass.getDeclaredMethods();
- for (Method method : methods) {
- addFailingMethod(suite, method, names, clazz, prefix);
- }
- superClass= superClass.getSuperclass();
- }
- if (suite.countTestCases() == 0) {
- return null;
- }
- return suite;
- }
-
- private static void addFailingMethod(TestSuite suite, Method m, Set<String> names,
- Class<? extends BaseTestCase> clazz, String prefix) {
- String name = m.getName();
- if (!names.add(name)) {
- return;
- }
- if (name.startsWith("test") || (prefix != null && !name.startsWith(prefix))) {
- return;
- }
- if (name.equals("tearDown") || name.equals("setUp") || name.equals("runBare")) {
- return;
- }
- if (Modifier.isPublic(m.getModifiers())) {
- Class<?>[] parameters = m.getParameterTypes();
- Class<?> returnType = m.getReturnType();
- if (parameters.length == 0 && returnType.equals(Void.TYPE)) {
- Test test = TestSuite.createTest(clazz, name);
- ((BaseTestCase) test).setExpectFailure(0);
- suite.addTest(test);
- }
- }
- }
-
- @Override
- public void runBare() throws Throwable {
- final List<IStatus> statusLog= Collections.synchronizedList(new ArrayList<>());
- ILogListener logListener= new ILogListener() {
- @Override
- public void logging(IStatus status, String plugin) {
- if (!status.isOK() && status.getSeverity() != IStatus.INFO) {
- switch (status.getCode()) {
- case IResourceStatus.NOT_FOUND_LOCAL:
- case IResourceStatus.NO_LOCATION_LOCAL:
- case IResourceStatus.FAILED_READ_LOCAL:
- case IResourceStatus.RESOURCE_NOT_LOCAL:
- // Logged by the resources plugin.
- return;
- }
- statusLog.add(status);
- }
- }
- };
- final ILog log = Package.getLog();
- if (log != null) { // Iff we don't run as a JUnit Plugin Test.
- log.addLogListener(logListener);
- }
-
- Throwable testThrowable= null;
- try {
- try {
- super.runBare();
- } catch (Throwable e) {
- testThrowable= e;
- }
-
- if (statusLog.size() != this.fExpectedLoggedNonOK) {
- StringBuilder msg= new StringBuilder("Expected number (" + this.fExpectedLoggedNonOK + ") of ");
- msg.append("Non-OK status objects in log differs from actual (" + statusLog.size() + ").\n");
- Throwable cause= null;
- if (!statusLog.isEmpty()) {
- synchronized (statusLog) {
- for (IStatus status : statusLog) {
- IStatus[] ss= {status};
- ss= status instanceof MultiStatus ? ((MultiStatus) status).getChildren() : ss;
- for (IStatus s : ss) {
- msg.append("\t" + s.getMessage() + " ");
-
- Throwable t= s.getException();
- cause= cause != null ? cause : t;
- if (t != null) {
- msg.append(t.getMessage() != null ? t.getMessage() : t.getClass().getCanonicalName());
- }
-
- msg.append("\n");
- }
- }
- }
- }
- cause= cause != null ? cause : testThrowable;
- AssertionFailedError afe= new AssertionFailedError(msg.toString());
- afe.initCause(cause);
- throw afe;
- }
- } finally {
- if (log != null) {
- log.removeLogListener(logListener);
- }
- }
-
- if (testThrowable != null)
- throw testThrowable;
- }
-
- @Override
- public void run(TestResult result) {
- if (!this.fExpectFailure || Boolean.parseBoolean(System.getProperty("SHOW_EXPECTED_FAILURES"))) {
- super.run(result);
- return;
- }
-
- result.startTest(this);
-
- TestResult r = new TestResult();
- super.run(r);
- if (r.failureCount() == 1) {
- TestFailure failure= r.failures().nextElement();
- String msg= failure.exceptionMessage();
- if (msg != null && msg.startsWith("Method \"" + getName() + "\"")) {
- result.addFailure(this, new AssertionFailedError(msg));
- }
- } else if (r.errorCount() == 0 && r.failureCount() == 0) {
- String err = "Unexpected success of " + getName();
- if (this.fBugNumber > 0) {
- err += ", bug #" + this.fBugNumber;
- }
- result.addFailure(this, new AssertionFailedError(err));
- }
-
- result.endTest(this);
- }
-
- public void setExpectFailure(int bugNumber) {
- this.fExpectFailure= true;
- this.fBugNumber= bugNumber;
- }
-
- /**
- * The last value passed to this method in the body of a testXXX method
- * will be used to determine whether or not the presence of non-OK status objects
- * in the log should fail the test. If the logged number of non-OK status objects
- * differs from the last value passed, the test is failed. If this method is not called
- * at all, the expected number defaults to zero.
- * @param count the expected number of logged error and warning messages
- */
- public void setExpectedNumberOfLoggedNonOKStatusObjects(int count) {
- this.fExpectedLoggedNonOK= count;
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/Package.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/Package.java
deleted file mode 100644
index f4aec9f0c9..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/Package.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2015, 2016 Google, Inc and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Stefan Xenos (Google) - Initial implementation
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd.util;
-
-import org.eclipse.core.runtime.ILog;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Plugin;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jdt.core.JavaCore;
-
-/**
- * @noreference This class is not intended to be referenced by clients
- */
-/* package */ class Package {
- public static String PLUGIN_ID = JavaCore.PLUGIN_ID;
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public static void log(Throwable e) {
- String msg= e.getMessage();
- if (msg == null) {
- log("Error", e); //$NON-NLS-1$
- } else {
- log("Error: " + msg, e); //$NON-NLS-1$
- }
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public static void log(String message, Throwable e) {
- log(createStatus(message, e));
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public static IStatus createStatus(String msg, Throwable e) {
- return new Status(IStatus.ERROR, PLUGIN_ID, msg, e);
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public static IStatus createStatus(String msg) {
- return new Status(IStatus.ERROR, PLUGIN_ID, msg);
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- *
- * Returns the appropriate ILog for this package
- */
- public static ILog getLog() {
- Plugin plugin = JavaCore.getPlugin();
- if (plugin == null) {
- return null;
- }
- return plugin.getLog();
- }
-
- /**
- * @noreference This method is not intended to be referenced by clients.
- */
- public static void log(IStatus status) {
- getLog().log(status);
- }
-}
diff --git a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/ResourceHelper.java b/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/ResourceHelper.java
deleted file mode 100644
index 1345e5af53..0000000000
--- a/org.eclipse.jdt.core.tests.model/src/org/eclipse/jdt/core/tests/nd/util/ResourceHelper.java
+++ /dev/null
@@ -1,576 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2009, 2016 Andrew Gvozdev and others.
- *
- * This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License 2.0
- * which accompanies this distribution, and is available at
- * https://www.eclipse.org/legal/epl-2.0/
- *
- * SPDX-License-Identifier: EPL-2.0
- *
- * Contributors:
- * Andrew Gvozdev - Initial API and implementation
- * James Blackburn (Broadcom Corp.)
- * Liviu Ionescu - bug 392416
- *******************************************************************************/
-package org.eclipse.jdt.core.tests.nd.util;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.charset.Charset;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.UUID;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.junit.Assert;
-
-/**
- * This class contains utility methods for creating resources
- * such as projects, files, folders etc. which are being used
- * in test fixture of unit tests.
- *
- * Some classes with similar idea worth to look at:
- * org.eclipse.core.filebuffers.tests.ResourceHelper,
- * org.eclipse.cdt.ui.tests.text.ResourceHelper.
- */
-public class ResourceHelper {
- private final static IProgressMonitor NULL_MONITOR = new NullProgressMonitor();
- private static final int MAX_RETRY= 5;
-
- private final static Set<String> externalFilesCreated = new HashSet<String>();
- private final static Set<IResource> resourcesCreated = new HashSet<IResource>();
-
- /**
- * Creates a plain Eclipse project.
- *
- * @param projectName
- * @return the project handle
- * @throws CoreException if project could not be created
- */
- public static IProject createProject(String projectName) throws CoreException {
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- IProject project= root.getProject(projectName);
- if (!project.exists()) {
- project.create(NULL_MONITOR);
- } else {
- project.refreshLocal(IResource.DEPTH_INFINITE, null);
- }
-
- if (!project.isOpen())
- project.open(NULL_MONITOR);
-
- resourcesCreated.add(project);
- return project;
- }
-
- /**
- * Deletes project by name.
- *
- * @param projectName
- * @throws CoreException
- */
- public static void deleteProject(String projectName) throws CoreException {
- IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot();
- IProject project= root.getProject(projectName);
- if (project.exists())
- delete(project);
- }
-
- /**
- * Deletes given project with content.
- *
- * @param project
- * @throws CoreException
- */
- public static void delete(final IProject project) throws CoreException {
- delete(project, true);
- }
-
- /**
- * Deletes project.
- *
- * @param project
- * @param deleteContent whether to delete project content
- * @throws CoreException
- */
- public static void delete(final IProject project, boolean deleteContent) throws CoreException {
- for (int i= 0; i < MAX_RETRY; i++) {
- try {
- project.delete(deleteContent, true, NULL_MONITOR);
- i= MAX_RETRY;
- } catch (CoreException x) {
- if (i == MAX_RETRY - 1) {
- Package.log(x.getStatus());
- }
- try {
- Thread.sleep(1000); // sleep a second
- } catch (InterruptedException e) {
- }
- }
- }
- }
-
- /**
- * Creates a file with specified content.
- *
- * @param file - file name.
- * @param contents - contents of the file.
- * @return file handle.
- * @throws CoreException - if the file can't be created.
- */
- public static IFile createFile(IFile file, String contents) throws CoreException {
- if (contents == null) {
- contents= "";
- }
-
- InputStream inputStream = new ByteArrayInputStream(contents.getBytes());
- file.create(inputStream, true, NULL_MONITOR);
- resourcesCreated.add(file);
- return file;
- }
-
- /**
- * Creates new file from project root with empty content. The filename
- * can include relative path as a part of the name but the the path
- * has to be present on disk.
- *
- * @param project - project where to create the file.
- * @param name - filename.
- * @return file handle.
- * @throws CoreException if something goes wrong.
- */
- public static IFile createFile(IProject project, String name) throws CoreException {
- if (new Path(name).segmentCount() > 1)
- createFolder(project, new Path(name).removeLastSegments(1).toString());
- return createFile(project.getFile(name), null);
- }
-
- /**
- * Creates new file from workspace root with empty content. The filename
- * can include relative path as a part of the name but the the path
- * has to be present on disk.
- * The intention of the method is to create files which do not belong to any project.
- *
- * @param name - filename.
- * @return full path of the created file.
- *
- * @throws CoreException...
- * @throws IOException...
- */
- public static IPath createWorkspaceFile(String name) throws CoreException, IOException {
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IPath fullPath = workspaceRoot.getLocation().append(name);
- java.io.File file = new java.io.File(fullPath.toOSString());
- if (!file.exists()) {
- boolean result = file.createNewFile();
- Assert.assertTrue(result);
- }
- Assert.assertTrue(file.exists());
-
- externalFilesCreated.add(fullPath.toOSString());
- workspaceRoot.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
- return fullPath;
- }
-
- /**
- * Creates new folder from project root. The folder name
- * can include relative path as a part of the name.
- * Nonexistent parent directories are being created.
- *
- * @param project - project where to create the folder.
- * @param name - folder name.
- * @return folder handle.
- * @throws CoreException if something goes wrong.
- */
- public static IFolder createFolder(IProject project, String name) throws CoreException {
- final IPath p = new Path(name);
- IContainer folder = project;
- for (String seg : p.segments()) {
- folder = folder.getFolder(new Path(seg));
- if (!folder.exists())
- ((IFolder)folder).create(true, true, NULL_MONITOR);
- }
- resourcesCreated.add(folder);
- return (IFolder)folder;
- }
-
- /**
- * Creates new folder from workspace root. The folder name
- * can include relative path as a part of the name.
- * Nonexistent parent directories are being created as per {@link File#mkdirs()}.
- * The intention of the method is to create folders which do not belong to any project.
- *
- * @param name - folder name.
- * @return absolute location of the folder on the file system.
- * @throws IOException if something goes wrong.
- */
- public static IPath createWorkspaceFolder(String name) throws CoreException, IOException {
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IPath fullPath = workspaceRoot.getLocation().append(name);
- java.io.File folder = new java.io.File(fullPath.toOSString());
- if (!folder.exists()) {
- boolean result = folder.mkdirs();
- Assert.assertTrue(result);
- }
- Assert.assertTrue(folder.exists());
-
- externalFilesCreated.add(fullPath.toOSString());
- workspaceRoot.refreshLocal(IResource.DEPTH_INFINITE, NULL_MONITOR);
- return fullPath;
- }
-
- /**
- * Creates new temporary folder with generated name from workspace root.
- *
- * @return absolute location of the folder on the file system.
- * @throws IOException if something goes wrong.
- */
- public static IPath createTemporaryFolder() throws CoreException, IOException {
- return ResourceHelper.createWorkspaceFolder("tmp/" + System.currentTimeMillis() + '.' + UUID.randomUUID());
- }
-
- /**
- * Creates new eclipse file-link from project root to file system file. The filename
- * can include relative path as a part of the name but the the path
- * has to be present on disk.
- *
- * @param project - project where to create the file.
- * @param fileLink - filename of the link being created.
- * @param realFile - file on the file system, the target of the link.
- * @return file handle.
- * @throws CoreException if something goes wrong.
- */
- public static IFile createLinkedFile(IProject project, String fileLink, IPath realFile) throws CoreException {
- IFile file = project.getFile(fileLink);
- file.createLink(realFile, IResource.REPLACE, null);
- Assert.assertTrue(file.exists());
- resourcesCreated.add(file);
- return file;
- }
-
- /**
- * Creates new eclipse file-link from project root to file system file. The filename
- * can include relative path as a part of the name but the the path
- * has to be present on disk.
- *
- * @param project - project where to create the file.
- * @param fileLink - filename of the link being created.
- * @param realFile - file on the file system, the target of the link.
- * @return file handle.
- * @throws CoreException if something goes wrong.
- */
- public static IFile createLinkedFile(IProject project, String fileLink, String realFile) throws CoreException {
- return createLinkedFile(project, fileLink, new Path(realFile));
- }
-
- /**
- * Creates new eclipse file-link from project root to EFS file.
- *
- * @param project - project where to create the file.
- * @param fileLink - filename of the link being created.
- * @param realFile - file on the EFS file system, the target of the link.
- * @return file handle.
- * @throws CoreException if something goes wrong.
- */
- public static IFile createEfsFile(IProject project, String fileLink, URI realFile) throws CoreException {
- IFile file= project.getFile(fileLink);
- file.createLink(realFile, IResource.ALLOW_MISSING_LOCAL, NULL_MONITOR);
- resourcesCreated.add(file);
- return file;
- }
-
- /**
- * Creates new eclipse file-link from project root to EFS file.
- *
- * @param project - project where to create the file.
- * @param fileLink - filename of the link being created.
- * @param realFile - file on the EFS file system, the target of the link.
- * @return file handle.
- * @throws CoreException if something goes wrong.
- * @throws URISyntaxException if wrong URI syntax
- */
- public static IFile createEfsFile(IProject project, String fileLink, String realFile) throws CoreException, URISyntaxException {
- return createEfsFile(project,fileLink,new URI(realFile));
- }
-
- /**
- * Creates new eclipse folder-link from project root to file system folder. The folder name
- * can include relative path as a part of the name but the the path
- * has to be present on disk.
- *
- * @param project - project where to create the file.
- * @param folderLink - name of the link being created.
- * @param realFolder - folder on the file system, the target of the link.
- * @return file handle.
- * @throws CoreException if something goes wrong.
- */
- public static IFolder createLinkedFolder(IProject project, String folderLink, IPath realFolder) throws CoreException {
- IFolder folder = project.getFolder(folderLink);
- folder.createLink(realFolder, IResource.REPLACE | IResource.ALLOW_MISSING_LOCAL, null);
- Assert.assertTrue(folder.exists());
- resourcesCreated.add(folder);
- return folder;
- }
-
- /**
- * Creates new eclipse folder-link from project root to file system folder. The folder name
- * can include relative path as a part of the name but the the path
- * has to be present on disk.
- *
- * @param project - project where to create the file.
- * @param folderLink - name of the link being created.
- * @param realFolder - folder on the file system, the target of the link.
- * @return file handle.
- * @throws CoreException if something goes wrong.
- */
- public static IFolder createLinkedFolder(IProject project, String folderLink, String realFolder) throws CoreException {
- return createLinkedFolder(project, folderLink, new Path(realFolder));
- }
-
- /**
- * Creates new eclipse folder-link from project root to EFS folder.
- *
- * @param project - project where to create the folder.
- * @param folderLink - folder name of the link being created.
- * @param realFolder - folder on the EFS file system, the target of the link.
- * @return folder handle.
- * @throws CoreException if something goes wrong.
- */
- public static IFolder createEfsFolder(IProject project, String folderLink, URI realFolder) throws CoreException {
- IFolder folder= project.getFolder(folderLink);
- if (folder.exists()) {
- Assert.assertEquals("Folder with the same name but different location already exists",
- realFolder, folder.getLocationURI());
- return folder;
- }
-
- folder.createLink(realFolder, IResource.ALLOW_MISSING_LOCAL, new NullProgressMonitor());
- resourcesCreated.add(folder);
- return folder;
- }
-
- /**
- * Creates new eclipse folder-link from project root to EFS folder.
- *
- * @param project - project where to create the folder.
- * @param folderLink - folder name of the link being created.
- * @param realFolder - folder on the EFS file system, the target of the link.
- * @return folder handle.
- * @throws CoreException if something goes wrong.
- * @throws URISyntaxException if wrong URI syntax
- */
- public static IFolder createEfsFolder(IProject project, String folderLink, String realFolder) throws CoreException, URISyntaxException {
- return createEfsFolder(project,folderLink,new URI(realFolder));
- }
-
- /**
- * Checks if symbolic links are supported on the system.
- * Used in particular by method {@link #createSymbolicLink(IPath, IPath)}
- * and other flavors to create symbolic links.
- *
- * Note that Windows links .lnk are not supported here.
- * @return {@code true} if symbolic links are suppoted, {@code false} otherwise.
- */
- public static boolean isSymbolicLinkSupported() {
- return ! Platform.getOS().equals(Platform.OS_WIN32);
- }
-
- /**
- * Creates new symbolic file system link from file or folder on project root
- * to another file system file. The filename can include relative path
- * as a part of the name but the the path has to be present on disk.
- *
- * @param project - project where to create the file.
- * @param linkName - name of the link being created.
- * @param realPath - file or folder on the file system, the target of the link.
- * @return file handle.
- *
- * @throws UnsupportedOperationException on Windows where links are not supported.
- * @throws IOException...
- * @throws CoreException...
- */
- public static IResource createSymbolicLink(IProject project, String linkName, IPath realPath)
- throws IOException, CoreException, UnsupportedOperationException {
- if (!isSymbolicLinkSupported()) {
- throw new UnsupportedOperationException("Windows links .lnk are not supported.");
- }
-
- Assert.assertTrue("Path for symbolic link does not exist: [" + realPath.toOSString() + "]",
- new File(realPath.toOSString()).exists());
-
- IPath linkedPath = project.getLocation().append(linkName);
- createSymbolicLink(linkedPath, realPath);
-
- IResource resource = project.getFile(linkName);
- resource.refreshLocal(IResource.DEPTH_ZERO, null);
-
- if (!resource.exists()) {
- resource = project.getFolder(linkName);
- resource.refreshLocal(IResource.DEPTH_ZERO, null);
- }
- Assert.assertTrue("Failed to create resource form symbolic link", resource.exists());
-
- externalFilesCreated.add(linkedPath.toOSString());
- ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, NULL_MONITOR);
- return resource;
- }
-
- /**
- * Creates new symbolic file system link from file or folder to another filesystem file.
- * The target path has to be present on disk.
- *
- * @param linkPath - filesystem path of the link being created.
- * @param realPath - file or folder on the file system, the target of the link.
- *
- * @throws UnsupportedOperationException on Windows where links are not supported.
- * @throws IOException if execution of the command fails.
- */
- public static void createSymbolicLink(IPath linkPath, IPath realPath) throws IOException {
- if (!isSymbolicLinkSupported()) {
- throw new UnsupportedOperationException("Windows links .lnk are not supported.");
- }
-
- String command[] = { "ln", "-s", realPath.toOSString(), linkPath.toOSString()};
- Process process = Runtime.getRuntime().exec(command);
-
- // Wait for up to 2.5s...
- for (int i = 0; i < 5; i++) {
- try {
- Assert.assertTrue("ln process exited with non-zero status", process.waitFor() == 0);
- // If exitValue succeeded, then the process has exited successfully.
- break;
- } catch (InterruptedException e) {
- // Clear interrupted state, see Java bug http://bugs.sun.com/view_bug.do?bug_id=6420270
- Thread.interrupted();
- }
- // Wait for a 500ms before checking again.
- try { Thread.sleep(500); } catch (InterruptedException e) {/*don't care*/}
- }
- Assert.assertTrue("Symbolic link not created, command=[" + command + "]", linkPath.toFile().exists());
- }
-
- /**
- * Creates new symbolic file system link from file or folder on project root
- * to another file system file. The filename can include relative path
- * as a part of the name but the the path has to be present on disk.
- *
- * @param project - project where to create the file.
- * @param linkName - name of the link being created.
- * @param realPath - file or folder on the file system, the target of the link.
- * @return file handle.
- *
- * @throws UnsupportedOperationException on Windows where links are not supported.
- * @throws IOException...
- * @throws CoreException...
- */
- public static IResource createSymbolicLink(IProject project, String linkName, String realPath)
- throws IOException, CoreException, UnsupportedOperationException {
- return createSymbolicLink(project, linkName, new Path(realPath));
- }
-
- /**
- * Get contents of file on file-system.
- *
- * @param fullPath - full path to the file on the file-system.
- * @return contents of the file.
- * @throws IOException on IO problem.
- */
- public static String getContents(IPath fullPath) throws IOException {
- FileInputStream stream = new FileInputStream(fullPath.toFile());
- try (Reader reader = new BufferedReader(new InputStreamReader(stream, Charset.defaultCharset()))){
- // Avoid using java.nio.channels.FileChannel,
- // see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4715154
- StringBuilder builder = new StringBuilder();
- char[] buffer = new char[8192];
- int read;
- while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
- builder.append(buffer, 0, read);
- }
- return builder.toString();
- }
- }
-
- /**
- * Get contents of file on file-system.
- *
- * @param fullPath - full path to the file on the file-system.
- * @return contents of the file.
- * @throws IOException on IO problem.
- */
- public static String getContents(String fullPath) throws IOException {
- return getContents(new Path(fullPath));
- }
-
- /**
- * Clean-up any files created as part of a unit test.
- * This method removes *all* Workspace IResources and any external
- * files / folders created with the #createWorkspaceFile #createWorkspaceFolder
- * methods in this class
- */
- public static void cleanUp() throws CoreException, IOException {
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- root.refreshLocal(IResource.DEPTH_INFINITE, NULL_MONITOR);
-
- // Delete all external files & folders created using ResourceHelper
- for (String loc : externalFilesCreated) {
- File f = new File(loc);
- if (f.exists())
- deleteRecursive(f);
- }
- externalFilesCreated.clear();
-
- // Remove IResources created by this helper
- for (IResource r : resourcesCreated) {
- if (r.exists()) {
- try {
- r.delete(true, NULL_MONITOR);
- } catch (CoreException e) {
- // Ignore
- }
- }
- }
- resourcesCreated.clear();
- }
-
- /**
- * Recursively delete a directory / file
- *
- * For safety this method only deletes files created under the workspace
- */
- private static final void deleteRecursive(File f) throws IllegalArgumentException {
- // Ensure that the file being deleted is a child of the workspace
- // root to prevent anything nasty happening
- if (!f.getAbsolutePath().startsWith(
- ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile().getAbsolutePath())) {
- throw new IllegalArgumentException("File must exist within the workspace!");
- }
-
- if (f.isDirectory()) {
- for (File f1 : f.listFiles()) {
- deleteRecursive(f1);
- }
- }
- f.delete();
- }
-}

Back to the top