diff options
author | Michael Keppler | 2018-11-13 20:13:44 +0000 |
---|---|---|
committer | Michael Keppler | 2018-11-20 13:15:14 +0000 |
commit | 1609457f70a4617b6583bd95da5239ee8cbcaea7 (patch) | |
tree | 0752f626c6387f70bd106b116a8d8cdd899c86b7 /org.eclipse.egit.core.test | |
parent | 2c2621dcab1a5ccc71bc02801f06d1f061aa3431 (diff) | |
download | egit-1609457f70a4617b6583bd95da5239ee8cbcaea7.tar.gz egit-1609457f70a4617b6583bd95da5239ee8cbcaea7.tar.xz egit-1609457f70a4617b6583bd95da5239ee8cbcaea7.zip |
Have test base classes in new plugin for better reuse
* new plugin egit.core.junit
* other test plugins/fragments can depend on it
* non-test classes for all test bundles/fragments can be added here
(moved 5 classes, which are used in multiple test bundles)
Bug: 541008
Change-Id: Ib9a3c9c8856a97746c07ab307c0016332cd5f853
Signed-off-by: Michael Keppler <Michael.Keppler@gmx.de>
Diffstat (limited to 'org.eclipse.egit.core.test')
8 files changed, 4 insertions, 1497 deletions
diff --git a/org.eclipse.egit.core.test/META-INF/MANIFEST.MF b/org.eclipse.egit.core.test/META-INF/MANIFEST.MF index 27919f3920..b42b9cc9a6 100644 --- a/org.eclipse.egit.core.test/META-INF/MANIFEST.MF +++ b/org.eclipse.egit.core.test/META-INF/MANIFEST.MF @@ -13,7 +13,8 @@ Require-Bundle: org.eclipse.core.runtime;bundle-version="[3.4.0,4.0.0)", org.eclipse.jdt.core;bundle-version="[3.4.0,4.0.0)", org.eclipse.jdt.launching;bundle-version="[3.4.0,4.0.0)", org.hamcrest;bundle-version="[1.1.0,2.0.0)", - org.junit;bundle-version="[4.3.0,5.0.0)" + org.junit;bundle-version="[4.3.0,5.0.0)", + org.eclipse.egit.core.junit;bundle-version="[5.2.0,5.3.0)" Import-Package: org.eclipse.egit.core;version="[5.2.0,5.3.0)", org.eclipse.egit.core.op;version="[5.2.0,5.3.0)", org.eclipse.egit.core.project;version="[5.2.0,5.3.0)", @@ -28,4 +29,3 @@ Import-Package: org.eclipse.egit.core;version="[5.2.0,5.3.0)", org.mockito.runners;version="[1.8.0,1.10.0)", org.mockito.stubbing;version="[1.8.0,1.10.0)" Bundle-RequiredExecutionEnvironment: JavaSE-1.8 -Export-Package: org.eclipse.egit.core.test;version="5.2.0" diff --git a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/DualRepositoryTestCase.java b/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/DualRepositoryTestCase.java deleted file mode 100644 index e0ffffde98..0000000000 --- a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/DualRepositoryTestCase.java +++ /dev/null @@ -1,75 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2010, 2012 Mathias Kinzler <mathias.kinzler@sap.com> and others. - * - * All rights reserved. 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 - *******************************************************************************/ -package org.eclipse.egit.core.test; - -import java.io.File; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IProjectDescription; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.Path; -import org.eclipse.egit.core.Activator; -import org.eclipse.egit.core.op.ConnectProviderOperation; -import org.junit.After; -import org.junit.Before; - -public abstract class DualRepositoryTestCase { - - protected TestUtils testUtils = new TestUtils(); - - protected TestRepository repository1; - - protected TestRepository repository2; - - protected IProject testProject; - - @Before - public void beforeTestCase() throws Exception { - // ensure there are no shared Repository instances left - // when starting a new test - Activator.getDefault().getRepositoryCache().clear(); - } - - @After - public void afterTestCase() throws Exception { - Activator.getDefault().getRepositoryCache().clear(); - if (repository1 != null) - repository1.dispose(); - if (repository2 != null) - repository2.dispose(); - if (testProject != null) { - testProject.close(null); - testProject.delete(false, false, null); - } - testUtils.deleteTempDirs(); - } - - protected IProject importProject(TestRepository repo, String projectName) - throws Exception { - IProject firstProject = ResourcesPlugin.getWorkspace().getRoot() - .getProject(projectName); - if (firstProject.exists()) - firstProject.delete(false, null); - IProjectDescription desc = ResourcesPlugin.getWorkspace() - .newProjectDescription(projectName); - File parentFile = repo.getRepository().getWorkTree(); - desc.setLocation(new Path(new File(parentFile, projectName).getPath())); - firstProject.create(desc, null); - firstProject.open(null); - ConnectProviderOperation cop = new ConnectProviderOperation( - firstProject, repo.getRepository().getDirectory()); - cop.execute(null); - return firstProject; - } - - - -} diff --git a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/GitTestCase.java b/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/GitTestCase.java deleted file mode 100644 index d3cabd2ba6..0000000000 --- a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/GitTestCase.java +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2007, 2013 Robin Rosenberg <robin.rosenberg@dewire.com> and others. - * - * All rights reserved. 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 - *******************************************************************************/ -package org.eclipse.egit.core.test; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.preferences.IEclipsePreferences; -import org.eclipse.core.runtime.preferences.InstanceScope; -import org.eclipse.egit.core.Activator; -import org.eclipse.egit.core.GitCorePreferences; -import org.eclipse.jgit.junit.MockSystemReader; -import org.eclipse.jgit.lib.Config; -import org.eclipse.jgit.lib.ConfigConstants; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectInserter; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.storage.file.FileBasedConfig; -import org.eclipse.jgit.util.FS; -import org.eclipse.jgit.util.FileUtils; -import org.eclipse.jgit.util.IO; -import org.eclipse.jgit.util.SystemReader; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; - -public abstract class GitTestCase { - - protected final TestUtils testUtils = new TestUtils(); - - protected TestProject project; - - protected File gitDir; - - @BeforeClass - public static void setUpClass() { - // suppress auto-ignoring and auto-sharing to avoid interference - IEclipsePreferences p = InstanceScope.INSTANCE.getNode(Activator - .getPluginId()); - p.putBoolean(GitCorePreferences.core_autoIgnoreDerivedResources, false); - p.putBoolean(GitCorePreferences.core_autoShareProjects, false); - } - - @Before - public void setUp() throws Exception { - // ensure there are no shared Repository instances left - // when starting a new test - Activator.getDefault().getRepositoryCache().clear(); - File configFile = File.createTempFile("gitconfigtest", "config"); - MockSystemReader mockSystemReader = new MockSystemReader() { - @Override - public FileBasedConfig openUserConfig(Config parent, FS fs) { - return new FileBasedConfig(parent, configFile, fs); - } - }; - configFile.deleteOnExit(); - SystemReader.setInstance(mockSystemReader); - mockSystemReader.setProperty(Constants.GIT_CEILING_DIRECTORIES_KEY, - ResourcesPlugin.getWorkspace().getRoot().getLocation().toFile() - .getParentFile().getAbsoluteFile().toString()); - FileBasedConfig userConfig = mockSystemReader.openUserConfig(null, - FS.DETECTED); - // We have to set autoDetach to false for tests, because tests expect to - // be able to clean up by recursively removing the repository, and - // background GC might be in the middle of writing or deleting files, - // which would disrupt this. - userConfig.setBoolean(ConfigConstants.CONFIG_GC_SECTION, null, - ConfigConstants.CONFIG_KEY_AUTODETACH, false); - userConfig.save(); - project = new TestProject(true); - gitDir = new File(project.getProject().getWorkspace().getRoot() - .getRawLocation().toFile(), Constants.DOT_GIT); - if (gitDir.exists()) - FileUtils.delete(gitDir, FileUtils.RECURSIVE | FileUtils.RETRY); - } - - @After - public void tearDown() throws Exception { - project.dispose(); - Activator.getDefault().getRepositoryCache().clear(); - if (gitDir.exists()) - FileUtils.delete(gitDir, FileUtils.RECURSIVE | FileUtils.RETRY); - SystemReader.setInstance(null); - } - - protected ObjectId createFile(Repository repository, IProject actProject, String name, String content) throws IOException { - File file = new File(actProject.getProject().getLocation().toFile(), name); - Writer fileWriter = new OutputStreamWriter(new FileOutputStream( - file), "UTF-8"); - fileWriter.write(content); - fileWriter.close(); - byte[] fileContents = IO.readFully(file); - try (ObjectInserter inserter = repository.newObjectInserter()) { - ObjectId objectId = inserter.insert(Constants.OBJ_BLOB, fileContents); - inserter.flush(); - return objectId; - } - } - - protected ObjectId createFileCorruptShort(Repository repository, - IProject actProject, String name, String content) - throws IOException { - ObjectId id = createFile(repository, actProject, name, content); - File file = new File(repository.getDirectory(), "objects/" - + id.name().substring(0, 2) + "/" + id.name().substring(2)); - byte[] readFully = IO.readFully(file); - FileUtils.delete(file); - FileOutputStream fileOutputStream = new FileOutputStream(file); - try { - byte[] truncatedData = new byte[readFully.length - 1]; - System.arraycopy(readFully, 0, truncatedData, 0, - truncatedData.length); - fileOutputStream.write(truncatedData); - } finally { - fileOutputStream.close(); - } - return id; - } -} diff --git a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/LinkedResourcesTest.java b/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/LinkedResourcesTest.java index 26e66b2ebf..47d7a71da9 100644 --- a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/LinkedResourcesTest.java +++ b/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/LinkedResourcesTest.java @@ -214,7 +214,7 @@ public class LinkedResourcesTest { .getLocation(), IResource.ALLOW_MISSING_LOCAL, null); // Test iterator WorkingTreeIterator iterator = IteratorService - .createInitialIterator(repository1.repository); + .createInitialIterator(repository1.getRepository()); assertTrue(iterator instanceof FileTreeIterator); while (!iterator.eof()) { assertFalse(iterator.getEntryPathString().startsWith("link2")); diff --git a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/RepositoryCacheTest.java b/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/RepositoryCacheTest.java index a991f71156..824bb8b41f 100644 --- a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/RepositoryCacheTest.java +++ b/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/RepositoryCacheTest.java @@ -100,6 +100,6 @@ public class RepositoryCacheTest extends GitTestCase { // assert that we don't get confused by nesting repositories assertEquals(repository, cache.getRepository(a)); - assertEquals(repository2.repository, cache.getRepository(b)); + assertEquals(repository2.getRepository(), cache.getRepository(b)); } } diff --git a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestProject.java b/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestProject.java deleted file mode 100644 index e8accbc1d3..0000000000 --- a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestProject.java +++ /dev/null @@ -1,296 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com> - * Copyright (C) 2006, Shawn O. Pearce <spearce@spearce.org> - * Copyright (C) 2012, Robin Stocker <robin@nibor.org> - * Copyright (C) 2013, Matthias Sohn <matthias.sohn@sap.com> - * - * All rights reserved. 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 - *******************************************************************************/ -package org.eclipse.egit.core.test; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; - -import org.eclipse.core.filesystem.URIUtil; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IProjectDescription; -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.Path; -import org.eclipse.core.runtime.Platform; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.launching.JavaRuntime; -import org.eclipse.jgit.util.FileUtils; -import org.osgi.framework.Bundle; - -public class TestProject { - public IProject project; - - public IJavaProject javaProject; - - private IPackageFragmentRoot sourceFolder; - private String location; - private TestUtils testUtils = new TestUtils(); - - private final File workspaceSupplement; - - private IFolder binFolder; - - /** - * @throws CoreException - * If project already exists - */ - public TestProject() throws CoreException { - this(false); - } - - public TestProject(boolean remove) throws CoreException { - this(remove, "Project-1"); - } - - /** - * @param remove - * should project be removed if already exists - * @param path - * @throws CoreException - */ - public TestProject(final boolean remove, String path) throws CoreException { - this(remove, path, true, null); - } - - /** - * @param remove - * should project be removed if already exists - * @param path - * @param insidews set false to create in temp - * @param workspaceSupplement - * @throws CoreException - */ - public TestProject(final boolean remove, String path, boolean insidews, File workspaceSupplement) throws CoreException { - this.workspaceSupplement = workspaceSupplement; - IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); - IProjectDescription description = createDescription(path, insidews, - root, workspaceSupplement); - project = root.getProject(description.getName()); - if (remove) - project.delete(true, null); - IPath locationBefore = description.getLocation(); - if (locationBefore == null) - locationBefore = root.getRawLocation().append(path); - location = locationBefore.toOSString(); - project.create(description, null); - project.open(null); - javaProject = JavaCore.create(project); - binFolder = createBinFolder(); - setJavaNature(); - javaProject.setRawClasspath(new IClasspathEntry[0], null); - createOutputFolder(binFolder); - addSystemLibraries(); - } - - public void setBinFolderDerived() throws CoreException { - binFolder.setDerived(true, null); - } - - public File getWorkspaceSupplement() { - return workspaceSupplement; - } - - private IProjectDescription createDescription(String path, - boolean insidews, IWorkspaceRoot root, File workspaceSupplement) { - Path ppath = new Path(path); - String projectName = ppath.lastSegment(); - URI locationURI; - URI top; - if (insidews) { - top = root.getRawLocationURI(); - } else { - top = URIUtil.toURI(workspaceSupplement.getAbsolutePath()); - } - if (!insidews || !ppath.lastSegment().equals(path)) { - locationURI = URIUtil.toURI(URIUtil.toPath(top).append(path)); - } else - locationURI = null; - IProjectDescription description = ResourcesPlugin.getWorkspace() - .newProjectDescription(projectName); - - description.setName(projectName); - description.setLocationURI(locationURI); - return description; - } - - public IProject getProject() { - return project; - } - - public IJavaProject getJavaProject() { - return javaProject; - } - - public void addJar(String plugin, String jar) throws JavaModelException { - Path result = findFileInPlugin(plugin, jar); - IClasspathEntry[] oldEntries = javaProject.getRawClasspath(); - IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1]; - System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length); - newEntries[oldEntries.length] = JavaCore.newLibraryEntry(result, null, - null); - javaProject.setRawClasspath(newEntries, null); - } - - public IPackageFragment createPackage(String name) throws CoreException { - if (sourceFolder == null) - sourceFolder = createSourceFolder(); - return sourceFolder.createPackageFragment(name, false, null); - } - - public IType createType(IPackageFragment pack, String cuName, String source) - throws JavaModelException { - StringBuilder buf = new StringBuilder(); - buf.append("package " + pack.getElementName() + ";\n"); - buf.append("\n"); - buf.append(source); - ICompilationUnit cu = pack.createCompilationUnit(cuName, - buf.toString(), false, null); - return cu.getTypes()[0]; - } - - public IFile createFile(String name, byte[] content) throws Exception { - IFile file = project.getFile(name); - InputStream inputStream = new ByteArrayInputStream(content); - file.create(inputStream, true, null); - - return file; - } - - public IFolder createFolder(String name) throws Exception { - IFolder folder = project.getFolder(name); - folder.create(true, true, null); - return folder; - } - - public IFolder createFolderWithKeep(String name) throws Exception { - IFolder folder = createFolder(name); - - IFile keep = project.getFile(name + "/keep"); - keep.create(new ByteArrayInputStream(new byte[] {0}), true, null); - - return folder; - } - - public void dispose() throws CoreException, IOException { - waitForIndexer(); - if (project.exists()) - project.delete(true, true, null); - else { - File f = new File(location); - if (f.exists()) - FileUtils.delete(f, FileUtils.RECURSIVE | FileUtils.RETRY); - } - } - - private IFolder createBinFolder() throws CoreException { - IFolder binFolder = project.getFolder("bin"); - binFolder.create(false, true, null); - return binFolder; - } - - private void setJavaNature() throws CoreException { - IProjectDescription description = project.getDescription(); - description.setNatureIds(new String[] { JavaCore.NATURE_ID }); - project.setDescription(description, null); - } - - private void createOutputFolder(IFolder binFolder) - throws JavaModelException { - IPath outputLocation = binFolder.getFullPath(); - javaProject.setOutputLocation(outputLocation, null); - } - - public IPackageFragmentRoot createSourceFolder() throws CoreException { - IFolder folder = project.getFolder("src"); - folder.create(false, true, null); - IPackageFragmentRoot root = javaProject.getPackageFragmentRoot(folder); - IClasspathEntry[] oldEntries = javaProject.getRawClasspath(); - IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1]; - System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length); - newEntries[oldEntries.length] = JavaCore.newSourceEntry(root.getPath()); - javaProject.setRawClasspath(newEntries, null); - return root; - } - - private void addSystemLibraries() throws JavaModelException { - IClasspathEntry[] oldEntries = javaProject.getRawClasspath(); - IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1]; - System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length); - newEntries[oldEntries.length] = JavaRuntime - .getDefaultJREContainerEntry(); - javaProject.setRawClasspath(newEntries, null); - } - - private Path findFileInPlugin(String plugin, String file) { - Bundle bundle = Platform.getBundle(plugin); - URL resource = bundle.getResource(file); - return new Path(resource.getPath()); - } - - public void waitForIndexer() { - // new SearchEngine().searchAllTypeNames(ResourcesPlugin.getWorkspace(), - // null, null, IJavaSearchConstants.EXACT_MATCH, - // IJavaSearchConstants.CASE_SENSITIVE, - // IJavaSearchConstants.CLASS, SearchEngine - // .createJavaSearchScope(new IJavaElement[0]), - // new ITypeNameRequestor() { - // public void acceptClass(char[] packageName, - // char[] simpleTypeName, char[][] enclosingTypeNames, - // String path) { - // } - // public void acceptInterface(char[] packageName, - // char[] simpleTypeName, char[][] enclosingTypeNames, - // String path) { - // } - // }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null); - } - - public String getFileContent(String filepath) throws Exception { - IFile file = project.getFile(filepath); - InputStream stream = file.getContents(); - return testUtils.slurpAndClose(stream); - } - /** - * @return Returns the sourceFolder. - */ - public IPackageFragmentRoot getSourceFolder() { - return sourceFolder; - } - - /** - * @param sourceFolder The sourceFolder to set. - */ - public void setSourceFolder(IPackageFragmentRoot sourceFolder) { - this.sourceFolder = sourceFolder; - } - - public String getLocation() { - return location; - } -} diff --git a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestRepository.java b/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestRepository.java deleted file mode 100644 index 8f296a27f1..0000000000 --- a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestRepository.java +++ /dev/null @@ -1,573 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2011, Mathias Kinzler <mathias.kinzler@sap.com> - * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com> - * Copyright (C) 2012, Robin Stocker <robin@nibor.org> - * Copyright (C) 2012, François Rey <eclipse.org_@_francois_._rey_._name> - * Copyright (C) 2015, Obeo - * - * All rights reserved. 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 - *******************************************************************************/ -package org.eclipse.egit.core.test; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.net.URISyntaxException; -import java.util.Collection; -import java.util.Collections; -import java.util.regex.Pattern; - -import org.eclipse.core.filesystem.EFS; -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IResourceVisitor; -import org.eclipse.core.resources.IWorkspace; -import org.eclipse.core.resources.IWorkspaceRunnable; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.Path; -import org.eclipse.egit.core.Activator; -import org.eclipse.egit.core.op.BranchOperation; -import org.eclipse.egit.core.op.ConnectProviderOperation; -import org.eclipse.egit.core.op.DisconnectProviderOperation; -import org.eclipse.jgit.api.CommitCommand; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.ConcurrentRefUpdateException; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.api.errors.JGitInternalException; -import org.eclipse.jgit.api.errors.NoFilepatternException; -import org.eclipse.jgit.api.errors.NoHeadException; -import org.eclipse.jgit.api.errors.NoMessageException; -import org.eclipse.jgit.api.errors.WrongRepositoryStateException; -import org.eclipse.jgit.dircache.DirCache; -import org.eclipse.jgit.dircache.DirCacheEntry; -import org.eclipse.jgit.errors.UnmergedPathException; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.RefUpdate; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; -import org.eclipse.jgit.transport.URIish; -import org.eclipse.jgit.treewalk.TreeWalk; -import org.eclipse.jgit.util.FileUtils; - -/** - * Helper class for creating and filling a test repository - * - */ -public class TestRepository { - - Repository repository; - - String workdirPrefix; - - /** - * Creates a new test repository - * - * @param gitDir - * @throws IOException - */ - public TestRepository(File gitDir) throws IOException { - Repository tmpRepository = FileRepositoryBuilder.create(gitDir); - tmpRepository.create(); - tmpRepository.close(); - // use repository instance from RepositoryCache! - repository = Activator.getDefault().getRepositoryCache().lookupRepository(gitDir); - workdirPrefix = repository.getWorkTree().getAbsolutePath(); - workdirPrefix = workdirPrefix.replace('\\', '/'); - if (!workdirPrefix.endsWith("/")) //$NON-NLS-1$ - workdirPrefix += "/"; //$NON-NLS-1$ - } - - /** - * Creates a test repository from an existing Repository - * - * @param repository - * @throws IOException - */ - public TestRepository(Repository repository) throws IOException { - this.repository = repository; - workdirPrefix = repository.getWorkTree().getAbsolutePath(); - workdirPrefix = workdirPrefix.replace('\\', '/'); - if (!workdirPrefix.endsWith("/")) //$NON-NLS-1$ - workdirPrefix += "/"; //$NON-NLS-1$ - } - - /** - * @return the wrapped repository - */ - public Repository getRepository() { - return repository; - } - - /** - * create an initial commit containing a file "dummy" in the - * - * @param message - * commit message - * @return commit object - * @throws IOException - * @throws JGitInternalException - * @throws GitAPIException - * @throws NoFilepatternException - */ - public RevCommit createInitialCommit(String message) throws IOException, - JGitInternalException, NoFilepatternException, GitAPIException { - String repoPath = repository.getWorkTree().getAbsolutePath(); - File file = new File(repoPath, "dummy"); - if (!file.exists()) - FileUtils.createNewFile(file); - track(file); - return commit(message); - } - - /** - * Create a file or get an existing one - * - * @param project - * instance of project inside with file will be created - * @param name - * name of file - * @return nearly created file - * @throws IOException - */ - public File createFile(IProject project, String name) throws IOException { - String path = project.getLocation().append(name).toOSString(); - int lastSeparator = path.lastIndexOf(File.separator); - FileUtils.mkdirs(new File(path.substring(0, lastSeparator)), true); - - File file = new File(path); - if (!file.exists()) - FileUtils.createNewFile(file); - - return file; - } - - /** - * Track, add to index and finally commit given file - * - * @param project - * @param file - * @param commitMessage - * @return commit object - * @throws Exception - */ - public RevCommit addAndCommit(IProject project, File file, String commitMessage) - throws Exception { - track(file); - addToIndex(project, file); - - return commit(commitMessage); - } - - /** - * Appends file content to given file, then track, add to index and finally - * commit it. - * - * @param project - * @param file - * @param content - * @param commitMessage - * @return commit object - * @throws Exception - */ - public RevCommit appendContentAndCommit(IProject project, File file, - byte[] content, String commitMessage) throws Exception { - return appendContentAndCommit(project, file, new String(content, - "UTF-8"), commitMessage); - } - - /** - * Appends file content to given file, then track, add to index and finally - * commit it. - * - * @param project - * @param file - * @param content - * @param commitMessage - * @return commit object - * @throws Exception - */ - public RevCommit appendContentAndCommit(IProject project, File file, - String content, String commitMessage) throws Exception { - appendFileContent(file, content); - track(file); - addToIndex(project, file); - - return commit(commitMessage); - } - - /** - * Commits the current index - * - * @param message - * commit message - * @return commit object - * - * @throws NoHeadException - * @throws NoMessageException - * @throws UnmergedPathException - * @throws ConcurrentRefUpdateException - * @throws JGitInternalException - * @throws GitAPIException - * @throws WrongRepositoryStateException - */ - public RevCommit commit(String message) throws NoHeadException, - NoMessageException, UnmergedPathException, - ConcurrentRefUpdateException, JGitInternalException, - WrongRepositoryStateException, GitAPIException { - try (Git git = new Git(repository)) { - CommitCommand commitCommand = git.commit(); - commitCommand.setAuthor("J. Git", "j.git@egit.org"); - commitCommand.setCommitter(commitCommand.getAuthor()); - commitCommand.setMessage(message); - return commitCommand.call(); - } - } - - /** - * Adds file to version control - * - * @param file - * @throws IOException - * @throws GitAPIException - * @throws NoFilepatternException - */ - public void track(File file) throws IOException, NoFilepatternException, GitAPIException { - String repoPath = getRepoRelativePath(new Path(file.getPath()) - .toString()); - try (Git git = new Git(repository)) { - git.add().addFilepattern(repoPath).call(); - } - } - - /** - * Adds all project files to version control - * - * @param project - * @throws CoreException - */ - public void trackAllFiles(IProject project) throws CoreException { - project.accept(new IResourceVisitor() { - - @Override - public boolean visit(IResource resource) throws CoreException { - if (resource instanceof IFile) { - try { - track(EFS.getStore(resource.getLocationURI()) - .toLocalFile(0, null)); - } catch (Exception e) { - throw new CoreException(Activator.error(e.getMessage(), - e)); - } - } - return true; - } - }); - } - - /** - * Removes file from version control - * - * @param file - * @throws IOException - */ - public void untrack(File file) throws IOException { - String repoPath = getRepoRelativePath(new Path(file.getPath()) - .toString()); - try (Git git = new Git(repository)) { - git.rm().addFilepattern(repoPath).call(); - } catch (GitAPIException e) { - throw new IOException(e.getMessage()); - } - } - - /** - * Creates a new branch and immediately checkout it. - * - * @param refName - * starting point for the new branch - * @param newRefName - * @throws Exception - */ - public void createAndCheckoutBranch(String refName, String newRefName) throws Exception { - createBranch(refName, newRefName); - checkoutBranch(newRefName); - } - - /** - * Creates a new branch - * - * @param refName - * starting point for the new branch - * @param newRefName - * @throws IOException - */ - public void createBranch(String refName, String newRefName) - throws IOException { - RefUpdate updateRef; - updateRef = repository.updateRef(newRefName); - Ref startRef = repository.findRef(refName); - ObjectId startAt = repository.resolve(refName); - String startBranch; - if (startRef != null) - startBranch = refName; - else - startBranch = startAt.name(); - startBranch = Repository.shortenRefName(startBranch); - updateRef.setNewObjectId(startAt); - updateRef - .setRefLogMessage("branch: Created from " + startBranch, false); //$NON-NLS-1$ - updateRef.update(); - } - - /** - * Checkouts branch - * - * @param refName - * full name of branch - * @throws CoreException - */ - public void checkoutBranch(String refName) throws CoreException { - new BranchOperation(repository, refName).execute(null); - } - - /** - * Adds the given file to the index - * - * @param project - * @param file - * @throws Exception - */ - public void addToIndex(IProject project, File file) throws Exception { - IFile iFile = getIFile(project, file); - addToIndex(iFile); - } - - - /** - * Adds the given resource to the index - * - * @param resource - * @throws CoreException - * @throws IOException - * @throws GitAPIException - * @throws NoFilepatternException - */ - public void addToIndex(IResource resource) throws CoreException, IOException, NoFilepatternException, GitAPIException { - String repoPath = getRepoRelativePath(resource.getLocation().toString()); - try (Git git = new Git(repository)) { - git.add().addFilepattern(repoPath).call(); - } - } - - /** - * Remove the given resource form the index. - * - * @param file - * @throws NoFilepatternException - * @throws GitAPIException - */ - public void removeFromIndex(File file) throws NoFilepatternException, GitAPIException { - String repoPath = getRepoRelativePath(new Path(file.getPath()) - .toString()); - try (Git git = new Git(repository)) { - git.rm().addFilepattern(repoPath).call(); - } - } - - /** - * Appends content to end of given file. - * - * @param file - * @param content - * @throws IOException - */ - public void appendFileContent(File file, byte[] content) throws IOException { - appendFileContent(file, new String(content, "UTF-8"), true); - } - - /** - * Appends content to end of given file. - * - * @param file - * @param content - * @throws IOException - */ - public void appendFileContent(File file, String content) throws IOException { - appendFileContent(file, content, true); - } - - /** - * Appends content to given file. - * - * @param file - * @param content - * @param append - * if true, then bytes will be written to the end of the file - * rather than the beginning - * @throws IOException - */ - public void appendFileContent(File file, byte[] content, boolean append) - throws IOException { - appendFileContent(file, new String(content, "UTF-8"), append); - } - - /** - * Appends content to given file. - * - * @param file - * @param content - * @param append - * if true, then bytes will be written to the end of the file - * rather than the beginning - * @throws IOException - */ - public void appendFileContent(File file, String content, boolean append) - throws IOException { - Writer fw = null; - try { - fw = new OutputStreamWriter(new FileOutputStream(file, append), - "UTF-8"); - fw.append(content); - } finally { - if (fw != null) - fw.close(); - } - } - - /** - * Checks if a file with the given path exists in the HEAD tree - * - * @param path - * @return true if the file exists - * @throws IOException - */ - public boolean inHead(String path) throws IOException { - ObjectId headId = repository.resolve(Constants.HEAD); - try (RevWalk rw = new RevWalk(repository); - TreeWalk tw = TreeWalk.forPath(repository, path, - rw.parseTree(headId))) { - return tw != null; - } - } - - public boolean inIndex(String absolutePath) throws IOException { - return getDirCacheEntry(absolutePath) != null; - } - - public boolean removedFromIndex(String absolutePath) throws IOException { - DirCacheEntry dc = getDirCacheEntry(absolutePath); - if (dc == null) - return true; - - Ref ref = repository.exactRef(Constants.HEAD); - try (RevWalk rw = new RevWalk(repository)) { - RevCommit c = rw.parseCommit(ref.getObjectId()); - - try (TreeWalk tw = TreeWalk.forPath(repository, - getRepoRelativePath(absolutePath), c.getTree())) { - return tw == null || dc.getObjectId().equals(tw.getObjectId(0)); - } - } - } - - public long lastModifiedInIndex(String path) throws IOException { - String repoPath = getRepoRelativePath(path); - DirCache dc = DirCache.read(repository.getIndexFile(), repository.getFS()); - - return dc.getEntry(repoPath).getLastModified(); - } - - public int getDirCacheEntryLength(String path) throws IOException { - String repoPath = getRepoRelativePath(path); - DirCache dc = DirCache.read(repository.getIndexFile(), repository.getFS()); - - return dc.getEntry(repoPath).getLength(); - } - - public String getRepoRelativePath(String path) { - final int pfxLen = workdirPrefix.length(); - final int pLen = path.length(); - if (pLen > pfxLen) - return path.substring(pfxLen); - else if (path.length() == pfxLen - 1) - return ""; //$NON-NLS-1$ - return null; - } - - public IFile getIFile(IProject project, File file) throws CoreException { - String relativePath = getRepoRelativePath(file.getAbsolutePath()); - - String quotedProjectName = Pattern.quote(project.getName()); - relativePath = relativePath.replaceFirst(quotedProjectName, ""); - - IFile iFile = project.getFile(relativePath); - iFile.refreshLocal(0, null); - - return iFile; - } - - public void dispose() { - if (repository != null) { - repository.close(); - repository = null; - } - } - - /** - * Connect a project to this repository - * - * @param project - * @throws Exception - */ - public void connect(IProject project) throws Exception { - ConnectProviderOperation op = new ConnectProviderOperation(project, - this.getRepository().getDirectory()); - op.execute(null); - TestUtils.waitForJobs(50, 5000, null); - } - - /** - * Disconnects provider from project - * - * @param project - * @throws Exception - */ - public void disconnect(IProject project) throws Exception { - Collection<IProject> projects = Collections.singleton(project - .getProject()); - DisconnectProviderOperation disconnect = new DisconnectProviderOperation( - projects); - ResourcesPlugin.getWorkspace().run(new IWorkspaceRunnable() { - @Override - public void run(IProgressMonitor monitor) throws CoreException { - disconnect.execute(null); - } - }, project, IWorkspace.AVOID_UPDATE, null); - TestUtils.waitForJobs(5000, null); - } - - public URIish getUri() throws URISyntaxException { - return new URIish("file:///" + repository.getDirectory().toString()); - } - - private DirCacheEntry getDirCacheEntry(String path) throws IOException { - String repoPath = getRepoRelativePath(path); - DirCache dc = DirCache.read(repository.getIndexFile(), repository.getFS()); - - return dc.getEntry(repoPath); - } -} diff --git a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestUtils.java b/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestUtils.java deleted file mode 100644 index f61e2286f1..0000000000 --- a/org.eclipse.egit.core.test/src/org/eclipse/egit/core/test/TestUtils.java +++ /dev/null @@ -1,416 +0,0 @@ -/******************************************************************************* - * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com> - * Copyright (C) 2010, Jens Baumgart <jens.baumgart@sap.com> - * Copyright (C) 2010, Mathias Kinzler <mathias.kinzler@sap.com> - * Copyright (C) 2012, François Rey <eclipse.org_@_francois_._rey_._name> - * - * All rights reserved. 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 - *******************************************************************************/ -package org.eclipse.egit.core.test; - -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.lang.management.LockInfo; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; -import java.util.UUID; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IProjectDescription; -import org.eclipse.core.resources.ResourcesPlugin; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.jobs.IJobManager; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.treewalk.TreeWalk; -import org.eclipse.jgit.util.FS; -import org.eclipse.jgit.util.FileUtils; - -public class TestUtils { - - public final static String AUTHOR = "The Author <The.author@some.com>"; - - public final static String COMMITTER = "The Commiter <The.committer@some.com>"; - - private final static File rootDir = customTestDirectory(); - - /** - * Allow to set a custom directory for running tests - * - * @return custom directory defined by system property - * {@code egit.test.tmpdir} or {@code ~/egit.test.tmpdir} if this - * property isn't defined - */ - private static File customTestDirectory() { - final String p = System.getProperty("egit.test.tmpdir"); //$NON-NLS-1$ - File testDir = null; - boolean isDefault = true; - if (p == null || p.length() == 0) - testDir = new File(FS.DETECTED.userHome(), "egit.test.tmpdir"); //$NON-NLS-1$ - else { - isDefault = false; - testDir = new File(p).getAbsoluteFile(); - } - System.out.println("egit.test.tmpdir" //$NON-NLS-1$ - + (isDefault ? "[default]: " : ": ") //$NON-NLS-1$ $NON-NLS-2$ - + testDir.getAbsolutePath()); - return testDir; - } - - private File baseTempDir; - - public TestUtils() { - // ensure that concurrent test runs don't use the same directory - baseTempDir = new File(rootDir, UUID.randomUUID().toString() - .replace("-", "")); - } - - /** - * Return the base directory in which temporary directories are created. - * Current implementation returns a "temporary" folder in the user home. - * - * @return a "temporary" folder in the user home that may not exist. - */ - public File getBaseTempDir() { - return baseTempDir; - } - - /** - * Create a "temporary" directory - * - * @param name - * the name of the directory - * @return a directory as child of a "temporary" folder in the user home - * directory; may or may not exist - * @throws IOException - */ - public File createTempDir(String name) throws IOException { - File result = new File(getBaseTempDir(), name); - if (result.exists()) - FileUtils.delete(result, FileUtils.RECURSIVE | FileUtils.RETRY); - FileUtils.mkdirs(result, true); - return result; - } - - /** - * Cleanup: delete the "temporary" folder and all children - * - * @throws IOException - */ - public void deleteTempDirs() throws IOException { - if (rootDir.exists()) - FileUtils.delete(rootDir, FileUtils.RECURSIVE | FileUtils.RETRY); - } - - /** - * Read the stream into a String - * - * @param inputStream - * @return the contents of the stream - * @throws IOException - */ - public String slurpAndClose(InputStream inputStream) throws IOException { - StringBuilder stringBuilder = new StringBuilder(); - try { - int ch; - while ((ch = inputStream.read()) != -1) { - stringBuilder.append((char) ch); - } - } finally { - inputStream.close(); - } - return stringBuilder.toString(); - } - - /** - * Add a file to an existing project - * - * @param project - * the project - * @param path - * e.g. "folder1/folder2/test.txt" - * @param content - * the contents - * @return the file - * @throws CoreException - * if the file cannot be created - * @throws UnsupportedEncodingException - */ - public IFile addFileToProject(IProject project, String path, String content) throws CoreException, UnsupportedEncodingException { - IPath filePath = new Path(path); - IFolder folder = null; - for (int i = 0; i < filePath.segmentCount() - 1; i++) { - if (folder == null) { - folder = project.getFolder(filePath.segment(i)); - } else { - folder = folder.getFolder(filePath.segment(i)); - } - if (!folder.exists()) - folder.create(false, true, null); - } - IFile file = project.getFile(filePath); - file.create(new ByteArrayInputStream(content.getBytes(project - .getDefaultCharset())), true, null); - return file; - } - - /** - * Change the content of a file - * - * @param project - * @param file - * @param newContent - * @return the file - * @throws CoreException - * @throws UnsupportedEncodingException - */ - public IFile changeContentOfFile(IProject project, IFile file, String newContent) throws UnsupportedEncodingException, CoreException { - file.setContents(new ByteArrayInputStream(newContent.getBytes(project - .getDefaultCharset())), 0, null); - return file; - } - - /** - * Create a project in the base directory of temp dirs - * - * @param projectName - * project name - * @return the project with a location pointing to the local file system - * @throws Exception - */ - public IProject createProjectInLocalFileSystem( - String projectName) throws Exception { - return createProjectInLocalFileSystem(getBaseTempDir(), projectName); - } - - /** - * Create a project in the local file system - * - * @param parentFile - * the parent directory - * @param projectName - * project name - * @return the project with a location pointing to the local file system - * @throws Exception - */ - public IProject createProjectInLocalFileSystem(File parentFile, - String projectName) throws Exception { - IProject project = ResourcesPlugin.getWorkspace().getRoot() - .getProject(projectName); - if (project.exists()) { - project.delete(true, null); - } - File testFile = new File(parentFile, projectName); - if (testFile.exists()) - FileUtils.delete(testFile, FileUtils.RECURSIVE | FileUtils.RETRY); - - IProjectDescription desc = ResourcesPlugin.getWorkspace() - .newProjectDescription(projectName); - desc.setLocation(new Path(new File(parentFile, projectName).getPath())); - project.create(desc, null); - project.open(null); - return project; - } - - /** - * verifies that repository contains exactly the given files. - * @param repository - * @param paths - * @throws Exception - */ - public void assertRepositoryContainsFiles(Repository repository, - String[] paths) throws Exception { - Set<String> expectedfiles = new HashSet<String>(); - for (String path : paths) - expectedfiles.add(path); - try (TreeWalk treeWalk = new TreeWalk(repository)) { - treeWalk.addTree(repository.resolve("HEAD^{tree}")); - treeWalk.setRecursive(true); - while (treeWalk.next()) { - String path = treeWalk.getPathString(); - if (!expectedfiles.contains(path)) - fail("Repository contains unexpected expected file " - + path); - expectedfiles.remove(path); - } - } - if (expectedfiles.size() > 0) { - StringBuilder message = new StringBuilder( - "Repository does not contain expected files: "); - for (String path : expectedfiles) { - message.append(path); - message.append(" "); - } - fail(message.toString()); - } - } - - /** - * verifies that repository contains exactly the given files with the given - * content. Usage example:<br> - * - * <code> - * assertRepositoryContainsFiles(repository, "foo/a.txt", "content of A", - * "foo/b.txt", "content of B") - * </code> - * @param repository - * @param args - * @throws Exception - */ - public void assertRepositoryContainsFilesWithContent(Repository repository, - String... args) throws Exception { - HashMap<String, String> expectedfiles = mkmap(args); - try (TreeWalk treeWalk = new TreeWalk(repository)) { - treeWalk.addTree(repository.resolve("HEAD^{tree}")); - treeWalk.setRecursive(true); - while (treeWalk.next()) { - String path = treeWalk.getPathString(); - assertTrue(expectedfiles.containsKey(path)); - ObjectId objectId = treeWalk.getObjectId(0); - byte[] expectedContent = expectedfiles.get(path) - .getBytes("UTF-8"); - byte[] repoContent = treeWalk.getObjectReader().open(objectId) - .getBytes(); - if (!Arrays.equals(repoContent, expectedContent)) { - fail("File " + path + " has repository content " - + new String(repoContent, "UTF-8") - + " instead of expected content " - + new String(expectedContent, "UTF-8")); - } - expectedfiles.remove(path); - } - } - if (expectedfiles.size() > 0) { - StringBuilder message = new StringBuilder( - "Repository does not contain expected files: "); - for (String path : expectedfiles.keySet()) { - message.append(path); - message.append(" "); - } - fail(message.toString()); - } - } - - /** - * Waits at least 50 milliseconds until no jobs of given family are running - * - * @param maxWaitTime - * @param family - * @throws InterruptedException - */ - public static void waitForJobs(long maxWaitTime, Object family) - throws InterruptedException { - waitForJobs(100, maxWaitTime, family); - } - - /** - * Waits at least <code>minWaitTime</code> milliseconds until no jobs of - * given family are running - * - * @param maxWaitTime - * @param minWaitTime - * @param family - * can be null which means all job families - * @throws InterruptedException - */ - public static void waitForJobs(long minWaitTime, long maxWaitTime, - Object family) - throws InterruptedException { - long start = System.currentTimeMillis(); - Thread.sleep(minWaitTime); - IJobManager jobManager = Job.getJobManager(); - Job[] jobs = jobManager.find(family); - while (busy(jobs)) { - Thread.sleep(50); - jobs = jobManager.find(family); - if (System.currentTimeMillis() - start > maxWaitTime) { - if (busy(jobs)) { - System.out.println("Following jobs were still running: " - + getJobNames(jobs)); - } - return; - } - } - } - - private static String getJobNames(Job[] jobs) { - StringBuilder sb = new StringBuilder(); - for (Job job : jobs) { - sb.append(job.getName()).append(" / ").append(job.toString()) - .append(", "); - } - return sb.toString(); - } - - private static boolean busy(Job[] jobs) { - for (Job job : jobs) { - int state = job.getState(); - if (state == Job.RUNNING || state == Job.WAITING) { - return true; - } - } - return false; - } - - private static HashMap<String, String> mkmap(String... args) { - if ((args.length % 2) > 0) - throw new IllegalArgumentException("needs to be pairs"); - HashMap<String, String> map = new HashMap<String, String>(); - for (int i = 0; i < args.length; i += 2) { - map.put(args[i], args[i+1]); - } - return map; - } - - public static String dumpThreads() { - final StringBuilder dump = new StringBuilder(); - final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean(); - final ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads( - threadMXBean.isObjectMonitorUsageSupported(), - threadMXBean.isSynchronizerUsageSupported()); - for (ThreadInfo threadInfo : threadInfos) { - dump.append("Thread ").append(threadInfo.getThreadId()).append(' ') - .append(threadInfo.getThreadName()).append(' ') - .append(threadInfo.getThreadState()).append('\n'); - LockInfo blocked = threadInfo.getLockInfo(); - if (blocked != null) { - dump.append(" Waiting for ").append(blocked); - String lockOwner = threadInfo.getLockOwnerName(); - if (lockOwner != null && !lockOwner.isEmpty()) { - dump.append(" held by ").append(lockOwner).append("(id=") - .append(threadInfo.getLockOwnerId()).append(')'); - } - dump.append('\n'); - } - for (LockInfo lock : threadInfo.getLockedSynchronizers()) { - dump.append(" Holding ").append(lock).append('\n'); - } - for (StackTraceElement s : threadInfo.getStackTrace()) { - dump.append(" at ").append(s).append('\n'); - } - } - return dump.toString(); - } - -} |