diff options
301 files changed, 3407 insertions, 3391 deletions
diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/AbstractFileBufferDocCreationTests.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/AbstractFileBufferDocCreationTests.java index 82830736bbd..ee6cb0fd44b 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/AbstractFileBufferDocCreationTests.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/AbstractFileBufferDocCreationTests.java @@ -14,8 +14,6 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import junit.framework.TestCase; - import org.eclipse.core.runtime.Path; import org.eclipse.core.filebuffers.IDocumentSetupParticipantExtension; @@ -30,6 +28,8 @@ import org.eclipse.core.filebuffers.tests.MockDocumentSetupParticipants.TestDSP6 import org.eclipse.jface.text.IDocument; +import junit.framework.TestCase; + /** * @since 3.4 @@ -106,13 +106,13 @@ public abstract class AbstractFileBufferDocCreationTests extends TestCase { /* Utilities */ - private void assertParticipantsInvoked(String path, Class[] expectedDSPsArray) { + private void assertParticipantsInvoked(String path, Class<?>[] expectedDSPsArray) { LocationKind[] lks= getSupportLocationKinds(); for(int i=0; i<lks.length; i++) { IDocument document= fManager.createEmptyDocument(new Path(path), lks[i]); String content= document.get(); - Set expectedDSPs= new HashSet(Arrays.asList(toString(expectedDSPsArray))); - Set actualDSPs= new HashSet(Arrays.asList(content.split("\n"))); + Set<String> expectedDSPs= new HashSet<>(Arrays.asList(toString(expectedDSPsArray))); + Set<String> actualDSPs= new HashSet<>(Arrays.asList(content.split("\n"))); assertEquals(expectedDSPs, actualDSPs); } } @@ -123,7 +123,7 @@ public abstract class AbstractFileBufferDocCreationTests extends TestCase { assertEquals(expectedContent, fManager.createEmptyDocument(new Path(path), locKind).get()); } - private static String[] toString(Class[] clss) { + private static String[] toString(Class<?>[] clss) { String[] result= new String[clss.length]; for(int i=0; i<result.length; i++) { String s= null; diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBufferFunctions.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBufferFunctions.java index 71533493dec..3881085b50a 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBufferFunctions.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBufferFunctions.java @@ -14,8 +14,6 @@ package org.eclipse.core.filebuffers.tests; import java.io.PrintStream; import java.io.PrintWriter; -import junit.framework.TestCase; - import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileInfo; import org.eclipse.core.filesystem.IFileStore; @@ -35,6 +33,8 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension4; import org.eclipse.jface.text.source.IAnnotationModel; +import junit.framework.TestCase; + /** * FileBufferFunctions */ @@ -57,7 +57,7 @@ public abstract class FileBufferFunctions extends TestCase { protected abstract boolean isStateValidationSupported(); - protected abstract Class getAnnotationModelClass() throws Exception; + protected abstract Class<IAnnotationModel> getAnnotationModelClass() throws Exception; @Override @@ -1109,7 +1109,7 @@ public abstract class FileBufferFunctions extends TestCase { ITextFileBuffer buffer= fManager.getTextFileBuffer(fPath, LocationKind.NORMALIZE); assertNotNull(buffer); - Class clazz= getAnnotationModelClass(); + Class<IAnnotationModel> clazz= getAnnotationModelClass(); if (clazz != null) { IAnnotationModel model= buffer.getAnnotationModel(); assertTrue(clazz.isInstance(model)); @@ -1176,7 +1176,7 @@ public abstract class FileBufferFunctions extends TestCase { ITextFileBuffer buffer= fManager.getTextFileBuffer(fPath, LocationKind.NORMALIZE); assertNotNull(buffer); - Class clazz= getAnnotationModelClass(); + Class<IAnnotationModel> clazz= getAnnotationModelClass(); if (clazz != null) { IAnnotationModel model= buffer.getAnnotationModel(); assertTrue(clazz.isInstance(model)); @@ -1216,7 +1216,7 @@ public abstract class FileBufferFunctions extends TestCase { try { ITextFileBuffer fileBuffer= fManager.getFileStoreTextFileBuffer(fileStore); IAnnotationModel model= fileBuffer.getAnnotationModel(); - Class clazz= getAnnotationModelClass(); + Class<IAnnotationModel> clazz= getAnnotationModelClass(); if (clazz != null) assertTrue(clazz.isInstance(model)); else diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForExternalFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForExternalFiles.java index 6f165eb60f3..b5840cbc3c5 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForExternalFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForExternalFiles.java @@ -22,6 +22,8 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.filebuffers.FileBuffers; +import org.eclipse.jface.text.source.IAnnotationModel; + /** * FileBuffersForExternalFiles */ @@ -70,7 +72,7 @@ public class FileBuffersForExternalFiles extends FileBufferFunctions { } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { return null; } } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForFilesInLinkedFolders.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForFilesInLinkedFolders.java index 55dc5ec0938..add40638ef3 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForFilesInLinkedFolders.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForFilesInLinkedFolders.java @@ -125,7 +125,7 @@ public class FileBuffersForFilesInLinkedFolders extends FileBufferFunctions { } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { Bundle bundle= Platform.getBundle("org.eclipse.ui.editors"); return bundle != null ? IAnnotationModel.class : null; } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForLinkedFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForLinkedFiles.java index 26a35228861..6977a6b4712 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForLinkedFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForLinkedFiles.java @@ -97,7 +97,7 @@ public class FileBuffersForLinkedFiles extends FileBufferFunctions { } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { Bundle bundle= Platform.getBundle("org.eclipse.ui.editors"); return bundle != null ? IAnnotationModel.class : null; } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonAccessibleWorkspaceFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonAccessibleWorkspaceFiles.java index f2526d51873..d4c1a9f1ca4 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonAccessibleWorkspaceFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonAccessibleWorkspaceFiles.java @@ -21,6 +21,8 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.filebuffers.FileBuffers; +import org.eclipse.jface.text.source.IAnnotationModel; + /** * FileBuffersForWorkspaceFiles */ @@ -77,7 +79,7 @@ public class FileBuffersForNonAccessibleWorkspaceFiles extends FileBufferFunctio } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { return null; } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonExistingExternalFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonExistingExternalFiles.java index ccf40bd5e14..e070b56e215 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonExistingExternalFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonExistingExternalFiles.java @@ -20,6 +20,8 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.filebuffers.FileBuffers; +import org.eclipse.jface.text.source.IAnnotationModel; + /** * FileBuffersForNonExistingExternalFiles */ @@ -69,7 +71,7 @@ public class FileBuffersForNonExistingExternalFiles extends FileBufferFunctions } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { return null; } } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonExistingWorkspaceFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonExistingWorkspaceFiles.java index 7629120ddcc..3484b862d08 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonExistingWorkspaceFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForNonExistingWorkspaceFiles.java @@ -23,6 +23,8 @@ import org.eclipse.core.filebuffers.FileBuffers; import org.eclipse.core.filebuffers.ITextFileBuffer; import org.eclipse.core.filebuffers.LocationKind; +import org.eclipse.jface.text.source.IAnnotationModel; + /** * FileBuffersForNonExistingWorkspaceFiles */ @@ -101,7 +103,7 @@ public class FileBuffersForNonExistingWorkspaceFiles extends FileBufferFunctions } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { return null; } } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForWorkspaceFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForWorkspaceFiles.java index 7f703dd39a8..d4627276b33 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForWorkspaceFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileBuffersForWorkspaceFiles.java @@ -105,7 +105,7 @@ public class FileBuffersForWorkspaceFiles extends FileBufferFunctions { } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { Bundle bundle= Platform.getBundle("org.eclipse.ui.editors"); return bundle != null ? IAnnotationModel.class : null; } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBufferFunctions.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBufferFunctions.java index 5a4b6a2dbcb..b6d985fea9e 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBufferFunctions.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBufferFunctions.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,8 +13,6 @@ package org.eclipse.core.filebuffers.tests; import java.io.PrintStream; import java.io.PrintWriter; -import junit.framework.TestCase; - import org.eclipse.core.filesystem.EFS; import org.eclipse.core.filesystem.IFileInfo; import org.eclipse.core.filesystem.IFileStore; @@ -33,6 +31,8 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension4; import org.eclipse.jface.text.source.IAnnotationModel; +import junit.framework.TestCase; + /** * FileBufferFunctions */ @@ -55,7 +55,7 @@ public abstract class FileStoreFileBufferFunctions extends TestCase { protected abstract boolean isStateValidationSupported(); - protected abstract Class getAnnotationModelClass() throws Exception; + protected abstract Class<IAnnotationModel> getAnnotationModelClass() throws Exception; @Override @@ -1095,7 +1095,7 @@ public abstract class FileStoreFileBufferFunctions extends TestCase { ITextFileBuffer buffer= fManager.getFileStoreTextFileBuffer(fFileStore); assertNotNull(buffer); - Class clazz= getAnnotationModelClass(); + Class<IAnnotationModel> clazz= getAnnotationModelClass(); if (clazz != null) { IAnnotationModel model= buffer.getAnnotationModel(); assertTrue(clazz.isInstance(model)); @@ -1162,7 +1162,7 @@ public abstract class FileStoreFileBufferFunctions extends TestCase { ITextFileBuffer buffer= fManager.getFileStoreTextFileBuffer(fFileStore); assertNotNull(buffer); - Class clazz= getAnnotationModelClass(); + Class<IAnnotationModel> clazz= getAnnotationModelClass(); if (clazz != null) { IAnnotationModel model= buffer.getAnnotationModel(); assertTrue(clazz.isInstance(model)); diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForExternalFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForExternalFiles.java index de05cffeb1d..de02b912946 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForExternalFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForExternalFiles.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -22,6 +22,8 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.filebuffers.FileBuffers; +import org.eclipse.jface.text.source.IAnnotationModel; + /** * FileBuffersForExternalFiles */ @@ -70,7 +72,7 @@ public class FileStoreFileBuffersForExternalFiles extends FileStoreFileBufferFun } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { return null; } } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForNonExistingExternalFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForNonExistingExternalFiles.java index 1484e941c21..ad1f6c91de9 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForNonExistingExternalFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForNonExistingExternalFiles.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -20,6 +20,8 @@ import org.eclipse.core.resources.IProject; import org.eclipse.core.filebuffers.FileBuffers; +import org.eclipse.jface.text.source.IAnnotationModel; + /** * FileBuffersForNonExistingExternalFiles */ @@ -69,7 +71,7 @@ public class FileStoreFileBuffersForNonExistingExternalFiles extends FileStoreFi } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { return null; } } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForNonExistingWorkspaceFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForNonExistingWorkspaceFiles.java index 9c50e9a9a32..2da4f6f1bb5 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForNonExistingWorkspaceFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForNonExistingWorkspaceFiles.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -23,6 +23,8 @@ import org.eclipse.core.filebuffers.FileBuffers; import org.eclipse.core.filebuffers.ITextFileBuffer; import org.eclipse.core.filebuffers.LocationKind; +import org.eclipse.jface.text.source.IAnnotationModel; + /** * FileBuffersForNonExistingWorkspaceFiles */ @@ -101,7 +103,7 @@ public class FileStoreFileBuffersForNonExistingWorkspaceFiles extends FileStoreF } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { return null; } } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForWorkspaceFiles.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForWorkspaceFiles.java index 22a7d3a204b..dcf49abe98f 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForWorkspaceFiles.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileStoreFileBuffersForWorkspaceFiles.java @@ -105,7 +105,7 @@ public class FileStoreFileBuffersForWorkspaceFiles extends FileBufferFunctions { } @Override - protected Class getAnnotationModelClass() throws Exception { + protected Class<IAnnotationModel> getAnnotationModelClass() throws Exception { Bundle bundle= Platform.getBundle("org.eclipse.ui.editors"); return bundle != null ? IAnnotationModel.class : null; } diff --git a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileTool.java b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileTool.java index 7d88be8dd12..022c8c94de8 100644 --- a/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileTool.java +++ b/org.eclipse.core.filebuffers.tests/src/org/eclipse/core/filebuffers/tests/FileTool.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -53,11 +53,11 @@ public class FileTool { */ public static void unzip(ZipFile zipFile, File dstDir) throws IOException { - Enumeration entries = zipFile.entries(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); try { while(entries.hasMoreElements()){ - ZipEntry entry = (ZipEntry)entries.nextElement(); + ZipEntry entry = entries.nextElement(); if(entry.isDirectory()){ continue; } diff --git a/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/manipulation/GenericFileBufferOperationRunner.java b/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/manipulation/GenericFileBufferOperationRunner.java index 2092ae679c7..b141a8849c8 100644 --- a/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/manipulation/GenericFileBufferOperationRunner.java +++ b/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/manipulation/GenericFileBufferOperationRunner.java @@ -200,21 +200,21 @@ public class GenericFileBufferOperationRunner { } private IFileBuffer[] findUnsynchronizedFileBuffers(IFileBuffer[] fileBuffers) { - ArrayList list= new ArrayList(); + ArrayList<IFileBuffer> list= new ArrayList<>(); for (int i= 0; i < fileBuffers.length; i++) { if (!fileBuffers[i].isSynchronizationContextRequested()) list.add(fileBuffers[i]); } - return (IFileBuffer[]) list.toArray(new IFileBuffer[list.size()]); + return list.toArray(new IFileBuffer[list.size()]); } private IFileBuffer[] findSynchronizedFileBuffers(IFileBuffer[] fileBuffers) { - ArrayList list= new ArrayList(); + ArrayList<IFileBuffer> list= new ArrayList<>(); for (int i= 0; i < fileBuffers.length; i++) { if (fileBuffers[i].isSynchronizationContextRequested()) list.add(fileBuffers[i]); } - return (IFileBuffer[]) list.toArray(new IFileBuffer[list.size()]); + return list.toArray(new IFileBuffer[list.size()]); } private IFileBuffer[] createFileBuffers(IPath[] locations, IProgressMonitor progressMonitor) throws CoreException { @@ -255,13 +255,13 @@ public class GenericFileBufferOperationRunner { } private IFileBuffer[] findFileBuffersToSave(IFileBuffer[] fileBuffers) { - ArrayList list= new ArrayList(); + ArrayList<IFileBuffer> list= new ArrayList<>(); for (int i= 0; i < fileBuffers.length; i++) { IFileBuffer buffer= fileBuffers[i]; if (!buffer.isDirty()) list.add(buffer); } - return (IFileBuffer[]) list.toArray(new IFileBuffer[list.size()]); + return list.toArray(new IFileBuffer[list.size()]); } private boolean isCommitable(IFileBuffer[] fileBuffers) { @@ -273,7 +273,7 @@ public class GenericFileBufferOperationRunner { } protected ISchedulingRule computeCommitRule(IFileBuffer[] fileBuffers) { - ArrayList list= new ArrayList(); + ArrayList<ISchedulingRule> list= new ArrayList<>(); for (int i= 0; i < fileBuffers.length; i++) { ISchedulingRule rule= fileBuffers[i].computeCommitRule(); if (rule != null) diff --git a/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/manipulation/TextFileBufferOperation.java b/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/manipulation/TextFileBufferOperation.java index c4321198b2a..37e96d2ad81 100644 --- a/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/manipulation/TextFileBufferOperation.java +++ b/org.eclipse.core.filebuffers/src/org/eclipse/core/filebuffers/manipulation/TextFileBufferOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -33,6 +33,7 @@ import org.eclipse.jface.text.DocumentRewriteSession; import org.eclipse.jface.text.DocumentRewriteSessionType; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension4; +import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.TextUtilities; /** @@ -96,7 +97,7 @@ public abstract class TextFileBufferOperation implements IFileBufferOperation { MultiTextEditWithProgress edit= computeTextEdit(textFileBuffer, subMonitor); subMonitor.done(); if (edit != null) { - Object stateData= startRewriteSession(textFileBuffer); + Map<String, IDocumentPartitioner> stateData= startRewriteSession(textFileBuffer); try { subMonitor= Progress.getSubMonitor(progressMonitor, 90); applyTextEdit(textFileBuffer, edit, subMonitor); @@ -111,8 +112,8 @@ public abstract class TextFileBufferOperation implements IFileBufferOperation { } } - private Object startRewriteSession(ITextFileBuffer fileBuffer) { - Object stateData= null; + private Map<String, IDocumentPartitioner> startRewriteSession(ITextFileBuffer fileBuffer) { + Map<String, IDocumentPartitioner> stateData= null; IDocument document= fileBuffer.getDocument(); if (document instanceof IDocumentExtension4) { @@ -124,14 +125,14 @@ public abstract class TextFileBufferOperation implements IFileBufferOperation { return stateData; } - private void stopRewriteSession(ITextFileBuffer fileBuffer, Object stateData) { + private void stopRewriteSession(ITextFileBuffer fileBuffer, Map<String, IDocumentPartitioner> stateData) { IDocument document= fileBuffer.getDocument(); if (document instanceof IDocumentExtension4) { IDocumentExtension4 extension= (IDocumentExtension4) document; extension.stopRewriteSession(fDocumentRewriteSession); fDocumentRewriteSession= null; - } else if (stateData instanceof Map) - TextUtilities.addDocumentPartitioners(document, (Map) stateData); + } else if (stateData != null) + TextUtilities.addDocumentPartitioners(document, stateData); } private void applyTextEdit(ITextFileBuffer fileBuffer, MultiTextEditWithProgress textEdit, IProgressMonitor progressMonitor) throws CoreException, OperationCanceledException { diff --git a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ExtensionsRegistry.java b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ExtensionsRegistry.java index 63731ff3a1c..4e5e483f60b 100644 --- a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ExtensionsRegistry.java +++ b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ExtensionsRegistry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -85,17 +85,17 @@ public class ExtensionsRegistry { protected static final String WILDCARD= "*"; //$NON-NLS-1$ /** The mapping between file attributes and configuration elements describing document factories. */ - private Map fFactoryDescriptors= new HashMap(); + private Map<Object, Set<IConfigurationElement>> fFactoryDescriptors= new HashMap<>(); /** The mapping between configuration elements for document factories and instantiated document factories. */ - private Map fFactories= new HashMap(); + private Map<IConfigurationElement, Object> fFactories= new HashMap<>(); /** The mapping between file attributes and configuration elements describing document setup participants. */ - private Map fSetupParticipantDescriptors= new HashMap(); + private Map<Object, Set<IConfigurationElement>> fSetupParticipantDescriptors= new HashMap<>(); /** The mapping between configuration elements for setup participants and instantiated setup participants. */ - private Map fSetupParticipants= new HashMap(); + private Map<IConfigurationElement, Object> fSetupParticipants= new HashMap<>(); /** The mapping between file attributes and configuration elements describing annotation model factories. */ - private Map fAnnotationModelFactoryDescriptors= new HashMap(); + private Map<Object, Set<IConfigurationElement>> fAnnotationModelFactoryDescriptors= new HashMap<>(); /** The mapping between configuration elements for annotation model factories */ - private Map fAnnotationModelFactories= new HashMap(); + private Map<IConfigurationElement, Object> fAnnotationModelFactories= new HashMap<>(); /** The content type manager. */ protected IContentTypeManager fContentTypeManager= Platform.getContentTypeManager(); @@ -125,16 +125,16 @@ public class ExtensionsRegistry { * @param element the configuration element * @param map the map which remembers the configuration element */ - private void read(String attributeName, IConfigurationElement element, Map map) { + private void read(String attributeName, IConfigurationElement element, Map<Object, Set<IConfigurationElement>> map) { String value= element.getAttribute(attributeName); if (value != null) { StringTokenizer tokenizer= new StringTokenizer(value, ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { String token= tokenizer.nextToken().trim(); - Set s= (Set) map.get(token); + Set<IConfigurationElement> s= map.get(token); if (s == null) { - s= new HashSet(); + s= new HashSet<>(); map.put(token, s); } s.add(element); @@ -150,7 +150,7 @@ public class ExtensionsRegistry { * @param element the configuration element * @param map the map which remembers the configuration element */ - private void readContentType(String attributeName, IConfigurationElement element, Map map) { + private void readContentType(String attributeName, IConfigurationElement element, Map<Object, Set<IConfigurationElement>> map) { String value= element.getAttribute(attributeName); if (value != null) { IContentType contentType= fContentTypeManager.getContentType(value); @@ -159,9 +159,9 @@ public class ExtensionsRegistry { return; } ContentTypeAdapter adapter= new ContentTypeAdapter(contentType); - Set s= (Set) map.get(adapter); + Set<IConfigurationElement> s= map.get(adapter); if (s == null) { - s= new HashSet(); + s= new HashSet<>(); map.put(adapter, s); } s.add(element); @@ -187,7 +187,7 @@ public class ExtensionsRegistry { * @param isContentTypeId the child element is a content type id * @param descriptors the map to be filled */ - private void initialize(String extensionPointName, String childElementName, boolean isContentTypeId, Map descriptors) { + private void initialize(String extensionPointName, String childElementName, boolean isContentTypeId, Map<Object, Set<IConfigurationElement>> descriptors) { IExtensionPoint extensionPoint= Platform.getExtensionRegistry().getExtensionPoint(FileBuffersPlugin.PLUGIN_ID, extensionPointName); if (extensionPoint == null) { @@ -214,13 +214,14 @@ public class ExtensionsRegistry { * @param extensionType the requested result type * @return the executable extension for the given configuration element. */ - private Object getExtension(IConfigurationElement entry, Map extensions, Class extensionType) { - Object extension= extensions.get(entry); + @SuppressWarnings("unchecked") + private <T> T getExtension(IConfigurationElement entry, Map<IConfigurationElement, Object> extensions, Class<T> extensionType) { + T extension= (T) extensions.get(entry); if (extension != null) return extension; try { - extension= entry.createExecutableExtension("class"); //$NON-NLS-1$ + extension= (T) entry.createExecutableExtension("class"); //$NON-NLS-1$ } catch (CoreException x) { log(x.getStatus()); } @@ -239,10 +240,10 @@ public class ExtensionsRegistry { * @param set the set from which to choose * @return the selected configuration element */ - private IConfigurationElement selectConfigurationElement(Set set) { + private IConfigurationElement selectConfigurationElement(Set<IConfigurationElement> set) { if (set != null && !set.isEmpty()) { - Iterator e= set.iterator(); - return (IConfigurationElement) e.next(); + Iterator<IConfigurationElement> e= set.iterator(); + return e.next(); } return null; } @@ -256,10 +257,10 @@ public class ExtensionsRegistry { */ @Deprecated protected org.eclipse.core.filebuffers.IDocumentFactory getDocumentFactory(String nameOrExtension) { - Set set= (Set) fFactoryDescriptors.get(nameOrExtension); + Set<IConfigurationElement> set= fFactoryDescriptors.get(nameOrExtension); if (set != null) { IConfigurationElement entry= selectConfigurationElement(set); - return (org.eclipse.core.filebuffers.IDocumentFactory)getExtension(entry, fFactories, org.eclipse.core.filebuffers.IDocumentFactory.class); + return getExtension(entry, fFactories, org.eclipse.core.filebuffers.IDocumentFactory.class); } return null; } @@ -273,15 +274,15 @@ public class ExtensionsRegistry { */ @Deprecated protected org.eclipse.core.filebuffers.IDocumentFactory doGetDocumentFactory(IContentType[] contentTypes) { - Set set= null; + Set<IConfigurationElement> set= null; int i= 0; while (i < contentTypes.length && set == null) { - set= (Set) fFactoryDescriptors.get(new ContentTypeAdapter(contentTypes[i++])); + set= fFactoryDescriptors.get(new ContentTypeAdapter(contentTypes[i++])); } if (set != null) { IConfigurationElement entry= selectConfigurationElement(set); - return (org.eclipse.core.filebuffers.IDocumentFactory)getExtension(entry, fFactories, org.eclipse.core.filebuffers.IDocumentFactory.class); + return getExtension(entry, fFactories, org.eclipse.core.filebuffers.IDocumentFactory.class); } return null; } @@ -312,16 +313,16 @@ public class ExtensionsRegistry { * @param nameOrExtension the name or extension to be used for lookup * @return the sharable set of document setup participants */ - protected List getDocumentSetupParticipants(String nameOrExtension) { - Set set= (Set) fSetupParticipantDescriptors.get(nameOrExtension); + protected List<IDocumentSetupParticipant> getDocumentSetupParticipants(String nameOrExtension) { + Set<IConfigurationElement> set= fSetupParticipantDescriptors.get(nameOrExtension); if (set == null) return null; - List participants= new ArrayList(); - Iterator e= set.iterator(); + List<IDocumentSetupParticipant> participants= new ArrayList<>(); + Iterator<IConfigurationElement> e= set.iterator(); while (e.hasNext()) { - IConfigurationElement entry= (IConfigurationElement) e.next(); - Object participant= getExtension(entry, fSetupParticipants, IDocumentSetupParticipant.class); + IConfigurationElement entry= e.next(); + IDocumentSetupParticipant participant= getExtension(entry, fSetupParticipants, IDocumentSetupParticipant.class); if (participant != null) participants.add(participant); } @@ -335,20 +336,20 @@ public class ExtensionsRegistry { * @param contentTypes the contentTypes to be used for lookup * @return the sharable set of document setup participants */ - private List doGetDocumentSetupParticipants(IContentType[] contentTypes) { - Set resultSet= new HashSet(); + private List<IDocumentSetupParticipant> doGetDocumentSetupParticipants(IContentType[] contentTypes) { + Set<IConfigurationElement> resultSet= new HashSet<>(); int i= 0; while (i < contentTypes.length) { - Set set= (Set) fSetupParticipantDescriptors.get(new ContentTypeAdapter(contentTypes[i++])); + Set<IConfigurationElement> set= fSetupParticipantDescriptors.get(new ContentTypeAdapter(contentTypes[i++])); if (set != null) resultSet.addAll(set); } - List participants= new ArrayList(); - Iterator e= resultSet.iterator(); + List<IDocumentSetupParticipant> participants= new ArrayList<>(); + Iterator<IConfigurationElement> e= resultSet.iterator(); while (e.hasNext()) { - IConfigurationElement entry= (IConfigurationElement) e.next(); - Object participant= getExtension(entry, fSetupParticipants, IDocumentSetupParticipant.class); + IConfigurationElement entry= e.next(); + IDocumentSetupParticipant participant= getExtension(entry, fSetupParticipants, IDocumentSetupParticipant.class); if (participant != null) participants.add(participant); } @@ -364,8 +365,8 @@ public class ExtensionsRegistry { * @param contentTypes the contentTypes to be used for lookup * @return the sharable set of document setup participants */ - protected List getDocumentSetupParticipants(IContentType[] contentTypes) { - List participants= doGetDocumentSetupParticipants(contentTypes); + protected List<IDocumentSetupParticipant> getDocumentSetupParticipants(IContentType[] contentTypes) { + List<IDocumentSetupParticipant> participants= doGetDocumentSetupParticipants(contentTypes); while (participants == null) { contentTypes= computeBaseContentTypes(contentTypes); if (contentTypes == null) @@ -382,15 +383,15 @@ public class ExtensionsRegistry { * @return the sharable annotation model factory or <code>null</code> */ private IAnnotationModelFactory doGetAnnotationModelFactory(IContentType[] contentTypes) { - Set set= null; + Set<IConfigurationElement> set= null; int i= 0; while (i < contentTypes.length && set == null) { - set= (Set) fAnnotationModelFactoryDescriptors.get(new ContentTypeAdapter(contentTypes[i++])); + set= fAnnotationModelFactoryDescriptors.get(new ContentTypeAdapter(contentTypes[i++])); } if (set != null) { IConfigurationElement entry= selectConfigurationElement(set); - return (IAnnotationModelFactory) getExtension(entry, fAnnotationModelFactories, IAnnotationModelFactory.class); + return getExtension(entry, fAnnotationModelFactories, IAnnotationModelFactory.class); } return null; } @@ -421,10 +422,10 @@ public class ExtensionsRegistry { * @return the sharable document factory or <code>null</code> */ protected IAnnotationModelFactory getAnnotationModelFactory(String extension) { - Set set= (Set) fAnnotationModelFactoryDescriptors.get(extension); + Set<IConfigurationElement> set= fAnnotationModelFactoryDescriptors.get(extension); if (set != null) { IConfigurationElement entry= selectConfigurationElement(set); - return (IAnnotationModelFactory) getExtension(entry, fAnnotationModelFactories, IAnnotationModelFactory.class); + return getExtension(entry, fAnnotationModelFactories, IAnnotationModelFactory.class); } return null; } @@ -451,7 +452,7 @@ public class ExtensionsRegistry { * @return the set of direct base content types */ private IContentType[] computeBaseContentTypes(IContentType[] contentTypes) { - List baseTypes= new ArrayList(); + List<IContentType> baseTypes= new ArrayList<>(); for (int i= 0; i < contentTypes.length; i++) { IContentType baseType= contentTypes[i].getBaseType(); if (baseType != null) @@ -497,9 +498,9 @@ public class ExtensionsRegistry { * @since 3.3 */ public IDocumentSetupParticipant[] getDocumentSetupParticipants(IPath location, LocationKind locationKind) { - Set participants= new HashSet(); + Set<IDocumentSetupParticipant> participants= new HashSet<>(); - List p= getDocumentSetupParticipants(findContentTypes(location, locationKind)); + List<IDocumentSetupParticipant> p= getDocumentSetupParticipants(findContentTypes(location, locationKind)); if (p != null) participants.addAll(p); diff --git a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceExtensionRegistry.java b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceExtensionRegistry.java index 0c171b05541..af4e33cca14 100644 --- a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceExtensionRegistry.java +++ b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceExtensionRegistry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -116,9 +116,9 @@ public class ResourceExtensionRegistry extends ExtensionsRegistry { * @return the sharable set of document setup participants */ IDocumentSetupParticipant[] getDocumentSetupParticipants(IFile file) { - Set participants= new HashSet(); + Set<IDocumentSetupParticipant> participants= new HashSet<>(); - List p= getDocumentSetupParticipants(findContentTypes(file)); + List<IDocumentSetupParticipant> p= getDocumentSetupParticipants(findContentTypes(file)); if (p != null) participants.addAll(p); diff --git a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceTextFileBufferManager.java b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceTextFileBufferManager.java index d3932fdbe45..0f183eb5ccd 100644 --- a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceTextFileBufferManager.java +++ b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ResourceTextFileBufferManager.java @@ -236,7 +236,7 @@ public class ResourceTextFileBufferManager extends TextFileBufferManager { } private IStatus validateEdit(IFileBuffer[] fileBuffers, Object computationContext) { - ArrayList list= new ArrayList(); + ArrayList<IFile> list= new ArrayList<>(); for (int i= 0; i < fileBuffers.length; i++) { IFile file= getWorkspaceFile(fileBuffers[i]); if (file != null) @@ -248,12 +248,12 @@ public class ResourceTextFileBufferManager extends TextFileBufferManager { } private IFileBuffer[] findFileBuffersToValidate(IFileBuffer[] fileBuffers) { - ArrayList list= new ArrayList(); + ArrayList<IFileBuffer> list= new ArrayList<>(); for (int i= 0; i < fileBuffers.length; i++) { if (!fileBuffers[i].isStateValidated()) list.add(fileBuffers[i]); } - return (IFileBuffer[]) list.toArray(new IFileBuffer[list.size()]); + return list.toArray(new IFileBuffer[list.size()]); } private void validationStateAboutToBeChanged(IFileBuffer[] fileBuffers) { @@ -288,7 +288,7 @@ public class ResourceTextFileBufferManager extends TextFileBufferManager { } private ISchedulingRule computeValidateStateRule(IFileBuffer[] fileBuffers) { - ArrayList list= new ArrayList(); + ArrayList<IResource> list= new ArrayList<>(); for (int i= 0; i < fileBuffers.length; i++) { IResource resource= getWorkspaceFile(fileBuffers[i]); if (resource != null) diff --git a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/TextFileBufferManager.java b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/TextFileBufferManager.java index 1a0da3fcec0..25aba768cd2 100644 --- a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/TextFileBufferManager.java +++ b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/TextFileBufferManager.java @@ -68,9 +68,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { protected static final IContentType TEXT_CONTENT_TYPE= Platform.getContentTypeManager().getContentType(IContentTypeManager.CT_TEXT); - private Map fFilesBuffers= new HashMap(); - private Map fFileStoreFileBuffers= new HashMap(); - private List fFileBufferListeners= new ArrayList(); + private Map<IPath, AbstractFileBuffer> fFilesBuffers= new HashMap<>(); + private Map<IFileStore, FileStoreFileBuffer> fFileStoreFileBuffers= new HashMap<>(); + private List<IFileBufferListener> fFileBufferListeners= new ArrayList<>(); protected ExtensionsRegistry fRegistry; private ISynchronizationContext fSynchronizationContext; @@ -339,13 +339,13 @@ public class TextFileBufferManager implements ITextFileBufferManager { private AbstractFileBuffer internalGetFileBuffer(IPath location) { synchronized (fFilesBuffers) { - return (AbstractFileBuffer)fFilesBuffers.get(location); + return fFilesBuffers.get(location); } } private FileStoreFileBuffer internalGetFileBuffer(IFileStore fileStore) { synchronized (fFileStoreFileBuffers) { - return (FileStoreFileBuffer)fFileStoreFileBuffers.get(fileStore); + return fFileStoreFileBuffers.get(fileStore); } } @@ -374,9 +374,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { @Override public ITextFileBuffer getTextFileBuffer(IDocument document) { Assert.isLegal(document != null); - Iterator iter; + Iterator<AbstractFileBuffer> iter; synchronized (fFilesBuffers) { - iter= new ArrayList(fFilesBuffers.values()).iterator(); + iter= new ArrayList<>(fFilesBuffers.values()).iterator(); } while (iter.hasNext()) { @@ -391,7 +391,7 @@ public class TextFileBufferManager implements ITextFileBufferManager { } } synchronized (fFileStoreFileBuffers) { - iter= new ArrayList(fFileStoreFileBuffers.values()).iterator(); + iter= new ArrayList<AbstractFileBuffer>(fFileStoreFileBuffers.values()).iterator(); } while (iter.hasNext()) { Object buffer= iter.next(); @@ -409,16 +409,16 @@ public class TextFileBufferManager implements ITextFileBufferManager { @Override public IFileBuffer[] getFileBuffers() { synchronized (fFilesBuffers) { - Collection values= fFilesBuffers.values(); - return (IFileBuffer[])values.toArray(new IFileBuffer[values.size()]); + Collection<AbstractFileBuffer> values= fFilesBuffers.values(); + return values.toArray(new IFileBuffer[values.size()]); } } @Override public IFileBuffer[] getFileStoreFileBuffers() { synchronized (fFileStoreFileBuffers) { - Collection values= fFileStoreFileBuffers.values(); - return (IFileBuffer[])values.toArray(new IFileBuffer[values.size()]); + Collection<FileStoreFileBuffer> values= fFileStoreFileBuffers.values(); + return values.toArray(new IFileBuffer[values.size()]); } } @@ -663,16 +663,16 @@ public class TextFileBufferManager implements ITextFileBufferManager { // return createTextFileBuffer(location); // } - private Iterator getFileBufferListenerIterator() { + private Iterator<IFileBufferListener> getFileBufferListenerIterator() { synchronized (fFileBufferListeners) { - return new ArrayList(fFileBufferListeners).iterator(); + return new ArrayList<>(fFileBufferListeners).iterator(); } } protected void fireDirtyStateChanged(final IFileBuffer buffer, final boolean isDirty) { - Iterator e= getFileBufferListenerIterator(); + Iterator<IFileBufferListener> e= getFileBufferListenerIterator(); while (e.hasNext()) { - final IFileBufferListener l= (IFileBufferListener) e.next(); + final IFileBufferListener l= e.next(); SafeRunner.run(new SafeNotifier() { @Override public void run() { @@ -683,9 +683,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { } protected void fireBufferContentAboutToBeReplaced(final IFileBuffer buffer) { - Iterator e= getFileBufferListenerIterator(); + Iterator<IFileBufferListener> e= getFileBufferListenerIterator(); while (e.hasNext()) { - final IFileBufferListener l= (IFileBufferListener) e.next(); + final IFileBufferListener l= e.next(); SafeRunner.run(new SafeNotifier() { @Override public void run() { @@ -696,9 +696,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { } protected void fireBufferContentReplaced(final IFileBuffer buffer) { - Iterator e= getFileBufferListenerIterator(); + Iterator<IFileBufferListener> e= getFileBufferListenerIterator(); while (e.hasNext()) { - final IFileBufferListener l= (IFileBufferListener) e.next(); + final IFileBufferListener l= e.next(); SafeRunner.run(new SafeNotifier() { @Override public void run() { @@ -709,9 +709,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { } protected void fireUnderlyingFileMoved(final IFileBuffer buffer, final IPath target) { - Iterator e= getFileBufferListenerIterator(); + Iterator<IFileBufferListener> e= getFileBufferListenerIterator(); while (e.hasNext()) { - final IFileBufferListener l= (IFileBufferListener) e.next(); + final IFileBufferListener l= e.next(); SafeRunner.run(new SafeNotifier() { @Override public void run() { @@ -722,9 +722,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { } protected void fireUnderlyingFileDeleted(final IFileBuffer buffer) { - Iterator e= getFileBufferListenerIterator(); + Iterator<IFileBufferListener> e= getFileBufferListenerIterator(); while (e.hasNext()) { - final IFileBufferListener l= (IFileBufferListener) e.next(); + final IFileBufferListener l= e.next(); SafeRunner.run(new SafeNotifier() { @Override public void run() { @@ -735,9 +735,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { } protected void fireStateValidationChanged(final IFileBuffer buffer, final boolean isStateValidated) { - Iterator e= getFileBufferListenerIterator(); + Iterator<IFileBufferListener> e= getFileBufferListenerIterator(); while (e.hasNext()) { - final IFileBufferListener l= (IFileBufferListener) e.next(); + final IFileBufferListener l= e.next(); SafeRunner.run(new SafeNotifier() { @Override public void run() { @@ -748,9 +748,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { } protected void fireStateChanging(final IFileBuffer buffer) { - Iterator e= getFileBufferListenerIterator(); + Iterator<IFileBufferListener> e= getFileBufferListenerIterator(); while (e.hasNext()) { - final IFileBufferListener l= (IFileBufferListener) e.next(); + final IFileBufferListener l= e.next(); SafeRunner.run(new SafeNotifier() { @Override public void run() { @@ -761,9 +761,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { } protected void fireStateChangeFailed(final IFileBuffer buffer) { - Iterator e= getFileBufferListenerIterator(); + Iterator<IFileBufferListener> e= getFileBufferListenerIterator(); while (e.hasNext()) { - final IFileBufferListener l= (IFileBufferListener) e.next(); + final IFileBufferListener l= e.next(); SafeRunner.run(new SafeNotifier() { @Override public void run() { @@ -774,9 +774,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { } protected void fireBufferCreated(final IFileBuffer buffer) { - Iterator e= getFileBufferListenerIterator(); + Iterator<IFileBufferListener> e= getFileBufferListenerIterator(); while (e.hasNext()) { - final IFileBufferListener l= (IFileBufferListener) e.next(); + final IFileBufferListener l= e.next(); SafeRunner.run(new SafeNotifier() { @Override public void run() { @@ -787,9 +787,9 @@ public class TextFileBufferManager implements ITextFileBufferManager { } protected void fireBufferDisposed(final IFileBuffer buffer) { - Iterator e= getFileBufferListenerIterator(); + Iterator<IFileBufferListener> e= getFileBufferListenerIterator(); while (e.hasNext()) { - final IFileBufferListener l= (IFileBufferListener) e.next(); + final IFileBufferListener l= e.next(); SafeRunner.run(new SafeNotifier() { @Override public void run() { diff --git a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/AbstractPairMatcherTest.java b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/AbstractPairMatcherTest.java index 6108c22400b..0a6a828a6c9 100644 --- a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/AbstractPairMatcherTest.java +++ b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/AbstractPairMatcherTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2012 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,8 +13,6 @@ package org.eclipse.jface.text.tests; import java.util.ArrayList; import java.util.List; -import junit.framework.TestCase; - import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; @@ -31,6 +29,8 @@ import org.eclipse.jface.text.source.DefaultCharacterPairMatcher; import org.eclipse.jface.text.source.ICharacterPairMatcher; import org.eclipse.jface.text.source.ICharacterPairMatcherExtension; +import junit.framework.TestCase; + /** * Generic test of simple character pair matchers * @@ -74,7 +74,7 @@ public abstract class AbstractPairMatcherTest extends TestCase { /** * Very simple checks. * - * @throws BadLocationException + * @throws BadLocationException test failure */ public void testSimpleMatchSameMatcher() throws BadLocationException { final ICharacterPairMatcher matcher= createMatcher("()[]{}"); @@ -106,7 +106,7 @@ public abstract class AbstractPairMatcherTest extends TestCase { /** * Very simple checks. * - * @throws BadLocationException + * @throws BadLocationException test failure */ public void testSimpleMatchDifferentMatchers() throws BadLocationException { performMatch("()[]{}", "#( )%"); @@ -124,7 +124,7 @@ public abstract class AbstractPairMatcherTest extends TestCase { /** * Close matches. * - * @throws BadLocationException + * @throws BadLocationException test failure */ public void testCloseMatches() throws BadLocationException { final ICharacterPairMatcher matcher= createMatcher("()[]{}"); @@ -151,7 +151,7 @@ public abstract class AbstractPairMatcherTest extends TestCase { /** * Checks of simple situations where no matches should be found. * - * @throws BadLocationException + * @throws BadLocationException test failure */ public void testIncompleteMatch() throws BadLocationException { final ICharacterPairMatcher matcher= createMatcher("()[]{}"); @@ -164,7 +164,7 @@ public abstract class AbstractPairMatcherTest extends TestCase { /** * Test that it doesn't match across different partitions. * - * @throws BadLocationException + * @throws BadLocationException test failure */ public void testPartitioned() throws BadLocationException { final ICharacterPairMatcher matcher= createMatcher("()[]{}"); @@ -201,7 +201,7 @@ public abstract class AbstractPairMatcherTest extends TestCase { /** * Test that it works properly next to partition boundaries. * - * @throws BadLocationException + * @throws BadLocationException test failure */ public void testTightPartitioned() throws BadLocationException { final ICharacterPairMatcher matcher= createMatcher("()[]{}"); @@ -255,7 +255,7 @@ public abstract class AbstractPairMatcherTest extends TestCase { /** * Test a few boundary conditions. * - * * @throws BadLocationException + * * @throws BadLocationException test failure */ public void testBoundaries() throws BadLocationException { final ICharacterPairMatcher matcher= createMatcher("()[]{}"); @@ -519,11 +519,11 @@ public abstract class AbstractPairMatcherTest extends TestCase { private static IDocumentPartitioner createPartitioner() { final RuleBasedPartitionScanner scan= new RuleBasedPartitionScanner(); - final List/*<IPredicateRule>*/ rules= new ArrayList/*<IPredicateRule>*/(); + final List<SingleLineRule> rules= new ArrayList<>(); rules.add(new SingleLineRule("|a", "a|", new Token("a"))); rules.add(new SingleLineRule("|b", "b|", new Token("b"))); rules.add(new SingleLineRule("|c", "c|", new Token("c"))); - scan.setPredicateRules((IPredicateRule[]) rules.toArray(new IPredicateRule[rules.size()])); + scan.setPredicateRules(rules.toArray(new IPredicateRule[rules.size()])); scan.setDefaultReturnToken(new Token(DEFAULT_PARTITION)); return new FastPartitioner(scan, new String[] { DEFAULT_PARTITION, "a", "b", "c" }); } diff --git a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/DefaultPairMatcherTest.java b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/DefaultPairMatcherTest.java index bac928e01b1..cd53ca47e3f 100644 --- a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/DefaultPairMatcherTest.java +++ b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/DefaultPairMatcherTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2012 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,12 +10,12 @@ *******************************************************************************/ package org.eclipse.jface.text.tests; -import junit.framework.Test; -import junit.framework.TestSuite; - import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.source.ICharacterPairMatcher; +import junit.framework.Test; +import junit.framework.TestSuite; + /** * Tests for the default pair matcher. @@ -42,7 +42,7 @@ public class DefaultPairMatcherTest extends AbstractPairMatcherTest { /** * Close matches. * - * @throws BadLocationException + * @throws BadLocationException test failure */ public void testCloseMatches1() throws BadLocationException { final ICharacterPairMatcher matcher= createMatcher("()[]{}"); @@ -55,7 +55,7 @@ public class DefaultPairMatcherTest extends AbstractPairMatcherTest { /** * Checks of simple situations where no matches should be found. * - * @throws BadLocationException + * @throws BadLocationException test failure */ public void testIncompleteMatch1() throws BadLocationException { final ICharacterPairMatcher matcher= createMatcher("()[]{}"); diff --git a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/DefaultPairMatcherTest2.java b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/DefaultPairMatcherTest2.java index 56f3d985ce4..30f6a16cc15 100644 --- a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/DefaultPairMatcherTest2.java +++ b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/DefaultPairMatcherTest2.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012 IBM Corporation and others. + * Copyright (c) 2012, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,12 +10,12 @@ *******************************************************************************/ package org.eclipse.jface.text.tests; -import junit.framework.Test; -import junit.framework.TestSuite; - import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.source.ICharacterPairMatcher; +import junit.framework.Test; +import junit.framework.TestSuite; + /** * Tests for the default pair matcher. @@ -42,7 +42,7 @@ public class DefaultPairMatcherTest2 extends AbstractPairMatcherTest { /** * Very simple checks. * - * @throws BadLocationException + * @throws BadLocationException test failure */ public void testSimpleMatchSameMatcher1() throws BadLocationException { final ICharacterPairMatcher matcher= createMatcher("()[]{}"); diff --git a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/HTML2TextReaderTest.java b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/HTML2TextReaderTest.java index 2c9fc3da7c7..60f8e0dbcde 100644 --- a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/HTML2TextReaderTest.java +++ b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/HTML2TextReaderTest.java @@ -16,14 +16,9 @@ import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; -import java.util.Comparator; import java.util.Iterator; import java.util.List; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; @@ -31,6 +26,10 @@ import org.eclipse.jface.internal.text.html.HTML2TextReader; import org.eclipse.jface.text.TextPresentation; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + public class HTML2TextReaderTest extends TestCase { @@ -47,10 +46,10 @@ public class HTML2TextReaderTest extends TestCase { } /** - * @param input - * @param expectedOutput - * @param styleRangeCount - * @throws IOException + * @param input input + * @param expectedOutput expected output + * @param styleRangeCount count + * @throws IOException test failure * @deprecated pass actual style ranges */ @Deprecated @@ -63,26 +62,19 @@ public class HTML2TextReaderTest extends TestCase { System.out.println("<" + result + "/>"); assertEquals(expectedOutput, result); - Iterator styleRangeIterator= textPresentation.getAllStyleRangeIterator(); - List ranges= new ArrayList(); + Iterator<StyleRange> styleRangeIterator= textPresentation.getAllStyleRangeIterator(); + List<StyleRange> ranges= new ArrayList<>(); while (styleRangeIterator.hasNext()) { ranges.add(styleRangeIterator.next()); } assertEquals("Incorrect number of style ranges", styleRangeCount, ranges.size()); - Collections.sort(ranges, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - StyleRange range1= (StyleRange)o1; - StyleRange range2= (StyleRange)o2; - return range1.start - range2.start; - } - }); + Collections.sort(ranges, (r1, r2) -> r1.start - r2.start); for (int i= 0; i < ranges.size() - 1; i++) { - StyleRange range1= (StyleRange)ranges.get(i); - StyleRange range2= (StyleRange)ranges.get(i + 1); + StyleRange range1= ranges.get(i); + StyleRange range2= ranges.get(i + 1); if (range1.start + range1.length > range2.start) { assertTrue("StyleRanges overlap", false); @@ -100,26 +92,19 @@ public class HTML2TextReaderTest extends TestCase { System.out.println("<" + result + "/>"); assertEquals(expectedOutput, result); - Iterator styleRangeIterator= textPresentation.getAllStyleRangeIterator(); - List ranges= new ArrayList(); + Iterator<StyleRange> styleRangeIterator= textPresentation.getAllStyleRangeIterator(); + List<StyleRange> ranges= new ArrayList<>(); while (styleRangeIterator.hasNext()) { ranges.add(styleRangeIterator.next()); } - Collections.sort(ranges, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - StyleRange range1= (StyleRange)o1; - StyleRange range2= (StyleRange)o2; - return range1.start - range2.start; - } - }); + Collections.sort(ranges, (r1, r2) -> r1.start - r2.start); assertEquals(Arrays.asList(styleRanges), ranges); for (int i= 0; i < ranges.size() - 1; i++) { - StyleRange range1= (StyleRange)ranges.get(i); - StyleRange range2= (StyleRange)ranges.get(i + 1); + StyleRange range1= ranges.get(i); + StyleRange range2= ranges.get(i + 1); if (range1.start + range1.length > range2.start) { assertTrue("StyleRanges overlap", false); diff --git a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TestTextViewer.java b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TestTextViewer.java index 7a1bc80228c..7e4bfb6b38f 100644 --- a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TestTextViewer.java +++ b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TestTextViewer.java @@ -51,8 +51,8 @@ public class TestTextViewer implements ISourceViewer, IDocumentListener { protected IDocument fDocument; - protected List fInputListeners= new ArrayList(); - protected List fTextListeners= new ArrayList(); + protected List<ITextInputListener> fInputListeners= new ArrayList<>(); + protected List<ITextListener> fTextListeners= new ArrayList<>(); protected TextPresentation fTextPresentation; protected Point fSelection= new Point(-1, -1); protected String fDeletion; @@ -112,9 +112,9 @@ public class TestTextViewer implements ISourceViewer, IDocumentListener { } protected void fireTextInputChanged(IDocument oldDoc, IDocument newDoc, boolean about) { - Iterator e= new ArrayList(fInputListeners).iterator(); + Iterator<ITextInputListener> e= new ArrayList<>(fInputListeners).iterator(); while (e.hasNext()) { - ITextInputListener l= (ITextInputListener) e.next(); + ITextInputListener l= e.next(); if (about) l.inputDocumentAboutToBeChanged(oldDoc, newDoc); else @@ -377,9 +377,9 @@ public class TestTextViewer implements ISourceViewer, IDocumentListener { } protected void fireTextChanged(TextEvent event) { - Iterator e= new ArrayList(fTextListeners).iterator(); + Iterator<ITextListener> e= new ArrayList<>(fTextListeners).iterator(); while (e.hasNext()) { - ITextListener l= (ITextListener) e.next(); + ITextListener l= e.next(); l.textChanged(event); } } diff --git a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TextPresentationTest.java b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TextPresentationTest.java index 665b53abc7d..3572129f1ba 100644 --- a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TextPresentationTest.java +++ b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/TextPresentationTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,10 +12,6 @@ package org.eclipse.jface.text.tests; import java.util.Iterator; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.graphics.Color; @@ -24,6 +20,10 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextPresentation; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + public class TextPresentationTest extends TestCase { private static final int NORMAL= SWT.NORMAL; @@ -98,7 +98,7 @@ public class TextPresentationTest extends TestCase { } private void checkRegions(StyleRange[] expectedAllRanges, StyleRange[] expectedNonDefaultRanges) { - Iterator e= fTextPresentation.getAllStyleRangeIterator(); + Iterator<StyleRange> e= fTextPresentation.getAllStyleRangeIterator(); for (int i= 0; i < expectedAllRanges.length; i++) { assertTrue(e.hasNext()); assertEquals(expectedAllRanges[i], e.next()); diff --git a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/reconciler/AbstractReconcilerTest.java b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/reconciler/AbstractReconcilerTest.java index ee4fddf83bf..1a74715804b 100644 --- a/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/reconciler/AbstractReconcilerTest.java +++ b/org.eclipse.jface.text.tests/src/org/eclipse/jface/text/tests/reconciler/AbstractReconcilerTest.java @@ -127,7 +127,7 @@ public class AbstractReconcilerTest extends TestCase { private Accessor fAccessor; private Barrier fBarrier; - private List fCallLog; + private List<String> fCallLog; private ITextViewer fViewer; protected AbstractReconciler fReconciler; private Document fDocument; @@ -138,7 +138,7 @@ public class AbstractReconcilerTest extends TestCase { @Override protected void setUp() { fBarrier= new Barrier(); - fCallLog= Collections.synchronizedList(new ArrayList()); + fCallLog= Collections.synchronizedList(new ArrayList<String>()); fReconciler= new AbstractReconciler() { @Override protected void initialProcess() { diff --git a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/AnnotationBag.java b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/AnnotationBag.java index 94681b1d885..94c91ae638d 100644 --- a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/AnnotationBag.java +++ b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/AnnotationBag.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -27,7 +27,7 @@ import org.eclipse.jface.text.source.Annotation; */ public class AnnotationBag extends Annotation { - private Set fAnnotations; + private Set<Annotation> fAnnotations; /** * Creates a new annotation bag. @@ -45,7 +45,7 @@ public class AnnotationBag extends Annotation { */ public void add(Annotation annotation) { if (fAnnotations == null) - fAnnotations= new HashSet(2); + fAnnotations= new HashSet<>(2); fAnnotations.add(annotation); } @@ -78,7 +78,7 @@ public class AnnotationBag extends Annotation { * @return an iterator for all annotations in the bag or <code>null</code> * @since 3.1 */ - public Iterator iterator() { + public Iterator<Annotation> iterator() { if (!isEmpty()) return fAnnotations.iterator(); return null; diff --git a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionAnnotationHover.java b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionAnnotationHover.java index 2374073e703..1ea796c8ab3 100644 --- a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionAnnotationHover.java +++ b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionAnnotationHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -23,6 +23,7 @@ import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.information.IInformationProviderExtension2; +import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationHover; import org.eclipse.jface.text.source.IAnnotationHoverExtension; import org.eclipse.jface.text.source.IAnnotationModel; @@ -102,7 +103,7 @@ class ProjectionAnnotationHover implements IAnnotationHover, IAnnotationHoverExt if (model != null) { try { IDocument document= viewer.getDocument(); - Iterator e= model.getAnnotationIterator(); + Iterator<Annotation> e= model.getAnnotationIterator(); while (e.hasNext()) { ProjectionAnnotation annotation= (ProjectionAnnotation) e.next(); if (!annotation.isCollapsed()) diff --git a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionAnnotationModel.java b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionAnnotationModel.java index a40bedb601e..d95eb17b542 100644 --- a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionAnnotationModel.java +++ b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionAnnotationModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -113,7 +113,7 @@ public class ProjectionAnnotationModel extends AnnotationModel { boolean collapsing= false; - Iterator iterator= getAnnotationIterator(); + Iterator<Annotation> iterator= getAnnotationIterator(); while (iterator.hasNext()) { ProjectionAnnotation annotation= (ProjectionAnnotation) iterator.next(); if (!annotation.isCollapsed()) { @@ -146,7 +146,7 @@ public class ProjectionAnnotationModel extends AnnotationModel { boolean expanding= false; - Iterator iterator= getAnnotationIterator(); + Iterator<Annotation> iterator= getAnnotationIterator(); while (iterator.hasNext()) { ProjectionAnnotation annotation= (ProjectionAnnotation) iterator.next(); if (annotation.isCollapsed()) { @@ -172,7 +172,7 @@ public class ProjectionAnnotationModel extends AnnotationModel { * @param additions the set of annotations to add together with their associated position * @param modifications the list of modified annotations */ - public void modifyAnnotations(Annotation[] deletions, Map additions, Annotation[] modifications) { + public void modifyAnnotations(Annotation[] deletions, Map<? extends Annotation, ? extends Position> additions, Annotation[] modifications) { try { replaceAnnotations(deletions, additions, false); if (modifications != null) { diff --git a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionRulerColumn.java b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionRulerColumn.java index d7c156a226b..b184718f8d5 100644 --- a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionRulerColumn.java +++ b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionRulerColumn.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -22,6 +22,7 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.AnnotationRulerColumn; import org.eclipse.jface.text.source.CompositeRuler; import org.eclipse.jface.text.source.IAnnotationAccess; @@ -113,7 +114,7 @@ class ProjectionRulerColumn extends AnnotationRulerColumn { int previousDistance= Integer.MAX_VALUE; - Iterator e= model.getAnnotationIterator(); + Iterator<Annotation> e= model.getAnnotationIterator(); while (e.hasNext()) { Object next= e.next(); if (next instanceof ProjectionAnnotation) { diff --git a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSummary.java b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSummary.java index 1475139012d..abd2fd7f664 100644 --- a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSummary.java +++ b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSummary.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -79,7 +79,7 @@ class ProjectionSummary { private ProjectionViewer fProjectionViewer; private IAnnotationAccess fAnnotationAccess; - private List fConfiguredAnnotationTypes; + private List<String> fConfiguredAnnotationTypes; private Object fLock= new Object(); private IProgressMonitor fProgressMonitor; @@ -106,7 +106,7 @@ class ProjectionSummary { public void addAnnotationType(String annotationType) { synchronized(fLock) { if (fConfiguredAnnotationTypes == null) { - fConfiguredAnnotationTypes= new ArrayList(); + fConfiguredAnnotationTypes= new ArrayList<>(); fConfiguredAnnotationTypes.add(annotationType); } else if (!fConfiguredAnnotationTypes.contains(annotationType)) fConfiguredAnnotationTypes.add(annotationType); @@ -161,16 +161,16 @@ class ProjectionSummary { private void removeSummaries(IProgressMonitor monitor, IAnnotationModel visualAnnotationModel) { IAnnotationModelExtension extension= null; - List bags= null; + List<Annotation> bags= null; if (visualAnnotationModel instanceof IAnnotationModelExtension) { extension= (IAnnotationModelExtension)visualAnnotationModel; - bags= new ArrayList(); + bags= new ArrayList<>(); } - Iterator e= visualAnnotationModel.getAnnotationIterator(); + Iterator<Annotation> e= visualAnnotationModel.getAnnotationIterator(); while (e.hasNext()) { - Annotation annotation= (Annotation) e.next(); + Annotation annotation= e.next(); if (annotation instanceof AnnotationBag) { if (bags == null) visualAnnotationModel.removeAnnotation(annotation); @@ -195,9 +195,9 @@ class ProjectionSummary { if (model == null) return; - Map additions= new HashMap(); + Map<Annotation, Position> additions= new HashMap<>(); - Iterator e= model.getAnnotationIterator(); + Iterator<Annotation> e= model.getAnnotationIterator(); while (e.hasNext()) { ProjectionAnnotation projection= (ProjectionAnnotation) e.next(); if (projection.isCollapsed()) { @@ -222,10 +222,10 @@ class ProjectionSummary { if (!isCanceled(monitor)) extension.replaceAnnotations(null, additions); } else { - Iterator e1= additions.keySet().iterator(); + Iterator<Annotation> e1= additions.keySet().iterator(); while (e1.hasNext()) { AnnotationBag bag= (AnnotationBag) e1.next(); - Position position= (Position) additions.get(bag); + Position position= additions.get(bag); if (isCanceled(monitor)) return; visualAnnotationModel.addAnnotation(bag, position); @@ -234,17 +234,17 @@ class ProjectionSummary { } } - private void createSummary(Map additions, IRegion[] summaryRegions, Position summaryAnchor) { + private void createSummary(Map<Annotation, Position> additions, IRegion[] summaryRegions, Position summaryAnchor) { int size= 0; - Map map= null; + Map<String, AnnotationBag> map= null; synchronized (fLock) { if (fConfiguredAnnotationTypes != null) { size= fConfiguredAnnotationTypes.size(); - map= new HashMap(); + map= new HashMap<>(); for (int i= 0; i < size; i++) { - String type= (String) fConfiguredAnnotationTypes.get(i); + String type= fConfiguredAnnotationTypes.get(i); map.put(type, new AnnotationBag(type)); } } @@ -256,9 +256,9 @@ class ProjectionSummary { IAnnotationModel model= fProjectionViewer.getAnnotationModel(); if (model == null) return; - Iterator e= model.getAnnotationIterator(); + Iterator<Annotation> e= model.getAnnotationIterator(); while (e.hasNext()) { - Annotation annotation= (Annotation) e.next(); + Annotation annotation= e.next(); AnnotationBag bag= findBagForType(map, annotation.getType()); if (bag != null) { Position position= model.getPosition(annotation); @@ -268,19 +268,19 @@ class ProjectionSummary { } for (int i= 0; i < size; i++) { - AnnotationBag bag= (AnnotationBag) map.get(fConfiguredAnnotationTypes.get(i)); + AnnotationBag bag= map.get(fConfiguredAnnotationTypes.get(i)); if (!bag.isEmpty()) additions.put(bag, new Position(summaryAnchor.getOffset(), summaryAnchor.getLength())); } } - private AnnotationBag findBagForType(Map bagMap, String annotationType) { - AnnotationBag bag= (AnnotationBag) bagMap.get(annotationType); + private AnnotationBag findBagForType(Map<String, AnnotationBag> bagMap, String annotationType) { + AnnotationBag bag= bagMap.get(annotationType); if (bag == null && fAnnotationAccess instanceof IAnnotationAccessExtension) { IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess; Object[] superTypes= extension.getSupertypes(annotationType); for (int i= 0; i < superTypes.length && bag == null; i++) { - bag= (AnnotationBag) bagMap.get(superTypes[i]); + bag= bagMap.get(superTypes[i]); } } return bag; diff --git a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSupport.java b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSupport.java index e6722f766eb..09b1be4f9c8 100644 --- a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSupport.java +++ b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionSupport.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -144,7 +144,7 @@ public class ProjectionSupport { private ProjectionViewer fViewer; private IAnnotationAccess fAnnotationAccess; private ISharedTextColors fSharedTextColors; - private List fSummarizableTypes; + private List<String> fSummarizableTypes; private IInformationControlCreator fInformationControlCreator; private IInformationControlCreator fInformationPresenterControlCreator; private ProjectionListener fProjectionListener; @@ -183,7 +183,7 @@ public class ProjectionSupport { */ public void addSummarizableAnnotationType(String annotationType) { if (fSummarizableTypes == null) { - fSummarizableTypes= new ArrayList(); + fSummarizableTypes= new ArrayList<>(); fSummarizableTypes.add(annotationType); } else if (!fSummarizableTypes.contains(annotationType)) fSummarizableTypes.add(annotationType); @@ -326,7 +326,7 @@ public class ProjectionSupport { if (fSummarizableTypes != null) { int size= fSummarizableTypes.size(); for (int i= 0; i < size; i++) - summary.addAnnotationType((String) fSummarizableTypes.get(i)); + summary.addAnnotationType(fSummarizableTypes.get(i)); } return summary; } @@ -347,11 +347,12 @@ public class ProjectionSupport { * @return the adapter or <code>null</code> * */ - public Object getAdapter(ISourceViewer viewer, Class required) { + @SuppressWarnings("unchecked") + public <T> T getAdapter(ISourceViewer viewer, Class<T> required) { if (ProjectionAnnotationModel.class.equals(required)) { if (viewer instanceof ProjectionViewer) { ProjectionViewer projectionViewer= (ProjectionViewer) viewer; - return projectionViewer.getProjectionAnnotationModel(); + return (T) projectionViewer.getProjectionAnnotationModel(); } } return null; diff --git a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java index 123b8bb8d28..6c8cd088658 100644 --- a/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java +++ b/org.eclipse.jface.text/projection/org/eclipse/jface/text/source/projection/ProjectionViewer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -224,7 +224,7 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi final static int REDRAW_COSTS= 15; final static int INVALIDATION_COSTS= 10; - List fList= new ArrayList(15); + List<ProjectionCommand> fList= new ArrayList<>(15); int fExpectedExecutionCosts= -1; @@ -232,7 +232,7 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi fList.add(command); } - Iterator iterator() { + Iterator<ProjectionCommand> iterator() { return fList.iterator(); } @@ -258,9 +258,9 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi fExpectedExecutionCosts= fList.size(); if (fExpectedExecutionCosts <= max_costs) { ProjectionCommand command; - Iterator e= fList.iterator(); + Iterator<ProjectionCommand> e= fList.iterator(); while (e.hasNext()) { - command= (ProjectionCommand) e.next(); + command= e.next(); fExpectedExecutionCosts += command.computeExpectedCosts(); if (fExpectedExecutionCosts > max_costs) break; @@ -280,11 +280,11 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi /** Indication whether projection changes in the visible document should be considered. */ private boolean fHandleProjectionChanges= true; /** The list of projection listeners. */ - private List fProjectionListeners; + private List<IProjectionListener> fProjectionListeners; /** Internal lock for protecting the list of pending requests */ private Object fLock= new Object(); /** The list of pending requests */ - private List fPendingRequests= new ArrayList(); + private List<AnnotationModelEvent> fPendingRequests= new ArrayList<>(); /** The replace-visible-document execution trigger */ private IDocument fReplaceVisibleDocumentExecutionTrigger; /** <code>true</code> if projection was on the last time we switched to segmented mode. */ @@ -436,7 +436,7 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi Assert.isNotNull(listener); if (fProjectionListeners == null) - fProjectionListeners= new ArrayList(); + fProjectionListeners= new ArrayList<>(); if (!fProjectionListeners.contains(listener)) fProjectionListeners.add(listener); @@ -466,9 +466,9 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi */ protected void fireProjectionEnabled() { if (fProjectionListeners != null) { - Iterator e= new ArrayList(fProjectionListeners).iterator(); + Iterator<IProjectionListener> e= new ArrayList<>(fProjectionListeners).iterator(); while (e.hasNext()) { - IProjectionListener l= (IProjectionListener) e.next(); + IProjectionListener l= e.next(); l.projectionEnabled(); } } @@ -480,9 +480,9 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi */ protected void fireProjectionDisabled() { if (fProjectionListeners != null) { - Iterator e= new ArrayList(fProjectionListeners).iterator(); + Iterator<IProjectionListener> e= new ArrayList<>(fProjectionListeners).iterator(); while (e.hasNext()) { - IProjectionListener l= (IProjectionListener) e.next(); + IProjectionListener l= e.next(); l.projectionDisabled(); } } @@ -535,7 +535,7 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi Position found= null; Annotation bestMatch= null; Point selection= getSelectedRange(); - for (Iterator e= fProjectionAnnotationModel.getAnnotationIterator(); e.hasNext();) { + for (Iterator<Annotation> e= fProjectionAnnotationModel.getAnnotationIterator(); e.hasNext();) { ProjectionAnnotation annotation= (ProjectionAnnotation) e.next(); if (annotation.isCollapsed()) { Position position= fProjectionAnnotationModel.getPosition(annotation); @@ -564,7 +564,7 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi Position found= null; Annotation bestMatch= null; Point selection= getSelectedRange(); - for (Iterator e= fProjectionAnnotationModel.getAnnotationIterator(); e.hasNext();) { + for (Iterator<Annotation> e= fProjectionAnnotationModel.getAnnotationIterator(); e.hasNext();) { ProjectionAnnotation annotation= (ProjectionAnnotation) e.next(); if (!annotation.isCollapsed()) { Position position= fProjectionAnnotationModel.getPosition(annotation); @@ -883,7 +883,7 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi synchronized (fLock) { if (fPendingRequests.size() == 0) return; - ame= (AnnotationModelEvent) fPendingRequests.remove(0); + ame= fPendingRequests.remove(0); } catchupWithProjectionAnnotationModel(ame); } @@ -959,7 +959,7 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi int topIndex= isRedrawing ? getTopIndex() : -1; processDeletions(event, removedAnnotations, true); - List coverage= new ArrayList(); + List<Position> coverage= new ArrayList<>(); processChanges(addedAnnotations, true, coverage); processChanges(changedAnnotation, true, coverage); @@ -991,9 +991,9 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi private void executeProjectionCommands(ProjectionCommandQueue commandQueue, boolean fireRedraw) throws BadLocationException { ProjectionCommand command; - Iterator e= commandQueue.iterator(); + Iterator<ProjectionCommand> e= commandQueue.iterator(); while (e.hasNext()) { - command= (ProjectionCommand) e.next(); + command= e.next(); switch (command.fType) { case ProjectionCommand.ADD: addMasterDocumentRange(command.fProjection, command.fOffset, command.fLength); @@ -1012,8 +1012,8 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi } private ProjectionAnnotation[] computeCollapsedNestedAnnotations(int offset, int length) { - List annotations= new ArrayList(5); - Iterator e= fProjectionAnnotationModel.getAnnotationIterator(offset, length, false, false); + List<ProjectionAnnotation> annotations= new ArrayList<>(5); + Iterator<Annotation> e= fProjectionAnnotationModel.getAnnotationIterator(offset, length, false, false); while (e.hasNext()) { ProjectionAnnotation annotation= (ProjectionAnnotation) e.next(); if (annotation.isCollapsed()) { @@ -1140,7 +1140,7 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi return null; } - private void processChanges(Annotation[] annotations, boolean fireRedraw, List coverage) throws BadLocationException { + private void processChanges(Annotation[] annotations, boolean fireRedraw, List<Position> coverage) throws BadLocationException { for (int i= 0; i < annotations.length; i++) { ProjectionAnnotation annotation= (ProjectionAnnotation) annotations[i]; Position position= fProjectionAnnotationModel.getPosition(annotation); @@ -1162,10 +1162,10 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi } } - private boolean covers(List coverage, Position position) { - Iterator e= coverage.iterator(); + private boolean covers(List<Position> coverage, Position position) { + Iterator<Position> e= coverage.iterator(); while (e.hasNext()) { - Position p= (Position) e.next(); + Position p= e.next(); if (p.getOffset() <= position.getOffset() && position.getOffset() + position.getLength() <= p.getOffset() + p.getLength()) return true; } @@ -1195,7 +1195,7 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi } if (projection != null) { - Iterator e= fProjectionAnnotationModel.getAnnotationIterator(); + Iterator<Annotation> e= fProjectionAnnotationModel.getAnnotationIterator(); while (e.hasNext()) { ProjectionAnnotation annotation= (ProjectionAnnotation) e.next(); if (annotation.isCollapsed()) { @@ -1260,9 +1260,9 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi public void setRangeIndication(int offset, int length, boolean moveCursor) { IRegion rangeIndication= getRangeIndication(); if (moveCursor && fProjectionAnnotationModel != null && (rangeIndication == null || offset != rangeIndication.getOffset() || length != rangeIndication.getLength())) { - List expand= new ArrayList(2); + List<ProjectionAnnotation> expand= new ArrayList<>(2); // expand the immediate affected collapsed regions - Iterator iterator= fProjectionAnnotationModel.getAnnotationIterator(); + Iterator<Annotation> iterator= fProjectionAnnotationModel.getAnnotationIterator(); while (iterator.hasNext()) { ProjectionAnnotation annotation= (ProjectionAnnotation)iterator.next(); if (annotation.isCollapsed() && willAutoExpand(fProjectionAnnotationModel.getPosition(annotation), offset, length)) @@ -1270,9 +1270,9 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi } if (!expand.isEmpty()) { - Iterator e= expand.iterator(); + Iterator<ProjectionAnnotation> e= expand.iterator(); while (e.hasNext()) - fProjectionAnnotationModel.expand((Annotation)e.next()); + fProjectionAnnotationModel.expand(e.next()); } } super.setRangeIndication(offset, length, moveCursor); @@ -1646,14 +1646,14 @@ public class ProjectionViewer extends SourceViewer implements ITextViewerExtensi * @since 3.1 */ private Position[] computeOverlappingAnnotationPositions(IRegion modelSelection) { - List positions= new ArrayList(); - for (Iterator e= fProjectionAnnotationModel.getAnnotationIterator(); e.hasNext();) { + List<Position> positions= new ArrayList<>(); + for (Iterator<Annotation> e= fProjectionAnnotationModel.getAnnotationIterator(); e.hasNext();) { ProjectionAnnotation annotation= (ProjectionAnnotation) e.next(); Position position= fProjectionAnnotationModel.getPosition(annotation); if (position != null && position.overlapsWith(modelSelection.getOffset(), modelSelection.getLength()) && modelRange2WidgetRange(position) != null) positions.add(position); } - return (Position[]) positions.toArray(new Position[positions.size()]); + return positions.toArray(new Position[positions.size()]); } @Override diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/AbstractControlContentAssistSubjectAdapter.java b/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/AbstractControlContentAssistSubjectAdapter.java index 57b16ebe092..221d971e24a 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/AbstractControlContentAssistSubjectAdapter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/AbstractControlContentAssistSubjectAdapter.java @@ -58,11 +58,11 @@ public abstract class AbstractControlContentAssistSubjectAdapter implements ICon /** * VerifyKeyListeners for the control. */ - private List fVerifyKeyListeners; + private List<VerifyKeyListener> fVerifyKeyListeners; /** * KeyListeners for the control. */ - private Set fKeyListeners; + private Set<KeyListener> fKeyListeners; /** * The Listener installed on the control which passes events to * {@link #fVerifyKeyListeners fVerifyKeyListeners} and {@link #fKeyListeners}. @@ -88,8 +88,8 @@ public abstract class AbstractControlContentAssistSubjectAdapter implements ICon * Creates a new {@link AbstractControlContentAssistSubjectAdapter}. */ public AbstractControlContentAssistSubjectAdapter() { - fVerifyKeyListeners= new ArrayList(1); - fKeyListeners= new HashSet(1); + fVerifyKeyListeners= new ArrayList<>(1); + fKeyListeners= new HashSet<>(1); } @Override @@ -192,8 +192,8 @@ public abstract class AbstractControlContentAssistSubjectAdapter implements ICon dump("before traverse", e, verifyEvent); //$NON-NLS-1$ verifyEvent.doit= true; - for (Iterator iter= fVerifyKeyListeners.iterator(); iter.hasNext(); ) { - ((VerifyKeyListener) iter.next()).verifyKey(verifyEvent); + for (Iterator<VerifyKeyListener> iter= fVerifyKeyListeners.iterator(); iter.hasNext(); ) { + iter.next().verifyKey(verifyEvent); if (! verifyEvent.doit) { e.detail= SWT.TRAVERSE_NONE; e.doit= true; @@ -208,8 +208,8 @@ public abstract class AbstractControlContentAssistSubjectAdapter implements ICon break; case SWT.KeyDown: - for (Iterator iter= fVerifyKeyListeners.iterator(); iter.hasNext(); ) { - ((VerifyKeyListener) iter.next()).verifyKey(verifyEvent); + for (Iterator<VerifyKeyListener> iter= fVerifyKeyListeners.iterator(); iter.hasNext(); ) { + iter.next().verifyKey(verifyEvent); if (! verifyEvent.doit) { e.doit= verifyEvent.doit; if (DEBUG) @@ -221,8 +221,8 @@ public abstract class AbstractControlContentAssistSubjectAdapter implements ICon if (DEBUG) dump("keyDown OK", e, verifyEvent); //$NON-NLS-1$ - for (Iterator iter= fKeyListeners.iterator(); iter.hasNext();) { - ((KeyListener) iter.next()).keyPressed(keyEvent); + for (Iterator<KeyListener> iter= fKeyListeners.iterator(); iter.hasNext();) { + iter.next().keyPressed(keyEvent); } break; diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/ComboContentAssistSubjectAdapter.java b/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/ComboContentAssistSubjectAdapter.java index c4b719507cd..93d98c27c00 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/ComboContentAssistSubjectAdapter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/ComboContentAssistSubjectAdapter.java @@ -85,7 +85,7 @@ public class ComboContentAssistSubjectAdapter extends AbstractControlContentAssi * The combo widget. */ private Combo fCombo; - private HashMap fModifyListeners; + private HashMap<SelectionListener, Listener> fModifyListeners; /** * Creates a content assist subject control adapter for the given combo. @@ -95,7 +95,7 @@ public class ComboContentAssistSubjectAdapter extends AbstractControlContentAssi public ComboContentAssistSubjectAdapter(Combo combo) { Assert.isNotNull(combo); fCombo= combo; - fModifyListeners= new HashMap(); + fModifyListeners= new HashMap<>(); } @Override diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/TextContentAssistSubjectAdapter.java b/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/TextContentAssistSubjectAdapter.java index 8dd2244aaee..b47cccde215 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/TextContentAssistSubjectAdapter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/contentassist/TextContentAssistSubjectAdapter.java @@ -74,7 +74,7 @@ public class TextContentAssistSubjectAdapter extends AbstractControlContentAssis /** The text. */ private Text fText; /** The modify listeners. */ - private HashMap fModifyListeners= new HashMap(); + private HashMap<SelectionListener, Listener> fModifyListeners= new HashMap<>(); /** * Creates a content assist subject control adapter for the given text widget. diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java index 67f9b3d74cb..bfc04873562 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/BrowserInformationControl.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -437,9 +437,9 @@ public class BrowserInformationControl extends AbstractInformationControl implem fTextLayout.setText(text); fTextLayout.setWidth(sizeConstraints == null ? SWT.DEFAULT : sizeConstraints.x - trim.width); - Iterator iter= presentation.getAllStyleRangeIterator(); + Iterator<StyleRange> iter= presentation.getAllStyleRangeIterator(); while (iter.hasNext()) { - StyleRange sr= (StyleRange)iter.next(); + StyleRange sr= iter.next(); if (sr.fontStyle == SWT.BOLD) fTextLayout.setStyle(fBoldStyle, sr.start, sr.start + sr.length - 1); } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTML2TextReader.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTML2TextReader.java index 290a684de35..9aef7af8999 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTML2TextReader.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTML2TextReader.java @@ -33,12 +33,12 @@ import org.eclipse.jface.text.TextPresentation; public class HTML2TextReader extends SubstitutionTextReader { private static final String EMPTY_STRING= ""; //$NON-NLS-1$ - private static final Map fgEntityLookup; - private static final Set fgTags; + private static final Map<String, String> fgEntityLookup; + private static final Set<String> fgTags; static { - fgTags= new HashSet(); + fgTags= new HashSet<>(); fgTags.add("b"); //$NON-NLS-1$ fgTags.add("br"); //$NON-NLS-1$ fgTags.add("br/"); //$NON-NLS-1$ @@ -58,7 +58,7 @@ public class HTML2TextReader extends SubstitutionTextReader { fgTags.add("pre"); //$NON-NLS-1$ fgTags.add("head"); //$NON-NLS-1$ - fgEntityLookup= new HashMap(7); + fgEntityLookup= new HashMap<>(7); fgEntityLookup.put("lt", "<"); //$NON-NLS-1$ //$NON-NLS-2$ fgEntityLookup.put("gt", ">"); //$NON-NLS-1$ //$NON-NLS-2$ fgEntityLookup.put("nbsp", " "); //$NON-NLS-1$ //$NON-NLS-2$ @@ -351,7 +351,7 @@ public class HTML2TextReader extends SubstitutionTextReader { } catch (NumberFormatException e) { } } else { - String str= (String) fgEntityLookup.get(symbol); + String str= fgEntityLookup.get(symbol); if (str != null) { return str; } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTMLTextPresenter.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTMLTextPresenter.java index 341452782dd..b88aa2762ab 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTMLTextPresenter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/html/HTMLTextPresenter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -57,10 +57,10 @@ public class HTMLTextPresenter implements DefaultInformationControl.IInformation int yoursEnd= offset + insertLength -1; yoursEnd= Math.max(yoursStart, yoursEnd); - Iterator e= presentation.getAllStyleRangeIterator(); + Iterator<StyleRange> e= presentation.getAllStyleRangeIterator(); while (e.hasNext()) { - StyleRange range= (StyleRange) e.next(); + StyleRange range= e.next(); int myStart= range.start; int myEnd= range.start + range.length -1; diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/CompletionProposalPopup2.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/CompletionProposalPopup2.java index 188df4e69ac..4d6a932b403 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/CompletionProposalPopup2.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/CompletionProposalPopup2.java @@ -85,7 +85,7 @@ class CompletionProposalPopup2 implements IContentAssistListener2 { /** The key listener to control navigation */ private KeyListener fKeyListener; /** List of document events used for filtering proposals */ - private List fDocumentEvents= new ArrayList(); + private List<DocumentEvent> fDocumentEvents= new ArrayList<>(); /** Listener filling the document event queue */ private IDocumentListener fDocumentListener; /** Reentrance count for <code>filterProposals</code> */ @@ -936,7 +936,7 @@ class CompletionProposalPopup2 implements IContentAssistListener2 { IDocument document= fViewer.getDocument(); int length= proposals.length; - List filtered= new ArrayList(length); + List<Object> filtered= new ArrayList<>(length); for (int i= 0; i < length; i++) { if (proposals[i] instanceof ICompletionProposalExtension2) { diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContentAssistant2.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContentAssistant2.java index f8993b471ea..26ea2ecc0f3 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContentAssistant2.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContentAssistant2.java @@ -667,7 +667,7 @@ public class ContentAssistant2 implements IContentAssistant, IContentAssistantEx private boolean fIsAutoInserting= false; private int fProposalPopupOrientation= PROPOSAL_OVERLAY; private int fContextInfoPopupOrientation= CONTEXT_INFO_ABOVE; - private Map fProcessors; + private Map<String, IContentAssistProcessor> fProcessors; private String fPartitioning; private Color fContextInfoPopupBackground; @@ -690,7 +690,7 @@ public class ContentAssistant2 implements IContentAssistant, IContentAssistantEx private int fCompletionPosition; private String[] fProposalStrings; private ICompletionProposal[] fProposals; - private final List fProposalListeners= new ArrayList(); + private final List<IProposalListener> fProposalListeners= new ArrayList<>(); /** * Tells whether colored label support is enabled. @@ -764,7 +764,7 @@ public class ContentAssistant2 implements IContentAssistant, IContentAssistantEx Assert.isNotNull(contentType); if (fProcessors == null) - fProcessors= new HashMap(); + fProcessors= new HashMap<>(); if (processor == null) fProcessors.remove(contentType); @@ -780,7 +780,7 @@ public class ContentAssistant2 implements IContentAssistant, IContentAssistantEx if (fProcessors == null) return null; - return (IContentAssistProcessor) fProcessors.get(contentType); + return fProcessors.get(contentType); } /** @@ -1522,9 +1522,9 @@ public class ContentAssistant2 implements IContentAssistant, IContentAssistantEx * @param proposal the proposal */ public void fireProposalChosen(ICompletionProposal proposal) { - List list= new ArrayList(fProposalListeners); - for (Iterator it= list.iterator(); it.hasNext();) { - IProposalListener listener= (IProposalListener) it.next(); + List<IProposalListener> list= new ArrayList<>(fProposalListeners); + for (Iterator<IProposalListener> it= list.iterator(); it.hasNext();) { + IProposalListener listener= it.next(); listener.proposalChosen(proposal); } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContextInformationPopup2.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContextInformationPopup2.java index 766c134b338..ce022e648c0 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContextInformationPopup2.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/link/contentassist/ContextInformationPopup2.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -84,7 +84,7 @@ class ContextInformationPopup2 implements IContentAssistListener2 { private StyledText fContextInfoText; private TextPresentation fTextPresentation; - private Stack fContextFrameStack= new Stack(); + private Stack<ContextFrame> fContextFrameStack= new Stack<>(); /** @@ -291,7 +291,7 @@ class ContextInformationPopup2 implements IContentAssistListener2 { } if (size > 0) { - ContextFrame current= (ContextFrame) fContextFrameStack.peek(); + ContextFrame current= fContextFrameStack.peek(); internalShowContextFrame(current, false); } else { @@ -619,7 +619,7 @@ class ContextInformationPopup2 implements IContentAssistListener2 { */ fContextInfoPopup.getDisplay().asyncExec(new Runnable() { - private ContextFrame fFrame= (ContextFrame) fContextFrameStack.peek(); + private ContextFrame fFrame= fContextFrameStack.peek(); @Override public void run() { diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/ChangeRegion.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/ChangeRegion.java index ac3aeef7648..84f4a8d6dd5 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/ChangeRegion.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/ChangeRegion.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -30,7 +30,7 @@ import org.eclipse.jface.text.source.LineRange; public final class ChangeRegion { private final Revision fRevision; private final ILineRange fLines; - private final List fAdjusted= new LinkedList(); + private final List<Range> fAdjusted= new LinkedList<>(); /** * Creates a new change region for the given revision and line range. @@ -66,12 +66,12 @@ public final class ChangeRegion { } /** - * Returns the list of {@link ILineRange}s of this change region for which the revision + * Returns the list of {@link Range}s of this change region for which the revision * information is still valid. * * @return the list of adjusted line ranges */ - public List getAdjustedRanges() { + public List<Range> getAdjustedRanges() { return fAdjusted; } @@ -84,8 +84,8 @@ public final class ChangeRegion { if (fAdjusted.isEmpty()) return new LineRange(fLines.getStartLine(), 0); - Range first= (Range) fAdjusted.get(0); - Range last= (Range) fAdjusted.get(fAdjusted.size() - 1); + Range first= fAdjusted.get(0); + Range last= fAdjusted.get(fAdjusted.size() - 1); return Range.createAbsolute(first.start(), last.end()); } @@ -104,8 +104,8 @@ public final class ChangeRegion { * @param hunk the diff hunk to adjust to */ public void adjustTo(Hunk hunk) { - for (ListIterator it= fAdjusted.listIterator(); it.hasNext();) { - Range range= (Range) it.next(); + for (ListIterator<Range> it= fAdjusted.listIterator(); it.hasNext();) { + Range range= it.next(); // do we need a split? int unchanged= getUnchanged(hunk, range.start()); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/HunkComputer.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/HunkComputer.java index 3e527e5790d..2e2d49026c4 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/HunkComputer.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/HunkComputer.java @@ -32,7 +32,7 @@ public final class HunkComputer { * @return the corresponding {@link Hunk} information */ public static Hunk[] computeHunks(ILineDiffer differ, int lines) { - List hunks= new ArrayList(lines); + List<Hunk> hunks= new ArrayList<>(lines); int added= 0; int changed= 0; @@ -70,7 +70,7 @@ public final class HunkComputer { } } - return (Hunk[]) hunks.toArray(new Hunk[hunks.size()]); + return hunks.toArray(new Hunk[hunks.size()]); } private HunkComputer() { } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/RevisionPainter.java b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/RevisionPainter.java index 2fbbb36dea9..91d5e026d2c 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/RevisionPainter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/internal/text/revisions/RevisionPainter.java @@ -138,15 +138,15 @@ public final class RevisionPainter { /** * A list of {@link Long}, storing the age of each revision in a sorted list. */ - private List fRevisions; + private List<Long> fRevisions; /** * The stored shaded colors. */ - private final Map fColors= new HashMap(); + private final Map<Revision, RGB> fColors= new HashMap<>(); /** * The stored focus colors. */ - private final Map fFocusColors= new HashMap(); + private final Map<Revision, RGB> fFocusColors= new HashMap<>(); /** * Sets the revision information, which is needed to compute the relative age of a revision. @@ -160,9 +160,9 @@ public final class RevisionPainter { if (info == null) return; - List revisions= new ArrayList(); - for (Iterator it= info.getRevisions().iterator(); it.hasNext();) { - Revision revision= (Revision) it.next(); + List<Long> revisions= new ArrayList<>(); + for (Iterator<Revision> it= info.getRevisions().iterator(); it.hasNext();) { + Revision revision= it.next(); revisions.add(new Long(computeAge(revision))); } Collections.sort(revisions); @@ -248,8 +248,8 @@ public final class RevisionPainter { * @return the color for a revision */ public RGB getColor(Revision revision, boolean focus) { - Map map= focus ? fFocusColors : fColors; - RGB color= (RGB) map.get(revision); + Map<Revision, RGB> map= focus ? fFocusColors : fColors; + RGB color= map.get(revision); if (color != null) return color; @@ -533,9 +533,9 @@ public final class RevisionPainter { /* Cache. */ /** The cached list of ranges adapted to quick diff. */ - private List fRevisionRanges= null; + private List<RevisionRange> fRevisionRanges= null; /** The annotations created for the overview ruler temporary display. */ - private List fAnnotations= new ArrayList(); + private List<Annotation> fAnnotations= new ArrayList<>(); /* State */ @@ -693,9 +693,9 @@ public final class RevisionPainter { } // draw change regions - List/* <RevisionRange> */ranges= getRanges(visibleLines); - for (Iterator it= ranges.iterator(); it.hasNext();) { - RevisionRange region= (RevisionRange) it.next(); + List<RevisionRange> ranges= getRanges(visibleLines); + for (Iterator<RevisionRange> it= ranges.iterator(); it.hasNext();) { + RevisionRange region= it.next(); paintRange(region, gc); } } @@ -902,19 +902,19 @@ public final class RevisionPainter { * @return the corresponding <code>RevisionRange</code> or <code>null</code> */ private RevisionRange getRange(int line) { - List ranges= getRangeCache(); + List<RevisionRange> ranges= getRangeCache(); if (ranges.isEmpty() || line == -1) return null; - for (Iterator it= ranges.iterator(); it.hasNext();) { - RevisionRange range= (RevisionRange) it.next(); + for (Iterator<RevisionRange> it= ranges.iterator(); it.hasNext();) { + RevisionRange range= it.next(); if (contains(range, line)) return range; } // line may be right after the last region - RevisionRange lastRegion= (RevisionRange) ranges.get(ranges.size() - 1); + RevisionRange lastRegion= ranges.get(ranges.size() - 1); if (line == end(lastRegion)) return lastRegion; return null; @@ -926,14 +926,14 @@ public final class RevisionPainter { * @param lines the model based lines of interest * @return elementType: RevisionRange */ - private List getRanges(ILineRange lines) { - List ranges= getRangeCache(); + private List<RevisionRange> getRanges(ILineRange lines) { + List<RevisionRange> ranges= getRangeCache(); // return the interesting subset int end= end(lines); int first= -1, last= -1; for (int i= 0; i < ranges.size(); i++) { - RevisionRange range= (RevisionRange) ranges.get(i); + RevisionRange range= ranges.get(i); int rangeEnd= end(range); if (first == -1 && rangeEnd > lines.getStartLine()) first= i; @@ -943,7 +943,7 @@ public final class RevisionPainter { } } if (first == -1) - return Collections.EMPTY_LIST; + return Collections.emptyList(); if (last == -1) last= ranges.size() - 1; // bottom index may be one too much @@ -956,10 +956,10 @@ public final class RevisionPainter { * * @return the list of all change regions, with diff information applied */ - private synchronized List getRangeCache() { + private synchronized List<RevisionRange> getRangeCache() { if (fRevisionRanges == null) { if (fRevisionInfo == null) { - fRevisionRanges= Collections.EMPTY_LIST; + fRevisionRanges= Collections.emptyList(); } else { Hunk[] hunks= HunkComputer.computeHunks(fLineDiffer, fViewer.getDocument().getNumberOfLines()); fRevisionInfo.applyDiff(hunks); @@ -1075,11 +1075,11 @@ public final class RevisionPainter { Revision revision= fFocusRevision != null ? fFocusRevision : fSelectedRevision; - Map added= null; + Map<Annotation, Position> added= null; if (revision != null) { - added= new HashMap(); - for (Iterator it= revision.getRegions().iterator(); it.hasNext();) { - RevisionRange range= (RevisionRange) it.next(); + added= new HashMap<>(); + for (Iterator<RevisionRange> it= revision.getRegions().iterator(); it.hasNext();) { + RevisionRange range= it.next(); try { IRegion charRegion= toCharRegion(range); Position position= new Position(charRegion.getOffset(), charRegion.getLength()); @@ -1093,16 +1093,16 @@ public final class RevisionPainter { if (fAnnotationModel instanceof IAnnotationModelExtension) { IAnnotationModelExtension ext= (IAnnotationModelExtension) fAnnotationModel; - ext.replaceAnnotations((Annotation[]) fAnnotations.toArray(new Annotation[fAnnotations.size()]), added); + ext.replaceAnnotations(fAnnotations.toArray(new Annotation[fAnnotations.size()]), added); } else { - for (Iterator it= fAnnotations.iterator(); it.hasNext();) { - Annotation annotation= (Annotation) it.next(); + for (Iterator<Annotation> it= fAnnotations.iterator(); it.hasNext();) { + Annotation annotation= it.next(); fAnnotationModel.removeAnnotation(annotation); } if (added != null) { - for (Iterator it= added.entrySet().iterator(); it.hasNext();) { - Entry entry= (Entry) it.next(); - fAnnotationModel.addAnnotation((Annotation) entry.getKey(), (Position) entry.getValue()); + for (Iterator<Entry<Annotation, Position>> it= added.entrySet().iterator(); it.hasNext();) { + Entry<Annotation, Position> entry= it.next(); + fAnnotationModel.addAnnotation(entry.getKey(), entry.getValue()); } } } @@ -1156,8 +1156,8 @@ public final class RevisionPainter { if (fRevisionInfo == null) return; - for (Iterator it= fRevisionInfo.getRevisions().iterator(); it.hasNext();) { - Revision revision= (Revision) it.next(); + for (Iterator<Revision> it= fRevisionInfo.getRevisions().iterator(); it.hasNext();) { + Revision revision= it.next(); if (id.equals(revision.getId())) { handleRevisionSelected(revision); return; @@ -1287,10 +1287,10 @@ public final class RevisionPainter { ILineRange nextWidgetRange= null; ILineRange last= null; - List ranges= fFocusRevision.getRegions(); + List<RevisionRange> ranges= fFocusRevision.getRegions(); if (up) { - for (Iterator it= ranges.iterator(); it.hasNext();) { - RevisionRange range= (RevisionRange) it.next(); + for (Iterator<RevisionRange> it= ranges.iterator(); it.hasNext();) { + RevisionRange range= it.next(); ILineRange widgetRange= modelLinesToWidgetLines(range); if (contains(range, documentHoverLine)) { nextWidgetRange= last; @@ -1300,8 +1300,8 @@ public final class RevisionPainter { last= widgetRange; } } else { - for (ListIterator it= ranges.listIterator(ranges.size()); it.hasPrevious();) { - RevisionRange range= (RevisionRange) it.previous(); + for (ListIterator<RevisionRange> it= ranges.listIterator(ranges.size()); it.hasPrevious();) { + RevisionRange range= it.previous(); ILineRange widgetRange= modelLinesToWidgetLines(range); if (contains(range, documentHoverLine)) { nextWidgetRange= last; @@ -1459,8 +1459,8 @@ public final class RevisionPainter { if (hasInformation() && (fShowRevision || fShowAuthor)) { int revisionWidth= 0; int authorWidth= 0; - for (Iterator it= fRevisionInfo.getRevisions().iterator(); it.hasNext();) { - Revision revision= (Revision) it.next(); + for (Iterator<Revision> it= fRevisionInfo.getRevisions().iterator(); it.hasNext();) { + Revision revision= it.next(); revisionWidth= Math.max(revisionWidth, revision.getId().length()); authorWidth= Math.max(authorWidth, revision.getAuthor().length()); } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractReusableInformationControlCreator.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractReusableInformationControlCreator.java index 94fc583607b..a28f14bfe59 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractReusableInformationControlCreator.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/AbstractReusableInformationControlCreator.java @@ -26,7 +26,7 @@ import org.eclipse.swt.widgets.Shell; */ public abstract class AbstractReusableInformationControlCreator implements IInformationControlCreator, IInformationControlCreatorExtension, DisposeListener { - private Map fInformationControls= new HashMap(); + private Map<Shell, IInformationControl> fInformationControls= new HashMap<>(); /** * Creates the control. @@ -38,7 +38,7 @@ public abstract class AbstractReusableInformationControlCreator implements IInfo @Override public IInformationControl createInformationControl(Shell parent) { - IInformationControl control= (IInformationControl)fInformationControls.get(parent); + IInformationControl control= fInformationControls.get(parent); if (control == null) { control= doCreateInformationControl(parent); control.addDisposeListener(this); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultDocumentAdapter.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultDocumentAdapter.java index 9c4704e7517..28cb78a473f 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultDocumentAdapter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultDocumentAdapter.java @@ -40,7 +40,7 @@ class DefaultDocumentAdapter implements IDocumentAdapter, IDocumentListener, IDo /** The original line delimiters */ private String[] fOriginalLineDelimiters; /** The registered text change listeners */ - private List fTextChangeListeners= new ArrayList(1); + private List<TextChangeListener> fTextChangeListeners= new ArrayList<>(1); /** * The remembered document event * @since 2.0 @@ -317,9 +317,9 @@ class DefaultDocumentAdapter implements IDocumentAdapter, IDocumentListener, IDo TextChangedEvent event= new TextChangedEvent(this); if (fTextChangeListeners != null && fTextChangeListeners.size() > 0) { - Iterator e= new ArrayList(fTextChangeListeners).iterator(); + Iterator<TextChangeListener> e= new ArrayList<>(fTextChangeListeners).iterator(); while (e.hasNext()) - ((TextChangeListener) e.next()).textChanged(event); + e.next().textChanged(event); } } @@ -334,9 +334,9 @@ class DefaultDocumentAdapter implements IDocumentAdapter, IDocumentListener, IDo TextChangedEvent event = new TextChangedEvent(this); if (fTextChangeListeners != null && fTextChangeListeners.size() > 0) { - Iterator e= new ArrayList(fTextChangeListeners).iterator(); + Iterator<TextChangeListener> e= new ArrayList<>(fTextChangeListeners).iterator(); while (e.hasNext()) - ((TextChangeListener) e.next()).textSet(event); + e.next().textSet(event); } } @@ -362,9 +362,9 @@ class DefaultDocumentAdapter implements IDocumentAdapter, IDocumentListener, IDo event.newLineCount= (fEvent.fText == null ? 0 : document.computeNumberOfLines(fEvent.fText)); if (fTextChangeListeners != null && fTextChangeListeners.size() > 0) { - Iterator e= new ArrayList(fTextChangeListeners).iterator(); + Iterator<TextChangeListener> e= new ArrayList<>(fTextChangeListeners).iterator(); while (e.hasNext()) - ((TextChangeListener) e.next()).textChanging(event); + e.next().textChanging(event); } } catch (BadLocationException e) { diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextHover.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextHover.java index d7551522243..ab30e23d784 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextHover.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultTextHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -51,9 +51,9 @@ public class DefaultTextHover implements ITextHover { if (model == null) return null; - Iterator e= model.getAnnotationIterator(); + Iterator<Annotation> e= model.getAnnotationIterator(); while (e.hasNext()) { - Annotation a= (Annotation) e.next(); + Annotation a= e.next(); if (isIncluded(a)) { Position p= model.getPosition(a); if (p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) { diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultUndoManager.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultUndoManager.java index ae95f9bb426..fb9b366a6f8 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultUndoManager.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/DefaultUndoManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -424,7 +424,7 @@ public class DefaultUndoManager implements IUndoManager, IUndoManagerExtension { class CompoundTextCommand extends TextCommand { /** The list of individual commands */ - private List fCommands= new ArrayList(); + private List<TextCommand> fCommands= new ArrayList<>(); /** * Creates a new compound text command. @@ -455,11 +455,11 @@ public class DefaultUndoManager implements IUndoManager, IUndoManagerExtension { TextCommand c; for (int i= size -1; i > 0; --i) { - c= (TextCommand) fCommands.get(i); + c= fCommands.get(i); c.undoTextChange(); } - c= (TextCommand) fCommands.get(0); + c= fCommands.get(0); c.undo(monitor, uiInfo); } @@ -476,11 +476,11 @@ public class DefaultUndoManager implements IUndoManager, IUndoManagerExtension { TextCommand c; for (int i= 0; i < size -1; ++i) { - c= (TextCommand) fCommands.get(i); + c= fCommands.get(i); c.redoTextChange(); } - c= (TextCommand) fCommands.get(size -1); + c= fCommands.get(size -1); c.redo(monitor, uiInfo); } return Status.OK_STATUS; @@ -556,7 +556,7 @@ public class DefaultUndoManager implements IUndoManager, IUndoManagerExtension { if (fStart > -1) return super.getUndoModificationStamp(); else if (fCommands.size() > 0) - return ((TextCommand)fCommands.get(0)).getUndoModificationStamp(); + return fCommands.get(0).getUndoModificationStamp(); return fUndoModificationStamp; } @@ -572,7 +572,7 @@ public class DefaultUndoManager implements IUndoManager, IUndoManagerExtension { if (fStart > -1) return super.getRedoModificationStamp(); else if (fCommands.size() > 0) - return ((TextCommand)fCommands.get(fCommands.size()-1)).getRedoModificationStamp(); + return fCommands.get(fCommands.size()-1).getRedoModificationStamp(); return fRedoModificationStamp; } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentCommand.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentCommand.java index 554032cfefe..cc3731f6051 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentCommand.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/DocumentCommand.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -37,7 +37,7 @@ public class DocumentCommand { * A command which is added to document commands. * @since 2.1 */ - private static class Command implements Comparable { + private static class Command implements Comparable<Command> { /** The offset of the range to be replaced */ private final int fOffset; /** The length of the range to be replaced. */ @@ -85,15 +85,12 @@ public class DocumentCommand { document.addDocumentListener(fOwner); } - /* - * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) - */ @Override - public int compareTo(final Object object) { + public int compareTo(Command object) { if (isEqual(object)) return 0; - final Command command= (Command) object; + Command command= object; // diff middle points if not intersecting if (fOffset + fLength <= command.fOffset || command.fOffset + command.fLength <= fOffset) { @@ -117,17 +114,19 @@ public class DocumentCommand { /** * An iterator, which iterates in reverse over a list. + * + * @param <E> the type of elements returned by this iterator */ - private static class ReverseListIterator implements Iterator { + private static class ReverseListIterator<E> implements Iterator<E> { /** The list iterator. */ - private final ListIterator fListIterator; + private final ListIterator<E> fListIterator; /** * Creates a reverse list iterator. * @param listIterator the iterator that this reverse iterator is based upon */ - public ReverseListIterator(ListIterator listIterator) { + public ReverseListIterator(ListIterator<E> listIterator) { if (listIterator == null) throw new IllegalArgumentException(); fListIterator= listIterator; @@ -139,7 +138,7 @@ public class DocumentCommand { } @Override - public Object next() { + public E next() { return fListIterator.previous(); } @@ -152,10 +151,10 @@ public class DocumentCommand { /** * A command iterator. */ - private static class CommandIterator implements Iterator { + private static class CommandIterator implements Iterator<Command> { /** The command iterator. */ - private final Iterator fIterator; + private final Iterator<Command> fIterator; /** The original command. */ private Command fCommand; @@ -170,10 +169,10 @@ public class DocumentCommand { * @param command the original command * @param forward the direction */ - public CommandIterator(final List commands, final Command command, final boolean forward) { + public CommandIterator(final List<Command> commands, final Command command, final boolean forward) { if (commands == null || command == null) throw new IllegalArgumentException(); - fIterator= forward ? commands.iterator() : new ReverseListIterator(commands.listIterator(commands.size())); + fIterator= forward ? commands.iterator() : new ReverseListIterator<>(commands.listIterator(commands.size())); fCommand= command; fForward= forward; } @@ -184,7 +183,7 @@ public class DocumentCommand { } @Override - public Object next() { + public Command next() { if (!hasNext()) throw new NoSuchElementException(); @@ -198,7 +197,7 @@ public class DocumentCommand { return tempCommand; } - final Command command= (Command) fIterator.next(); + final Command command= fIterator.next(); final int compareValue= command.compareTo(fCommand); if ((compareValue < 0) ^ !fForward) { @@ -242,7 +241,7 @@ public class DocumentCommand { * Additional document commands. * @since 2.1 */ - private final List fCommands= new ArrayList(); + private final List<Command> fCommands= new ArrayList<>(); /** * Indicates whether the caret should be shifted by this command. * @since 3.0 @@ -319,11 +318,11 @@ public class DocumentCommand { final int insertionIndex= -(index + 1); // overlaps to the right? - if (insertionIndex != fCommands.size() && intersects((Command) fCommands.get(insertionIndex), command)) + if (insertionIndex != fCommands.size() && intersects(fCommands.get(insertionIndex), command)) throw new BadLocationException(); // overlaps to the left? - if (insertionIndex != 0 && intersects((Command) fCommands.get(insertionIndex - 1), command)) + if (insertionIndex != 0 && intersects(fCommands.get(insertionIndex - 1), command)) throw new BadLocationException(); fCommands.add(insertionIndex, command); @@ -336,7 +335,7 @@ public class DocumentCommand { * * @return returns the command iterator */ - public Iterator getCommandIterator() { + public Iterator<Command> getCommandIterator() { Command command= new Command(offset, length, text, owner); return new CommandIterator(fCommands, command, true); } @@ -403,8 +402,8 @@ public class DocumentCommand { } final Command originalCommand= new Command(offset, length, text, owner); - for (final Iterator iterator= new CommandIterator(fCommands, originalCommand, false); iterator.hasNext(); ) - ((Command) iterator.next()).execute(document); + for (final Iterator<Command> iterator= new CommandIterator(fCommands, originalCommand, false); iterator.hasNext(); ) + iterator.next().execute(document); } catch (BadLocationException e) { // ignore diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java index 37089e74f54..4d9a270f3d0 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/FindReplaceDocumentAdapterContentProposalProvider.java @@ -51,11 +51,11 @@ public class FindReplaceDocumentAdapterContentProposalProvider implements IConte /** * The high-priority proposals. */ - private final ArrayList fPriorityProposals; + private final ArrayList<ContentProposal> fPriorityProposals; /** * The low-priority proposals. */ - private final ArrayList fProposals; + private final ArrayList<ContentProposal> fProposals; /** * <code>true</code> iff <code>fExpression</code> ends with an open escape. */ @@ -69,8 +69,8 @@ public class FindReplaceDocumentAdapterContentProposalProvider implements IConte public ProposalComputer(String contents, int position) { fExpression= contents; fDocumentOffset= position; - fPriorityProposals= new ArrayList(); - fProposals= new ArrayList(); + fPriorityProposals= new ArrayList<>(); + fProposals= new ArrayList<>(); boolean isEscape= false; esc: for (int i= position - 1; i >= 0; i--) { @@ -196,7 +196,7 @@ public class FindReplaceDocumentAdapterContentProposalProvider implements IConte } fPriorityProposals.addAll(fProposals); - return (IContentProposal[]) fPriorityProposals.toArray(new IContentProposal[fProposals.size()]); + return fPriorityProposals.toArray(new IContentProposal[fProposals.size()]); } /** @@ -224,7 +224,7 @@ public class FindReplaceDocumentAdapterContentProposalProvider implements IConte addBsProposal("\\C", RegExMessages.getString("displayString_replace_bs_C"), RegExMessages.getString("additionalInfo_replace_bs_C")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } fPriorityProposals.addAll(fProposals); - return (IContentProposal[]) fPriorityProposals.toArray(new IContentProposal[fPriorityProposals.size()]); + return fPriorityProposals.toArray(new IContentProposal[fPriorityProposals.size()]); } /** diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/PaintManager.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/PaintManager.java index 0220b5f2984..551bc5b845f 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/PaintManager.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/PaintManager.java @@ -172,7 +172,7 @@ public final class PaintManager implements KeyListener, MouseListener, ISelectio /** The painters managed by this paint manager. */ - private List fPainters= new ArrayList(2); + private List<IPainter> fPainters= new ArrayList<>(2); /** The position manager used by this paint manager */ private PositionManager fManager; /** The associated text viewer */ @@ -264,8 +264,8 @@ public final class PaintManager implements KeyListener, MouseListener, ISelectio fManager= null; } - for (Iterator e = fPainters.iterator(); e.hasNext();) - ((IPainter) e.next()).dispose(); + for (Iterator<IPainter> e = fPainters.iterator(); e.hasNext();) + e.next().dispose(); fPainters.clear(); fTextViewer.removeTextInputListener(this); @@ -298,8 +298,8 @@ public final class PaintManager implements KeyListener, MouseListener, ISelectio * @see IPainter */ private void paint(int reason) { - for (Iterator e = fPainters.iterator(); e.hasNext();) - ((IPainter) e.next()).paint(reason); + for (Iterator<IPainter> e = fPainters.iterator(); e.hasNext();) + e.next().paint(reason); } @Override @@ -350,8 +350,8 @@ public final class PaintManager implements KeyListener, MouseListener, ISelectio @Override public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (oldInput != null) { - for (Iterator e= fPainters.iterator(); e.hasNext();) - ((IPainter)e.next()).deactivate(false); + for (Iterator<IPainter> e= fPainters.iterator(); e.hasNext();) + e.next().deactivate(false); fManager.uninstall(oldInput); removeListeners(); } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/TextPresentation.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/TextPresentation.java index 6730ae24f52..d38b0790102 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/TextPresentation.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/TextPresentation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -48,9 +48,9 @@ public class TextPresentation { StyleRange[] ranges= new StyleRange[presentation.getDenumerableRanges()]; int i= 0; - Iterator e= presentation.getAllStyleRangeIterator(); + Iterator<StyleRange> e= presentation.getAllStyleRangeIterator(); while (e.hasNext()) - ranges[i++]= (StyleRange) e.next(); + ranges[i++]= e.next(); text.setStyleRanges(ranges); } @@ -61,7 +61,7 @@ public class TextPresentation { /** * Enumerates all the <code>StyleRange</code>s included in the presentation. */ - class FilterIterator implements Iterator { + class FilterIterator implements Iterator<StyleRange> { /** The index of the next style range to be enumerated */ protected int fIndex; @@ -91,9 +91,9 @@ public class TextPresentation { } @Override - public Object next() { + public StyleRange next() { try { - StyleRange r= (StyleRange) fRanges.get(fIndex++); + StyleRange r= fRanges.get(fIndex++); return createWindowRelativeRange(fWindow, r); } catch (ArrayIndexOutOfBoundsException x) { throw new NoSuchElementException(); @@ -136,7 +136,7 @@ public class TextPresentation { /** The style information for the range covered by the whole presentation */ private StyleRange fDefaultRange; /** The member ranges of the presentation */ - private ArrayList fRanges; + private ArrayList<StyleRange> fRanges; /** A clipping region against which the presentation can be clipped when asked for results */ private IRegion fResultWindow; /** @@ -150,7 +150,7 @@ public class TextPresentation { * Creates a new empty text presentation. */ public TextPresentation() { - fRanges= new ArrayList(50); + fRanges= new ArrayList<>(50); } /** @@ -161,7 +161,7 @@ public class TextPresentation { */ public TextPresentation(int sizeHint) { Assert.isTrue(sizeHint > 0); - fRanges= new ArrayList(sizeHint); + fRanges= new ArrayList<>(sizeHint); } /** @@ -294,7 +294,7 @@ public class TextPresentation { int last= getFirstIndexAfterWindow(rangeRegion); for (int i= first; i < last && length > 0; i++) { - StyleRange current= (StyleRange)fRanges.get(i); + StyleRange current= fRanges.get(i); int currentStart= current.start; int currentEnd= currentStart + current.length; @@ -405,8 +405,8 @@ public class TextPresentation { */ private void applyStyleRanges(StyleRange[] ranges, boolean merge) { int j= 0; - ArrayList oldRanges= fRanges; - ArrayList newRanges= new ArrayList(2*ranges.length + oldRanges.size()); + ArrayList<StyleRange> oldRanges= fRanges; + ArrayList<StyleRange> newRanges= new ArrayList<>(2*ranges.length + oldRanges.size()); for (int i= 0, n= ranges.length; i < n; i++) { StyleRange range= ranges[i]; fRanges= oldRanges; // for getFirstIndexAfterWindow(...) @@ -511,7 +511,7 @@ public class TextPresentation { int i= -1, j= fRanges.size(); while (j - i > 1) { int k= (i + j) >> 1; - StyleRange r= (StyleRange) fRanges.get(k); + StyleRange r= fRanges.get(k); if (r.start + r.length > start) j= k; else @@ -535,7 +535,7 @@ public class TextPresentation { int i= -1, j= fRanges.size(); while (j - i > 1) { int k= (i + j) >> 1; - StyleRange r= (StyleRange) fRanges.get(k); + StyleRange r= fRanges.get(k); if (r.start < end) i= k; else @@ -605,7 +605,7 @@ public class TextPresentation { * * @return a style range iterator */ - public Iterator getNonDefaultStyleRangeIterator() { + public Iterator<StyleRange> getNonDefaultStyleRangeIterator() { return new FilterIterator(fDefaultRange != null); } @@ -616,7 +616,7 @@ public class TextPresentation { * * @return a style range iterator */ - public Iterator getAllStyleRangeIterator() { + public Iterator<StyleRange> getAllStyleRangeIterator() { return new FilterIterator(false); } @@ -650,7 +650,7 @@ public class TextPresentation { public StyleRange getFirstStyleRange() { try { - StyleRange range= (StyleRange) fRanges.get(getFirstIndexInWindow(fResultWindow)); + StyleRange range= fRanges.get(getFirstIndexInWindow(fResultWindow)); return createWindowRelativeRange(fResultWindow, range); } catch (NoSuchElementException x) { @@ -668,7 +668,7 @@ public class TextPresentation { public StyleRange getLastStyleRange() { try { - StyleRange range= (StyleRange) fRanges.get(getFirstIndexAfterWindow(fResultWindow) - 1); + StyleRange range= fRanges.get(getFirstIndexAfterWindow(fResultWindow) - 1); return createWindowRelativeRange(fResultWindow, range); } catch (NoSuchElementException x) { diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java index fe62f16a3f7..adf4e39098f 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/TextViewer.java @@ -466,9 +466,9 @@ public class TextViewer extends Viewer implements } /** List of registered verify key listeners. */ - private List fListeners= new ArrayList(); + private List<VerifyKeyListener> fListeners= new ArrayList<>(); /** List of pending batches. */ - private List fBatched= new ArrayList(); + private List<Batch> fBatched= new ArrayList<>(); /** The reentrance count. */ private int fReentranceCount= 0; @@ -479,9 +479,9 @@ public class TextViewer extends Viewer implements try { fReentranceCount++; - Iterator iterator= fListeners.iterator(); + Iterator<VerifyKeyListener> iterator= fListeners.iterator(); while (iterator.hasNext() && event.doit) { - VerifyKeyListener listener= (VerifyKeyListener) iterator.next(); + VerifyKeyListener listener= iterator.next(); listener.verifyKey(event); // we might trigger reentrant calls on GTK } } finally { @@ -496,9 +496,9 @@ public class TextViewer extends Viewer implements */ private void processBatchedRequests() { if (!fBatched.isEmpty()) { - Iterator e= fBatched.iterator(); + Iterator<Batch> e= fBatched.iterator(); while (e.hasNext()) { - Batch batch= (Batch) e.next(); + Batch batch= e.next(); insertListener(batch.listener, batch.index); } fBatched.clear(); @@ -777,7 +777,7 @@ public class TextViewer extends Viewer implements /** The highlight color of the range of this target. */ private Color fScopeHighlightColor; /** The document partitioner remembered in case of a "Replace All". */ - private Map fRememberedPartitioners; + private Map<String, IDocumentPartitioner> fRememberedPartitioners; /** * The active rewrite session. * @since 3.1 @@ -1522,7 +1522,7 @@ public class TextViewer extends Viewer implements * The registered post selection changed listeners. * @since 3.0 */ - private List fPostSelectionChangedListeners; + private List<ISelectionChangedListener> fPostSelectionChangedListeners; /** * Queued post selection changed events count. * @since 3.0 @@ -1537,7 +1537,7 @@ public class TextViewer extends Viewer implements * The set of registered editor helpers. * @since 3.1 */ - private Set fEditorHelpers= new HashSet(); + private Set<IEditingSupport> fEditorHelpers= new HashSet<>(); /** * The internal rewrite session listener. * @since 3.1 @@ -1547,25 +1547,25 @@ public class TextViewer extends Viewer implements /** Should the auto indent strategies ignore the next edit operation */ protected boolean fIgnoreAutoIndent= false; /** The strings a line is prefixed with on SHIFT_RIGHT and removed from each line on SHIFT_LEFT */ - protected Map fIndentChars; + protected Map<String, String[]> fIndentChars; /** The string a line is prefixed with on PREFIX and removed from each line on STRIP_PREFIX */ - protected Map fDefaultPrefixChars; + protected Map<String, String[]> fDefaultPrefixChars; /** The text viewer's text double click strategies */ - protected Map fDoubleClickStrategies; + protected Map<String, ITextDoubleClickStrategy> fDoubleClickStrategies; /** The text viewer's undo manager */ protected IUndoManager fUndoManager; /** The text viewer's auto indent strategies */ - protected Map fAutoIndentStrategies; + protected Map<String, List<IAutoEditStrategy>> fAutoIndentStrategies; /** The text viewer's text hovers */ - protected Map fTextHovers; + protected Map<TextHoverKey, ITextHover> fTextHovers; /** All registered view port listeners> */ - protected List fViewportListeners; + protected List<IViewportListener> fViewportListeners; /** The last visible vertical position of the top line */ protected int fLastTopPixel; /** All registered text listeners */ - protected List fTextListeners; + protected List<ITextListener> fTextListeners; /** All registered text input listeners */ - protected List fTextInputListeners; + protected List<ITextInputListener> fTextInputListeners; /** The text viewer's event consumer */ protected IEventConsumer fEventConsumer; /** Indicates whether the viewer's text presentation should be replaced are modified. */ @@ -1594,7 +1594,7 @@ public class TextViewer extends Viewer implements * All registered text presentation listeners. * since 3.0 */ - protected List fTextPresentationListeners; + protected List<ITextPresentationListener> fTextPresentationListeners; /** * The find/replace document adapter. * @since 3.0 @@ -1953,9 +1953,9 @@ public class TextViewer extends Viewer implements */ protected final void setAutoEditStrategies(IAutoEditStrategy[] strategies, String contentType) { if (fAutoIndentStrategies == null) - fAutoIndentStrategies= new HashMap(); + fAutoIndentStrategies= new HashMap<>(); - List autoEditStrategies= (List) fAutoIndentStrategies.get(contentType); + List<IAutoEditStrategy> autoEditStrategies= fAutoIndentStrategies.get(contentType); if (strategies == null) { if (autoEditStrategies == null) @@ -1965,7 +1965,7 @@ public class TextViewer extends Viewer implements } else { if (autoEditStrategies == null) { - autoEditStrategies= new ArrayList(); + autoEditStrategies= new ArrayList<>(); fAutoIndentStrategies.put(contentType, autoEditStrategies); } @@ -1981,11 +1981,11 @@ public class TextViewer extends Viewer implements throw new IllegalArgumentException(); if (fAutoIndentStrategies == null) - fAutoIndentStrategies= new HashMap(); + fAutoIndentStrategies= new HashMap<>(); - List autoEditStrategies= (List) fAutoIndentStrategies.get(contentType); + List<IAutoEditStrategy> autoEditStrategies= fAutoIndentStrategies.get(contentType); if (autoEditStrategies == null) { - autoEditStrategies= new ArrayList(); + autoEditStrategies= new ArrayList<>(); fAutoIndentStrategies.put(contentType, autoEditStrategies); } @@ -1997,11 +1997,11 @@ public class TextViewer extends Viewer implements if (fAutoIndentStrategies == null) return; - List autoEditStrategies= (List) fAutoIndentStrategies.get(contentType); + List<IAutoEditStrategy> autoEditStrategies= fAutoIndentStrategies.get(contentType); if (autoEditStrategies == null) return; - for (final Iterator iterator= autoEditStrategies.iterator(); iterator.hasNext(); ) { + for (final Iterator<IAutoEditStrategy> iterator= autoEditStrategies.iterator(); iterator.hasNext(); ) { if (iterator.next().equals(strategy)) { iterator.remove(); break; @@ -2028,7 +2028,7 @@ public class TextViewer extends Viewer implements if (ok) { if (fIndentChars == null) - fIndentChars= new HashMap(); + fIndentChars= new HashMap<>(); fIndentChars.put(contentType, indentPrefixes); @@ -2063,7 +2063,7 @@ public class TextViewer extends Viewer implements if (defaultPrefixes != null && defaultPrefixes.length > 0) { if (fDefaultPrefixChars == null) - fDefaultPrefixChars= new HashMap(); + fDefaultPrefixChars= new HashMap<>(); fDefaultPrefixChars.put(contentType, defaultPrefixes); } else if (fDefaultPrefixChars != null) fDefaultPrefixChars.remove(contentType); @@ -2089,7 +2089,7 @@ public class TextViewer extends Viewer implements TextHoverKey key= new TextHoverKey(contentType, stateMask); if (hover != null) { if (fTextHovers == null) { - fTextHovers= new HashMap(); + fTextHovers= new HashMap<>(); } fTextHovers.put(key, hover); } else if (fTextHovers != null) @@ -2103,9 +2103,9 @@ public class TextViewer extends Viewer implements if (fTextHovers == null) return; - Iterator iter= new HashSet(fTextHovers.keySet()).iterator(); + Iterator<TextHoverKey> iter= new HashSet<>(fTextHovers.keySet()).iterator(); while (iter.hasNext()) { - TextHoverKey key= (TextHoverKey)iter.next(); + TextHoverKey key= iter.next(); if (key.fContentType.equals(contentType)) fTextHovers.remove(key); } @@ -2486,7 +2486,7 @@ public class TextViewer extends Viewer implements Assert.isNotNull(listener); if (fPostSelectionChangedListeners == null) - fPostSelectionChangedListeners= new ArrayList(); + fPostSelectionChangedListeners= new ArrayList<>(); if (!fPostSelectionChangedListeners.contains(listener)) fPostSelectionChangedListeners.add(listener); @@ -2613,11 +2613,11 @@ public class TextViewer extends Viewer implements * @since 3.0 */ private void firePostSelectionChanged(SelectionChangedEvent event) { - List listeners= fPostSelectionChangedListeners; + List<ISelectionChangedListener> listeners= fPostSelectionChangedListeners; if (listeners != null) { - listeners= new ArrayList(listeners); + listeners= new ArrayList<>(listeners); for (int i= 0; i < listeners.size(); i++) { - ISelectionChangedListener l= (ISelectionChangedListener) listeners.get(i); + ISelectionChangedListener l= listeners.get(i); l.selectionChanged(event); } } @@ -2654,7 +2654,7 @@ public class TextViewer extends Viewer implements Assert.isNotNull(listener); if (fTextListeners == null) - fTextListeners= new ArrayList(); + fTextListeners= new ArrayList<>(); if (!fTextListeners.contains(listener)) fTextListeners.add(listener); @@ -2679,16 +2679,16 @@ public class TextViewer extends Viewer implements * @param cmd the widget command translated into a text event sent to all text listeners */ protected void updateTextListeners(WidgetCommand cmd) { - List textListeners= fTextListeners; + List<ITextListener> textListeners= fTextListeners; if (textListeners != null) { - textListeners= new ArrayList(textListeners); + textListeners= new ArrayList<>(textListeners); DocumentEvent event= cmd.event; if (event instanceof SlaveDocumentEvent) event= ((SlaveDocumentEvent) event).getMasterEvent(); TextEvent e= new TextEvent(cmd.start, cmd.length, cmd.text, cmd.preservedText, event, redraws()); for (int i= 0; i < textListeners.size(); i++) { - ITextListener l= (ITextListener) textListeners.get(i); + ITextListener l= textListeners.get(i); l.textChanged(e); } } @@ -2702,7 +2702,7 @@ public class TextViewer extends Viewer implements Assert.isNotNull(listener); if (fTextInputListeners == null) - fTextInputListeners= new ArrayList(); + fTextInputListeners= new ArrayList<>(); if (!fTextInputListeners.contains(listener)) fTextInputListeners.add(listener); @@ -2728,10 +2728,10 @@ public class TextViewer extends Viewer implements * @param newInput the new input document */ protected void fireInputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { - List listener= fTextInputListeners; + List<ITextInputListener> listener= fTextInputListeners; if (listener != null) { for (int i= 0; i < listener.size(); i++) { - ITextInputListener l= (ITextInputListener) listener.get(i); + ITextInputListener l= listener.get(i); l.inputDocumentAboutToBeChanged(oldInput, newInput); } } @@ -2745,10 +2745,10 @@ public class TextViewer extends Viewer implements * @param newInput the new input document */ protected void fireInputDocumentChanged(IDocument oldInput, IDocument newInput) { - List listener= fTextInputListeners; + List<ITextInputListener> listener= fTextInputListeners; if (listener != null) { for (int i= 0; i < listener.size(); i++) { - ITextInputListener l= (ITextInputListener) listener.get(i); + ITextInputListener l= listener.get(i); l.inputDocumentChanged(oldInput, newInput); } } @@ -2937,7 +2937,7 @@ public class TextViewer extends Viewer implements public void addViewportListener(IViewportListener listener) { if (fViewportListeners == null) { - fViewportListeners= new ArrayList(); + fViewportListeners= new ArrayList<>(); initializeViewportUpdate(); } @@ -2966,7 +2966,7 @@ public class TextViewer extends Viewer implements if (topPixel >= 0 && topPixel != fLastTopPixel) { if (fViewportListeners != null) { for (int i= 0; i < fViewportListeners.size(); i++) { - IViewportListener l= (IViewportListener) fViewportListeners.get(i); + IViewportListener l= fViewportListeners.get(i); l.viewportChanged(topPixel); } } @@ -3532,7 +3532,7 @@ public class TextViewer extends Viewer implements if (strategy != null) { if (fDoubleClickStrategies == null) - fDoubleClickStrategies= new HashMap(); + fDoubleClickStrategies= new HashMap<>(); fDoubleClickStrategies.put(contentType, strategy); } else if (fDoubleClickStrategies != null) fDoubleClickStrategies.remove(contentType); @@ -3542,11 +3542,11 @@ public class TextViewer extends Viewer implements * Selects from the given map the one which is registered under the content type of the * partition in which the given offset is located. * - * @param plugins the map from which to choose * @param offset the offset for which to find the plug-in + * @param plugins the map from which to choose * @return the plug-in registered under the offset's content type or <code>null</code> if none */ - protected Object selectContentTypePlugin(int offset, Map plugins) { + protected Object selectContentTypePlugin(int offset, Map<String, ?> plugins) { final IDocument document= getDocument(); if (document == null) return null; @@ -3567,7 +3567,7 @@ public class TextViewer extends Viewer implements * @param plugins the table to be searched * @return the plug-in in the map for the given content type */ - private Object selectContentTypePlugin(String type, Map plugins) { + private Object selectContentTypePlugin(String type, Map<String, ?> plugins) { if (plugins == null) return null; @@ -3592,7 +3592,8 @@ public class TextViewer extends Viewer implements if (fTabsToSpacesConverter != null) fTabsToSpacesConverter.customizeDocumentCommand(document, command); - List strategies= (List) selectContentTypePlugin(command.offset, fAutoIndentStrategies); + @SuppressWarnings("unchecked") + List<IAutoEditStrategy> strategies= (List<IAutoEditStrategy>) selectContentTypePlugin(command.offset, fAutoIndentStrategies); if (strategies == null) return; @@ -3602,14 +3603,14 @@ public class TextViewer extends Viewer implements break; case 1: - ((IAutoEditStrategy) strategies.iterator().next()).customizeDocumentCommand(document, command); + strategies.iterator().next().customizeDocumentCommand(document, command); break; // make iterator robust against adding/removing strategies from within strategies default: - strategies= new ArrayList(strategies); - for (final Iterator iterator= strategies.iterator(); iterator.hasNext(); ) - ((IAutoEditStrategy) iterator.next()).customizeDocumentCommand(document, command); + strategies= new ArrayList<>(strategies); + for (final Iterator<IAutoEditStrategy> iterator= strategies.iterator(); iterator.hasNext(); ) + iterator.next().customizeDocumentCommand(document, command); break; } @@ -4219,7 +4220,7 @@ public class TextViewer extends Viewer implements fUndoManager.beginCompoundChange(); IDocument d= getDocument(); - Map partitioners= null; + Map<String, IDocumentPartitioner> partitioners= null; DocumentRewriteSession rewriteSession= null; try { ITextSelection selection= (ITextSelection) getSelection(); @@ -4251,7 +4252,7 @@ public class TextViewer extends Viewer implements partitioners= TextUtilities.removeDocumentPartitioners(d); // Perform the shift operation. - Map map= (useDefaultPrefixes ? fDefaultPrefixChars : fIndentChars); + Map<String, String[]> map= (useDefaultPrefixes ? fDefaultPrefixChars : fIndentChars); for (int i= 0, j= 0; i < regions.length; i++, j += 2) { String[] prefixes= (String[]) selectContentTypePlugin(regions[i].getType(), map); if (prefixes != null && prefixes.length > 0 && lines[j] >= 0 && lines[j + 1] >= 0) { @@ -4652,27 +4653,27 @@ public class TextViewer extends Viewer implements if (range != null) fTextWidget.setStyleRange(range); - ArrayList ranges= new ArrayList(presentation.getDenumerableRanges()); - Iterator e= presentation.getNonDefaultStyleRangeIterator(); + ArrayList<StyleRange> ranges= new ArrayList<>(presentation.getDenumerableRanges()); + Iterator<StyleRange> e= presentation.getNonDefaultStyleRangeIterator(); while (e.hasNext()) { - range= (StyleRange) e.next(); + range= e.next(); range= modelStyleRange2WidgetStyleRange(range); if (range != null) ranges.add(range); } if (!ranges.isEmpty()) - fTextWidget.replaceStyleRanges(0, 0, (StyleRange[])ranges.toArray(new StyleRange[ranges.size()])); + fTextWidget.replaceStyleRanges(0, 0, ranges.toArray(new StyleRange[ranges.size()])); } else { IRegion region= modelRange2WidgetRange(presentation.getCoverage()); if (region == null) return; - List list= new ArrayList(presentation.getDenumerableRanges()); - Iterator e= presentation.getAllStyleRangeIterator(); + List<StyleRange> list= new ArrayList<>(presentation.getDenumerableRanges()); + Iterator<StyleRange> e= presentation.getAllStyleRangeIterator(); while (e.hasNext()) { - range= (StyleRange) e.next(); + range= e.next(); range= modelStyleRange2WidgetStyleRange(range); if (range != null) list.add(range); @@ -4694,10 +4695,10 @@ public class TextViewer extends Viewer implements */ private void applyTextPresentation(TextPresentation presentation) { - List list= new ArrayList(presentation.getDenumerableRanges()); - Iterator e= presentation.getAllStyleRangeIterator(); + List<StyleRange> list= new ArrayList<>(presentation.getDenumerableRanges()); + Iterator<StyleRange> e= presentation.getAllStyleRangeIterator(); while (e.hasNext()) { - StyleRange range= (StyleRange) e.next(); + StyleRange range= e.next(); range= modelStyleRange2WidgetStyleRange(range); if (range != null) list.add(range); @@ -4742,9 +4743,9 @@ public class TextViewer extends Viewer implements * and let them apply their presentation. */ if (fTextPresentationListeners != null) { - ArrayList listeners= new ArrayList(fTextPresentationListeners); + ArrayList<ITextPresentationListener> listeners= new ArrayList<>(fTextPresentationListeners); for (int i= 0, size= listeners.size(); i < size; i++) { - ITextPresentationListener listener= (ITextPresentationListener)listeners.get(i); + ITextPresentationListener listener= listeners.get(i); listener.applyTextPresentation(presentation); } } @@ -5459,7 +5460,7 @@ public class TextViewer extends Viewer implements Assert.isNotNull(listener); if (fTextPresentationListeners == null) - fTextPresentationListeners= new ArrayList(); + fTextPresentationListeners= new ArrayList<>(); if (!fTextPresentationListeners.contains(listener)) fTextPresentationListeners.add(listener); @@ -5502,7 +5503,7 @@ public class TextViewer extends Viewer implements */ @Override public IEditingSupport[] getRegisteredSupports() { - return (IEditingSupport[]) fEditorHelpers.toArray(new IEditingSupport[fEditorHelpers.size()]); + return fEditorHelpers.toArray(new IEditingSupport[fEditorHelpers.size()]); } @Override diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposalPopup.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposalPopup.java index cb28c396118..697c52fbaf7 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposalPopup.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/CompletionProposalPopup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,7 +15,6 @@ package org.eclipse.jface.text.contentassist; import java.util.ArrayList; import java.util.Arrays; -import java.util.Comparator; import java.util.List; import org.eclipse.osgi.util.TextProcessor; @@ -291,7 +290,7 @@ class CompletionProposalPopup implements IContentAssistListener { /** The key listener to control navigation. */ private ProposalSelectionListener fKeyListener; /** List of document events used for filtering proposals. */ - private final List fDocumentEvents= new ArrayList(); + private final List<DocumentEvent> fDocumentEvents= new ArrayList<>(); /** Listener filling the document event queue. */ private IDocumentListener fDocumentListener; /** The filter list of proposals. */ @@ -1509,7 +1508,7 @@ class CompletionProposalPopup implements IContentAssistListener { IDocument document= fContentAssistSubjectControlAdapter.getDocument(); int length= proposals.length; - List filtered= new ArrayList(length); + List<Object> filtered= new ArrayList<>(length); for (int i= 0; i < length; i++) { if (proposals[i] instanceof ICompletionProposalExtension2) { @@ -1540,7 +1539,7 @@ class CompletionProposalPopup implements IContentAssistListener { } } - return (ICompletionProposal[]) filtered.toArray(new ICompletionProposal[filtered.size()]); + return filtered.toArray(new ICompletionProposal[filtered.size()]); } /** @@ -1658,7 +1657,7 @@ class CompletionProposalPopup implements IContentAssistListener { // contains the common postfix in the case that there are any proposals matching our LHS StringBuffer rightCasePostfix= null; - List rightCase= new ArrayList(); + List<ICompletionProposal> rightCase= new ArrayList<>(); boolean isWrongCaseMatch= false; @@ -1668,7 +1667,7 @@ class CompletionProposalPopup implements IContentAssistListener { int wrongCasePrefixStart= 0; // contains the common postfix of all case-insensitive matches StringBuffer wrongCasePostfix= null; - List wrongCase= new ArrayList(); + List<ICompletionProposal> wrongCase= new ArrayList<>(); for (int i= 0; i < fFilteredProposals.length; i++) { ICompletionProposal proposal= fFilteredProposals[i]; @@ -1721,7 +1720,7 @@ class CompletionProposalPopup implements IContentAssistListener { // 2: replace single proposals if (rightCase.size() == 1) { - ICompletionProposal proposal= (ICompletionProposal) rightCase.get(0); + ICompletionProposal proposal= rightCase.get(0); if (canAutoInsert(proposal) && rightCasePostfix.length() > 0) { insertProposal(proposal, (char) 0, 0, fInvocationOffset); hide(); @@ -1729,7 +1728,7 @@ class CompletionProposalPopup implements IContentAssistListener { } return false; } else if (isWrongCaseMatch && wrongCase.size() == 1) { - ICompletionProposal proposal= (ICompletionProposal) wrongCase.get(0); + ICompletionProposal proposal= wrongCase.get(0); if (canAutoInsert(proposal)) { insertProposal(proposal, (char) 0, 0, fInvocationOffset); hide(); @@ -1904,12 +1903,6 @@ class CompletionProposalPopup implements IContentAssistListener { * @since 3.8 */ private void sortProposals(final ICompletionProposal[] proposals) { - Arrays.sort(proposals, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - return fSorter.compare((ICompletionProposal)o1, - (ICompletionProposal)o2); - } - }); + Arrays.sort(proposals, fSorter::compare); } } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistant.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistant.java index 94f6c04436b..7fc5166fce3 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistant.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContentAssistant.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -906,7 +906,7 @@ public class ContentAssistant implements IContentAssistant, IContentAssistantExt private boolean fIsAutoInserting= false; private int fProposalPopupOrientation= PROPOSAL_OVERLAY; private int fContextInfoPopupOrientation= CONTEXT_INFO_ABOVE; - private Map fProcessors; + private Map<String, IContentAssistProcessor> fProcessors; /** * The partitioning. @@ -1023,7 +1023,7 @@ public class ContentAssistant implements IContentAssistant, IContentAssistantExt * * @since 3.4 */ - private Map fHandlers; + private Map<String, IHandler> fHandlers; /** * Tells whether colored labels support is enabled. @@ -1080,7 +1080,7 @@ public class ContentAssistant implements IContentAssistant, IContentAssistantExt Assert.isNotNull(contentType); if (fProcessors == null) - fProcessors= new HashMap(); + fProcessors= new HashMap<>(); if (processor == null) fProcessors.remove(contentType); @@ -1096,7 +1096,7 @@ public class ContentAssistant implements IContentAssistant, IContentAssistantExt if (fProcessors == null) return null; - return (IContentAssistProcessor) fProcessors.get(contentType); + return fProcessors.get(contentType); } /** @@ -1110,10 +1110,10 @@ public class ContentAssistant implements IContentAssistant, IContentAssistantExt return ""; //$NON-NLS-1$ StringBuffer buf= new StringBuffer(5); - Iterator iter= fProcessors.entrySet().iterator(); + Iterator<Entry<String, IContentAssistProcessor>> iter= fProcessors.entrySet().iterator(); while (iter.hasNext()) { - Entry entry= (Entry) iter.next(); - IContentAssistProcessor processor= (IContentAssistProcessor) entry.getValue(); + Entry<String, IContentAssistProcessor> entry= iter.next(); + IContentAssistProcessor processor= entry.getValue(); char[] triggers= processor.getCompletionProposalAutoActivationCharacters(); if (triggers != null) buf.append(triggers); @@ -2535,7 +2535,7 @@ public class ContentAssistant implements IContentAssistant, IContentAssistantExt if (fHandlers == null) throw new IllegalStateException(); - IHandler handler= (IHandler)fHandlers.get(commandId); + IHandler handler= fHandlers.get(commandId); if (handler != null) return handler; @@ -2552,7 +2552,7 @@ public class ContentAssistant implements IContentAssistant, IContentAssistantExt */ protected final void registerHandler(String commandId, IHandler handler) { if (fHandlers == null) - fHandlers= new HashMap(2); + fHandlers= new HashMap<>(2); fHandlers.put(commandId, handler); } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationPopup.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationPopup.java index 0bc4eb0360b..600741249f0 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationPopup.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/contentassist/ContextInformationPopup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -117,7 +117,7 @@ class ContextInformationPopup implements IContentAssistListener { private StyledText fContextInfoText; private TextPresentation fTextPresentation; - private Stack fContextFrameStack= new Stack(); + private Stack<ContextFrame> fContextFrameStack= new Stack<>(); /** * The content assist subject control. * @@ -218,8 +218,8 @@ class ContextInformationPopup implements IContentAssistListener { } // also check all other contexts - for (Iterator it= fContextFrameStack.iterator(); it.hasNext(); ) { - ContextFrame stackFrame= (ContextFrame) it.next(); + for (Iterator<ContextFrame> it= fContextFrameStack.iterator(); it.hasNext(); ) { + ContextFrame stackFrame= it.next(); if (stackFrame.equals(frame)) { validateContextInformation(); return; @@ -321,7 +321,7 @@ class ContextInformationPopup implements IContentAssistListener { if (fContextFrameStack.isEmpty()) return false; // stack not empty - ContextFrame top= (ContextFrame) fContextFrameStack.peek(); + ContextFrame top= fContextFrameStack.peek(); return frame.equals(top); } @@ -460,12 +460,12 @@ class ContextInformationPopup implements IContentAssistListener { int size= fContextFrameStack.size(); if (size > 0) { - fLastContext= (ContextFrame) fContextFrameStack.pop(); + fLastContext= fContextFrameStack.pop(); -- size; } if (size > 0) { - ContextFrame current= (ContextFrame) fContextFrameStack.peek(); + ContextFrame current= fContextFrameStack.peek(); internalShowContextFrame(current, false); } else { @@ -872,7 +872,7 @@ class ContextInformationPopup implements IContentAssistListener { fContextInfoPopup.getDisplay().asyncExec(new Runnable() { - private ContextFrame fFrame= (ContextFrame) fContextFrameStack.peek(); + private ContextFrame fFrame= fContextFrameStack.peek(); @Override public void run() { @@ -882,7 +882,7 @@ class ContextInformationPopup implements IContentAssistListener { // iterate all contexts on the stack while (Helper.okToUse(fContextInfoPopup) && !fContextFrameStack.isEmpty()) { - ContextFrame top= (ContextFrame) fContextFrameStack.peek(); + ContextFrame top= fContextFrameStack.peek(); if (top.fValidator == null || !top.fValidator.isContextInformationValid(offset)) { hideContextInfoPopup(); // loop variant: reduces the number of contexts on the stack } else if (top.fPresenter != null && top.fPresenter.updatePresentation(offset, fTextPresentation)) { diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContentFormatter.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContentFormatter.java index e02b999a493..fd0d9b8ddc4 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContentFormatter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContentFormatter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -69,7 +69,7 @@ public class ContentFormatter implements IContentFormatter { * Defines a reference to either the offset or the end offset of * a particular position. */ - static class PositionReference implements Comparable { + static class PositionReference implements Comparable<PositionReference> { /** The referenced position */ protected Position fPosition; @@ -167,14 +167,8 @@ public class ContentFormatter implements IContentFormatter { } @Override - public int compareTo(Object obj) { - - if (obj instanceof PositionReference) { - PositionReference r= (PositionReference) obj; - return getCharacterPosition() - r.getCharacterPosition(); - } - - throw new ClassCastException(); + public int compareTo(PositionReference r) { + return getCharacterPosition() - r.getCharacterPosition(); } } @@ -251,14 +245,14 @@ public class ContentFormatter implements IContentFormatter { private final static String PARTITIONING= "__formatter_partitioning"; //$NON-NLS-1$ /** The map of <code>IFormattingStrategy</code> objects */ - private Map fStrategies; + private Map<String, IFormattingStrategy> fStrategies; /** The indicator of whether the formatter operates in partition aware mode or not */ private boolean fIsPartitionAware= true; /** The partition information managing document position categories */ private String[] fPartitionManagingCategories; /** The list of references to offset and end offset of all overlapping positions */ - private List fOverlappingPositionReferences; + private List<PositionReference> fOverlappingPositionReferences; /** Position updater used for partitioning positions */ private IPositionUpdater fPartitioningUpdater; /** @@ -306,7 +300,7 @@ public class ContentFormatter implements IContentFormatter { Assert.isNotNull(contentType); if (fStrategies == null) - fStrategies= new HashMap(); + fStrategies= new HashMap<>(); if (strategy == null) fStrategies.remove(contentType); @@ -355,7 +349,7 @@ public class ContentFormatter implements IContentFormatter { if (fStrategies == null) return null; - return (IFormattingStrategy) fStrategies.get(contentType); + return fStrategies.get(contentType); } @Override @@ -657,7 +651,7 @@ public class ContentFormatter implements IContentFormatter { */ private int[] getAffectedPositions(int offset, int length) { - fOverlappingPositionReferences= new ArrayList(); + fOverlappingPositionReferences= new ArrayList<>(); determinePositionsToUpdate(offset, length); @@ -665,7 +659,7 @@ public class ContentFormatter implements IContentFormatter { int[] positions= new int[fOverlappingPositionReferences.size()]; for (int i= 0; i < positions.length; i++) { - PositionReference r= (PositionReference) fOverlappingPositionReferences.get(i); + PositionReference r= fOverlappingPositionReferences.get(i); positions[i]= r.getCharacterPosition() - offset; } @@ -681,7 +675,7 @@ public class ContentFormatter implements IContentFormatter { private void removeAffectedPositions(IDocument document) { int size= fOverlappingPositionReferences.size(); for (int i= 0; i < size; i++) { - PositionReference r= (PositionReference) fOverlappingPositionReferences.get(i); + PositionReference r= fOverlappingPositionReferences.get(i); try { document.removePosition(r.getCategory(), r.getPosition()); } catch (BadPositionCategoryException x) { @@ -708,7 +702,7 @@ public class ContentFormatter implements IContentFormatter { for (int i= 0; i < positions.length; i++) { - PositionReference r= (PositionReference) fOverlappingPositionReferences.get(i); + PositionReference r= fOverlappingPositionReferences.get(i); if (r.refersToOffset()) r.setOffset(offset + positions[i]); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContextBasedFormattingStrategy.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContextBasedFormattingStrategy.java index ddeccc8d140..65342636d28 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContextBasedFormattingStrategy.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/ContextBasedFormattingStrategy.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,14 +25,14 @@ import java.util.Map; public abstract class ContextBasedFormattingStrategy implements IFormattingStrategy, IFormattingStrategyExtension { /** The current preferences for formatting */ - private Map fCurrentPreferences= null; + private Map<String, String> fCurrentPreferences= null; /** The list of preferences for initiated the formatting steps */ - private final LinkedList fPreferences= new LinkedList(); + private final LinkedList<Map<String, String>> fPreferences= new LinkedList<>(); @Override public void format() { - fCurrentPreferences= (Map)fPreferences.removeFirst(); + fCurrentPreferences= fPreferences.removeFirst(); } @Override @@ -42,7 +42,9 @@ public abstract class ContextBasedFormattingStrategy implements IFormattingStrat @Override public void formatterStarts(final IFormattingContext context) { - fPreferences.addLast(context.getProperty(FormattingContextProperties.CONTEXT_PREFERENCES)); + @SuppressWarnings("unchecked") + Map<String, String> prefs= (Map<String, String>) context.getProperty(FormattingContextProperties.CONTEXT_PREFERENCES); + fPreferences.addLast(prefs); } @Override @@ -62,7 +64,7 @@ public abstract class ContextBasedFormattingStrategy implements IFormattingStrat * * @return The preferences for the current formatting step */ - public final Map getPreferences() { + public final Map<String, String> getPreferences() { return fCurrentPreferences; } } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/FormattingContext.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/FormattingContext.java index 9b76ced365e..adce0392947 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/FormattingContext.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/FormattingContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -24,7 +24,7 @@ import org.eclipse.jface.preference.IPreferenceStore; public class FormattingContext implements IFormattingContext { /** Map to store the properties */ - private final Map fMap= new HashMap(); + private final Map<Object, Object> fMap= new HashMap<>(); @Override public void dispose() { @@ -73,7 +73,7 @@ public class FormattingContext implements IFormattingContext { } @Override - public void mapToStore(Map map, IPreferenceStore store) { + public void mapToStore(Map<Object, Object> map, IPreferenceStore store) { final String[] preferences= getPreferenceKeys(); @@ -114,7 +114,7 @@ public class FormattingContext implements IFormattingContext { } @Override - public void storeToMap(IPreferenceStore store, Map map, boolean useDefault) { + public void storeToMap(IPreferenceStore store, Map<Object, Object> map, boolean useDefault) { final String[] preferences= getPreferenceKeys(); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/FormattingContextProperties.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/FormattingContextProperties.java index 662b1d0f2c5..27fa75a3003 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/FormattingContextProperties.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/FormattingContextProperties.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -42,8 +42,8 @@ public class FormattingContextProperties { public static final String CONTEXT_PARTITION= "formatting.context.partition"; //$NON-NLS-1$ /** - * Property key of the preferences property. The property must implement - * <code>java.util#Map</code>. The formatting preferences mapping preference + * Property key of the preferences property. The property value must implement + * {@code java.util.Map<String, String>}. The formatting preferences mapping preference * keys to values. * <p> * Value: <code>"formatting.context.preferences"</code> diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/IFormattingContext.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/IFormattingContext.java index fa92119d1c7..616c1e2f990 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/IFormattingContext.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/IFormattingContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -41,7 +41,7 @@ public interface IFormattingContext { /** * Retrieves the property <code>key</code> from the formatting context * - * @param key the key of the property to store in the context + * @param key the key of the property to store in the context. Must be a {@link String}. * @return the property <code>key</code> if available, <code>null</code> otherwise */ Object getProperty(Object key); @@ -110,12 +110,12 @@ public interface IFormattingContext { * @param map Map to retrieve the preferences from * @param store Preference store to store the preferences in */ - void mapToStore(Map map, IPreferenceStore store); + void mapToStore(Map<Object, Object> map, IPreferenceStore store); /** * Stores the property <code>key</code> in the formatting context. * - * @param key Key of the property to store in the context + * @param key Key of the property to store in the context. Must be a {@link String}. * @param property Property to store in the context. If already present, the new property * overwrites the present one. */ @@ -133,5 +133,5 @@ public interface IFormattingContext { * @param useDefault <code>true</code> if the default preferences should be used, * <code>false</code> otherwise */ - void storeToMap(IPreferenceStore store, Map map, boolean useDefault); + void storeToMap(IPreferenceStore store, Map<Object, Object> map, boolean useDefault); } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/MultiPassContentFormatter.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/MultiPassContentFormatter.java index be8d549897c..7abacbb4a89 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/MultiPassContentFormatter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/formatter/MultiPassContentFormatter.java @@ -20,6 +20,7 @@ import org.eclipse.core.runtime.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.TextUtilities; @@ -103,7 +104,7 @@ public class MultiPassContentFormatter implements IContentFormatter, IContentFor /** The partitioning of this content formatter */ private final String fPartitioning; /** The slave formatting strategies */ - private final Map fSlaves= new HashMap(); + private final Map<String, IFormattingStrategy> fSlaves= new HashMap<>(); /** The default content type */ private final String fType; @@ -240,7 +241,7 @@ public class MultiPassContentFormatter implements IContentFormatter, IContentFor */ protected void formatSlaves(final IFormattingContext context, final IDocument document, final int offset, final int length) { - Map partitioners= new HashMap(0); + Map<String, IDocumentPartitioner> partitioners= new HashMap<>(0); try { final ITypedRegion[] partitions= TextUtilities.computePartitioning(document, fPartitioning, offset, length, false); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/AbstractHyperlinkDetector.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/AbstractHyperlinkDetector.java index cd73b4f4480..56684a0baf5 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/AbstractHyperlinkDetector.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/AbstractHyperlinkDetector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -60,7 +60,7 @@ public abstract class AbstractHyperlinkDetector implements IHyperlinkDetector, I * or <code>null</code> if this object does not * have an adapter for the given class */ - protected final Object getAdapter(Class adapterClass) { + protected final <T> T getAdapter(Class<T> adapterClass) { Assert.isLegal(adapterClass != null); if (fContext != null) return fContext.getAdapter(adapterClass); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/HyperlinkManager.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/HyperlinkManager.java index 419e4bb0bf2..e38a970cf2d 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/HyperlinkManager.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/hyperlink/HyperlinkManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -267,7 +267,7 @@ public class HyperlinkManager implements ITextListener, Listener, KeyListener, M * @since 3.7 */ private IHyperlink[] findHyperlinks(IRegion region) { - List allHyperlinks= new ArrayList(fHyperlinkDetectors.length * 2); + List<IHyperlink> allHyperlinks= new ArrayList<>(fHyperlinkDetectors.length * 2); synchronized (fHyperlinkDetectors) { for (int i= 0, length= fHyperlinkDetectors.length; i < length; i++) { IHyperlinkDetector detector= fHyperlinkDetectors[i]; @@ -304,18 +304,18 @@ public class HyperlinkManager implements ITextListener, Listener, KeyListener, M if (fDetectionStrategy != ALL) { int maxLength= computeLongestHyperlinkLength(allHyperlinks); - Iterator iter= new ArrayList(allHyperlinks).iterator(); + Iterator<IHyperlink> iter= new ArrayList<>(allHyperlinks).iterator(); while (iter.hasNext()) { - IHyperlink hyperlink= (IHyperlink)iter.next(); + IHyperlink hyperlink= iter.next(); if (hyperlink.getHyperlinkRegion().getLength() < maxLength) allHyperlinks.remove(hyperlink); } } if (fDetectionStrategy == LONGEST_REGION_FIRST) - return new IHyperlink[] {(IHyperlink)allHyperlinks.get(0)}; + return new IHyperlink[] {allHyperlinks.get(0)}; - return (IHyperlink[])allHyperlinks.toArray(new IHyperlink[allHyperlinks.size()]); + return allHyperlinks.toArray(new IHyperlink[allHyperlinks.size()]); } @@ -325,12 +325,12 @@ public class HyperlinkManager implements ITextListener, Listener, KeyListener, M * @param hyperlinks the list of hyperlinks * @return the length of the longest detected */ - protected int computeLongestHyperlinkLength(List hyperlinks) { + protected int computeLongestHyperlinkLength(List<? extends IHyperlink> hyperlinks) { Assert.isLegal(hyperlinks != null && !hyperlinks.isEmpty()); - Iterator iter= hyperlinks.iterator(); + Iterator<? extends IHyperlink> iter= hyperlinks.iterator(); int length= Integer.MIN_VALUE; while (iter.hasNext()) { - IRegion region= ((IHyperlink)iter.next()).getHyperlinkRegion(); + IRegion region= iter.next().getHyperlinkRegion(); if (region.getLength() < length) continue; length= region.getLength(); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/information/InformationPresenter.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/information/InformationPresenter.java index c9c73534e47..45e927dc274 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/information/InformationPresenter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/information/InformationPresenter.java @@ -200,7 +200,7 @@ public class InformationPresenter extends AbstractInformationControlManager impl /** The text viewer this information presenter works on */ private ITextViewer fTextViewer; /** The map of <code>IInformationProvider</code> objects */ - private Map fProviders; + private Map<String, IInformationProvider> fProviders; /** The offset to override selection. */ private int fOffset= -1; /** @@ -256,7 +256,7 @@ public class InformationPresenter extends AbstractInformationControlManager impl Assert.isNotNull(contentType); if (fProviders == null) - fProviders= new HashMap(); + fProviders= new HashMap<>(); if (provider == null) fProviders.remove(contentType); @@ -269,7 +269,7 @@ public class InformationPresenter extends AbstractInformationControlManager impl if (fProviders == null) return null; - return (IInformationProvider) fProviders.get(contentType); + return fProviders.get(contentType); } /** diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedModeUI.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedModeUI.java index 4f2a5492d0c..40cf26cd61e 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedModeUI.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedModeUI.java @@ -1043,12 +1043,12 @@ public class LinkedModeUI { if (document instanceof IDocumentExtension3) { IDocumentExtension3 ext= (IDocumentExtension3) document; String[] partitionings= ext.getPartitionings(); - Set contentTypes= new HashSet(20); + Set<String> contentTypes= new HashSet<>(20); for (int i= 0; i < partitionings.length; i++) { contentTypes.addAll(Arrays.asList(ext.getLegalContentTypes(partitionings[i]))); } contentTypes.add(IDocument.DEFAULT_CONTENT_TYPE); - return (String[]) contentTypes.toArray(new String[contentTypes.size()]); + return contentTypes.toArray(new String[contentTypes.size()]); } return document.getLegalContentTypes(); } @@ -1149,7 +1149,7 @@ public class LinkedModeUI { if ((flags & ILinkedModeListener.UPDATE_CARET) != 0 && fExitPosition != null && fFramePosition != fExitPosition && !fExitPosition.isDeleted()) switchPosition(fExitPosition, true, false); - final List docs= new ArrayList(); + final List<IDocument> docs= new ArrayList<>(); for (int i= 0; i < fTargets.length; i++) { IDocument doc= fTargets[i].getViewer().getDocument(); if (doc != null) @@ -1164,8 +1164,8 @@ public class LinkedModeUI { if (fExitPosition != null) fExitPosition.getDocument().removePosition(fExitPosition); - for (Iterator iter = docs.iterator(); iter.hasNext(); ) { - IDocument doc= (IDocument) iter.next(); + for (Iterator<IDocument> iter = docs.iterator(); iter.hasNext(); ) { + IDocument doc= iter.next(); doc.removePositionUpdater(fPositionUpdater); boolean uninstallCat= false; String[] cats= doc.getPositionCategories(); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedPositionAnnotations.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedPositionAnnotations.java index b379b88ca4c..297afa7d8d8 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedPositionAnnotations.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/link/LinkedPositionAnnotations.java @@ -46,8 +46,8 @@ final class LinkedPositionAnnotations extends AnnotationModel { private Annotation fFocusAnnotation= null; private Annotation fExitAnnotation= null; - private final Map fGroupAnnotations= new HashMap(); - private final Map fTargetAnnotations= new HashMap(); + private final Map<Position, Annotation> fGroupAnnotations= new HashMap<>(); + private final Map<Position, Annotation> fTargetAnnotations= new HashMap<>(); private Position[] fTargets= new Position[0]; private LinkedPosition fExitPosition= null; @@ -96,7 +96,7 @@ final class LinkedPositionAnnotations extends AnnotationModel { * @param positions the new slave positions, or <code>null</code> if no slave positions are to be set * @throws BadLocationException in case any of the given positions is invalid */ - private void setGroupPositions(List positions) throws BadLocationException { + private void setGroupPositions(List<Position> positions) throws BadLocationException { if (!fMarkSlaves) return; @@ -104,11 +104,11 @@ final class LinkedPositionAnnotations extends AnnotationModel { // Algorithm: toRemove contains all mappings at first, but all that are in // positions get removed -> toRemove contains the difference set of previous - new // toAdd are the new positions, which don't exist in previous = new - previous - List toRemove= new ArrayList(fGroupAnnotations.values()); - Map toAdd= new HashMap(); + List<Annotation> toRemove= new ArrayList<>(fGroupAnnotations.values()); + Map<Annotation, Position> toAdd= new HashMap<>(); if (positions != null) { - for (Iterator iter= positions.iterator(); iter.hasNext();) { - Position p= (Position) iter.next(); + for (Iterator<Position> iter= positions.iterator(); iter.hasNext();) { + Position p= iter.next(); if (fGroupAnnotations.containsKey(p)) { toRemove.remove(fGroupAnnotations.get(p)); } else { @@ -120,7 +120,7 @@ final class LinkedPositionAnnotations extends AnnotationModel { } fGroupAnnotations.values().removeAll(toRemove); - replaceAnnotations((Annotation[]) toRemove.toArray(new Annotation[0]), toAdd, false); + replaceAnnotations(toRemove.toArray(new Annotation[0]), toAdd, false); } /** @@ -130,7 +130,7 @@ final class LinkedPositionAnnotations extends AnnotationModel { * @param positions the new target positions, or <code>null</code> if no target positions are to be set * @throws BadLocationException in case any of the given positions is invalid */ - private void setTargetPositions(List positions) throws BadLocationException { + private void setTargetPositions(List<Position> positions) throws BadLocationException { if (!fMarkTargets) return; @@ -138,11 +138,11 @@ final class LinkedPositionAnnotations extends AnnotationModel { // Algorithm: toRemove contains all mappings at first, but all that are in // positions get removed -> toRemove contains the difference set of previous - new // toAdd are the new positions, which don't exist in previous = new - previous - List toRemove= new ArrayList(fTargetAnnotations.values()); - Map toAdd= new HashMap(); + List<Annotation> toRemove= new ArrayList<>(fTargetAnnotations.values()); + Map<Annotation, Position> toAdd= new HashMap<>(); if (positions != null) { - for (Iterator iter= positions.iterator(); iter.hasNext();) { - Position p= (Position) iter.next(); + for (Iterator<Position> iter= positions.iterator(); iter.hasNext();) { + Position p= iter.next(); if (fTargetAnnotations.containsKey(p)) { toRemove.remove(fTargetAnnotations.get(p)); } else { @@ -154,7 +154,7 @@ final class LinkedPositionAnnotations extends AnnotationModel { } fTargetAnnotations.values().removeAll(toRemove); - replaceAnnotations((Annotation[]) toRemove.toArray(new Annotation[0]), toAdd, false); + replaceAnnotations(toRemove.toArray(new Annotation[0]), toAdd, false); } /** @@ -175,14 +175,14 @@ final class LinkedPositionAnnotations extends AnnotationModel { if (position != null) linkedGroup= env.getGroupForPosition(position); - List targets= new ArrayList(); + List<Position> targets= new ArrayList<>(); targets.addAll(Arrays.asList(fTargets)); - List group; + List<Position> group; if (linkedGroup != null) - group= new ArrayList(Arrays.asList(linkedGroup.getPositions())); + group= new ArrayList<>(Arrays.asList(linkedGroup.getPositions())); else - group= new ArrayList(); + group= new ArrayList<>(); if (position == null || !fDocument.equals(position.getDocument())) // position is not valid if not in this document @@ -225,8 +225,8 @@ final class LinkedPositionAnnotations extends AnnotationModel { * * @param list the list of positions to prune */ - private void prune(List list) { - for (Iterator iter= list.iterator(); iter.hasNext();) { + private void prune(List<Position> list) { + for (Iterator<Position> iter= list.iterator(); iter.hasNext();) { LinkedPosition pos= (LinkedPosition) iter.next(); if (!pos.getDocument().equals(fDocument)) iter.remove(); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/link/TabStopIterator.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/link/TabStopIterator.java index e45acee3371..bfcdaea8922 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/link/TabStopIterator.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/link/TabStopIterator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -36,18 +36,10 @@ class TabStopIterator { * Comparator for <code>LinkedPosition</code>s. If the sequence number of two positions is equal, the * offset is used. */ - private static class SequenceComparator implements Comparator { - - /** - * {@inheritDoc} - * - * <p><code>o1</code> and <code>o2</code> are required to be instances - * of <code>LinkedPosition</code>.</p> - */ + private static class SequenceComparator implements Comparator<LinkedPosition> { + @Override - public int compare(Object o1, Object o2) { - LinkedPosition p1= (LinkedPosition)o1; - LinkedPosition p2= (LinkedPosition)o2; + public int compare(LinkedPosition p1, LinkedPosition p2) { int i= p1.getSequenceNumber() - p2.getSequenceNumber(); if (i != 0) return i; @@ -57,10 +49,10 @@ class TabStopIterator { } /** The comparator to sort the list of positions. */ - private static final Comparator fComparator= new SequenceComparator(); + private static final Comparator<LinkedPosition> fComparator= new SequenceComparator(); /** The iteration sequence. */ - private final ArrayList fList; + private final ArrayList<LinkedPosition> fList; /** The size of <code>fList</code>. */ private int fSize; /** Index of the current element, to the first one initially. */ @@ -68,9 +60,9 @@ class TabStopIterator { /** Cycling property. */ private boolean fIsCycling= false; - TabStopIterator(List positionSequence) { + TabStopIterator(List<LinkedPosition> positionSequence) { Assert.isNotNull(positionSequence); - fList= new ArrayList(positionSequence); + fList= new ArrayList<>(positionSequence); Collections.sort(fList, fComparator); fSize= fList.size(); fIndex= -1; @@ -113,8 +105,8 @@ class TabStopIterator { // find the position that follows closest to the current position LinkedPosition found= null; - for (Iterator it= fList.iterator(); it.hasNext(); ) { - LinkedPosition p= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= fList.iterator(); it.hasNext(); ) { + LinkedPosition p= it.next(); if (p.offset > current.offset) if (found == null || found.offset > p.offset) found= p; @@ -163,8 +155,8 @@ class TabStopIterator { // find the position that follows closest to the current position LinkedPosition found= null; - for (Iterator it= fList.iterator(); it.hasNext(); ) { - LinkedPosition p= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= fList.iterator(); it.hasNext(); ) { + LinkedPosition p= it.next(); if (p.offset < current.offset) if (found == null || found.offset < p.offset) found= p; @@ -180,20 +172,20 @@ class TabStopIterator { LinkedPosition next(LinkedPosition current) { if (!hasNext(current)) throw new NoSuchElementException(); - return (LinkedPosition) fList.get(fIndex= getNextIndex(current)); + return fList.get(fIndex= getNextIndex(current)); } LinkedPosition previous(LinkedPosition current) { if (!hasPrevious(current)) throw new NoSuchElementException(); - return (LinkedPosition) fList.get(fIndex= getPreviousIndex(current)); + return fList.get(fIndex= getPreviousIndex(current)); } void setCycling(boolean mode) { fIsCycling= mode; } - void addPosition(Position position) { + void addPosition(LinkedPosition position) { fList.add(fSize++, position); Collections.sort(fList, fComparator); } @@ -211,6 +203,6 @@ class TabStopIterator { } LinkedPosition[] getPositions() { - return (LinkedPosition[]) fList.toArray(new LinkedPosition[fSize]); + return fList.toArray(new LinkedPosition[fSize]); } } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/presentation/PresentationReconciler.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/presentation/PresentationReconciler.java index d530446456b..5fe6030a56f 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/presentation/PresentationReconciler.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/presentation/PresentationReconciler.java @@ -240,9 +240,9 @@ public class PresentationReconciler implements IPresentationReconciler, IPresent } /** The map of presentation damagers. */ - private Map fDamagers; + private Map<String, IPresentationDamager> fDamagers; /** The map of presentation repairers. */ - private Map fRepairers; + private Map<String, IPresentationRepairer> fRepairers; /** The target viewer. */ private ITextViewer fViewer; /** The internal listener. */ @@ -308,7 +308,7 @@ public class PresentationReconciler implements IPresentationReconciler, IPresent Assert.isNotNull(contentType); if (fDamagers == null) - fDamagers= new HashMap(); + fDamagers= new HashMap<>(); if (damager == null) fDamagers.remove(contentType); @@ -329,7 +329,7 @@ public class PresentationReconciler implements IPresentationReconciler, IPresent Assert.isNotNull(contentType); if (fRepairers == null) - fRepairers= new HashMap(); + fRepairers= new HashMap<>(); if (repairer == null) fRepairers.remove(contentType); @@ -363,7 +363,7 @@ public class PresentationReconciler implements IPresentationReconciler, IPresent if (fDamagers == null) return null; - return (IPresentationDamager) fDamagers.get(contentType); + return fDamagers.get(contentType); } @Override @@ -372,7 +372,7 @@ public class PresentationReconciler implements IPresentationReconciler, IPresent if (fRepairers == null) return null; - return (IPresentationRepairer) fRepairers.get(contentType); + return fRepairers.get(contentType); } /** @@ -382,9 +382,9 @@ public class PresentationReconciler implements IPresentationReconciler, IPresent */ protected void setDocumentToDamagers(IDocument document) { if (fDamagers != null) { - Iterator e= fDamagers.values().iterator(); + Iterator<IPresentationDamager> e= fDamagers.values().iterator(); while (e.hasNext()) { - IPresentationDamager damager= (IPresentationDamager) e.next(); + IPresentationDamager damager= e.next(); damager.setDocument(document); } } @@ -397,9 +397,9 @@ public class PresentationReconciler implements IPresentationReconciler, IPresent */ protected void setDocumentToRepairers(IDocument document) { if (fRepairers != null) { - Iterator e= fRepairers.values().iterator(); + Iterator<IPresentationRepairer> e= fRepairers.values().iterator(); while (e.hasNext()) { - IPresentationRepairer repairer= (IPresentationRepairer) e.next(); + IPresentationRepairer repairer= e.next(); repairer.setDocument(document); } } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconcileStep.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconcileStep.java index 111607fd63d..8e1fec14504 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconcileStep.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/AbstractReconcileStep.java @@ -132,9 +132,9 @@ public abstract class AbstractReconcileStep implements IReconcileStep { return results1; // XXX: not yet performance optimized - Collection collection= new ArrayList(Arrays.asList(results1)); + Collection<IReconcileResult> collection= new ArrayList<>(Arrays.asList(results1)); collection.addAll(Arrays.asList(results2)); - return (IReconcileResult[])collection.toArray(new IReconcileResult[collection.size()]); + return collection.toArray(new IReconcileResult[collection.size()]); } /* diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegionQueue.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegionQueue.java index bd0ff409802..abce516458f 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegionQueue.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/DirtyRegionQueue.java @@ -25,7 +25,7 @@ import java.util.List; class DirtyRegionQueue { /** The list of dirty regions. */ - private List fDirtyRegions= new ArrayList(); + private List<DirtyRegion> fDirtyRegions= new ArrayList<>(); /** * Creates a new empty dirty region. @@ -70,7 +70,7 @@ class DirtyRegionQueue { */ private DirtyRegion getLastDirtyRegion() { int size= fDirtyRegions.size(); - return (size == 0 ? null : (DirtyRegion) fDirtyRegions.get(size - 1)); + return (size == 0 ? null : fDirtyRegions.get(size - 1)); } /** @@ -97,7 +97,7 @@ class DirtyRegionQueue { public DirtyRegion removeNextDirtyRegion() { if (fDirtyRegions.size() == 0) return null; - DirtyRegion dr= (DirtyRegion) fDirtyRegions.get(0); + DirtyRegion dr= fDirtyRegions.get(0); fDirtyRegions.remove(0); return dr; } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/Reconciler.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/Reconciler.java index 4ff26dd2238..39ba8881cb5 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/Reconciler.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/reconciler/Reconciler.java @@ -44,7 +44,7 @@ import org.eclipse.jface.text.TypedRegion; public class Reconciler extends AbstractReconciler implements IReconcilerExtension { /** The map of reconciling strategies. */ - private Map fStrategies; + private Map<String, IReconcilingStrategy> fStrategies; /** * The partitioning this reconciler uses. @@ -92,7 +92,7 @@ public class Reconciler extends AbstractReconciler implements IReconcilerExtensi Assert.isNotNull(contentType); if (fStrategies == null) - fStrategies= new HashMap(); + fStrategies= new HashMap<>(); if (strategy == null) fStrategies.remove(contentType); @@ -113,7 +113,7 @@ public class Reconciler extends AbstractReconciler implements IReconcilerExtensi if (fStrategies == null) return null; - return (IReconcilingStrategy) fStrategies.get(contentType); + return fStrategies.get(contentType); } /** @@ -151,9 +151,9 @@ public class Reconciler extends AbstractReconciler implements IReconcilerExtensi @Override protected void reconcilerDocumentChanged(IDocument document) { if (fStrategies != null) { - Iterator e= fStrategies.values().iterator(); + Iterator<IReconcilingStrategy> e= fStrategies.values().iterator(); while (e.hasNext()) { - IReconcilingStrategy strategy= (IReconcilingStrategy) e.next(); + IReconcilingStrategy strategy= e.next(); strategy.setDocument(document); } } @@ -164,9 +164,9 @@ public class Reconciler extends AbstractReconciler implements IReconcilerExtensi super.setProgressMonitor(monitor); if (fStrategies != null) { - Iterator e= fStrategies.values().iterator(); + Iterator<IReconcilingStrategy> e= fStrategies.values().iterator(); while (e.hasNext()) { - IReconcilingStrategy strategy= (IReconcilingStrategy) e.next(); + IReconcilingStrategy strategy= e.next(); if (strategy instanceof IReconcilingStrategyExtension) { IReconcilingStrategyExtension extension= (IReconcilingStrategyExtension) strategy; extension.setProgressMonitor(monitor); @@ -178,7 +178,7 @@ public class Reconciler extends AbstractReconciler implements IReconcilerExtensi @Override protected void initialProcess() { ITypedRegion[] regions= computePartitioning(0, getDocument().getLength()); - List contentTypes= new ArrayList(regions.length); + List<String> contentTypes= new ArrayList<>(regions.length); for (int i= 0; i < regions.length; i++) { String contentType= regions[i].getType(); if( contentTypes.contains(contentType)) diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/Revision.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/Revision.java index 9765150f933..9a69d52642d 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/Revision.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/Revision.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -20,6 +20,7 @@ import org.eclipse.swt.graphics.RGB; import org.eclipse.jface.internal.text.revisions.ChangeRegion; import org.eclipse.jface.internal.text.revisions.Hunk; +import org.eclipse.jface.internal.text.revisions.Range; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.source.ILineRange; @@ -33,15 +34,15 @@ import org.eclipse.jface.text.source.ILineRange; * @since 3.2 */ public abstract class Revision { - /** The original list of change regions, element type: {@link ChangeRegion}. */ - private final List fChangeRegions= new ArrayList(); + /** The original list of change regions. */ + private final List<ChangeRegion> fChangeRegions= new ArrayList<>(); /** - * The cached list of adjusted ranges, element type: {@link RevisionRange}. <code>null</code> + * The cached list of adjusted ranges. <code>null</code> * if the list must be re-computed. Unmodifiable. * * @since 3.3 */ - private List fRanges= null; + private List<RevisionRange> fRanges= null; /** * Creates a new revision. @@ -65,15 +66,15 @@ public abstract class Revision { * information is only valid at the moment it is returned, and may change as the annotated * document is modified. * - * @return an unmodifiable view of the contained ranges (element type: {@link RevisionRange}) + * @return an unmodifiable view of the contained ranges */ - public final List getRegions() { + public final List<RevisionRange> getRegions() { if (fRanges == null) { - List ranges= new ArrayList(fChangeRegions.size()); - for (Iterator it= fChangeRegions.iterator(); it.hasNext();) { - ChangeRegion region= (ChangeRegion) it.next(); - for (Iterator inner= region.getAdjustedRanges().iterator(); inner.hasNext();) { - ILineRange range= (ILineRange) inner.next(); + List<RevisionRange> ranges= new ArrayList<>(fChangeRegions.size()); + for (Iterator<ChangeRegion> it= fChangeRegions.iterator(); it.hasNext();) { + ChangeRegion region= it.next(); + for (Iterator<Range> inner= region.getAdjustedRanges().iterator(); inner.hasNext();) { + ILineRange range= inner.next(); ranges.add(new RevisionRange(this, range)); } } @@ -91,8 +92,8 @@ public abstract class Revision { */ final void applyDiff(Hunk[] hunks) { fRanges= null; // mark for recomputation - for (Iterator regions= fChangeRegions.iterator(); regions.hasNext();) { - ChangeRegion region= (ChangeRegion) regions.next(); + for (Iterator<ChangeRegion> regions= fChangeRegions.iterator(); regions.hasNext();) { + ChangeRegion region= regions.next(); region.clearDiff(); for (int i= 0; i < hunks.length; i++) { Hunk hunk= hunks[i]; diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/RevisionInformation.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/RevisionInformation.java index 42f04a2bed8..aaf5656c653 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/RevisionInformation.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/revisions/RevisionInformation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,7 +12,6 @@ package org.eclipse.jface.text.revisions; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.Iterator; import java.util.List; @@ -34,17 +33,17 @@ import org.eclipse.jface.text.information.IInformationProviderExtension2; * @see Revision */ public final class RevisionInformation implements ITextHoverExtension, IInformationProviderExtension2 { - /** The revisions, element type: {@link Revision}. */ - private final List fRevisions= new ArrayList(); + /** The revisions. */ + private final List<Revision> fRevisions= new ArrayList<>(); /** A unmodifiable view of <code>fRevisions</code>. */ - private final List fRORevisions= Collections.unmodifiableList(fRevisions); + private final List<Revision> fRORevisions= Collections.unmodifiableList(fRevisions); /** * The flattened list of {@link RevisionRange}s, unmodifiable. <code>null</code> if the list * must be re-computed. * * @since 3.3 */ - private List fRanges= null; + private List<RevisionRange> fRanges= null; /** * The hover control creator. Can be <code>null</code>. @@ -79,9 +78,9 @@ public final class RevisionInformation implements ITextHoverExtension, IInformat /** * Returns the contained revisions. * - * @return an unmodifiable view of the contained revisions (element type: {@link Revision}) + * @return an unmodifiable view of the contained revisions */ - public List getRevisions() { + public List<Revision> getRevisions() { return fRORevisions; } @@ -91,28 +90,20 @@ public final class RevisionInformation implements ITextHoverExtension, IInformat * {@link IRevisionListener} for a way to be informed when the revision information changes. The * returned list is sorted by document offset. * - * @return an unmodifiable view of the line ranges (element type: {@link RevisionRange}) + * @return an unmodifiable view of the line ranges * @see IRevisionListener * @since 3.3 */ - public List getRanges() { + public List<RevisionRange> getRanges() { if (fRanges == null) { - List ranges= new ArrayList(fRevisions.size() * 2); // wild size guess - for (Iterator it= fRevisions.iterator(); it.hasNext();) { - Revision revision= (Revision) it.next(); + List<RevisionRange> ranges= new ArrayList<>(fRevisions.size() * 2); // wild size guess + for (Iterator<Revision> it= fRevisions.iterator(); it.hasNext();) { + Revision revision= it.next(); ranges.addAll(revision.getRegions()); } // sort by start line - Collections.sort(ranges, new Comparator() { - @Override - public int compare(Object o1, Object o2) { - RevisionRange r1= (RevisionRange) o1; - RevisionRange r2= (RevisionRange) o2; - - return r1.getStartLine() - r2.getStartLine(); - } - }); + Collections.sort(ranges, (r1, r2) -> r1.getStartLine() - r2.getStartLine()); fRanges= Collections.unmodifiableList(ranges); } @@ -130,8 +121,8 @@ public final class RevisionInformation implements ITextHoverExtension, IInformat */ public void applyDiff(Hunk[] hunks) { fRanges= null; // mark for recomputation - for (Iterator revisions= getRevisions().iterator(); revisions.hasNext();) - ((Revision) revisions.next()).applyDiff(hunks); + for (Iterator<Revision> revisions= getRevisions().iterator(); revisions.hasNext();) + revisions.next().applyDiff(hunks); } @Override diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/DefaultPartitioner.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/DefaultPartitioner.java index 210e6bacddb..7c8cdb1e2a4 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/DefaultPartitioner.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/DefaultPartitioner.java @@ -537,7 +537,7 @@ public class DefaultPartitioner implements IDocumentPartitioner, IDocumentPartit @Override public ITypedRegion[] computePartitioning(int offset, int length, boolean includeZeroLengthPartitions) { checkInitialization(); - List list= new ArrayList(); + List<TypedRegion> list= new ArrayList<>(); try { diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/FastPartitioner.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/FastPartitioner.java index cb2937ec8a5..63e5251ec81 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/FastPartitioner.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/FastPartitioner.java @@ -613,7 +613,7 @@ public class FastPartitioner implements IDocumentPartitioner, IDocumentPartition @Override public ITypedRegion[] computePartitioning(int offset, int length, boolean includeZeroLengthPartitions) { checkInitialization(); - List list= new ArrayList(); + List<TypedRegion> list= new ArrayList<>(); try { diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/PatternRule.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/PatternRule.java index bb9ffa87090..4f8cf94120f 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/PatternRule.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/PatternRule.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -33,10 +33,10 @@ public class PatternRule implements IPredicateRule { * * @since 3.1 */ - private static class DecreasingCharArrayLengthComparator implements Comparator { + private static class DecreasingCharArrayLengthComparator implements Comparator<char[]> { @Override - public int compare(Object o1, Object o2) { - return ((char[]) o2).length - ((char[]) o1).length; + public int compare(char[] o1, char[] o2) { + return o2.length - o1.length; } } @@ -67,7 +67,7 @@ public class PatternRule implements IPredicateRule { * Line delimiter comparator which orders according to decreasing delimiter length. * @since 3.1 */ - private Comparator fLineDelimiterComparator= new DecreasingCharArrayLengthComparator(); + private Comparator<char[]> fLineDelimiterComparator= new DecreasingCharArrayLengthComparator(); /** * Cached line delimiters. * @since 3.1 diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/RuleBasedPartitioner.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/RuleBasedPartitioner.java index e6150e68f0b..2d0303f3607 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/RuleBasedPartitioner.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/RuleBasedPartitioner.java @@ -528,7 +528,7 @@ public class RuleBasedPartitioner implements IDocumentPartitioner, IDocumentPart @Override public ITypedRegion[] computePartitioning(int offset, int length, boolean includeZeroLengthPartitions) { - List list= new ArrayList(); + List<TypedRegion> list= new ArrayList<>(); try { diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/WordRule.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/WordRule.java index 12ec542a543..d091e18d60b 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/WordRule.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/rules/WordRule.java @@ -37,7 +37,7 @@ public class WordRule implements IRule { /** The column constraint. */ protected int fColumn= UNDEFINED; /** The table of predefined words and token for this rule. */ - protected Map fWords= new HashMap(); + protected Map<String, IToken> fWords= new HashMap<>(); /** Buffer used for pattern detection. */ private StringBuffer fBuffer= new StringBuffer(); /** @@ -143,7 +143,7 @@ public class WordRule implements IRule { if (fIgnoreCase) buffer= buffer.toLowerCase(); - IToken token= (IToken)fWords.get(buffer); + IToken token= fWords.get(buffer); if (token != null) return token; diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationBarHoverManager.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationBarHoverManager.java index 760b2b6ed7c..3b96efa606a 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationBarHoverManager.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationBarHoverManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -540,7 +540,7 @@ public class AnnotationBarHoverManager extends AbstractHoverInformationControlMa if (fVerticalRulerInfo instanceof CompositeRuler) { CompositeRuler comp= (CompositeRuler) fVerticalRulerInfo; - for (Iterator it= comp.getDecoratorIterator(); it.hasNext();) { + for (Iterator<IVerticalRulerColumn> it= comp.getDecoratorIterator(); it.hasNext();) { Object o= it.next(); if (o instanceof IVerticalRulerInfoExtension && o instanceof IVerticalRulerInfo) { if (((IVerticalRulerInfo) o).getControl() == event.getSource()) { diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java index b1361603e23..ef1addf1982 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationPainter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -18,8 +18,8 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; -import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import org.eclipse.swt.SWT; @@ -355,12 +355,12 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo * The map with decorations * @since 3.0 */ - private Map fDecorationsMap= new HashMap(); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=50767 + private Map<Annotation, Decoration> fDecorationsMap= new HashMap<>(); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=50767 /** * The map with of highlighted decorations. * @since 3.0 */ - private Map fHighlightedDecorationsMap= new HashMap(); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=50767 + private Map<Annotation, Decoration> fHighlightedDecorationsMap= new HashMap<>(); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=50767 /** * Mutex for highlighted decorations map. * @since 3.0 @@ -376,13 +376,13 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo * * @see #setAnnotationTypeColor(Object, Color) */ - private Map fAnnotationType2Color= new HashMap(); + private Map<Object, Color> fAnnotationType2Color= new HashMap<>(); /** * Cache that maps the annotation type to its color. * @since 3.4 */ - private Map fCachedAnnotationType2Color= new HashMap(); + private Map<Object, Color> fCachedAnnotationType2Color= new HashMap<>(); /** * The range in which the current highlight annotations can be found. * @since 3.0 @@ -421,19 +421,19 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo * @see #addAnnotationType(Object, Object) * @since 3.0 */ - private Map fAnnotationType2PaintingStrategyId= new HashMap(); + private Map<Object, Object> fAnnotationType2PaintingStrategyId= new HashMap<>(); /** * Maps annotation types to painting strategy identifiers. * @since 3.4 */ - private Map fCachedAnnotationType2PaintingStrategy= new HashMap(); + private Map<String, Object> fCachedAnnotationType2PaintingStrategy= new HashMap<>(); /** * Maps painting strategy identifiers to painting strategies. * * @since 3.0 */ - private Map fPaintingStrategyId2PaintingStrategy= new HashMap(); + private Map<Object, Object> fPaintingStrategyId2PaintingStrategy= new HashMap<>(); /** * Reuse this region for performance reasons. @@ -552,31 +552,31 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo int drawRangeStart= Integer.MAX_VALUE; int drawRangeEnd= -1; - Map decorationsMap; - Map highlightedDecorationsMap; + Map<Annotation, Decoration> decorationsMap; + Map<Annotation, Decoration> highlightedDecorationsMap; // Clone decoration maps synchronized (fDecorationMapLock) { - decorationsMap= new HashMap(fDecorationsMap); + decorationsMap= new HashMap<>(fDecorationsMap); } synchronized (fHighlightedDecorationsMapLock) { - highlightedDecorationsMap= new HashMap(fHighlightedDecorationsMap); + highlightedDecorationsMap= new HashMap<>(fHighlightedDecorationsMap); } boolean isWorldChange= false; - Iterator e; + Iterator<Annotation> e; if (event == null || event.isWorldChange()) { isWorldChange= true; if (DEBUG && event == null) System.out.println("AP: INTERNAL CHANGE"); //$NON-NLS-1$ - Iterator iter= decorationsMap.entrySet().iterator(); + Iterator<Entry<Annotation, Decoration>> iter= decorationsMap.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry entry= (Map.Entry)iter.next(); - Annotation annotation= (Annotation)entry.getKey(); - Decoration decoration= (Decoration)entry.getValue(); + Entry<Annotation, Decoration> entry= iter.next(); + Annotation annotation= entry.getKey(); + Decoration decoration= entry.getValue(); drawDecoration(decoration, null, annotation, clippingRegion, document); } @@ -593,7 +593,7 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo Annotation[] removedAnnotations= event.getRemovedAnnotations(); for (int i= 0, length= removedAnnotations.length; i < length; i++) { Annotation annotation= removedAnnotations[i]; - Decoration decoration= (Decoration)highlightedDecorationsMap.remove(annotation); + Decoration decoration= highlightedDecorationsMap.remove(annotation); if (decoration != null) { Position position= decoration.fPosition; if (position != null) { @@ -601,7 +601,7 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, position.offset + position.length); } } - decoration= (Decoration)decorationsMap.remove(annotation); + decoration= decorationsMap.remove(annotation); if (decoration != null) { drawDecoration(decoration, null, annotation, clippingRegion, document); Position position= decoration.fPosition; @@ -620,14 +620,14 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo boolean isHighlighting= false; - Decoration decoration= (Decoration)highlightedDecorationsMap.get(annotation); + Decoration decoration= highlightedDecorationsMap.get(annotation); if (decoration != null) { isHighlighting= true; // The call below updates the decoration - no need to create new decoration decoration= getDecoration(annotation, decoration); if (decoration == null) { - Decoration removedDecoration= (Decoration)highlightedDecorationsMap.remove(annotation); + Decoration removedDecoration= highlightedDecorationsMap.remove(annotation); if (removedDecoration != null) { highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, removedDecoration.fPosition.offset); highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, removedDecoration.fPosition.offset + removedDecoration.fPosition.length); @@ -660,7 +660,7 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo drawRangeEnd= Math.max(drawRangeEnd, position.offset + position.length); } } else { - Decoration removedDecoration= (Decoration)highlightedDecorationsMap.remove(annotation); + Decoration removedDecoration= highlightedDecorationsMap.remove(annotation); if (removedDecoration != null) { highlightAnnotationRangeStart= Math.min(highlightAnnotationRangeStart, removedDecoration.fPosition.offset); highlightAnnotationRangeEnd= Math.max(highlightAnnotationRangeEnd, removedDecoration.fPosition.offset + removedDecoration.fPosition.length); @@ -668,7 +668,7 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo } if (usesDrawingStrategy) { - Decoration oldDecoration= (Decoration)decorationsMap.get(annotation); + Decoration oldDecoration= decorationsMap.get(annotation); if (oldDecoration != null) { drawDecoration(oldDecoration, null, annotation, clippingRegion, document); if (decoration != null) @@ -684,7 +684,7 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo // Add new annotations while (e.hasNext()) { - Annotation annotation= (Annotation)e.next(); + Annotation annotation= e.next(); Decoration pp= getDecoration(annotation, null); if (pp != null) { if (pp.fPaintingStrategy instanceof IDrawingStrategy) { @@ -910,11 +910,11 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo * @since 3.0 */ private Color getColor(final Object annotationType) { - Color color= (Color)fCachedAnnotationType2Color.get(annotationType); + Color color= fCachedAnnotationType2Color.get(annotationType); if (color != null) return color; - color= (Color)fAnnotationType2Color.get(annotationType); + color= fAnnotationType2Color.get(annotationType); if (color != null) { fCachedAnnotationType2Color.put(annotationType, color); return color; @@ -925,7 +925,7 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo Object[] superTypes= extension.getSupertypes(annotationType); if (superTypes != null) { for (int i= 0; i < superTypes.length; i++) { - color= (Color)fAnnotationType2Color.get(superTypes[i]); + color= fAnnotationType2Color.get(superTypes[i]); if (color != null) { fCachedAnnotationType2Color.put(annotationType, color); return color; @@ -976,13 +976,13 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo @Override public void applyTextPresentation(TextPresentation tp) { - Set decorations; + Set<Entry<Annotation, Decoration>> decorations; synchronized (fHighlightedDecorationsMapLock) { if (fHighlightedDecorationsMap == null || fHighlightedDecorationsMap.isEmpty()) return; - decorations= new HashSet(fHighlightedDecorationsMap.entrySet()); + decorations= new HashSet<>(fHighlightedDecorationsMap.entrySet()); } IRegion region= tp.getExtent(); @@ -992,14 +992,14 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo for (int layer= 0, maxLayer= 1; layer < maxLayer; layer++) { - for (Iterator iter= decorations.iterator(); iter.hasNext();) { - Map.Entry entry= (Map.Entry)iter.next(); + for (Iterator<Entry<Annotation, Decoration>> iter= decorations.iterator(); iter.hasNext();) { + Entry<Annotation, Decoration> entry= iter.next(); - Annotation a= (Annotation)entry.getKey(); + Annotation a= entry.getKey(); if (a.isMarkedDeleted()) continue; - Decoration pp = (Decoration)entry.getValue(); + Decoration pp = entry.getValue(); maxLayer= Math.max(maxLayer, pp.fLayer + 1); // dynamically update layer maximum if (pp.fLayer != layer) // wrong layer: skip annotation @@ -1362,9 +1362,9 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo final GC gc= event != null ? event.gc : null; // Clone decorations - Collection decorations; + Collection<Entry<Annotation, Decoration>> decorations; synchronized (fDecorationMapLock) { - decorations= new ArrayList(fDecorationsMap.size()); + decorations= new ArrayList<>(fDecorationsMap.size()); decorations.addAll(fDecorationsMap.entrySet()); } @@ -1372,27 +1372,27 @@ public class AnnotationPainter implements IPainter, PaintListener, IAnnotationMo * Create a new list of annotations to be drawn, since removing from decorations is more * expensive. One bucket per drawing layer. Use linked lists as addition is cheap here. */ - ArrayList toBeDrawn= new ArrayList(10); - for (Iterator e = decorations.iterator(); e.hasNext();) { - Map.Entry entry= (Map.Entry)e.next(); + ArrayList<LinkedList<Entry<Annotation, Decoration>>> toBeDrawn= new ArrayList<>(10); + for (Iterator<Entry<Annotation, Decoration>> e = decorations.iterator(); e.hasNext();) { + Entry<Annotation, Decoration> entry= e.next(); - Annotation a= (Annotation)entry.getKey(); - Decoration pp = (Decoration)entry.getValue(); + Annotation a= entry.getKey(); + Decoration pp = entry.getValue(); // prune any annotation that is not drawable or does not need drawing if (!(a.isMarkedDeleted() || skip(a) || !regionsTouchOrOverlap(pp.fPosition.getOffset(), pp.fPosition.getLength(), vOffset, vLength))) { // ensure sized appropriately for (int i= toBeDrawn.size(); i <= pp.fLayer; i++) - toBeDrawn.add(new LinkedList()); - ((List) toBeDrawn.get(pp.fLayer)).add(entry); + toBeDrawn.add(new LinkedList<>()); + toBeDrawn.get(pp.fLayer).add(entry); } } IDocument document= fSourceViewer.getDocument(); - for (Iterator it= toBeDrawn.iterator(); it.hasNext();) { - List layer= (List) it.next(); - for (Iterator e = layer.iterator(); e.hasNext();) { - Map.Entry entry= (Map.Entry)e.next(); - Annotation a= (Annotation)entry.getKey(); - Decoration pp = (Decoration)entry.getValue(); + for (Iterator<LinkedList<Entry<Annotation, Decoration>>> it= toBeDrawn.iterator(); it.hasNext();) { + LinkedList<Entry<Annotation, Decoration>> layer= it.next(); + for (Iterator<Entry<Annotation, Decoration>> e = layer.iterator(); e.hasNext();) { + Entry<Annotation, Decoration> entry= e.next(); + Annotation a= entry.getKey(); + Decoration pp = entry.getValue(); drawDecoration(pp, gc, a, clippingRegion, document); } } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationRulerColumn.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationRulerColumn.java index 3673751fa0b..0e3472bedc0 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationRulerColumn.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/AnnotationRulerColumn.java @@ -115,11 +115,11 @@ public class AnnotationRulerColumn implements IVerticalRulerColumn, IVerticalRul * Comparator for <code>Tuple</code>s. * @since 3.0 */ - private static class TupleComparator implements Comparator { + private static class TupleComparator implements Comparator<Tuple> { @Override - public int compare(Object o1, Object o2) { - Position p1= ((Tuple) o1).position; - Position p2= ((Tuple) o2).position; + public int compare(Tuple o1, Tuple o2) { + Position p1= o1.position; + Position p2= o2.position; return p1.getOffset() - p2.getOffset(); } } @@ -148,14 +148,14 @@ public class AnnotationRulerColumn implements IVerticalRulerColumn, IVerticalRul * The list of annotation types to be shown in this ruler. * @since 3.0 */ - private Set fConfiguredAnnotationTypes= new HashSet(); + private Set<Object> fConfiguredAnnotationTypes= new HashSet<>(); /** * The list of allowed annotation types to be shown in this ruler. * An allowed annotation type maps to <code>true</code>, a disallowed * to <code>false</code>. * @since 3.0 */ - private Map fAllowedAnnotationTypes= new HashMap(); + private Map<Object, Boolean> fAllowedAnnotationTypes= new HashMap<>(); /** * The annotation access extension. * @since 3.0 @@ -170,12 +170,12 @@ public class AnnotationRulerColumn implements IVerticalRulerColumn, IVerticalRul * The cached annotations. * @since 3.0 */ - private List fCachedAnnotations= new ArrayList(); + private List<Tuple> fCachedAnnotations= new ArrayList<>(); /** * The comparator for sorting annotations according to the offset of their position. * @since 3.0 */ - private Comparator fTupleComparator= new TupleComparator(); + private Comparator<Tuple> fTupleComparator= new TupleComparator(); /** * The hit detection cursor. Do not dispose. * @since 3.0 @@ -474,14 +474,14 @@ public class AnnotationRulerColumn implements IVerticalRulerColumn, IVerticalRul int lineStart= line.getOffset(); int lineLength= line.getLength(); - Iterator e; + Iterator<Annotation> e; if (fModel instanceof IAnnotationModelExtension2) e= ((IAnnotationModelExtension2)fModel).getAnnotationIterator(lineStart, lineLength + 1, true, true); else e= model.getAnnotationIterator(); while (e.hasNext()) { - Annotation a= (Annotation) e.next(); + Annotation a= e.next(); if (a.isMarkedDeleted()) continue; @@ -646,14 +646,14 @@ public class AnnotationRulerColumn implements IVerticalRulerColumn, IVerticalRul int maxLayer= 1; // loop at least once through layers. for (int layer= 0; layer < maxLayer; layer++) { - Iterator iter; + Iterator<Annotation> iter; if (fModel instanceof IAnnotationModelExtension2) iter= ((IAnnotationModelExtension2)fModel).getAnnotationIterator(topLeft, viewPort + 1, true, true); else iter= fModel.getAnnotationIterator(); while (iter.hasNext()) { - Annotation annotation= (Annotation) iter.next(); + Annotation annotation= iter.next(); int lay= IAnnotationAccessExtension.DEFAULT_LAYER; if (fAnnotationAccessExtension != null) @@ -736,14 +736,14 @@ public class AnnotationRulerColumn implements IVerticalRulerColumn, IVerticalRul int minLayer= Integer.MAX_VALUE, maxLayer= Integer.MIN_VALUE; fCachedAnnotations.clear(); - Iterator iter; + Iterator<Annotation> iter; if (fModel instanceof IAnnotationModelExtension2) iter= ((IAnnotationModelExtension2)fModel).getAnnotationIterator(vOffset, vLength + 1, true, true); else iter= fModel.getAnnotationIterator(); while (iter.hasNext()) { - Annotation annotation= (Annotation) iter.next(); + Annotation annotation= iter.next(); if (skip(annotation)) continue; @@ -769,7 +769,7 @@ public class AnnotationRulerColumn implements IVerticalRulerColumn, IVerticalRul for (int layer= minLayer; layer <= maxLayer; layer++) { for (int i= 0, n= fCachedAnnotations.size(); i < n; i++) { - Tuple tuple= (Tuple) fCachedAnnotations.get(i); + Tuple tuple= fCachedAnnotations.get(i); Annotation annotation= tuple.annotation; Position position= tuple.position; @@ -924,7 +924,7 @@ public class AnnotationRulerColumn implements IVerticalRulerColumn, IVerticalRul */ private boolean skip(Annotation annotation) { Object annotationType= annotation.getType(); - Boolean allowed= (Boolean) fAllowedAnnotationTypes.get(annotationType); + Boolean allowed= fAllowedAnnotationTypes.get(annotationType); if (allowed != null) return !allowed.booleanValue(); @@ -944,7 +944,7 @@ public class AnnotationRulerColumn implements IVerticalRulerColumn, IVerticalRul */ private boolean skip(Object annotationType) { if (fAnnotationAccessExtension != null) { - Iterator e= fConfiguredAnnotationTypes.iterator(); + Iterator<Object> e= fConfiguredAnnotationTypes.iterator(); while (e.hasNext()) { if (fAnnotationAccessExtension.isSubtype(annotationType, e.next())) return false; diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/CompositeRuler.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/CompositeRuler.java index fca69ff52fb..4b62c5870d1 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/CompositeRuler.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/CompositeRuler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -102,9 +102,9 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, int rulerHeight= clArea.height; int x= 0; - Iterator e= fDecorators.iterator(); + Iterator<IVerticalRulerColumn> e= fDecorators.iterator(); while (e.hasNext()) { - IVerticalRulerColumn column= (IVerticalRulerColumn) e.next(); + IVerticalRulerColumn column= e.next(); int columnWidth= column.getWidth(); column.getControl().setBounds(x, 0, columnWidth, rulerHeight); x += (columnWidth + fGap); @@ -122,12 +122,12 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, * Keeps the information for which event type a listener object has been added. */ static class ListenerInfo { - Class fClass; + Class<? extends EventListener> fClass; EventListener fListener; } /** The list of listeners added to this canvas. */ - private List fCachedListeners= new ArrayList(); + private List<ListenerInfo> fCachedListeners= new ArrayList<>(); /** * Internal listener for opening the context menu. * @since 3.0 @@ -173,7 +173,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, * @param control the control to add the listener to * @param listener the listener to be added */ - private void addListener(Class clazz, Control control, EventListener listener) { + private void addListener(Class<? extends EventListener> clazz, Control control, EventListener listener) { if (ControlListener.class.equals(clazz)) { control. addControlListener((ControlListener) listener); return; @@ -228,7 +228,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, * @param control the control to remove the listener from * @param listener the listener to be removed */ - private void removeListener(Class clazz, Control control, EventListener listener) { + private void removeListener(Class<? extends EventListener> clazz, Control control, EventListener listener) { if (ControlListener.class.equals(clazz)) { control. removeControlListener((ControlListener) listener); return; @@ -278,7 +278,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, * @param clazz the listener type * @param listener the listener object */ - private void addListener(Class clazz, EventListener listener) { + private void addListener(Class<? extends EventListener> clazz, EventListener listener) { Control[] children= getChildren(); for (int i= 0; i < children.length; i++) { if (children[i] != null && !children[i].isDisposed()) @@ -298,7 +298,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, * @param clazz the listener type * @param listener the listener object */ - private void removeListener(Class clazz, EventListener listener) { + private void removeListener(Class<? extends EventListener> clazz, EventListener listener) { // Keep as first statement to ensure checkWidget() is called. Control[] children= getChildren(); @@ -307,7 +307,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, int length= fCachedListeners.size(); for (int i= 0; i < length; i++) { - ListenerInfo info= (ListenerInfo) fCachedListeners.get(i); + ListenerInfo info= fCachedListeners.get(i); if (listener == info.fListener && clazz.equals(info.fClass)) { fCachedListeners.remove(i); break; @@ -329,7 +329,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, if (child != null && !child.isDisposed()) { int length= fCachedListeners.size(); for (int i= 0; i < length; i++) { - ListenerInfo info= (ListenerInfo) fCachedListeners.get(i); + ListenerInfo info= fCachedListeners.get(i); addListener(info.fClass, child, info.fListener); } child.addListener(SWT.MenuDetect, fMenuDetectListener); @@ -345,7 +345,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, if (child != null && !child.isDisposed()) { int length= fCachedListeners.size(); for (int i= 0; i < length; i++) { - ListenerInfo info= (ListenerInfo) fCachedListeners.get(i); + ListenerInfo info= fCachedListeners.get(i); removeListener(info.fClass, child, info.fListener); } child.removeListener(SWT.MenuDetect, fMenuDetectListener); @@ -498,7 +498,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, /** The ruler's annotation model */ private IAnnotationModel fModel; /** The list of columns */ - private List fDecorators= new ArrayList(2); + private List<IVerticalRulerColumn> fDecorators= new ArrayList<>(2); /** The cached location of the last mouse button activity */ private Point fLocation= new Point(-1, -1); /** The cached line of the list mouse button activity */ @@ -509,7 +509,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, * The set of annotation listeners. * @since 3.0 */ - private Set fAnnotationListeners= new HashSet(); + private Set<IVerticalRulerListener> fAnnotationListeners= new HashSet<>(); /** @@ -556,7 +556,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, * @param index the index */ public void removeDecorator(int index) { - IVerticalRulerColumn rulerColumn= (IVerticalRulerColumn) fDecorators.get(index); + IVerticalRulerColumn rulerColumn= fDecorators.get(index); removeDecorator(rulerColumn); } @@ -608,9 +608,9 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, fComposite= new CompositeRulerCanvas(parent, SWT.NONE); fComposite.setLayout(new RulerLayout()); - Iterator iter= fDecorators.iterator(); + Iterator<IVerticalRulerColumn> iter= fDecorators.iterator(); while (iter.hasNext()) { - IVerticalRulerColumn column= (IVerticalRulerColumn) iter.next(); + IVerticalRulerColumn column= iter.next(); column.createControl(this, fComposite); fComposite.childAdded(column.getControl()); } @@ -623,9 +623,9 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, fModel= model; - Iterator e= fDecorators.iterator(); + Iterator<IVerticalRulerColumn> e= fDecorators.iterator(); while (e.hasNext()) { - IVerticalRulerColumn column= (IVerticalRulerColumn) e.next(); + IVerticalRulerColumn column= e.next(); column.setModel(model); } } @@ -656,18 +656,18 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, * @since 3.2 */ public void immediateUpdate() { - Iterator e= fDecorators.iterator(); + Iterator<IVerticalRulerColumn> e= fDecorators.iterator(); while (e.hasNext()) { - IVerticalRulerColumn column= (IVerticalRulerColumn) e.next(); + IVerticalRulerColumn column= e.next(); column.redraw(); } } @Override public void setFont(Font font) { - Iterator e= fDecorators.iterator(); + Iterator<IVerticalRulerColumn> e= fDecorators.iterator(); while (e.hasNext()) { - IVerticalRulerColumn column= (IVerticalRulerColumn) e.next(); + IVerticalRulerColumn column= e.next(); column.setFont(font); } } @@ -675,9 +675,9 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, @Override public int getWidth() { int width= 0; - Iterator e= fDecorators.iterator(); + Iterator<IVerticalRulerColumn> e= fDecorators.iterator(); while (e.hasNext()) { - IVerticalRulerColumn column= (IVerticalRulerColumn) e.next(); + IVerticalRulerColumn column= e.next(); width += (column.getWidth() + fGap); } return Math.max(0, width - fGap); @@ -757,7 +757,7 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, * @return an iterator over the contained columns. * @since 3.0 */ - public Iterator getDecoratorIterator() { + public Iterator<IVerticalRulerColumn> getDecoratorIterator() { Assert.isNotNull(fDecorators, "fDecorators must be initialized"); //$NON-NLS-1$ return fDecorators.iterator(); } @@ -787,8 +787,8 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, */ public void fireAnnotationSelected(VerticalRulerEvent event) { // forward to listeners - for (Iterator it= fAnnotationListeners.iterator(); it.hasNext();) { - IVerticalRulerListener listener= (IVerticalRulerListener) it.next(); + for (Iterator<IVerticalRulerListener> it= fAnnotationListeners.iterator(); it.hasNext();) { + IVerticalRulerListener listener= it.next(); listener.annotationSelected(event); } } @@ -803,8 +803,8 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, */ public void fireAnnotationDefaultSelected(VerticalRulerEvent event) { // forward to listeners - for (Iterator it= fAnnotationListeners.iterator(); it.hasNext();) { - IVerticalRulerListener listener= (IVerticalRulerListener) it.next(); + for (Iterator<IVerticalRulerListener> it= fAnnotationListeners.iterator(); it.hasNext();) { + IVerticalRulerListener listener= it.next(); listener.annotationDefaultSelected(event); } } @@ -820,8 +820,8 @@ public class CompositeRuler implements IVerticalRuler, IVerticalRulerExtension, */ public void fireAnnotationContextMenuAboutToShow(VerticalRulerEvent event, Menu menu) { // forward to listeners - for (Iterator it= fAnnotationListeners.iterator(); it.hasNext();) { - IVerticalRulerListener listener= (IVerticalRulerListener) it.next(); + for (Iterator<IVerticalRulerListener> it= fAnnotationListeners.iterator(); it.hasNext();) { + IVerticalRulerListener listener= it.next(); listener.annotationContextMenuAboutToShow(event, menu); } } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultAnnotationHover.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultAnnotationHover.java index ade74e15b50..9a83dd09149 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultAnnotationHover.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/DefaultAnnotationHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2011 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -58,31 +58,31 @@ public class DefaultAnnotationHover implements IAnnotationHover { @Override public String getHoverInfo(ISourceViewer sourceViewer, int lineNumber) { - List javaAnnotations= getAnnotationsForLine(sourceViewer, lineNumber); + List<Annotation> javaAnnotations= getAnnotationsForLine(sourceViewer, lineNumber); if (javaAnnotations != null) { if (javaAnnotations.size() == 1) { // optimization - Annotation annotation= (Annotation) javaAnnotations.get(0); + Annotation annotation= javaAnnotations.get(0); String message= annotation.getText(); if (message != null && message.trim().length() > 0) return formatSingleMessage(message); } else { - List messages= new ArrayList(); + List<String> messages= new ArrayList<>(); - Iterator e= javaAnnotations.iterator(); + Iterator<Annotation> e= javaAnnotations.iterator(); while (e.hasNext()) { - Annotation annotation= (Annotation) e.next(); + Annotation annotation= e.next(); String message= annotation.getText(); if (message != null && message.trim().length() > 0) messages.add(message.trim()); } if (messages.size() == 1) - return formatSingleMessage((String)messages.get(0)); + return formatSingleMessage(messages.get(0)); if (messages.size() > 1) return formatMultipleMessages(messages); @@ -127,17 +127,17 @@ public class DefaultAnnotationHover implements IAnnotationHover { * format like HTML. * </p> * - * @param messages the messages to format (element type: {@link String}) + * @param messages the messages to format * @return the formatted message */ - protected String formatMultipleMessages(List messages) { + protected String formatMultipleMessages(List<String> messages) { StringBuffer buffer= new StringBuffer(); buffer.append(JFaceTextMessages.getString("DefaultAnnotationHover.multipleMarkers")); //$NON-NLS-1$ - Iterator e= messages.iterator(); + Iterator<String> e= messages.iterator(); while (e.hasNext()) { buffer.append('\n'); - String listItemText= (String) e.next(); + String listItemText= e.next(); buffer.append(JFaceTextMessages.getFormattedString("DefaultAnnotationHover.listItem", new String[] { listItemText })); //$NON-NLS-1$ } return buffer.toString(); @@ -161,20 +161,21 @@ public class DefaultAnnotationHover implements IAnnotationHover { return viewer.getAnnotationModel(); } - private boolean isDuplicateAnnotation(Map messagesAtPosition, Position position, String message) { + private boolean isDuplicateAnnotation(Map<Position, Object> messagesAtPosition, Position position, String message) { if (messagesAtPosition.containsKey(position)) { Object value= messagesAtPosition.get(position); if (message.equals(value)) return true; if (value instanceof List) { - List messages= (List)value; + @SuppressWarnings("unchecked") + List<Object> messages= (List<Object>) value; if (messages.contains(message)) return true; messages.add(message); } else { - ArrayList messages= new ArrayList(); + ArrayList<Object> messages= new ArrayList<>(); messages.add(value); messages.add(message); messagesAtPosition.put(position, messages); @@ -184,7 +185,7 @@ public class DefaultAnnotationHover implements IAnnotationHover { return false; } - private boolean includeAnnotation(Annotation annotation, Position position, HashMap messagesAtPosition) { + private boolean includeAnnotation(Annotation annotation, Position position, HashMap<Position, Object> messagesAtPosition) { if (!isIncluded(annotation)) return false; @@ -192,18 +193,18 @@ public class DefaultAnnotationHover implements IAnnotationHover { return (text != null && !isDuplicateAnnotation(messagesAtPosition, position, text)); } - private List getAnnotationsForLine(ISourceViewer viewer, int line) { + private List<Annotation> getAnnotationsForLine(ISourceViewer viewer, int line) { IAnnotationModel model= getAnnotationModel(viewer); if (model == null) return null; IDocument document= viewer.getDocument(); - List javaAnnotations= new ArrayList(); - HashMap messagesAtPosition= new HashMap(); - Iterator iterator= model.getAnnotationIterator(); + List<Annotation> javaAnnotations= new ArrayList<>(); + HashMap<Position, Object> messagesAtPosition= new HashMap<>(); + Iterator<Annotation> iterator= model.getAnnotationIterator(); while (iterator.hasNext()) { - Annotation annotation= (Annotation) iterator.next(); + Annotation annotation= iterator.next(); Position position= model.getPosition(annotation); if (position == null) @@ -214,9 +215,9 @@ public class DefaultAnnotationHover implements IAnnotationHover { if (annotation instanceof AnnotationBag) { AnnotationBag bag= (AnnotationBag) annotation; - Iterator e= bag.iterator(); + Iterator<Annotation> e= bag.iterator(); while (e.hasNext()) { - annotation= (Annotation) e.next(); + annotation= e.next(); position= model.getPosition(annotation); if (position != null && includeAnnotation(annotation, position, messagesAtPosition)) javaAnnotations.add(annotation); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java index 4b9df872431..73522d8190d 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/LineChangeHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -88,7 +88,7 @@ public class LineChangeHover implements IAnnotationHover, IAnnotationHoverExtens if (differ == null) return null; - final List lines= new LinkedList(); + final List<ILineDiffInfo> lines= new LinkedList<>(); for (int l= first; l <= last; l++) { ILineDiffInfo info= differ.getLineInfo(l); if (info != null) @@ -110,15 +110,15 @@ public class LineChangeHover implements IAnnotationHover, IAnnotationHoverExtens * more than that due to deleted lines. * @return a <code>String</code> suitable for hover display */ - protected String decorateText(List diffInfos, int maxLines) { + protected String decorateText(List<? extends ILineDiffInfo> diffInfos, int maxLines) { /* maxLines controls the size of the hover (not more than what fits into the display are of * the viewer). * added controls how many lines are added - added lines are */ String text= ""; //$NON-NLS-1$ int added= 0; - for (Iterator it= diffInfos.iterator(); it.hasNext();) { - ILineDiffInfo info= (ILineDiffInfo)it.next(); + for (Iterator<? extends ILineDiffInfo> it= diffInfos.iterator(); it.hasNext();) { + ILineDiffInfo info= it.next(); String[] original= info.getOriginalText(); int type= info.getChangeType(); int i= 0; diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java index 153fc777685..7f060da4b5f 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/OverviewRuler.java @@ -137,13 +137,13 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { * Enumerates the annotations of a specified type and characteristics * of the associated annotation model. */ - class FilterIterator implements Iterator { + class FilterIterator implements Iterator<Annotation> { final static int TEMPORARY= 1 << 1; final static int PERSISTENT= 1 << 2; final static int IGNORE_BAGS= 1 << 3; - private Iterator fIterator; + private Iterator<Annotation> fIterator; private Object fType; private Annotation fNext; private int fStyle; @@ -170,7 +170,7 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { * @param style the style * @param iterator the iterator */ - public FilterIterator(Object annotationType, int style, Iterator iterator) { + public FilterIterator(Object annotationType, int style, Iterator<Annotation> iterator) { fType= annotationType; fStyle= style; fIterator= iterator; @@ -184,7 +184,7 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { boolean ignr= (fStyle & IGNORE_BAGS) != 0; while (fIterator.hasNext()) { - Annotation next= (Annotation) fIterator.next(); + Annotation next= fIterator.next(); if (next.isMarkedDeleted()) continue; @@ -216,7 +216,7 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { return fNext != null; } @Override - public Object next() { + public Annotation next() { try { return fNext; } finally { @@ -403,14 +403,14 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { * The list of annotation types to be shown in this ruler. * @since 3.0 */ - private Set fConfiguredAnnotationTypes= new HashSet(); + private Set<Object> fConfiguredAnnotationTypes= new HashSet<>(); /** * The list of annotation types to be shown in the header of this ruler. * @since 3.0 */ - private Set fConfiguredHeaderAnnotationTypes= new HashSet(); + private Set<Object> fConfiguredHeaderAnnotationTypes= new HashSet<>(); /** The mapping between annotation types and colors */ - private Map fAnnotationTypes2Colors= new HashMap(); + private Map<Object, Color> fAnnotationTypes2Colors= new HashMap<>(); /** The color manager */ private ISharedTextColors fSharedTextColors; /** @@ -418,32 +418,32 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { * * @since 3.0 */ - private List fAnnotationsSortedByLayer= new ArrayList(); + private List<Object> fAnnotationsSortedByLayer= new ArrayList<>(); /** * All available layers sorted by layer. * This list may contain duplicates. * @since 3.0 */ - private List fLayersSortedByLayer= new ArrayList(); + private List<Integer> fLayersSortedByLayer= new ArrayList<>(); /** * Map of allowed annotation types. * An allowed annotation type maps to <code>true</code>, a disallowed * to <code>false</code>. * @since 3.0 */ - private Map fAllowedAnnotationTypes= new HashMap(); + private Map<Object, Boolean> fAllowedAnnotationTypes= new HashMap<>(); /** * Map of allowed header annotation types. * An allowed annotation type maps to <code>true</code>, a disallowed * to <code>false</code>. * @since 3.0 */ - private Map fAllowedHeaderAnnotationTypes= new HashMap(); + private Map<Object, Boolean> fAllowedHeaderAnnotationTypes= new HashMap<>(); /** * The cached annotations. * @since 3.0 */ - private List fCachedAnnotations= new ArrayList(); + private List<Annotation> fCachedAnnotations= new ArrayList<>(); /** * Redraw runnable lock @@ -695,9 +695,9 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { private void cacheAnnotations() { fCachedAnnotations.clear(); if (fModel != null) { - Iterator iter= fModel.getAnnotationIterator(); + Iterator<Annotation> iter= fModel.getAnnotationIterator(); while (iter.hasNext()) { - Annotation annotation= (Annotation) iter.next(); + Annotation annotation= iter.next(); if (annotation.isMarkedDeleted()) continue; @@ -731,7 +731,7 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { WidgetInfos infos= null; - for (Iterator iterator= fAnnotationsSortedByLayer.iterator(); iterator.hasNext();) { + for (Iterator<Object> iterator= fAnnotationsSortedByLayer.iterator(); iterator.hasNext();) { Object annotationType= iterator.next(); if (skip(annotationType)) @@ -743,9 +743,9 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { Color fill= null; Color stroke= null; - Iterator e= new FilterIterator(annotationType, style[t], fCachedAnnotations.iterator()); + Iterator<Annotation> e= new FilterIterator(annotationType, style[t], fCachedAnnotations.iterator()); while (e.hasNext()) { - Annotation a= (Annotation) e.next(); + Annotation a= e.next(); Position p= fModel.getPosition(a); if (p == null) @@ -1036,9 +1036,9 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { Object annotationType= fAnnotationsSortedByLayer.get(i); - Iterator e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY); + Iterator<Annotation> e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY); while (e.hasNext() && found == null) { - Annotation a= (Annotation) e.next(); + Annotation a= e.next(); if (a.isMarkedDeleted()) continue; @@ -1179,7 +1179,7 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { if (layer >= 0) { int i= 0; int size= fLayersSortedByLayer.size(); - while (i < size && layer >= ((Integer)fLayersSortedByLayer.get(i)).intValue()) + while (i < size && layer >= fLayersSortedByLayer.get(i).intValue()) i++; Integer layerObj= new Integer(layer); fLayersSortedByLayer.add(i, layerObj); @@ -1228,10 +1228,10 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { * otherwise * @since 3.0 */ - private boolean contains(Object annotationType, Map allowed, Set configured) { + private boolean contains(Object annotationType, Map<Object, Boolean> allowed, Set<Object> configured) { boolean covered; synchronized (fRunnableLock){ - Boolean cached= (Boolean) allowed.get(annotationType); + Boolean cached= allowed.get(annotationType); if (cached != null) return cached.booleanValue(); @@ -1252,10 +1252,10 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { * otherwise * @since 3.0 */ - private boolean isCovered(Object annotationType, Set configured) { + private boolean isCovered(Object annotationType, Set<Object> configured) { if (fAnnotationAccess instanceof IAnnotationAccessExtension) { IAnnotationAccessExtension extension= (IAnnotationAccessExtension) fAnnotationAccess; - Iterator e= configured.iterator(); + Iterator<Object> e= configured.iterator(); while (e.hasNext()) { if (extension.isSubtype(annotationType,e.next())) return true; @@ -1337,7 +1337,7 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { * @since 3.0 */ private Color findColor(Object annotationType) { - Color color= (Color) fAnnotationTypes2Colors.get(annotationType); + Color color= fAnnotationTypes2Colors.get(annotationType); if (color != null) return color; @@ -1346,7 +1346,7 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { Object[] superTypes= extension.getSupertypes(annotationType); if (superTypes != null) { for (int i= 0; i < superTypes.length; i++) { - color= (Color) fAnnotationTypes2Colors.get(superTypes[i]); + color= fAnnotationTypes2Colors.get(superTypes[i]); if (color != null) return color; } @@ -1451,7 +1451,7 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { if (skipInHeader(annotationType) || skip(annotationType)) continue; - Iterator e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY | FilterIterator.IGNORE_BAGS, fCachedAnnotations.iterator()); + Iterator<Annotation> e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY | FilterIterator.IGNORE_BAGS, fCachedAnnotations.iterator()); while (e.hasNext()) { if (e.next() != null) { colorType= annotationType; @@ -1501,9 +1501,9 @@ public class OverviewRuler implements IOverviewRulerExtension, IOverviewRuler { int count= 0; String annotationTypeLabel= null; - Iterator e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY | FilterIterator.IGNORE_BAGS, fCachedAnnotations.iterator()); + Iterator<Annotation> e= new FilterIterator(annotationType, FilterIterator.PERSISTENT | FilterIterator.TEMPORARY | FilterIterator.IGNORE_BAGS, fCachedAnnotations.iterator()); while (e.hasNext()) { - Annotation annotation= (Annotation)e.next(); + Annotation annotation= e.next(); if (annotation != null) { if (annotationTypeLabel == null) annotationTypeLabel= ((IAnnotationAccessExtension)fAnnotationAccess).getTypeLabel(annotation); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java index 29ed1c65b3c..f8448a7c318 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/SourceViewer.java @@ -295,7 +295,7 @@ public class SourceViewer extends TextViewer implements ISourceViewer, ISourceVi * Stack of saved selections in the underlying document * @since 3.0 */ - protected final Stack fSelections= new Stack(); + protected final Stack<Position> fSelections= new Stack<>(); /** * Position updater for saved selections * @since 3.0 @@ -877,7 +877,7 @@ public class SourceViewer extends TextViewer implements ISourceViewer, ISourceVi if (!fSelections.isEmpty()) { final IDocument document= getDocument(); - final Position position= (Position) fSelections.pop(); + final Position position= fSelections.pop(); try { document.removePosition(fSelectionCategory, position); @@ -1148,7 +1148,7 @@ public class SourceViewer extends TextViewer implements ISourceViewer, ISourceVi return true; if (fVerticalRuler instanceof CompositeRuler) { - Iterator iter= ((CompositeRuler)fVerticalRuler).getDecoratorIterator(); + Iterator<IVerticalRulerColumn> iter= ((CompositeRuler)fVerticalRuler).getDecoratorIterator(); return iter.hasNext() && iter.next() instanceof AnnotationRulerColumn && !iter.hasNext(); } return false; diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/VerticalRuler.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/VerticalRuler.java index 005c8c21a90..b710fafa605 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/source/VerticalRuler.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/source/VerticalRuler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -307,10 +307,10 @@ public final class VerticalRuler implements IVerticalRuler, IVerticalRulerExtens int maxLayer= 1; // loop at least once though layers. for (int layer= 0; layer < maxLayer; layer++) { - Iterator iter= fModel.getAnnotationIterator(); + Iterator<Annotation> iter= fModel.getAnnotationIterator(); while (iter.hasNext()) { IAnnotationPresentation annotationPresentation= null; - Annotation annotation= (Annotation) iter.next(); + Annotation annotation= iter.next(); int lay= IAnnotationAccessExtension.DEFAULT_LAYER; if (annotationAccessExtension != null) @@ -394,10 +394,10 @@ public final class VerticalRuler implements IVerticalRuler, IVerticalRulerExtens int maxLayer= 1; // loop at least once through layers. for (int layer= 0; layer < maxLayer; layer++) { - Iterator iter= fModel.getAnnotationIterator(); + Iterator<Annotation> iter= fModel.getAnnotationIterator(); while (iter.hasNext()) { IAnnotationPresentation annotationPresentation= null; - Annotation annotation= (Annotation) iter.next(); + Annotation annotation= iter.next(); int lay= IAnnotationAccessExtension.DEFAULT_LAYER; if (annotationAccessExtension != null) diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/ContextTypeRegistry.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/ContextTypeRegistry.java index 8a216202538..cb8b9f68ea0 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/ContextTypeRegistry.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/ContextTypeRegistry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -27,7 +27,7 @@ import java.util.Map; public class ContextTypeRegistry { /** all known context types */ - private final Map fContextTypes= new LinkedHashMap(); + private final Map<String, TemplateContextType> fContextTypes= new LinkedHashMap<>(); /** * Adds a context type to the registry. If there already is a context type @@ -46,15 +46,15 @@ public class ContextTypeRegistry { * @return the context type if <code>name</code> is valid, <code>null</code> otherwise */ public TemplateContextType getContextType(String id) { - return (TemplateContextType) fContextTypes.get(id); + return fContextTypes.get(id); } /** * Returns an iterator over all registered context types. * - * @return an iterator over all registered context types (element type: {@link TemplateContextType}) + * @return an iterator over all registered context types */ - public Iterator contextTypes() { + public Iterator<TemplateContextType> contextTypes() { return fContextTypes.values().iterator(); } } diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateCompletionProcessor.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateCompletionProcessor.java index f3d6e7ae19e..4fd70687c97 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateCompletionProcessor.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/TemplateCompletionProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -38,14 +38,16 @@ import org.eclipse.jface.text.contentassist.IContextInformationValidator; */ public abstract class TemplateCompletionProcessor implements IContentAssistProcessor { - private static final class ProposalComparator implements Comparator { + private static final class ProposalComparator implements Comparator<ICompletionProposal> { @Override - public int compare(Object o1, Object o2) { - return ((TemplateProposal) o2).getRelevance() - ((TemplateProposal) o1).getRelevance(); + public int compare(ICompletionProposal o1, ICompletionProposal o2) { + int r1= o1 instanceof TemplateProposal ? ((TemplateProposal) o1).getRelevance() : 0; + int r2= o2 instanceof TemplateProposal ? ((TemplateProposal) o2).getRelevance() : 0; + return r2 - r1; } } - private static final Comparator fgProposalComparator= new ProposalComparator(); + private static final Comparator<ICompletionProposal> fgProposalComparator= new ProposalComparator(); @Override public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { @@ -66,7 +68,7 @@ public abstract class TemplateCompletionProcessor implements IContentAssistProce Template[] templates= getTemplates(context.getContextType().getId()); - List matches= new ArrayList(); + List<ICompletionProposal> matches= new ArrayList<>(); for (int i= 0; i < templates.length; i++) { Template template= templates[i]; try { @@ -80,7 +82,7 @@ public abstract class TemplateCompletionProcessor implements IContentAssistProce Collections.sort(matches, fgProposalComparator); - return (ICompletionProposal[]) matches.toArray(new ICompletionProposal[matches.size()]); + return matches.toArray(new ICompletionProposal[matches.size()]); } /** diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateReaderWriter.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateReaderWriter.java index 4a0aa208ad3..cda02f46a36 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateReaderWriter.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateReaderWriter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -145,8 +145,8 @@ public class TemplateReaderWriter { */ private TemplatePersistenceData[] read(InputSource source, ResourceBundle bundle, String singleId) throws IOException { try { - Collection templates= new ArrayList(); - Set ids= new HashSet(); + Collection<TemplatePersistenceData> templates= new ArrayList<>(); + Set<String> ids= new HashSet<>(); DocumentBuilderFactory factory= DocumentBuilderFactory.newInstance(); DocumentBuilder parser= factory.newDocumentBuilder(); @@ -206,7 +206,7 @@ public class TemplateReaderWriter { break; } - return (TemplatePersistenceData[]) templates.toArray(new TemplatePersistenceData[templates.size()]); + return templates.toArray(new TemplatePersistenceData[templates.size()]); } catch (ParserConfigurationException e) { Assert.isTrue(false); diff --git a/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateStore.java b/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateStore.java index edbdbcab920..631955a5bdd 100644 --- a/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateStore.java +++ b/org.eclipse.jface.text/src/org/eclipse/jface/text/templates/persistence/TemplateStore.java @@ -38,7 +38,7 @@ import org.eclipse.jface.text.templates.TemplateException; */ public class TemplateStore { /** The stored templates. */ - private final List fTemplates= new ArrayList(); + private final List<TemplatePersistenceData> fTemplates= new ArrayList<>(); /** The preference store. */ private IPreferenceStore fPreferenceStore; /** @@ -185,8 +185,8 @@ public class TemplateStore { if (!data.isCustom()) { // check if the added template is not a duplicate id String id= data.getId(); - for (Iterator it= fTemplates.iterator(); it.hasNext();) { - TemplatePersistenceData d2= (TemplatePersistenceData) it.next(); + for (Iterator<TemplatePersistenceData> it= fTemplates.iterator(); it.hasNext();) { + TemplatePersistenceData d2= it.next(); if (d2.getId() != null && d2.getId().equals(id)) return; } @@ -200,16 +200,16 @@ public class TemplateStore { * @throws IOException if the templates cannot be written */ public void save() throws IOException { - ArrayList custom= new ArrayList(); - for (Iterator it= fTemplates.iterator(); it.hasNext();) { - TemplatePersistenceData data= (TemplatePersistenceData) it.next(); + ArrayList<TemplatePersistenceData> custom= new ArrayList<>(); + for (Iterator<TemplatePersistenceData> it= fTemplates.iterator(); it.hasNext();) { + TemplatePersistenceData data= it.next(); if (data.isCustom() && !(data.isUserAdded() && data.isDeleted())) // don't save deleted user-added templates custom.add(data); } StringWriter output= new StringWriter(); TemplateReaderWriter writer= new TemplateReaderWriter(); - writer.save((TemplatePersistenceData[]) custom.toArray(new TemplatePersistenceData[custom.size()]), output); + writer.save(custom.toArray(new TemplatePersistenceData[custom.size()]), output); fIgnorePreferenceStoreChanges= true; try { @@ -234,8 +234,8 @@ public class TemplateStore { if (data.isUserAdded()) { fTemplates.add(data); } else { - for (Iterator it= fTemplates.iterator(); it.hasNext();) { - TemplatePersistenceData d2= (TemplatePersistenceData) it.next(); + for (Iterator<TemplatePersistenceData> it= fTemplates.iterator(); it.hasNext();) { + TemplatePersistenceData d2= it.next(); if (d2.getId() != null && d2.getId().equals(data.getId())) { d2.setTemplate(data.getTemplate()); d2.setDeleted(data.isDeleted()); @@ -268,8 +268,8 @@ public class TemplateStore { * Restores all contributed templates that have been deleted. */ public void restoreDeleted() { - for (Iterator it= fTemplates.iterator(); it.hasNext();) { - TemplatePersistenceData data= (TemplatePersistenceData) it.next(); + for (Iterator<TemplatePersistenceData> it= fTemplates.iterator(); it.hasNext();) { + TemplatePersistenceData data= it.next(); if (data.isDeleted()) data.setDeleted(false); } @@ -336,14 +336,14 @@ public class TemplateStore { * @return all enabled templates for the given context type */ public Template[] getTemplates(String contextTypeId) { - List templates= new ArrayList(); - for (Iterator it= fTemplates.iterator(); it.hasNext();) { - TemplatePersistenceData data= (TemplatePersistenceData) it.next(); + List<Template> templates= new ArrayList<>(); + for (Iterator<TemplatePersistenceData> it= fTemplates.iterator(); it.hasNext();) { + TemplatePersistenceData data= it.next(); if (data.isEnabled() && !data.isDeleted() && (contextTypeId == null || contextTypeId.equals(data.getTemplate().getContextTypeId()))) templates.add(data.getTemplate()); } - return (Template[]) templates.toArray(new Template[templates.size()]); + return templates.toArray(new Template[templates.size()]); } /** @@ -366,8 +366,8 @@ public class TemplateStore { public Template findTemplate(String name, String contextTypeId) { Assert.isNotNull(name); - for (Iterator it= fTemplates.iterator(); it.hasNext();) { - TemplatePersistenceData data= (TemplatePersistenceData) it.next(); + for (Iterator<TemplatePersistenceData> it= fTemplates.iterator(); it.hasNext();) { + TemplatePersistenceData data= it.next(); Template template= data.getTemplate(); if (data.isEnabled() && !data.isDeleted() && (contextTypeId == null || contextTypeId.equals(template.getContextTypeId())) @@ -400,14 +400,14 @@ public class TemplateStore { * @return all template data, whether enabled or not */ public TemplatePersistenceData[] getTemplateData(boolean includeDeleted) { - List datas= new ArrayList(); - for (Iterator it= fTemplates.iterator(); it.hasNext();) { - TemplatePersistenceData data= (TemplatePersistenceData) it.next(); + List<TemplatePersistenceData> datas= new ArrayList<>(); + for (Iterator<TemplatePersistenceData> it= fTemplates.iterator(); it.hasNext();) { + TemplatePersistenceData data= it.next(); if (includeDeleted || !data.isDeleted()) datas.add(data); } - return (TemplatePersistenceData[]) datas.toArray(new TemplatePersistenceData[datas.size()]); + return datas.toArray(new TemplatePersistenceData[datas.size()]); } /** @@ -420,8 +420,8 @@ public class TemplateStore { */ public TemplatePersistenceData getTemplateData(String id) { Assert.isNotNull(id); - for (Iterator it= fTemplates.iterator(); it.hasNext();) { - TemplatePersistenceData data= (TemplatePersistenceData) it.next(); + for (Iterator<TemplatePersistenceData> it= fTemplates.iterator(); it.hasNext();) { + TemplatePersistenceData data= it.next(); if (id.equals(data.getId())) return data; } diff --git a/org.eclipse.search.tests/src/org/eclipse/search/tests/FileTool.java b/org.eclipse.search.tests/src/org/eclipse/search/tests/FileTool.java index b227e8dafa1..160ac8fe930 100644 --- a/org.eclipse.search.tests/src/org/eclipse/search/tests/FileTool.java +++ b/org.eclipse.search.tests/src/org/eclipse/search/tests/FileTool.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -50,11 +50,11 @@ public class FileTool { * @throws IOException in case of problem */ public static void unzip(ZipFile zipFile, File dstDir) throws IOException { - Enumeration entries = zipFile.entries(); + Enumeration<? extends ZipEntry> entries = zipFile.entries(); try { while(entries.hasMoreElements()){ - ZipEntry entry = (ZipEntry)entries.nextElement(); + ZipEntry entry = entries.nextElement(); if(entry.isDirectory()){ continue; } diff --git a/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/AnnotationManagerTest.java b/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/AnnotationManagerTest.java index e7e8856a337..1c98bdb66f5 100644 --- a/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/AnnotationManagerTest.java +++ b/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/AnnotationManagerTest.java @@ -97,9 +97,9 @@ public class AnnotationManagerTest extends TestCase { ITextEditor editor= (ITextEditor)SearchTestPlugin.openTextEditor(SearchPlugin.getActivePage(), file); IAnnotationModel annotationModel= editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); annotationModel.getAnnotationIterator(); - HashSet positions= new HashSet(); - for (Iterator iter= annotationModel.getAnnotationIterator(); iter.hasNext();) { - Annotation annotation= (Annotation) iter.next(); + HashSet<Position> positions= new HashSet<>(); + for (Iterator<Annotation> iter= annotationModel.getAnnotationIterator(); iter.hasNext();) { + Annotation annotation= iter.next(); if (annotation.getType().equals(fAnnotationTypeLookup.getAnnotationType(NewSearchUI.SEARCH_MARKER, IMarker.SEVERITY_INFO))) { positions.add(annotationModel.getPosition(annotation)); } @@ -138,8 +138,8 @@ public class AnnotationManagerTest extends TestCase { ITextEditor editor= (ITextEditor)SearchTestPlugin.openTextEditor(SearchPlugin.getActivePage(), file); IAnnotationModel annotationModel= editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); int annotationCount= 0; - for (Iterator annotations= annotationModel.getAnnotationIterator(); annotations.hasNext();) { - Annotation annotation= (Annotation) annotations.next(); + for (Iterator<Annotation> annotations= annotationModel.getAnnotationIterator(); annotations.hasNext();) { + Annotation annotation= annotations.next(); if (annotation.getType().equals(fAnnotationTypeLookup.getAnnotationType(NewSearchUI.SEARCH_MARKER, IMarker.SEVERITY_INFO))) { annotationCount++; } @@ -164,8 +164,8 @@ public class AnnotationManagerTest extends TestCase { IAnnotationModel annotationModel= editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); int annotationCount= 0; IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput()); - for (Iterator annotations= annotationModel.getAnnotationIterator(); annotations.hasNext();) { - Annotation annotation= (Annotation) annotations.next(); + for (Iterator<Annotation> annotations= annotationModel.getAnnotationIterator(); annotations.hasNext();) { + Annotation annotation= annotations.next(); if (annotation.getType().equals(fAnnotationTypeLookup.getAnnotationType(NewSearchUI.SEARCH_MARKER, IMarker.SEVERITY_INFO))) { Position p= annotationModel.getPosition(annotation); String text= document.get(p.getOffset(), p.getLength()); @@ -192,8 +192,8 @@ public class AnnotationManagerTest extends TestCase { IAnnotationModel annotationModel= editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); int annotationCount= 0; IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput()); - for (Iterator annotations= annotationModel.getAnnotationIterator(); annotations.hasNext();) { - Annotation annotation= (Annotation) annotations.next(); + for (Iterator<Annotation> annotations= annotationModel.getAnnotationIterator(); annotations.hasNext();) { + Annotation annotation= annotations.next(); if (annotation.getType().equals(fAnnotationTypeLookup.getAnnotationType(NewSearchUI.SEARCH_MARKER, IMarker.SEVERITY_INFO))) { Position p= annotationModel.getPosition(annotation); String text= document.get(p.getOffset(), p.getLength()); diff --git a/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/FileSearchTests.java b/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/FileSearchTests.java index 097516acecd..86e76d62b84 100644 --- a/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/FileSearchTests.java +++ b/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/FileSearchTests.java @@ -55,14 +55,14 @@ public class FileSearchTests extends TestCase { private static class TestResultCollector extends TextSearchRequestor { - protected List fResult; + protected List<TestResult> fResult; public TestResultCollector() { reset(); } public TestResult[] getResults() { - return (TestResult[]) fResult.toArray(new TestResult[fResult.size()]); + return fResult.toArray(new TestResult[fResult.size()]); } public int getNumberOfResults() { @@ -70,7 +70,7 @@ public class FileSearchTests extends TestCase { } public void reset() { - fResult= new ArrayList(); + fResult= new ArrayList<>(); } } diff --git a/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/LineAnnotationManagerTest.java b/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/LineAnnotationManagerTest.java index efc1708dea6..78896fe4e31 100644 --- a/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/LineAnnotationManagerTest.java +++ b/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/LineAnnotationManagerTest.java @@ -94,9 +94,9 @@ public class LineAnnotationManagerTest extends TestCase { IAnnotationModel annotationModel= editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput()); annotationModel.getAnnotationIterator(); - ArrayList positions= new ArrayList(); - for (Iterator iter= annotationModel.getAnnotationIterator(); iter.hasNext();) { - Annotation annotation= (Annotation) iter.next(); + ArrayList<Position> positions= new ArrayList<>(); + for (Iterator<Annotation> iter= annotationModel.getAnnotationIterator(); iter.hasNext();) { + Annotation annotation= iter.next(); if (annotation.getType().equals(fAnnotationTypeLookup.getAnnotationType(NewSearchUI.SEARCH_MARKER, IMarker.SEVERITY_INFO))) { positions.add(annotationModel.getPosition(annotation)); } diff --git a/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/SortingTest.java b/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/SortingTest.java index 7595720a65b..c45cd30b6f4 100644 --- a/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/SortingTest.java +++ b/org.eclipse.search.tests/src/org/eclipse/search/tests/filesearch/SortingTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,16 +13,15 @@ package org.eclipse.search.tests.filesearch; import java.util.ArrayList; import java.util.List; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - +import org.eclipse.search.internal.ui.text.FileSearchQuery; import org.eclipse.search.ui.NewSearchUI; import org.eclipse.search.ui.text.AbstractTextSearchResult; import org.eclipse.search.ui.text.FileTextSearchScope; import org.eclipse.search.ui.text.Match; -import org.eclipse.search.internal.ui.text.FileSearchQuery; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; public class SortingTest extends TestCase { FileSearchQuery fQuery1; @@ -58,7 +57,7 @@ public class SortingTest extends TestCase { NewSearchUI.runQueryInForeground(null, fQuery1); AbstractTextSearchResult result= (AbstractTextSearchResult) fQuery1.getSearchResult(); int originalMatchCount= result.getMatchCount(); - List allMatches= new ArrayList(originalMatchCount); + List<Match> allMatches= new ArrayList<>(originalMatchCount); // first, collect all matches Object[] elements= result.getElements(); @@ -73,7 +72,7 @@ public class SortingTest extends TestCase { assertTrue("removed all matches", result.getMatchCount() == 0); for (int i= allMatches.size()-1; i >= 0; i--) { - result.addMatch((Match) allMatches.get(i)); + result.addMatch(allMatches.get(i)); } assertEquals("Test that all matches have been added again", result.getMatchCount(), originalMatchCount); diff --git a/org.eclipse.search/new search/org/eclipse/search/ui/text/AbstractTextSearchResult.java b/org.eclipse.search/new search/org/eclipse/search/ui/text/AbstractTextSearchResult.java index fbd75957f9b..f4ba3d60c6c 100644 --- a/org.eclipse.search/new search/org/eclipse/search/ui/text/AbstractTextSearchResult.java +++ b/org.eclipse.search/new search/org/eclipse/search/ui/text/AbstractTextSearchResult.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -33,8 +33,8 @@ public abstract class AbstractTextSearchResult implements ISearchResult { private static final Match[] EMPTY_ARRAY= new Match[0]; - private final Map fElementsToMatches; - private final List fListeners; + private final Map<Object, List<Match>> fElementsToMatches; + private final List<ISearchResultListener> fListeners; private final MatchEvent fMatchEvent; private MatchFilter[] fMatchFilters; @@ -43,8 +43,8 @@ public abstract class AbstractTextSearchResult implements ISearchResult { * Constructs a new <code>AbstractTextSearchResult</code> */ protected AbstractTextSearchResult() { - fElementsToMatches= new HashMap(); - fListeners= new ArrayList(); + fElementsToMatches= new HashMap<>(); + fListeners= new ArrayList<>(); fMatchEvent= new MatchEvent(this); fMatchFilters= null; // filtering disabled by default @@ -60,9 +60,9 @@ public abstract class AbstractTextSearchResult implements ISearchResult { */ public Match[] getMatches(Object element) { synchronized (fElementsToMatches) { - List matches= (List) fElementsToMatches.get(element); + List<Match> matches= fElementsToMatches.get(element); if (matches != null) - return (Match[]) matches.toArray(new Match[matches.size()]); + return matches.toArray(new Match[matches.size()]); return EMPTY_ARRAY; } } @@ -94,7 +94,7 @@ public abstract class AbstractTextSearchResult implements ISearchResult { * @param matches the matches to add */ public void addMatches(Match[] matches) { - Collection reallyAdded= new ArrayList(); + Collection<Match> reallyAdded= new ArrayList<>(); synchronized (fElementsToMatches) { for (int i = 0; i < matches.length; i++) { if (doAddMatch(matches[i])) @@ -111,9 +111,9 @@ public abstract class AbstractTextSearchResult implements ISearchResult { return fMatchEvent; } - private MatchEvent getSearchResultEvent(Collection matches, int eventKind) { + private MatchEvent getSearchResultEvent(Collection<Match> matches, int eventKind) { fMatchEvent.setKind(eventKind); - Match[] matchArray= (Match[]) matches.toArray(new Match[matches.size()]); + Match[] matchArray= matches.toArray(new Match[matches.size()]); fMatchEvent.setMatches(matchArray); return fMatchEvent; } @@ -121,9 +121,9 @@ public abstract class AbstractTextSearchResult implements ISearchResult { private boolean doAddMatch(Match match) { updateFilterState(match); - List matches= (List) fElementsToMatches.get(match.getElement()); + List<Match> matches= fElementsToMatches.get(match.getElement()); if (matches == null) { - matches= new ArrayList(); + matches= new ArrayList<>(); fElementsToMatches.put(match.getElement(), matches); matches.add(match); return true; @@ -135,17 +135,17 @@ public abstract class AbstractTextSearchResult implements ISearchResult { return false; } - private static void insertSorted(List matches, Match match) { + private static void insertSorted(List<Match> matches, Match match) { int insertIndex= getInsertIndex(matches, match); matches.add(insertIndex, match); } - private static int getInsertIndex(List matches, Match match) { + private static int getInsertIndex(List<Match> matches, Match match) { int count= matches.size(); int min = 0, max = count - 1; while (min <= max) { int mid = (min + max) / 2; - Match data = (Match) matches.get(mid); + Match data = matches.get(mid); int compare = compare(match, data); if (compare > 0) max = mid - 1; @@ -206,7 +206,7 @@ public abstract class AbstractTextSearchResult implements ISearchResult { * @param matches the matches to remove */ public void removeMatches(Match[] matches) { - Collection existing= new ArrayList(); + Collection<Match> existing= new ArrayList<>(); synchronized (fElementsToMatches) { for (int i = 0; i < matches.length; i++) { if (doRemoveMatch(matches[i])) @@ -220,7 +220,7 @@ public abstract class AbstractTextSearchResult implements ISearchResult { private boolean doRemoveMatch(Match match) { boolean existed= false; - List matches= (List) fElementsToMatches.get(match.getElement()); + List<Match> matches= fElementsToMatches.get(match.getElement()); if (matches != null) { existed= matches.remove(match); if (matches.isEmpty()) @@ -252,19 +252,19 @@ public abstract class AbstractTextSearchResult implements ISearchResult { * @see ISearchResultListener */ protected void fireChange(SearchResultEvent e) { - HashSet copiedListeners= new HashSet(); + HashSet<ISearchResultListener> copiedListeners= new HashSet<>(); synchronized (fListeners) { copiedListeners.addAll(fListeners); } - Iterator listeners= copiedListeners.iterator(); + Iterator<ISearchResultListener> listeners= copiedListeners.iterator(); while (listeners.hasNext()) { - ((ISearchResultListener) listeners.next()).searchResultChanged(e); + listeners.next().searchResultChanged(e); } } private void updateFilterStateForAllMatches() { boolean disableFiltering= getActiveMatchFilters() == null; - ArrayList changed= new ArrayList(); + ArrayList<Match> changed= new ArrayList<>(); Object[] elements= getElements(); for (int i= 0; i < elements.length; i++) { Match[] matches= getMatches(elements[i]); @@ -274,7 +274,7 @@ public abstract class AbstractTextSearchResult implements ISearchResult { } } } - Match[] allChanges= (Match[]) changed.toArray(new Match[changed.size()]); + Match[] allChanges= changed.toArray(new Match[changed.size()]); fireChange(new FilterUpdateEvent(this, allChanges, getActiveMatchFilters())); } @@ -307,8 +307,8 @@ public abstract class AbstractTextSearchResult implements ISearchResult { public int getMatchCount() { int count= 0; synchronized (fElementsToMatches) { - for (Iterator elements= fElementsToMatches.values().iterator(); elements.hasNext();) { - List element= (List) elements.next(); + for (Iterator<List<Match>> elements= fElementsToMatches.values().iterator(); elements.hasNext();) { + List<Match> element= elements.next(); if (element != null) count+= element.size(); } @@ -325,7 +325,7 @@ public abstract class AbstractTextSearchResult implements ISearchResult { * @return the number of matches reported against the element */ public int getMatchCount(Object element) { - List matches= (List) fElementsToMatches.get(element); + List<Match> matches= fElementsToMatches.get(element); if (matches != null) return matches.size(); return 0; diff --git a/org.eclipse.search/new search/org/eclipse/search/ui/text/AbstractTextSearchViewPage.java b/org.eclipse.search/new search/org/eclipse/search/ui/text/AbstractTextSearchViewPage.java index f7578dddcfe..dfda8772022 100644 --- a/org.eclipse.search/new search/org/eclipse/search/ui/text/AbstractTextSearchViewPage.java +++ b/org.eclipse.search/new search/org/eclipse/search/ui/text/AbstractTextSearchViewPage.java @@ -174,7 +174,7 @@ public abstract class AbstractTextSearchViewPage extends Page implements ISearch } private class SelectionProviderAdapter implements ISelectionProvider, ISelectionChangedListener { - private ArrayList fListeners= new ArrayList(5); + private ArrayList<ISelectionChangedListener> fListeners= new ArrayList<>(5); @Override public void addSelectionChangedListener(ISelectionChangedListener listener) { @@ -200,8 +200,8 @@ public abstract class AbstractTextSearchViewPage extends Page implements ISearch public void selectionChanged(SelectionChangedEvent event) { // forward to my listeners SelectionChangedEvent wrappedEvent= new SelectionChangedEvent(this, event.getSelection()); - for (Iterator listeners= fListeners.iterator(); listeners.hasNext();) { - ISelectionChangedListener listener= (ISelectionChangedListener) listeners.next(); + for (Iterator<ISelectionChangedListener> listeners= fListeners.iterator(); listeners.hasNext();) { + ISelectionChangedListener listener= listeners.next(); listener.selectionChanged(wrappedEvent); } } @@ -223,7 +223,7 @@ public abstract class AbstractTextSearchViewPage extends Page implements ISearch private PageBook fPagebook; private boolean fIsBusyShown; private ISearchResultViewPart fViewPart; - private Set fBatchedUpdates; + private Set<Object> fBatchedUpdates; private boolean fBatchedClearAll; private ISearchResultListener fListener; @@ -296,7 +296,7 @@ public abstract class AbstractTextSearchViewPage extends Page implements ISearch fSelectAllAction= new SelectAllAction(); createLayoutActions(); - fBatchedUpdates = new HashSet(); + fBatchedUpdates = new HashSet<>(); fBatchedClearAll= false; fListener = new ISearchResultListener() { @@ -1240,7 +1240,7 @@ public abstract class AbstractTextSearchViewPage extends Page implements ISearch * @param changedElements the set that collects the elements to change. Clients should only add elements to the set. * @since 3.4 */ - protected void evaluateChangedElements(Match[] matches, Set changedElements) { + protected void evaluateChangedElements(Match[] matches, Set<Object> changedElements) { for (int i = 0; i < matches.length; i++) { changedElements.add(matches[i].getElement()); } @@ -1357,7 +1357,7 @@ public abstract class AbstractTextSearchViewPage extends Page implements ISearch StructuredViewer viewer = getViewer(); IStructuredSelection selection = (IStructuredSelection) viewer.getSelection(); - HashSet set = new HashSet(); + HashSet<Match> set = new HashSet<>(); if (viewer instanceof TreeViewer) { ITreeContentProvider cp = (ITreeContentProvider) viewer.getContentProvider(); collectAllMatchesBelow(result, set, cp, selection.toArray()); @@ -1371,7 +1371,7 @@ public abstract class AbstractTextSearchViewPage extends Page implements ISearch result.removeMatches(matches); } - private void collectAllMatches(HashSet set, Object[] elements) { + private void collectAllMatches(HashSet<Match> set, Object[] elements) { for (int j = 0; j < elements.length; j++) { Match[] matches = getDisplayedMatches(elements[j]); for (int i = 0; i < matches.length; i++) { @@ -1380,7 +1380,7 @@ public abstract class AbstractTextSearchViewPage extends Page implements ISearch } } - private void collectAllMatchesBelow(AbstractTextSearchResult result, Set set, ITreeContentProvider cp, Object[] elements) { + private void collectAllMatchesBelow(AbstractTextSearchResult result, Set<Match> set, ITreeContentProvider cp, Object[] elements) { for (int j = 0; j < elements.length; j++) { Match[] matches = getDisplayedMatches(elements[j]); for (int i = 0; i < matches.length; i++) { diff --git a/org.eclipse.search/new search/org/eclipse/search/ui/text/FileTextSearchScope.java b/org.eclipse.search/new search/org/eclipse/search/ui/text/FileTextSearchScope.java index 9ace3c800e8..da2462f3d99 100644 --- a/org.eclipse.search/new search/org/eclipse/search/ui/text/FileTextSearchScope.java +++ b/org.eclipse.search/new search/org/eclipse/search/ui/text/FileTextSearchScope.java @@ -240,7 +240,7 @@ public final class FileTextSearchScope extends TextSearchScope { if (fileNamePatterns == null || fileNamePatterns.length == 0) { return null; } - ArrayList patterns= new ArrayList(); + ArrayList<String> patterns= new ArrayList<>(); for (int i= 0; i < fileNamePatterns.length; i++) { String pattern= fFileNamePatterns[i]; if (negativeMatcher == pattern.startsWith(FileTypeEditor.FILE_PATTERN_NEGATOR)) { @@ -253,7 +253,7 @@ public final class FileTextSearchScope extends TextSearchScope { } } if (!patterns.isEmpty()) { - String[] patternArray= (String[]) patterns.toArray(new String[patterns.size()]); + String[] patternArray= patterns.toArray(new String[patterns.size()]); Pattern pattern= PatternConstructor.createPattern(patternArray, IS_CASE_SENSITIVE_FILESYSTEM); return pattern.matcher(""); //$NON-NLS-1$ } @@ -261,16 +261,16 @@ public final class FileTextSearchScope extends TextSearchScope { } private static IResource[] removeRedundantEntries(IResource[] elements, boolean includeDerived) { - ArrayList res= new ArrayList(); + ArrayList<IResource> res= new ArrayList<>(); for (int i= 0; i < elements.length; i++) { IResource curr= elements[i]; addToList(res, curr, includeDerived); } - return (IResource[])res.toArray(new IResource[res.size()]); + return res.toArray(new IResource[res.size()]); } private static IResource[] convertToResources(IWorkingSet[] workingSets, boolean includeDerived) { - ArrayList res= new ArrayList(); + ArrayList<IResource> res= new ArrayList<>(); for (int i= 0; i < workingSets.length; i++) { IWorkingSet workingSet= workingSets[i]; if (workingSet.isAggregateWorkingSet() && workingSet.isEmpty()) { @@ -284,16 +284,16 @@ public final class FileTextSearchScope extends TextSearchScope { } } } - return (IResource[]) res.toArray(new IResource[res.size()]); + return res.toArray(new IResource[res.size()]); } - private static void addToList(ArrayList res, IResource curr, boolean includeDerived) { + private static void addToList(ArrayList<IResource> res, IResource curr, boolean includeDerived) { if (!includeDerived && curr.isDerived(IResource.CHECK_ANCESTORS)) { return; } IPath currPath= curr.getFullPath(); for (int k= res.size() - 1; k >= 0 ; k--) { - IResource other= (IResource) res.get(k); + IResource other= res.get(k); IPath otherPath= other.getFullPath(); if (otherPath.isPrefixOf(currPath)) { return; diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/InternalSearchUI.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/InternalSearchUI.java index 04e885b3d42..99ac2018bee 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/InternalSearchUI.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/InternalSearchUI.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -46,7 +46,7 @@ public class InternalSearchUI { private static InternalSearchUI fgInstance; // contains all running jobs - private HashMap fSearchJobs; + private HashMap<ISearchQuery, SearchJobRecord> fSearchJobs; private QueryManager fSearchResultsManager; private PositionTracker fPositionTracker; @@ -123,7 +123,7 @@ public class InternalSearchUI { */ public InternalSearchUI() { fgInstance= this; - fSearchJobs= new HashMap(); + fSearchJobs= new HashMap<>(); fSearchResultsManager= new QueryManager(); fPositionTracker= new PositionTracker(); @@ -186,7 +186,7 @@ public class InternalSearchUI { } public boolean isQueryRunning(ISearchQuery query) { - SearchJobRecord sjr= (SearchJobRecord) fSearchJobs.get(query); + SearchJobRecord sjr= fSearchJobs.get(query); return sjr != null && sjr.isRunning; } @@ -253,9 +253,9 @@ public class InternalSearchUI { } private void doShutdown() { - Iterator jobRecs= fSearchJobs.values().iterator(); + Iterator<SearchJobRecord> jobRecs= fSearchJobs.values().iterator(); while (jobRecs.hasNext()) { - SearchJobRecord element= (SearchJobRecord) jobRecs.next(); + SearchJobRecord element= jobRecs.next(); if (element.job != null) element.job.cancel(); } @@ -266,7 +266,7 @@ public class InternalSearchUI { } public void cancelSearch(ISearchQuery job) { - SearchJobRecord rec= (SearchJobRecord) fSearchJobs.get(job); + SearchJobRecord rec= fSearchJobs.get(job); if (rec != null && rec.job != null) rec.job.cancel(); } @@ -332,8 +332,8 @@ public class InternalSearchUI { } public void removeAllQueries() { - for (Iterator queries= fSearchJobs.keySet().iterator(); queries.hasNext();) { - ISearchQuery query= (ISearchQuery) queries.next(); + for (Iterator<ISearchQuery> queries= fSearchJobs.keySet().iterator(); queries.hasNext();) { + ISearchQuery query= queries.next(); cancelSearch(query); } fSearchJobs.clear(); diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/MatchFilterAction.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/MatchFilterAction.java index 63c78167762..27978fe4b22 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/MatchFilterAction.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/MatchFilterAction.java @@ -41,7 +41,7 @@ public class MatchFilterAction extends Action implements IUpdate { if (input == null) { return; } - ArrayList newFilters= new ArrayList(); + ArrayList<MatchFilter> newFilters= new ArrayList<>(); MatchFilter[] activeMatchFilters= input.getActiveMatchFilters(); if (activeMatchFilters == null) { return; @@ -56,7 +56,7 @@ public class MatchFilterAction extends Action implements IUpdate { if (newState) { newFilters.add(fFilter); } - input.setActiveMatchFilters((MatchFilter[]) newFilters.toArray(new MatchFilter[newFilters.size()])); + input.setActiveMatchFilters(newFilters.toArray(new MatchFilter[newFilters.size()])); } public MatchFilter getFilter() { diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/QueryManager.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/QueryManager.java index 673e1f94ea1..1bed6493e09 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/QueryManager.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/QueryManager.java @@ -21,14 +21,14 @@ import org.eclipse.search.ui.IQueryListener; import org.eclipse.search.ui.ISearchQuery; class QueryManager { - private List fQueries; - private List fListeners; + private List<ISearchQuery> fQueries; + private List<IQueryListener> fListeners; public QueryManager() { super(); // an ArrayList should be plenty fast enough (few searches). - fListeners= new ArrayList(); - fQueries= new LinkedList(); + fListeners= new ArrayList<>(); + fQueries= new LinkedList<>(); } public boolean hasQueries() { @@ -50,7 +50,7 @@ class QueryManager { */ public ISearchQuery[] getQueries() { synchronized (this) { - return (ISearchQuery[]) fQueries.toArray(new ISearchQuery[fQueries.size()]); + return fQueries.toArray(new ISearchQuery[fQueries.size()]); } } @@ -83,60 +83,60 @@ class QueryManager { } public void fireAdded(ISearchQuery query) { - Set copiedListeners= new HashSet(); + Set<IQueryListener> copiedListeners= new HashSet<>(); synchronized (fListeners) { copiedListeners.addAll(fListeners); } - Iterator listeners= copiedListeners.iterator(); + Iterator<IQueryListener> listeners= copiedListeners.iterator(); while (listeners.hasNext()) { - IQueryListener l= (IQueryListener) listeners.next(); + IQueryListener l= listeners.next(); l.queryAdded(query); } } public void fireRemoved(ISearchQuery query) { - Set copiedListeners= new HashSet(); + Set<IQueryListener> copiedListeners= new HashSet<>(); synchronized (fListeners) { copiedListeners.addAll(fListeners); } - Iterator listeners= copiedListeners.iterator(); + Iterator<IQueryListener> listeners= copiedListeners.iterator(); while (listeners.hasNext()) { - IQueryListener l= (IQueryListener) listeners.next(); + IQueryListener l= listeners.next(); l.queryRemoved(query); } } public void fireStarting(ISearchQuery query) { - Set copiedListeners= new HashSet(); + Set<IQueryListener> copiedListeners= new HashSet<>(); synchronized (fListeners) { copiedListeners.addAll(fListeners); } - Iterator listeners= copiedListeners.iterator(); + Iterator<IQueryListener> listeners= copiedListeners.iterator(); while (listeners.hasNext()) { - IQueryListener l= (IQueryListener) listeners.next(); + IQueryListener l= listeners.next(); l.queryStarting(query); } } public void fireFinished(ISearchQuery query) { - Set copiedListeners= new HashSet(); + Set<IQueryListener> copiedListeners= new HashSet<>(); synchronized (fListeners) { copiedListeners.addAll(fListeners); } - Iterator listeners= copiedListeners.iterator(); + Iterator<IQueryListener> listeners= copiedListeners.iterator(); while (listeners.hasNext()) { - IQueryListener l= (IQueryListener) listeners.next(); + IQueryListener l= listeners.next(); l.queryFinished(query); } } public void removeAll() { synchronized (this) { - List old= fQueries; - fQueries= new LinkedList(); - Iterator iter= old.iterator(); + List<ISearchQuery> old= fQueries; + fQueries= new LinkedList<>(); + Iterator<ISearchQuery> iter= old.iterator(); while (iter.hasNext()) { - ISearchQuery element= (ISearchQuery) iter.next(); + ISearchQuery element= iter.next(); fireRemoved(element); } } diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchHistoryDropDownAction.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchHistoryDropDownAction.java index 7b695e09266..45924a447ff 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchHistoryDropDownAction.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchHistoryDropDownAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -38,7 +38,7 @@ class SearchHistoryDropDownAction extends Action implements IMenuCreator { String label= escapeAmp(search.getLabel()); if (InternalSearchUI.getInstance().isQueryRunning(search.getQuery())) - label= MessageFormat.format(SearchMessages.SearchDropDownAction_running_message, new String[] { label }); + label= MessageFormat.format(SearchMessages.SearchDropDownAction_running_message, new Object[] { label }); // fix for bug 38049 if (label.indexOf('@') >= 0) label+= '@'; diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchHistorySelectionDialog.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchHistorySelectionDialog.java index aa6a69aadbc..9d7e59cd4b9 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchHistorySelectionDialog.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchHistorySelectionDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -67,8 +67,8 @@ public class SearchHistorySelectionDialog extends SelectionDialog { private static final int REMOVE_ID= IDialogConstants.CLIENT_ID+1; private static final int WIDTH_IN_CHARACTERS= 55; - private List fInput; - private final List fRemovedEntries; + private List<ISearchResult> fInput; + private final List<ISearchResult> fRemovedEntries; private TableViewer fViewer; private Button fRemoveButton; @@ -82,10 +82,10 @@ public class SearchHistorySelectionDialog extends SelectionDialog { private int fHistorySize; private Text fHistorySizeTextField; - private final List fCurrentList; - private final List fCurrentRemoves; + private final List<ISearchResult> fCurrentList; + private final List<ISearchResult> fCurrentRemoves; - public HistoryConfigurationDialog(Shell parent, List currentList, List removedEntries) { + public HistoryConfigurationDialog(Shell parent, List<ISearchResult> currentList, List<ISearchResult> removedEntries) { super(parent); fCurrentList= currentList; fCurrentRemoves= removedEntries; @@ -186,7 +186,7 @@ public class SearchHistorySelectionDialog extends SelectionDialog { private static final class SearchesLabelProvider extends LabelProvider { - private ArrayList fImages= new ArrayList(); + private ArrayList<Image> fImages= new ArrayList<>(); @Override public String getText(Object element) { @@ -208,20 +208,20 @@ public class SearchHistorySelectionDialog extends SelectionDialog { @Override public void dispose() { - Iterator iter= fImages.iterator(); + Iterator<Image> iter= fImages.iterator(); while (iter.hasNext()) - ((Image)iter.next()).dispose(); + iter.next().dispose(); fImages= null; } } - public SearchHistorySelectionDialog(Shell parent, List input) { + public SearchHistorySelectionDialog(Shell parent, List<ISearchResult> input) { super(parent); setTitle(SearchMessages.SearchesDialog_title); setMessage(SearchMessages.SearchesDialog_message); fInput= input; - fRemovedEntries= new ArrayList(); + fRemovedEntries= new ArrayList<>(); setHelpAvailable(false); } @@ -273,7 +273,7 @@ public class SearchHistorySelectionDialog extends SelectionDialog { public void create() { super.create(); - List initialSelection= getInitialElementSelections(); + List<?> initialSelection= getInitialElementSelections(); if (initialSelection != null) fViewer.setSelection(new StructuredSelection(initialSelection)); @@ -388,9 +388,9 @@ public class SearchHistorySelectionDialog extends SelectionDialog { protected void buttonPressed(int buttonId) { if (buttonId == REMOVE_ID) { IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection(); - Iterator searchResults= selection.iterator(); + Iterator<?> searchResults= selection.iterator(); while (searchResults.hasNext()) { - Object curr= searchResults.next(); + ISearchResult curr= (ISearchResult) searchResults.next(); fRemovedEntries.add(curr); fInput.remove(curr); fViewer.remove(curr); @@ -418,8 +418,8 @@ public class SearchHistorySelectionDialog extends SelectionDialog { setResult(((IStructuredSelection) fViewer.getSelection()).toList()); // remove queries - for (Iterator iter= fRemovedEntries.iterator(); iter.hasNext();) { - ISearchResult result= (ISearchResult) iter.next(); + for (Iterator<ISearchResult> iter= fRemovedEntries.iterator(); iter.hasNext();) { + ISearchResult result= iter.next(); ISearchQuery query= result.getQuery(); if (query != null) { // must not be null: invalid implementation of a search query InternalSearchUI.getInstance().removeQuery(query); diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchPageRegistry.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchPageRegistry.java index 821322c02a9..0eb8fc7c25b 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchPageRegistry.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchPageRegistry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -35,13 +35,13 @@ public class SearchPageRegistry { public static final String ATTRIB_HELP_CONTEXT= "helpContextId"; //$NON-NLS-1$ - private final Map fResultClassNameToExtension; - private final Map fExtensionToInstance; + private final Map<String, IConfigurationElement> fResultClassNameToExtension; + private final Map<IConfigurationElement, ISearchResultPage> fExtensionToInstance; private final IConfigurationElement[] fExtensions; public SearchPageRegistry() { - fExtensionToInstance= new HashMap(); - fResultClassNameToExtension= new HashMap(); + fExtensionToInstance= new HashMap<>(); + fResultClassNameToExtension= new HashMap<>(); fExtensions= Platform.getExtensionRegistry().getConfigurationElementsFor(ID_EXTENSION_POINT); for (int i= 0; i < fExtensions.length; i++) { fResultClassNameToExtension.put(fExtensions[i].getAttribute(ATTRIB_SEARCH_RESULT_CLASS), fExtensions[i]); @@ -49,7 +49,7 @@ public class SearchPageRegistry { } public ISearchResultPage findPageForSearchResult(ISearchResult result, boolean create) { - Class resultClass= result.getClass(); + Class<? extends ISearchResult> resultClass= result.getClass(); IConfigurationElement configElement= findConfigurationElement(resultClass); if (configElement != null) { return getSearchResultPage(configElement, create); @@ -82,7 +82,7 @@ public class SearchPageRegistry { } private ISearchResultPage getSearchResultPage(final IConfigurationElement configElement, boolean create) { - ISearchResultPage instance= (ISearchResultPage) fExtensionToInstance.get(configElement); + ISearchResultPage instance= fExtensionToInstance.get(configElement); if (instance == null && create) { final Object[] result= new Object[1]; @@ -117,13 +117,13 @@ public class SearchPageRegistry { return null; } - private IConfigurationElement findConfigurationElement(Class resultClass) { + private IConfigurationElement findConfigurationElement(Class<?> resultClass) { String className= resultClass.getName(); - IConfigurationElement configElement= (IConfigurationElement) fResultClassNameToExtension.get(className); + IConfigurationElement configElement= fResultClassNameToExtension.get(className); if (configElement != null) { return configElement; } - Class superclass= resultClass.getSuperclass(); + Class<?> superclass= resultClass.getSuperclass(); if (superclass != null) { IConfigurationElement foundExtension= findConfigurationElement(superclass); if (foundExtension != null) { @@ -132,7 +132,7 @@ public class SearchPageRegistry { } } - Class[] interfaces= resultClass.getInterfaces(); + Class<?>[] interfaces= resultClass.getInterfaces(); for (int i= 0; i < interfaces.length; i++) { IConfigurationElement foundExtension= findConfigurationElement(interfaces[i]); if (foundExtension != null) { diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchView.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchView.java index 51ac161063f..2d4bd7fbc0f 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchView.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchView.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,7 +15,7 @@ package org.eclipse.search2.internal.ui; import java.util.HashMap; import java.util.Iterator; -import java.util.Map; +import java.util.Map.Entry; import com.ibm.icu.text.MessageFormat; @@ -91,9 +91,9 @@ public class SearchView extends PageBookView implements ISearchResultViewPart, I private static final String MEMENTO_KEY_IS_PINNED= "isPinned"; //$NON-NLS-1$ private static final String MEMENTO_KEY_LAST_ACTIVATION= "org.eclipse.search.lastActivation"; //$NON-NLS-1$ private static final String MEMENTO_KEY_RESTORE= "org.eclipse.search.restore"; //$NON-NLS-1$ - private HashMap fPartsToPages; - private HashMap fPagesToParts; - private HashMap fSearchViewStates; + private HashMap<DummyPart, IPageBookViewPage> fPartsToPages; + private HashMap<ISearchResultPage, DummyPart> fPagesToParts; + private HashMap<ISearchResult, Object> fSearchViewStates; private SearchPageRegistry fSearchViewPageService; private SearchHistoryDropDownAction fSearchesDropDownAction; private ISearchResult fCurrentSearch; @@ -216,7 +216,7 @@ public class SearchView extends PageBookView implements ISearchResultViewPart, I @Override public void setFocus() {/*dummy*/} @Override - public Object getAdapter(Class adapter) { return null; } + public <T> T getAdapter(Class<T> adapter) { return null; } } static class EmptySearchView extends Page implements ISearchResultPage { @@ -312,10 +312,10 @@ public class SearchView extends PageBookView implements ISearchResultViewPart, I public SearchView() { super(); - fPartsToPages= new HashMap(); - fPagesToParts= new HashMap(); + fPartsToPages= new HashMap<>(); + fPagesToParts= new HashMap<>(); fSearchViewPageService= new SearchPageRegistry(); - fSearchViewStates= new HashMap(); + fSearchViewStates= new HashMap<>(); fIsPinned= false; } @@ -337,7 +337,7 @@ public class SearchView extends PageBookView implements ISearchResultViewPart, I @Override protected IPage createDefaultPage(PageBook book) { - IPageBookViewPage page= new EmptySearchView(); + ISearchResultPage page= new EmptySearchView(); page.createControl(book); initPage(page); DummyPart part= new DummyPart(getSite()); @@ -349,7 +349,7 @@ public class SearchView extends PageBookView implements ISearchResultViewPart, I @Override protected PageRec doCreatePage(IWorkbenchPart part) { - IPageBookViewPage page = (IPageBookViewPage) fPartsToPages.get(part); + IPageBookViewPage page = fPartsToPages.get(part); initPage(page); page.createControl(getPageBook()); PageRec rec = new PageRec(part, page); @@ -409,7 +409,7 @@ public class SearchView extends PageBookView implements ISearchResultViewPart, I if (page != null) { if (page != currentPage) { - DummyPart part= (DummyPart) fPagesToParts.get(page); + DummyPart part= fPagesToParts.get(page); if (part == null) { part= new DummyPart(getSite()); fPagesToParts.put(page, part); @@ -657,7 +657,7 @@ public class SearchView extends PageBookView implements ISearchResultViewPart, I if (result != null) { menuManager.appendToGroup(IContextMenuConstants.GROUP_SEARCH, fSearchAgainAction); // first check if we have a selection for the show in mechanism, bugzilla 127718 - IShowInSource showInSource= (IShowInSource) getAdapter(IShowInSource.class); + IShowInSource showInSource= getAdapter(IShowInSource.class); if (showInSource != null) { ShowInContext context= showInSource.getShowInContext(); if (context != null) { @@ -690,10 +690,10 @@ public class SearchView extends PageBookView implements ISearchResultViewPart, I @Override public void saveState(IMemento memento) { - for (Iterator iter= fPagesToParts.entrySet().iterator(); iter.hasNext();) { - Map.Entry entry= (Map.Entry) iter.next(); - ISearchResultPage page= (ISearchResultPage) entry.getKey(); - DummyPart part= (DummyPart) entry.getValue(); + for (Iterator<Entry<ISearchResultPage, DummyPart>> iter= fPagesToParts.entrySet().iterator(); iter.hasNext();) { + Entry<ISearchResultPage, DummyPart> entry= iter.next(); + ISearchResultPage page= entry.getKey(); + DummyPart part= entry.getValue(); IMemento child= memento.createChild(MEMENTO_TYPE, page.getID()); page.saveState(child); @@ -778,13 +778,14 @@ public class SearchView extends PageBookView implements ISearchResultViewPart, I getProgressService().warnOfContentChange(); } + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Class adapter) { + public <T> T getAdapter(Class<T> adapter) { Object superAdapter= super.getAdapter(adapter); if (superAdapter != null) - return superAdapter; + return (T) superAdapter; if (adapter == IShowInSource.class) { - return new IShowInSource() { + return (T) new IShowInSource() { @Override public ShowInContext getShowInContext() { return new ShowInContext(null, getSelectionProvider().getSelection()); diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchViewManager.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchViewManager.java index e4d1e7f3b3a..0d0f7d3eab7 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchViewManager.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/SearchViewManager.java @@ -38,7 +38,7 @@ public class SearchViewManager { private IQueryListener fNewQueryListener; private int fViewCount= 0; - private LinkedList fLRUSearchViews; + private LinkedList<SearchView> fLRUSearchViews; public SearchViewManager(QueryManager queryManager) { @@ -60,7 +60,7 @@ public class SearchViewManager { queryManager.addQueryListener(fNewQueryListener); - fLRUSearchViews= new LinkedList(); + fLRUSearchViews= new LinkedList<>(); } @@ -71,7 +71,7 @@ public class SearchViewManager { protected boolean showNewSearchQuery(ISearchQuery query) { if (!fLRUSearchViews.isEmpty()) { - SearchView view= (SearchView) fLRUSearchViews.getFirst(); + SearchView view= fLRUSearchViews.getFirst(); view.showSearchResult(query.getSearchResult()); return true; } @@ -120,8 +120,8 @@ public class SearchViewManager { } public boolean isShown(ISearchQuery query) { - for (Iterator iter= fLRUSearchViews.iterator(); iter.hasNext();) { - SearchView view= (SearchView) iter.next(); + for (Iterator<SearchView> iter= fLRUSearchViews.iterator(); iter.hasNext();) { + SearchView view= iter.next(); ISearchResult currentSearchResult= view.getCurrentSearchResult(); if (currentSearchResult != null && query == currentSearchResult.getQuery()) { return true; @@ -142,8 +142,8 @@ public class SearchViewManager { private ISearchResultViewPart findLRUSearchResultView(IWorkbenchPage page, boolean avoidPinnedViews) { boolean viewFoundInPage= false; - for (Iterator iter= fLRUSearchViews.iterator(); iter.hasNext();) { - SearchView view= (SearchView) iter.next(); + for (Iterator<SearchView> iter= fLRUSearchViews.iterator(); iter.hasNext();) { + SearchView view= iter.next(); if (page.equals(view.getSite().getPage())) { if (!avoidPinnedViews || !view.isPinned()) { return view; diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/ShowSearchHistoryDialogAction.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/ShowSearchHistoryDialogAction.java index ca3d107fd62..bfee6fcfb19 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/ShowSearchHistoryDialogAction.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/ShowSearchHistoryDialogAction.java @@ -43,7 +43,7 @@ class ShowSearchHistoryDialogAction extends Action { public void run() { ISearchQuery[] queries= NewSearchUI.getQueries(); - ArrayList input= new ArrayList(); + ArrayList<ISearchResult> input= new ArrayList<>(); for (int j= 0; j < queries.length; j++) { ISearchResult search= queries[j].getSearchResult(); input.add(search); diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/AnnotationHighlighter.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/AnnotationHighlighter.java index 278661bc74a..954c1abc7c5 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/AnnotationHighlighter.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/AnnotationHighlighter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -41,17 +41,17 @@ import org.eclipse.search2.internal.ui.SearchMessages; public class AnnotationHighlighter extends Highlighter { private IAnnotationModel fModel; private IDocument fDocument; - private Map fMatchesToAnnotations; + private Map<Match, Annotation> fMatchesToAnnotations; public AnnotationHighlighter(IAnnotationModel model, IDocument document) { fModel= model; fDocument= document; - fMatchesToAnnotations= new HashMap(); + fMatchesToAnnotations= new HashMap<>(); } @Override public void addHighlights(Match[] matches) { - HashMap map= new HashMap(matches.length); + HashMap<Annotation, Position> map= new HashMap<>(matches.length); for (int i= 0; i < matches.length; i++) { int offset= matches[i].getOffset(); int length= matches[i].getLength(); @@ -95,9 +95,9 @@ public class AnnotationHighlighter extends Highlighter { @Override public void removeHighlights(Match[] matches) { - HashSet annotations= new HashSet(matches.length); + HashSet<Annotation> annotations= new HashSet<>(matches.length); for (int i= 0; i < matches.length; i++) { - Annotation annotation= (Annotation) fMatchesToAnnotations.remove(matches[i]); + Annotation annotation= fMatchesToAnnotations.remove(matches[i]); if (annotation != null) { annotations.add(annotation); } @@ -107,19 +107,19 @@ public class AnnotationHighlighter extends Highlighter { @Override public void removeAll() { - Collection matchSet= fMatchesToAnnotations.values(); + Collection<Annotation> matchSet= fMatchesToAnnotations.values(); removeAnnotations(matchSet); fMatchesToAnnotations.clear(); } - private void addAnnotations(Map annotationToPositionMap) { + private void addAnnotations(Map<Annotation, Position> annotationToPositionMap) { if (fModel instanceof IAnnotationModelExtension) { IAnnotationModelExtension ame= (IAnnotationModelExtension) fModel; ame.replaceAnnotations(new Annotation[0], annotationToPositionMap); } else { - for (Iterator elements= annotationToPositionMap.keySet().iterator(); elements.hasNext();) { - Annotation element= (Annotation) elements.next(); - Position p= (Position) annotationToPositionMap.get(element); + for (Iterator<Annotation> elements= annotationToPositionMap.keySet().iterator(); elements.hasNext();) { + Annotation element= elements.next(); + Position p= annotationToPositionMap.get(element); fModel.addAnnotation(element, p); } } @@ -132,14 +132,14 @@ public class AnnotationHighlighter extends Highlighter { * @param annotations A set containing the annotations to be removed. * @see Annotation */ - private void removeAnnotations(Collection annotations) { + private void removeAnnotations(Collection<Annotation> annotations) { if (fModel instanceof IAnnotationModelExtension) { IAnnotationModelExtension ame= (IAnnotationModelExtension) fModel; Annotation[] annotationArray= new Annotation[annotations.size()]; - ame.replaceAnnotations((Annotation[]) annotations.toArray(annotationArray), Collections.EMPTY_MAP); + ame.replaceAnnotations(annotations.toArray(annotationArray), Collections.emptyMap()); } else { - for (Iterator iter= annotations.iterator(); iter.hasNext();) { - Annotation element= (Annotation) iter.next(); + for (Iterator<Annotation> iter= annotations.iterator(); iter.hasNext();) { + Annotation element= iter.next(); fModel.removeAnnotation(element); } } @@ -152,8 +152,8 @@ public class AnnotationHighlighter extends Highlighter { ITextFileBuffer textBuffer= (ITextFileBuffer) buffer; if (fDocument != null && fDocument.equals(textBuffer.getDocument())) { - Set allMatches= fMatchesToAnnotations.keySet(); - Match[] matchesCopy= (Match[]) allMatches.toArray(new Match[allMatches.size()]); + Set<Match> allMatches= fMatchesToAnnotations.keySet(); + Match[] matchesCopy= allMatches.toArray(new Match[allMatches.size()]); removeAll(); addHighlights(matchesCopy); } diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/AnnotationManagers.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/AnnotationManagers.java index 15f69f08e18..1dc966b461e 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/AnnotationManagers.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/AnnotationManagers.java @@ -21,7 +21,7 @@ import org.eclipse.search.ui.text.AbstractTextSearchResult; public class AnnotationManagers { static { - fgManagerMap = new HashMap(); + fgManagerMap = new HashMap<>(); IWindowListener listener = new IWindowListener() { @Override public void windowActivated(IWorkbenchWindow window) { @@ -46,11 +46,11 @@ public class AnnotationManagers { PlatformUI.getWorkbench().addWindowListener(listener); } - private static HashMap fgManagerMap; + private static HashMap<IWorkbenchWindow, WindowAnnotationManager> fgManagerMap; private static void disposeAnnotationManager(IWorkbenchWindow window) { - WindowAnnotationManager mgr = (WindowAnnotationManager) fgManagerMap.remove(window); + WindowAnnotationManager mgr = fgManagerMap.remove(window); if (mgr != null) mgr.dispose(); } @@ -64,7 +64,7 @@ public class AnnotationManagers { } private static WindowAnnotationManager getWindowAnnotationManager(IWorkbenchWindow window) { - WindowAnnotationManager mgr= (WindowAnnotationManager) fgManagerMap.get(window); + WindowAnnotationManager mgr= fgManagerMap.get(window); if (mgr == null) { mgr= new WindowAnnotationManager(window); fgManagerMap.put(window, mgr); diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/EditorAccessHighlighter.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/EditorAccessHighlighter.java index 7312e2308ec..a2c665c87e9 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/EditorAccessHighlighter.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/EditorAccessHighlighter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -40,16 +40,16 @@ import org.eclipse.search2.internal.ui.SearchMessages; public class EditorAccessHighlighter extends Highlighter { private ISearchEditorAccess fEditorAcess; - private Map fMatchesToAnnotations; + private Map<Match, Annotation> fMatchesToAnnotations; public EditorAccessHighlighter(ISearchEditorAccess editorAccess) { fEditorAcess= editorAccess; - fMatchesToAnnotations= new HashMap(); + fMatchesToAnnotations= new HashMap<>(); } @Override public void addHighlights(Match[] matches) { - Map mapsByAnnotationModel= new HashMap(); + Map<IAnnotationModel, HashMap<Annotation, Position>> mapsByAnnotationModel= new HashMap<>(); for (int i= 0; i < matches.length; i++) { int offset= matches[i].getOffset(); int length= matches[i].getLength(); @@ -57,7 +57,7 @@ public class EditorAccessHighlighter extends Highlighter { try { Position position= createPosition(matches[i]); if (position != null) { - Map map= getMap(mapsByAnnotationModel, matches[i]); + Map<Annotation, Position> map= getMap(mapsByAnnotationModel, matches[i]); if (map != null) { Annotation annotation= matches[i].isFiltered() ? new Annotation(SearchPlugin.FILTERED_SEARCH_ANNOTATION_TYPE, true, null) @@ -71,9 +71,9 @@ public class EditorAccessHighlighter extends Highlighter { } } } - for (Iterator maps= mapsByAnnotationModel.keySet().iterator(); maps.hasNext();) { - IAnnotationModel model= (IAnnotationModel) maps.next(); - Map positionMap= (Map) mapsByAnnotationModel.get(model); + for (Iterator<IAnnotationModel> maps= mapsByAnnotationModel.keySet().iterator(); maps.hasNext();) { + IAnnotationModel model= maps.next(); + Map<Annotation, Position> positionMap= mapsByAnnotationModel.get(model); addAnnotations(model, positionMap); } @@ -98,25 +98,25 @@ public class EditorAccessHighlighter extends Highlighter { return position; } - private Map getMap(Map mapsByAnnotationModel, Match match) { + private Map<Annotation, Position> getMap(Map<IAnnotationModel, HashMap<Annotation, Position>> mapsByAnnotationModel, Match match) { IAnnotationModel model= fEditorAcess.getAnnotationModel(match); if (model == null) return null; - HashMap map= (HashMap) mapsByAnnotationModel.get(model); + HashMap<Annotation, Position> map= mapsByAnnotationModel.get(model); if (map == null) { - map= new HashMap(); + map= new HashMap<>(); mapsByAnnotationModel.put(model, map); } return map; } - private Set getSet(Map setsByAnnotationModel, Match match) { + private Set<Annotation> getSet(Map<IAnnotationModel, HashSet<Annotation>> setsByAnnotationModel, Match match) { IAnnotationModel model= fEditorAcess.getAnnotationModel(match); if (model == null) return null; - HashSet set= (HashSet) setsByAnnotationModel.get(model); + HashSet<Annotation> set= setsByAnnotationModel.get(model); if (set == null) { - set= new HashSet(); + set= new HashSet<>(); setsByAnnotationModel.put(model, set); } return set; @@ -124,32 +124,32 @@ public class EditorAccessHighlighter extends Highlighter { @Override public void removeHighlights(Match[] matches) { - Map setsByAnnotationModel= new HashMap(); + Map<IAnnotationModel, HashSet<Annotation>> setsByAnnotationModel= new HashMap<>(); for (int i= 0; i < matches.length; i++) { - Annotation annotation= (Annotation) fMatchesToAnnotations.remove(matches[i]); + Annotation annotation= fMatchesToAnnotations.remove(matches[i]); if (annotation != null) { - Set annotations= getSet(setsByAnnotationModel, matches[i]); + Set<Annotation> annotations= getSet(setsByAnnotationModel, matches[i]); if (annotations != null) annotations.add(annotation); } } - for (Iterator maps= setsByAnnotationModel.keySet().iterator(); maps.hasNext();) { - IAnnotationModel model= (IAnnotationModel) maps.next(); - Set set= (Set) setsByAnnotationModel.get(model); + for (Iterator<IAnnotationModel> maps= setsByAnnotationModel.keySet().iterator(); maps.hasNext();) { + IAnnotationModel model= maps.next(); + Set<Annotation> set= setsByAnnotationModel.get(model); removeAnnotations(model, set); } } - private void addAnnotations(IAnnotationModel model, Map annotationToPositionMap) { + private void addAnnotations(IAnnotationModel model, Map<Annotation, Position> annotationToPositionMap) { if (model instanceof IAnnotationModelExtension) { IAnnotationModelExtension ame= (IAnnotationModelExtension) model; ame.replaceAnnotations(new Annotation[0], annotationToPositionMap); } else { - for (Iterator elements= annotationToPositionMap.keySet().iterator(); elements.hasNext();) { - Annotation element= (Annotation) elements.next(); - Position p= (Position) annotationToPositionMap.get(element); + for (Iterator<Annotation> elements= annotationToPositionMap.keySet().iterator(); elements.hasNext();) { + Annotation element= elements.next(); + Position p= annotationToPositionMap.get(element); model.addAnnotation(element, p); } } @@ -162,14 +162,14 @@ public class EditorAccessHighlighter extends Highlighter { * @param annotations A set containing the annotations to be removed. * @see Annotation */ - private void removeAnnotations(IAnnotationModel model, Set annotations) { + private void removeAnnotations(IAnnotationModel model, Set<Annotation> annotations) { if (model instanceof IAnnotationModelExtension) { IAnnotationModelExtension ame= (IAnnotationModelExtension) model; Annotation[] annotationArray= new Annotation[annotations.size()]; - ame.replaceAnnotations((Annotation[]) annotations.toArray(annotationArray), Collections.EMPTY_MAP); + ame.replaceAnnotations(annotations.toArray(annotationArray), Collections.emptyMap()); } else { - for (Iterator iter= annotations.iterator(); iter.hasNext();) { - Annotation element= (Annotation) iter.next(); + for (Iterator<Annotation> iter= annotations.iterator(); iter.hasNext();) { + Annotation element= iter.next(); model.removeAnnotation(element); } } @@ -177,9 +177,9 @@ public class EditorAccessHighlighter extends Highlighter { @Override public void removeAll() { - Set matchSet= fMatchesToAnnotations.keySet(); + Set<Match> matchSet= fMatchesToAnnotations.keySet(); Match[] matches= new Match[matchSet.size()]; - removeHighlights((Match[]) matchSet.toArray(matches)); + removeHighlights(matchSet.toArray(matches)); } @Override @@ -188,8 +188,8 @@ public class EditorAccessHighlighter extends Highlighter { return; IDocument document= null; ITextFileBuffer textBuffer= (ITextFileBuffer) buffer; - for (Iterator matches = fMatchesToAnnotations.keySet().iterator(); matches.hasNext();) { - Match match = (Match) matches.next(); + for (Iterator<Match> matches = fMatchesToAnnotations.keySet().iterator(); matches.hasNext();) { + Match match = matches.next(); document= fEditorAcess.getDocument(match); if (document != null) break; diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/EditorAnnotationManager.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/EditorAnnotationManager.java index 00fa9f39323..30334152f93 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/EditorAnnotationManager.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/EditorAnnotationManager.java @@ -42,7 +42,7 @@ import org.eclipse.search.ui.text.RemoveAllEvent; public class EditorAnnotationManager implements ISearchResultListener { - private ArrayList fResults; + private ArrayList<AbstractTextSearchResult> fResults; private IEditorPart fEditor; private Highlighter fHighlighter; // initialized lazy @@ -57,7 +57,7 @@ public class EditorAnnotationManager implements ISearchResultListener { Assert.isNotNull(editorPart); fEditor= editorPart; fHighlighter= null; // lazy initialization - fResults= new ArrayList(3); + fResults= new ArrayList<>(3); } @@ -72,7 +72,7 @@ public class EditorAnnotationManager implements ISearchResultListener { fHighlighter.dispose(); for (int i= 0; i < fResults.size(); i++) { - ((AbstractTextSearchResult) fResults.get(i)).removeListener(this); + fResults.get(i).removeListener(this); } fResults.clear(); } @@ -86,20 +86,20 @@ public class EditorAnnotationManager implements ISearchResultListener { } for (int i= 0; i < fResults.size(); i++) { - AbstractTextSearchResult curr= (AbstractTextSearchResult) fResults.get(i); + AbstractTextSearchResult curr= fResults.get(i); addAnnotations(curr); } } - public synchronized void setSearchResults(List results) { + public synchronized void setSearchResults(List<AbstractTextSearchResult> results) { removeAllAnnotations(); for (int i= 0; i < fResults.size(); i++) { - ((AbstractTextSearchResult) fResults.get(i)).removeListener(this); + fResults.get(i).removeListener(this); } fResults.clear(); for (int i= 0; i < results.size(); i++) { - addSearchResult((AbstractTextSearchResult) results.get(i)); + addSearchResult(results.get(i)); } } @@ -154,18 +154,18 @@ public class EditorAnnotationManager implements ISearchResultListener { return adapter.isShownInEditor(matches[0], fEditor) ? matches : null; } - ArrayList matchesInEditor= null; // lazy initialization + ArrayList<Match> matchesInEditor= null; // lazy initialization for (int i= 0; i < matches.length; i++) { Match curr= matches[i]; if (adapter.isShownInEditor(curr, fEditor)) { if (matchesInEditor == null) { - matchesInEditor= new ArrayList(); + matchesInEditor= new ArrayList<>(); } matchesInEditor.add(curr); } } if (matchesInEditor != null) { - return (Match[]) matchesInEditor.toArray(new Match[matchesInEditor.size()]); + return matchesInEditor.toArray(new Match[matchesInEditor.size()]); } return null; } @@ -230,7 +230,7 @@ public class EditorAnnotationManager implements ISearchResultListener { removeAllAnnotations(); for (int i= 0; i < fResults.size(); i++) { - AbstractTextSearchResult curr= (AbstractTextSearchResult) fResults.get(i); + AbstractTextSearchResult curr= fResults.get(i); if (curr != result) { addAnnotations(curr); } diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/MarkerHighlighter.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/MarkerHighlighter.java index e4b1e81d20a..fab4562db97 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/MarkerHighlighter.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/MarkerHighlighter.java @@ -34,11 +34,11 @@ import org.eclipse.search2.internal.ui.InternalSearchUI; public class MarkerHighlighter extends Highlighter { private IFile fFile; - private Map fMatchesToAnnotations; + private Map<Match, IMarker> fMatchesToAnnotations; public MarkerHighlighter(IFile file) { fFile= file; - fMatchesToAnnotations= new HashMap(); + fMatchesToAnnotations= new HashMap<>(); } @Override @@ -74,7 +74,7 @@ public class MarkerHighlighter extends Highlighter { IMarker marker= match.isFiltered() ? fFile.createMarker(SearchPlugin.FILTERED_SEARCH_MARKER) : fFile.createMarker(NewSearchUI.SEARCH_MARKER); - HashMap attributes= new HashMap(4); + HashMap<String, Integer> attributes= new HashMap<>(4); if (match.getBaseUnit() == Match.UNIT_CHARACTER) { attributes.put(IMarker.CHAR_START, new Integer(position.getOffset())); attributes.put(IMarker.CHAR_END, new Integer(position.getOffset()+position.getLength())); @@ -88,7 +88,7 @@ public class MarkerHighlighter extends Highlighter { @Override public void removeHighlights(Match[] matches) { for (int i= 0; i < matches.length; i++) { - IMarker marker= (IMarker) fMatchesToAnnotations.remove(matches[i]); + IMarker marker= fMatchesToAnnotations.remove(matches[i]); if (marker != null) { try { marker.delete(); diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/PositionTracker.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/PositionTracker.java index 3a28913fcf4..b5ed04173a9 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/PositionTracker.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/PositionTracker.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -48,9 +48,9 @@ import org.eclipse.search.ui.text.RemoveAllEvent; public class PositionTracker implements IQueryListener, ISearchResultListener, IFileBufferListener { - private Map fMatchesToPositions= new HashMap(); - private Map fMatchesToSearchResults= new HashMap(); - private Map fFileBuffersToMatches= new HashMap(); + private Map<Match, Position> fMatchesToPositions= new HashMap<>(); + private Map<Match, AbstractTextSearchResult> fMatchesToSearchResults= new HashMap<>(); + private Map<ITextFileBuffer, Set<Match>> fFileBuffersToMatches= new HashMap<>(); private interface IFileBufferMatchOperation { void run(ITextFileBuffer buffer, Match match); @@ -108,10 +108,10 @@ public class PositionTracker implements IQueryListener, ISearchResultListener, I } private void untrackAll(AbstractTextSearchResult result) { - Set matchSet= new HashSet(fMatchesToPositions.keySet()); - for (Iterator matches= matchSet.iterator(); matches.hasNext();) { - Match match= (Match) matches.next(); - AbstractTextSearchResult matchContainer= (AbstractTextSearchResult) fMatchesToSearchResults.get(match); + Set<Match> matchSet= new HashSet<>(fMatchesToPositions.keySet()); + for (Iterator<Match> matches= matchSet.iterator(); matches.hasNext();) { + Match match= matches.next(); + AbstractTextSearchResult matchContainer= fMatchesToSearchResults.get(match); if (result.equals(matchContainer)) { ITextFileBuffer fb= getTrackedFileBuffer(result, match.getElement()); if (fb != null) { @@ -122,7 +122,7 @@ public class PositionTracker implements IQueryListener, ISearchResultListener, I } private void untrackPosition(ITextFileBuffer fb, Match match) { - Position position= (Position) fMatchesToPositions.get(match); + Position position= fMatchesToPositions.get(match); if (position != null) { removeFileBufferMapping(fb, match); fMatchesToSearchResults.remove(match); @@ -168,16 +168,16 @@ public class PositionTracker implements IQueryListener, ISearchResultListener, I } private void addFileBufferMapping(ITextFileBuffer fb, Match match) { - Set matches= (Set) fFileBuffersToMatches.get(fb); + Set<Match> matches= fFileBuffersToMatches.get(fb); if (matches == null) { - matches= new HashSet(); + matches= new HashSet<>(); fFileBuffersToMatches.put(fb, matches); } matches.add(match); } private void removeFileBufferMapping(ITextFileBuffer fb, Match match) { - Set matches= (Set) fFileBuffersToMatches.get(fb); + Set<Match> matches= fFileBuffersToMatches.get(fb); if (matches != null) { matches.remove(match); if (matches.size() == 0) @@ -198,10 +198,10 @@ public class PositionTracker implements IQueryListener, ISearchResultListener, I } public Position getCurrentPosition(Match match) { - Position pos= (Position)fMatchesToPositions.get(match); + Position pos= fMatchesToPositions.get(match); if (pos == null) return pos; - AbstractTextSearchResult result= (AbstractTextSearchResult) fMatchesToSearchResults.get(match); + AbstractTextSearchResult result= fMatchesToSearchResults.get(match); if (match.getBaseUnit() == Match.UNIT_LINE && result != null) { ITextFileBuffer fb= getTrackedFileBuffer(result, match.getElement()); if (fb != null) { @@ -268,11 +268,11 @@ public class PositionTracker implements IQueryListener, ISearchResultListener, I private void doForExistingMatchesIn(IFileBuffer buffer, IFileBufferMatchOperation operation) { if (!(buffer instanceof ITextFileBuffer)) return; - Set matches= (Set) fFileBuffersToMatches.get(buffer); + Set<Match> matches= fFileBuffersToMatches.get(buffer); if (matches != null) { - Set matchSet= new HashSet(matches); - for (Iterator matchIterator= matchSet.iterator(); matchIterator.hasNext();) { - Match element= (Match) matchIterator.next(); + Set<Match> matchSet= new HashSet<>(matches); + for (Iterator<Match> matchIterator= matchSet.iterator(); matchIterator.hasNext();) { + Match element= matchIterator.next(); operation.run((ITextFileBuffer) buffer, element); } } @@ -303,7 +303,7 @@ public class PositionTracker implements IQueryListener, ISearchResultListener, I @Override public void run(ITextFileBuffer textBuffer, Match match) { trackCount[0]++; - AbstractTextSearchResult result= (AbstractTextSearchResult) fMatchesToSearchResults.get(match); + AbstractTextSearchResult result= fMatchesToSearchResults.get(match); untrackPosition(textBuffer, match); trackPosition(result, textBuffer, match); } @@ -324,10 +324,10 @@ public class PositionTracker implements IQueryListener, ISearchResultListener, I @Override public void run(ITextFileBuffer textBuffer, Match match) { trackCount[0]++; - Position pos= (Position) fMatchesToPositions.get(match); + Position pos= fMatchesToPositions.get(match); if (pos != null) { if (pos.isDeleted()) { - AbstractTextSearchResult result= (AbstractTextSearchResult) fMatchesToSearchResults.get(match); + AbstractTextSearchResult result= fMatchesToSearchResults.get(match); // might be that the containing element has been removed. if (result != null) { result.removeMatch(match); diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/WindowAnnotationManager.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/WindowAnnotationManager.java index a35c52d645e..65ff7f2cdc0 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/WindowAnnotationManager.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text/WindowAnnotationManager.java @@ -26,15 +26,15 @@ import org.eclipse.search.ui.text.AbstractTextSearchResult; public class WindowAnnotationManager { private IWorkbenchWindow fWindow; - private Map fAnnotationManagers; + private Map<IEditorPart, EditorAnnotationManager> fAnnotationManagers; private IPartListener2 fPartListener; - private ArrayList fSearchResults; + private ArrayList<AbstractTextSearchResult> fSearchResults; public WindowAnnotationManager(IWorkbenchWindow window) { fWindow = window; - fAnnotationManagers = new HashMap(); + fAnnotationManagers = new HashMap<>(); - fSearchResults= new ArrayList(); + fSearchResults= new ArrayList<>(); initEditors(); fPartListener= new IPartListener2() { @@ -83,7 +83,7 @@ public class WindowAnnotationManager { private void startHighlighting(IEditorPart editor) { if (editor == null) return; - EditorAnnotationManager mgr= (EditorAnnotationManager) fAnnotationManagers.get(editor); + EditorAnnotationManager mgr= fAnnotationManagers.get(editor); if (mgr == null) { mgr= new EditorAnnotationManager(editor); fAnnotationManagers.put(editor, mgr); @@ -94,7 +94,7 @@ public class WindowAnnotationManager { private void updateHighlighting(IEditorPart editor) { if (editor == null) return; - EditorAnnotationManager mgr= (EditorAnnotationManager) fAnnotationManagers.get(editor); + EditorAnnotationManager mgr= fAnnotationManagers.get(editor); if (mgr != null) { mgr.doEditorInputChanged(); } @@ -117,7 +117,7 @@ public class WindowAnnotationManager { private void stopHighlighting(IEditorPart editor) { if (editor == null) return; - EditorAnnotationManager mgr= (EditorAnnotationManager) fAnnotationManagers.remove(editor); + EditorAnnotationManager mgr= fAnnotationManagers.remove(editor); if (mgr != null) mgr.dispose(); } @@ -131,8 +131,8 @@ public class WindowAnnotationManager { void dispose() { fWindow.getPartService().removePartListener(fPartListener); - for (Iterator mgrs = fAnnotationManagers.values().iterator(); mgrs.hasNext();) { - EditorAnnotationManager mgr = (EditorAnnotationManager) mgrs.next(); + for (Iterator<EditorAnnotationManager> mgrs = fAnnotationManagers.values().iterator(); mgrs.hasNext();) { + EditorAnnotationManager mgr = mgrs.next(); mgr.dispose(); } fAnnotationManagers= null; @@ -142,8 +142,8 @@ public class WindowAnnotationManager { boolean alreadyShown= fSearchResults.contains(result); fSearchResults.add(result); if (!alreadyShown) { - for (Iterator mgrs = fAnnotationManagers.values().iterator(); mgrs.hasNext();) { - EditorAnnotationManager mgr = (EditorAnnotationManager) mgrs.next(); + for (Iterator<EditorAnnotationManager> mgrs = fAnnotationManagers.values().iterator(); mgrs.hasNext();) { + EditorAnnotationManager mgr = mgrs.next(); mgr.addSearchResult(result); } } @@ -153,8 +153,8 @@ public class WindowAnnotationManager { fSearchResults.remove(result); boolean stillShown= fSearchResults.contains(result); if (!stillShown) { - for (Iterator mgrs = fAnnotationManagers.values().iterator(); mgrs.hasNext();) { - EditorAnnotationManager mgr = (EditorAnnotationManager) mgrs.next(); + for (Iterator<EditorAnnotationManager> mgrs = fAnnotationManagers.values().iterator(); mgrs.hasNext();) { + EditorAnnotationManager mgr = mgrs.next(); mgr.removeSearchResult(result); } } diff --git a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text2/TextSearchQueryProviderRegistry.java b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text2/TextSearchQueryProviderRegistry.java index fe12c0aee1d..10f146c5aea 100644 --- a/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text2/TextSearchQueryProviderRegistry.java +++ b/org.eclipse.search/new search/org/eclipse/search2/internal/ui/text2/TextSearchQueryProviderRegistry.java @@ -91,7 +91,7 @@ public class TextSearchQueryProviderRegistry { } public String[][] getAvailableProviders() { - ArrayList res= new ArrayList(); + ArrayList<String[]> res= new ArrayList<>(); res.add(new String[] { SearchMessages.TextSearchQueryProviderRegistry_defaultProviderLabel, "" }); //$NON-NLS-1$ IConfigurationElement[] extensions= Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID); @@ -101,6 +101,6 @@ public class TextSearchQueryProviderRegistry { res.add(new String[] { engine.getAttribute(ATTRIB_LABEL), engine.getAttribute(ATTRIB_ID) }); } } - return (String[][]) res.toArray(new String[res.size()][]); + return res.toArray(new String[res.size()][]); } } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/core/text/FileNamePatternSearchScope.java b/org.eclipse.search/search/org/eclipse/search/internal/core/text/FileNamePatternSearchScope.java index dd01d712e76..f55b7e00e4f 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/core/text/FileNamePatternSearchScope.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/core/text/FileNamePatternSearchScope.java @@ -44,7 +44,7 @@ public class FileNamePatternSearchScope extends TextSearchScope { private final String fDescription; private final IResource[] fRootElements; - private final Set fFileNamePatterns; + private final Set<String> fFileNamePatterns; private Matcher fFileNameMatcher; private boolean fVisitDerived; @@ -53,7 +53,7 @@ public class FileNamePatternSearchScope extends TextSearchScope { Assert.isNotNull(description); fDescription= description; fRootElements= resources; - fFileNamePatterns= new HashSet(3); + fFileNamePatterns= new HashSet<>(3); fFileNameMatcher= null; fVisitDerived= visitDerived; } @@ -119,7 +119,7 @@ public class FileNamePatternSearchScope extends TextSearchScope { if (fFileNamePatterns.isEmpty()) { pattern= Pattern.compile(".*"); //$NON-NLS-1$ } else { - String[] patternStrings= (String[]) fFileNamePatterns.toArray(new String[fFileNamePatterns.size()]); + String[] patternStrings= fFileNamePatterns.toArray(new String[fFileNamePatterns.size()]); pattern= PatternConstructor.createPattern(patternStrings, IS_CASE_SENSITIVE_FILESYSTEM); } fFileNameMatcher= pattern.matcher(""); //$NON-NLS-1$ @@ -141,7 +141,7 @@ public class FileNamePatternSearchScope extends TextSearchScope { * @return the description of the scope */ public String getFileNamePatternDescription() { - String[] ext= (String[]) fFileNamePatterns.toArray(new String[fFileNamePatterns.size()]); + String[] ext= fFileNamePatterns.toArray(new String[fFileNamePatterns.size()]); Arrays.sort(ext); StringBuffer buf= new StringBuffer(); for (int i= 0; i < ext.length; i++) { @@ -155,21 +155,21 @@ public class FileNamePatternSearchScope extends TextSearchScope { private static IResource[] removeRedundantEntries(IResource[] elements, boolean includeDerived) { - ArrayList res= new ArrayList(); + ArrayList<IResource> res= new ArrayList<>(); for (int i= 0; i < elements.length; i++) { IResource curr= elements[i]; addToList(res, curr, includeDerived); } - return (IResource[])res.toArray(new IResource[res.size()]); + return res.toArray(new IResource[res.size()]); } - private static void addToList(ArrayList res, IResource curr, boolean includeDerived) { + private static void addToList(ArrayList<IResource> res, IResource curr, boolean includeDerived) { if (!includeDerived && curr.isDerived(IResource.CHECK_ANCESTORS)) { return; } IPath currPath= curr.getFullPath(); for (int k= res.size() - 1; k >= 0 ; k--) { - IResource other= (IResource) res.get(k); + IResource other= res.get(k); IPath otherPath= other.getFullPath(); if (otherPath.isPrefixOf(currPath)) { return; diff --git a/org.eclipse.search/search/org/eclipse/search/internal/core/text/FilesOfScopeCalculator.java b/org.eclipse.search/search/org/eclipse/search/internal/core/text/FilesOfScopeCalculator.java index 4f9eea1a77f..b4b2ec1c7ac 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/core/text/FilesOfScopeCalculator.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/core/text/FilesOfScopeCalculator.java @@ -26,7 +26,7 @@ public class FilesOfScopeCalculator implements IResourceProxyVisitor { private final TextSearchScope fScope; private final MultiStatus fStatus; - private ArrayList fFiles; + private ArrayList<IResource> fFiles; public FilesOfScopeCalculator(TextSearchScope scope, MultiStatus status) { fScope= scope; @@ -44,7 +44,7 @@ public class FilesOfScopeCalculator implements IResourceProxyVisitor { } public IFile[] process() { - fFiles= new ArrayList(); + fFiles= new ArrayList<>(); try { IResource[] roots= fScope.getRoots(); for (int i= 0; i < roots.length; i++) { @@ -58,7 +58,7 @@ public class FilesOfScopeCalculator implements IResourceProxyVisitor { fStatus.add(ex.getStatus()); } } - return (IFile[]) fFiles.toArray(new IFile[fFiles.size()]); + return fFiles.toArray(new IFile[fFiles.size()]); } finally { fFiles= null; } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchEngineRegistry.java b/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchEngineRegistry.java index 82476a46060..20ab53caaf3 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchEngineRegistry.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchEngineRegistry.java @@ -100,7 +100,7 @@ public class TextSearchEngineRegistry { } public String[][] getAvailableEngines() { - ArrayList res= new ArrayList(); + ArrayList<String[]> res= new ArrayList<>(); res.add(new String[] { SearchMessages.TextSearchEngineRegistry_defaulttextsearch_label, "" }); //$NON-NLS-1$ IConfigurationElement[] extensions= Platform.getExtensionRegistry().getConfigurationElementsFor(EXTENSION_POINT_ID); @@ -110,6 +110,6 @@ public class TextSearchEngineRegistry { res.add(new String[] { engine.getAttribute(ATTRIB_LABEL), engine.getAttribute(ATTRIB_ID) }); } } - return (String[][]) res.toArray(new String[res.size()][]); + return res.toArray(new String[res.size()][]); } } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchVisitor.java b/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchVisitor.java index b50496b8980..8942085da61 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchVisitor.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/core/text/TextSearchVisitor.java @@ -142,7 +142,7 @@ public class TextSearchVisitor { private final IFile[] fFiles; private final int fBegin; private final int fEnd; - private final Map fDocumentsInEditors; + private final Map<IFile, IDocument> fDocumentsInEditors; private ReusableMatchAccess fReusableMatchAccess; private IProgressMonitor fMonitor; @@ -154,7 +154,7 @@ public class TextSearchVisitor { * @param end one past the last element in the array to process * @param documentsInEditors a map from IFile to IDocument for all open, dirty editors */ - public TextSearchJob(IFile[] files, int begin, int end, Map documentsInEditors) { + public TextSearchJob(IFile[] files, int begin, int end, Map<IFile, IDocument> documentsInEditors) { super(files[begin].getName()); setSystem(true); fFiles = files; @@ -185,7 +185,7 @@ public class TextSearchVisitor { return fMonitor; } - public Map getDocumentsInEditors() { + public Map<IFile, IDocument> getDocumentsInEditors() { return fDocumentsInEditors; } @@ -281,7 +281,7 @@ public class TextSearchVisitor { monitorUpdateJob.schedule(); try { fCollector.beginReporting(); - Map documentsInEditors= PlatformUI.isWorkbenchRunning() ? evalNonFileBufferDocuments() : Collections.EMPTY_MAP; + Map<IFile, IDocument> documentsInEditors= PlatformUI.isWorkbenchRunning() ? evalNonFileBufferDocuments() : Collections.emptyMap(); int filesPerJob = (files.length + jobCount - 1) / jobCount; for (int first= 0; first < files.length; first += filesPerJob) { int end= Math.min(files.length, first + filesPerJob); @@ -324,8 +324,8 @@ public class TextSearchVisitor { * * @return a map from IFile to IDocument for all open, dirty editors */ - private Map evalNonFileBufferDocuments() { - Map result= new HashMap(); + private Map<IFile, IDocument> evalNonFileBufferDocuments() { + Map<IFile, IDocument> result= new HashMap<>(); IWorkbench workbench= SearchPlugin.getDefault().getWorkbench(); IWorkbenchWindow[] windows= workbench.getWorkbenchWindows(); for (int i= 0; i < windows.length; i++) { @@ -343,7 +343,7 @@ public class TextSearchVisitor { return result; } - private void evaluateTextEditor(Map result, IEditorPart ep) { + private void evaluateTextEditor(Map<IFile, IDocument> result, IEditorPart ep) { IEditorInput input= ep.getEditorInput(); if (input instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) input).getFile(); @@ -497,8 +497,8 @@ public class TextSearchVisitor { return message; } - private IDocument getOpenDocument(IFile file, Map documentsInEditors) { - IDocument document= (IDocument)documentsInEditors.get(file); + private IDocument getOpenDocument(IFile file, Map<IFile, IDocument> documentsInEditors) { + IDocument document= documentsInEditors.get(file); if (document == null) { ITextFileBufferManager bufferManager= FileBuffers.getTextFileBufferManager(); ITextFileBuffer textFileBuffer= bufferManager.getTextFileBuffer(file.getFullPath(), LocationKind.IFILE); diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/CopyToClipboardAction.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/CopyToClipboardAction.java index 696ad75105d..31b56c3278a 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/CopyToClipboardAction.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/CopyToClipboardAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -109,7 +109,7 @@ public class CopyToClipboardAction extends Action { IBaseLabelProvider labelProvider= fViewer.getLabelProvider(); String lineDelim= System.getProperty("line.separator"); //$NON-NLS-1$ StringBuffer buf= new StringBuffer(); - Iterator iter= getSelection(); + Iterator<?> iter= getSelection(); while (iter.hasNext()) { if (buf.length() > 0) { buf.append(lineDelim); @@ -141,11 +141,11 @@ public class CopyToClipboardAction extends Action { } } - private Iterator getSelection() { + private Iterator<?> getSelection() { ISelection s= fViewer.getSelection(); if (s instanceof IStructuredSelection) return ((IStructuredSelection)s).iterator(); - return Collections.EMPTY_LIST.iterator(); + return Collections.emptyList().iterator(); } private void copyToClipboard(Clipboard clipboard, String str, Shell shell) { diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/OpenSearchDialogPageAction.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/OpenSearchDialogPageAction.java index 8740ee84117..068992c47ac 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/OpenSearchDialogPageAction.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/OpenSearchDialogPageAction.java @@ -75,10 +75,10 @@ public class OpenSearchDialogPageAction implements IWorkbenchWindowPulldownDeleg } private void fillMenu(final Menu localMenu) { - List pageDescriptors= SearchPlugin.getDefault().getSearchPageDescriptors(); + List<SearchPageDescriptor> pageDescriptors= SearchPlugin.getDefault().getSearchPageDescriptors(); int accelerator= 1; - for (Iterator iter= pageDescriptors.iterator(); iter.hasNext();) { - SearchPageDescriptor desc= (SearchPageDescriptor) iter.next(); + for (Iterator<SearchPageDescriptor> iter= pageDescriptors.iterator(); iter.hasNext();) { + SearchPageDescriptor desc= iter.next(); if (!WorkbenchActivityHelper.filterItem(desc) && desc.isEnabled()) { SearchPageAction action= new SearchPageAction(fWorkbenchWindow, desc); addToMenu(localMenu, action, accelerator++); diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/RemovePotentialMatchesAction.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/RemovePotentialMatchesAction.java index e30dfd45a52..0d1622be627 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/RemovePotentialMatchesAction.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/RemovePotentialMatchesAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -78,18 +78,18 @@ class RemovePotentialMatchesAction extends Action { if (size <= 0) return null; - ArrayList markers= new ArrayList(size * 3); - Iterator iter= selection.iterator(); + ArrayList<IMarker> markers= new ArrayList<>(size * 3); + Iterator<?> iter= selection.iterator(); while (iter.hasNext()) { SearchResultViewEntry entry= (SearchResultViewEntry)iter.next(); - Iterator entryIter= entry.getMarkers().iterator(); + Iterator<IMarker> entryIter= entry.getMarkers().iterator(); while (entryIter.hasNext()) { - IMarker marker= (IMarker)entryIter.next(); + IMarker marker= entryIter.next(); if (marker.getAttribute(SearchUI.POTENTIAL_MATCH, false)) markers.add(marker); } } - return (IMarker[])markers.toArray(new IMarker[markers.size()]); + return markers.toArray(new IMarker[markers.size()]); } private boolean usePluralLabel() { @@ -104,12 +104,12 @@ class RemovePotentialMatchesAction extends Action { return false; int markerCount= 0; - Iterator iter= selection.iterator(); + Iterator<?> iter= selection.iterator(); while (iter.hasNext()) { SearchResultViewEntry entry= (SearchResultViewEntry)iter.next(); - Iterator entryIter= entry.getMarkers().iterator(); + Iterator<IMarker> entryIter= entry.getMarkers().iterator(); while (entryIter.hasNext()) { - IMarker marker= (IMarker)entryIter.next(); + IMarker marker= entryIter.next(); if (marker.getAttribute(SearchUI.POTENTIAL_MATCH, false)) { markerCount++; } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/RemoveResultAction.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/RemoveResultAction.java index c60a0aaa4af..996f7bc994f 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/RemoveResultAction.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/RemoveResultAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -73,15 +73,15 @@ class RemoveResultAction extends Action { int size= selection.size(); if (size <= 0) return null; - ArrayList markers= new ArrayList(size * 3); + ArrayList<IMarker> markers= new ArrayList<>(size * 3); int markerCount= 0; - Iterator iter= selection.iterator(); + Iterator<?> iter= selection.iterator(); while (iter.hasNext()) { SearchResultViewEntry entry= (SearchResultViewEntry)iter.next(); markerCount += entry.getMatchCount(); markers.addAll(entry.getMarkers()); } - return (IMarker[])markers.toArray(new IMarker[markerCount]); + return markers.toArray(new IMarker[markerCount]); } private boolean usePluralLabel() { diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/ResourceToItemsMapper.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/ResourceToItemsMapper.java index 0546843fff7..8e74e8a6e9e 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/ResourceToItemsMapper.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/ResourceToItemsMapper.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -37,15 +37,15 @@ class ResourceToItemsMapper { private static final int NUMBER_LIST_REUSE= 10; - // map from resource to item - private HashMap fResourceToItem; - private Stack fReuseLists; + // map from IResource to Item | List<Item> + private HashMap<IResource, Object> fResourceToItem; + private Stack<List<Item>> fReuseLists; private ContentViewer fContentViewer; public ResourceToItemsMapper(ContentViewer viewer) { - fResourceToItem= new HashMap(); - fReuseLists= new Stack(); + fResourceToItem= new HashMap<>(); + fReuseLists= new Stack<>(); fContentViewer= viewer; } @@ -61,9 +61,10 @@ class ResourceToItemsMapper { } else if (obj instanceof Item) { updateItem((Item) obj); } else { // List of Items - List list= (List) obj; + @SuppressWarnings("unchecked") + List<Item> list= (List<Item>) obj; for (int k= 0; k < list.size(); k++) { - updateItem((Item) list.get(k)); + updateItem(list.get(k)); } } } @@ -101,13 +102,14 @@ class ResourceToItemsMapper { fResourceToItem.put(resource, item); } else if (existingMapping instanceof Item) { if (existingMapping != item) { - List list= getNewList(); - list.add(existingMapping); + List<Item> list= getNewList(); + list.add((Item) existingMapping); list.add(item); fResourceToItem.put(resource, list); } } else { // List - List list= (List) existingMapping; + @SuppressWarnings("unchecked") + List<Item> list= (List<Item>) existingMapping; if (!list.contains(item)) { list.add(item); } @@ -129,7 +131,8 @@ class ResourceToItemsMapper { } else if (existingMapping instanceof Item) { fResourceToItem.remove(resource); } else { // List - List list= (List) existingMapping; + @SuppressWarnings("unchecked") + List<Item> list= (List<Item>) existingMapping; list.remove(item); if (list.isEmpty()) { fResourceToItem.remove(list); @@ -139,14 +142,14 @@ class ResourceToItemsMapper { } } - private List getNewList() { + private List<Item> getNewList() { if (!fReuseLists.isEmpty()) { - return (List) fReuseLists.pop(); + return fReuseLists.pop(); } - return new ArrayList(2); + return new ArrayList<>(2); } - private void releaseList(List list) { + private void releaseList(List<Item> list) { if (fReuseLists.size() < NUMBER_LIST_REUSE) { fReuseLists.push(list); } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/ScopePart.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/ScopePart.java index 279e9710635..5596d58cb8a 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/ScopePart.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/ScopePart.java @@ -125,7 +125,7 @@ public class ScopePart { IWorkingSetManager workingSetManager= PlatformUI.getWorkbench().getWorkingSetManager(); if (lruWorkingSetNames != null) { - Set existingWorkingSets= new HashSet(lruWorkingSetNames.length); + Set<IWorkingSet> existingWorkingSets= new HashSet<>(lruWorkingSetNames.length); for (int i= 0; i < lruWorkingSetNames.length; i++) { IWorkingSet workingSet= getWorkingSet(workingSetManager, lruWorkingSetNames[i]); if (workingSet != null) { @@ -133,7 +133,7 @@ public class ScopePart { } } if (!existingWorkingSets.isEmpty()) { - return (IWorkingSet[]) existingWorkingSets.toArray(new IWorkingSet[existingWorkingSets.size()]); + return existingWorkingSets.toArray(new IWorkingSet[existingWorkingSets.size()]); } } else { // Backward compatibility @@ -230,7 +230,7 @@ public class ScopePart { Assert.isNotNull(workingSets); setSelectedScope(ISearchPageContainer.WORKING_SET_SCOPE); fWorkingSets= null; - Set existingWorkingSets= new HashSet(workingSets.length); + Set<IWorkingSet> existingWorkingSets= new HashSet<>(workingSets.length); for (int i= 0; i < workingSets.length; i++) { String name= workingSets[i].getName(); IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(name); @@ -238,7 +238,7 @@ public class ScopePart { existingWorkingSets.add(workingSet); } if (!existingWorkingSets.isEmpty()) - fWorkingSets= (IWorkingSet[]) existingWorkingSets.toArray(new IWorkingSet[existingWorkingSets.size()]); + fWorkingSets= existingWorkingSets.toArray(new IWorkingSet[existingWorkingSets.size()]); saveState(); diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/Search.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/Search.java index e9c4d970b20..2796e550555 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/Search.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/Search.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -42,7 +42,7 @@ public class Search extends Object { private ImageDescriptor fImageDescriptor; private ILabelProvider fLabelProvider; private ISelection fSelection; - private ArrayList fResults; + private ArrayList<SearchResultViewEntry> fResults; private IAction fGotoMarkerAction; private IContextMenuContributor fContextMenuContributor; private IActionGroupFactory fActionGroupFactory; @@ -125,15 +125,15 @@ public class Search extends Object { int getItemCount() { int count= 0; - Iterator iter= getResults().iterator(); + Iterator<SearchResultViewEntry> iter= getResults().iterator(); while (iter.hasNext()) count += ((ISearchResultViewEntry)iter.next()).getMatchCount(); return count; } - List getResults() { + List<SearchResultViewEntry> getResults() { if (fResults == null) - return new ArrayList(); + return new ArrayList<>(); return fResults; } @@ -161,9 +161,9 @@ public class Search extends Object { } void backupMarkers() { - Iterator iter= getResults().iterator(); + Iterator<SearchResultViewEntry> iter= getResults().iterator(); while (iter.hasNext()) { - ((SearchResultViewEntry)iter.next()).backupMarkers(); + iter.next().backupMarkers(); } } @@ -195,7 +195,7 @@ public class Search extends Object { fResults= null; } - void setResults(ArrayList results) { + void setResults(ArrayList<SearchResultViewEntry> results) { Assert.isNotNull(results); fResults= results; } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchDialog.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchDialog.java index dabc2c4ac46..bde9ccc084d 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchDialog.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -143,7 +143,7 @@ public class SearchDialog extends ExtendedDialogWindow implements ISearchPageCon private String fInitialPageId; private int fCurrentIndex; - private List fDescriptors; + private List<SearchPageDescriptor> fDescriptors; private Point fMinSize; private ScopePart[] fScopeParts; private boolean fLastEnableState; @@ -197,8 +197,8 @@ public class SearchDialog extends ExtendedDialogWindow implements ISearchPageCon return new String[] { name }; } } else if (selection instanceof IStructuredSelection) { - HashSet res= new HashSet(); - for (Iterator iter= ((IStructuredSelection) selection).iterator(); iter.hasNext();) { + HashSet<String> res= new HashSet<>(); + for (Iterator<?> iter= ((IStructuredSelection) selection).iterator(); iter.hasNext();) { Object curr= iter.next(); if (curr instanceof IWorkingSet) { IWorkingSet workingSet= (IWorkingSet) curr; @@ -227,7 +227,7 @@ public class SearchDialog extends ExtendedDialogWindow implements ISearchPageCon } } if (!res.isEmpty()) { - return (String[]) res.toArray(new String[res.size()]); + return res.toArray(new String[res.size()]); } } return new String[0]; @@ -307,10 +307,10 @@ public class SearchDialog extends ExtendedDialogWindow implements ISearchPageCon } private void handleCustomizePressed() { - List input= SearchPlugin.getDefault().getSearchPageDescriptors(); + List<SearchPageDescriptor> input= SearchPlugin.getDefault().getSearchPageDescriptors(); input= filterByActivities(input); - final ArrayList createdImages= new ArrayList(input.size()); + final ArrayList<Image> createdImages= new ArrayList<>(input.size()); ILabelProvider labelProvider= new LabelProvider() { @Override public String getText(Object element) { @@ -393,10 +393,10 @@ public class SearchDialog extends ExtendedDialogWindow implements ISearchPageCon destroyImages(createdImages); } - private List filterByActivities(List input) { - ArrayList filteredList= new ArrayList(input.size()); - for (Iterator descriptors= input.iterator(); descriptors.hasNext();) { - SearchPageDescriptor descriptor= (SearchPageDescriptor) descriptors.next(); + private List<SearchPageDescriptor> filterByActivities(List<SearchPageDescriptor> input) { + ArrayList<SearchPageDescriptor> filteredList= new ArrayList<>(input.size()); + for (Iterator<SearchPageDescriptor> descriptors= input.iterator(); descriptors.hasNext();) { + SearchPageDescriptor descriptor= descriptors.next(); if (!WorkbenchActivityHelper.filterItem(descriptor)) filteredList.add(descriptor); @@ -404,10 +404,10 @@ public class SearchDialog extends ExtendedDialogWindow implements ISearchPageCon return filteredList; } - private void destroyImages(List images) { - Iterator iter= images.iterator(); + private void destroyImages(List<Image> images) { + Iterator<Image> iter= images.iterator(); while (iter.hasNext()) { - Image image= (Image)iter.next(); + Image image= iter.next(); if (image != null && !image.isDisposed()) image.dispose(); } @@ -544,7 +544,7 @@ public class SearchDialog extends ExtendedDialogWindow implements ISearchPageCon } private SearchPageDescriptor getDescriptorAt(int index) { - return (SearchPageDescriptor) fDescriptors.get(index); + return fDescriptors.get(index); } private Point getMinSize() { @@ -616,7 +616,7 @@ public class SearchDialog extends ExtendedDialogWindow implements ISearchPageCon int level= ISearchPageScoreComputer.LOWEST; int size= fDescriptors.size(); for (int i= 0; i < size; i++) { - SearchPageDescriptor descriptor= (SearchPageDescriptor) fDescriptors.get(i); + SearchPageDescriptor descriptor= fDescriptors.get(i); if (fInitialPageId != null && fInitialPageId.equals(descriptor.getId())) return i; @@ -834,7 +834,7 @@ public class SearchDialog extends ExtendedDialogWindow implements ISearchPageCon @Override public boolean close() { for (int i= 0; i < fDescriptors.size(); i++) { - SearchPageDescriptor desc= (SearchPageDescriptor) fDescriptors.get(i); + SearchPageDescriptor desc= fDescriptors.get(i); desc.dispose(); } return super.close(); diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchDropDownAction.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchDropDownAction.java index 1fe05775b1c..ac1fe2f1b6f 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchDropDownAction.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchDropDownAction.java @@ -59,11 +59,11 @@ class SearchDropDownAction extends Action implements IMenuCreator { fMenu= new Menu(parent); boolean checkedOne= false; - Iterator iter= SearchManager.getDefault().getPreviousSearches().iterator(); + Iterator<Search> iter= SearchManager.getDefault().getPreviousSearches().iterator(); Search selected= SearchManager.getDefault().getCurrentSearch(); int i= 0; while (iter.hasNext() && i++ < RESULTS_IN_DROP_DOWN) { - Search search= (Search)iter.next(); + Search search= iter.next(); ShowSearchAction action= new ShowSearchAction(search); action.setChecked(search.equals(selected)); if (search.equals(selected)) diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchManager.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchManager.java index 253bf416ebc..0eb749fcc08 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchManager.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -58,8 +58,8 @@ public class SearchManager implements IResourceChangeListener { SearchPlugin.getWorkspace().addResourceChangeListener(this); } - private HashSet fListeners= new HashSet(); - private LinkedList fPreviousSearches= new LinkedList(); + private HashSet<SearchResultViewer> fListeners= new HashSet<>(); + private LinkedList<Search> fPreviousSearches= new LinkedList<>(); private boolean fIsRemoveAll= false; public static synchronized SearchManager getDefault() { @@ -76,17 +76,17 @@ public class SearchManager implements IResourceChangeListener { * Returns the list with previous searches (ISearch). * @return previous searches */ - LinkedList getPreviousSearches() { + LinkedList<Search> getPreviousSearches() { return fPreviousSearches; } /** * Returns the list with current (last) results * @return the current results */ - ArrayList getCurrentResults() { + ArrayList<SearchResultViewEntry> getCurrentResults() { if (fCurrentSearch == null) - return new ArrayList(0); - return (ArrayList)fCurrentSearch.getResults(); + return new ArrayList<>(0); + return (ArrayList<SearchResultViewEntry>)fCurrentSearch.getResults(); } public Search getCurrentSearch() { @@ -118,13 +118,13 @@ public class SearchManager implements IResourceChangeListener { } // clear searches - fPreviousSearches= new LinkedList(); + fPreviousSearches= new LinkedList<>(); fCurrentSearch= null; // update viewers - Iterator iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter= fListeners.iterator(); while (iter.hasNext()) { - SearchResultViewer viewer= (SearchResultViewer)iter.next(); + SearchResultViewer viewer= iter.next(); handleAllSearchesRemoved(viewer); } } @@ -177,15 +177,15 @@ public class SearchManager implements IResourceChangeListener { monitor.worked(10); // add search markers - Iterator iter= getCurrentResults().iterator(); - ArrayList emptyEntries= new ArrayList(10); + Iterator<SearchResultViewEntry> iter= getCurrentResults().iterator(); + ArrayList<SearchResultViewEntry> emptyEntries= new ArrayList<>(10); boolean filesChanged= false; boolean filesDeleted= false; IGroupByKeyComputer groupByKeyComputer= getCurrentSearch().getGroupByKeyComputer(); while (iter.hasNext()) { monitor.worked(1); - SearchResultViewEntry entry= (SearchResultViewEntry)iter.next(); - Iterator attrPerMarkerIter= entry.getAttributesPerMarker().iterator(); + SearchResultViewEntry entry= iter.next(); + Iterator<Map<String, Object>> attrPerMarkerIter= entry.getAttributesPerMarker().iterator(); entry.clearMarkerList(); if (entry.getResource() == null || !entry.getResource().exists()) { emptyEntries.add(entry); @@ -201,7 +201,7 @@ public class SearchManager implements IResourceChangeListener { continue; } try { - newMarker.setAttributes((Map)attrPerMarkerIter.next()); + newMarker.setAttributes(attrPerMarkerIter.next()); if (groupByKeyComputer !=null && groupByKeyComputer.computeGroupByKey(newMarker) == null) { filesDeleted= true; newMarker.delete(); @@ -246,11 +246,11 @@ public class SearchManager implements IResourceChangeListener { } // update viewers - iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter2= fListeners.iterator(); if (display != null && !display.isDisposed()) { final Viewer visibleViewer= ((SearchResultView)SearchUI.getSearchResultView()).getViewer(); - while (iter.hasNext()) { - final SearchResultViewer viewer= (SearchResultViewer)iter.next(); + while (iter2.hasNext()) { + final SearchResultViewer viewer= iter2.next(); display.syncExec(new Runnable() { @Override public void run() { @@ -296,12 +296,12 @@ public class SearchManager implements IResourceChangeListener { SearchPlugin.getWorkspace().removeResourceChangeListener(this); // Clear the viewers - Iterator iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter= fListeners.iterator(); Display display= getDisplay(); if (display != null && !display.isDisposed()) { final Viewer visibleViewer= ((SearchResultView)SearchUI.getSearchResultView()).getViewer(); while (iter.hasNext()) { - final SearchResultViewer viewer= (SearchResultViewer)iter.next(); + final SearchResultViewer viewer= iter.next(); display.syncExec(new Runnable() { @Override public void run() { @@ -330,7 +330,7 @@ public class SearchManager implements IResourceChangeListener { } } - void searchFinished(ArrayList results) { + void searchFinished(ArrayList<SearchResultViewEntry> results) { Assert.isNotNull(results); getCurrentSearch().setResults(results); @@ -369,9 +369,9 @@ public class SearchManager implements IResourceChangeListener { return; } - Iterator iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter= fListeners.iterator(); while (iter.hasNext()) - ((SearchResultViewer)iter.next()).getControl().setRedraw(false); + iter.next().getControl().setRedraw(false); for (int i=0; i < markerDeltas.length; i++) { handleSearchMarkerChanged(markerDeltas[i]); @@ -379,7 +379,7 @@ public class SearchManager implements IResourceChangeListener { iter= fListeners.iterator(); while (iter.hasNext()) - ((SearchResultViewer)iter.next()).getControl().setRedraw(true); + iter.next().getControl().setRedraw(true); } @@ -395,15 +395,15 @@ public class SearchManager implements IResourceChangeListener { private void handleRemoveAll() { if (fCurrentSearch != null) fCurrentSearch.removeResults(); - Iterator iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter= fListeners.iterator(); while (iter.hasNext()) - ((SearchResultViewer)iter.next()).handleRemoveAll(); + iter.next().handleRemoveAll(); } private void handleNewSearchResult() { - Iterator iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter= fListeners.iterator(); while (iter.hasNext()) { - SearchResultViewer viewer= (SearchResultViewer)iter.next(); + SearchResultViewer viewer= iter.next(); viewer.setInput(getCurrentResults()); } } @@ -423,14 +423,14 @@ public class SearchManager implements IResourceChangeListener { entry.remove(marker); if (entry.getMatchCount() == 0) { getCurrentResults().remove(entry); - Iterator iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter= fListeners.iterator(); while (iter.hasNext()) - ((SearchResultViewer)iter.next()).handleRemoveMatch(entry); + iter.next().handleRemoveMatch(entry); } else { - Iterator iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter= fListeners.iterator(); while (iter.hasNext()) - ((SearchResultViewer)iter.next()).handleUpdateMatch(entry, true); + iter.next().handleUpdateMatch(entry, true); } } } @@ -438,16 +438,16 @@ public class SearchManager implements IResourceChangeListener { private void handleUpdateMatch(IMarker marker) { SearchResultViewEntry entry= findEntry(marker); if (entry != null) { - Iterator iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter= fListeners.iterator(); while (iter.hasNext()) - ((SearchResultViewer)iter.next()).handleUpdateMatch(entry, false); + iter.next().handleUpdateMatch(entry, false); } } private SearchResultViewEntry findEntry(IMarker marker) { - Iterator entries= getCurrentResults().iterator(); + Iterator<SearchResultViewEntry> entries= getCurrentResults().iterator(); while (entries.hasNext()) { - SearchResultViewEntry entry= (SearchResultViewEntry)entries.next(); + SearchResultViewEntry entry= entries.next(); if (entry.contains(marker)) return entry; } @@ -479,9 +479,9 @@ public class SearchManager implements IResourceChangeListener { if (getCurrentSearch() != null) { handleSearchMarkersChanged(markerDeltas); // update title and actions - Iterator iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter= fListeners.iterator(); while (iter.hasNext()) { - SearchResultViewer viewer= (SearchResultViewer)iter.next(); + SearchResultViewer viewer= iter.next(); viewer.enableActions(); viewer.updateTitle(); } @@ -495,7 +495,7 @@ public class SearchManager implements IResourceChangeListener { * @return the display */ private Display getDisplay() { - Iterator iter= fListeners.iterator(); + Iterator<SearchResultViewer> iter= fListeners.iterator(); while (iter.hasNext()) { Control control= ((Viewer)iter.next()).getControl(); if (control != null && !control.isDisposed()) { diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPageDescriptor.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPageDescriptor.java index 36c2dfa2300..3c59e8b5d72 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPageDescriptor.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPageDescriptor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -47,7 +47,7 @@ import org.eclipse.search.ui.ISearchPageScoreComputer; /** * Proxy that represents a search page. */ -class SearchPageDescriptor implements IPluginContribution, Comparable { +class SearchPageDescriptor implements IPluginContribution, Comparable<SearchPageDescriptor> { public final static String PAGE_TAG= "page"; //$NON-NLS-1$ private final static String ID_ATTRIBUTE= "id"; //$NON-NLS-1$ @@ -69,7 +69,7 @@ class SearchPageDescriptor implements IPluginContribution, Comparable { private final static String STORE_ENABLED_PAGE_IDS= SECTION_ID + ".enabledPageIds"; //$NON-NLS-1$ private final static String STORE_PROCESSED_PAGE_IDS= SECTION_ID + ".processedPageIds"; //$NON-NLS-1$ - private static List fgEnabledPageIds; + private static List<String> fgEnabledPageIds; private static class ExtensionScorePair { public String extension; @@ -81,7 +81,7 @@ class SearchPageDescriptor implements IPluginContribution, Comparable { } private IConfigurationElement fElement; - private List fExtensionScorePairs; + private List<ExtensionScorePair> fExtensionScorePairs; private int fWildcardScore= ISearchPageScoreComputer.UNKNOWN; private ISearchPage fCreatedPage; @@ -232,7 +232,7 @@ class SearchPageDescriptor implements IPluginContribution, Comparable { } static void setEnabled(Object[] enabledDescriptors) { - fgEnabledPageIds= new ArrayList(5); + fgEnabledPageIds= new ArrayList<>(5); for (int i= 0; i < enabledDescriptors.length; i++) { if (enabledDescriptors[i] instanceof SearchPageDescriptor) fgEnabledPageIds.add(((SearchPageDescriptor)enabledDescriptors[i]).getId()); @@ -240,28 +240,28 @@ class SearchPageDescriptor implements IPluginContribution, Comparable { storeEnabledPageIds(); } - private static List getEnabledPageIds() { + private static List<String> getEnabledPageIds() { if (fgEnabledPageIds == null) { - List descriptors= SearchPlugin.getDefault().getSearchPageDescriptors(); + List<SearchPageDescriptor> descriptors= SearchPlugin.getDefault().getSearchPageDescriptors(); String[] enabledPageIds= getDialogSettings().getArray(STORE_ENABLED_PAGE_IDS); if (enabledPageIds == null) - fgEnabledPageIds= new ArrayList(descriptors.size()); + fgEnabledPageIds= new ArrayList<>(descriptors.size()); else - fgEnabledPageIds= new ArrayList(Arrays.asList(enabledPageIds)); + fgEnabledPageIds= new ArrayList<>(Arrays.asList(enabledPageIds)); - List processedPageIds; + List<String> processedPageIds; String[] processedPageIdsArr= getDialogSettings().getArray(STORE_PROCESSED_PAGE_IDS); if (processedPageIdsArr == null) - processedPageIds= new ArrayList(descriptors.size()); + processedPageIds= new ArrayList<>(descriptors.size()); else - processedPageIds= new ArrayList(Arrays.asList(processedPageIdsArr)); + processedPageIds= new ArrayList<>(Arrays.asList(processedPageIdsArr)); // Enable pages based on contribution - Iterator iter= descriptors.iterator(); + Iterator<SearchPageDescriptor> iter= descriptors.iterator(); while (iter.hasNext()) { - SearchPageDescriptor desc= (SearchPageDescriptor)iter.next(); + SearchPageDescriptor desc= iter.next(); if (processedPageIds.contains(desc.getId())) continue; @@ -270,14 +270,14 @@ class SearchPageDescriptor implements IPluginContribution, Comparable { fgEnabledPageIds.add(desc.getId()); } - getDialogSettings().put(STORE_PROCESSED_PAGE_IDS, (String[])processedPageIds.toArray(new String[processedPageIds.size()])); + getDialogSettings().put(STORE_PROCESSED_PAGE_IDS, processedPageIds.toArray(new String[processedPageIds.size()])); storeEnabledPageIds(); } return fgEnabledPageIds; } private static void storeEnabledPageIds() { - getDialogSettings().put(STORE_ENABLED_PAGE_IDS, (String[])fgEnabledPageIds.toArray(new String[fgEnabledPageIds.size()])); + getDialogSettings().put(STORE_ENABLED_PAGE_IDS, fgEnabledPageIds.toArray(new String[fgEnabledPageIds.size()])); } private static IDialogSettings getDialogSettings() { @@ -289,15 +289,12 @@ class SearchPageDescriptor implements IPluginContribution, Comparable { return section; } - /* - * Implements a method from IComparable - */ @Override - public int compareTo(Object o) { + public int compareTo(SearchPageDescriptor o) { int myPos= getTabPosition(); - int objsPos= ((SearchPageDescriptor)o).getTabPosition(); + int objsPos= o.getTabPosition(); if (myPos == Integer.MAX_VALUE && objsPos == Integer.MAX_VALUE || myPos == objsPos) - return getLabel().compareTo(((SearchPageDescriptor)o).getLabel()); + return getLabel().compareTo(o.getLabel()); return myPos - objsPos; } @@ -338,7 +335,7 @@ class SearchPageDescriptor implements IPluginContribution, Comparable { int size= fExtensionScorePairs.size(); for (int i= 0; i < size; i++) { - ExtensionScorePair p= (ExtensionScorePair)fExtensionScorePairs.get(i); + ExtensionScorePair p= fExtensionScorePairs.get(i); if (extension.equals(p.extension)) return p.score; } @@ -347,7 +344,7 @@ class SearchPageDescriptor implements IPluginContribution, Comparable { } private void readExtensionScorePairs() { - fExtensionScorePairs= new ArrayList(3); + fExtensionScorePairs= new ArrayList<>(3); String content= fElement.getAttribute(EXTENSIONS_ATTRIBUTE); if (content == null) return; diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPlugin.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPlugin.java index 538a67eccfc..3702c32cb06 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPlugin.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPlugin.java @@ -85,8 +85,8 @@ public class SearchPlugin extends AbstractUIPlugin { private static SearchPlugin fgSearchPlugin; - private List fPageDescriptors; - private List fSorterDescriptors; + private List<SearchPageDescriptor> fPageDescriptors; + private List<SorterDescriptor> fSorterDescriptors; private TextSearchEngineRegistry fTextSearchEngineRegistry; private TextSearchQueryProviderRegistry fTextSearchQueryProviderRegistry; @@ -226,7 +226,7 @@ public class SearchPlugin extends AbstractUIPlugin { /** * @return Returns all search pages contributed to the workbench. */ - public List getSearchPageDescriptors() { + public List<SearchPageDescriptor> getSearchPageDescriptors() { if (fPageDescriptors == null) { IConfigurationElement[] elements= Platform.getExtensionRegistry().getConfigurationElementsFor(NewSearchUI.PLUGIN_ID, SEARCH_PAGE_EXTENSION_POINT); fPageDescriptors= createSearchPageDescriptors(elements); @@ -238,11 +238,11 @@ public class SearchPlugin extends AbstractUIPlugin { * @param pageId the page id or <code>null</code> * @return all descriptors of the enabled search pages, plus the descriptor for the given page id */ - public List getEnabledSearchPageDescriptors(String pageId) { - Iterator iter= getSearchPageDescriptors().iterator(); - List enabledDescriptors= new ArrayList(5); + public List<SearchPageDescriptor> getEnabledSearchPageDescriptors(String pageId) { + Iterator<SearchPageDescriptor> iter= getSearchPageDescriptors().iterator(); + List<SearchPageDescriptor> enabledDescriptors= new ArrayList<>(5); while (iter.hasNext()) { - SearchPageDescriptor desc= (SearchPageDescriptor)iter.next(); + SearchPageDescriptor desc= iter.next(); if (desc.isEnabled() || desc.getId().equals(pageId)) enabledDescriptors.add(desc); } @@ -261,9 +261,9 @@ public class SearchPlugin extends AbstractUIPlugin { Search currentSearch= SearchManager.getDefault().getCurrentSearch(); if (currentSearch != null) { String pageId= currentSearch.getPageId(); - Iterator iter= getSearchPageDescriptors().iterator(); + Iterator<SearchPageDescriptor> iter= getSearchPageDescriptors().iterator(); while (iter.hasNext()) { - SearchPageDescriptor desc= (SearchPageDescriptor)iter.next(); + SearchPageDescriptor desc= iter.next(); if (desc.getId().equals(pageId)) { String helpId= desc.getSearchViewHelpContextId(); if (helpId == null) @@ -280,8 +280,8 @@ public class SearchPlugin extends AbstractUIPlugin { * @param elements the configuration elements * @return the created SearchPageDescriptor */ - private List createSearchPageDescriptors(IConfigurationElement[] elements) { - List result= new ArrayList(5); + private List<SearchPageDescriptor> createSearchPageDescriptors(IConfigurationElement[] elements) { + List<SearchPageDescriptor> result= new ArrayList<>(5); for (int i= 0; i < elements.length; i++) { IConfigurationElement element= elements[i]; if (SearchPageDescriptor.PAGE_TAG.equals(element.getName())) { @@ -296,7 +296,7 @@ public class SearchPlugin extends AbstractUIPlugin { /** * @return Returns all sorters contributed to the workbench. */ - public List getSorterDescriptors() { + public List<SorterDescriptor> getSorterDescriptors() { if (fSorterDescriptors == null) { IConfigurationElement[] elements= Platform.getExtensionRegistry().getConfigurationElementsFor(NewSearchUI.PLUGIN_ID, SORTER_EXTENSION_POINT); fSorterDescriptors= createSorterDescriptors(elements); @@ -324,8 +324,8 @@ public class SearchPlugin extends AbstractUIPlugin { * @param elements the configuration elements * @return the created SorterDescriptor */ - private List createSorterDescriptors(IConfigurationElement[] elements) { - List result= new ArrayList(5); + private List<SorterDescriptor> createSorterDescriptors(IConfigurationElement[] elements) { + List<SorterDescriptor> result= new ArrayList<>(5); for (int i= 0; i < elements.length; i++) { IConfigurationElement element= elements[i]; if (SorterDescriptor.SORTER_TAG.equals(element.getName())) diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPreferencePage.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPreferencePage.java index 01c47faadfb..716c1321b24 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPreferencePage.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchPreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -59,15 +59,12 @@ public class SearchPreferencePage extends FieldEditorPreferencePage implements I private BooleanFieldEditor fIgnorePotentialMatchesCheckbox; - private static class PerspectiveDescriptorComparator implements Comparator { + private static class PerspectiveDescriptorComparator implements Comparator<IPerspectiveDescriptor> { @Override - public int compare(Object o1, Object o2) { - if (o1 instanceof IPerspectiveDescriptor && o2 instanceof IPerspectiveDescriptor) { - String id1= ((IPerspectiveDescriptor)o1).getLabel(); - String id2= ((IPerspectiveDescriptor)o2).getLabel(); - return Collator.getInstance().compare(id1, id2); - } - return 0; + public int compare(IPerspectiveDescriptor o1, IPerspectiveDescriptor o2) { + String id1= o1.getLabel(); + String id2= o2.getLabel(); + return Collator.getInstance().compare(id1, id2); } } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultView.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultView.java index 953f26e6984..f05bdcf7259 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultView.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultView.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -57,10 +57,10 @@ import org.eclipse.search.ui.ISearchResultView; public class SearchResultView extends ViewPart implements ISearchResultView { - private static Map fgLabelProviders= new HashMap(5); + private static Map<String, ILabelProvider> fgLabelProviders= new HashMap<>(5); private SearchResultViewer fViewer; - private Map fResponse; + private Map<Object, SearchResultViewEntry> fResponse; private IMemento fMemento; private IPropertyChangeListener fPropertyChangeListener; private CellEditorActionHandler fCellEditorActionHandler; @@ -183,7 +183,7 @@ public class SearchResultView extends ViewPart implements ISearchResultView { ILabelProvider getLabelProvider(String pageId) { if (pageId != null) - return (ILabelProvider)fgLabelProviders.get(pageId); + return fgLabelProviders.get(pageId); return null; } @@ -245,10 +245,10 @@ public class SearchResultView extends ViewPart implements ISearchResultView { Assert.isNotNull(pluralLabelPattern); Assert.isNotNull(gotoAction); - fResponse= new HashMap(500); + fResponse= new HashMap<>(500); setGotoMarkerAction(gotoAction); - ILabelProvider oldLabelProvider= (ILabelProvider)fgLabelProviders.get(pageId); + ILabelProvider oldLabelProvider= fgLabelProviders.get(pageId); if (oldLabelProvider != null) oldLabelProvider.dispose(); fgLabelProviders.put(pageId, labelProvider); @@ -301,10 +301,10 @@ public class SearchResultView extends ViewPart implements ISearchResultView { Assert.isNotNull(pluralLabelPattern); Assert.isNotNull(gotoAction); - fResponse= new HashMap(500); + fResponse= new HashMap<>(500); setGotoMarkerAction(gotoAction); - ILabelProvider oldLabelProvider= (ILabelProvider)fgLabelProviders.get(pageId); + ILabelProvider oldLabelProvider= fgLabelProviders.get(pageId); if (oldLabelProvider != null) oldLabelProvider.dispose(); fgLabelProviders.put(pageId, labelProvider); @@ -327,7 +327,7 @@ public class SearchResultView extends ViewPart implements ISearchResultView { */ @Override public void addMatch(String description, Object groupByKey, IResource resource, IMarker marker) { - SearchResultViewEntry entry= (SearchResultViewEntry)fResponse.get(groupByKey); + SearchResultViewEntry entry= fResponse.get(groupByKey); if (entry == null) { entry= new SearchResultViewEntry(groupByKey, resource); fResponse.put(groupByKey, entry); @@ -341,7 +341,7 @@ public class SearchResultView extends ViewPart implements ISearchResultView { */ @Override public void searchFinished() { - SearchManager.getDefault().searchFinished(new ArrayList(fResponse.values())); + SearchManager.getDefault().searchFinished(new ArrayList<>(fResponse.values())); fResponse= null; } } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewEntry.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewEntry.java index 5e73850e8a2..485f60bd8e1 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewEntry.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewEntry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -34,8 +34,8 @@ public class SearchResultViewEntry extends PlatformObject implements ISearchResu private Object fGroupByKey= null; private IResource fResource= null; private IMarker fMarker= null; - private ArrayList fMarkers= null; - private ArrayList fAttributes; + private ArrayList<IMarker> fMarkers= null; + private ArrayList<Map<String, Object>> fAttributes; private int fSelectedMarkerIndex; private long fModificationStamp= IResource.NULL_STAMP; private String fMarkerType; @@ -77,9 +77,9 @@ public class SearchResultViewEntry extends PlatformObject implements ISearchResu return false; } - List getAttributesPerMarker() { + List<Map<String, Object>> getAttributesPerMarker() { if (fAttributes == null) - return new ArrayList(0); + return new ArrayList<>(0); return fAttributes; } @@ -109,7 +109,7 @@ public class SearchResultViewEntry extends PlatformObject implements ISearchResu return; } if (fMarkers == null) { - fMarkers= new ArrayList(10); + fMarkers= new ArrayList<>(10); addByStartpos(fMarkers, fMarker); } addByStartpos(fMarkers, marker); @@ -125,15 +125,15 @@ public class SearchResultViewEntry extends PlatformObject implements ISearchResu if (fMarkers == null && fMarker == null) return null; if (fMarkers != null && fSelectedMarkerIndex >= 0) - return (IMarker)fMarkers.get(fSelectedMarkerIndex); + return fMarkers.get(fSelectedMarkerIndex); return fMarker; } - public List getMarkers() { + public List<IMarker> getMarkers() { if (fMarkers == null && fMarker == null) - return new ArrayList(0); + return new ArrayList<>(0); else if (fMarkers == null && fMarker != null) { - List markers= new ArrayList(1); + List<IMarker> markers= new ArrayList<>(1); markers.add(fMarker); return markers; } @@ -165,7 +165,7 @@ public class SearchResultViewEntry extends PlatformObject implements ISearchResu else { fMarkers.remove(marker); if (fMarkers.size() == 1) { - fMarker= (IMarker)fMarkers.get(0); + fMarker= fMarkers.get(0); fMarkers= null; } } @@ -174,12 +174,12 @@ public class SearchResultViewEntry extends PlatformObject implements ISearchResu void backupMarkers() { if (fResource != null) fModificationStamp= fResource.getModificationStamp(); - List markers= getMarkers(); - fAttributes= new ArrayList(markers.size()); - Iterator iter= markers.iterator(); + List<IMarker> markers= getMarkers(); + fAttributes= new ArrayList<>(markers.size()); + Iterator<IMarker> iter= markers.iterator(); while (iter.hasNext()) { - IMarker marker= (IMarker)iter.next(); - Map attributes= null; + IMarker marker= iter.next(); + Map<String, Object> attributes= null; try { attributes= marker.getAttributes(); } catch (CoreException ex) { @@ -190,11 +190,11 @@ public class SearchResultViewEntry extends PlatformObject implements ISearchResu } } - private void addByStartpos(ArrayList markers, IMarker marker) { + private void addByStartpos(ArrayList<IMarker> markers, IMarker marker) { int startPos= marker.getAttribute(IMarker.CHAR_START, -1); int i= 0; int markerCount= markers.size(); - while (i < markerCount && startPos >= ((IMarker)markers.get(i)).getAttribute(IMarker.CHAR_START, -1)) + while (i < markerCount && startPos >= markers.get(i).getAttribute(IMarker.CHAR_START, -1)) i++; markers.add(i, marker); if (i == 0) @@ -202,7 +202,7 @@ public class SearchResultViewEntry extends PlatformObject implements ISearchResu } @Override - public Object getAdapter(Class adapter) { + public <T> T getAdapter(Class<T> adapter) { return super.getAdapter(adapter); } } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewEntryAdapterFactory.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewEntryAdapterFactory.java index 7151156a8bd..b122d1628b9 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewEntryAdapterFactory.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewEntryAdapterFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -27,23 +27,24 @@ import org.eclipse.search.ui.ISearchResultViewEntry; @Deprecated public class SearchResultViewEntryAdapterFactory implements IAdapterFactory { - private static Class[] PROPERTIES= new Class[] { + private static Class<?>[] PROPERTIES= new Class[] { IResource.class, IMarker.class, }; @Override - public Class[] getAdapterList() { + public Class<?>[] getAdapterList() { return PROPERTIES; } + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Object element, Class key) { + public <T> T getAdapter(Object element, Class<T> key) { ISearchResultViewEntry entry= (ISearchResultViewEntry) element; if (IMarker.class.equals(key)) { - return entry.getSelectedMarker(); + return (T) entry.getSelectedMarker(); } if (IResource.class.equals(key)) { IResource resource= entry.getResource(); @@ -54,7 +55,7 @@ public class SearchResultViewEntryAdapterFactory implements IAdapterFactory { */ int type= resource.getType(); if (type != IResource.PROJECT && type != IResource.ROOT) - return resource; + return (T) resource; } return null; } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewer.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewer.java index aa53a3c97bb..4af2237ee0f 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewer.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SearchResultViewer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -347,7 +347,7 @@ public class SearchResultViewer extends TableViewer { if (getSelectedEntriesCount() == 0) return false; - Iterator iter= Collections.EMPTY_LIST.iterator(); + Iterator<?> iter= Collections.emptyList().iterator(); ISelection selection= getSelection(); if (selection instanceof IStructuredSelection) iter= ((IStructuredSelection)selection).iterator(); @@ -677,7 +677,7 @@ public class SearchResultViewer extends TableViewer { protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { Object[] changed= event.getElements(); if (changed != null && !fResourceToItemsMapper.isEmpty()) { - ArrayList others= new ArrayList(changed.length); + ArrayList<Object> others= new ArrayList<>(changed.length); for (int i= 0; i < changed.length; i++) { Object curr= changed[i]; if (curr instanceof IResource) diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SelectAllAction.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SelectAllAction.java index 1b4be53d703..1e497535be0 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SelectAllAction.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SelectAllAction.java @@ -44,7 +44,7 @@ public class SelectAllAction extends Action { fViewer= viewer; } - private void collectExpandedAndVisible(TreeItem[] items, List result) { + private void collectExpandedAndVisible(TreeItem[] items, List<TreeItem> result) { for (int i= 0; i < items.length; i++) { TreeItem item= items[i]; result.add(item); @@ -63,10 +63,10 @@ public class SelectAllAction extends Action { return; } if (fViewer instanceof TreeViewer) { - ArrayList allVisible= new ArrayList(); + ArrayList<TreeItem> allVisible= new ArrayList<>(); Tree tree= ((TreeViewer) fViewer).getTree(); collectExpandedAndVisible(tree.getItems(), allVisible); - tree.setSelection((TreeItem[]) allVisible.toArray(new TreeItem[allVisible.size()])); + tree.setSelection(allVisible.toArray(new TreeItem[allVisible.size()])); } else if (fViewer instanceof TableViewer) { ((TableViewer) fViewer).getTable().selectAll(); // force viewer selection change diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/ShowSearchesAction.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/ShowSearchesAction.java index 10ee4dd15e5..4c504e5e774 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/ShowSearchesAction.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/ShowSearchesAction.java @@ -36,7 +36,7 @@ class ShowSearchesAction extends Action { private static final class SearchesLabelProvider extends LabelProvider { - private ArrayList fImages= new ArrayList(); + private ArrayList<Image> fImages= new ArrayList<>(); @Override public String getText(Object element) { @@ -61,9 +61,9 @@ class ShowSearchesAction extends Action { @Override public void dispose() { - Iterator iter= fImages.iterator(); + Iterator<Image> iter= fImages.iterator(); while (iter.hasNext()) - ((Image)iter.next()).dispose(); + iter.next().dispose(); fImages= null; } @@ -85,7 +85,7 @@ class ShowSearchesAction extends Action { } public void run(boolean showAll) { - Iterator iter= SearchManager.getDefault().getPreviousSearches().iterator(); + Iterator<Search> iter= SearchManager.getDefault().getPreviousSearches().iterator(); int cutOffSize; if (showAll) cutOffSize= 0; @@ -94,10 +94,10 @@ class ShowSearchesAction extends Action { int size= SearchManager.getDefault().getPreviousSearches().size() - cutOffSize; Search selectedSearch= SearchManager.getDefault().getCurrentSearch(); Action selectedAction = null; - ArrayList input= new ArrayList(size); + ArrayList<Action> input= new ArrayList<>(size); int i= 0; while (iter.hasNext()) { - Search search= (Search)iter.next(); + Search search= iter.next(); if (i++ < cutOffSize) continue; Action action= new ShowSearchAction(search); @@ -132,7 +132,7 @@ class ShowSearchesAction extends Action { dlg.setInitialSelections(selected); } if (dlg.open() == Window.OK) { - List result= Arrays.asList(dlg.getResult()); + List<Object> result= Arrays.asList(dlg.getResult()); if (result != null && result.size() == 1) { ((ShowSearchAction)result.get(0)).run(); } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/SortDropDownAction.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/SortDropDownAction.java index 8e973814622..0130c9cc70c 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/SortDropDownAction.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/SortDropDownAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,6 +13,7 @@ package org.eclipse.search.internal.ui; import java.util.HashMap; import java.util.Iterator; import java.util.Map; +import java.util.Map.Entry; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.widgets.Control; @@ -40,12 +41,12 @@ class SortDropDownAction extends Action implements IMenuCreator { private static final String TAG_PAGE_ID= "pageId"; //$NON-NLS-1$ private static final String TAG_SORTER_ID= "sorterId"; //$NON-NLS-1$ - private static Map fgLastCheckedForType= new HashMap(5); + private static Map<String, SorterDescriptor> fgLastCheckedForType= new HashMap<>(5); private SearchResultViewer fViewer; private String fPageId; private Menu fMenu; - private Map fLastCheckedForType; + private Map<String, SorterDescriptor> fLastCheckedForType; public SortDropDownAction(SearchResultViewer viewer) { super(SearchMessages.SortDropDownAction_label); @@ -53,7 +54,7 @@ class SortDropDownAction extends Action implements IMenuCreator { fViewer= viewer; setToolTipText(SearchMessages.SortDropDownAction_tooltip); setMenuCreator(this); - fLastCheckedForType= new HashMap(5); + fLastCheckedForType= new HashMap<>(5); } @Override @@ -70,9 +71,9 @@ class SortDropDownAction extends Action implements IMenuCreator { void setPageId(String pageId) { fPageId= pageId; - SorterDescriptor sorterDesc= (SorterDescriptor)fLastCheckedForType.get(pageId); + SorterDescriptor sorterDesc= fLastCheckedForType.get(pageId); if (sorterDesc == null) - sorterDesc= (SorterDescriptor)fgLastCheckedForType.get(pageId); + sorterDesc= fgLastCheckedForType.get(pageId); if (sorterDesc == null) sorterDesc= findSorter(fPageId); if (sorterDesc != null) { @@ -90,7 +91,7 @@ class SortDropDownAction extends Action implements IMenuCreator { fMenu= new Menu(parent); - Iterator iter= SearchPlugin.getDefault().getSorterDescriptors().iterator(); + Iterator<SorterDescriptor> iter= SearchPlugin.getDefault().getSorterDescriptors().iterator(); while (iter.hasNext()) { Object value= fLastCheckedForType.get(fPageId); final String checkedId; @@ -99,7 +100,7 @@ class SortDropDownAction extends Action implements IMenuCreator { else checkedId= ""; //$NON-NLS-1$ - final SorterDescriptor sorterDesc= (SorterDescriptor) iter.next(); + final SorterDescriptor sorterDesc= iter.next(); if (!sorterDesc.getPageId().equals(fPageId) && !sorterDesc.getPageId().equals("*")) //$NON-NLS-1$ continue; final ViewerSorter sorter= sorterDesc.createObject(); @@ -139,9 +140,9 @@ class SortDropDownAction extends Action implements IMenuCreator { } private SorterDescriptor findSorter(String pageId) { - Iterator iter= SearchPlugin.getDefault().getSorterDescriptors().iterator(); + Iterator<SorterDescriptor> iter= SearchPlugin.getDefault().getSorterDescriptors().iterator(); while (iter.hasNext()) { - SorterDescriptor sorterDesc= (SorterDescriptor)iter.next(); + SorterDescriptor sorterDesc= iter.next(); if (sorterDesc.getPageId().equals(pageId) || sorterDesc.getPageId().equals("*")) //$NON-NLS-1$ return sorterDesc; } @@ -149,9 +150,9 @@ class SortDropDownAction extends Action implements IMenuCreator { } private SorterDescriptor getSorter(String sorterId) { - Iterator iter= SearchPlugin.getDefault().getSorterDescriptors().iterator(); + Iterator<SorterDescriptor> iter= SearchPlugin.getDefault().getSorterDescriptors().iterator(); while (iter.hasNext()) { - SorterDescriptor sorterDesc= (SorterDescriptor)iter.next(); + SorterDescriptor sorterDesc= iter.next(); if (sorterDesc.getId().equals(sorterId)) return sorterDesc; } @@ -184,7 +185,7 @@ class SortDropDownAction extends Action implements IMenuCreator { restoreState(memento, fgLastCheckedForType, TAG_DEFAULT_SORTERS); } - private void restoreState(IMemento memento, Map map, String mapName) { + private void restoreState(IMemento memento, Map<String, SorterDescriptor> map, String mapName) { memento= memento.getChild(mapName); if (memento == null) return; @@ -203,22 +204,22 @@ class SortDropDownAction extends Action implements IMenuCreator { saveState(memento, fLastCheckedForType, TAG_SORTERS); } - private void saveState(IMemento memento, Map map, String mapName) { - Iterator iter= map.entrySet().iterator(); + private void saveState(IMemento memento, Map<String, SorterDescriptor> map, String mapName) { + Iterator<Entry<String, SorterDescriptor>> iter= map.entrySet().iterator(); memento= memento.createChild(mapName); while (iter.hasNext()) { IMemento mementoElement= memento.createChild(TAG_ELEMENT); - Map.Entry entry= (Map.Entry)iter.next(); - mementoElement.putString(TAG_PAGE_ID, (String)entry.getKey()); - mementoElement.putString(TAG_SORTER_ID, ((SorterDescriptor)entry.getValue()).getId()); + Entry<String, SorterDescriptor> entry= iter.next(); + mementoElement.putString(TAG_PAGE_ID, entry.getKey()); + mementoElement.putString(TAG_SORTER_ID, entry.getValue().getId()); } } int getSorterCount() { int count= 0; - Iterator iter= SearchPlugin.getDefault().getSorterDescriptors().iterator(); + Iterator<SorterDescriptor> iter= SearchPlugin.getDefault().getSorterDescriptors().iterator(); while (iter.hasNext()) { - SorterDescriptor sorterDesc= (SorterDescriptor)iter.next(); + SorterDescriptor sorterDesc= iter.next(); if (sorterDesc.getPageId().equals(fPageId) || sorterDesc.getPageId().equals("*")) //$NON-NLS-1$ count++; } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/WorkingSetComparator.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/WorkingSetComparator.java index 9fbc46976b7..075c3511a60 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/WorkingSetComparator.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/WorkingSetComparator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -16,21 +16,14 @@ import com.ibm.icu.text.Collator; import org.eclipse.ui.IWorkingSet; -public class WorkingSetComparator implements Comparator { +public class WorkingSetComparator implements Comparator<IWorkingSet> { private Collator fCollator= Collator.getInstance(); @Override - public int compare(Object o1, Object o2) { - String name1= null; - String name2= null; - - if (o1 instanceof IWorkingSet) - name1= ((IWorkingSet)o1).getLabel(); - - if (o2 instanceof IWorkingSet) - name2= ((IWorkingSet)o2).getLabel(); - + public int compare(IWorkingSet o1, IWorkingSet o2) { + String name1= o1.getLabel(); + String name2= o2.getLabel(); return fCollator.compare(name1, name2); } } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/EditorOpener.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/EditorOpener.java index 8b0744b8259..f907e685d61 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/EditorOpener.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/EditorOpener.java @@ -127,7 +127,7 @@ public class EditorOpener { IMarker marker= null; try { marker= file.createMarker(NewSearchUI.SEARCH_MARKER); - HashMap attributes= new HashMap(4); + HashMap<String, Integer> attributes= new HashMap<>(4); attributes.put(IMarker.CHAR_START, new Integer(offset)); attributes.put(IMarker.CHAR_END, new Integer(offset + length)); marker.setAttributes(attributes); diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileLabelProvider.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileLabelProvider.java index 6d90937d259..797e7f7a278 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileLabelProvider.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,11 +21,11 @@ import org.eclipse.swt.graphics.Image; import org.eclipse.core.resources.IResource; +import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.StyledCellLabelProvider; import org.eclipse.jface.viewers.StyledString; -import org.eclipse.jface.viewers.DelegatingStyledCellLabelProvider.IStyledLabelProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; @@ -48,7 +48,7 @@ public class FileLabelProvider extends LabelProvider implements IStyledLabelProv private final WorkbenchLabelProvider fLabelProvider; private final AbstractTextSearchViewPage fPage; - private final Comparator fMatchComparator; + private final Comparator<FileMatch> fMatchComparator; private final Image fLineMatchImage; @@ -59,10 +59,10 @@ public class FileLabelProvider extends LabelProvider implements IStyledLabelProv fOrder= orderFlag; fPage= page; fLineMatchImage= SearchPluginImages.get(SearchPluginImages.IMG_OBJ_TEXT_SEARCH_LINE); - fMatchComparator= new Comparator() { + fMatchComparator= new Comparator<FileMatch>() { @Override - public int compare(Object o1, Object o2) { - return ((FileMatch) o1).getOriginalOffset() - ((FileMatch) o2).getOriginalOffset(); + public int compare(FileMatch o1, FileMatch o2) { + return o1.getOriginalOffset() - o2.getOriginalOffset(); } }; } @@ -116,7 +116,7 @@ public class FileLabelProvider extends LabelProvider implements IStyledLabelProv StyledString str= new StyledString(lineNumberString, StyledString.QUALIFIER_STYLER); - Match[] matches= lineElement.getMatches(fPage.getInput()); + FileMatch[] matches= lineElement.getMatches(fPage.getInput()); Arrays.sort(matches, fMatchComparator); String content= lineElement.getContents(); @@ -127,7 +127,7 @@ public class FileLabelProvider extends LabelProvider implements IStyledLabelProv int charsToCut= getCharsToCut(length, matches); // number of characters to leave away if the line is too long for (int i= 0; i < matches.length; i++) { - FileMatch match= (FileMatch) matches[i]; + FileMatch match= matches[i]; int start= Math.max(match.getOriginalOffset() - lineElement.getOffset(), 0); // append gap between last match and the new one if (pos < start) { diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileSearchPage.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileSearchPage.java index a40dcf2e78e..55d54928f5b 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileSearchPage.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileSearchPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -104,7 +104,9 @@ public class FileSearchPage extends AbstractTextSearchViewPage implements IAdapt name1 = "";//$NON-NLS-1$ if (name2 == null) name2 = "";//$NON-NLS-1$ - return getComparator().compare(name1, name2); + @SuppressWarnings("unchecked") + int result= getComparator().compare(name1, name2); + return result; } } @@ -308,10 +310,11 @@ public class FileSearchPage extends AbstractTextSearchViewPage implements IAdapt memento.putInteger(KEY_LIMIT, getElementLimit().intValue()); } + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Class adapter) { + public <T> T getAdapter(Class<T> adapter) { if (IShowInTargetList.class.equals(adapter)) { - return SHOW_IN_TARGET_LIST; + return (T) SHOW_IN_TARGET_LIST; } if (adapter == IShowInSource.class) { @@ -322,8 +325,8 @@ public class FileSearchPage extends AbstractTextSearchViewPage implements IAdapt ISelection selection= selectionProvider.getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection= ((StructuredSelection)selection); - final Set newSelection= new HashSet(structuredSelection.size()); - Iterator iter= structuredSelection.iterator(); + final Set<Object> newSelection= new HashSet<>(structuredSelection.size()); + Iterator<?> iter= structuredSelection.iterator(); while (iter.hasNext()) { Object element= iter.next(); if (element instanceof LineElement) @@ -331,10 +334,10 @@ public class FileSearchPage extends AbstractTextSearchViewPage implements IAdapt newSelection.add(element); } - return new IShowInSource() { + return (T) new IShowInSource() { @Override public ShowInContext getShowInContext() { - return new ShowInContext(null, new StructuredSelection(new ArrayList(newSelection))); + return new ShowInContext(null, new StructuredSelection(new ArrayList<>(newSelection))); } }; } @@ -395,7 +398,7 @@ public class FileSearchPage extends AbstractTextSearchViewPage implements IAdapt } @Override - protected void evaluateChangedElements(Match[] matches, Set changedElements) { + protected void evaluateChangedElements(Match[] matches, Set<Object> changedElements) { if (showLineMatches()) { for (int i = 0; i < matches.length; i++) { changedElements.add(((FileMatch) matches[i]).getLineElement()); diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileSearchQuery.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileSearchQuery.java index 04328300593..1b47a288596 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileSearchQuery.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileSearchQuery.java @@ -52,7 +52,7 @@ public class FileSearchQuery implements ISearchQuery { private final boolean fSearchInBinaries; private final boolean fIsLightweightAutoRefresh; - private Map fCachedMatches; // map of IFile -> ArrayList of FileMatches + private Map<IFile, ArrayList<FileMatch>> fCachedMatches; private Object fLock= new Object(); private TextSearchResultCollector(AbstractTextSearchResult result, boolean isFileSearchOnly, boolean searchInBinaries) { @@ -89,7 +89,7 @@ public class FileSearchQuery implements ISearchQuery { @Override public boolean acceptPatternMatch(TextSearchMatchAccess matchRequestor) throws CoreException { - ArrayList matches; + ArrayList<FileMatch> matches; synchronized(fLock) { // fCachedMatches is set to null when the caller invokes endReporting(), // indicating that no further results are desired/expected, so discard @@ -97,7 +97,7 @@ public class FileSearchQuery implements ISearchQuery { if (fCachedMatches == null) { return false; } - matches= (ArrayList) fCachedMatches.get(matchRequestor.getFile()); + matches= fCachedMatches.get(matchRequestor.getFile()); } int matchOffset= matchRequestor.getMatchOffset(); @@ -120,9 +120,9 @@ public class FileSearchQuery implements ISearchQuery { if (fCachedMatches == null) { return false; } - matches= (ArrayList) fCachedMatches.get(matchRequestor.getFile()); + matches= fCachedMatches.get(matchRequestor.getFile()); if (matches == null) { - matches= new ArrayList(); + matches= new ArrayList<>(); fCachedMatches.put(matchRequestor.getFile(), matches); } matches.add(fileMatch); @@ -131,13 +131,13 @@ public class FileSearchQuery implements ISearchQuery { return true; } - private LineElement getLineElement(int offset, TextSearchMatchAccess matchRequestor, ArrayList matches) { + private LineElement getLineElement(int offset, TextSearchMatchAccess matchRequestor, ArrayList<FileMatch> matches) { int lineNumber= 1; int lineStart= 0; if (matches != null) { // match on same line as last? - FileMatch last= (FileMatch) matches.get(matches.size() - 1); + FileMatch last= matches.get(matches.size() - 1); LineElement lineElement= last.getLineElement(); if (lineElement.contains(offset)) { return lineElement; @@ -188,7 +188,7 @@ public class FileSearchQuery implements ISearchQuery { @Override public void beginReporting() { - fCachedMatches= new HashMap(); + fCachedMatches= new HashMap<>(); } @Override @@ -202,10 +202,10 @@ public class FileSearchQuery implements ISearchQuery { private void flushMatches() { synchronized (fLock) { if (fCachedMatches != null && !fCachedMatches.isEmpty()) { - Iterator it = fCachedMatches.values().iterator(); + Iterator<ArrayList<FileMatch>> it = fCachedMatches.values().iterator(); while(it.hasNext()) { - ArrayList matches= (ArrayList) it.next(); - fResult.addMatches((Match[]) matches.toArray(new Match[matches.size()])); + ArrayList<FileMatch> matches= it.next(); + fResult.addMatches(matches.toArray(new Match[matches.size()])); } fCachedMatches.clear(); } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileTreeContentProvider.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileTreeContentProvider.java index d891cd5e2e7..8ee249cb20e 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileTreeContentProvider.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/FileTreeContentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -36,7 +36,7 @@ public class FileTreeContentProvider implements ITreeContentProvider, IFileSearc private AbstractTextSearchResult fResult; private FileSearchPage fPage; private AbstractTreeViewer fTreeViewer; - private Map fChildrenMap; + private Map<Object, Set<Object>> fChildrenMap; FileTreeContentProvider(FileSearchPage page, AbstractTreeViewer viewer) { fPage= page; @@ -73,7 +73,7 @@ public class FileTreeContentProvider implements ITreeContentProvider, IFileSearc private synchronized void initialize(AbstractTextSearchResult result) { fResult= result; - fChildrenMap= new HashMap(); + fChildrenMap= new HashMap<>(); boolean showLineMatches= !((FileSearchQuery) fResult.getQuery()).isFileNameSearch(); if (result != null) { @@ -120,16 +120,16 @@ public class FileTreeContentProvider implements ITreeContentProvider, IFileSearc */ private boolean insertChild(Object parent, Object child) { - Set children= (Set) fChildrenMap.get(parent); + Set<Object> children= fChildrenMap.get(parent); if (children == null) { - children= new HashSet(); + children= new HashSet<>(); fChildrenMap.put(parent, children); } return children.add(child); } private boolean hasChild(Object parent, Object child) { - Set children= (Set) fChildrenMap.get(parent); + Set<Object> children= fChildrenMap.get(parent); return children != null && children.contains(child); } @@ -170,7 +170,7 @@ public class FileTreeContentProvider implements ITreeContentProvider, IFileSearc private void removeFromSiblings(Object element, Object parent) { - Set siblings= (Set) fChildrenMap.get(parent); + Set<Object> siblings= fChildrenMap.get(parent); if (siblings != null) { siblings.remove(element); } @@ -178,7 +178,7 @@ public class FileTreeContentProvider implements ITreeContentProvider, IFileSearc @Override public Object[] getChildren(Object parentElement) { - Set children= (Set) fChildrenMap.get(parentElement); + Set<Object> children= fChildrenMap.get(parentElement); if (children == null) return EMPTY_ARR; return children.toArray(); diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/LineElement.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/LineElement.java index 7d0e0c1019e..cb9c0d2ff16 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/LineElement.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/LineElement.java @@ -62,7 +62,7 @@ public class LineElement { } public FileMatch[] getMatches(AbstractTextSearchResult result) { - ArrayList res= new ArrayList(); + ArrayList<FileMatch> res= new ArrayList<>(); Match[] matches= result.getMatches(fParent); for (int i= 0; i < matches.length; i++) { FileMatch curr= (FileMatch) matches[i]; @@ -70,7 +70,7 @@ public class LineElement { res.add(curr); } } - return (FileMatch[]) res.toArray(new FileMatch[res.size()]); + return res.toArray(new FileMatch[res.size()]); } public int getNumberOfMatches(AbstractTextSearchResult result) { diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/ReplaceConfigurationPage.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/ReplaceConfigurationPage.java index 838c4a6828e..ee0710c580a 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/ReplaceConfigurationPage.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/ReplaceConfigurationPage.java @@ -196,7 +196,7 @@ public class ReplaceConfigurationPage extends UserInputWizardPage { private void storeSettings() { String[] items= fTextField.getItems(); - ArrayList history= new ArrayList(); + ArrayList<String> history= new ArrayList<>(); history.add(fTextField.getText()); int historySize= Math.min(items.length, 6); for (int i= 0; i < historySize; i++) { @@ -206,7 +206,7 @@ public class ReplaceConfigurationPage extends UserInputWizardPage { } } IDialogSettings settings= SearchPlugin.getDefault().getDialogSettings().addNewSection(SETTINGS_GROUP); - settings.put(SETTINGS_REPLACE_WITH, (String[]) history.toArray(new String[history.size()])); + settings.put(SETTINGS_REPLACE_WITH, history.toArray(new String[history.size()])); } diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/ReplaceRefactoring.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/ReplaceRefactoring.java index 67bde0296be..c8d7bcee13c 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/ReplaceRefactoring.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/ReplaceRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2011 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -19,6 +19,7 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; @@ -87,16 +88,16 @@ public class ReplaceRefactoring extends Refactoring { private MatchGroup[] fMatchGroups; private Match[] fMatches; - private Map/*<URI,ArrayList<Match>*/ fIgnoredMatches; + private Map<URI, ArrayList<FileMatch>> fIgnoredMatches; private final FileSearchResult fResult; private final boolean fIsRemove; - public SearchResultUpdateChange(FileSearchResult result, MatchGroup[] matchGroups, Map ignoredMatches) { + public SearchResultUpdateChange(FileSearchResult result, MatchGroup[] matchGroups, Map<URI, ArrayList<FileMatch>> ignoredMatches) { this(result, null, ignoredMatches, true); fMatchGroups= matchGroups; } - private SearchResultUpdateChange(FileSearchResult result, Match[] matches, Map ignoredMatches, boolean isRemove) { + private SearchResultUpdateChange(FileSearchResult result, Match[] matches, Map<URI, ArrayList<FileMatch>> ignoredMatches, boolean isRemove) { fResult= result; fMatches= matches; fIgnoredMatches= ignoredMatches; @@ -124,7 +125,7 @@ public class ReplaceRefactoring extends Refactoring { private Match[] getMatches() { if (fMatches == null) { - ArrayList matches= new ArrayList(); + ArrayList<FileMatch> matches= new ArrayList<>(); for (int i= 0; i < fMatchGroups.length; i++) { MatchGroup curr= fMatchGroups[i]; if (curr.group.isEnabled()) { @@ -138,13 +139,13 @@ public class ReplaceRefactoring extends Refactoring { IFile file= match.getFile(); URI uri= file.getLocationURI(); if (uri != null) { - ArrayList ignoredMatches= (ArrayList)fIgnoredMatches.get(uri); + ArrayList<FileMatch> ignoredMatches= fIgnoredMatches.get(uri); if (ignoredMatches != null) matches.addAll(ignoredMatches); } } } - fMatches= (Match[]) matches.toArray(new Match[matches.size()]); + fMatches= matches.toArray(new Match[matches.size()]); fMatchGroups= null; } return fMatches; @@ -168,13 +169,13 @@ public class ReplaceRefactoring extends Refactoring { private final FileSearchResult fResult; private final Object[] fSelection; - private final HashMap/*<IFile,Set<Match>*/ fMatches; + private final HashMap<IFile, Set<FileMatch>> fMatches; /** Map that keeps already collected locations. */ - private final Map/*<URI,IFile>*/fAlreadyCollected; + private final Map<URI, IFile> fAlreadyCollected; /** Map that keeps ignored matches (can be null). */ - private Map/*<URI,ArrayList<Match>*/ fIgnoredMatches; + private Map<URI, ArrayList<FileMatch>> fIgnoredMatches; private String fReplaceString; @@ -186,8 +187,8 @@ public class ReplaceRefactoring extends Refactoring { fResult= result; fSelection= selection; - fMatches= new HashMap(); - fAlreadyCollected= new HashMap(selection != null ? selection.length : result.getElements().length); + fMatches= new HashMap<>(); + fAlreadyCollected= new HashMap<>(selection != null ? selection.length : result.getElements().length); fReplaceString= null; } @@ -244,7 +245,7 @@ public class ReplaceRefactoring extends Refactoring { } else if (object instanceof IFile) { Match[] matches= fResult.getMatches(object); if (matches.length > 0) { - Collection bucket= null; + Collection<FileMatch> bucket= null; for (int i= 0; i < matches.length; i++) { FileMatch fileMatch= (FileMatch) matches[i]; if (isMatchToBeIncluded(fileMatch)) { @@ -264,8 +265,8 @@ public class ReplaceRefactoring extends Refactoring { public int getNumberOfMatches() { int count= 0; - for (Iterator iterator= fMatches.values().iterator(); iterator.hasNext();) { - Collection bucket= (Collection) iterator.next(); + for (Iterator<Set<FileMatch>> iterator= fMatches.values().iterator(); iterator.hasNext();) { + Set<FileMatch> bucket= iterator.next(); count += bucket.size(); } return count; @@ -289,17 +290,17 @@ public class ReplaceRefactoring extends Refactoring { if (uri == null) return true; - for (Iterator iter= fAlreadyCollected.keySet().iterator(); iter.hasNext();) { - if (URIUtil.equals((URI)iter.next(), uri)) { + for (Iterator<URI> iter= fAlreadyCollected.keySet().iterator(); iter.hasNext();) { + if (URIUtil.equals(iter.next(), uri)) { if (file.equals(fAlreadyCollected.get(uri))) return true; // another FileMatch for an IFile which already had matches if (fIgnoredMatches == null) - fIgnoredMatches= new HashMap(); + fIgnoredMatches= new HashMap<>(); - ArrayList matches= (ArrayList)fIgnoredMatches.get(uri); + ArrayList<FileMatch> matches= fIgnoredMatches.get(uri); if (matches == null) { - matches= new ArrayList(); + matches= new ArrayList<>(); fIgnoredMatches.put(uri, matches); } matches.add(match); @@ -312,13 +313,13 @@ public class ReplaceRefactoring extends Refactoring { return true; } - private Collection getBucket(IFile file) { - Collection col= (Collection) fMatches.get(file); - if (col == null) { - col= new HashSet(); - fMatches.put(file, col); + private Set<FileMatch> getBucket(IFile file) { + Set<FileMatch> set= fMatches.get(file); + if (set == null) { + set= new HashSet<>(); + fMatches.put(file, set); } - return col; + return set; } @Override @@ -335,14 +336,14 @@ public class ReplaceRefactoring extends Refactoring { RefactoringStatus resultingStatus= new RefactoringStatus(); - Collection allFilesSet= fMatches.keySet(); - IFile[] allFiles= (IFile[]) allFilesSet.toArray(new IFile[allFilesSet.size()]); - Arrays.sort(allFiles, new Comparator() { + Collection<IFile> allFilesSet= fMatches.keySet(); + IFile[] allFiles= allFilesSet.toArray(new IFile[allFilesSet.size()]); + Arrays.sort(allFiles, new Comparator<IFile>() { private Collator fCollator= Collator.getInstance(); @Override - public int compare(Object o1, Object o2) { - String p1= ((IFile) o1).getFullPath().toString(); - String p2= ((IFile) o2).getFullPath().toString(); + public int compare(IFile o1, IFile o2) { + String p1= o1.getFullPath().toString(); + String p2= o2.getFullPath().toString(); return fCollator.compare(p1, p2); } }); @@ -354,12 +355,12 @@ public class ReplaceRefactoring extends Refactoring { CompositeChange compositeChange= new CompositeChange(SearchMessages.ReplaceRefactoring_composite_change_name); compositeChange.markAsSynthetic(); - ArrayList matchGroups= new ArrayList(); + ArrayList<MatchGroup> matchGroups= new ArrayList<>(); boolean hasChanges= false; try { for (int i= 0; i < allFiles.length; i++) { IFile file= allFiles[i]; - Collection bucket= (Collection) fMatches.get(file); + Set<FileMatch> bucket= fMatches.get(file); if (!bucket.isEmpty()) { try { TextChange change= createFileChange(file, pattern, bucket, resultingStatus, matchGroups); @@ -381,20 +382,20 @@ public class ReplaceRefactoring extends Refactoring { return RefactoringStatus.createFatalErrorStatus(SearchMessages.ReplaceRefactoring_error_no_changes); } - compositeChange.add(new SearchResultUpdateChange(fResult, (MatchGroup[])matchGroups.toArray(new MatchGroup[matchGroups.size()]), fIgnoredMatches)); + compositeChange.add(new SearchResultUpdateChange(fResult, matchGroups.toArray(new MatchGroup[matchGroups.size()]), fIgnoredMatches)); fChange= compositeChange; return resultingStatus; } private void checkFilesToBeChanged(IFile[] filesToBeChanged, RefactoringStatus resultingStatus) throws CoreException { - ArrayList readOnly= new ArrayList(); + ArrayList<IFile> readOnly= new ArrayList<>(); for (int i= 0; i < filesToBeChanged.length; i++) { IFile file= filesToBeChanged[i]; if (file.isReadOnly()) readOnly.add(file); } - IFile[] readOnlyFiles= (IFile[]) readOnly.toArray(new IFile[readOnly.size()]); + IFile[] readOnlyFiles= readOnly.toArray(new IFile[readOnly.size()]); IStatus status= ResourcesPlugin.getWorkspace().validateEdit(readOnlyFiles, getValidationContext()); if (status.getSeverity() == IStatus.CANCEL) { @@ -407,7 +408,7 @@ public class ReplaceRefactoring extends Refactoring { resultingStatus.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeChanged, null)); } - private TextChange createFileChange(IFile file, Pattern pattern, Collection/*FileMatch*/ matches, RefactoringStatus resultingStatus, Collection matchGroups) throws PatternSyntaxException, CoreException { + private TextChange createFileChange(IFile file, Pattern pattern, Set<FileMatch> matches, RefactoringStatus resultingStatus, Collection<MatchGroup> matchGroups) throws PatternSyntaxException, CoreException { PositionTracker tracker= InternalSearchUI.getInstance().getPositionTracker(); TextFileChange change= new TextFileChange(Messages.format(SearchMessages.ReplaceRefactoring_group_label_change_for_file, file.getName()), file); @@ -424,8 +425,8 @@ public class ReplaceRefactoring extends Refactoring { IDocument document= textFileBuffer.getDocument(); String lineDelimiter= TextUtilities.getDefaultLineDelimiter(document); - for (Iterator iterator= matches.iterator(); iterator.hasNext();) { - FileMatch match= (FileMatch) iterator.next(); + for (Iterator<FileMatch> iterator= matches.iterator(); iterator.hasNext();) { + FileMatch match= iterator.next(); int offset= match.getOffset(); int length= match.getLength(); Position currentPosition= tracker.getCurrentPosition(match); diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/TextSearchPage.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/TextSearchPage.java index 039f1128bfb..5d81904ee4f 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/text/TextSearchPage.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/text/TextSearchPage.java @@ -112,7 +112,7 @@ public class TextSearchPage extends DialogPage implements ISearchPage, IReplaceP */ private static final String STORE_EXTENSIONS= "EXTENSIONS"; //$NON-NLS-1$ - private List fPreviousSearchPatterns= new ArrayList(HISTORY_SIZE); + private List<SearchPatternData> fPreviousSearchPatterns= new ArrayList<>(HISTORY_SIZE); private boolean fFirstTime= true; private boolean fIsCaseSensitive; @@ -336,10 +336,10 @@ public class TextSearchPage extends DialogPage implements ISearchPage, IReplaceP } private FileTextSearchScope getSelectedResourcesScope() { - HashSet resources= new HashSet(); + HashSet<IResource> resources= new HashSet<>(); ISelection sel= getContainer().getSelection(); if (sel instanceof IStructuredSelection && !sel.isEmpty()) { - Iterator iter= ((IStructuredSelection) sel).iterator(); + Iterator<?> iter= ((IStructuredSelection) sel).iterator(); while (iter.hasNext()) { Object curr= iter.next(); if (curr instanceof IWorkingSet) { @@ -368,7 +368,7 @@ public class TextSearchPage extends DialogPage implements ISearchPage, IReplaceP } else if (getContainer().getActiveEditorInput() != null) { resources.add(getContainer().getActiveEditorInput().getAdapter(IFile.class)); } - IResource[] arr= (IResource[]) resources.toArray(new IResource[resources.size()]); + IResource[] arr= resources.toArray(new IResource[resources.size()]); return FileTextSearchScope.newSearchScope(arr, getExtensions(), fSearchDerived); } @@ -389,8 +389,8 @@ public class TextSearchPage extends DialogPage implements ISearchPage, IReplaceP private SearchPatternData findInPrevious(String pattern) { - for (Iterator iter= fPreviousSearchPatterns.iterator(); iter.hasNext();) { - SearchPatternData element= (SearchPatternData) iter.next(); + for (Iterator<SearchPatternData> iter= fPreviousSearchPatterns.iterator(); iter.hasNext();) { + SearchPatternData element= iter.next(); if (pattern.equals(element.textPattern)) { return element; } @@ -421,22 +421,22 @@ public class TextSearchPage extends DialogPage implements ISearchPage, IReplaceP } private String[] getPreviousExtensionsOldStyle() { - List extensions= new ArrayList(fPreviousSearchPatterns.size()); + List<String> extensions= new ArrayList<>(fPreviousSearchPatterns.size()); int size= fPreviousSearchPatterns.size(); for (int i= 0; i < size; i++) { - SearchPatternData data= (SearchPatternData)fPreviousSearchPatterns.get(i); + SearchPatternData data= fPreviousSearchPatterns.get(i); String text= FileTypeEditor.typesToString(data.fileNamePatterns); if (!extensions.contains(text)) extensions.add(text); } - return (String[])extensions.toArray(new String[extensions.size()]); + return extensions.toArray(new String[extensions.size()]); } private String[] getPreviousSearchPatterns() { int size= fPreviousSearchPatterns.size(); String [] patterns= new String[size]; for (int i= 0; i < size; i++) - patterns[i]= ((SearchPatternData) fPreviousSearchPatterns.get(i)).textPattern; + patterns[i]= fPreviousSearchPatterns.get(i).textPattern; return patterns; } @@ -632,7 +632,7 @@ public class TextSearchPage extends DialogPage implements ISearchPage, IReplaceP if (selectionIndex < 0 || selectionIndex >= fPreviousSearchPatterns.size()) return; - SearchPatternData patternData= (SearchPatternData) fPreviousSearchPatterns.get(selectionIndex); + SearchPatternData patternData= fPreviousSearchPatterns.get(selectionIndex); if (!fPattern.getText().equals(patternData.textPattern)) return; fIsCaseSensitiveCheckbox.setSelection(patternData.isCaseSensitive); @@ -852,7 +852,7 @@ public class TextSearchPage extends DialogPage implements ISearchPage, IReplaceP // ignore } - Set previousExtensions= new LinkedHashSet(HISTORY_SIZE); + Set<String> previousExtensions= new LinkedHashSet<>(HISTORY_SIZE); IDialogSettings extensionsSettings= s.getSection(STORE_EXTENSIONS); if (extensionsSettings != null) { for (int i= 0; i < HISTORY_SIZE; i++) { @@ -883,13 +883,13 @@ public class TextSearchPage extends DialogPage implements ISearchPage, IReplaceP s.put(STORE_HISTORY_SIZE, historySize); for (int i= 0; i < historySize; i++) { IDialogSettings histSettings= s.addNewSection(STORE_HISTORY + i); - SearchPatternData data= ((SearchPatternData) fPreviousSearchPatterns.get(i)); + SearchPatternData data= fPreviousSearchPatterns.get(i); data.store(histSettings); } IDialogSettings extensionsSettings= s.addNewSection(STORE_EXTENSIONS); extensionsSettings.put(Integer.toString(0), fExtensions.getText()); - Set extensions= new HashSet(HISTORY_SIZE); + Set<String> extensions= new HashSet<>(HISTORY_SIZE); extensions.add(fExtensions.getText()); int length= Math.min(fExtensions.getItemCount(), HISTORY_SIZE - 1); int j= 1; diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/util/ExtendedDialogWindow.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/util/ExtendedDialogWindow.java index c479282aaa0..70819f64665 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/util/ExtendedDialogWindow.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/util/ExtendedDialogWindow.java @@ -47,7 +47,7 @@ public abstract class ExtendedDialogWindow extends TrayDialog implements IRunnab private Control fContents; private Button fCancelButton; - private List fActionButtons; + private List<Button> fActionButtons; // The number of long running operation executed from the dialog. private long fActiveRunningOperations; @@ -60,7 +60,7 @@ public abstract class ExtendedDialogWindow extends TrayDialog implements IRunnab public ExtendedDialogWindow(Shell shell) { super(shell); - fActionButtons= new ArrayList(); + fActionButtons= new ArrayList<>(); } @Override @@ -174,8 +174,8 @@ public abstract class ExtendedDialogWindow extends TrayDialog implements IRunnab * @param state The new state */ public void setPerformActionEnabled(boolean state) { - for (Iterator buttons = fActionButtons.iterator(); buttons.hasNext(); ) { - Button element = (Button) buttons.next(); + for (Iterator<Button> buttons = fActionButtons.iterator(); buttons.hasNext(); ) { + Button element = buttons.next(); element.setEnabled(state); } } @@ -211,7 +211,7 @@ public abstract class ExtendedDialogWindow extends TrayDialog implements IRunnab * @return The saved UI state. */ protected synchronized Object aboutToStart(boolean enableCancelButton) { - HashMap savedState= null; + HashMap<Object, Object> savedState= null; Shell shell= getShell(); if (shell != null) { Display d= shell.getDisplay(); @@ -257,7 +257,8 @@ public abstract class ExtendedDialogWindow extends TrayDialog implements IRunnab fProgressMonitorPart.removeFromCancelComponent(fCancelButton); } - HashMap state= (HashMap)savedState; + @SuppressWarnings("unchecked") + HashMap<Object, Object> state= (HashMap<Object, Object>)savedState; restoreUIState(state); setDisplayCursor(shell.getDisplay(), null); @@ -276,10 +277,10 @@ public abstract class ExtendedDialogWindow extends TrayDialog implements IRunnab //---- UI state save and restoring --------------------------------------------- - private void restoreUIState(HashMap state) { + private void restoreUIState(HashMap<Object, Object> state) { restoreEnableState(fCancelButton, state); - for (Iterator actionButtons = fActionButtons.iterator(); actionButtons.hasNext(); ) { - Button button = (Button) actionButtons.next(); + for (Iterator<Button> actionButtons = fActionButtons.iterator(); actionButtons.hasNext(); ) { + Button button = actionButtons.next(); restoreEnableState(button, state); } ControlEnableState pageState= (ControlEnableState)state.get("tabForm"); //$NON-NLS-1$ @@ -289,7 +290,7 @@ public abstract class ExtendedDialogWindow extends TrayDialog implements IRunnab /* * Restores the enable state of the given control. */ - protected void restoreEnableState(Control w, HashMap h) { + protected void restoreEnableState(Control w, HashMap<Object, Object> h) { if (!w.isDisposed()) { Boolean b= (Boolean)h.get(w); if (b != null) @@ -297,11 +298,11 @@ public abstract class ExtendedDialogWindow extends TrayDialog implements IRunnab } } - private HashMap saveUIState(boolean keepCancelEnabled) { - HashMap savedState= new HashMap(10); + private HashMap<Object, Object> saveUIState(boolean keepCancelEnabled) { + HashMap<Object, Object> savedState= new HashMap<>(10); saveEnableStateAndSet(fCancelButton, savedState, keepCancelEnabled); - for (Iterator actionButtons = fActionButtons.iterator(); actionButtons.hasNext(); ) { - Button button = (Button) actionButtons.next(); + for (Iterator<Button> actionButtons = fActionButtons.iterator(); actionButtons.hasNext(); ) { + Button button = actionButtons.next(); saveEnableStateAndSet(button, savedState, false); } savedState.put("tabForm", ControlEnableState.disable(fContents)); //$NON-NLS-1$ @@ -309,7 +310,7 @@ public abstract class ExtendedDialogWindow extends TrayDialog implements IRunnab return savedState; } - private void saveEnableStateAndSet(Control w, HashMap h, boolean enabled) { + private void saveEnableStateAndSet(Control w, HashMap<Object, Object> h, boolean enabled) { if (!w.isDisposed()) { h.put(w, Boolean.valueOf(w.isEnabled())); w.setEnabled(enabled); diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/util/FileLabelProvider.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/util/FileLabelProvider.java index 9c7418971d8..91bae8fe13a 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/util/FileLabelProvider.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/util/FileLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -45,7 +45,7 @@ public class FileLabelProvider extends LabelProvider { private ILabelDecorator fDecorator; private int fOrder; - private String[] fArgs= new String[2]; + private Object[] fArgs= new String[2]; public FileLabelProvider(int orderFlag) { fDecorator= PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator(); diff --git a/org.eclipse.search/search/org/eclipse/search/internal/ui/util/FileTypeEditor.java b/org.eclipse.search/search/org/eclipse/search/internal/ui/util/FileTypeEditor.java index e5fb3e9cacc..f8cd8e8928e 100644 --- a/org.eclipse.search/search/org/eclipse/search/internal/ui/util/FileTypeEditor.java +++ b/org.eclipse.search/search/org/eclipse/search/internal/ui/util/FileTypeEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -38,11 +38,8 @@ public class FileTypeEditor extends SelectionAdapter implements DisposeListener private final static String TYPE_DELIMITER= SearchMessages.FileTypeEditor_typeDelimiter; public final static String FILE_PATTERN_NEGATOR= "!"; //$NON-NLS-1$ - private static final Comparator FILE_TYPES_COMPARATOR= new Comparator() { + private static final Comparator<String> FILE_TYPES_COMPARATOR= new Comparator<String>() { @Override - public int compare(Object o1, Object o2) { - return compare((String) o1, (String) o2); - } public int compare(String fp1, String fp2) { boolean isNegative1= fp1.startsWith(FILE_PATTERN_NEGATOR); boolean isNegative2= fp2.startsWith(FILE_PATTERN_NEGATOR); @@ -78,14 +75,14 @@ public class FileTypeEditor extends SelectionAdapter implements DisposeListener } public String[] getFileTypes() { - Set result= new HashSet(); + Set<String> result= new HashSet<>(); StringTokenizer tokenizer= new StringTokenizer(fTextField.getText(), TYPE_DELIMITER); while (tokenizer.hasMoreTokens()) { String currentExtension= tokenizer.nextToken().trim(); result.add(currentExtension); } - return (String[]) result.toArray(new String[result.size()]); + return result.toArray(new String[result.size()]); } public void setFileTypes(String[] types) { @@ -96,7 +93,7 @@ public class FileTypeEditor extends SelectionAdapter implements DisposeListener TypeFilteringDialog dialog= new TypeFilteringDialog(fTextField.getShell(), Arrays.asList(getFileTypes())); if (dialog.open() == Window.OK) { Object[] result= dialog.getResult(); - HashSet patterns= new HashSet(); + HashSet<String> patterns= new HashSet<>(); boolean starIncluded= false; for (int i= 0; i < result.length; i++) { String curr= result[i].toString(); @@ -109,7 +106,7 @@ public class FileTypeEditor extends SelectionAdapter implements DisposeListener if (patterns.isEmpty() && starIncluded) { // remove star when other file extensions active patterns.add("*"); //$NON-NLS-1$ } - String[] filePatterns= (String[]) patterns.toArray(new String[patterns.size()]); + String[] filePatterns= patterns.toArray(new String[patterns.size()]); Arrays.sort(filePatterns); setFileTypes(filePatterns); } diff --git a/org.eclipse.text.tests/projection/org/eclipse/text/tests/ProjectionDocumentTest.java b/org.eclipse.text.tests/projection/org/eclipse/text/tests/ProjectionDocumentTest.java index 314073d9094..e0a0e31583e 100644 --- a/org.eclipse.text.tests/projection/org/eclipse/text/tests/ProjectionDocumentTest.java +++ b/org.eclipse.text.tests/projection/org/eclipse/text/tests/ProjectionDocumentTest.java @@ -1576,7 +1576,7 @@ public class ProjectionDocumentTest extends TestCase { public void test22() { // test document events sent out by the slave document when adding segments - final List receivedEvents= new ArrayList(); + final List<DocumentEvent> receivedEvents= new ArrayList<>(); IDocumentListener listener= new IDocumentListener() { @Override @@ -1606,7 +1606,7 @@ public class ProjectionDocumentTest extends TestCase { public void test23() { // test document events sent out by the slave document when removing segments - final List receivedEvents= new ArrayList(); + final List<DocumentEvent> receivedEvents= new ArrayList<>(); IDocumentListener listener= new IDocumentListener() { @Override diff --git a/org.eclipse.text.tests/src/org/eclipse/text/tests/Accessor.java b/org.eclipse.text.tests/src/org/eclipse/text/tests/Accessor.java index 82e70551f8f..0290286ade7 100644 --- a/org.eclipse.text.tests/src/org/eclipse/text/tests/Accessor.java +++ b/org.eclipse.text.tests/src/org/eclipse/text/tests/Accessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -28,7 +28,7 @@ import org.eclipse.core.runtime.Assert; public class Accessor { /** The class to access. */ - private Class fClass; + private Class<?> fClass; /** The instance to access. */ private Object fInstance; @@ -40,7 +40,7 @@ public class Accessor { * @param instance the instance * @param clazz the class */ - public Accessor(Object instance, Class clazz) { + public Accessor(Object instance, Class<?> clazz) { org.eclipse.core.runtime.Assert.isNotNull(instance); Assert.isNotNull(clazz); fInstance= instance; @@ -94,7 +94,7 @@ public class Accessor { * @param constructorTypes the types of the constructor arguments * @param constructorArgs the constructor arguments */ - public Accessor(String className, ClassLoader classLoader, Class[] constructorTypes, Object[] constructorArgs) { + public Accessor(String className, ClassLoader classLoader, Class<?>[] constructorTypes, Object[] constructorArgs) { try { fClass= Class.forName(className, true, classLoader); } catch (ClassNotFoundException e) { @@ -102,7 +102,7 @@ public class Accessor { } catch (ExceptionInInitializerError e) { fail(); } - Constructor constructor= null; + Constructor<?> constructor= null; try { constructor= fClass.getDeclaredConstructor(constructorTypes); } catch (SecurityException e2) { @@ -168,7 +168,7 @@ public class Accessor { * @param arguments the method arguments * @return the method return value */ - public Object invoke(String methodName, Class[] types, Object[] arguments) { + public Object invoke(String methodName, Class<?>[] types, Object[] arguments) { Method method= null; try { method= fClass.getDeclaredMethod(methodName, types); @@ -312,12 +312,12 @@ public class Accessor { return field; } - private static Class[] getTypes(Object[] objects) { + private static Class<?>[] getTypes(Object[] objects) { if (objects == null) return null; int length= objects.length; - Class[] classes= new Class[length]; + Class<?>[] classes= new Class[length]; for (int i= 0; i < length; i++) { Assert.isNotNull(objects[i]); classes[i]= objects[i].getClass(); diff --git a/org.eclipse.text.tests/src/org/eclipse/text/tests/AnnotationModelExtension2Test.java b/org.eclipse.text.tests/src/org/eclipse/text/tests/AnnotationModelExtension2Test.java index 764712c150b..c39b3f91a81 100644 --- a/org.eclipse.text.tests/src/org/eclipse/text/tests/AnnotationModelExtension2Test.java +++ b/org.eclipse.text.tests/src/org/eclipse/text/tests/AnnotationModelExtension2Test.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -16,10 +16,6 @@ import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.Position; @@ -28,6 +24,10 @@ import org.eclipse.jface.text.source.AnnotationModel; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IAnnotationModelListener; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + /** * Tests the {@link org.eclipse.jface.text.source.IAnnotationModelExtension2}. @@ -38,7 +38,7 @@ public class AnnotationModelExtension2Test extends TestCase { public class OldAnnotationModel implements IAnnotationModel { - private final HashMap fAnnotations= new HashMap(); + private final HashMap<Annotation, Position> fAnnotations= new HashMap<>(); @Override public void addAnnotation(Annotation annotation, Position position) { @@ -58,13 +58,13 @@ public class AnnotationModelExtension2Test extends TestCase { } @Override - public Iterator getAnnotationIterator() { + public Iterator<Annotation> getAnnotationIterator() { return fAnnotations.keySet().iterator(); } @Override public Position getPosition(Annotation annotation) { - return (Position) fAnnotations.get(annotation); + return fAnnotations.get(annotation); } @Override @@ -135,7 +135,7 @@ public class AnnotationModelExtension2Test extends TestCase { } private void assertEquals(Annotation[] expected, Annotation[] actual, IAnnotationModel insideModel, IAnnotationModel beforeModel, IAnnotationModel afterModel) { - HashSet expectedSet= new HashSet(Arrays.asList(expected)); + HashSet<Annotation> expectedSet= new HashSet<>(Arrays.asList(expected)); for (int i= 0; i < actual.length; i++) { if (!expectedSet.contains(actual[i])) { String message= "Unexpected annotation " + getName(actual[i]) + " in result with models [" + getAnnotationModelNames(insideModel, beforeModel, afterModel) + "]"; @@ -146,8 +146,8 @@ public class AnnotationModelExtension2Test extends TestCase { if (!expectedSet.isEmpty()) { String message= "Missing annotations in result with models [" + getAnnotationModelNames(insideModel, beforeModel, afterModel) + "]"; - for (Iterator iterator= expectedSet.iterator(); iterator.hasNext();) { - Annotation missing= (Annotation) iterator.next(); + for (Iterator<Annotation> iterator= expectedSet.iterator(); iterator.hasNext();) { + Annotation missing= iterator.next(); message= message + "\n" + getName(missing); } assertTrue(message, false); @@ -210,14 +210,14 @@ public class AnnotationModelExtension2Test extends TestCase { } private Annotation[] getAnnotations(boolean lookAhead, boolean lookBehind) { - Iterator iterator= fAnnotationModel.getAnnotationIterator(10, 11, lookAhead, lookBehind); + Iterator<Annotation> iterator= fAnnotationModel.getAnnotationIterator(10, 11, lookAhead, lookBehind); - ArrayList result= new ArrayList(); + ArrayList<Annotation> result= new ArrayList<>(); while (iterator.hasNext()) { result.add(iterator.next()); } - return (Annotation[]) result.toArray(new Annotation[result.size()]); + return result.toArray(new Annotation[result.size()]); } private void assertPermutations(boolean lookAhead, boolean lookBehind, Annotation[] expected) { diff --git a/org.eclipse.text.tests/src/org/eclipse/text/tests/AnnotationModelStressTest.java b/org.eclipse.text.tests/src/org/eclipse/text/tests/AnnotationModelStressTest.java index 6926f671e90..4e5bca4b9d6 100644 --- a/org.eclipse.text.tests/src/org/eclipse/text/tests/AnnotationModelStressTest.java +++ b/org.eclipse.text.tests/src/org/eclipse/text/tests/AnnotationModelStressTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,16 +14,16 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.Random; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - import org.eclipse.jface.text.Document; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.AnnotationModel; import org.eclipse.jface.text.source.IAnnotationModel; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + /** * @since 3.4 @@ -1253,8 +1253,8 @@ public class AnnotationModelStressTest extends TestCase { return null; } - private void assertRemove(ArrayList added) { - AnnotationData first= (AnnotationData) added.remove(0); + private void assertRemove(ArrayList<AnnotationData> added) { + AnnotationData first= added.remove(0); IAnnotationModel model= getModel(first.annotationNumber); assertTrue(model.getPosition(first.annotation) == first.position); @@ -1262,7 +1262,7 @@ public class AnnotationModelStressTest extends TestCase { assertTrue(model.getPosition(first.annotation) == null); } - private void assertAdd(AnnotationData data, ArrayList added) { + private void assertAdd(AnnotationData data, ArrayList<AnnotationData> added) { Annotation annotation= new Annotation(false); Position position= new Position(data.offset, data.length); IAnnotationModel model= getModel(data.annotationNumber); @@ -1276,18 +1276,18 @@ public class AnnotationModelStressTest extends TestCase { added.add(data); } - private void assertExist(ArrayList added) { + private void assertExist(ArrayList<AnnotationData> added) { for (int i= 0, size= added.size(); i < size; i++) { - AnnotationData data= (AnnotationData) added.get(i); + AnnotationData data= added.get(i); IAnnotationModel model= getModel(data.annotationNumber); assertTrue(model.getPosition(data.annotation) == data.position); } - ArrayList annotations= getAllAnnotations(); + ArrayList<Annotation> annotations= getAllAnnotations(); assertEquals(added.size(), annotations.size()); for (int i= 0, size= annotations.size(); i < size; i++) { - Annotation annotation= (Annotation) annotations.get(i); + Annotation annotation= annotations.get(i); AnnotationData data= getAnnotationData(added, annotation); assertNotNull(data); @@ -1296,18 +1296,18 @@ public class AnnotationModelStressTest extends TestCase { } } - private void assertExistNew(ArrayList added) { + private void assertExistNew(ArrayList<AnnotationData> added) { for (int i= 0, size= added.size(); i < size; i++) { - AnnotationData data= (AnnotationData) added.get(i); + AnnotationData data= added.get(i); IAnnotationModel model= getModel(data.annotationNumber); assertTrue(model.getPosition(data.annotation) == data.position); } - ArrayList annotations= getAllAnnotationsNew(); + ArrayList<Annotation> annotations= getAllAnnotationsNew(); assertEquals(added.size(), annotations.size()); for (int i= 0, size= annotations.size(); i < size; i++) { - Annotation annotation= (Annotation) annotations.get(i); + Annotation annotation= annotations.get(i); AnnotationData data= getAnnotationData(added, annotation); assertNotNull(data); @@ -1316,19 +1316,19 @@ public class AnnotationModelStressTest extends TestCase { } } - private AnnotationData getAnnotationData(ArrayList datas, Annotation annotation) { + private AnnotationData getAnnotationData(ArrayList<AnnotationData> datas, Annotation annotation) { for (int i= 0, size= datas.size(); i < size; i++) { - AnnotationData data= (AnnotationData) datas.get(i); + AnnotationData data= datas.get(i); if (data.annotation == annotation) return data; } return null; } - private ArrayList getAllAnnotations() { - ArrayList result= new ArrayList(); + private ArrayList<Annotation> getAllAnnotations() { + ArrayList<Annotation> result= new ArrayList<>(); - Iterator iterator= fAnnotationModel.getAnnotationIterator(); + Iterator<Annotation> iterator= fAnnotationModel.getAnnotationIterator(); while (iterator.hasNext()) { result.add(iterator.next()); } @@ -1336,10 +1336,10 @@ public class AnnotationModelStressTest extends TestCase { return result; } - private ArrayList getAllAnnotationsNew() { - ArrayList result= new ArrayList(); + private ArrayList<Annotation> getAllAnnotationsNew() { + ArrayList<Annotation> result= new ArrayList<>(); - Iterator iterator= fAnnotationModel.getAnnotationIterator(0, fDocument.getLength(), true, true); + Iterator<Annotation> iterator= fAnnotationModel.getAnnotationIterator(0, fDocument.getLength(), true, true); while (iterator.hasNext()) { result.add(iterator.next()); } @@ -1348,7 +1348,7 @@ public class AnnotationModelStressTest extends TestCase { } public void testStressTestPlainOld() throws Exception { - ArrayList added= new ArrayList(); + ArrayList<AnnotationData> added= new ArrayList<>(); int i= 0; while (i < 20) { AnnotationData data= RANDOM_ANNOTATIONS[i]; @@ -1378,7 +1378,7 @@ public class AnnotationModelStressTest extends TestCase { } public void testStressTestPlainNew() throws Exception { - ArrayList added= new ArrayList(); + ArrayList<AnnotationData> added= new ArrayList<>(); int i= 0; while (i < 20) { AnnotationData data= RANDOM_ANNOTATIONS[i]; @@ -1408,7 +1408,7 @@ public class AnnotationModelStressTest extends TestCase { } public void testStressTestMoveOld() throws Exception { - ArrayList added= new ArrayList(); + ArrayList<AnnotationData> added= new ArrayList<>(); int i= 0; while (i < 20) { AnnotationData data= RANDOM_ANNOTATIONS[i]; @@ -1442,7 +1442,7 @@ public class AnnotationModelStressTest extends TestCase { } public void testStressTestMoveNew() throws Exception { - ArrayList added= new ArrayList(); + ArrayList<AnnotationData> added= new ArrayList<>(); int i= 0; while (i < 20) { AnnotationData data= RANDOM_ANNOTATIONS[i]; diff --git a/org.eclipse.text.tests/src/org/eclipse/text/tests/DocumentExtensionTest.java b/org.eclipse.text.tests/src/org/eclipse/text/tests/DocumentExtensionTest.java index 47ed07ee7d9..40126d353fe 100644 --- a/org.eclipse.text.tests/src/org/eclipse/text/tests/DocumentExtensionTest.java +++ b/org.eclipse.text.tests/src/org/eclipse/text/tests/DocumentExtensionTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,10 +14,6 @@ package org.eclipse.text.tests; import java.util.ArrayList; import java.util.List; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentEvent; @@ -27,6 +23,10 @@ import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.projection.ChildDocument; import org.eclipse.jface.text.projection.ChildDocumentManager; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + public class DocumentExtensionTest extends TestCase { @@ -116,15 +116,15 @@ public class DocumentExtensionTest extends TestCase { static class TestDocumentListener implements IDocumentListener { private IDocument fDocument1; - private List fTrace1; + private List<TestDocumentEvent> fTrace1; private TestDocumentEvent fExpected1; - private List fTrace2; + private List<TestDocumentEvent> fTrace2; private TestDocumentEvent fExpected2; private boolean fPopped= false; - public TestDocumentListener(IDocument d1, List t1, List t2) { + public TestDocumentListener(IDocument d1, List<TestDocumentEvent> t1, List<TestDocumentEvent> t2) { fDocument1= d1; fTrace1= t1; fTrace2= t2; @@ -134,8 +134,8 @@ public class DocumentExtensionTest extends TestCase { public void documentAboutToBeChanged(DocumentEvent received) { if (!fPopped) { fPopped= true; - fExpected1= (TestDocumentEvent) fTrace1.remove(0); - fExpected2= (TestDocumentEvent) fTrace2.remove(0); + fExpected1= fTrace1.remove(0); + fExpected2= fTrace2.remove(0); } TestDocumentEvent e= (received.getDocument() == fDocument1 ? fExpected1 : fExpected2); @@ -252,9 +252,9 @@ public class DocumentExtensionTest extends TestCase { assertTrue("axxxxxbxxxxxcxxxxx".equals(document.get())); } - private List createTrace(IDocument document, int repetitions) { + private List<TestDocumentEvent> createTrace(IDocument document, int repetitions) { int i; - List trace= new ArrayList(); + List<TestDocumentEvent> trace= new ArrayList<>(); trace.add(new TestDocumentEvent(document, 0, 0, "c")); for (i= 0; i < repetitions; i++) diff --git a/org.eclipse.text.tests/src/org/eclipse/text/tests/TextEditTests.java b/org.eclipse.text.tests/src/org/eclipse/text/tests/TextEditTests.java index c5c7b687ba6..16176538ce0 100644 --- a/org.eclipse.text.tests/src/org/eclipse/text/tests/TextEditTests.java +++ b/org.eclipse.text.tests/src/org/eclipse/text/tests/TextEditTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,10 +15,6 @@ import java.util.Comparator; import java.util.Iterator; import java.util.List; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - import org.eclipse.text.edits.CopySourceEdit; import org.eclipse.text.edits.CopyTargetEdit; import org.eclipse.text.edits.DeleteEdit; @@ -38,9 +34,13 @@ import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + public class TextEditTests extends TestCase { - private static final Class THIS= TextEditTests.class; + private static final Class<TextEditTests> THIS= TextEditTests.class; private IDocument fDocument; private MultiTextEdit fRoot; @@ -274,9 +274,9 @@ public class TextEditTests extends TestCase { TextEdit e2= new ReplaceEdit(2, 3, "3456"); root.addChild(e1); root.addChild(e2); - List org= flatten(root); + List<TextEdit> org= flatten(root); TextEditCopier copier= new TextEditCopier(root); - List copy= flatten(copier.perform()); + List<TextEdit> copy= flatten(copier.perform()); compare(org, copy); } @@ -290,19 +290,19 @@ public class TextEditTests extends TestCase { root.addChild(s1); root.addChild(t1); root.addChild(t2); - List org= flatten(root); + List<TextEdit> org= flatten(root); TextEditCopier copier= new TextEditCopier(root); - List copy= flatten(copier.perform()); + List<TextEdit> copy= flatten(copier.perform()); compare(org, copy); } - private List flatten(TextEdit edit) { - List result= new ArrayList(); + private List<TextEdit> flatten(TextEdit edit) { + List<TextEdit> result= new ArrayList<>(); flatten(result, edit); return result; } - private static void flatten(List result, TextEdit edit) { + private static void flatten(List<TextEdit> result, TextEdit edit) { result.add(edit); TextEdit[] children= edit.getChildren(); for (int i= 0; i < children.length; i++) { @@ -310,10 +310,10 @@ public class TextEditTests extends TestCase { } } - private static void compare(List org, List copy) { + private static void compare(List<TextEdit> org, List<TextEdit> copy) { assertTrue("Same length", org.size() == copy.size()); - for (Iterator iter= copy.iterator(); iter.hasNext();) { - TextEdit edit= (TextEdit)iter.next(); + for (Iterator<TextEdit> iter= copy.iterator(); iter.hasNext();) { + TextEdit edit= iter.next(); assertTrue("Original is part of copy list", !org.contains(edit)); if (edit instanceof MoveSourceEdit) { MoveSourceEdit source= (MoveSourceEdit)edit; @@ -1206,7 +1206,8 @@ public class TextEditTests extends TestCase { public void testComparator() throws Exception { DeleteEdit d1= new DeleteEdit(1,3); Accessor accessor= new Accessor(d1, TextEdit.class); - Comparator comparator= (Comparator)accessor.get("INSERTION_COMPARATOR"); + @SuppressWarnings("unchecked") + Comparator<TextEdit> comparator= (Comparator<TextEdit>)accessor.get("INSERTION_COMPARATOR"); TextEdit edit1= new InsertEdit(1, "test"); TextEdit edit2= new InsertEdit(1, "test"); diff --git a/org.eclipse.text.tests/src/org/eclipse/text/tests/TextUtilitiesTest.java b/org.eclipse.text.tests/src/org/eclipse/text/tests/TextUtilitiesTest.java index 9bddfec24a4..e8390adf42d 100644 --- a/org.eclipse.text.tests/src/org/eclipse/text/tests/TextUtilitiesTest.java +++ b/org.eclipse.text.tests/src/org/eclipse/text/tests/TextUtilitiesTest.java @@ -56,7 +56,7 @@ public class TextUtilitiesTest extends TestCase { private final DocumentListener fDocumentListener= new DocumentListener(); /** The buffered events. */ - private final List fEvents= new ArrayList(); + private final List<DocumentEvent> fEvents= new ArrayList<>(); public LazilyMirroredDocument(IDocument document) { document.addDocumentListener(fDocumentListener); @@ -107,7 +107,7 @@ public class TextUtilitiesTest extends TestCase { private final DocumentListener fDocumentListener= new DocumentListener(); /** The buffered events. */ - private final List fEvents= new ArrayList(); + private final List<DocumentEvent> fEvents= new ArrayList<>(); public LazilyMirroredDocument2(IDocument document) { document.addDocumentListener(fDocumentListener); @@ -187,7 +187,7 @@ public class TextUtilitiesTest extends TestCase { try { - List events= new ArrayList(); + List<DocumentEvent> events= new ArrayList<>(); int currentLength= 0; events.add(new DocumentEvent(reference, 0, 0, "foo bar goo haa")); @@ -198,8 +198,8 @@ public class TextUtilitiesTest extends TestCase { events.add(new DocumentEvent(reference, 9, 2, "asd")); events.add(new DocumentEvent(reference, 0, 2, "asd")); - for (Iterator iterator= events.iterator(); iterator.hasNext();) { - DocumentEvent event= (DocumentEvent) iterator.next(); + for (Iterator<DocumentEvent> iterator= events.iterator(); iterator.hasNext();) { + DocumentEvent event= iterator.next(); currentLength += event.getText().length() - event.getLength(); } @@ -210,8 +210,8 @@ public class TextUtilitiesTest extends TestCase { events.add(event); } - for (Iterator iterator= events.iterator(); iterator.hasNext();) { - DocumentEvent event= (DocumentEvent) iterator.next(); + for (Iterator<DocumentEvent> iterator= events.iterator(); iterator.hasNext();) { + DocumentEvent event= iterator.next(); // System.err.println(event.getOffset() + ", " + event.getLength() + ", [" + event.getText() + "]") ; @@ -239,7 +239,7 @@ public class TextUtilitiesTest extends TestCase { try { - List events= new ArrayList(); + List<DocumentEvent> events= new ArrayList<>(); int currentLength= 0; events.add(new DocumentEvent(reference, 0, 0, "foo bar goo haa")); @@ -250,8 +250,8 @@ public class TextUtilitiesTest extends TestCase { events.add(new DocumentEvent(reference, 9, 2, "asd")); events.add(new DocumentEvent(reference, 0, 2, "asd")); - for (Iterator iterator= events.iterator(); iterator.hasNext();) { - DocumentEvent event= (DocumentEvent) iterator.next(); + for (Iterator<DocumentEvent> iterator= events.iterator(); iterator.hasNext();) { + DocumentEvent event= iterator.next(); currentLength += event.getText().length() - event.getLength(); } @@ -262,8 +262,8 @@ public class TextUtilitiesTest extends TestCase { events.add(event); } - for (Iterator iterator= events.iterator(); iterator.hasNext();) { - DocumentEvent event= (DocumentEvent) iterator.next(); + for (Iterator<DocumentEvent> iterator= events.iterator(); iterator.hasNext();) { + DocumentEvent event= iterator.next(); reference.replace(event.getOffset(), event.getLength(), event.getText()); if (Math.random() < 0.3) { diff --git a/org.eclipse.text.tests/src/org/eclipse/text/tests/link/LinkedModeModelTest.java b/org.eclipse.text.tests/src/org/eclipse/text/tests/link/LinkedModeModelTest.java index eb145a344b0..6914890ac05 100644 --- a/org.eclipse.text.tests/src/org/eclipse/text/tests/link/LinkedModeModelTest.java +++ b/org.eclipse.text.tests/src/org/eclipse/text/tests/link/LinkedModeModelTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,8 +17,6 @@ import java.util.Iterator; import java.util.LinkedList; import java.util.List; -import junit.framework.TestCase; - import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; @@ -27,12 +25,14 @@ import org.eclipse.jface.text.link.LinkedModeModel; import org.eclipse.jface.text.link.LinkedPosition; import org.eclipse.jface.text.link.LinkedPositionGroup; +import junit.framework.TestCase; + public class LinkedModeModelTest extends TestCase { - private List fPositions= new LinkedList(); + private List<LinkedPosition> fPositions= new LinkedList<>(); - private List fDocumentMap= new ArrayList(); + private List<IDocument[]> fDocumentMap= new ArrayList<>(); public void testUpdate() throws BadLocationException { IDocument doc1= new Document(GARTEN1); @@ -541,7 +541,7 @@ public class LinkedModeModelTest extends TestCase { } private void assertUnchanged(LinkedPositionGroup actual1, LinkedPositionGroup actual2) throws BadLocationException { - LinkedPosition[] exp= (LinkedPosition[]) fPositions.toArray(new LinkedPosition[0]); + LinkedPosition[] exp= fPositions.toArray(new LinkedPosition[0]); LinkedPosition[] act1= actual1.getPositions(); LinkedPosition[] act2= actual2.getPositions(); LinkedPosition[] act= new LinkedPosition[act1.length + act2.length]; @@ -620,8 +620,8 @@ public class LinkedModeModelTest extends TestCase { } private IDocument getOriginal(IDocument doc) { - for (Iterator it = fDocumentMap.iterator(); it.hasNext(); ) { - IDocument[] docs = (IDocument[]) it.next(); + for (Iterator<IDocument[]> it = fDocumentMap.iterator(); it.hasNext(); ) { + IDocument[] docs = it.next(); if (docs[0] == doc) return docs[1]; } @@ -814,13 +814,10 @@ public class LinkedModeModelTest extends TestCase { public void resume(LinkedModeModel environment, int flags) {} } - public class PositionComparator implements Comparator { + public class PositionComparator implements Comparator<LinkedPosition> { @Override - public int compare(Object o1, Object o2) { - LinkedPosition p1= (LinkedPosition) o1; - LinkedPosition p2= (LinkedPosition) o2; - + public int compare(LinkedPosition p1, LinkedPosition p2) { IDocument d1= p1.getDocument(); IDocument d2= p2.getDocument(); @@ -832,8 +829,8 @@ public class LinkedModeModelTest extends TestCase { private int getIndex(IDocument doc) { int i= 0; - for (Iterator it= fDocumentMap.iterator(); it.hasNext(); i++) { - IDocument[] docs= (IDocument[]) it.next(); + for (Iterator<IDocument[]> it= fDocumentMap.iterator(); it.hasNext(); i++) { + IDocument[] docs= it.next(); if (docs[0] == doc || docs[1] == doc) return i; } diff --git a/org.eclipse.text.tests/src/org/eclipse/text/tests/templates/TemplateTranslatorTest.java b/org.eclipse.text.tests/src/org/eclipse/text/tests/templates/TemplateTranslatorTest.java index 7ded6114746..494e3f1c26a 100644 --- a/org.eclipse.text.tests/src/org/eclipse/text/tests/templates/TemplateTranslatorTest.java +++ b/org.eclipse.text.tests/src/org/eclipse/text/tests/templates/TemplateTranslatorTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2011 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,15 +15,15 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - import org.eclipse.jface.text.templates.TemplateBuffer; import org.eclipse.jface.text.templates.TemplateException; import org.eclipse.jface.text.templates.TemplateTranslator; import org.eclipse.jface.text.templates.TemplateVariable; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + /** * @since 3.3 */ @@ -287,7 +287,7 @@ public class TemplateTranslatorTest extends TestCase { assertEquals(1, vars[0].getValues().length); assertEquals(vars[0].getDefaultValue(), vars[0].getValues()[0]); assertEquals("type", vars[0].getType()); - List params= new ArrayList(2); + List<String> params= new ArrayList<>(2); params.add("param1"); params.add("param2"); params.add("param3"); @@ -309,7 +309,7 @@ public class TemplateTranslatorTest extends TestCase { assertEquals(1, vars[0].getValues().length); assertEquals(vars[0].getDefaultValue(), vars[0].getValues()[0]); assertEquals("qual.type", vars[0].getType()); - List params= new ArrayList(2); + List<String> params= new ArrayList<>(2); params.add("qual.param1"); params.add("qual.param2"); assertEquals(params, vars[0].getVariableType().getParams()); @@ -330,7 +330,7 @@ public class TemplateTranslatorTest extends TestCase { assertEquals(1, vars[0].getValues().length); assertEquals(vars[0].getDefaultValue(), vars[0].getValues()[0]); assertEquals("qual.type", vars[0].getType()); - List params= new ArrayList(3); + List<String> params= new ArrayList<>(3); params.add("a parameter 1"); params.add("qual.param2"); params.add("a parameter '3"); diff --git a/org.eclipse.text/projection/org/eclipse/jface/text/projection/ProjectionDocument.java b/org.eclipse.text/projection/org/eclipse/jface/text/projection/ProjectionDocument.java index 7b3b6d0453f..c73299bfcbb 100644 --- a/org.eclipse.text/projection/org/eclipse/jface/text/projection/ProjectionDocument.java +++ b/org.eclipse.text/projection/org/eclipse/jface/text/projection/ProjectionDocument.java @@ -460,7 +460,7 @@ public class ProjectionDocument extends AbstractDocument { if (fragments == null || fragments.length == 0) return new IRegion[] { new Region(offsetInMaster, lengthInMaster) }; - List gaps= new ArrayList(); + List<Region> gaps= new ArrayList<>(); IRegion region= fragments[0]; if (offsetInMaster < region.getOffset()) diff --git a/org.eclipse.text/projection/org/eclipse/jface/text/projection/ProjectionDocumentManager.java b/org.eclipse.text/projection/org/eclipse/jface/text/projection/ProjectionDocumentManager.java index 9d154107510..820d7dfe1e1 100644 --- a/org.eclipse.text/projection/org/eclipse/jface/text/projection/ProjectionDocumentManager.java +++ b/org.eclipse.text/projection/org/eclipse/jface/text/projection/ProjectionDocumentManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -47,7 +47,7 @@ import org.eclipse.jface.text.ISlaveDocumentManagerExtension; public class ProjectionDocumentManager implements IDocumentListener, ISlaveDocumentManager, ISlaveDocumentManagerExtension { /** Registry for master documents and their projection documents. */ - private Map fProjectionRegistry= new HashMap(); + private Map<IDocument, List<ProjectionDocument>> fProjectionRegistry= new HashMap<>(); /** * Registers the given projection document for the given master document. @@ -56,9 +56,9 @@ public class ProjectionDocumentManager implements IDocumentListener, ISlaveDocum * @param projection the projection document */ private void add(IDocument master, ProjectionDocument projection) { - List list= (List) fProjectionRegistry.get(master); + List<ProjectionDocument> list= fProjectionRegistry.get(master); if (list == null) { - list= new ArrayList(1); + list= new ArrayList<>(1); fProjectionRegistry.put(master, list); } list.add(projection); @@ -71,7 +71,7 @@ public class ProjectionDocumentManager implements IDocumentListener, ISlaveDocum * @param projection the projection document */ private void remove(IDocument master, ProjectionDocument projection) { - List list= (List) fProjectionRegistry.get(master); + List<ProjectionDocument> list= fProjectionRegistry.get(master); if (list != null) { list.remove(projection); if (list.size() == 0) @@ -86,7 +86,7 @@ public class ProjectionDocumentManager implements IDocumentListener, ISlaveDocum * @return <code>true</code> if the given document is a master document known to this manager */ private boolean hasProjection(IDocument master) { - return (fProjectionRegistry.get(master) instanceof List); + return (fProjectionRegistry.get(master) != null); } /** @@ -96,8 +96,8 @@ public class ProjectionDocumentManager implements IDocumentListener, ISlaveDocum * @param master the document * @return an iterator for all registered projection documents or <code>null</code> */ - private Iterator getProjectionsIterator(IDocument master) { - List list= (List) fProjectionRegistry.get(master); + private Iterator<ProjectionDocument> getProjectionsIterator(IDocument master) { + List<ProjectionDocument> list= fProjectionRegistry.get(master); if (list != null) return list.iterator(); return null; @@ -111,12 +111,12 @@ public class ProjectionDocumentManager implements IDocumentListener, ISlaveDocum */ protected void fireDocumentEvent(boolean about, DocumentEvent masterEvent) { IDocument master= masterEvent.getDocument(); - Iterator e= getProjectionsIterator(master); + Iterator<ProjectionDocument> e= getProjectionsIterator(master); if (e == null) return; while (e.hasNext()) { - ProjectionDocument document= (ProjectionDocument) e.next(); + ProjectionDocument document= e.next(); if (about) document.masterDocumentAboutToBeChanged(masterEvent); else @@ -194,7 +194,7 @@ public class ProjectionDocumentManager implements IDocumentListener, ISlaveDocum @Override public IDocument[] getSlaveDocuments(IDocument master) { - List list= (List) fProjectionRegistry.get(master); + List<ProjectionDocument> list= fProjectionRegistry.get(master); if (list != null) { IDocument[] result= new IDocument[list.size()]; list.toArray(result); diff --git a/org.eclipse.text/src/org/eclipse/jface/text/AbstractDocument.java b/org.eclipse.text/src/org/eclipse/jface/text/AbstractDocument.java index ba2fe5ac7d2..b9c734a50ba 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/AbstractDocument.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/AbstractDocument.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,8 +12,8 @@ package org.eclipse.jface.text; +import java.util.AbstractList; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -98,19 +98,19 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, /** The registered document partitioning listeners */ private ListenerList fDocumentPartitioningListeners; /** All positions managed by the document ordered by their start positions. */ - private Map fPositions; + private Map<String, List<Position>> fPositions; /** - * All positions managed by the document ordered by there end positions. + * All positions managed by the document ordered by their end positions. * @since 3.4 */ - private Map fEndPositions; + private Map<String, List<Position>> fEndPositions; /** All registered document position updaters */ - private List fPositionUpdaters; + private List<IPositionUpdater> fPositionUpdaters; /** * The list of post notification changes * @since 2.0 */ - private List fPostNotificationChanges; + private List<RegisteredReplace> fPostNotificationChanges; /** * The reentrance count for post notification changes. * @since 2.0 @@ -140,7 +140,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, * The registered document partitioners. * @since 3.0 */ - private Map fDocumentPartitioners; + private Map<String, IDocumentPartitioner> fDocumentPartitioners; /** * The partitioning changed event. * @since 3.0 @@ -160,7 +160,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, * The registered document rewrite session listeners. * @since 3.1 */ - private List fDocumentRewriteSessionListeners; + private List<IDocumentRewriteSessionListener> fDocumentRewriteSessionListeners; /** * The current modification stamp. * @since 3.1 @@ -211,13 +211,31 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, return fTracker; } + private static <T> List<T> asList(Object[] listeners) { + // Workaround for Bug 483340: ListenerList should be parameterized + // Use Arrays.asList(..) once that bug is fixed. + return new AbstractList<T>() { + @SuppressWarnings("unchecked") + @Override + public T get(int index) { + return (T) listeners[index]; + } + + @Override + public int size() { + return listeners.length; + } + }; + } + + /** * Returns the document's document listeners. * * @return the document's document listeners */ - protected List getDocumentListeners() { - return Arrays.asList(fDocumentListeners.getListeners()); + protected List<IDocumentListener> getDocumentListeners() { + return asList(fDocumentListeners.getListeners()); } /** @@ -225,8 +243,8 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, * * @return the document's partitioning listeners */ - protected List getDocumentPartitioningListeners() { - return Arrays.asList(fDocumentPartitioningListeners.getListeners()); + protected List<IDocumentPartitioningListener> getDocumentPartitioningListeners() { + return asList(fDocumentPartitioningListeners.getListeners()); } /** @@ -234,7 +252,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, * * @return the document's positions */ - protected Map getDocumentManagedPositions() { + protected Map<String, List<Position>> getDocumentManagedPositions() { return fPositions; } @@ -279,13 +297,13 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, */ protected void completeInitialization() { - fPositions= new HashMap(); - fEndPositions= new HashMap(); - fPositionUpdaters= new ArrayList(); + fPositions= new HashMap<>(); + fEndPositions= new HashMap<>(); + fPositionUpdaters= new ArrayList<>(); fDocumentListeners= new ListenerList(ListenerList.IDENTITY); fPrenotifiedDocumentListeners= new ListenerList(ListenerList.IDENTITY); fDocumentPartitioningListeners= new ListenerList(ListenerList.IDENTITY); - fDocumentRewriteSessionListeners= new ArrayList(); + fDocumentRewriteSessionListeners= new ArrayList<>(); addPositionCategory(DEFAULT_CATEGORY); addPositionUpdater(new DefaultPositionUpdater(DEFAULT_CATEGORY)); @@ -339,12 +357,12 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, if (category == null) throw new BadPositionCategoryException(); - List list= (List) fPositions.get(category); + List<Position> list= fPositions.get(category); if (list == null) throw new BadPositionCategoryException(); list.add(computeIndexInPositionList(list, position.offset), position); - List endPositions= (List) fEndPositions.get(category); + List<Position> endPositions= fEndPositions.get(category); if (endPositions == null) throw new BadPositionCategoryException(); endPositions.add(computeIndexInPositionList(endPositions, position.offset + position.length - 1, false), position); @@ -365,8 +383,8 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, return; if (!containsPositionCategory(category)) { - fPositions.put(category, new ArrayList()); - fEndPositions.put(category, new ArrayList()); + fPositions.put(category, new ArrayList<>()); + fEndPositions.put(category, new ArrayList<>()); } } @@ -381,7 +399,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, if (category == null) return false; - List list= (List) fPositions.get(category); + List<Position> list= fPositions.get(category); if (list == null) return false; @@ -391,12 +409,12 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, int index= computeIndexInPositionList(list, offset); if (index < size) { - Position p= (Position) list.get(index); + Position p= list.get(index); while (p != null && p.offset == offset) { if (p.length == length) return true; ++ index; - p= (index < size) ? (Position) list.get(index) : null; + p= (index < size) ? list.get(index) : null; } } @@ -424,7 +442,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, * @deprecated As of 3.4, replaced by {@link #computeIndexInPositionList(List, int, boolean)} */ @Deprecated - protected int computeIndexInPositionList(List positions, int offset) { + protected int computeIndexInPositionList(List<Position> positions, int offset) { return computeIndexInPositionList(positions, offset, true); } @@ -439,7 +457,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, * @return the computed index * @since 3.4 */ - protected int computeIndexInPositionList(List positions, int offset, boolean orderedByOffset) { + protected int computeIndexInPositionList(List<Position> positions, int offset, boolean orderedByOffset) { if (positions.size() == 0) return 0; @@ -452,7 +470,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, mid= (left + right) / 2; - p= (Position) positions.get(mid); + p= positions.get(mid); int pOffset= getOffset(orderedByOffset, p); if (offset < pOffset) { if (left == mid) @@ -471,7 +489,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, } int pos= left; - p= (Position) positions.get(pos); + p= positions.get(pos); int pPosition= getOffset(orderedByOffset, p); if (offset > pPosition) { // append to the end @@ -482,7 +500,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, --pos; if (pos < 0) break; - p= (Position) positions.get(pos); + p= positions.get(pos); pPosition= getOffset(orderedByOffset, p); } while (offset == pPosition); ++pos; @@ -508,7 +526,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, if (0 > offset || offset > getLength()) throw new BadLocationException(); - List c= (List) fPositions.get(category); + List<Position> c= fPositions.get(category); if (c == null) throw new BadPositionCategoryException(); @@ -607,9 +625,9 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, flushPostNotificationChanges(); if (fDocumentPartitioners != null) { - Iterator e= fDocumentPartitioners.values().iterator(); + Iterator<IDocumentPartitioner> e= fDocumentPartitioners.values().iterator(); while (e.hasNext()) { - IDocumentPartitioner p= (IDocumentPartitioner) e.next(); + IDocumentPartitioner p= e.next(); if (p instanceof IDocumentPartitionerExtension3) { IDocumentPartitionerExtension3 extension= (IDocumentPartitionerExtension3) p; if (extension.getActiveRewriteSession() != null) @@ -653,10 +671,10 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, if (fDocumentPartitioners != null) { fDocumentPartitioningChangedEvent= new DocumentPartitioningChangedEvent(this); - Iterator e= fDocumentPartitioners.keySet().iterator(); + Iterator<String> e= fDocumentPartitioners.keySet().iterator(); while (e.hasNext()) { - String partitioning= (String) e.next(); - IDocumentPartitioner partitioner= (IDocumentPartitioner) fDocumentPartitioners.get(partitioning); + String partitioning= e.next(); + IDocumentPartitioner partitioner= fDocumentPartitioners.get(partitioning); if (partitioner instanceof IDocumentPartitionerExtension3) { IDocumentPartitionerExtension3 extension= (IDocumentPartitionerExtension3) partitioner; @@ -927,7 +945,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, if (category == null) throw new BadPositionCategoryException(); - List c= (List) fPositions.get(category); + List<Position> c= fPositions.get(category); if (c == null) throw new BadPositionCategoryException(); @@ -939,9 +957,9 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, @Override public String[] getPositionCategories() { String[] categories= new String[fPositions.size()]; - Iterator keys= fPositions.keySet().iterator(); + Iterator<String> keys= fPositions.keySet().iterator(); for (int i= 0; i < categories.length; i++) - categories[i]= (String) keys.next(); + categories[i]= keys.next(); return categories; } @@ -988,12 +1006,12 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, if (category == null) throw new BadPositionCategoryException(); - List c= (List) fPositions.get(category); + List<Position> c= fPositions.get(category); if (c == null) throw new BadPositionCategoryException(); removeFromPositionsList(c, position, true); - List endPositions= (List) fEndPositions.get(category); + List<Position> endPositions= fEndPositions.get(category); if (endPositions == null) throw new BadPositionCategoryException(); removeFromPositionsList(endPositions, position, false); @@ -1007,7 +1025,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, * @param orderedByOffset true if <code>positions</code> is ordered by offset, false if ordered by end position * @since 3.4 */ - private void removeFromPositionsList(List positions, Position position, boolean orderedByOffset) { + private void removeFromPositionsList(List<Position> positions, Position position, boolean orderedByOffset) { int size= positions.size(); //Assume position is somewhere near it was before @@ -1150,10 +1168,10 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, * the positions */ protected void updatePositions(DocumentEvent event) { - List list= new ArrayList(fPositionUpdaters); - Iterator e= list.iterator(); + List<IPositionUpdater> list= new ArrayList<>(fPositionUpdaters); + Iterator<IPositionUpdater> e= list.iterator(); while (e.hasNext()) { - IPositionUpdater u= (IPositionUpdater) e.next(); + IPositionUpdater u= e.next(); u.update(event); } } @@ -1211,12 +1229,12 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, return; while (fPostNotificationChanges != null) { - List changes= fPostNotificationChanges; + List<RegisteredReplace> changes= fPostNotificationChanges; fPostNotificationChanges= null; - Iterator e= changes.iterator(); + Iterator<RegisteredReplace> e= changes.iterator(); while (e.hasNext()) { - RegisteredReplace replace= (RegisteredReplace) e.next(); + RegisteredReplace replace= e.next(); replace.fReplace.perform(this, replace.fOwner); } } @@ -1236,7 +1254,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, public void registerPostNotificationReplace(IDocumentListener owner, IDocumentExtension.IReplace replace) { if (fAcceptPostNotificationReplaces) { if (fPostNotificationChanges == null) - fPostNotificationChanges= new ArrayList(1); + fPostNotificationChanges= new ArrayList<>(1); fPostNotificationChanges.add(new RegisteredReplace(owner, replace)); } } @@ -1352,7 +1370,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, @Override public IDocumentPartitioner getDocumentPartitioner(String partitioning) { - return fDocumentPartitioners != null ? (IDocumentPartitioner) fDocumentPartitioners.get(partitioning) : null; + return fDocumentPartitioners != null ? fDocumentPartitioners.get(partitioning) : null; } @Override @@ -1407,7 +1425,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, } } else { if (fDocumentPartitioners == null) - fDocumentPartitioners= new HashMap(); + fDocumentPartitioners= new HashMap<>(); fDocumentPartitioners.put(partitioning, partitioner); } DocumentPartitioningChangedEvent event= new DocumentPartitioningChangedEvent(this); @@ -1428,11 +1446,11 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, */ protected void fireRewriteSessionChanged(DocumentRewriteSessionEvent event) { if (fDocumentRewriteSessionListeners.size() > 0) { - List list= new ArrayList(fDocumentRewriteSessionListeners); - Iterator e= list.iterator(); + List<IDocumentRewriteSessionListener> list= new ArrayList<>(fDocumentRewriteSessionListeners); + Iterator<IDocumentRewriteSessionListener> e= list.iterator(); while (e.hasNext()) { try { - IDocumentRewriteSessionListener l= (IDocumentRewriteSessionListener)e.next(); + IDocumentRewriteSessionListener l= e.next(); l.documentRewriteSessionChanged(event); } catch (Exception ex) { log(ex); @@ -1483,7 +1501,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, */ protected final void startRewriteSessionOnPartitioners(DocumentRewriteSession session) { if (fDocumentPartitioners != null) { - Iterator e= fDocumentPartitioners.values().iterator(); + Iterator<IDocumentPartitioner> e= fDocumentPartitioners.values().iterator(); while (e.hasNext()) { Object partitioner= e.next(); if (partitioner instanceof IDocumentPartitionerExtension3) { @@ -1527,10 +1545,10 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, protected final void stopRewriteSessionOnPartitioners(DocumentRewriteSession session) { if (fDocumentPartitioners != null) { DocumentPartitioningChangedEvent event= new DocumentPartitioningChangedEvent(this); - Iterator e= fDocumentPartitioners.keySet().iterator(); + Iterator<String> e= fDocumentPartitioners.keySet().iterator(); while (e.hasNext()) { - String partitioning= (String) e.next(); - IDocumentPartitioner partitioner= (IDocumentPartitioner) fDocumentPartitioners.get(partitioning); + String partitioning= e.next(); + IDocumentPartitioner partitioner= fDocumentPartitioners.get(partitioning); if (partitioner instanceof IDocumentPartitionerExtension3) { IDocumentPartitionerExtension3 extension= (IDocumentPartitionerExtension3) partitioner; extension.stopRewriteSession(session); @@ -1597,7 +1615,7 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, */ public Position[] getPositions(String category, int offset, int length, boolean canStartBefore, boolean canEndAfter) throws BadPositionCategoryException { if (canStartBefore && canEndAfter || (!canStartBefore && !canEndAfter)) { - List documentPositions; + List<Position> documentPositions; if (canStartBefore && canEndAfter) { if (offset < getLength() / 2) { documentPositions= getStartingPositions(category, 0, offset + length); @@ -1608,12 +1626,12 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, documentPositions= getStartingPositions(category, offset, length); } - ArrayList list= new ArrayList(documentPositions.size()); + ArrayList<Position> list= new ArrayList<>(documentPositions.size()); Position region= new Position(offset, length); - for (Iterator iterator= documentPositions.iterator(); iterator.hasNext();) { - Position position= (Position) iterator.next(); + for (Iterator<Position> iterator= documentPositions.iterator(); iterator.hasNext();) { + Position position= iterator.next(); if (isWithinRegion(region, position, canStartBefore, canEndAfter)) { list.add(position); } @@ -1623,14 +1641,14 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, list.toArray(positions); return positions; } else if (canStartBefore) { - List list= getEndingPositions(category, offset, length); + List<Position> list= getEndingPositions(category, offset, length); Position[] positions= new Position[list.size()]; list.toArray(positions); return positions; } else { Assert.isLegal(canEndAfter && !canStartBefore); - List list= getStartingPositions(category, offset, length); + List<Position> list= getStartingPositions(category, offset, length); Position[] positions= new Position[list.size()]; list.toArray(positions); return positions; @@ -1664,8 +1682,8 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, * @throws BadPositionCategoryException if category is undefined in this document * @since 3.4 */ - private List getStartingPositions(String category, int offset, int length) throws BadPositionCategoryException { - List positions= (List) fPositions.get(category); + private List<Position> getStartingPositions(String category, int offset, int length) throws BadPositionCategoryException { + List<Position> positions= fPositions.get(category); if (positions == null) throw new BadPositionCategoryException(); @@ -1686,8 +1704,8 @@ public abstract class AbstractDocument implements IDocument, IDocumentExtension, * @throws BadPositionCategoryException if category is undefined in this document * @since 3.4 */ - private List getEndingPositions(String category, int offset, int length) throws BadPositionCategoryException { - List positions= (List) fEndPositions.get(category); + private List<Position> getEndingPositions(String category, int offset, int length) throws BadPositionCategoryException { + List<Position> positions= fEndPositions.get(category); if (positions == null) throw new BadPositionCategoryException(); diff --git a/org.eclipse.text/src/org/eclipse/jface/text/AbstractLineTracker.java b/org.eclipse.text/src/org/eclipse/jface/text/AbstractLineTracker.java index ba4f3ac17a3..8cf30f89628 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/AbstractLineTracker.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/AbstractLineTracker.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -88,7 +88,7 @@ public abstract class AbstractLineTracker implements ILineTracker, ILineTrackerE * * @since 3.1 */ - private List fPendingRequests; + private List<Request> fPendingRequests; /** * The implementation that this tracker delegates to. * @@ -233,7 +233,7 @@ public abstract class AbstractLineTracker implements ILineTracker, ILineTrackerE if (fActiveRewriteSession != null) throw new IllegalStateException(); fActiveRewriteSession= session; - fPendingRequests= new ArrayList(20); + fPendingRequests= new ArrayList<>(20); } @Override @@ -266,13 +266,13 @@ public abstract class AbstractLineTracker implements ILineTracker, ILineTrackerE if (DEBUG) System.out.println("AbstractLineTracker: Flushing rewrite session: " + fActiveRewriteSession); //$NON-NLS-1$ - Iterator e= fPendingRequests.iterator(); + Iterator<Request> e= fPendingRequests.iterator(); fPendingRequests= null; fActiveRewriteSession= null; while (e.hasNext()) { - Request request= (Request) e.next(); + Request request= e.next(); if (request.isReplaceRequest()) replace(request.offset, request.length, request.text); else diff --git a/org.eclipse.text/src/org/eclipse/jface/text/DocumentPartitioningChangedEvent.java b/org.eclipse.text/src/org/eclipse/jface/text/DocumentPartitioningChangedEvent.java index 1fc4a8db300..af7e0a05d58 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/DocumentPartitioningChangedEvent.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/DocumentPartitioningChangedEvent.java @@ -27,7 +27,7 @@ public class DocumentPartitioningChangedEvent { /** The document whose partitionings changed */ private final IDocument fDocument; /** The map of partitionings to changed regions. */ - private final Map fMap= new HashMap(); + private final Map<String, Region> fMap= new HashMap<>(); /** @@ -57,7 +57,7 @@ public class DocumentPartitioningChangedEvent { * @return the changed region of the given partitioning or <code>null</code> */ public IRegion getChangedRegion(String partitioning) { - return (IRegion) fMap.get(partitioning); + return fMap.get(partitioning); } /** @@ -105,9 +105,9 @@ public class DocumentPartitioningChangedEvent { int offset= -1; int endOffset= -1; - Iterator e= fMap.values().iterator(); + Iterator<Region> e= fMap.values().iterator(); while (e.hasNext()) { - IRegion r= (IRegion) e.next(); + IRegion r= e.next(); if (offset < 0 || r.getOffset() < offset) offset= r.getOffset(); diff --git a/org.eclipse.text/src/org/eclipse/jface/text/ListLineTracker.java b/org.eclipse.text/src/org/eclipse/jface/text/ListLineTracker.java index 11fcf70c977..299e9c647d6 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/ListLineTracker.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/ListLineTracker.java @@ -34,7 +34,7 @@ import org.eclipse.jface.text.AbstractLineTracker.DelimiterInfo; abstract class ListLineTracker implements ILineTracker { /** The line information */ - private final List fLines= new ArrayList(); + private final List<Line> fLines= new ArrayList<>(); /** The length of the tracked text */ private int fTextLength; @@ -64,7 +64,7 @@ abstract class ListLineTracker implements ILineTracker { mid= (left + right) / 2; - line= (Line) fLines.get(mid); + line= fLines.get(mid); if (offset < line.offset) { if (left == mid) right= left; @@ -80,7 +80,7 @@ abstract class ListLineTracker implements ILineTracker { } } - line= (Line) fLines.get(left); + line= fLines.get(left); if (line.offset > offset) --left; return left; @@ -102,7 +102,7 @@ abstract class ListLineTracker implements ILineTracker { int target= offset + length; - Line l= (Line) fLines.get(startLine); + Line l= fLines.get(startLine); if (l.delimiter == null) return 1; @@ -126,7 +126,7 @@ abstract class ListLineTracker implements ILineTracker { if (lines == 0 || lines == line) return 0; - Line l= (Line) fLines.get(line); + Line l= fLines.get(line); return l.length; } @@ -141,7 +141,7 @@ abstract class ListLineTracker implements ILineTracker { if (lastLine < 0) return 0; - Line l= (Line) fLines.get(lastLine); + Line l= fLines.get(lastLine); return (l.delimiter != null ? lastLine + 1 : lastLine); } @@ -157,7 +157,7 @@ abstract class ListLineTracker implements ILineTracker { int size= fLines.size(); if (size == 0) return new Region(0, 0); - Line l= (Line) fLines.get(size - 1); + Line l= fLines.get(size - 1); return (l.delimiter != null ? new Line(fTextLength, 0) : new Line(fTextLength - l.length, l.length)); } @@ -175,11 +175,11 @@ abstract class ListLineTracker implements ILineTracker { return new Line(0, 0); if (line == lines) { - Line l= (Line) fLines.get(line - 1); + Line l= fLines.get(line - 1); return new Line(l.offset + l.length, 0); } - Line l= (Line) fLines.get(line); + Line l= fLines.get(line); return (l.delimiter != null ? new Line(l.offset, l.length - l.delimiter.length()) : l); } @@ -194,13 +194,13 @@ abstract class ListLineTracker implements ILineTracker { return 0; if (line == lines) { - Line l= (Line) fLines.get(line - 1); + Line l= fLines.get(line - 1); if (l.delimiter != null) return l.offset + l.length; throw new BadLocationException(); } - Line l= (Line) fLines.get(line); + Line l= fLines.get(line); return l.offset; } @@ -211,7 +211,7 @@ abstract class ListLineTracker implements ILineTracker { if (lines == 0) return 1; - Line l= (Line) fLines.get(lines - 1); + Line l= fLines.get(lines - 1); return (l.delimiter != null ? lines + 1 : lines); } @@ -253,7 +253,7 @@ abstract class ListLineTracker implements ILineTracker { if (line == lines) return null; - Line l= (Line) fLines.get(line); + Line l= fLines.get(line); return l.delimiter; } @@ -300,7 +300,7 @@ abstract class ListLineTracker implements ILineTracker { if (start < text.length()) { if (insertPosition + count < fLines.size()) { // there is a line below the current - Line l= (Line) fLines.get(insertPosition + count); + Line l= fLines.get(insertPosition + count); int delta= text.length() - start; l.offset-= delta; l.length+= delta; @@ -333,7 +333,7 @@ abstract class ListLineTracker implements ILineTracker { * * @return the internal list of lines. */ - final List getLines() { + final List<Line> getLines() { return fLines; } } diff --git a/org.eclipse.text/src/org/eclipse/jface/text/SequentialRewriteTextStore.java b/org.eclipse.text/src/org/eclipse/jface/text/SequentialRewriteTextStore.java index 3c26c5de467..5d1de092ed2 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/SequentialRewriteTextStore.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/SequentialRewriteTextStore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -45,7 +45,7 @@ public class SequentialRewriteTextStore implements ITextStore { } /** The list of buffered replacements. */ - private LinkedList fReplaceList; + private LinkedList<Replace> fReplaceList; /** The source text store */ private ITextStore fSource; /** A flag to enforce sequential access. */ @@ -58,7 +58,7 @@ public class SequentialRewriteTextStore implements ITextStore { * @param source the source text store */ public SequentialRewriteTextStore(ITextStore source) { - fReplaceList= new LinkedList(); + fReplaceList= new LinkedList<>(); fSource= source; } @@ -81,15 +81,15 @@ public class SequentialRewriteTextStore implements ITextStore { fReplaceList.add(new Replace(offset, offset, length, text)); } else { - Replace firstReplace= (Replace) fReplaceList.getFirst(); - Replace lastReplace= (Replace) fReplaceList.getLast(); + Replace firstReplace= fReplaceList.getFirst(); + Replace lastReplace= fReplaceList.getLast(); // backward if (offset + length <= firstReplace.newOffset) { int delta= text.length() - length; if (delta != 0) { - for (Iterator i= fReplaceList.iterator(); i.hasNext(); ) { - Replace replace= (Replace) i.next(); + for (Iterator<Replace> i= fReplaceList.iterator(); i.hasNext(); ) { + Replace replace= i.next(); replace.newOffset += delta; } } @@ -124,8 +124,8 @@ public class SequentialRewriteTextStore implements ITextStore { return fSource.get(offset, length); - Replace firstReplace= (Replace) fReplaceList.getFirst(); - Replace lastReplace= (Replace) fReplaceList.getLast(); + Replace firstReplace= fReplaceList.getFirst(); + Replace lastReplace= fReplaceList.getLast(); // before if (offset + length <= firstReplace.newOffset) { @@ -142,8 +142,8 @@ public class SequentialRewriteTextStore implements ITextStore { } else { int delta= 0; - for (Iterator i= fReplaceList.iterator(); i.hasNext(); ) { - Replace replace= (Replace) i.next(); + for (Iterator<Replace> i= fReplaceList.iterator(); i.hasNext(); ) { + Replace replace= i.next(); if (offset + length < replace.newOffset) { return fSource.get(offset - delta, length); @@ -182,8 +182,8 @@ public class SequentialRewriteTextStore implements ITextStore { if (fReplaceList.isEmpty()) return fSource.get(offset); - Replace firstReplace= (Replace) fReplaceList.getFirst(); - Replace lastReplace= (Replace) fReplaceList.getLast(); + Replace firstReplace= fReplaceList.getFirst(); + Replace lastReplace= fReplaceList.getLast(); // before if (offset < firstReplace.newOffset) { @@ -200,8 +200,8 @@ public class SequentialRewriteTextStore implements ITextStore { } else { int delta= 0; - for (Iterator i= fReplaceList.iterator(); i.hasNext(); ) { - Replace replace= (Replace) i.next(); + for (Iterator<Replace> i= fReplaceList.iterator(); i.hasNext(); ) { + Replace replace= i.next(); if (offset < replace.newOffset) return fSource.get(offset - delta); @@ -221,7 +221,7 @@ public class SequentialRewriteTextStore implements ITextStore { if (fReplaceList.isEmpty()) return fSource.getLength(); - Replace lastReplace= (Replace) fReplaceList.getLast(); + Replace lastReplace= fReplaceList.getLast(); return fSource.getLength() + getDelta(lastReplace); } @@ -244,8 +244,8 @@ public class SequentialRewriteTextStore implements ITextStore { StringBuffer buffer= new StringBuffer(); int delta= 0; - for (Iterator i= fReplaceList.iterator(); i.hasNext(); ) { - Replace replace= (Replace) i.next(); + for (Iterator<Replace> i= fReplaceList.iterator(); i.hasNext(); ) { + Replace replace= i.next(); int offset= buffer.length() - delta; buffer.append(fSource.get(offset, replace.offset - offset)); diff --git a/org.eclipse.text/src/org/eclipse/jface/text/TextUtilities.java b/org.eclipse.text/src/org/eclipse/jface/text/TextUtilities.java index 64fcf4c94c7..df2e9ad5029 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/TextUtilities.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/TextUtilities.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -182,13 +182,13 @@ public class TextUtilities { * @return returns the merged document event * @throws BadLocationException might be thrown if document is not in the correct state with respect to document events */ - public static DocumentEvent mergeUnprocessedDocumentEvents(IDocument unprocessedDocument, List documentEvents) throws BadLocationException { + public static DocumentEvent mergeUnprocessedDocumentEvents(IDocument unprocessedDocument, List<? extends DocumentEvent> documentEvents) throws BadLocationException { if (documentEvents.size() == 0) return null; - final Iterator iterator= documentEvents.iterator(); - final DocumentEvent firstEvent= (DocumentEvent) iterator.next(); + final Iterator<? extends DocumentEvent> iterator= documentEvents.iterator(); + final DocumentEvent firstEvent= iterator.next(); // current merged event final IDocument document= unprocessedDocument; @@ -200,7 +200,7 @@ public class TextUtilities { final int delta= text.length() - length; - final DocumentEvent event= (DocumentEvent) iterator.next(); + final DocumentEvent event= iterator.next(); final int eventOffset= event.getOffset(); final int eventLength= event.getLength(); final String eventText= event.getText() == null ? "" : event.getText(); //$NON-NLS-1$ @@ -247,13 +247,13 @@ public class TextUtilities { * @return returns the merged document event * @throws BadLocationException might be thrown if document is not in the correct state with respect to document events */ - public static DocumentEvent mergeProcessedDocumentEvents(List documentEvents) throws BadLocationException { + public static DocumentEvent mergeProcessedDocumentEvents(List<? extends DocumentEvent> documentEvents) throws BadLocationException { if (documentEvents.size() == 0) return null; - final ListIterator iterator= documentEvents.listIterator(documentEvents.size()); - final DocumentEvent firstEvent= (DocumentEvent) iterator.previous(); + final ListIterator<? extends DocumentEvent> iterator= documentEvents.listIterator(documentEvents.size()); + final DocumentEvent firstEvent= iterator.previous(); // current merged event final IDocument document= firstEvent.getDocument(); @@ -265,7 +265,7 @@ public class TextUtilities { final int delta= length - textLength; - final DocumentEvent event= (DocumentEvent) iterator.previous(); + final DocumentEvent event= iterator.previous(); final int eventOffset= event.getOffset(); final int eventLength= event.getLength(); final int eventTextLength= event.getText() == null ? 0 : event.getText().length(); @@ -303,11 +303,10 @@ public class TextUtilities { * the given document is no longer connected to any document partitioner. * * @param document the document - * @return the map containing the removed partitioners (key type: {@link String}, value type: - * {@link IDocumentPartitioner}) + * @return the map containing the removed partitioners */ - public static Map removeDocumentPartitioners(IDocument document) { - Map partitioners= new HashMap(); + public static Map<String, IDocumentPartitioner> removeDocumentPartitioners(IDocument document) { + Map<String, IDocumentPartitioner> partitioners= new HashMap<>(); if (document instanceof IDocumentExtension3) { IDocumentExtension3 extension3= (IDocumentExtension3) document; String[] partitionings= extension3.getPartitionings(); @@ -335,23 +334,22 @@ public class TextUtilities { * their partitioning name. This method cleans the given map. * * @param document the document - * @param partitioners the map containing the partitioners to be connected (key type: {@link String}, value type: - * {@link IDocumentPartitioner}) + * @param partitioners the map containing the partitioners to be connected * @since 3.0 */ - public static void addDocumentPartitioners(IDocument document, Map partitioners) { + public static void addDocumentPartitioners(IDocument document, Map<String, ? extends IDocumentPartitioner> partitioners) { if (document instanceof IDocumentExtension3) { IDocumentExtension3 extension3= (IDocumentExtension3) document; - Iterator e= partitioners.keySet().iterator(); + Iterator<String> e= partitioners.keySet().iterator(); while (e.hasNext()) { - String partitioning= (String) e.next(); - IDocumentPartitioner partitioner= (IDocumentPartitioner) partitioners.get(partitioning); + String partitioning= e.next(); + IDocumentPartitioner partitioner= partitioners.get(partitioning); partitioner.connect(document); extension3.setDocumentPartitioner(partitioning, partitioner); } partitioners.clear(); } else { - IDocumentPartitioner partitioner= (IDocumentPartitioner) partitioners.get(IDocumentExtension3.DEFAULT_PARTITIONING); + IDocumentPartitioner partitioner= partitioners.get(IDocumentExtension3.DEFAULT_PARTITIONING); partitioner.connect(document); document.setDocumentPartitioner(partitioner); } @@ -451,7 +449,7 @@ public class TextUtilities { IDocumentExtension3 extension3= (IDocumentExtension3) document; String[] partitionings= extension3.getPartitionings(); if (partitionings != null) { - Set categories= new HashSet(); + Set<String> categories= new HashSet<>(); for (int i= 0; i < partitionings.length; i++) { IDocumentPartitioner p= extension3.getDocumentPartitioner(partitionings[i]); if (p instanceof IDocumentPartitionerExtension2) { diff --git a/org.eclipse.text/src/org/eclipse/jface/text/TreeLineTracker.java b/org.eclipse.text/src/org/eclipse/jface/text/TreeLineTracker.java index faede932120..9c2acf1bb5b 100755 --- a/org.eclipse.text/src/org/eclipse/jface/text/TreeLineTracker.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/TreeLineTracker.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2010 IBM Corporation and others. + * Copyright (c) 2005, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -170,12 +170,12 @@ abstract class TreeLineTracker implements ILineTracker { * @param tracker the list line tracker */ TreeLineTracker(ListLineTracker tracker) { - final List lines= tracker.getLines(); + final List<Line> lines= tracker.getLines(); final int n= lines.size(); if (n == 0) return; - Line line= (Line) lines.get(0); + Line line= lines.get(0); String delim= line.delimiter; if (delim == null) delim= NO_DELIM; @@ -184,7 +184,7 @@ abstract class TreeLineTracker implements ILineTracker { Node node= fRoot; for (int i= 1; i < n; i++) { - line= (Line) lines.get(i); + line= lines.get(i); delim= line.delimiter; if (delim == null) delim= NO_DELIM; @@ -1229,7 +1229,7 @@ abstract class TreeLineTracker implements ILineTracker { int width= WIDTH * leaves; String empty= "."; //$NON-NLS-1$ - List roots= new LinkedList(); + List<Node> roots= new LinkedList<>(); roots.add(fRoot); StringBuffer buf= new StringBuffer((width + 1) * depth); int indents= leaves; @@ -1240,11 +1240,11 @@ abstract class TreeLineTracker implements ILineTracker { indents /= 2; int spaces= Math.max(0, indents * WIDTH - WIDTH / 2); // print nodes - for (ListIterator it= roots.listIterator(); it.hasNext();) { + for (ListIterator<Node> it= roots.listIterator(); it.hasNext();) { // pad before buf.append(space, 0, spaces); - Node node= (Node) it.next(); + Node node= it.next(); String box; // replace the node with its children if (node == null) { diff --git a/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedModeManager.java b/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedModeManager.java index d91f4a119ed..8334798e9ac 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedModeManager.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedModeManager.java @@ -55,7 +55,7 @@ class LinkedModeManager { } /** Global map from documents to managers. */ - private static Map fgManagers= new HashMap(); + private static Map<IDocument, LinkedModeManager> fgManagers= new HashMap<>(); /** * Returns whether there exists a <code>LinkedModeManager</code> on <code>document</code>. @@ -94,17 +94,17 @@ class LinkedModeManager { if (documents == null || documents.length == 0) return null; - Set mgrs= new HashSet(); + Set<LinkedModeManager> mgrs= new HashSet<>(); LinkedModeManager mgr= null; for (int i= 0; i < documents.length; i++) { - mgr= (LinkedModeManager) fgManagers.get(documents[i]); + mgr= fgManagers.get(documents[i]); if (mgr != null) mgrs.add(mgr); } if (mgrs.size() > 1) if (force) { - for (Iterator it= mgrs.iterator(); it.hasNext(); ) { - LinkedModeManager m= (LinkedModeManager) it.next(); + for (Iterator<LinkedModeManager> it= mgrs.iterator(); it.hasNext(); ) { + LinkedModeManager m= it.next(); m.closeAllEnvironments(); } } else { @@ -126,13 +126,13 @@ class LinkedModeManager { * @param document the document whose <code>LinkedModeManager</code> should be canceled */ public static void cancelManager(IDocument document) { - LinkedModeManager mgr= (LinkedModeManager) fgManagers.get(document); + LinkedModeManager mgr= fgManagers.get(document); if (mgr != null) mgr.closeAllEnvironments(); } /** The hierarchy of environments managed by this manager. */ - private Stack fEnvironments= new Stack(); + private Stack<LinkedModeModel> fEnvironments= new Stack<>(); private Listener fListener= new Listener(); /** @@ -146,7 +146,7 @@ class LinkedModeManager { return; while (!fEnvironments.isEmpty()) { - LinkedModeModel env= (LinkedModeModel) fEnvironments.pop(); + LinkedModeModel env= fEnvironments.pop(); if (env == model) break; env.exit(ILinkedModeListener.NONE); @@ -159,7 +159,7 @@ class LinkedModeManager { private void closeAllEnvironments() { while (!fEnvironments.isEmpty()) { - LinkedModeModel env= (LinkedModeModel) fEnvironments.pop(); + LinkedModeModel env= fEnvironments.pop(); env.exit(ILinkedModeListener.NONE); } @@ -167,8 +167,8 @@ class LinkedModeManager { } private void removeManager() { - for (Iterator it= fgManagers.keySet().iterator(); it.hasNext();) { - IDocument doc= (IDocument) it.next(); + for (Iterator<IDocument> it= fgManagers.keySet().iterator(); it.hasNext();) { + IDocument doc= it.next(); if (fgManagers.get(doc) == this) it.remove(); } @@ -195,7 +195,7 @@ class LinkedModeManager { return true; } - LinkedModeModel top= (LinkedModeModel) fEnvironments.peek(); + LinkedModeModel top= fEnvironments.peek(); if (model.canNestInto(top)) { model.addLinkingListener(fListener); fEnvironments.push(model); @@ -223,6 +223,6 @@ class LinkedModeManager { public LinkedModeModel getTopEnvironment() { if (fEnvironments.isEmpty()) return null; - return (LinkedModeModel) fEnvironments.peek(); + return fEnvironments.peek(); } } diff --git a/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedModeModel.java b/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedModeModel.java index d6ad8897ef9..0a19721ca1b 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedModeModel.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedModeModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -28,10 +28,10 @@ import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension; +import org.eclipse.jface.text.IDocumentExtension.IReplace; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.Position; -import org.eclipse.jface.text.IDocumentExtension.IReplace; /** @@ -182,8 +182,8 @@ public class LinkedModeModel { if (fParentEnvironment != null && fParentEnvironment.isChanging()) return; - for (Iterator it= fGroups.iterator(); it.hasNext(); ) { - LinkedPositionGroup group= (LinkedPositionGroup) it.next(); + for (Iterator<LinkedPositionGroup> it= fGroups.iterator(); it.hasNext(); ) { + LinkedPositionGroup group= it.next(); if (!group.isLegalEvent(event)) { fExit= true; return; @@ -209,11 +209,11 @@ public class LinkedModeModel { return; // collect all results - Map result= null; - for (Iterator it= fGroups.iterator(); it.hasNext();) { - LinkedPositionGroup group= (LinkedPositionGroup) it.next(); + Map<IDocument, TextEdit> result= null; + for (Iterator<LinkedPositionGroup> it= fGroups.iterator(); it.hasNext();) { + LinkedPositionGroup group= it.next(); - Map map= group.handleEvent(event); + Map<IDocument, TextEdit> map= group.handleEvent(event); if (result != null && map != null) { // exit if more than one position was changed LinkedModeModel.this.exit(ILinkedModeListener.EXTERNAL_MODIFICATION); @@ -225,9 +225,9 @@ public class LinkedModeModel { if (result != null) { // edit all documents - for (Iterator it2= result.keySet().iterator(); it2.hasNext(); ) { - IDocument doc= (IDocument) it2.next(); - TextEdit edit= (TextEdit) result.get(doc); + for (Iterator<IDocument> it2= result.keySet().iterator(); it2.hasNext(); ) { + IDocument doc= it2.next(); + TextEdit edit= result.get(doc); Replace replace= new Replace(edit); // apply the edition, either as post notification replace @@ -249,9 +249,9 @@ public class LinkedModeModel { } /** The set of linked position groups. */ - private final List fGroups= new ArrayList(); + private final List<LinkedPositionGroup> fGroups= new ArrayList<>(); /** The set of documents spanned by this group. */ - private final Set fDocuments= new HashSet(); + private final Set<IDocument> fDocuments= new HashSet<>(); /** The position updater for linked positions. */ private final IPositionUpdater fUpdater= new InclusivePositionUpdater(getCategory()); /** The document listener on the documents affected by this model. */ @@ -272,14 +272,14 @@ public class LinkedModeModel { /** <code>true</code> when this model is changing documents. */ private boolean fIsChanging= false; /** The linked listeners. */ - private final List fListeners= new ArrayList(); + private final List<ILinkedModeListener> fListeners= new ArrayList<>(); /** Flag telling whether we have exited: */ private boolean fIsActive= true; /** * The sequence of document positions as we are going to iterate through * them. */ - private List fPositionSequence= new ArrayList(); + private List<LinkedPosition> fPositionSequence= new ArrayList<>(); /** * Whether we are in the process of editing documents (set by <code>Replace</code>, @@ -301,8 +301,8 @@ public class LinkedModeModel { * model's groups */ private void enforceDisjoint(LinkedPositionGroup group) throws BadLocationException { - for (Iterator it= fGroups.iterator(); it.hasNext(); ) { - LinkedPositionGroup g= (LinkedPositionGroup) it.next(); + for (Iterator<LinkedPositionGroup> it= fGroups.iterator(); it.hasNext(); ) { + LinkedPositionGroup g= it.next(); g.enforceDisjoint(group); } } @@ -319,8 +319,8 @@ public class LinkedModeModel { fIsActive= false; - for (Iterator it= fDocuments.iterator(); it.hasNext(); ) { - IDocument doc= (IDocument) it.next(); + for (Iterator<IDocument> it= fDocuments.iterator(); it.hasNext(); ) { + IDocument doc= it.next(); try { doc.removePositionCategory(getCategory()); } catch (BadPositionCategoryException e) { @@ -334,10 +334,10 @@ public class LinkedModeModel { fDocuments.clear(); fGroups.clear(); - List listeners= new ArrayList(fListeners); + List<ILinkedModeListener> listeners= new ArrayList<>(fListeners); fListeners.clear(); - for (Iterator it= listeners.iterator(); it.hasNext(); ) { - ILinkedModeListener listener= (ILinkedModeListener) it.next(); + for (Iterator<ILinkedModeListener> it= listeners.iterator(); it.hasNext(); ) { + ILinkedModeListener listener= it.next(); listener.left(this, flags); } @@ -507,8 +507,8 @@ public class LinkedModeModel { // register positions try { - for (Iterator it= fGroups.iterator(); it.hasNext(); ) { - LinkedPositionGroup group= (LinkedPositionGroup) it.next(); + for (Iterator<LinkedPositionGroup> it= fGroups.iterator(); it.hasNext(); ) { + LinkedPositionGroup group= it.next(); group.register(this); } return true; @@ -525,8 +525,8 @@ public class LinkedModeModel { */ private void enforceNotEmpty() { boolean hasPosition= false; - for (Iterator it= fGroups.iterator(); it.hasNext(); ) - if (!((LinkedPositionGroup) it.next()).isEmpty()) { + for (Iterator<LinkedPositionGroup> it= fGroups.iterator(); it.hasNext(); ) + if (!it.next().isEmpty()) { hasPosition= true; break; } @@ -540,12 +540,12 @@ public class LinkedModeModel { * @return the set of documents affected by this model */ private IDocument[] getDocuments() { - Set docs= new HashSet(); - for (Iterator it= fGroups.iterator(); it.hasNext(); ) { - LinkedPositionGroup group= (LinkedPositionGroup) it.next(); + Set<IDocument> docs= new HashSet<>(); + for (Iterator<LinkedPositionGroup> it= fGroups.iterator(); it.hasNext(); ) { + LinkedPositionGroup group= it.next(); docs.addAll(Arrays.asList(group.getDocuments())); } - return (IDocument[]) docs.toArray(new IDocument[docs.size()]); + return docs.toArray(new IDocument[docs.size()]); } /** @@ -557,8 +557,8 @@ public class LinkedModeModel { * @return <code>true</code> if the receiver can be nested into <code>parent</code>, <code>false</code> otherwise */ boolean canNestInto(LinkedModeModel parent) { - for (Iterator it= fGroups.iterator(); it.hasNext(); ) { - LinkedPositionGroup group= (LinkedPositionGroup) it.next(); + for (Iterator<LinkedPositionGroup> it= fGroups.iterator(); it.hasNext(); ) { + LinkedPositionGroup group= it.next(); if (!enforceNestability(group, parent)) { fParentPosition= null; return false; @@ -584,8 +584,8 @@ public class LinkedModeModel { Assert.isNotNull(group); try { - for (Iterator it= model.fGroups.iterator(); it.hasNext(); ) { - LinkedPositionGroup pg= (LinkedPositionGroup) it.next(); + for (Iterator<LinkedPositionGroup> it= model.fGroups.iterator(); it.hasNext(); ) { + LinkedPositionGroup pg= it.next(); LinkedPosition pos; pos= pg.adopt(group); if (pos != null && fParentPosition != null && fParentPosition != pos) @@ -628,7 +628,7 @@ public class LinkedModeModel { * @return the positions in this model that have a tab stop, in the * order they were added */ - public List getTabStopSequence() { + public List<LinkedPosition> getTabStopSequence() { return fPositionSequence; } @@ -670,8 +670,8 @@ public class LinkedModeModel { */ public LinkedPosition findPosition(LinkedPosition toFind) { LinkedPosition position= null; - for (Iterator it= fGroups.iterator(); it.hasNext(); ) { - LinkedPositionGroup group= (LinkedPositionGroup) it.next(); + for (Iterator<LinkedPositionGroup> it= fGroups.iterator(); it.hasNext(); ) { + LinkedPositionGroup group= it.next(); position= group.getPosition(toFind); if (position != null) break; @@ -708,9 +708,9 @@ public class LinkedModeModel { * Suspends this model. */ private void suspend() { - List l= new ArrayList(fListeners); - for (Iterator it= l.iterator(); it.hasNext(); ) { - ILinkedModeListener listener= (ILinkedModeListener) it.next(); + List<ILinkedModeListener> l= new ArrayList<>(fListeners); + for (Iterator<ILinkedModeListener> it= l.iterator(); it.hasNext(); ) { + ILinkedModeListener listener= it.next(); listener.suspend(this); } } @@ -722,9 +722,9 @@ public class LinkedModeModel { * @param flags <code>NONE</code> or <code>SELECT</code> */ private void resume(int flags) { - List l= new ArrayList(fListeners); - for (Iterator it= l.iterator(); it.hasNext(); ) { - ILinkedModeListener listener= (ILinkedModeListener) it.next(); + List<ILinkedModeListener> l= new ArrayList<>(fListeners); + for (Iterator<ILinkedModeListener> it= l.iterator(); it.hasNext(); ) { + ILinkedModeListener listener= it.next(); listener.resume(this, flags); } } @@ -739,8 +739,8 @@ public class LinkedModeModel { * model, <code>false</code> otherwise */ public boolean anyPositionContains(int offset) { - for (Iterator it= fGroups.iterator(); it.hasNext(); ) { - LinkedPositionGroup group= (LinkedPositionGroup) it.next(); + for (Iterator<LinkedPositionGroup> it= fGroups.iterator(); it.hasNext(); ) { + LinkedPositionGroup group= it.next(); if (group.contains(offset)) // take the first hit - exclusion is guaranteed by enforcing // disjointness when adding positions @@ -767,8 +767,8 @@ public class LinkedModeModel { * or <code>null</code> if no group contains <code>position</code> */ public LinkedPositionGroup getGroupForPosition(Position position) { - for (Iterator it= fGroups.iterator(); it.hasNext(); ) { - LinkedPositionGroup group= (LinkedPositionGroup) it.next(); + for (Iterator<LinkedPositionGroup> it= fGroups.iterator(); it.hasNext(); ) { + LinkedPositionGroup group= it.next(); if (group.contains(position)) return group; } diff --git a/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedPositionGroup.java b/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedPositionGroup.java index 9c8450d316a..49f39fd2d77 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedPositionGroup.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/link/LinkedPositionGroup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -62,7 +62,7 @@ public class LinkedPositionGroup { /* members */ /** The linked positions of this group. */ - private final List fPositions= new LinkedList(); + private final List<LinkedPosition> fPositions= new LinkedList<>(); /** Whether we are sealed or not. */ private boolean fIsSealed= false; /** @@ -137,7 +137,7 @@ public class LinkedPositionGroup { */ private void checkContent(LinkedPosition position) throws BadLocationException { if (fPositions.size() > 0) { - LinkedPosition groupPosition= (LinkedPosition) fPositions.get(0); + LinkedPosition groupPosition= fPositions.get(0); String groupContent= groupPosition.getContent(); String positionContent= position.getContent(); if (!fMustEnforceEqualContents && !groupContent.equals(positionContent)) { @@ -153,8 +153,8 @@ public class LinkedPositionGroup { * @throws BadLocationException if the disjointness check fails */ private void enforceDisjoint(LinkedPosition position) throws BadLocationException { - for (Iterator it= fPositions.iterator(); it.hasNext(); ) { - LinkedPosition p= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= fPositions.iterator(); it.hasNext(); ) { + LinkedPosition p= it.next(); if (p.overlapsWith(position)) throw new BadLocationException(); } @@ -168,8 +168,8 @@ public class LinkedPositionGroup { */ void enforceDisjoint(LinkedPositionGroup group) throws BadLocationException { Assert.isNotNull(group); - for (Iterator it= group.fPositions.iterator(); it.hasNext(); ) { - LinkedPosition p= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= group.fPositions.iterator(); it.hasNext(); ) { + LinkedPosition p= it.next(); enforceDisjoint(p); } } @@ -186,8 +186,8 @@ public class LinkedPositionGroup { fLastPosition= null; fLastRegion= null; - for (Iterator it= fPositions.iterator(); it.hasNext(); ) { - LinkedPosition pos= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= fPositions.iterator(); it.hasNext(); ) { + LinkedPosition pos= it.next(); if (overlapsOrTouches(pos, event)) { if (fLastPosition != null) { fLastPosition= null; @@ -226,11 +226,11 @@ public class LinkedPositionGroup { * @return a map of edits, grouped by edited document, or <code>null</code> * if there are no edits */ - Map handleEvent(DocumentEvent event) { + Map<IDocument, TextEdit> handleEvent(DocumentEvent event) { if (fLastPosition != null) { - Map map= new HashMap(); + Map<IDocument, List<ReplaceEdit>> map= new HashMap<>(); int relativeOffset= event.getOffset() - fLastRegion.getOffset(); @@ -250,14 +250,14 @@ public class LinkedPositionGroup { if (text == null) text= ""; //$NON-NLS-1$ - for (Iterator it= fPositions.iterator(); it.hasNext(); ) { - LinkedPosition p= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= fPositions.iterator(); it.hasNext(); ) { + LinkedPosition p= it.next(); if (p == fLastPosition || p.isDeleted()) continue; // don't re-update the origin of the change - List edits= (List) map.get(p.getDocument()); + List<ReplaceEdit> edits= map.get(p.getDocument()); if (edits == null) { - edits= new ArrayList(); + edits= new ArrayList<>(); map.put(p.getDocument(), edits); } @@ -274,14 +274,15 @@ public class LinkedPositionGroup { fMustEnforceEqualContents= false; try { - for (Iterator it= map.keySet().iterator(); it.hasNext();) { - IDocument d= (IDocument) it.next(); + Map<IDocument, TextEdit> result= new HashMap<>(); + for (Iterator<IDocument> it= map.keySet().iterator(); it.hasNext();) { + IDocument d= it.next(); TextEdit edit= new MultiTextEdit(0, d.getLength()); - edit.addChildren((TextEdit[]) ((List) map.get(d)).toArray(new TextEdit[0])); - map.put(d, edit); + edit.addChildren(map.get(d).toArray(new TextEdit[0])); + result.put(d, edit); } - return map; + return result; } catch (MalformedTreeException x) { // may happen during undo, as LinkedModeModel does not know // that the changes technically originate from a parent environment @@ -305,23 +306,23 @@ public class LinkedPositionGroup { fIsSealed= true; if (fHasCustomIteration == false && fPositions.size() > 0) { - ((LinkedPosition) fPositions.get(0)).setSequenceNumber(0); + fPositions.get(0).setSequenceNumber(0); } } IDocument[] getDocuments() { IDocument[] docs= new IDocument[fPositions.size()]; int i= 0; - for (Iterator it= fPositions.iterator(); it.hasNext(); i++) { - LinkedPosition pos= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= fPositions.iterator(); it.hasNext(); i++) { + LinkedPosition pos= it.next(); docs[i]= pos.getDocument(); } return docs; } void register(LinkedModeModel model) throws BadLocationException { - for (Iterator it= fPositions.iterator(); it.hasNext(); ) { - LinkedPosition pos= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= fPositions.iterator(); it.hasNext(); ) { + LinkedPosition pos= it.next(); model.register(pos); } } @@ -338,11 +339,11 @@ public class LinkedPositionGroup { */ LinkedPosition adopt(LinkedPositionGroup group) throws BadLocationException { LinkedPosition found= null; - for (Iterator it= group.fPositions.iterator(); it.hasNext(); ) { - LinkedPosition pos= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= group.fPositions.iterator(); it.hasNext(); ) { + LinkedPosition pos= it.next(); LinkedPosition localFound= null; - for (Iterator it2= fPositions.iterator(); it2.hasNext(); ) { - LinkedPosition myPos= (LinkedPosition) it2.next(); + for (Iterator<LinkedPosition> it2= fPositions.iterator(); it2.hasNext(); ) { + LinkedPosition myPos= it2.next(); if (myPos.includes(pos)) { if (found == null) found= myPos; @@ -366,8 +367,8 @@ public class LinkedPositionGroup { * @return the closest position to <code>toFind</code>. */ LinkedPosition getPosition(LinkedPosition toFind) { - for (Iterator it= fPositions.iterator(); it.hasNext(); ) { - LinkedPosition p= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= fPositions.iterator(); it.hasNext(); ) { + LinkedPosition p= it.next(); if (p.includes(toFind)) return p; } @@ -382,8 +383,8 @@ public class LinkedPositionGroup { * @return <code>true</code> if offset is contained by this group */ boolean contains(int offset) { - for (Iterator it= fPositions.iterator(); it.hasNext(); ) { - LinkedPosition pos= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= fPositions.iterator(); it.hasNext(); ) { + LinkedPosition pos= it.next(); if (pos.includes(offset)) { return true; } @@ -420,7 +421,7 @@ public class LinkedPositionGroup { * @return the positions of this group in no particular order */ public LinkedPosition[] getPositions() { - return (LinkedPosition[]) fPositions.toArray(new LinkedPosition[0]); + return fPositions.toArray(new LinkedPosition[0]); } /** @@ -430,8 +431,8 @@ public class LinkedPositionGroup { * @return <code>true</code> if the receiver contains <code>position</code> */ boolean contains(Position position) { - for (Iterator it= fPositions.iterator(); it.hasNext(); ) { - LinkedPosition p= (LinkedPosition) it.next(); + for (Iterator<LinkedPosition> it= fPositions.iterator(); it.hasNext(); ) { + LinkedPosition p= it.next(); if (position.equals(p)) return true; } diff --git a/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationMap.java b/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationMap.java index 490083414c3..e43af5b7739 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationMap.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationMap.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -18,6 +18,8 @@ import java.util.Iterator; import java.util.Map; import java.util.Set; +import org.eclipse.jface.text.Position; + /** * Internal implementation of {@link org.eclipse.jface.text.source.IAnnotationMap}. @@ -38,7 +40,7 @@ class AnnotationMap implements IAnnotationMap { private final Object fInternalLockObject= new Object(); /** The map holding the annotations */ - private Map fInternalMap; + private Map<Annotation, Position> fInternalMap; /** * Creates a new annotation map with the given capacity. @@ -46,7 +48,7 @@ class AnnotationMap implements IAnnotationMap { * @param capacity the capacity */ public AnnotationMap(int capacity) { - fInternalMap= new HashMap(capacity); + fInternalMap= new HashMap<>(capacity); } @Override @@ -62,16 +64,16 @@ class AnnotationMap implements IAnnotationMap { } @Override - public Iterator valuesIterator() { + public Iterator<Position> valuesIterator() { synchronized (getLockObject()) { - return new ArrayList(fInternalMap.values()).iterator(); + return new ArrayList<>(fInternalMap.values()).iterator(); } } @Override - public Iterator keySetIterator() { + public Iterator<Annotation> keySetIterator() { synchronized (getLockObject()) { - return new ArrayList(fInternalMap.keySet()).iterator(); + return new ArrayList<>(fInternalMap.keySet()).iterator(); } } @@ -83,14 +85,14 @@ class AnnotationMap implements IAnnotationMap { } @Override - public Object put(Object annotation, Object position) { + public Position put(Annotation annotation, Position position) { synchronized (getLockObject()) { return fInternalMap.put(annotation, position); } } @Override - public Object get(Object annotation) { + public Position get(Object annotation) { synchronized (getLockObject()) { return fInternalMap.get(annotation); } @@ -104,7 +106,7 @@ class AnnotationMap implements IAnnotationMap { } @Override - public Object remove(Object annotation) { + public Position remove(Object annotation) { synchronized (getLockObject()) { return fInternalMap.remove(annotation); } @@ -132,28 +134,28 @@ class AnnotationMap implements IAnnotationMap { } @Override - public void putAll(Map map) { + public void putAll(Map<? extends Annotation, ? extends Position> map) { synchronized (getLockObject()) { fInternalMap.putAll(map); } } @Override - public Set entrySet() { + public Set<Entry<Annotation, Position>> entrySet() { synchronized (getLockObject()) { return fInternalMap.entrySet(); } } @Override - public Set keySet() { + public Set<Annotation> keySet() { synchronized (getLockObject()) { return fInternalMap.keySet(); } } @Override - public Collection values() { + public Collection<Position> values() { synchronized (getLockObject()) { return fInternalMap.values(); } diff --git a/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModel.java b/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModel.java index 3631aee4f0d..d3ae54c0c69 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModel.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModel.java @@ -18,6 +18,7 @@ import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.NoSuchElementException; import org.eclipse.core.runtime.Assert; @@ -49,13 +50,13 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * @since 3.4 * @see AnnotationModel.RegionIterator#RegionIterator(Iterator, IAnnotationModel, int, int, boolean, boolean) */ - private static final class RegionIterator implements Iterator { + private static final class RegionIterator implements Iterator<Annotation> { - private final Iterator fParentIterator; + private final Iterator<Annotation> fParentIterator; private final boolean fCanEndAfter; private final boolean fCanStartBefore; private final IAnnotationModel fModel; - private Object fNext; + private Annotation fNext; private Position fRegion; /** @@ -74,7 +75,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * @param canEndAfter include annotations ending after region * @see IAnnotationModelExtension2 */ - public RegionIterator(Iterator parentIterator, IAnnotationModel model, int offset, int length, boolean canStartBefore, boolean canEndAfter) { + public RegionIterator(Iterator<Annotation> parentIterator, IAnnotationModel model, int offset, int length, boolean canStartBefore, boolean canEndAfter) { fParentIterator= parentIterator; fModel= model; fRegion= new Position(offset, length); @@ -89,11 +90,11 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens } @Override - public Object next() { + public Annotation next() { if (!hasNext()) throw new NoSuchElementException(); - Object result= fNext; + Annotation result= fNext; fNext= findNext(); return result; } @@ -103,9 +104,9 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens throw new UnsupportedOperationException(); } - private Object findNext() { + private Annotation findNext() { while (fParentIterator.hasNext()) { - Annotation next= (Annotation) fParentIterator.next(); + Annotation next= fParentIterator.next(); Position position= fModel.getPosition(next); if (position != null) { int offset= position.getOffset(); @@ -134,18 +135,18 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * * @since 3.4 */ - private static final class AnnotationsInterator implements Iterator { + private static final class AnnotationsInterator implements Iterator<Annotation> { - private Object fNext; + private Annotation fNext; private final Position[] fPositions; private int fIndex; - private final Map fMap; + private final Map<Position, Annotation> fMap; /** * @param positions positions to iterate over * @param map a map to map positions to annotations */ - public AnnotationsInterator(Position[] positions, Map map) { + public AnnotationsInterator(Position[] positions, Map<Position, Annotation> map) { fPositions= positions; fIndex= 0; fMap= map; @@ -158,8 +159,8 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens } @Override - public Object next() { - Object result= fNext; + public Annotation next() { + Annotation result= fNext; fNext= findNext(); return result; } @@ -169,7 +170,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens throw new UnsupportedOperationException(); } - private Object findNext() { + private Annotation findNext() { while (fIndex < fPositions.length) { Position position= fPositions[fIndex]; fIndex++; @@ -183,22 +184,23 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens /** * A single iterator builds its behavior based on a sequence of iterators. - * + * + * @param <E> the type of elements returned by this iterator * @since 3.1 */ - private static class MetaIterator implements Iterator { + private static class MetaIterator<E> implements Iterator<E> { /** The iterator over a list of iterators. */ - private Iterator fSuperIterator; + private Iterator<? extends Iterator<? extends E>> fSuperIterator; /** The current iterator. */ - private Iterator fCurrent; + private Iterator<? extends E> fCurrent; /** The current element. */ - private Object fCurrentElement; + private E fCurrentElement; - public MetaIterator(Iterator iterator) { + public MetaIterator(Iterator<? extends Iterator<? extends E>> iterator) { fSuperIterator= iterator; - fCurrent= (Iterator) fSuperIterator.next(); // there is at least one. + fCurrent= fSuperIterator.next(); // there is at least one. } @Override @@ -215,18 +217,18 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens fCurrentElement= fCurrent.next(); return true; } else if (fSuperIterator.hasNext()) { - fCurrent= (Iterator) fSuperIterator.next(); + fCurrent= fSuperIterator.next(); return hasNext(); } else return false; } @Override - public Object next() { + public E next() { if (!hasNext()) throw new NoSuchElementException(); - Object element= fCurrentElement; + E element= fCurrentElement; fCurrentElement= null; return element; } @@ -256,14 +258,14 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * @deprecated since 3.0 use <code>getAnnotationMap</code> instead */ @Deprecated - protected Map fAnnotations; + protected Map<Annotation, Position> fAnnotations; /** * The map which maps {@link Position} to {@link Annotation}. * @since 3.4 **/ - private IdentityHashMap fPositions; + private IdentityHashMap<Position, Annotation> fPositions; /** The list of annotation model listeners */ - protected ArrayList fAnnotationModelListeners; + protected ArrayList<IAnnotationModelListener> fAnnotationModelListeners; /** The document connected with this model */ protected IDocument fDocument; /** The number of open connections to the same document */ @@ -276,7 +278,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * The model's attachment. * @since 3.0 */ - private Map fAttachments= new HashMap(); + private Map<Object, IAnnotationModel> fAttachments= new HashMap<>(); /** * The annotation model listener on attached sub-models. * @since 3.0 @@ -299,8 +301,8 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens */ public AnnotationModel() { fAnnotations= new AnnotationMap(10); - fPositions= new IdentityHashMap(10); - fAnnotationModelListeners= new ArrayList(2); + fPositions= new IdentityHashMap<>(10); + fAnnotationModelListeners= new ArrayList<>(2); fDocumentListener= new IDocumentListener() { @@ -363,7 +365,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens } @Override - public void replaceAnnotations(Annotation[] annotationsToRemove, Map annotationsToAdd) { + public void replaceAnnotations(Annotation[] annotationsToRemove, Map<? extends Annotation, ? extends Position> annotationsToAdd) { try { replaceAnnotations(annotationsToRemove, annotationsToAdd, true); } catch (BadLocationException x) { @@ -382,7 +384,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * invalid position * @since 3.0 */ - protected void replaceAnnotations(Annotation[] annotationsToRemove, Map annotationsToAdd, boolean fireModelChanged) throws BadLocationException { + protected void replaceAnnotations(Annotation[] annotationsToRemove, Map<? extends Annotation, ? extends Position> annotationsToAdd, boolean fireModelChanged) throws BadLocationException { if (annotationsToRemove != null) { for (int i= 0, length= annotationsToRemove.length; i < length; i++) @@ -390,11 +392,11 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens } if (annotationsToAdd != null) { - Iterator iter= annotationsToAdd.entrySet().iterator(); + Iterator<? extends Entry<? extends Annotation, ? extends Position>> iter= annotationsToAdd.entrySet().iterator(); while (iter.hasNext()) { - Map.Entry mapEntry= (Map.Entry) iter.next(); - Annotation annotation= (Annotation) mapEntry.getKey(); - Position position= (Position) mapEntry.getValue(); + Map.Entry<? extends Annotation, ? extends Position> mapEntry= iter.next(); + Annotation annotation= mapEntry.getKey(); + Position position= mapEntry.getValue(); addAnnotation(annotation, position, false); } } @@ -476,10 +478,10 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens if (fDocument == null) { fDocument= document; - Iterator e= getAnnotationMap().valuesIterator(); + Iterator<Position> e= getAnnotationMap().valuesIterator(); while (e.hasNext()) try { - addPosition(document, (Position) e.next()); + addPosition(document, e.next()); } catch (BadLocationException x) { // ignore invalid position } @@ -491,8 +493,8 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens connected(); } - for (Iterator it= fAttachments.keySet().iterator(); it.hasNext();) { - IAnnotationModel model= (IAnnotationModel) fAttachments.get(it.next()); + for (Iterator<Object> it= fAttachments.keySet().iterator(); it.hasNext();) { + IAnnotationModel model= fAttachments.get(it.next()); model.connect(document); } } @@ -516,8 +518,8 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens Assert.isTrue(fDocument == document); - for (Iterator it= fAttachments.keySet().iterator(); it.hasNext();) { - IAnnotationModel model= (IAnnotationModel) fAttachments.get(it.next()); + for (Iterator<Object> it= fAttachments.keySet().iterator(); it.hasNext();) { + IAnnotationModel model= fAttachments.get(it.next()); model.disconnect(document); } @@ -527,9 +529,9 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens disconnected(); document.removeDocumentListener(fDocumentListener); - Iterator e= getAnnotationMap().valuesIterator(); + Iterator<Position> e= getAnnotationMap().valuesIterator(); while (e.hasNext()) { - Position p= (Position) e.next(); + Position p= e.next(); removePosition(document, p); } fDocument= null; @@ -579,10 +581,10 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens if (event.isEmpty()) return; - ArrayList v= new ArrayList(fAnnotationModelListeners); - Iterator e= v.iterator(); + ArrayList<IAnnotationModelListener> v= new ArrayList<>(fAnnotationModelListeners); + Iterator<IAnnotationModelListener> e= v.iterator(); while (e.hasNext()) { - IAnnotationModelListener l= (IAnnotationModelListener) e.next(); + IAnnotationModelListener l= e.next(); if (l instanceof IAnnotationModelListenerExtension) ((IAnnotationModelListenerExtension) l).modelChanged(event); else if (l != null) @@ -600,11 +602,11 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * @param fireModelChanged indicates whether to notify all model listeners * @param modelInitiated indicates whether this changes has been initiated by this model */ - protected void removeAnnotations(List annotations, boolean fireModelChanged, boolean modelInitiated) { + protected void removeAnnotations(List<? extends Annotation> annotations, boolean fireModelChanged, boolean modelInitiated) { if (annotations.size() > 0) { - Iterator e= annotations.iterator(); + Iterator<? extends Annotation> e= annotations.iterator(); while (e.hasNext()) - removeAnnotation((Annotation) e.next(), false); + removeAnnotation(e.next(), false); if (fireModelChanged) fireModelChanged(); @@ -634,11 +636,11 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens if (fDocumentChanged) { fDocumentChanged= false; - ArrayList deleted= new ArrayList(); - Iterator e= getAnnotationMap().keySetIterator(); + ArrayList<Annotation> deleted= new ArrayList<>(); + Iterator<Annotation> e= getAnnotationMap().keySetIterator(); while (e.hasNext()) { - Annotation a= (Annotation) e.next(); - Position p= (Position) fAnnotations.get(a); + Annotation a= e.next(); + Position p= fAnnotations.get(a); if (p == null || p.isDeleted()) deleted.add(a); } @@ -660,7 +662,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens } @Override - public Iterator getAnnotationIterator() { + public Iterator<Annotation> getAnnotationIterator() { return getAnnotationIterator(true, true); } @@ -670,24 +672,24 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * @since 3.4 */ @Override - public Iterator getAnnotationIterator(int offset, int length, boolean canStartBefore, boolean canEndAfter) { - Iterator regionIterator= getRegionAnnotationIterator(offset, length, canStartBefore, canEndAfter); + public Iterator<Annotation> getAnnotationIterator(int offset, int length, boolean canStartBefore, boolean canEndAfter) { + Iterator<Annotation> regionIterator= getRegionAnnotationIterator(offset, length, canStartBefore, canEndAfter); if (fAttachments.isEmpty()) return regionIterator; - List iterators= new ArrayList(fAttachments.size() + 1); + List<Iterator<Annotation>> iterators= new ArrayList<>(fAttachments.size() + 1); iterators.add(regionIterator); - Iterator it= fAttachments.keySet().iterator(); + Iterator<Object> it= fAttachments.keySet().iterator(); while (it.hasNext()) { - IAnnotationModel attachment= (IAnnotationModel) fAttachments.get(it.next()); + IAnnotationModel attachment= fAttachments.get(it.next()); if (attachment instanceof IAnnotationModelExtension2) iterators.add(((IAnnotationModelExtension2) attachment).getAnnotationIterator(offset, length, canStartBefore, canEndAfter)); else iterators.add(new RegionIterator(attachment.getAnnotationIterator(), attachment, offset, length, canStartBefore, canEndAfter)); } - return new MetaIterator(iterators.iterator()); + return new MetaIterator<>(iterators.iterator()); } /** @@ -701,7 +703,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * @see IAnnotationModelExtension2#getAnnotationIterator(int, int, boolean, boolean) * @since 3.4 */ - private Iterator getRegionAnnotationIterator(int offset, int length, boolean canStartBefore, boolean canEndAfter) { + private Iterator<Annotation> getRegionAnnotationIterator(int offset, int length, boolean canStartBefore, boolean canEndAfter) { if (!(fDocument instanceof AbstractDocument)) return new RegionIterator(getAnnotationIterator(true), this, offset, length, canStartBefore, canEndAfter); @@ -713,7 +715,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens return new AnnotationsInterator(positions, fPositions); } catch (BadPositionCategoryException e) { // can happen if e.g. the document doesn't contain such a category, or when removed in a different thread - return Collections.EMPTY_LIST.iterator(); + return Collections.<Annotation>emptyList().iterator(); } } @@ -728,18 +730,18 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * @return all annotations managed by this model * @since 3.0 */ - private Iterator getAnnotationIterator(boolean cleanup, boolean recurse) { - Iterator iter= getAnnotationIterator(cleanup); + private Iterator<Annotation> getAnnotationIterator(boolean cleanup, boolean recurse) { + Iterator<Annotation> iter= getAnnotationIterator(cleanup); if (!recurse || fAttachments.isEmpty()) return iter; - List iterators= new ArrayList(fAttachments.size() + 1); + List<Iterator<Annotation>> iterators= new ArrayList<>(fAttachments.size() + 1); iterators.add(iter); - Iterator it= fAttachments.keySet().iterator(); + Iterator<Object> it= fAttachments.keySet().iterator(); while (it.hasNext()) - iterators.add(((IAnnotationModel) fAttachments.get(it.next())).getAnnotationIterator()); + iterators.add(fAttachments.get(it.next()).getAnnotationIterator()); - return new MetaIterator(iterators.iterator()); + return new MetaIterator<>(iterators.iterator()); } /** @@ -750,7 +752,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens * @param cleanup indicates whether annotations with deleted associated positions are removed * @return all annotations managed by this model */ - protected Iterator getAnnotationIterator(boolean cleanup) { + protected Iterator<Annotation> getAnnotationIterator(boolean cleanup) { if (cleanup) cleanup(true); @@ -759,13 +761,13 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens @Override public Position getPosition(Annotation annotation) { - Position position= (Position) fAnnotations.get(annotation); + Position position= fAnnotations.get(annotation); if (position != null) return position; - Iterator it= fAttachments.values().iterator(); + Iterator<IAnnotationModel> it= fAttachments.values().iterator(); while (position == null && it.hasNext()) - position= ((IAnnotationModel) it.next()).getPosition(annotation); + position= it.next().getPosition(annotation); return position; } @@ -783,10 +785,10 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens protected void removeAllAnnotations(boolean fireModelChanged) { if (fDocument != null) { - Iterator e= getAnnotationMap().keySetIterator(); + Iterator<Annotation> e= getAnnotationMap().keySetIterator(); while (e.hasNext()) { - Annotation a= (Annotation) e.next(); - Position p= (Position) fAnnotations.get(a); + Annotation a= e.next(); + Position p= fAnnotations.get(a); removePosition(fDocument, p); // p.delete(); synchronized (getLockObject()) { @@ -818,7 +820,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens if (fAnnotations.containsKey(annotation)) { Position p= null; - p= (Position) fAnnotations.get(annotation); + p= fAnnotations.get(annotation); if (fDocument != null) { removePosition(fDocument, p); // p.delete(); @@ -860,7 +862,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens if (position == null) { removeAnnotation(annotation, fireModelChanged); } else { - Position p= (Position) fAnnotations.get(annotation); + Position p= fAnnotations.get(annotation); if (p != null) { if (position.getOffset() != p.getOffset() || position.getLength() != p.getLength()) { @@ -936,7 +938,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens */ @Override public IAnnotationModel getAnnotationModel(Object key) { - return (IAnnotationModel) fAttachments.get(key); + return fAttachments.get(key); } /* @@ -945,7 +947,7 @@ public class AnnotationModel implements IAnnotationModel, IAnnotationModelExtens */ @Override public IAnnotationModel removeAnnotationModel(Object key) { - IAnnotationModel ret= (IAnnotationModel) fAttachments.remove(key); + IAnnotationModel ret= fAttachments.remove(key); if (ret != null) { for (int i= 0; i < fOpenConnections; i++) ret.disconnect(fDocument); diff --git a/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModelEvent.java b/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModelEvent.java index 5c78b1fcbc1..5858b07498f 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModelEvent.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/source/AnnotationModelEvent.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -39,17 +39,17 @@ public class AnnotationModelEvent { * The added annotations. * @since 3.0 */ - private Set fAddedAnnotations= new HashSet(); + private Set<Annotation> fAddedAnnotations= new HashSet<>(); /** * The removed annotations. * @since 3.0 */ - private Map fRemovedAnnotations= new HashMap(); + private Map<Annotation, Position> fRemovedAnnotations= new HashMap<>(); /** * The changed annotations. * @since 3.0 */ - private Set fChangedAnnotations= new HashSet(); + private Set<Annotation> fChangedAnnotations= new HashSet<>(); /** * Indicates that this event does not contain detailed information. * @since 3.0 @@ -165,7 +165,7 @@ public class AnnotationModelEvent { * @since 3.0 */ public Position getPositionOfRemovedAnnotation(Annotation annotation) { - return (Position) fRemovedAnnotations.get(annotation); + return fRemovedAnnotations.get(annotation); } /** diff --git a/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationMap.java b/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationMap.java index 4c73d8045d7..b7f979fae22 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationMap.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationMap.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,6 +17,7 @@ import java.util.Map; import java.util.Set; import org.eclipse.jface.text.ISynchronizable; +import org.eclipse.jface.text.Position; /** @@ -36,21 +37,21 @@ import org.eclipse.jface.text.ISynchronizable; * @see org.eclipse.jface.text.source.IAnnotationModel * @since 3.0 */ -public interface IAnnotationMap extends Map, ISynchronizable { +public interface IAnnotationMap extends Map<Annotation, Position>, ISynchronizable { /** * Returns an iterator for a copy of this annotation map's values. * * @return an iterator for a copy of this map's values */ - Iterator valuesIterator(); + Iterator<Position> valuesIterator(); /** * Returns an iterator for a copy of this map's key set. * * @return an iterator for a copy of this map's key set */ - Iterator keySetIterator(); + Iterator<Annotation> keySetIterator(); /** * {@inheritDoc} @@ -58,7 +59,7 @@ public interface IAnnotationMap extends Map, ISynchronizable { * The returned set is not synchronized on this annotation map's lock object. */ @Override - Set entrySet(); + Set<Entry<Annotation, Position>> entrySet(); /** * {@inheritDoc} @@ -66,7 +67,7 @@ public interface IAnnotationMap extends Map, ISynchronizable { * The returned set is not synchronized on this annotation map's lock object. */ @Override - Set keySet(); + Set<Annotation> keySet(); /** * {@inheritDoc} @@ -74,5 +75,5 @@ public interface IAnnotationMap extends Map, ISynchronizable { * The returned collection is not synchronized on this annotation map's lock object. */ @Override - Collection values(); + Collection<Position> values(); } diff --git a/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModel.java b/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModel.java index 5a813ea187a..2ba27b63048 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModel.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -131,9 +131,9 @@ public interface IAnnotationModel { /** * Returns all annotations managed by this model. * - * @return all annotations managed by this model (element type: {@link Annotation}) + * @return all annotations managed by this model */ - Iterator getAnnotationIterator(); + Iterator<Annotation> getAnnotationIterator(); /** * Returns the position associated with the given annotation. diff --git a/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModelExtension.java b/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModelExtension.java index 6ea5fabd359..e7db30991d4 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModelExtension.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModelExtension.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -75,7 +75,7 @@ public interface IAnnotationModelExtension { * @throws ClassCastException if one of the map key or values has a wrong * type */ - void replaceAnnotations(Annotation[] annotationsToRemove, Map annotationsToAdd) throws ClassCastException; + void replaceAnnotations(Annotation[] annotationsToRemove, Map<? extends Annotation, ? extends Position> annotationsToAdd) throws ClassCastException; /** * Modifies the position associated with the given annotation to equal the diff --git a/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModelExtension2.java b/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModelExtension2.java index 745b479d5db..7533db23214 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModelExtension2.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/source/IAnnotationModelExtension2.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,7 +31,7 @@ public interface IAnnotationModelExtension2 { * which start before the region if they end at or after the region's start * @param canEndAfter if <code>true</code> then annotations are included * which end after the region if they start at or before the region's end - * @return all annotations inside the region managed by this model (element type: {@link Annotation}) + * @return all annotations inside the region managed by this model */ - Iterator getAnnotationIterator(int offset, int length, boolean canStartBefore, boolean canEndAfter); + Iterator<Annotation> getAnnotationIterator(int offset, int length, boolean canStartBefore, boolean canEndAfter); } diff --git a/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateContext.java b/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateContext.java index 6dc5d1abc25..e6a54921d2c 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateContext.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateContext.java @@ -29,7 +29,7 @@ public abstract class TemplateContext { /** The context type of this context */ private final TemplateContextType fContextType; /** Additional variables. */ - private final Map fVariables= new HashMap(); + private final Map<String, String> fVariables= new HashMap<>(); /** A flag to indicate that the context should not be modified. */ private boolean fReadOnly; @@ -87,7 +87,7 @@ public abstract class TemplateContext { * @return returns the value of the variable, <code>null</code> if the variable was not defined */ public String getVariable(String name) { - return (String) fVariables.get(name); + return fVariables.get(name); } /** diff --git a/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateContextType.java b/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateContextType.java index 756df860730..b856c04a240 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateContextType.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateContextType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -48,7 +48,7 @@ public class TemplateContextType { private /* final */ String fId= null; /** Variable resolvers used by this content type. */ - private final Map/*<String, TemplateVariableResolver>*/ fResolvers= new HashMap(); + private final Map<String, TemplateVariableResolver> fResolvers= new HashMap<>(); /** The name of the context type. */ private String fName= null; @@ -172,9 +172,9 @@ public class TemplateContextType { /** * Returns an iterator for the variables known to the context type. * - * @return an iterator over the variables in this context type (element type: {@link TemplateVariableResolver}) + * @return an iterator over the variables in this context type */ - public Iterator resolvers() { + public Iterator<TemplateVariableResolver> resolvers() { return Collections.unmodifiableMap(fResolvers).values().iterator(); } @@ -185,7 +185,7 @@ public class TemplateContextType { * @return a resolver for the given type, or <code>null</code> if none is registered */ protected TemplateVariableResolver getResolver(String type) { - return (TemplateVariableResolver) fResolvers.get(type); + return fResolvers.get(type); } /** @@ -229,8 +229,8 @@ public class TemplateContextType { Assert.isNotNull(context); TemplateVariable[] variables= buffer.getVariables(); - List positions= variablesToPositions(variables); - List edits= new ArrayList(5); + List<RangeMarker> positions= variablesToPositions(variables); + List<ReplaceEdit> edits= new ArrayList<>(5); // iterate over all variables and try to resolve them for (int i= 0; i != variables.length; i++) { @@ -249,8 +249,8 @@ public class TemplateContextType { IDocument document= new Document(buffer.getString()); MultiTextEdit edit= new MultiTextEdit(0, document.getLength()); - edit.addChildren((TextEdit[]) positions.toArray(new TextEdit[positions.size()])); - edit.addChildren((TextEdit[]) edits.toArray(new TextEdit[edits.size()])); + edit.addChildren(positions.toArray(new TextEdit[positions.size()])); + edit.addChildren(edits.toArray(new TextEdit[edits.size()])); edit.apply(document, TextEdit.UPDATE_REGIONS); positionsToVariables(positions, variables); @@ -267,14 +267,14 @@ public class TemplateContextType { */ public void resolve(TemplateVariable variable, TemplateContext context) { String type= variable.getType(); - TemplateVariableResolver resolver= (TemplateVariableResolver) fResolvers.get(type); + TemplateVariableResolver resolver= fResolvers.get(type); if (resolver == null) resolver= new TemplateVariableResolver(type, ""); //$NON-NLS-1$ resolver.resolve(variable, context); } - private static List variablesToPositions(TemplateVariable[] variables) { - List positions= new ArrayList(5); + private static List<RangeMarker> variablesToPositions(TemplateVariable[] variables) { + List<RangeMarker> positions= new ArrayList<>(5); for (int i= 0; i != variables.length; i++) { int[] offsets= variables[i].getOffsets(); for (int j= 0; j != offsets.length; j++) @@ -284,15 +284,15 @@ public class TemplateContextType { return positions; } - private static void positionsToVariables(List positions, TemplateVariable[] variables) { - Iterator iterator= positions.iterator(); + private static void positionsToVariables(List<RangeMarker> positions, TemplateVariable[] variables) { + Iterator<RangeMarker> iterator= positions.iterator(); for (int i= 0; i != variables.length; i++) { TemplateVariable variable= variables[i]; int[] offsets= new int[variable.getOffsets().length]; for (int j= 0; j != offsets.length; j++) - offsets[j]= ((TextEdit) iterator.next()).getOffset(); + offsets[j]= iterator.next().getOffset(); variable.setOffsets(offsets); } diff --git a/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateTranslator.java b/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateTranslator.java index 9cf79156f27..0b74d8481a1 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateTranslator.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateTranslator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -108,7 +108,7 @@ public class TemplateTranslator { * @since 3.3 */ private final class VariableDescription { - final List fOffsets= new ArrayList(5); + final List<Integer> fOffsets= new ArrayList<>(5); final String fName; TemplateVariableType fType; @@ -186,7 +186,7 @@ public class TemplateTranslator { fErrorMessage= null; final StringBuffer buffer= new StringBuffer(string.length()); final Matcher matcher= ESCAPE_PATTERN.matcher(string); - final Map variables= new LinkedHashMap(); + final Map<String, VariableDescription> variables= new LinkedHashMap<>(); int complete= 0; while (matcher.find()) { @@ -227,7 +227,7 @@ public class TemplateTranslator { return new TemplateVariableType(typeName); final Matcher matcher= PARAM_PATTERN.matcher(paramString); - List params= new ArrayList(5); + List<String> params= new ArrayList<>(5); while (matcher.find()) { String argument= matcher.group(); if (argument.charAt(0) == '\'') { @@ -238,7 +238,7 @@ public class TemplateTranslator { params.add(argument); } - return new TemplateVariableType(typeName, (String[]) params.toArray(new String[params.size()])); + return new TemplateVariableType(typeName, params.toArray(new String[params.size()])); } private void fail(String message) throws TemplateException { @@ -258,8 +258,8 @@ public class TemplateTranslator { * @throws TemplateException if merging the type fails * @since 3.3 */ - private void updateOrCreateVariable(Map variables, String name, TemplateVariableType type, int offset) throws TemplateException { - VariableDescription varDesc= (VariableDescription) variables.get(name); + private void updateOrCreateVariable(Map<String, VariableDescription> variables, String name, TemplateVariableType type, int offset) throws TemplateException { + VariableDescription varDesc= variables.get(name); if (varDesc == null) { varDesc= new VariableDescription(name, type); variables.put(name, varDesc); @@ -276,16 +276,16 @@ public class TemplateTranslator { * @return the corresponding variables * @since 3.3 */ - private TemplateVariable[] createVariables(Map variables) { + private TemplateVariable[] createVariables(Map<String, VariableDescription> variables) { TemplateVariable[] result= new TemplateVariable[variables.size()]; int idx= 0; - for (Iterator it= variables.values().iterator(); it.hasNext(); idx++) { - VariableDescription desc= (VariableDescription) it.next(); + for (Iterator<VariableDescription> it= variables.values().iterator(); it.hasNext(); idx++) { + VariableDescription desc= it.next(); TemplateVariableType type= desc.fType == null ? new TemplateVariableType(desc.fName) : desc.fType; int[] offsets= new int[desc.fOffsets.size()]; int i= 0; - for (Iterator intIt= desc.fOffsets.iterator(); intIt.hasNext(); i++) { - Integer offset= (Integer) intIt.next(); + for (Iterator<Integer> intIt= desc.fOffsets.iterator(); intIt.hasNext(); i++) { + Integer offset= intIt.next(); offsets[i]= offset.intValue(); } fCurrentType= type; diff --git a/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateVariableType.java b/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateVariableType.java index e3b705f1354..eaffa9a7db1 100644 --- a/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateVariableType.java +++ b/org.eclipse.text/src/org/eclipse/jface/text/templates/TemplateVariableType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2008 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -30,7 +30,7 @@ public final class TemplateVariableType { /** The name of the type. */ private final String fName; /** The parameter list. */ - private final List fParams; + private final List<String> fParams; TemplateVariableType(String name) { this(name, new String[0]); @@ -40,7 +40,7 @@ public final class TemplateVariableType { Assert.isLegal(name != null); Assert.isLegal(params != null); fName= name; - fParams= Collections.unmodifiableList(new ArrayList(Arrays.asList(params))); + fParams= Collections.unmodifiableList(new ArrayList<>(Arrays.asList(params))); } /** @@ -53,11 +53,11 @@ public final class TemplateVariableType { } /** - * Returns the unmodifiable and possibly empty list of parameters (element type: {@link String}) + * Returns the unmodifiable and possibly empty list of parameters * * @return the list of parameters */ - public List getParams() { + public List<String> getParams() { return fParams; } diff --git a/org.eclipse.text/src/org/eclipse/text/edits/CopySourceEdit.java b/org.eclipse.text/src/org/eclipse/text/edits/CopySourceEdit.java index d6c513c18d6..03daeb57d60 100644 --- a/org.eclipse.text/src/org/eclipse/text/edits/CopySourceEdit.java +++ b/org.eclipse.text/src/org/eclipse/text/edits/CopySourceEdit.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -45,7 +45,7 @@ public final class CopySourceEdit extends TextEdit { private static class PartialCopier extends TextEditVisitor { TextEdit fResult; - List fParents= new ArrayList(); + List<TextEdit> fParents= new ArrayList<>(); TextEdit fCurrentParent; public static TextEdit perform(TextEdit source) { @@ -64,7 +64,7 @@ public final class CopySourceEdit extends TextEdit { } @Override public void postVisit(TextEdit edit) { - fCurrentParent= (TextEdit)fParents.remove(fParents.size() - 1); + fCurrentParent= fParents.remove(fParents.size() - 1); } @Override public boolean visitNode(TextEdit edit) { @@ -220,22 +220,22 @@ public final class CopySourceEdit extends TextEdit { //---- consistency check ---------------------------------------------------- @Override - int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List sourceEdits) { + int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List<List<TextEdit>> sourceEdits) { int result= super.traverseConsistencyCheck(processor, document, sourceEdits); // Since source computation takes place in a recursive fashion (see // performSourceComputation) we only do something if we don't have a // computed source already. if (fSourceContent == null) { if (sourceEdits.size() <= result) { - List list= new ArrayList(); + List<TextEdit> list= new ArrayList<>(); list.add(this); for (int i= sourceEdits.size(); i < result; i++) sourceEdits.add(null); sourceEdits.add(list); } else { - List list= (List)sourceEdits.get(result); + List<TextEdit> list= sourceEdits.get(result); if (list == null) { - list= new ArrayList(); + list= new ArrayList<>(); sourceEdits.add(result, list); } list.add(this); diff --git a/org.eclipse.text/src/org/eclipse/text/edits/CopyTargetEdit.java b/org.eclipse.text/src/org/eclipse/text/edits/CopyTargetEdit.java index 1c6569e3bdb..4eed83d5416 100644 --- a/org.eclipse.text/src/org/eclipse/text/edits/CopyTargetEdit.java +++ b/org.eclipse.text/src/org/eclipse/text/edits/CopyTargetEdit.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -132,7 +132,7 @@ public final class CopyTargetEdit extends TextEdit { * @see TextEdit#traverseConsistencyCheck */ @Override - int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List sourceEdits) { + int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List<List<TextEdit>> sourceEdits) { return super.traverseConsistencyCheck(processor, document, sourceEdits) + 1; } diff --git a/org.eclipse.text/src/org/eclipse/text/edits/MoveSourceEdit.java b/org.eclipse.text/src/org/eclipse/text/edits/MoveSourceEdit.java index 25f56b4010e..f297f2c0fd7 100644 --- a/org.eclipse.text/src/org/eclipse/text/edits/MoveSourceEdit.java +++ b/org.eclipse.text/src/org/eclipse/text/edits/MoveSourceEdit.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -183,22 +183,22 @@ public final class MoveSourceEdit extends TextEdit { //---- consistency check ---------------------------------------------------------------- @Override - int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List sourceEdits) { + int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List<List<TextEdit>> sourceEdits) { int result= super.traverseConsistencyCheck(processor, document, sourceEdits); // Since source computation takes place in a recursive fashion (see // performSourceComputation) we only do something if we don't have a // computed source already. if (fSourceContent == null) { if (sourceEdits.size() <= result) { - List list= new ArrayList(); + List<TextEdit> list= new ArrayList<>(); list.add(this); for (int i= sourceEdits.size(); i < result; i++) sourceEdits.add(null); sourceEdits.add(list); } else { - List list= (List)sourceEdits.get(result); + List<TextEdit> list= sourceEdits.get(result); if (list == null) { - list= new ArrayList(); + list= new ArrayList<>(); sourceEdits.add(result, list); } list.add(this); @@ -292,9 +292,9 @@ public final class MoveSourceEdit extends TextEdit { private void applyTransformation(IDocument document, int style) throws MalformedTreeException { if ((style & TextEdit.UPDATE_REGIONS) != 0 && fSourceRoot != null) { - Map editMap= new HashMap(); + Map<TextEdit, TextEdit> editMap= new HashMap<>(); TextEdit newEdit= createEdit(editMap); - List replaces= new ArrayList(Arrays.asList(fModifier.getModifications(document.get()))); + List<ReplaceEdit> replaces= new ArrayList<>(Arrays.asList(fModifier.getModifications(document.get()))); insertEdits(newEdit, replaces); try { newEdit.apply(document, style); @@ -316,14 +316,14 @@ public final class MoveSourceEdit extends TextEdit { } } - private TextEdit createEdit(Map editMap) { + private TextEdit createEdit(Map<TextEdit, TextEdit> editMap) { MultiTextEdit result= new MultiTextEdit(0, fSourceRoot.getLength()); editMap.put(result, fSourceRoot); createEdit(fSourceRoot, result, editMap); return result; } - private static void createEdit(TextEdit source, TextEdit target, Map editMap) { + private static void createEdit(TextEdit source, TextEdit target, Map<TextEdit, TextEdit> editMap) { TextEdit[] children= source.getChildren(); for (int i= 0; i < children.length; i++) { TextEdit child= children[i]; @@ -338,13 +338,13 @@ public final class MoveSourceEdit extends TextEdit { } } - private void insertEdits(TextEdit root, List edits) { + private void insertEdits(TextEdit root, List<ReplaceEdit> edits) { while(edits.size() > 0) { - ReplaceEdit edit= (ReplaceEdit)edits.remove(0); + ReplaceEdit edit= edits.remove(0); insert(root, edit, edits); } } - private static void insert(TextEdit parent, ReplaceEdit edit, List edits) { + private static void insert(TextEdit parent, ReplaceEdit edit, List<ReplaceEdit> edits) { if (!parent.hasChildren()) { parent.addChild(edit); return; @@ -419,10 +419,10 @@ public final class MoveSourceEdit extends TextEdit { return result; } - private static void restorePositions(Map editMap) { - for (Iterator iter= editMap.keySet().iterator(); iter.hasNext();) { - TextEdit marker= (TextEdit)iter.next(); - TextEdit edit= (TextEdit)editMap.get(marker); + private static void restorePositions(Map<TextEdit, TextEdit> editMap) { + for (Iterator<TextEdit> iter= editMap.keySet().iterator(); iter.hasNext();) { + TextEdit marker= iter.next(); + TextEdit edit= editMap.get(marker); if (marker.isDeleted()) { edit.markAsDeleted(); } else { diff --git a/org.eclipse.text/src/org/eclipse/text/edits/MoveTargetEdit.java b/org.eclipse.text/src/org/eclipse/text/edits/MoveTargetEdit.java index 1815ca28545..3efb0064ad2 100644 --- a/org.eclipse.text/src/org/eclipse/text/edits/MoveTargetEdit.java +++ b/org.eclipse.text/src/org/eclipse/text/edits/MoveTargetEdit.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2006 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -133,7 +133,7 @@ public final class MoveTargetEdit extends TextEdit { * @see TextEdit#traverseConsistencyCheck */ @Override - int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List sourceEdits) { + int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List<List<TextEdit>> sourceEdits) { return super.traverseConsistencyCheck(processor, document, sourceEdits) + 1; } @@ -163,7 +163,7 @@ public final class MoveTargetEdit extends TextEdit { if (sourceRoot != null) { sourceRoot.internalMoveTree(getOffset()); TextEdit[] sourceChildren= sourceRoot.removeChildren(); - List children= new ArrayList(sourceChildren.length); + List<TextEdit> children= new ArrayList<>(sourceChildren.length); for (int i= 0; i < sourceChildren.length; i++) { TextEdit child= sourceChildren[i]; child.internalSetParent(this); diff --git a/org.eclipse.text/src/org/eclipse/text/edits/MultiTextEdit.java b/org.eclipse.text/src/org/eclipse/text/edits/MultiTextEdit.java index c1dcb81f555..9ace8e96880 100644 --- a/org.eclipse.text/src/org/eclipse/text/edits/MultiTextEdit.java +++ b/org.eclipse.text/src/org/eclipse/text/edits/MultiTextEdit.java @@ -98,11 +98,11 @@ public class MultiTextEdit extends TextEdit { if (fDefined) return super.getOffset(); - List/*<TextEdit>*/ children= internalGetChildren(); + List<TextEdit> children= internalGetChildren(); if (children == null || children.size() == 0) return 0; // the children are already sorted - return ((TextEdit)children.get(0)).getOffset(); + return children.get(0).getOffset(); } @Override @@ -110,12 +110,12 @@ public class MultiTextEdit extends TextEdit { if (fDefined) return super.getLength(); - List/*<TextEdit>*/ children= internalGetChildren(); + List<TextEdit> children= internalGetChildren(); if (children == null || children.size() == 0) return 0; // the children are already sorted - TextEdit first= (TextEdit)children.get(0); - TextEdit last= (TextEdit)children.get(children.size() - 1); + TextEdit first= children.get(0); + TextEdit last= children.get(children.size() - 1); return last.getOffset() - first.getOffset() + last.getLength(); } diff --git a/org.eclipse.text/src/org/eclipse/text/edits/TextEdit.java b/org.eclipse.text/src/org/eclipse/text/edits/TextEdit.java index b3aba990a9c..4806d620d8e 100644 --- a/org.eclipse.text/src/org/eclipse/text/edits/TextEdit.java +++ b/org.eclipse.text/src/org/eclipse/text/edits/TextEdit.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -98,12 +98,9 @@ public abstract class TextEdit { */ public static final int UPDATE_REGIONS= 1 << 1; - private static class InsertionComparator implements Comparator { + private static class InsertionComparator implements Comparator<TextEdit> { @Override - public int compare(Object o1, Object o2) throws MalformedTreeException { - TextEdit edit1= (TextEdit)o1; - TextEdit edit2= (TextEdit)o2; - + public int compare(TextEdit edit1, TextEdit edit2) throws MalformedTreeException { int offset1= edit1.getOffset(); int length1= edit1.getLength(); @@ -134,7 +131,7 @@ public abstract class TextEdit { private int fLength; private TextEdit fParent; - private List fChildren; + private List<TextEdit> fChildren; int fDelta; @@ -365,7 +362,7 @@ public abstract class TextEdit { public final TextEdit removeChild(int index) { if (fChildren == null) throw new IndexOutOfBoundsException("Index: " + index + " Size: 0"); //$NON-NLS-1$//$NON-NLS-2$ - TextEdit result= (TextEdit)fChildren.remove(index); + TextEdit result= fChildren.remove(index); result.internalSetParent(null); if (fChildren.isEmpty()) fChildren= null; @@ -405,7 +402,7 @@ public abstract class TextEdit { int size= fChildren.size(); TextEdit[] result= new TextEdit[size]; for (int i= 0; i < size; i++) { - result[i]= (TextEdit)fChildren.get(i); + result[i]= fChildren.get(i); result[i].internalSetParent(null); } fChildren= null; @@ -432,7 +429,7 @@ public abstract class TextEdit { public final TextEdit[] getChildren() { if (fChildren == null) return EMPTY_ARRAY; - return (TextEdit[])fChildren.toArray(new TextEdit[fChildren.size()]); + return fChildren.toArray(new TextEdit[fChildren.size()]); } /** @@ -566,8 +563,8 @@ public abstract class TextEdit { private void toStringWithChildren(StringBuffer buffer, int indent) { internalToString(buffer, indent); if (fChildren != null) { - for (Iterator iterator= fChildren.iterator(); iterator.hasNext();) { - TextEdit child= (TextEdit) iterator.next(); + for (Iterator<TextEdit> iterator= fChildren.iterator(); iterator.hasNext();) { + TextEdit child= iterator.next(); buffer.append('\n'); child.toStringWithChildren(buffer, indent + 1); } @@ -676,9 +673,9 @@ public abstract class TextEdit { protected final void acceptChildren(TextEditVisitor visitor) { if (fChildren == null) return; - Iterator iterator= fChildren.iterator(); + Iterator<TextEdit> iterator= fChildren.iterator(); while (iterator.hasNext()) { - TextEdit curr= (TextEdit) iterator.next(); + TextEdit curr= iterator.next(); curr.accept(visitor); } } @@ -762,11 +759,11 @@ public abstract class TextEdit { fLength= length; } - List internalGetChildren() { + List<TextEdit> internalGetChildren() { return fChildren; } - void internalSetChildren(List children) { + void internalSetChildren(List<TextEdit> children) { fChildren= children; } @@ -777,7 +774,7 @@ public abstract class TextEdit { if (!covers(child)) throw new MalformedTreeException(this, child, TextEditMessages.getString("TextEdit.range_outside")); //$NON-NLS-1$ if (fChildren == null) { - fChildren= new ArrayList(2); + fChildren= new ArrayList<>(2); } int index= computeInsertionIndex(child); fChildren.add(index, child); @@ -789,7 +786,7 @@ public abstract class TextEdit { if (size == 0) return 0; int lastIndex= size - 1; - TextEdit last= (TextEdit)fChildren.get(lastIndex); + TextEdit last= fChildren.get(lastIndex); if (last.getExclusiveEnd() <= edit.getOffset()) return size; try { @@ -862,11 +859,11 @@ public abstract class TextEdit { * * @return the number of indirect move or copy target edit children */ - int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List sourceEdits) { + int traverseConsistencyCheck(TextEditProcessor processor, IDocument document, List<List<TextEdit>> sourceEdits) { int result= 0; if (fChildren != null) { for (int i= fChildren.size() - 1; i >= 0; i--) { - TextEdit child= (TextEdit)fChildren.get(i); + TextEdit child= fChildren.get(i); result= Math.max(result, child.traverseConsistencyCheck(processor, document, sourceEdits)); } } @@ -907,7 +904,7 @@ public abstract class TextEdit { int delta= 0; if (fChildren != null) { for (int i= fChildren.size() - 1; i >= 0; i--) { - TextEdit child= (TextEdit)fChildren.get(i); + TextEdit child= fChildren.get(i); delta+= child.traverseDocumentUpdating(processor, document); childDocumentUpdated(); } @@ -942,8 +939,8 @@ public abstract class TextEdit { performRegionUpdating(accumulatedDelta, delete); if (fChildren != null) { boolean childDelete= delete || deleteChildren(); - for (Iterator iter= fChildren.iterator(); iter.hasNext();) { - TextEdit child= (TextEdit)iter.next(); + for (Iterator<TextEdit> iter= fChildren.iterator(); iter.hasNext();) { + TextEdit child= iter.next(); accumulatedDelta= child.traverseRegionUpdating(processor, document, accumulatedDelta, childDelete); childRegionUpdated(); } @@ -978,8 +975,8 @@ public abstract class TextEdit { void internalMoveTree(int delta) { adjustOffset(delta); if (fChildren != null) { - for (Iterator iter= fChildren.iterator(); iter.hasNext();) { - ((TextEdit)iter.next()).internalMoveTree(delta); + for (Iterator<TextEdit> iter= fChildren.iterator(); iter.hasNext();) { + iter.next().internalMoveTree(delta); } } } @@ -987,8 +984,8 @@ public abstract class TextEdit { void deleteTree() { markAsDeleted(); if (fChildren != null) { - for (Iterator iter= fChildren.iterator(); iter.hasNext();) { - TextEdit child= (TextEdit)iter.next(); + for (Iterator<TextEdit> iter= fChildren.iterator(); iter.hasNext();) { + TextEdit child= iter.next(); child.deleteTree(); } } diff --git a/org.eclipse.text/src/org/eclipse/text/edits/TextEditCopier.java b/org.eclipse.text/src/org/eclipse/text/edits/TextEditCopier.java index 002b7fe79ed..eea20c07749 100644 --- a/org.eclipse.text/src/org/eclipse/text/edits/TextEditCopier.java +++ b/org.eclipse.text/src/org/eclipse/text/edits/TextEditCopier.java @@ -29,7 +29,7 @@ import org.eclipse.core.runtime.Assert; public final class TextEditCopier { private TextEdit fEdit; - private Map fCopies; + private Map<TextEdit, TextEdit> fCopies; /** * Constructs a new <code>TextEditCopier</code> for the @@ -44,7 +44,7 @@ public final class TextEditCopier { super(); Assert.isNotNull(edit); fEdit= edit; - fCopies= new HashMap(); + fCopies= new HashMap<>(); } /** @@ -55,8 +55,8 @@ public final class TextEditCopier { public TextEdit perform() { TextEdit result= doCopy(fEdit); if (result != null) { - for (Iterator iter= fCopies.keySet().iterator(); iter.hasNext();) { - TextEdit edit= (TextEdit)iter.next(); + for (Iterator<TextEdit> iter= fCopies.keySet().iterator(); iter.hasNext();) { + TextEdit edit= iter.next(); edit.postProcessCopy(this); } } @@ -73,18 +73,18 @@ public final class TextEditCopier { */ public TextEdit getCopy(TextEdit original) { Assert.isNotNull(original); - return (TextEdit)fCopies.get(original); + return fCopies.get(original); } //---- helper methods -------------------------------------------- private TextEdit doCopy(TextEdit edit) { TextEdit result= edit.doCopy(); - List children= edit.internalGetChildren(); + List<TextEdit> children= edit.internalGetChildren(); if (children != null) { - List newChildren= new ArrayList(children.size()); - for (Iterator iter= children.iterator(); iter.hasNext();) { - TextEdit childCopy= doCopy((TextEdit)iter.next()); + List<TextEdit> newChildren= new ArrayList<>(children.size()); + for (Iterator<TextEdit> iter= children.iterator(); iter.hasNext();) { + TextEdit childCopy= doCopy(iter.next()); childCopy.internalSetParent(result); newChildren.add(childCopy); } diff --git a/org.eclipse.text/src/org/eclipse/text/edits/TextEditGroup.java b/org.eclipse.text/src/org/eclipse/text/edits/TextEditGroup.java index 4ad9cae9ca3..1442dbe00ae 100644 --- a/org.eclipse.text/src/org/eclipse/text/edits/TextEditGroup.java +++ b/org.eclipse.text/src/org/eclipse/text/edits/TextEditGroup.java @@ -34,7 +34,7 @@ import org.eclipse.jface.text.IRegion; public class TextEditGroup { private String fDescription; - private List fEdits; + private List<TextEdit> fEdits; /** * Creates a new text edit group with the given name. @@ -46,7 +46,7 @@ public class TextEditGroup { super(); Assert.isNotNull(name); fDescription= name; - fEdits= new ArrayList(3); + fEdits= new ArrayList<>(3); } /** @@ -61,7 +61,7 @@ public class TextEditGroup { Assert.isNotNull(name); Assert.isNotNull(edit); fDescription= name; - fEdits= new ArrayList(1); + fEdits= new ArrayList<>(1); fEdits.add(edit); } @@ -78,7 +78,7 @@ public class TextEditGroup { Assert.isNotNull(name); Assert.isNotNull(edits); fDescription= name; - fEdits= new ArrayList(Arrays.asList(edits)); + fEdits= new ArrayList<>(Arrays.asList(edits)); } /** @@ -140,7 +140,7 @@ public class TextEditGroup { * @return the managed text edits */ public TextEdit[] getTextEdits() { - return (TextEdit[]) fEdits.toArray(new TextEdit[fEdits.size()]); + return fEdits.toArray(new TextEdit[fEdits.size()]); } /** @@ -156,9 +156,9 @@ public class TextEditGroup { if (size == 0) { return null; } else if (size == 1) { - return ((TextEdit)fEdits.get(0)).getRegion(); + return fEdits.get(0).getRegion(); } else { - return TextEdit.getCoverage((TextEdit[])fEdits.toArray(new TextEdit[fEdits.size()])); + return TextEdit.getCoverage(fEdits.toArray(new TextEdit[fEdits.size()])); } } } diff --git a/org.eclipse.text/src/org/eclipse/text/edits/TextEditProcessor.java b/org.eclipse.text/src/org/eclipse/text/edits/TextEditProcessor.java index 77e29af6a44..73c7e6dd01f 100644 --- a/org.eclipse.text/src/org/eclipse/text/edits/TextEditProcessor.java +++ b/org.eclipse.text/src/org/eclipse/text/edits/TextEditProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -40,7 +40,7 @@ public class TextEditProcessor { private boolean fChecked; private MalformedTreeException fException; - private List fSourceEdits; + private List<List<TextEdit>> fSourceEdits; /** * Constructs a new edit processor for the given @@ -69,7 +69,7 @@ public class TextEditProcessor { fStyle= style; if (secondary) { fChecked= true; - fSourceEdits= new ArrayList(); + fSourceEdits= new ArrayList<>(); } } @@ -172,7 +172,7 @@ public class TextEditProcessor { //---- checking -------------------------------------------------------------------- void checkIntegrityDo() throws MalformedTreeException { - fSourceEdits= new ArrayList(); + fSourceEdits= new ArrayList<>(); fRoot.traverseConsistencyCheck(this, fDocument, fSourceEdits); if (fRoot.getExclusiveEnd() > fDocument.getLength()) throw new MalformedTreeException(null, fRoot, TextEditMessages.getString("TextEditProcessor.invalid_length")); //$NON-NLS-1$ @@ -202,11 +202,11 @@ public class TextEditProcessor { } private void computeSources() { - for (Iterator iter= fSourceEdits.iterator(); iter.hasNext();) { - List list= (List)iter.next(); + for (Iterator<List<TextEdit>> iter= fSourceEdits.iterator(); iter.hasNext();) { + List<TextEdit> list= iter.next(); if (list != null) { - for (Iterator edits= list.iterator(); edits.hasNext();) { - TextEdit edit= (TextEdit)edits.next(); + for (Iterator<TextEdit> edits= list.iterator(); edits.hasNext();) { + TextEdit edit= edits.next(); edit.traverseSourceComputation(this, fDocument); } } diff --git a/org.eclipse.text/src/org/eclipse/text/edits/UndoEdit.java b/org.eclipse.text/src/org/eclipse/text/edits/UndoEdit.java index 57601327cab..663a9c4c328 100644 --- a/org.eclipse.text/src/org/eclipse/text/edits/UndoEdit.java +++ b/org.eclipse.text/src/org/eclipse/text/edits/UndoEdit.java @@ -85,9 +85,9 @@ public final class UndoEdit extends TextEdit { } void add(ReplaceEdit edit) { - List children= internalGetChildren(); + List<TextEdit> children= internalGetChildren(); if (children == null) { - children= new ArrayList(2); + children= new ArrayList<>(2); internalSetChildren(children); } children.add(edit); diff --git a/org.eclipse.text/src/org/eclipse/text/undo/DocumentUndoManager.java b/org.eclipse.text/src/org/eclipse/text/undo/DocumentUndoManager.java index 7f15f60f664..4ead31215b1 100644 --- a/org.eclipse.text/src/org/eclipse/text/undo/DocumentUndoManager.java +++ b/org.eclipse.text/src/org/eclipse/text/undo/DocumentUndoManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2009 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -422,7 +422,7 @@ public class DocumentUndoManager implements IDocumentUndoManager { private static class UndoableCompoundTextChange extends UndoableTextChange { /** The list of individual changes */ - private List fChanges= new ArrayList(); + private List<UndoableTextChange> fChanges= new ArrayList<>(); /** * Creates a new compound text change. @@ -449,11 +449,11 @@ public class DocumentUndoManager implements IDocumentUndoManager { if (size > 0) { UndoableTextChange c; - c= (UndoableTextChange) fChanges.get(0); + c= fChanges.get(0); fDocumentUndoManager.fireDocumentUndo(c.fStart, c.fPreservedText, c.fText, uiInfo, DocumentUndoEvent.ABOUT_TO_UNDO, true); for (int i= size - 1; i >= 0; --i) { - c= (UndoableTextChange) fChanges.get(i); + c= fChanges.get(i); c.undoTextChange(); } fDocumentUndoManager.resetProcessChangeState(); @@ -470,11 +470,11 @@ public class DocumentUndoManager implements IDocumentUndoManager { if (size > 0) { UndoableTextChange c; - c= (UndoableTextChange) fChanges.get(size - 1); + c= fChanges.get(size - 1); fDocumentUndoManager.fireDocumentUndo(c.fStart, c.fText, c.fPreservedText, uiInfo, DocumentUndoEvent.ABOUT_TO_REDO, true); for (int i= 0; i <= size - 1; ++i) { - c= (UndoableTextChange) fChanges.get(i); + c= fChanges.get(i); c.redoTextChange(); } fDocumentUndoManager.resetProcessChangeState(); @@ -532,7 +532,7 @@ public class DocumentUndoManager implements IDocumentUndoManager { if (fStart > -1) return super.getUndoModificationStamp(); else if (fChanges.size() > 0) - return ((UndoableTextChange) fChanges.get(0)) + return fChanges.get(0) .getUndoModificationStamp(); return fUndoModificationStamp; @@ -543,7 +543,7 @@ public class DocumentUndoManager implements IDocumentUndoManager { if (fStart > -1) return super.getRedoModificationStamp(); else if (fChanges.size() > 0) - return ((UndoableTextChange) fChanges.get(fChanges.size() - 1)) + return fChanges.get(fChanges.size() - 1) .getRedoModificationStamp(); return fRedoModificationStamp; @@ -738,7 +738,7 @@ public class DocumentUndoManager implements IDocumentUndoManager { private ListenerList fDocumentUndoListeners; /** The list of clients connected. */ - private List fConnected; + private List<Object> fConnected; /** * @@ -752,7 +752,7 @@ public class DocumentUndoManager implements IDocumentUndoManager { fDocument= document; fHistory= OperationHistoryFactory.getOperationHistory(); fUndoContext= new ObjectUndoContext(fDocument); - fConnected= new ArrayList(); + fConnected= new ArrayList<>(); fDocumentUndoListeners= new ListenerList(ListenerList.IDENTITY); } diff --git a/org.eclipse.text/src/org/eclipse/text/undo/DocumentUndoManagerRegistry.java b/org.eclipse.text/src/org/eclipse/text/undo/DocumentUndoManagerRegistry.java index 5a1cf42cc36..5879f4d58b6 100644 --- a/org.eclipse.text/src/org/eclipse/text/undo/DocumentUndoManagerRegistry.java +++ b/org.eclipse.text/src/org/eclipse/text/undo/DocumentUndoManagerRegistry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -44,7 +44,7 @@ public final class DocumentUndoManagerRegistry { private IDocumentUndoManager undoManager; } - private static Map fgFactory= new HashMap(); + private static Map<IDocument, Record> fgFactory= new HashMap<>(); private DocumentUndoManagerRegistry() { // Do not instantiate @@ -62,7 +62,7 @@ public final class DocumentUndoManagerRegistry { */ public static synchronized void connect(IDocument document) { Assert.isNotNull(document); - Record record= (Record)fgFactory.get(document); + Record record= fgFactory.get(document); if (record == null) { record= new Record(document); fgFactory.put(document, record); @@ -77,7 +77,7 @@ public final class DocumentUndoManagerRegistry { */ public static synchronized void disconnect(IDocument document) { Assert.isNotNull(document); - Record record= (Record)fgFactory.get(document); + Record record= fgFactory.get(document); record.count--; if (record.count == 0) fgFactory.remove(document); @@ -99,7 +99,7 @@ public final class DocumentUndoManagerRegistry { */ public static synchronized IDocumentUndoManager getDocumentUndoManager(IDocument document) { Assert.isNotNull(document); - Record record= (Record)fgFactory.get(document); + Record record= fgFactory.get(document); if (record == null) return null; return record.undoManager; diff --git a/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/ChainedPreferenceStoreTest.java b/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/ChainedPreferenceStoreTest.java index 8ddf3d09acc..77f822e8db3 100644 --- a/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/ChainedPreferenceStoreTest.java +++ b/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/ChainedPreferenceStoreTest.java @@ -35,7 +35,7 @@ public class ChainedPreferenceStoreTest extends TestCase { } } - private List fEvents= new ArrayList(); + private List<PropertyChangeEvent> fEvents= new ArrayList<>(); private PropertyChangeListener fPropertyChangeListener= new PropertyChangeListener(); private static final String PROPERTY= "some.property"; @@ -62,7 +62,7 @@ public class ChainedPreferenceStoreTest extends TestCase { chainedStore.removePropertyChangeListener(fPropertyChangeListener); assertEquals(1, fEvents.size()); - PropertyChangeEvent event= (PropertyChangeEvent) fEvents.get(0); + PropertyChangeEvent event= fEvents.get(0); assertEquals(chainedStore, event.getSource()); assertEquals(PROPERTY, event.getProperty()); assertEquals(VALUE, event.getOldValue()); @@ -83,7 +83,7 @@ public class ChainedPreferenceStoreTest extends TestCase { chainedStore.removePropertyChangeListener(fPropertyChangeListener); assertEquals(1, fEvents.size()); - PropertyChangeEvent event= (PropertyChangeEvent) fEvents.get(0); + PropertyChangeEvent event= fEvents.get(0); assertEquals(store1, event.getSource()); assertEquals(PROPERTY, event.getProperty()); assertEquals(VALUE, event.getOldValue()); @@ -104,7 +104,7 @@ public class ChainedPreferenceStoreTest extends TestCase { chainedStore.removePropertyChangeListener(fPropertyChangeListener); assertEquals(1, fEvents.size()); - PropertyChangeEvent event= (PropertyChangeEvent) fEvents.get(0); + PropertyChangeEvent event= fEvents.get(0); assertEquals(store1, event.getSource()); assertEquals(PROPERTY, event.getProperty()); assertEquals(DEFAULT_VALUE, event.getOldValue()); @@ -125,7 +125,7 @@ public class ChainedPreferenceStoreTest extends TestCase { chainedStore.removePropertyChangeListener(fPropertyChangeListener); assertEquals(1, fEvents.size()); - PropertyChangeEvent event= (PropertyChangeEvent) fEvents.get(0); + PropertyChangeEvent event= fEvents.get(0); assertEquals(chainedStore, event.getSource()); assertEquals(PROPERTY, event.getProperty()); assertEquals(null, event.getOldValue()); diff --git a/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/MarkerAnnotationOrderTest.java b/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/MarkerAnnotationOrderTest.java index 6820ccc2467..1da066152c9 100644 --- a/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/MarkerAnnotationOrderTest.java +++ b/org.eclipse.ui.editors.tests/src/org/eclipse/ui/editors/tests/MarkerAnnotationOrderTest.java @@ -83,7 +83,7 @@ public class MarkerAnnotationOrderTest extends TestCase { } public void testDirectDependency() { - final ArrayList list= new ArrayList(2); + final ArrayList<IStatus> list= new ArrayList<>(2); Bundle bundle= Platform.getBundle(EditorsUI.PLUGIN_ID); ILog log= Platform.getLog(bundle); log.addLogListener(new ILogListener() { diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/EncodingActionGroup.java b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/EncodingActionGroup.java index 7499d06370a..f99f3d1c685 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/EncodingActionGroup.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/EncodingActionGroup.java @@ -326,7 +326,7 @@ public class EncodingActionGroup extends ActionGroup { /** List of encoding actions of this group. */ - private List fRetargetActions= new ArrayList(); + private List<RetargetTextEditorAction> fRetargetActions= new ArrayList<>(); /** * Creates a new encoding action group for an action bar contributor. @@ -357,11 +357,11 @@ public class EncodingActionGroup extends ActionGroup { } }); - Iterator e= fRetargetActions.iterator(); - subMenu.add((IAction) e.next()); + Iterator<RetargetTextEditorAction> e= fRetargetActions.iterator(); + subMenu.add(e.next()); subMenu.add(new Separator()); while (e.hasNext()) - subMenu.add((IAction) e.next()); + subMenu.add(e.next()); editMenu.add(subMenu); } @@ -374,9 +374,9 @@ public class EncodingActionGroup extends ActionGroup { */ public void retarget(ITextEditor editor) { fTextEditor= editor; - Iterator e= fRetargetActions.iterator(); + Iterator<RetargetTextEditorAction> e= fRetargetActions.iterator(); while (e.hasNext()) { - RetargetTextEditorAction a= (RetargetTextEditorAction) e.next(); + RetargetTextEditorAction a= e.next(); a.setAction(editor == null ? null : editor.getAction(a.getId())); } } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/FileBufferOperationAction.java b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/FileBufferOperationAction.java index 598ecb548f7..0efd803137f 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/FileBufferOperationAction.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/FileBufferOperationAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -55,7 +55,7 @@ import org.eclipse.ui.PlatformUI; */ public class FileBufferOperationAction extends Action implements IWorkbenchWindowActionDelegate { - private Set fResources; + private Set<Object> fResources; private IPath fLocation; private IWorkbenchWindow fWindow; protected IFileBufferOperation fFileBufferOperation; @@ -80,13 +80,13 @@ public class FileBufferOperationAction extends Action implements IWorkbenchWindo @Override public void selectionChanged(IAction action, ISelection selection) { - fResources= new HashSet(); + fResources= new HashSet<>(); fLocation= null; if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection= (IStructuredSelection) selection; - Iterator e= structuredSelection.iterator(); + Iterator<?> e= structuredSelection.iterator(); while (e.hasNext()) { Object element= e.next(); if (element instanceof IResource) @@ -139,7 +139,7 @@ public class FileBufferOperationAction extends Action implements IWorkbenchWindo @Override public void run(IAction action) { if (fResources != null && !fResources.isEmpty()) { - IFile[] files= collectFiles((IResource[]) fResources.toArray(new IResource[fResources.size()])); + IFile[] files= collectFiles(fResources.toArray(new IResource[fResources.size()])); if (files != null && files.length > 0) doRun(files, null, fFileBufferOperation); } else if (isAcceptableLocation(fLocation)) @@ -154,13 +154,13 @@ public class FileBufferOperationAction extends Action implements IWorkbenchWindo * @return the files to process, can be <code>null</code> */ protected IFile[] collectFiles(IResource[] resources) { - Set files= new HashSet(); + Set<IResource> files= new HashSet<>(); for (int i= 0; i < resources.length; i++) { IResource resource= resources[i]; if ((IResource.FILE & resource.getType()) > 0) files.add(resource); } - return (IFile[]) files.toArray(new IFile[files.size()]); + return files.toArray(new IFile[files.size()]); } protected final void doRun(final IFile[] files, final IPath location, final IFileBufferOperation fileBufferOperation) { @@ -206,14 +206,14 @@ public class FileBufferOperationAction extends Action implements IWorkbenchWindo protected final IPath[] generateLocations(IFile[] files, IProgressMonitor progressMonitor) { progressMonitor.beginTask(TextEditorMessages.FileBufferOperationAction_collectionFiles_label, files.length); try { - Set locations= new HashSet(); + Set<IPath> locations= new HashSet<>(); for (int i= 0; i < files.length; i++) { IPath fullPath= files[i].getFullPath(); if (isAcceptableLocation(fullPath)) locations.add(fullPath); progressMonitor.worked(1); } - return (IPath[]) locations.toArray(new IPath[locations.size()]); + return locations.toArray(new IPath[locations.size()]); } finally { progressMonitor.done(); diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/FileBufferOperationHandler.java b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/FileBufferOperationHandler.java index 24ec9c2fe76..63ee227c408 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/FileBufferOperationHandler.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/FileBufferOperationHandler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -100,9 +100,9 @@ public class FileBufferOperationHandler extends AbstractHandler { ISelection selection= getSelection(); if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection= (IStructuredSelection) selection; - ArrayList resources= new ArrayList(structuredSelection.size()); + ArrayList<Object> resources= new ArrayList<>(structuredSelection.size()); - Iterator e= structuredSelection.iterator(); + Iterator<?> e= structuredSelection.iterator(); while (e.hasNext()) { Object element= e.next(); if (element instanceof IResource) @@ -116,7 +116,7 @@ public class FileBufferOperationHandler extends AbstractHandler { } if (!resources.isEmpty()) - fResources= (IResource[]) resources.toArray(new IResource[resources.size()]); + fResources= resources.toArray(new IResource[resources.size()]); } else if (selection instanceof ITextSelection) { IWorkbenchWindow window= getWorkbenchWindow(); @@ -170,13 +170,13 @@ public class FileBufferOperationHandler extends AbstractHandler { * @return an array of files */ protected IFile[] collectFiles(IResource[] resources) { - Set files= new HashSet(); + Set<IResource> files= new HashSet<>(); for (int i= 0; i < resources.length; i++) { IResource resource= resources[i]; if ((IResource.FILE & resource.getType()) > 0) files.add(resource); } - return (IFile[]) files.toArray(new IFile[files.size()]); + return files.toArray(new IFile[files.size()]); } /** @@ -246,14 +246,14 @@ public class FileBufferOperationHandler extends AbstractHandler { protected final IPath[] generateLocations(IFile[] files, IProgressMonitor progressMonitor) { progressMonitor.beginTask(TextEditorMessages.FileBufferOperationHandler_collectionFiles_label, files.length); try { - Set locations= new HashSet(); + Set<IPath> locations= new HashSet<>(); for (int i= 0; i < files.length; i++) { IPath fullPath= files[i].getFullPath(); if (isAcceptableLocation(fullPath)) locations.add(fullPath); progressMonitor.worked(1); } - return (IPath[]) locations.toArray(new IPath[locations.size()]); + return locations.toArray(new IPath[locations.size()]); } finally { progressMonitor.done(); diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextEditor.java b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextEditor.java index 7493d9094b8..470773e6b23 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextEditor.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -152,10 +152,11 @@ public class TextEditor extends AbstractDecoratedTextEditor { fEncodingSupport.reset(); } + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Class adapter) { + public <T> T getAdapter(Class<T> adapter) { if (IEncodingSupport.class.equals(adapter)) - return fEncodingSupport; + return (T) fEncodingSupport; return super.getAdapter(adapter); } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextFileDocumentProvider.java b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextFileDocumentProvider.java index b5676271dde..0cc3c8f0a22 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextFileDocumentProvider.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextFileDocumentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -226,11 +226,11 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro public boolean fCachedReadOnlyState; } - static private class SingleElementIterator implements Iterator { + static private class SingleElementIterator<E> implements Iterator<E> { - private Object fElement; + private E fElement; - public SingleElementIterator(Object element) { + public SingleElementIterator(E element) { fElement= element; } @@ -240,9 +240,9 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro } @Override - public Object next() { + public E next() { if (fElement != null) { - Object result= fElement; + E result= fElement; fElement= null; return result; } @@ -262,11 +262,11 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void bufferContentAboutToBeReplaced(IFileBuffer file) { - List list= new ArrayList(fElementStateListeners); - Iterator e= list.iterator(); + List<IElementStateListener> list= new ArrayList<>(fElementStateListeners); + Iterator<IElementStateListener> e= list.iterator(); while (e.hasNext()) { - IElementStateListener l= (IElementStateListener) e.next(); - Iterator i= getElements(file); + IElementStateListener l= e.next(); + Iterator<Object> i= getElements(file); while (i.hasNext()) l.elementContentAboutToBeReplaced(i.next()); } @@ -274,11 +274,11 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void bufferContentReplaced(IFileBuffer file) { - List list= new ArrayList(fElementStateListeners); - Iterator e= list.iterator(); + List<IElementStateListener> list= new ArrayList<>(fElementStateListeners); + Iterator<IElementStateListener> e= list.iterator(); while (e.hasNext()) { - IElementStateListener l= (IElementStateListener) e.next(); - Iterator i= getElements(file); + IElementStateListener l= e.next(); + Iterator<Object> i= getElements(file); while (i.hasNext()) l.elementContentReplaced(i.next()); } @@ -286,18 +286,18 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void stateChanging(IFileBuffer file) { - Iterator i= getElements(file); + Iterator<Object> i= getElements(file); while (i.hasNext()) fireElementStateChanging(i.next()); } @Override public void dirtyStateChanged(IFileBuffer file, boolean isDirty) { - List list= new ArrayList(fElementStateListeners); - Iterator e= list.iterator(); + List<IElementStateListener> list= new ArrayList<>(fElementStateListeners); + Iterator<IElementStateListener> e= list.iterator(); while (e.hasNext()) { - IElementStateListener l= (IElementStateListener) e.next(); - Iterator i= getElements(file); + IElementStateListener l= e.next(); + Iterator<Object> i= getElements(file); while (i.hasNext()) l.elementDirtyStateChanged(i.next(), isDirty); } @@ -305,13 +305,13 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void stateValidationChanged(IFileBuffer file, boolean isStateValidated) { - List list= new ArrayList(fElementStateListeners); - Iterator e= list.iterator(); + List<IElementStateListener> list= new ArrayList<>(fElementStateListeners); + Iterator<IElementStateListener> e= list.iterator(); while (e.hasNext()) { Object l= e.next(); if (l instanceof IElementStateListenerExtension) { IElementStateListenerExtension x= (IElementStateListenerExtension) l; - Iterator i= getElements(file); + Iterator<Object> i= getElements(file); while (i.hasNext()) x.elementStateValidationChanged(i.next(), isStateValidated); } @@ -323,11 +323,11 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro IWorkspace workspace=ResourcesPlugin.getWorkspace(); IFile newFile= workspace.getRoot().getFile(newLocation); IEditorInput input= new FileEditorInput(newFile); - List list= new ArrayList(fElementStateListeners); - Iterator e= list.iterator(); + List<IElementStateListener> list= new ArrayList<>(fElementStateListeners); + Iterator<IElementStateListener> e= list.iterator(); while (e.hasNext()) { - IElementStateListener l= (IElementStateListener) e.next(); - Iterator i= getElements(file); + IElementStateListener l= e.next(); + Iterator<Object> i= getElements(file); while (i.hasNext()) l.elementMoved(i.next(), input); } @@ -335,11 +335,11 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void underlyingFileDeleted(IFileBuffer file) { - List list= new ArrayList(fElementStateListeners); - Iterator e= list.iterator(); + List<IElementStateListener> list= new ArrayList<>(fElementStateListeners); + Iterator<IElementStateListener> e= list.iterator(); while (e.hasNext()) { - IElementStateListener l= (IElementStateListener) e.next(); - Iterator i= getElements(file); + IElementStateListener l= e.next(); + Iterator<Object> i= getElements(file); while (i.hasNext()) l.elementDeleted(i.next()); } @@ -347,7 +347,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void stateChangeFailed(IFileBuffer file) { - Iterator i= getElements(file); + Iterator<Object> i= getElements(file); while (i.hasNext()) fireElementStateChangeFailed(i.next()); } @@ -366,11 +366,11 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro /** The parent document provider. */ private IDocumentProvider fParentProvider; /** Element information of all connected elements. */ - private final Map fFileInfoMap= new HashMap(); - /** Map from file buffers to their connected elements. */ - private final Map fFileBufferMap= new HashMap(); + private final Map<Object, FileInfo> fFileInfoMap= new HashMap<>(); + /** Map from file buffers to their connected elements. Value is an Object or a {@code List<Object>}. */ + private final Map<ITextFileBuffer, Object> fFileBufferMap= new HashMap<>(); /** The list of element state listeners. */ - private List fElementStateListeners= new ArrayList(); + private List<IElementStateListener> fElementStateListeners= new ArrayList<>(); /** The file buffer listener. */ private final IFileBufferListener fFileBufferListener= new FileBufferListener(); /** The progress monitor. */ @@ -472,7 +472,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void connect(Object element) throws CoreException { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info == null) { info= createFileInfo(element); @@ -499,7 +499,8 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro Object value= fFileBufferMap.get(info.fTextFileBuffer); if (value instanceof List) { - List list= (List) value; + @SuppressWarnings("unchecked") + List<Object> list= (List<Object>) value; list.add(element); return; } @@ -507,7 +508,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro if (value == null) { value= element; } else { - List list= new ArrayList(2); + List<Object> list= new ArrayList<>(2); list.add(value); list.add(element); @@ -637,7 +638,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void disconnect(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info == null) { getParentProvider().disconnect(element); @@ -667,7 +668,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro return; if (value instanceof List) { - List list= (List) value; + List<?> list= (List<?>) value; list.remove(element); if (list.size() == 1) fFileBufferMap.put(info.fTextFileBuffer, list.get(0)); @@ -705,16 +706,16 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro * @param file the file buffer * @return an iterator for all elements connected with the given file buffer */ - protected Iterator getElements(IFileBuffer file) { + protected Iterator<Object> getElements(IFileBuffer file) { Object value= fFileBufferMap.get(file); if (value instanceof List) - return new ArrayList((List) value).iterator(); - return new SingleElementIterator(value); + return new ArrayList<Object>((List<?>) value).iterator(); + return new SingleElementIterator<>(value); } @Override public IDocument getDocument(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return info.fTextFileBuffer.getDocument(); return getParentProvider().getDocument(element); @@ -722,7 +723,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void resetDocument(Object element) throws CoreException { - final FileInfo info= (FileInfo) fFileInfoMap.get(element); + final FileInfo info= fFileInfoMap.get(element); if (info != null) { DocumentProviderOperation operation= new DocumentProviderOperation() { @Override @@ -763,7 +764,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro } protected DocumentProviderOperation createSaveOperation(final Object element, final IDocument document, final boolean overwrite) throws CoreException { - final FileInfo info= (FileInfo) fFileInfoMap.get(element); + final FileInfo info= fFileInfoMap.get(element); if (info != null) { if (info.fTextFileBuffer.getDocument() != document) { @@ -898,7 +899,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public long getModificationStamp(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return info.fTextFileBuffer.getModificationStamp(); return getParentProvider().getModificationStamp(element); @@ -906,7 +907,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public long getSynchronizationStamp(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return 0; return getParentProvider().getSynchronizationStamp(element); @@ -914,7 +915,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public boolean isDeleted(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) { IFileStore fileStore= getFileStore(info); return fileStore == null ? true : !fileStore.fetchInfo().exists(); @@ -924,7 +925,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public boolean mustSaveDocument(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return (info.fCount == 1) && info.fTextFileBuffer.isDirty(); return getParentProvider().mustSaveDocument(element); @@ -932,7 +933,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public boolean canSaveDocument(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return info.fTextFileBuffer.isDirty(); return getParentProvider().canSaveDocument(element); @@ -940,7 +941,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public IAnnotationModel getAnnotationModel(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return info.fModel; return getParentProvider().getAnnotationModel(element); @@ -948,14 +949,14 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void aboutToChange(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info == null) getParentProvider().aboutToChange(element); } @Override public void changed(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info == null) getParentProvider().changed(element); } @@ -986,7 +987,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public boolean isReadOnly(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return info.fCachedReadOnlyState; return ((IDocumentProviderExtension) getParentProvider()).isReadOnly(element); @@ -994,7 +995,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public boolean isModifiable(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return info.fTextFileBuffer.isStateValidated() ? !isReadOnly(element) : true; return ((IDocumentProviderExtension) getParentProvider()).isModifiable(element); @@ -1002,7 +1003,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void validateState(Object element, final Object computationContext) throws CoreException { - final FileInfo info= (FileInfo) fFileInfoMap.get(element); + final FileInfo info= fFileInfoMap.get(element); if (info != null) { DocumentProviderOperation operation= new DocumentProviderOperation() { @Override @@ -1025,7 +1026,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public boolean isStateValidated(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return info.fTextFileBuffer.isStateValidated(); return ((IDocumentProviderExtension) getParentProvider()).isStateValidated(element); @@ -1033,7 +1034,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void updateStateCache(Object element) throws CoreException { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) { boolean isReadOnly= isSystemFileReadOnly(info); // See http://bugs.eclipse.org/bugs/show_bug.cgi?id=14469 for the dirty bit check @@ -1048,14 +1049,14 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void setCanSaveDocument(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info == null) ((IDocumentProviderExtension) getParentProvider()).setCanSaveDocument(element); } @Override public IStatus getStatus(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info == null) return ((IDocumentProviderExtension) getParentProvider()).getStatus(element); @@ -1086,7 +1087,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void synchronize(Object element) throws CoreException { - final FileInfo info= (FileInfo) fFileInfoMap.get(element); + final FileInfo info= fFileInfoMap.get(element); if (info != null) { DocumentProviderOperation operation= new DocumentProviderOperation() { @Override @@ -1121,7 +1122,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public boolean isSynchronized(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return info.fTextFileBuffer.isSynchronized(); return ((IDocumentProviderExtension3) getParentProvider()).isSynchronized(element); @@ -1146,7 +1147,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public String getEncoding(Object element) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return info.fTextFileBuffer.getEncoding(); return ((IStorageDocumentProvider) getParentProvider()).getEncoding(element); @@ -1154,7 +1155,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public void setEncoding(Object element, String encoding) { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) info.fTextFileBuffer.setEncoding(encoding); else @@ -1163,7 +1164,7 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro @Override public IContentType getContentType(Object element) throws CoreException { - FileInfo info= (FileInfo) fFileInfoMap.get(element); + FileInfo info= fFileInfoMap.get(element); if (info != null) return info.fTextFileBuffer.getContentType(); IDocumentProvider parent= getParentProvider(); @@ -1232,25 +1233,25 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro * @return the file info object, or <code>null</code> if none */ protected FileInfo getFileInfo(Object element) { - return (FileInfo) fFileInfoMap.get(element); + return fFileInfoMap.get(element); } /** * Returns an iterator over the elements connected via this document provider. * - * @return an iterator over the list of elements (element type: {@link java.lang.Object}) + * @return an iterator over the list of elements */ - protected Iterator getConnectedElementsIterator() { - return new HashSet(fFileInfoMap.keySet()).iterator(); + protected Iterator<Object> getConnectedElementsIterator() { + return new HashSet<>(fFileInfoMap.keySet()).iterator(); } /** * Returns an iterator over this document provider's file info objects. * - * @return the iterator over list of file info objects (element type: {@link TextFileDocumentProvider.FileInfo}) + * @return the iterator over list of file info objects */ - protected Iterator getFileInfosIterator() { - return new ArrayList(fFileInfoMap.values()).iterator(); + protected Iterator<FileInfo> getFileInfosIterator() { + return new ArrayList<>(fFileInfoMap.values()).iterator(); } /** @@ -1261,8 +1262,8 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro * @see IElementStateListenerExtension#elementStateChanging(Object) */ protected void fireElementStateChanging(Object element) { - List list= new ArrayList(fElementStateListeners); - Iterator e= list.iterator(); + List<IElementStateListener> list= new ArrayList<>(fElementStateListeners); + Iterator<IElementStateListener> e= list.iterator(); while (e.hasNext()) { Object l= e.next(); if (l instanceof IElementStateListenerExtension) { @@ -1280,8 +1281,8 @@ public class TextFileDocumentProvider implements IDocumentProvider, IDocumentPro * @see IElementStateListenerExtension#elementStateChangeFailed(Object) */ protected void fireElementStateChangeFailed(Object element) { - List list= new ArrayList(fElementStateListeners); - Iterator e= list.iterator(); + List<IElementStateListener> list= new ArrayList<>(fElementStateListeners); + Iterator<IElementStateListener> e= list.iterator(); while (e.hasNext()) { Object l= e.next(); if (l instanceof IElementStateListenerExtension) { diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextSourceViewerConfiguration.java b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextSourceViewerConfiguration.java index db85c0dc6fe..9fba7bfda78 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextSourceViewerConfiguration.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/TextSourceViewerConfiguration.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -230,15 +230,15 @@ public class TextSourceViewerConfiguration extends SourceViewerConfiguration { protected final IHyperlinkDetector[] getRegisteredHyperlinkDetectors(ISourceViewer sourceViewer) { HyperlinkDetectorRegistry registry= EditorsUI.getHyperlinkDetectorRegistry(); - Map targets= getHyperlinkDetectorTargets(sourceViewer); + Map<String, IAdaptable> targets= getHyperlinkDetectorTargets(sourceViewer); Assert.isNotNull(targets); IHyperlinkDetector[] result= null; - Iterator iter= targets.entrySet().iterator(); + Iterator<Entry<String, IAdaptable>> iter= targets.entrySet().iterator(); while (iter.hasNext()) { - Entry target= (Entry)iter.next(); - String targetId= (String)target.getKey(); - IAdaptable context= (IAdaptable)target.getValue(); + Entry<String, IAdaptable> target= iter.next(); + String targetId= target.getKey(); + IAdaptable context= target.getValue(); result= merge(result, registry.createHyperlinkDetectors(targetId, context)); } return result; @@ -256,8 +256,8 @@ public class TextSourceViewerConfiguration extends SourceViewerConfiguration { * and the target context (<code>IAdaptable</code>) as value * @since 3.3 */ - protected Map getHyperlinkDetectorTargets(ISourceViewer sourceViewer) { - Map targets= new HashMap(); + protected Map<String, IAdaptable> getHyperlinkDetectorTargets(ISourceViewer sourceViewer) { + Map<String, IAdaptable> targets= new HashMap<>(); targets.put(EditorsUI.DEFAULT_TEXT_EDITOR_ID, null); return targets; } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/templates/ContributionContextTypeRegistry.java b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/templates/ContributionContextTypeRegistry.java index 963686cf5fc..92cb4761cb3 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/templates/ContributionContextTypeRegistry.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/templates/ContributionContextTypeRegistry.java @@ -182,7 +182,7 @@ public class ContributionContextTypeRegistry extends ContextTypeRegistry { * @return the instantiated resolvers */ private static TemplateVariableResolver[] createResolvers(IConfigurationElement[] extensions, String contextTypeId) { - List resolvers= new ArrayList(); + List<TemplateVariableResolver> resolvers= new ArrayList<>(); for (int i= 0; i < extensions.length; i++) { if (extensions[i].getName().equals(RESOLVER)) { String declaredId= extensions[i].getAttribute(CONTEXT_TYPE_ID); @@ -198,7 +198,7 @@ public class ContributionContextTypeRegistry extends ContextTypeRegistry { } } - return (TemplateVariableResolver[]) resolvers.toArray(new TemplateVariableResolver[resolvers.size()]); + return resolvers.toArray(new TemplateVariableResolver[resolvers.size()]); } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/templates/ContributionTemplateStore.java b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/templates/ContributionTemplateStore.java index 83f1c579cc9..d7479dd8667 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/templates/ContributionTemplateStore.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/editors/text/templates/ContributionTemplateStore.java @@ -105,15 +105,15 @@ public class ContributionTemplateStore extends TemplateStore { @Override protected void loadContributedTemplates() throws IOException { IConfigurationElement[] extensions= getTemplateExtensions(); - Collection contributed= readContributedTemplates(extensions); - for (Iterator it= contributed.iterator(); it.hasNext();) { - TemplatePersistenceData data= (TemplatePersistenceData) it.next(); + Collection<TemplatePersistenceData> contributed= readContributedTemplates(extensions); + for (Iterator<TemplatePersistenceData> it= contributed.iterator(); it.hasNext();) { + TemplatePersistenceData data= it.next(); internalAdd(data); } } - private Collection readContributedTemplates(IConfigurationElement[] extensions) throws IOException { - Collection templates= new ArrayList(); + private Collection<TemplatePersistenceData> readContributedTemplates(IConfigurationElement[] extensions) throws IOException { + Collection<TemplatePersistenceData> templates= new ArrayList<>(); for (int i= 0; i < extensions.length; i++) { if (extensions[i].getName().equals(TEMPLATE)) createTemplate(templates, extensions[i]); @@ -125,7 +125,7 @@ public class ContributionTemplateStore extends TemplateStore { return templates; } - private void readIncludedTemplates(Collection templates, IConfigurationElement element) throws IOException { + private void readIncludedTemplates(Collection<TemplatePersistenceData> templates, IConfigurationElement element) throws IOException { String file= element.getAttribute(FILE); if (file != null) { Bundle plugin = Platform.getBundle(element.getContributor().getName()); @@ -218,7 +218,7 @@ public class ContributionTemplateStore extends TemplateStore { return Platform.getExtensionRegistry().getConfigurationElementsFor(TEMPLATES_EXTENSION_POINT); } - private void createTemplate(Collection map, IConfigurationElement element) { + private void createTemplate(Collection<TemplatePersistenceData> map, IConfigurationElement element) { String contextTypeId= element.getAttribute(CONTEXT_TYPE_ID); // log failures since extension point id and name are mandatory if (contextExists(contextTypeId)) { diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/AccessibilityPreferencePage.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/AccessibilityPreferencePage.java index 63c1bccbd55..55d8024250b 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/AccessibilityPreferencePage.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/AccessibilityPreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -40,6 +40,7 @@ import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.internal.editors.text.AccessibilityPreferencePage.EnumeratedDomain.EnumValue; +import org.eclipse.ui.internal.editors.text.OverlayPreferenceStore.OverlayKey; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; @@ -208,8 +209,8 @@ public class AccessibilityPreferencePage extends PreferencePage implements IWork } } - private final java.util.List fItems= new ArrayList(); - private final Set fValueSet= new HashSet(); + private final java.util.List<EnumValue> fItems= new ArrayList<>(); + private final Set<EnumValue> fValueSet= new HashSet<>(); public void addValue(EnumValue val) { if (fValueSet.contains(val)) @@ -220,8 +221,8 @@ public class AccessibilityPreferencePage extends PreferencePage implements IWork public int getIndex(EnumValue enumValue) { int i= 0; - for (Iterator it= fItems.iterator(); it.hasNext();) { - EnumValue ev= (EnumValue) it.next(); + for (Iterator<EnumValue> it= fItems.iterator(); it.hasNext();) { + EnumValue ev= it.next(); if (ev.equals(enumValue)) return i; i++; @@ -231,13 +232,13 @@ public class AccessibilityPreferencePage extends PreferencePage implements IWork public EnumValue getValueByIndex (int index) { if (index >= 0 && fItems.size() > index) - return (EnumValue) fItems.get(index); + return fItems.get(index); return null; } public EnumValue getValueByInteger(int intValue) { - for (Iterator it= fItems.iterator(); it.hasNext();) { - EnumValue e= (EnumValue) it.next(); + for (Iterator<EnumValue> it= fItems.iterator(); it.hasNext();) { + EnumValue e= it.next(); if (e.getIntValue() == intValue) return e; } @@ -344,12 +345,12 @@ public class AccessibilityPreferencePage extends PreferencePage implements IWork */ private boolean fFieldsInitialized= false; - private java.util.List fInitializers= new ArrayList(); + private java.util.List<Initializer> fInitializers= new ArrayList<>(); private InitializerFactory fInitializerFactory= new InitializerFactory(); private Control fContents; - private ArrayList fMasterSlaveListeners= new ArrayList(); + private ArrayList<SelectionListener> fMasterSlaveListeners= new ArrayList<>(); public AccessibilityPreferencePage() { @@ -367,7 +368,7 @@ public class AccessibilityPreferencePage extends PreferencePage implements IWork private OverlayPreferenceStore createOverlayStore() { - ArrayList overlayKeys= new ArrayList(); + ArrayList<OverlayKey> overlayKeys= new ArrayList<>(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_USE_CUSTOM_CARETS)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_WIDE_CARET)); @@ -439,8 +440,8 @@ public class AccessibilityPreferencePage extends PreferencePage implements IWork private void initializeFields() { - for (Iterator it= fInitializers.iterator(); it.hasNext();) { - Initializer initializer= (Initializer) it.next(); + for (Iterator<Initializer> it= fInitializers.iterator(); it.hasNext();) { + Initializer initializer= it.next(); initializer.initialize(); } @@ -463,8 +464,8 @@ public class AccessibilityPreferencePage extends PreferencePage implements IWork initializeFields(); - for (Iterator iterator= fMasterSlaveListeners.iterator(); iterator.hasNext();) { - SelectionListener listener= (SelectionListener)iterator.next(); + for (Iterator<SelectionListener> iterator= fMasterSlaveListeners.iterator(); iterator.hasNext();) { + SelectionListener listener= iterator.next(); listener.widgetSelected(null); } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/AnnotationsConfigurationBlock.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/AnnotationsConfigurationBlock.java index a0d8f4018d5..cf0695a4c5e 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/AnnotationsConfigurationBlock.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/AnnotationsConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -55,6 +55,7 @@ import org.eclipse.jface.viewers.ViewerComparator; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.internal.editors.text.OverlayPreferenceStore.OverlayKey; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess; @@ -154,7 +155,7 @@ class AnnotationsConfigurationBlock implements IPreferenceConfigurationBlock { private final ListItem[] fListModel; private ComboViewer fDecorationViewer; - private final Set fImageKeys= new HashSet(); + private final Set<String> fImageKeys= new HashSet<>(); public AnnotationsConfigurationBlock(OverlayPreferenceStore store) { Assert.isNotNull(store); @@ -166,11 +167,11 @@ class AnnotationsConfigurationBlock implements IPreferenceConfigurationBlock { private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys(MarkerAnnotationPreferences preferences) { - ArrayList overlayKeys= new ArrayList(); - Iterator e= preferences.getAnnotationPreferences().iterator(); + ArrayList<OverlayKey> overlayKeys= new ArrayList<>(); + Iterator<AnnotationPreference> e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, info.getColorPreferenceKey())); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, info.getTextPreferenceKey())); if (info.getHighlightPreferenceKey() != null) @@ -527,11 +528,11 @@ class AnnotationsConfigurationBlock implements IPreferenceConfigurationBlock { } private ListItem[] createAnnotationTypeListModel(MarkerAnnotationPreferences preferences) { - ArrayList listModelItems= new ArrayList(); - Iterator e= preferences.getAnnotationPreferences().iterator(); + ArrayList<ListItem> listModelItems= new ArrayList<>(); + Iterator<AnnotationPreference> e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); if (info.isIncludeOnPreferencePage()) { String label= info.getPreferenceLabel(); if (containsMoreThanOne(preferences.getAnnotationPreferences().iterator(), label)) @@ -544,16 +545,11 @@ class AnnotationsConfigurationBlock implements IPreferenceConfigurationBlock { } } - Comparator comparator= new Comparator() { + Comparator<ListItem> comparator= new Comparator<ListItem>() { @Override - public int compare(Object o1, Object o2) { - if (!(o2 instanceof ListItem)) - return -1; - if (!(o1 instanceof ListItem)) - return 1; - - String label1= ((ListItem)o1).label; - String label2= ((ListItem)o2).label; + public int compare(ListItem o1, ListItem o2) { + String label1= o1.label; + String label2= o2.label; return Collator.getInstance().compare(label1, label2); @@ -649,13 +645,13 @@ class AnnotationsConfigurationBlock implements IPreferenceConfigurationBlock { return copy; } - private boolean containsMoreThanOne(Iterator annotationPrefernceIterator, String label) { + private boolean containsMoreThanOne(Iterator<AnnotationPreference> annotationPrefernceIterator, String label) { if (label == null) return false; int count= 0; while (annotationPrefernceIterator.hasNext()) { - if (label.equals(((AnnotationPreference)annotationPrefernceIterator.next()).getPreferenceLabel())) + if (label.equals(annotationPrefernceIterator.next().getPreferenceLabel())) count++; if (count == 2) @@ -668,8 +664,8 @@ class AnnotationsConfigurationBlock implements IPreferenceConfigurationBlock { public void dispose() { ImageRegistry registry= EditorsPlugin.getDefault().getImageRegistry(); - for (Iterator it= fImageKeys.iterator(); it.hasNext();) { - String string= (String) it.next(); + for (Iterator<String> it= fImageKeys.iterator(); it.hasNext();) { + String string= it.next(); registry.remove(string); } @@ -688,7 +684,7 @@ class AnnotationsConfigurationBlock implements IPreferenceConfigurationBlock { if (changed) { String[] selection= null; - ArrayList list= new ArrayList(); + ArrayList<String[]> list= new ArrayList<>(); // highlighting if (item.highlightKey != null) { @@ -712,8 +708,8 @@ class AnnotationsConfigurationBlock implements IPreferenceConfigurationBlock { // set selection if (selection == null) { String val= item.textStyleKey == null ? SQUIGGLES[1] : fStore.getString(item.textStyleKey); - for (Iterator iter= list.iterator(); iter.hasNext();) { - String[] elem= (String[]) iter.next(); + for (Iterator<String[]> iter= list.iterator(); iter.hasNext();) { + String[] elem= iter.next(); if (elem[1].equals(val)) { selection= elem; break; diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/ConvertLineDelimitersAction.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/ConvertLineDelimitersAction.java index f635e2aeaca..20b98b019ac 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/ConvertLineDelimitersAction.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/ConvertLineDelimitersAction.java @@ -154,7 +154,7 @@ public class ConvertLineDelimitersAction extends FileBufferOperationAction { */ private IFile[] filterUnacceptableFiles(IFile[] files) { boolean askForBinary= true; - Set filtered= new HashSet(); + Set<IFile> filtered= new HashSet<>(); for (int i= 0; i < files.length; i++) { IFile file= files[i]; if (isAcceptableLocation(file.getFullPath())) { @@ -174,7 +174,7 @@ public class ConvertLineDelimitersAction extends FileBufferOperationAction { } } } - return (IFile[]) filtered.toArray(new IFile[filtered.size()]); + return filtered.toArray(new IFile[filtered.size()]); } } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/FileEditorInputAdapterFactory.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/FileEditorInputAdapterFactory.java index e7f5a3d18bb..ad274083f89 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/FileEditorInputAdapterFactory.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/FileEditorInputAdapterFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -40,22 +40,23 @@ public class FileEditorInputAdapterFactory implements IAdapterFactory { } /** The list of provided adapters. */ - private static final Class[] ADAPTER_LIST= new Class[] { ILocationProvider.class }; + private static final Class<?>[] ADAPTER_LIST= new Class[] { ILocationProvider.class }; /** The provided location provider */ private ILocationProvider fLocationProvider= new LocationProvider(); + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Object adaptableObject, Class adapterType) { + public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (ILocationProvider.class.equals(adapterType)) { if (adaptableObject instanceof IFile) - return fLocationProvider; + return (T) fLocationProvider; } return null; } @Override - public Class[] getAdapterList() { + public Class<?>[] getAdapterList() { return ADAPTER_LIST; } } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/HyperlinkDetectorsConfigurationBlock.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/HyperlinkDetectorsConfigurationBlock.java index 2724db09139..d128c92316a 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/HyperlinkDetectorsConfigurationBlock.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/HyperlinkDetectorsConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -57,6 +57,8 @@ import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.Viewer; +import org.eclipse.ui.internal.editors.text.OverlayPreferenceStore.OverlayKey; + import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.HyperlinkDetectorDescriptor; import org.eclipse.ui.texteditor.HyperlinkDetectorTargetDescriptor; @@ -176,7 +178,7 @@ class HyperlinkDetectorsConfigurationBlock implements IPreferenceConfigurationBl } private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { - ArrayList overlayKeys= new ArrayList(); + ArrayList<OverlayKey> overlayKeys= new ArrayList<>(); for (int i= 0; i < fHyperlinkDetectorDescriptors.length; i++) { overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, fHyperlinkDetectorDescriptors[i].getId())); @@ -447,7 +449,7 @@ class HyperlinkDetectorsConfigurationBlock implements IPreferenceConfigurationBl } private Object[] getCheckedItems() { - List result= new ArrayList(); + List<ListItem> result= new ArrayList<>(); for (int i= 0; i < fListModel.length; i++) if (!fStore.getBoolean(fListModel[i].id)) result.add(fListModel[i]); @@ -513,7 +515,7 @@ class HyperlinkDetectorsConfigurationBlock implements IPreferenceConfigurationBl } private ListItem[] createListModel() { - ArrayList listModelItems= new ArrayList(); + ArrayList<ListItem> listModelItems= new ArrayList<>(); for (int i= 0; i < fHyperlinkDetectorDescriptors.length; i++) { HyperlinkDetectorDescriptor desc= fHyperlinkDetectorDescriptors[i]; HyperlinkDetectorTargetDescriptor target= desc.getTarget(); @@ -524,17 +526,11 @@ class HyperlinkDetectorsConfigurationBlock implements IPreferenceConfigurationBl listModelItems.add(new ListItem(desc.getId(), desc.getName(), target.getName(), modifierKeys)); } - Comparator comparator= new Comparator() { + Comparator<ListItem> comparator= new Comparator<ListItem>() { @Override - public int compare(Object o1, Object o2) { - if (!(o2 instanceof ListItem)) - return -1; - if (!(o1 instanceof ListItem)) - return 1; - - String label1= ((ListItem)o1).name; - String label2= ((ListItem)o2).name; - + public int compare(ListItem o1, ListItem o2) { + String label1= o1.name; + String label2= o2.name; return Collator.getInstance().compare(label1, label2); } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/IURIEditorInputAdapterFactory.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/IURIEditorInputAdapterFactory.java index 10023802fee..e17b056b4b6 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/IURIEditorInputAdapterFactory.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/IURIEditorInputAdapterFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2008 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -54,22 +54,23 @@ public class IURIEditorInputAdapterFactory implements IAdapterFactory { /** The list of provided adapters. */ - private static final Class[] ADAPTER_LIST= new Class[] { ILocationProvider.class }; + private static final Class<?>[] ADAPTER_LIST= new Class[] { ILocationProvider.class }; /** The provided location provider */ private ILocationProvider fLocationProvider= new LocationProvider(); + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Object adaptableObject, Class adapterType) { + public <T> T getAdapter(Object adaptableObject, Class<T> adapterType) { if (ILocationProvider.class.equals(adapterType)) { if (adaptableObject instanceof IURIEditorInput) - return fLocationProvider; + return (T) fLocationProvider; } return null; } @Override - public Class[] getAdapterList() { + public Class<?>[] getAdapterList() { return ADAPTER_LIST; } } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/LinkedModeConfigurationBlock.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/LinkedModeConfigurationBlock.java index 38a5dae7801..fbaba7547e9 100755 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/LinkedModeConfigurationBlock.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/LinkedModeConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -53,6 +53,8 @@ import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerComparator; +import org.eclipse.ui.internal.editors.text.OverlayPreferenceStore.OverlayKey; + import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; @@ -79,9 +81,9 @@ class LinkedModeConfigurationBlock implements IPreferenceConfigurationBlock { final String highlightKey; final String textStyleKey; final String textKey; - final List validStyles; + final List<String[]> validStyles; - ListItem(String label, String colorKey, String textKey, String highlightKey, String textStyleKey, List validStyles) { + ListItem(String label, String colorKey, String textKey, String highlightKey, String textStyleKey, List<String[]> validStyles) { this.label= label; this.colorKey= colorKey; this.highlightKey= highlightKey; @@ -141,7 +143,7 @@ class LinkedModeConfigurationBlock implements IPreferenceConfigurationBlock { protected static final int INDENT= 20; private OverlayPreferenceStore fStore; - private ArrayList fMasterSlaveListeners= new ArrayList(); + private ArrayList<SelectionListener> fMasterSlaveListeners= new ArrayList<>(); private OverlayPreferenceStore getPreferenceStore() { return fStore; @@ -155,11 +157,11 @@ class LinkedModeConfigurationBlock implements IPreferenceConfigurationBlock { } private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys(MarkerAnnotationPreferences preferences) { - ArrayList overlayKeys= new ArrayList(); + ArrayList<OverlayKey> overlayKeys= new ArrayList<>(); - Iterator e= preferences.getAnnotationPreferences().iterator(); + Iterator<AnnotationPreference> e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); if (isLinkedModeAnnotation(info)) { overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, info.getColorPreferenceKey())); @@ -183,14 +185,14 @@ class LinkedModeConfigurationBlock implements IPreferenceConfigurationBlock { } private ListItem[] createAnnotationTypeListModel(MarkerAnnotationPreferences preferences) { - ArrayList listModelItems= new ArrayList(); - Iterator e= preferences.getAnnotationPreferences().iterator(); + ArrayList<ListItem> listModelItems= new ArrayList<>(); + Iterator<AnnotationPreference> e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); if (isLinkedModeAnnotation(info)) { String label= info.getPreferenceLabel(); - List styles= getStyles(info.getAnnotationType()); + List<String[]> styles= getStyles(info.getAnnotationType()); listModelItems.add(new ListItem(label, info.getColorPreferenceKey(), info.getTextPreferenceKey(), info.getHighlightPreferenceKey(), info.getTextStylePreferenceKey(), styles)); } } @@ -201,7 +203,7 @@ class LinkedModeConfigurationBlock implements IPreferenceConfigurationBlock { } - private List getStyles(Object type) { + private List<String[]> getStyles(Object type) { if (type.equals(MASTER)) return Arrays.asList(new String[][] {BOX, DASHED_BOX, HIGHLIGHT, UNDERLINE, SQUIGGLES}); if (type.equals(SLAVE)) @@ -210,7 +212,7 @@ class LinkedModeConfigurationBlock implements IPreferenceConfigurationBlock { return Arrays.asList(new String[][] {BOX, DASHED_BOX, HIGHLIGHT, UNDERLINE, SQUIGGLES}); if (type.equals(EXIT)) return Arrays.asList(new String[][] {IBEAM}); - return new ArrayList(); + return new ArrayList<>(); } /** @@ -466,7 +468,7 @@ class LinkedModeConfigurationBlock implements IPreferenceConfigurationBlock { if (changed) { String[] selection= null; - ArrayList list= new ArrayList(); + ArrayList<String[]> list= new ArrayList<>(); list.addAll(item.validStyles); @@ -476,8 +478,8 @@ class LinkedModeConfigurationBlock implements IPreferenceConfigurationBlock { // set selection if (selection == null) { String val= getPreferenceStore().getString(item.textStyleKey); - for (Iterator iter= list.iterator(); iter.hasNext();) { - String[] elem= (String[]) iter.next(); + for (Iterator<String[]> iter= list.iterator(); iter.hasNext();) { + String[] elem= iter.next(); if (elem[1].equals(val)) { selection= elem; break; @@ -487,7 +489,7 @@ class LinkedModeConfigurationBlock implements IPreferenceConfigurationBlock { fDecorationViewer.setInput(list.toArray(new Object[list.size()])); if (selection == null) - selection= (String[]) list.get(0); + selection= list.get(0); fDecorationViewer.setSelection(new StructuredSelection((Object) selection), true); } } @@ -556,9 +558,9 @@ class LinkedModeConfigurationBlock implements IPreferenceConfigurationBlock { private void initializeFields() { // Update slaves - Iterator iter= fMasterSlaveListeners.iterator(); + Iterator<SelectionListener> iter= fMasterSlaveListeners.iterator(); while (iter.hasNext()) { - SelectionListener listener= (SelectionListener)iter.next(); + SelectionListener listener= iter.next(); listener.widgetSelected(null); } } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/NextPreviousPulldownActionDelegate.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/NextPreviousPulldownActionDelegate.java index 64e5392e00c..951b60f5738 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/NextPreviousPulldownActionDelegate.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/NextPreviousPulldownActionDelegate.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -47,7 +47,7 @@ public abstract class NextPreviousPulldownActionDelegate extends Action implemen private IPreferenceStore fStore; /** Action for handling menu item selection. */ - private static class NavigationEnablementAction extends Action implements Comparable { + private static class NavigationEnablementAction extends Action implements Comparable<NavigationEnablementAction> { /** The preference store. */ private IPreferenceStore fStore; @@ -82,13 +82,8 @@ public abstract class NextPreviousPulldownActionDelegate extends Action implemen } @Override - public int compareTo(Object o) { - if (!(o instanceof NavigationEnablementAction)) - return -1; - - String otherName= ((NavigationEnablementAction)o).fName; - - return Collator.getInstance().compare(fName, otherName); + public int compareTo(NavigationEnablementAction o) { + return Collator.getInstance().compare(fName, o.fName); } } @@ -160,11 +155,11 @@ public abstract class NextPreviousPulldownActionDelegate extends Action implemen */ private IAction[] getActionsFromDescriptors() { MarkerAnnotationPreferences fMarkerAnnotationPreferences= EditorsPlugin.getDefault().getMarkerAnnotationPreferences(); - SortedSet containers= new TreeSet(); + SortedSet<NavigationEnablementAction> containers= new TreeSet<>(); - Iterator iter= fMarkerAnnotationPreferences.getAnnotationPreferences().iterator(); + Iterator<AnnotationPreference> iter= fMarkerAnnotationPreferences.getAnnotationPreferences().iterator(); while (iter.hasNext()) { - AnnotationPreference preference= (AnnotationPreference)iter.next(); + AnnotationPreference preference= iter.next(); String key= preference.getShowInNextPrevDropdownToolbarActionKey(); if (key != null && fStore.getBoolean(key)) { String preferenceKey= getPreferenceKey(preference); @@ -182,7 +177,7 @@ public abstract class NextPreviousPulldownActionDelegate extends Action implemen } } - return (IAction[]) containers.toArray(new Action[containers.size()]); + return containers.toArray(new Action[containers.size()]); } @Override diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/NonExistingFileEditorInput.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/NonExistingFileEditorInput.java index 33b3670648b..049d04ff266 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/NonExistingFileEditorInput.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/NonExistingFileEditorInput.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -69,10 +69,11 @@ public class NonExistingFileEditorInput implements IEditorInput, ILocationProvid return fName; } + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Class adapter) { + public <T> T getAdapter(Class<T> adapter) { if (ILocationProvider.class.equals(adapter)) - return this; + return (T) this; return Platform.getAdapterManager().getAdapter(this, adapter); } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/QuickDiffConfigurationBlock.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/QuickDiffConfigurationBlock.java index fc48a4af8ac..4531693e940 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/QuickDiffConfigurationBlock.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/QuickDiffConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,6 +14,7 @@ package org.eclipse.ui.internal.editors.text; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; import org.eclipse.swt.SWT; @@ -37,6 +38,8 @@ import org.eclipse.jface.preference.ColorSelector; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.ui.internal.editors.text.OverlayPreferenceStore.OverlayKey; + import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.MarkerAnnotationPreferences; @@ -54,7 +57,7 @@ class QuickDiffConfigurationBlock implements IPreferenceConfigurationBlock { private OverlayPreferenceStore fStore; - private Map fCheckBoxes= new HashMap(); + private Map<Button, String> fCheckBoxes= new HashMap<>(); private SelectionListener fCheckBoxListener= new SelectionListener() { @Override public void widgetDefaultSelected(SelectionEvent e) { @@ -62,7 +65,7 @@ class QuickDiffConfigurationBlock implements IPreferenceConfigurationBlock { @Override public void widgetSelected(SelectionEvent e) { Button button= (Button) e.widget; - fStore.setValue((String) fCheckBoxes.get(button), button.getSelection()); + fStore.setValue(fCheckBoxes.get(button), button.getSelection()); } }; @@ -114,14 +117,14 @@ class QuickDiffConfigurationBlock implements IPreferenceConfigurationBlock { } private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys(MarkerAnnotationPreferences preferences) { - ArrayList overlayKeys= new ArrayList(); + ArrayList<OverlayKey> overlayKeys= new ArrayList<>(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractDecoratedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER)); - Iterator e= preferences.getAnnotationPreferences().iterator(); + Iterator<AnnotationPreference> e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); if (info.getAnnotationType().equals("org.eclipse.ui.workbench.texteditor.quickdiffChange") //$NON-NLS-1$ || (info.getAnnotationType().equals("org.eclipse.ui.workbench.texteditor.quickdiffAddition")) //$NON-NLS-1$ @@ -140,9 +143,9 @@ class QuickDiffConfigurationBlock implements IPreferenceConfigurationBlock { private String[][] createQuickDiffModel(MarkerAnnotationPreferences preferences) { String[][] items= new String[3][]; - Iterator e= preferences.getAnnotationPreferences().iterator(); + Iterator<AnnotationPreference> e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); if (info.getAnnotationType().equals("org.eclipse.ui.workbench.texteditor.quickdiffChange")) //$NON-NLS-1$ items[0]= new String[] { info.getColorPreferenceKey(), info.getOverviewRulerPreferenceKey(), TextEditorMessages.QuickDiffConfigurationBlock_changeColor }; else if (info.getAnnotationType().equals("org.eclipse.ui.workbench.texteditor.quickdiffAddition")) //$NON-NLS-1$ @@ -154,10 +157,10 @@ class QuickDiffConfigurationBlock implements IPreferenceConfigurationBlock { } private String[][] createQuickDiffReferenceListModel() { - java.util.List descriptors= new QuickDiff().getReferenceProviderDescriptors(); - ArrayList listModelItems= new ArrayList(); - for (Iterator it= descriptors.iterator(); it.hasNext();) { - ReferenceProviderDescriptor descriptor= (ReferenceProviderDescriptor) it.next(); + List<ReferenceProviderDescriptor> descriptors= new QuickDiff().getReferenceProviderDescriptors(); + ArrayList<String[]> listModelItems= new ArrayList<>(); + for (Iterator<ReferenceProviderDescriptor> it= descriptors.iterator(); it.hasNext();) { + ReferenceProviderDescriptor descriptor= it.next(); String label= LegacyActionTools.removeMnemonics(descriptor.getLabel()); listModelItems.add(new String[] { descriptor.getId(), label }); } @@ -408,10 +411,10 @@ class QuickDiffConfigurationBlock implements IPreferenceConfigurationBlock { } private void initializeFields() { - Iterator e= fCheckBoxes.keySet().iterator(); + Iterator<Button> e= fCheckBoxes.keySet().iterator(); while (e.hasNext()) { - Button b= (Button) e.next(); - String key= (String) fCheckBoxes.get(b); + Button b= e.next(); + String key= fCheckBoxes.get(b); b.setSelection(fStore.getBoolean(key)); } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/RefreshEditorAction.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/RefreshEditorAction.java index d574dc90f01..cbd84775ae5 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/RefreshEditorAction.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/RefreshEditorAction.java @@ -37,7 +37,7 @@ public class RefreshEditorAction extends RefreshAction implements IUpdate { @Override public void update() { - final IResource resource= fTextEditor == null ? null : (IResource)fTextEditor.getEditorInput().getAdapter(IResource.class); + final IResource resource= fTextEditor == null ? null : fTextEditor.getEditorInput().getAdapter(IResource.class); if (resource != null) selectionChanged(new StructuredSelection(resource)); else diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/RemoveTrailingWhitespaceHandler.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/RemoveTrailingWhitespaceHandler.java index 3ab60367b19..56e6f967bcf 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/RemoveTrailingWhitespaceHandler.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/RemoveTrailingWhitespaceHandler.java @@ -104,13 +104,13 @@ public class RemoveTrailingWhitespaceHandler extends FileBufferOperationHandler * @since 3.2 */ private IFile[] filterUnacceptableFiles(IFile[] files) { - Set filtered= new HashSet(); + Set<IFile> filtered= new HashSet<>(); for (int i= 0; i < files.length; i++) { IFile file= files[i]; if (isAcceptableLocation(file.getFullPath())) filtered.add(file); } - return (IFile[]) filtered.toArray(new IFile[filtered.size()]); + return filtered.toArray(new IFile[filtered.size()]); } @Override diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SelectResourcesBlock.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SelectResourcesBlock.java index ac6e768c5f1..8f3b8cf846a 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SelectResourcesBlock.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SelectResourcesBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,6 +31,8 @@ import org.eclipse.swt.widgets.Tree; import org.eclipse.core.runtime.ListenerList; import org.eclipse.core.runtime.SafeRunner; +import org.eclipse.core.resources.IContainer; + import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.util.SafeRunnable; import org.eclipse.jface.viewers.CheckStateChangedEvent; @@ -70,7 +72,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList */ interface IElementFilter { - void filterElements(Collection elements) throws InterruptedException; + void filterElements(Collection<Object> elements) throws InterruptedException; void filterElements(Object[] elements) throws InterruptedException; } @@ -80,11 +82,11 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList private Object currentTreeSelection; - private Collection expandedTreeNodes= new HashSet(); + private Collection<Object> expandedTreeNodes= new HashSet<>(); - private Map checkedStateStore= new HashMap(9); + private Map<Object, List<Object>> checkedStateStore= new HashMap<>(9); - private Collection whiteCheckedTreeItems= new HashSet(); + private Collection<Object> whiteCheckedTreeItems= new HashSet<>(); private ListenerList listeners= new ListenerList(ListenerList.IDENTITY); @@ -265,7 +267,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList private boolean determineShouldBeAtLeastGrayChecked(Object treeElement) { // if any list items associated with treeElement are checked then it // retains its gray-checked status regardless of its children - List checked= (List) checkedStateStore.get(treeElement); + List<Object> checked= checkedStateStore.get(treeElement); if (checked != null && (!checked.isEmpty())) return true; @@ -310,7 +312,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList Object child= children[i]; setWhiteChecked(child, true); treeViewer.setChecked(child, true); - checkedStateStore.put(child, new ArrayList()); + checkedStateStore.put(child, new ArrayList<>()); } } @@ -341,7 +343,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList filter.filterElements(listContentProvider.getElements(treeElement)); else { //Add what we have stored if (checkedStateStore.containsKey(treeElement)) - filter.filterElements((Collection) checkedStateStore.get(treeElement)); + filter.filterElements(checkedStateStore.get(treeElement)); } Object[] treeChildren= treeContentProvider.getChildren(treeElement); @@ -365,12 +367,12 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList * @param treeElement java.lang.Object * @param result java.util.Collection */ - private void findAllWhiteCheckedItems(Object treeElement, Collection result) { + private void findAllWhiteCheckedItems(Object treeElement, Collection<Object> result) { if (whiteCheckedTreeItems.contains(treeElement)) result.add(treeElement); else { - Collection listChildren= (Collection) checkedStateStore.get(treeElement); + Collection<Object> listChildren= checkedStateStore.get(treeElement); //if it is not in the store then it and its children are not interesting if (listChildren == null) return; @@ -404,14 +406,14 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList * @return all of the leaf elements which are checked. This API does not * return null in order to keep backwards compatibility. */ - public List getAllCheckedListItems() { + public List<Object> getAllCheckedListItems() { - final ArrayList returnValue= new ArrayList(); + final ArrayList<Object> returnValue= new ArrayList<>(); IElementFilter passThroughFilter= new IElementFilter() { @Override - public void filterElements(Collection elements) throws InterruptedException { + public void filterElements(Collection<Object> elements) throws InterruptedException { returnValue.addAll(elements); } @@ -426,7 +428,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList try { getAllCheckedListItems(passThroughFilter); } catch (InterruptedException exception) { - return new ArrayList(); + return new ArrayList<>(); } return returnValue; @@ -439,9 +441,9 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList * * @return the list of all of the items that are white checked */ - public List getAllWhiteCheckedItems() { + public List<Object> getAllWhiteCheckedItems() { - List result= new ArrayList(); + List<Object> result= new ArrayList<>(); //Iterate through the children of the root as the root is not in the // store @@ -469,7 +471,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList if (checkedStateStore.containsKey(treeElement)) return; // no need to proceed upwards from here - checkedStateStore.put(treeElement, new ArrayList()); + checkedStateStore.put(treeElement, new ArrayList<>()); Object parent= treeContentProvider.getParent(treeElement); if (parent != null) grayCheckHierarchy(parent); @@ -508,7 +510,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList */ private void initialize() { treeViewer.setInput(root); - this.expandedTreeNodes= new ArrayList(); + this.expandedTreeNodes= new ArrayList<>(); this.expandedTreeNodes.add(root); Object[] topElements= treeContentProvider.getElements(root); if (topElements.length == 1) @@ -526,7 +528,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList * update caused by selection */ private void listItemChecked(Object listElement, boolean state, boolean updatingFromSelection) { - List checkedListItems= (List) checkedStateStore.get(currentTreeSelection); + List<Object> checkedListItems= checkedStateStore.get(currentTreeSelection); //If it has not been expanded do so as the selection of list items will // affect gray state if (!expandedTreeNodes.contains(currentTreeSelection)) @@ -537,7 +539,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList // since the associated tree item has gone from 0 -> 1 checked // list items, tree checking may need to be updated grayCheckHierarchy(currentTreeSelection); - checkedListItems= (List) checkedStateStore.get(currentTreeSelection); + checkedListItems= checkedStateStore.get(currentTreeSelection); } checkedListItems.add(listElement); } else { @@ -597,10 +599,10 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList }); } else { - List listItemsToCheck= (List) checkedStateStore.get(treeElement); + List<Object> listItemsToCheck= checkedStateStore.get(treeElement); if (listItemsToCheck != null) { - Iterator listItemsEnum= listItemsToCheck.iterator(); + Iterator<Object> listItemsEnum= listItemsToCheck.iterator(); while (listItemsEnum.hasNext()) listViewer.setChecked(listItemsEnum.next(), true); } @@ -615,13 +617,13 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList * @param item the tree item * @param selectedNodes the set of selected nodes */ - private void primeHierarchyForSelection(Object item, Set selectedNodes) { + private void primeHierarchyForSelection(Object item, Set<Object> selectedNodes) { //Only prime it if we haven't visited yet if (selectedNodes.contains(item)) return; - checkedStateStore.put(item, new ArrayList()); + checkedStateStore.put(item, new ArrayList<>()); //mark as expanded as we are going to populate it after this expandedTreeNodes.add(item); @@ -708,7 +710,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList private void setListForWhiteSelection(Object treeElement) { Object[] listItems= listContentProvider.getElements(treeElement); - List listItemsChecked= new ArrayList(); + List<Object> listItemsChecked= new ArrayList<>(); for (int i= 0; i < listItems.length; ++i) { listItemsChecked.add(listItems[i]); } @@ -855,18 +857,18 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList * empty list). If a tree element does not have any selected * items, do not include the element in the Map. */ - public void updateSelections(Map items) { + public void updateSelections(Map<IContainer, List<Object>> items) { // We are replacing all selected items with the given selected items, // so reinitialize everything. this.listViewer.setAllChecked(false); this.treeViewer.setCheckedElements(new Object[0]); - this.whiteCheckedTreeItems= new HashSet(); - Set selectedNodes= new HashSet(); - checkedStateStore= new HashMap(); + this.whiteCheckedTreeItems= new HashSet<>(); + Set<Object> selectedNodes= new HashSet<>(); + checkedStateStore= new HashMap<>(); //Update the store before the hierarchy to prevent updating parents // before all of the children are done - Iterator keyIterator= items.keySet().iterator(); + Iterator<IContainer> keyIterator= items.keySet().iterator(); while (keyIterator.hasNext()) { Object key= keyIterator.next(); primeHierarchyForSelection(key, selectedNodes); @@ -882,7 +884,7 @@ class SelectResourcesBlock implements ICheckStateListener, ISelectionChangedList if (currentTreeSelection != null) { Object displayItems= items.get(currentTreeSelection); if (displayItems != null) - listViewer.setCheckedElements(((List) displayItems).toArray()); + listViewer.setCheckedElements(((List<?>) displayItems).toArray()); } } } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SelectResourcesDialog.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SelectResourcesDialog.java index 87cd0b0b723..a5596442f3d 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SelectResourcesDialog.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SelectResourcesDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -62,7 +62,7 @@ class SelectResourcesDialog extends Dialog { } private SelectResourcesBlock fResourceGroup; - private List fAcceptedFileTypes = new ArrayList(); + private List<Object> fAcceptedFileTypes = new ArrayList<>(); private IResource[] fInput; private String fTitle; private String fInstruction; @@ -92,8 +92,8 @@ class SelectResourcesDialog extends Dialog { } public IResource[] getSelectedResources() { - List items= fResourceGroup.getAllCheckedListItems(); - return (IResource[]) items.toArray(new IResource[items.size()]); + List<Object> items= fResourceGroup.getAllCheckedListItems(); + return items.toArray(new IResource[items.size()]); } @Override @@ -139,7 +139,7 @@ class SelectResourcesDialog extends Dialog { @Override public Object[] getChildren(Object o) { if (o instanceof IWorkspaceRoot) { - HashSet projects= new HashSet(); + HashSet<IResource> projects= new HashSet<>(); for (int i= 0; i < fInput.length; i++) { IResource project= fInput[i].getProject(); if ((project.getType() & resourceType) > 0) @@ -158,7 +158,7 @@ class SelectResourcesDialog extends Dialog { } //filter out the desired resource types - ArrayList results = new ArrayList(); + ArrayList<IResource> results = new ArrayList<>(); for (int i = 0; i < members.length; i++) { //And the test bits with the resource types to see if they are what we want if ((members[i].getType() & resourceType) > 0 && (resourceType != IResource.FILE || fAcceptableLocationsFilter == null || fAcceptableLocationsFilter.accept(members[i]))) { @@ -170,7 +170,7 @@ class SelectResourcesDialog extends Dialog { //input element case if (o instanceof ArrayList) - return ((ArrayList) o).toArray(); + return ((ArrayList<?>) o).toArray(); return new Object[0]; } @@ -252,8 +252,8 @@ class SelectResourcesDialog extends Dialog { } }; - List list= fResourceGroup.getAllWhiteCheckedItems(); - final IResource[] resources= (IResource[]) list.toArray(new IResource[list.size()]); + List<Object> list= fResourceGroup.getAllWhiteCheckedItems(); + final IResource[] resources= list.toArray(new IResource[list.size()]); Runnable runnable = new Runnable() { @Override @@ -276,7 +276,7 @@ class SelectResourcesDialog extends Dialog { String extension= resourceName.substring(separatorIndex + 1); - Iterator e= fAcceptedFileTypes.iterator(); + Iterator<Object> e= fAcceptedFileTypes.iterator(); while (e.hasNext()) { if (extension.equalsIgnoreCase((String) e.next())) return true; @@ -291,17 +291,17 @@ class SelectResourcesDialog extends Dialog { } protected void setSelection(IResource[] input, IFilter filter) { - Map selectionMap= new Hashtable(); + Map<IContainer, List<Object>> selectionMap= new Hashtable<>(); for (int i= 0; i < input.length; i++) { IResource resource= input[i]; if ((resource.getType() & IResource.FILE) > 0) { if (filter.accept(resource)) { - List files= null; + List<Object> files= null; IContainer parent= resource.getParent(); if (selectionMap.containsKey(parent)) - files= (List) selectionMap.get(parent); + files= selectionMap.get(parent); else - files= new ArrayList(); + files= new ArrayList<>(); files.add(resource); selectionMap.put(parent, files); @@ -313,11 +313,11 @@ class SelectResourcesDialog extends Dialog { updateSelectionCount(); } - private void setSelection(Map selectionMap, IContainer parent, IFilter filter) { + private void setSelection(Map<IContainer, List<Object>> selectionMap, IContainer parent, IFilter filter) { try { IResource[] resources= parent.members(); - List selections= new ArrayList(); + List<Object> selections= new ArrayList<>(); for (int i= 0; i < resources.length; i++) { IResource resource= resources[i]; @@ -348,7 +348,7 @@ class SelectResourcesDialog extends Dialog { } private void updateSelectionCount() { - List listItems= fResourceGroup.getAllCheckedListItems(); + List<Object> listItems= fResourceGroup.getAllCheckedListItems(); int checkedFiles= listItems == null ? 0 : listItems.size(); StringBuffer buffer= new StringBuffer(); switch (checkedFiles) { diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SharedTextColors.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SharedTextColors.java index 047968bd09a..fabb852146e 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SharedTextColors.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SharedTextColors.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -27,7 +27,7 @@ import org.eclipse.jface.text.source.ISharedTextColors; class SharedTextColors implements ISharedTextColors { /** The display table. */ - private Map fDisplayTable; + private Map<Display, Map<RGB, Color>> fDisplayTable; /** Creates an returns a shared color manager. */ public SharedTextColors() { @@ -40,13 +40,13 @@ class SharedTextColors implements ISharedTextColors { return null; if (fDisplayTable == null) - fDisplayTable= new HashMap(2); + fDisplayTable= new HashMap<>(2); final Display display= Display.getCurrent(); - Map colorTable= (Map) fDisplayTable.get(display); + Map<RGB, Color> colorTable= fDisplayTable.get(display); if (colorTable == null) { - colorTable= new HashMap(10); + colorTable= new HashMap<>(10); fDisplayTable.put(display, colorTable); display.disposeExec(new Runnable() { @Override @@ -56,7 +56,7 @@ class SharedTextColors implements ISharedTextColors { }); } - Color color= (Color) colorTable.get(rgb); + Color color= colorTable.get(rgb); if (color == null) { color= new Color(display, rgb); colorTable.put(rgb, color); @@ -70,9 +70,9 @@ class SharedTextColors implements ISharedTextColors { if (fDisplayTable == null) return; - Iterator iter= fDisplayTable.values().iterator(); + Iterator<Map<RGB, Color>> iter= fDisplayTable.values().iterator(); while (iter.hasNext()) - dispose((Map)iter.next()); + dispose(iter.next()); fDisplayTable= null; } @@ -84,7 +84,7 @@ class SharedTextColors implements ISharedTextColors { */ private void dispose(Display display) { if (fDisplayTable != null) - dispose((Map)fDisplayTable.remove(display)); + dispose(fDisplayTable.remove(display)); } /** @@ -93,13 +93,13 @@ class SharedTextColors implements ISharedTextColors { * @param colorTable the color table that maps <code>RGB</code> to <code>Color</code> * @since 3.3 */ - private void dispose(Map colorTable) { + private void dispose(Map<RGB, Color> colorTable) { if (colorTable == null) return; - Iterator iter= colorTable.values().iterator(); + Iterator<Color> iter= colorTable.values().iterator(); while (iter.hasNext()) - ((Color) iter.next()).dispose(); + iter.next().dispose(); colorTable.clear(); } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SpellingConfigurationBlock.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SpellingConfigurationBlock.java index 1d711e1d252..50d53dcb65e 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SpellingConfigurationBlock.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/SpellingConfigurationBlock.java @@ -50,6 +50,8 @@ import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; +import org.eclipse.ui.internal.editors.text.OverlayPreferenceStore.OverlayKey; + import org.eclipse.ui.texteditor.spelling.IPreferenceStatusMonitor; import org.eclipse.ui.texteditor.spelling.ISpellingPreferenceBlock; import org.eclipse.ui.texteditor.spelling.SpellingEngineDescriptor; @@ -175,9 +177,9 @@ class SpellingConfigurationBlock implements IPreferenceConfigurationBlock { private StackLayout fStackLayout; /* the model */ - private final Map fProviderDescriptors; - private final Map fProviderPreferences; - private final Map fProviderControls; + private final Map<String, SpellingEngineDescriptor> fProviderDescriptors; + private final Map<String, ISpellingPreferenceBlock> fProviderPreferences; + private final Map<String, Control> fProviderControls; private ForwardingStatusMonitor fStatusMonitor; @@ -190,13 +192,13 @@ class SpellingConfigurationBlock implements IPreferenceConfigurationBlock { fStore.addKeys(createOverlayStoreKeys()); fStatusMonitor= new ForwardingStatusMonitor(statusMonitor); fProviderDescriptors= createListModel(); - fProviderPreferences= new HashMap(); - fProviderControls= new HashMap(); + fProviderPreferences= new HashMap<>(); + fProviderControls= new HashMap<>(); } - private Map createListModel() { + private Map<String, SpellingEngineDescriptor> createListModel() { SpellingEngineDescriptor[] descs= EditorsUI.getSpellingService().getSpellingEngineDescriptors(); - Map map= new HashMap(); + Map<String, SpellingEngineDescriptor> map= new HashMap<>(); for (int i= 0; i < descs.length; i++) { map.put(descs[i].getId(), descs[i]); } @@ -205,7 +207,7 @@ class SpellingConfigurationBlock implements IPreferenceConfigurationBlock { private OverlayPreferenceStore.OverlayKey[] createOverlayStoreKeys() { - ArrayList overlayKeys= new ArrayList(); + ArrayList<OverlayKey> overlayKeys= new ArrayList<>(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, SpellingService.PREFERENCE_SPELLING_ENABLED)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, SpellingService.PREFERENCE_SPELLING_ENGINE)); @@ -398,7 +400,7 @@ class SpellingConfigurationBlock implements IPreferenceConfigurationBlock { setEnabled(fComboGroup, enabled); SpellingEngineDescriptor desc= EditorsUI.getSpellingService().getActiveSpellingEngineDescriptor(fStore); String id= desc != null ? desc.getId() : ""; //$NON-NLS-1$ - final ISpellingPreferenceBlock preferenceBlock= (ISpellingPreferenceBlock) fProviderPreferences.get(id); + final ISpellingPreferenceBlock preferenceBlock= fProviderPreferences.get(id); if (preferenceBlock != null) { ISafeRunnable runnable= new ISafeRunnable() { @Override @@ -433,7 +435,7 @@ class SpellingConfigurationBlock implements IPreferenceConfigurationBlock { fCurrentBlock= new ErrorPreferences(message); } else { id= desc.getId(); - fCurrentBlock= (ISpellingPreferenceBlock) fProviderPreferences.get(id); + fCurrentBlock= fProviderPreferences.get(id); if (fCurrentBlock == null) { try { fCurrentBlock= desc.createPreferences(); @@ -445,7 +447,7 @@ class SpellingConfigurationBlock implements IPreferenceConfigurationBlock { } } - Control control= (Control) fProviderControls.get(id); + Control control= fProviderControls.get(id); if (control == null) { final Control[] result= new Control[1]; ISafeRunnable runnable= new ISafeRunnable() { @@ -495,7 +497,7 @@ class SpellingConfigurationBlock implements IPreferenceConfigurationBlock { public boolean canPerformOk() { SpellingEngineDescriptor desc= EditorsUI.getSpellingService().getActiveSpellingEngineDescriptor(fStore); String id= desc != null ? desc.getId() : ""; //$NON-NLS-1$ - final ISpellingPreferenceBlock block= (ISpellingPreferenceBlock) fProviderPreferences.get(id); + final ISpellingPreferenceBlock block= fProviderPreferences.get(id); if (block == null) return true; @@ -515,8 +517,8 @@ class SpellingConfigurationBlock implements IPreferenceConfigurationBlock { @Override public void performOk() { - for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) { - final ISpellingPreferenceBlock block= (ISpellingPreferenceBlock) it.next(); + for (Iterator<ISpellingPreferenceBlock> it= fProviderPreferences.values().iterator(); it.hasNext();) { + final ISpellingPreferenceBlock block= it.next(); ISafeRunnable runnable= new ISafeRunnable() { @Override public void run() throws Exception { @@ -533,8 +535,8 @@ class SpellingConfigurationBlock implements IPreferenceConfigurationBlock { @Override public void performDefaults() { restoreFromPreferences(); - for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) { - final ISpellingPreferenceBlock block= (ISpellingPreferenceBlock) it.next(); + for (Iterator<ISpellingPreferenceBlock> it= fProviderPreferences.values().iterator(); it.hasNext();) { + final ISpellingPreferenceBlock block= it.next(); ISafeRunnable runnable= new ISafeRunnable() { @Override public void run() throws Exception { @@ -550,8 +552,8 @@ class SpellingConfigurationBlock implements IPreferenceConfigurationBlock { @Override public void dispose() { - for (Iterator it= fProviderPreferences.values().iterator(); it.hasNext();) { - final ISpellingPreferenceBlock block= (ISpellingPreferenceBlock) it.next(); + for (Iterator<ISpellingPreferenceBlock> it= fProviderPreferences.values().iterator(); it.hasNext();) { + final ISpellingPreferenceBlock block= it.next(); ISafeRunnable runnable= new ISafeRunnable() { @Override public void run() throws Exception { diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/TextEditorDefaultsPreferencePage.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/TextEditorDefaultsPreferencePage.java index 571c0d7018e..ad2fae6dc0e 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/TextEditorDefaultsPreferencePage.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/editors/text/TextEditorDefaultsPreferencePage.java @@ -58,6 +58,7 @@ import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.PreferencesUtil; +import org.eclipse.ui.internal.editors.text.OverlayPreferenceStore.OverlayKey; import org.eclipse.ui.internal.editors.text.TextEditorDefaultsPreferencePage.EnumeratedDomain.EnumValue; import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants; @@ -256,8 +257,8 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements } } - private final java.util.List fItems= new ArrayList(); - private final Set fValueSet= new HashSet(); + private final java.util.List<EnumValue> fItems= new ArrayList<>(); + private final Set<EnumValue> fValueSet= new HashSet<>(); public void addValue(EnumValue val) { if (fValueSet.contains(val)) @@ -268,8 +269,8 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements public int getIndex(EnumValue enumValue) { int i= 0; - for (Iterator it= fItems.iterator(); it.hasNext();) { - EnumValue ev= (EnumValue) it.next(); + for (Iterator<EnumValue> it= fItems.iterator(); it.hasNext();) { + EnumValue ev= it.next(); if (ev.equals(enumValue)) return i; i++; @@ -279,13 +280,13 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements public EnumValue getValueByIndex (int index) { if (index >= 0 && fItems.size() > index) - return (EnumValue) fItems.get(index); + return fItems.get(index); return null; } public EnumValue getValueByInteger(int intValue) { - for (Iterator it= fItems.iterator(); it.hasNext();) { - EnumValue e= (EnumValue) it.next(); + for (Iterator<EnumValue> it= fItems.iterator(); it.hasNext();) { + EnumValue e= it.next(); if (e.getIntValue() == intValue) return e; } @@ -392,7 +393,7 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements private static class WhitespaceCharacterPainterOptionsDialog extends Dialog { - private java.util.List fDialogInitializers= new ArrayList(); + private java.util.List<Initializer> fDialogInitializers= new ArrayList<>(); private OverlayPreferenceStore fDialogOverlayStore; @@ -410,7 +411,7 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements } private OverlayPreferenceStore createDialogOverlayStore() { - ArrayList overlayKeys= new ArrayList(); + ArrayList<OverlayKey> overlayKeys= new ArrayList<>(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SHOW_LEADING_SPACES)); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SHOW_ENCLOSED_SPACES)); @@ -447,8 +448,8 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements } private void initializeShowWhitespaceCharactersPreferences() { - for (Iterator it= fDialogInitializers.iterator(); it.hasNext();) { - Initializer initializer= (Initializer)it.next(); + for (Iterator<Initializer> it= fDialogInitializers.iterator(); it.hasNext();) { + Initializer initializer= it.next(); initializer.initialize(); } } @@ -670,13 +671,13 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements */ private boolean fFieldsInitialized= false; - private ArrayList fMasterSlaveListeners= new ArrayList(); + private ArrayList<SelectionListener> fMasterSlaveListeners= new ArrayList<>(); - private java.util.List fInitializers= new ArrayList(); + private java.util.List<Initializer> fInitializers= new ArrayList<>(); private InitializerFactory fInitializerFactory; - private Map fDomains= new HashMap(); + private Map<Domain, Text> fDomains= new HashMap<>(); public TextEditorDefaultsPreferencePage() { @@ -688,7 +689,7 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements private OverlayPreferenceStore createOverlayStore() { - ArrayList overlayKeys= new ArrayList(); + ArrayList<OverlayKey> overlayKeys= new ArrayList<>(); overlayKeys.add(new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE)); @@ -1043,8 +1044,8 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements } private void initializeFields() { - for (Iterator it= fInitializers.iterator(); it.hasNext();) { - Initializer initializer= (Initializer) it.next(); + for (Iterator<Initializer> it= fInitializers.iterator(); it.hasNext();) { + Initializer initializer= it.next(); initializer.initialize(); } @@ -1052,9 +1053,9 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements updateStatus(new StatusInfo()); // Update slaves - Iterator iter= fMasterSlaveListeners.iterator(); + Iterator<SelectionListener> iter= fMasterSlaveListeners.iterator(); while (iter.hasNext()) { - SelectionListener listener= (SelectionListener)iter.next(); + SelectionListener listener= iter.next(); listener.widgetSelected(null); } @@ -1205,8 +1206,8 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); combo.setLayoutData(gd); combo.setToolTipText(preference.getDescription()); - for (Iterator it= domain.fItems.iterator(); it.hasNext();) { - EnumValue value= (EnumValue) it.next(); + for (Iterator<EnumValue> it= domain.fItems.iterator(); it.hasNext();) { + EnumValue value= it.next(); combo.add(value.getLabel()); } @@ -1351,9 +1352,9 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements if (updateStatusOnError(checkedDomain)) return; - Iterator iter= fDomains.keySet().iterator(); + Iterator<Domain> iter= fDomains.keySet().iterator(); while (iter.hasNext()) { - Domain domain= (Domain)iter.next(); + Domain domain= iter.next(); if (domain.equals(checkedDomain)) continue; if (updateStatusOnError(domain)) @@ -1363,7 +1364,7 @@ public class TextEditorDefaultsPreferencePage extends PreferencePage implements } private boolean updateStatusOnError(Domain domain) { - Text textWidget= (Text)fDomains.get(domain); + Text textWidget= fDomains.get(domain); if (textWidget.isEnabled()) { IStatus status= domain.validate(textWidget.getText()); if (status.matches(IStatus.ERROR)) { diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/AnnotationColumn.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/AnnotationColumn.java index 06c344b6e38..5b8af149ef4 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/AnnotationColumn.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/AnnotationColumn.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2008 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -114,8 +114,8 @@ public class AnnotationColumn extends AbstractContributedRulerColumn implements if (store != null && fDelegate instanceof AnnotationRulerColumn) { final AnnotationRulerColumn column= (AnnotationRulerColumn) fDelegate; // initial set up - for (Iterator iter2= fAnnotationPreferences.getAnnotationPreferences().iterator(); iter2.hasNext();) { - AnnotationPreference preference= (AnnotationPreference)iter2.next(); + for (Iterator<AnnotationPreference> iter2= fAnnotationPreferences.getAnnotationPreferences().iterator(); iter2.hasNext();) { + AnnotationPreference preference= iter2.next(); String key= preference.getVerticalRulerPreferenceKey(); boolean showAnnotation= true; if (key != null && store.contains(key)) @@ -156,9 +156,9 @@ public class AnnotationColumn extends AbstractContributedRulerColumn implements if (preferenceKey == null) return null; - Iterator e= fAnnotationPreferences.getAnnotationPreferences().iterator(); + Iterator<AnnotationPreference> e= fAnnotationPreferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); if (info != null && preferenceKey.equals(info.getVerticalRulerPreferenceKey())) return info; } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/AnnotationTypeHierarchy.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/AnnotationTypeHierarchy.java index 7bd4280324d..f195f6daee9 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/AnnotationTypeHierarchy.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/AnnotationTypeHierarchy.java @@ -30,14 +30,14 @@ import org.eclipse.ui.editors.text.EditorsUI; */ public final class AnnotationTypeHierarchy { - private Map fTypeMap; - private Map fTypesCache= new HashMap(); + private Map<String, String> fTypeMap; + private Map<String, AnnotationType> fTypesCache= new HashMap<>(); public AnnotationTypeHierarchy() { } public AnnotationType getAnnotationType(String typeName) { - AnnotationType type= (AnnotationType) fTypesCache.get(typeName); + AnnotationType type= fTypesCache.get(typeName); if (type == null) { String[] superTypes= computeSuperTypes(typeName); type= new AnnotationType(typeName, superTypes); @@ -52,11 +52,11 @@ public final class AnnotationTypeHierarchy { } private String[] computeSuperTypes(String typeName) { - ArrayList types= new ArrayList(); + ArrayList<String> types= new ArrayList<>(); append(types, getDirectSuperType(typeName)); int index= 0; while (index < types.size()) { - String type= (String) types.get(index++); + String type= types.get(index++); append(types, getDirectSuperType(type)); } @@ -66,10 +66,10 @@ public final class AnnotationTypeHierarchy { } private String getDirectSuperType(String typeName) { - return (String) getTypeMap().get(typeName); + return getTypeMap().get(typeName); } - private void append(List list, String string) { + private void append(List<String> list, String string) { if (string == null || string.trim().length() == 0) return; @@ -77,14 +77,14 @@ public final class AnnotationTypeHierarchy { list.add(string); } - private Map getTypeMap() { + private Map<String, String> getTypeMap() { if (fTypeMap == null) fTypeMap= readTypes(); return fTypeMap; } - private Map readTypes() { - HashMap allTypes= new HashMap(); + private Map<String, String> readTypes() { + HashMap<String, String> allTypes= new HashMap<>(); IExtensionPoint extensionPoint= Platform.getExtensionRegistry().getExtensionPoint(EditorsUI.PLUGIN_ID, "annotationTypes"); //$NON-NLS-1$ if (extensionPoint != null) { diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/DelegatingAnnotationPreference.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/DelegatingAnnotationPreference.java index 85efcfb3056..7840f06c2a3 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/DelegatingAnnotationPreference.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/DelegatingAnnotationPreference.java @@ -28,7 +28,7 @@ public class DelegatingAnnotationPreference extends AnnotationPreference { private AnnotationType fType; private AnnotationPreferenceLookup fLookup; - private Set fCache= new HashSet(); + private Set<Object> fCache= new HashSet<>(); public DelegatingAnnotationPreference(AnnotationType type, AnnotationPreferenceLookup lookup) { fType= type; diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/LineNumberColumn.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/LineNumberColumn.java index f639325d16b..f903c1213fc 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/LineNumberColumn.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/LineNumberColumn.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2010 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -33,8 +33,8 @@ import org.eclipse.jface.window.Window; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.revisions.IRevisionRulerColumn; import org.eclipse.jface.text.revisions.IRevisionRulerColumnExtension; -import org.eclipse.jface.text.revisions.RevisionInformation; import org.eclipse.jface.text.revisions.IRevisionRulerColumnExtension.RenderingMode; +import org.eclipse.jface.text.revisions.RevisionInformation; import org.eclipse.jface.text.source.AnnotationModel; import org.eclipse.jface.text.source.CompositeRuler; import org.eclipse.jface.text.source.IAnnotationHover; @@ -225,10 +225,10 @@ public class LineNumberColumn extends AbstractContributedRulerColumn implements updateRevisionAuthorVisibility(store, fDelegate); updateRevisionIdVisibility(store, fDelegate); - Map annotationPrefs= getAnnotationPreferenceMap(); - final AnnotationPreference changedPref= (AnnotationPreference) annotationPrefs.get("org.eclipse.ui.workbench.texteditor.quickdiffChange"); //$NON-NLS-1$ - final AnnotationPreference addedPref= (AnnotationPreference) annotationPrefs.get("org.eclipse.ui.workbench.texteditor.quickdiffAddition"); //$NON-NLS-1$ - final AnnotationPreference deletedPref= (AnnotationPreference) annotationPrefs.get("org.eclipse.ui.workbench.texteditor.quickdiffDeletion"); //$NON-NLS-1$ + Map<Object, AnnotationPreference> annotationPrefs= getAnnotationPreferenceMap(); + final AnnotationPreference changedPref= annotationPrefs.get("org.eclipse.ui.workbench.texteditor.quickdiffChange"); //$NON-NLS-1$ + final AnnotationPreference addedPref= annotationPrefs.get("org.eclipse.ui.workbench.texteditor.quickdiffAddition"); //$NON-NLS-1$ + final AnnotationPreference deletedPref= annotationPrefs.get("org.eclipse.ui.workbench.texteditor.quickdiffDeletion"); //$NON-NLS-1$ updateChangedColor(changedPref, store, fDelegate); updateAddedColor(addedPref, store, fDelegate); updateDeletedColor(deletedPref, store, fDelegate); @@ -327,11 +327,11 @@ public class LineNumberColumn extends AbstractContributedRulerColumn implements } } - private Map getAnnotationPreferenceMap() { - Map annotationPrefs= new HashMap(); - Iterator iter= fAnnotationPreferences.getAnnotationPreferences().iterator(); + private Map<Object, AnnotationPreference> getAnnotationPreferenceMap() { + Map<Object, AnnotationPreference> annotationPrefs= new HashMap<>(); + Iterator<AnnotationPreference> iter= fAnnotationPreferences.getAnnotationPreferences().iterator(); while (iter.hasNext()) { - AnnotationPreference pref= (AnnotationPreference) iter.next(); + AnnotationPreference pref= iter.next(); Object type= pref.getAnnotationType(); annotationPrefs.put(type, pref); } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/PropertyEventDispatcher.java b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/PropertyEventDispatcher.java index 35f49ff8153..0dddf4d09b9 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/PropertyEventDispatcher.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/internal/texteditor/PropertyEventDispatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -23,8 +23,8 @@ import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; public final class PropertyEventDispatcher { - private final Map fHandlerMap= new HashMap(); - private final Map fReverseMap= new HashMap(); + private final Map<Object, Object> fHandlerMap= new HashMap<>(); + private final Map<Object, Object> fReverseMap= new HashMap<>(); private final IPreferenceStore fStore; private final IPropertyChangeListener fListener= new IPropertyChangeListener() { @Override @@ -47,8 +47,8 @@ public final class PropertyEventDispatcher { if (value instanceof IPropertyChangeListener) ((IPropertyChangeListener) value).propertyChange(event); else if (value instanceof Set) - for (Iterator it= ((Set) value).iterator(); it.hasNext(); ) - ((IPropertyChangeListener) it.next()).propertyChange(event); + for (@SuppressWarnings("unchecked") Iterator<IPropertyChangeListener> it= ((Set<IPropertyChangeListener>) value).iterator(); it.hasNext(); ) + it.next().propertyChange(event); } public void addPropertyChangeListener(String property, IPropertyChangeListener listener) { Assert.isLegal(property != null); @@ -60,23 +60,27 @@ public final class PropertyEventDispatcher { multiMapPut(fHandlerMap, property, listener); multiMapPut(fReverseMap, listener, property); } - private void multiMapPut(Map map, Object key, Object value) { + private void multiMapPut(Map<Object, Object> map, Object key, Object value) { Object mapping= map.get(key); if (mapping == null) { map.put(key, value); } else if (mapping instanceof Set) { - ((Set) mapping).add(value); + @SuppressWarnings("unchecked") + Set<Object> set= (Set<Object>) mapping; + set.add(value); } else { - Set set= new LinkedHashSet(); + Set<Object> set= new LinkedHashSet<>(); set.add(mapping); set.add(value); map.put(key, set); } } - private void multiMapRemove(Map map, Object key, Object value) { + private void multiMapRemove(Map<Object, Object> map, Object key, Object value) { Object mapping= map.get(key); if (mapping instanceof Set) { - ((Set) mapping).remove(value); + @SuppressWarnings("unchecked") + Set<Object> set= (Set<Object>) mapping; + set.remove(value); } else if (mapping != null) { map.remove(key); } @@ -90,7 +94,7 @@ public final class PropertyEventDispatcher { multiMapRemove(fHandlerMap, value, listener); } else if (value instanceof Set) { fReverseMap.remove(listener); - for (Iterator it= ((Set) value).iterator(); it.hasNext();) + for (@SuppressWarnings("unchecked") Iterator<Object> it= ((Set<Object>) value).iterator(); it.hasNext();) multiMapRemove(fHandlerMap, it.next(), listener); } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractDecoratedTextEditor.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractDecoratedTextEditor.java index 0e3c4137720..d08346b7163 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractDecoratedTextEditor.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractDecoratedTextEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -402,9 +402,9 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { protected IOverviewRuler createOverviewRuler(ISharedTextColors sharedColors) { IOverviewRuler ruler= new OverviewRuler(getAnnotationAccess(), VERTICAL_RULER_WIDTH, sharedColors); - Iterator e= fAnnotationPreferences.getAnnotationPreferences().iterator(); + Iterator<AnnotationPreference> e= fAnnotationPreferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference preference= (AnnotationPreference) e.next(); + AnnotationPreference preference= e.next(); if (preference.contributesToHeader()) ruler.addHeaderAnnotationType(preference.getAnnotationType()); } @@ -428,9 +428,9 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { */ protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { - Iterator e= fAnnotationPreferences.getAnnotationPreferences().iterator(); + Iterator<AnnotationPreference> e= fAnnotationPreferences.getAnnotationPreferences().iterator(); while (e.hasNext()) - support.setAnnotationPreference((AnnotationPreference) e.next()); + support.setAnnotationPreference(e.next()); support.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR); support.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN); @@ -446,7 +446,7 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { if (fSourceViewerDecorationSupport != null) fSourceViewerDecorationSupport.install(getPreferenceStore()); - IColumnSupport columnSupport= (IColumnSupport)getAdapter(IColumnSupport.class); + IColumnSupport columnSupport= getAdapter(IColumnSupport.class); if (isLineNumberRulerVisible()) { RulerColumnDescriptor lineNumberColumnDescriptor= RulerColumnRegistry.getDefault().getColumnDescriptor(LineNumberColumn.ID); @@ -564,7 +564,7 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { if (show == isChangeInformationShowing()) return; - IColumnSupport columnSupport= (IColumnSupport)getAdapter(IColumnSupport.class); + IColumnSupport columnSupport= getAdapter(IColumnSupport.class); // only handle visibility of the combined column, but not the number/change only state if (show && fLineColumn == null) { @@ -820,7 +820,7 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { if (LINE_NUMBER_RULER.equals(property)) { // only handle visibility of the combined column, but not the number/change only state - IColumnSupport columnSupport= (IColumnSupport)getAdapter(IColumnSupport.class); + IColumnSupport columnSupport= getAdapter(IColumnSupport.class); if (isLineNumberRulerVisible() && fLineColumn == null) { RulerColumnDescriptor lineNumberColumnDescriptor= RulerColumnRegistry.getDefault().getColumnDescriptor(LineNumberColumn.ID); if (lineNumberColumnDescriptor != null) @@ -1385,16 +1385,17 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { setAction(ITextEditorActionConstants.PRINT, action); } + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Class adapter) { + public <T> T getAdapter(Class<T> adapter) { if (IGotoMarker.class.equals(adapter)) - return fGotoMarkerAdapter; + return (T) fGotoMarkerAdapter; if (IAnnotationAccess.class.equals(adapter)) - return getAnnotationAccess(); + return (T) getAnnotationAccess(); if (adapter == IShowInSource.class) { - return new IShowInSource() { + return (T) new IShowInSource() { @Override public ShowInContext getShowInContext() { ISelection selection= null; @@ -1408,11 +1409,11 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { if (IRevisionRulerColumn.class.equals(adapter)) { if (fLineNumberRulerColumn instanceof IRevisionRulerColumn) - return fLineNumberRulerColumn; + return (T) fLineNumberRulerColumn; } if (MarkerAnnotationPreferences.class.equals(adapter)) - return EditorsPlugin.getDefault().getMarkerAnnotationPreferences(); + return (T) EditorsPlugin.getDefault().getMarkerAnnotationPreferences(); return super.getAdapter(adapter); @@ -1466,7 +1467,7 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { RulerColumnDescriptor lineNumberColumnDescriptor= RulerColumnRegistry.getDefault().getColumnDescriptor(LineNumberColumn.ID); if (lineNumberColumnDescriptor != null) { - IColumnSupport columnSupport= (IColumnSupport)getAdapter(IColumnSupport.class); + IColumnSupport columnSupport= getAdapter(IColumnSupport.class); columnSupport.setColumnVisible(lineNumberColumnDescriptor, isLineNumberRulerVisible() || isPrefQuickDiffAlwaysOn()); } } @@ -1702,7 +1703,7 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { * @since 3.6 */ private Charset getCharset() { - IEncodingSupport encodingSupport= (IEncodingSupport)getAdapter(IEncodingSupport.class); + IEncodingSupport encodingSupport= getAdapter(IEncodingSupport.class); if (encodingSupport == null) return null; try { @@ -1785,9 +1786,9 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { Point selection= getSourceViewer().getSelectedRange(); IAnnotationModel model= getSourceViewer().getAnnotationModel(); Annotation annotation= null; - Iterator iter= model.getAnnotationIterator(); + Iterator<Annotation> iter= model.getAnnotationIterator(); while (iter.hasNext()) { - annotation= (Annotation)iter.next(); + annotation= iter.next(); Position p= model.getPosition(annotation); if (p.getOffset() == selection.x && p.getLength() == selection.y) break; @@ -1905,12 +1906,12 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { */ private void addRulerContributionActions(IMenuManager menu) { // store directly in generic editor preferences - final IColumnSupport support= (IColumnSupport) getAdapter(IColumnSupport.class); + final IColumnSupport support= getAdapter(IColumnSupport.class); IPreferenceStore store= EditorsUI.getPreferenceStore(); final RulerColumnPreferenceAdapter adapter= new RulerColumnPreferenceAdapter(store, AbstractTextEditor.PREFERENCE_RULER_CONTRIBUTIONS); - List descriptors= RulerColumnRegistry.getDefault().getColumnDescriptors(); - for (Iterator t= descriptors.iterator(); t.hasNext();) { - final RulerColumnDescriptor descriptor= (RulerColumnDescriptor) t.next(); + List<RulerColumnDescriptor> descriptors= RulerColumnRegistry.getDefault().getColumnDescriptors(); + for (Iterator<RulerColumnDescriptor> t= descriptors.iterator(); t.hasNext();) { + final RulerColumnDescriptor descriptor= t.next(); if (!descriptor.isIncludedInMenu() || !support.isColumnSupported(descriptor)) continue; final boolean isVisible= support.isColumnVisible(descriptor); @@ -2013,7 +2014,7 @@ public abstract class AbstractDecoratedTextEditor extends StatusTextEditor { if (editor instanceof IGotoMarker) gotoMarkerTarget= (IGotoMarker)editor; else - gotoMarkerTarget= editor != null ? (IGotoMarker)editor.getAdapter(IGotoMarker.class) : null; + gotoMarkerTarget= editor != null ? editor.getAdapter(IGotoMarker.class) : null; if (gotoMarkerTarget != null) { final IEditorInput input= editor.getEditorInput(); if (input instanceof IFileEditorInput) { diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractMarkerAnnotationModel.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractMarkerAnnotationModel.java index 7ba1f7788f6..120c86346f0 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractMarkerAnnotationModel.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AbstractMarkerAnnotationModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -70,11 +70,11 @@ import org.eclipse.ui.editors.text.EditorsUI; public abstract class AbstractMarkerAnnotationModel extends AnnotationModel implements IPersistableAnnotationModel { /** List of annotations whose text range became invalid because of document changes */ - private List fDeletedAnnotations= new ArrayList(2); + private List<Annotation> fDeletedAnnotations= new ArrayList<>(2); /** List of registered and instantiated marker updaters */ - private List fInstantiatedMarkerUpdaters= null; + private List<IMarkerUpdater> fInstantiatedMarkerUpdaters= null; /** List of registered but not yet instantiated marker updaters */ - private List fMarkerUpdaterSpecifications= null; + private List<IConfigurationElement> fMarkerUpdaterSpecifications= null; private static final String ID= "id"; //$NON-NLS-1$ @@ -262,9 +262,9 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl private void installMarkerUpdaters() { // initialize lists - indicates that the initialization happened - fInstantiatedMarkerUpdaters= new ArrayList(2); - HashMap markerUpdaterOrderMap = new HashMap(2); - LinkedList markerUpdaterSpecificationsLinkedList= new LinkedList(); + fInstantiatedMarkerUpdaters= new ArrayList<>(2); + HashMap<String, Integer> markerUpdaterOrderMap = new HashMap<>(2); + LinkedList<IConfigurationElement> markerUpdaterSpecificationsLinkedList= new LinkedList<>(); // populate list IExtensionPoint extensionPoint= Platform.getExtensionRegistry().getExtensionPoint(EditorsUI.PLUGIN_ID, "markerUpdaters"); //$NON-NLS-1$ @@ -275,7 +275,7 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl markerUpdaterOrderMap.put(elements[i].getAttribute(ID), new Integer(i)); } //start sorting based on required-updater definition - HashMap markerUpdaterRequiredByOrderMap= new HashMap(2); + HashMap<String, ArrayList<String>> markerUpdaterRequiredByOrderMap= new HashMap<>(2); for (int i= 0; i < elements.length; i++) { // Required marker should execute before other updater markers IConfigurationElement[] requiredUpdaters= elements[i].getChildren("required-updater"); //$NON-NLS-1$ @@ -292,16 +292,16 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl // Updating requiredByUpdaters to identify and log error for cyclic Dependency like A required B, B required C, C required D and D required A // or A requires B and B requires A - ArrayList requiredByUpdaters; + ArrayList<String> requiredByUpdaters; if (markerUpdaterRequiredByOrderMap.get(requiredID) == null) { - requiredByUpdaters= new ArrayList(2); + requiredByUpdaters= new ArrayList<>(2); } else { - requiredByUpdaters= (ArrayList)markerUpdaterRequiredByOrderMap.get(requiredID); + requiredByUpdaters= markerUpdaterRequiredByOrderMap.get(requiredID); } // Build up extended required id list to identify Case 2 if (markerUpdaterRequiredByOrderMap.get(elements[i].getAttribute(ID)) != null) { - ArrayList requiredByList= (ArrayList)markerUpdaterRequiredByOrderMap.get(elements[i].getAttribute(ID)); + ArrayList<String> requiredByList= markerUpdaterRequiredByOrderMap.get(elements[i].getAttribute(ID)); requiredByUpdaters.addAll(requiredByList); } if (requiredByUpdaters.contains(requiredID)) { //log error if marker ID is in the required list of required ID @@ -312,11 +312,11 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl requiredByUpdaters.add(elements[i].getAttribute(ID)); markerUpdaterRequiredByOrderMap.put(requiredID, requiredByUpdaters); - Integer requiredLocation= (Integer)markerUpdaterOrderMap.get(requiredID); - if (requiredLocation.intValue() > ((Integer)markerUpdaterOrderMap.get(elements[i].getAttribute(ID))).intValue()) { // If required marker is not ordered before - int newLocation= (((Integer)markerUpdaterOrderMap.get(elements[i].getAttribute(ID))).intValue() == 0) ? 0 : (((Integer)markerUpdaterOrderMap.get(elements[i] - .getAttribute(ID))).intValue() - 1); - Object requiredMarker= markerUpdaterSpecificationsLinkedList.remove(requiredLocation.intValue()); + Integer requiredLocation= markerUpdaterOrderMap.get(requiredID); + if (requiredLocation.intValue() > markerUpdaterOrderMap.get(elements[i].getAttribute(ID)).intValue()) { // If required marker is not ordered before + int newLocation= (markerUpdaterOrderMap.get(elements[i].getAttribute(ID)).intValue() == 0) ? 0 : (markerUpdaterOrderMap.get(elements[i] + .getAttribute(ID)).intValue() - 1); + IConfigurationElement requiredMarker= markerUpdaterSpecificationsLinkedList.remove(requiredLocation.intValue()); markerUpdaterSpecificationsLinkedList.add(newLocation, requiredMarker); // Put the required location before the marker markerUpdaterOrderMap.put(requiredID, new Integer(newLocation)); markerUpdaterOrderMap.put(elements[i].getAttribute(ID), new Integer(newLocation + 1)); @@ -324,7 +324,7 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl } } } - fMarkerUpdaterSpecifications= new ArrayList(markerUpdaterSpecificationsLinkedList); + fMarkerUpdaterSpecifications= new ArrayList<>(markerUpdaterSpecificationsLinkedList); //end sorting } @@ -364,7 +364,7 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl public Position getMarkerPosition(IMarker marker) { MarkerAnnotation a= getMarkerAnnotation(marker); if (a != null) { - return (Position) getAnnotationMap().get(a); + return getAnnotationMap().get(a); } return null; } @@ -390,12 +390,12 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl } @Override - protected void removeAnnotations(List annotations, boolean fireModelChanged, boolean modelInitiated) { + protected void removeAnnotations(List<? extends Annotation> annotations, boolean fireModelChanged, boolean modelInitiated) { if (annotations != null && annotations.size() > 0) { - List markerAnnotations= new ArrayList(); - for (Iterator e= annotations.iterator(); e.hasNext();) { - Annotation a= (Annotation) e.next(); + List<Annotation> markerAnnotations= new ArrayList<>(); + for (Iterator<? extends Annotation> e= annotations.iterator(); e.hasNext();) { + Annotation a= e.next(); if (a instanceof MarkerAnnotation) markerAnnotations.add(a); @@ -455,8 +455,8 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl */ private void catchupWithMarkers() throws CoreException { - for (Iterator e=getAnnotationIterator(false); e.hasNext();) { - Annotation a= (Annotation) e.next(); + for (Iterator<Annotation> e=getAnnotationIterator(false); e.hasNext();) { + Annotation a= e.next(); if (a instanceof MarkerAnnotation) removeAnnotation(a, false); } @@ -475,7 +475,7 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl * @return the annotation, or <code>null</code> if none */ public final MarkerAnnotation getMarkerAnnotation(IMarker marker) { - Iterator e= getAnnotationIterator(false); + Iterator<Annotation> e= getAnnotationIterator(false); while (e.hasNext()) { Object o= e.next(); if (o instanceof MarkerAnnotation) { @@ -513,9 +513,9 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl * @since 2.0 */ private void checkMarkerUpdaters(IMarker marker) { - List toBeDeleted= new ArrayList(); + List<IConfigurationElement> toBeDeleted= new ArrayList<>(); for (int i= 0; i < fMarkerUpdaterSpecifications.size(); i++) { - IConfigurationElement spec= (IConfigurationElement) fMarkerUpdaterSpecifications.get(i); + IConfigurationElement spec= fMarkerUpdaterSpecifications.get(i); String markerType= spec.getAttribute("markerType"); //$NON-NLS-1$ if (markerType == null || MarkerUtilities.isMarkerType(marker, markerType)) { toBeDeleted.add(spec); @@ -561,7 +561,7 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl boolean isOK= true; for (int i= 0; i < fInstantiatedMarkerUpdaters.size(); i++) { - IMarkerUpdater updater= (IMarkerUpdater) fInstantiatedMarkerUpdaters.get(i); + IMarkerUpdater updater= fInstantiatedMarkerUpdaters.get(i); String markerType= updater.getMarkerType(); if (markerType == null || MarkerUtilities.isMarkerType(marker, markerType)) { @@ -624,12 +624,12 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl try { // update all markers with the positions known by the annotation model - for (Iterator e= getAnnotationIterator(false); e.hasNext();) { + for (Iterator<Annotation> e= getAnnotationIterator(false); e.hasNext();) { Object o= e.next(); if (o instanceof MarkerAnnotation) { MarkerAnnotation a= (MarkerAnnotation) o; IMarker marker= a.getMarker(); - Position position= (Position) annotationMap.get(a); + Position position= annotationMap.get(a); if ( !updateMarker(marker, document, position)) { if ( !fDeletedAnnotations.contains(a)) fDeletedAnnotations.add(a); @@ -655,7 +655,7 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl public void resetMarkers() { // re-initializes the positions from the markers - for (Iterator e= getAnnotationIterator(false); e.hasNext();) { + for (Iterator<Annotation> e= getAnnotationIterator(false); e.hasNext();) { Object o= e.next(); if (o instanceof MarkerAnnotation) { MarkerAnnotation a= (MarkerAnnotation) o; @@ -672,7 +672,7 @@ public abstract class AbstractMarkerAnnotationModel extends AnnotationModel impl } // add the markers of deleted positions back to the annotation model - for (Iterator e= fDeletedAnnotations.iterator(); e.hasNext();) { + for (Iterator<Annotation> e= fDeletedAnnotations.iterator(); e.hasNext();) { Object o= e.next(); if (o instanceof MarkerAnnotation) { MarkerAnnotation a= (MarkerAnnotation) o; diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AddMarkerAction.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AddMarkerAction.java index 82ee3f86c6f..9fbd8b7ab0f 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AddMarkerAction.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AddMarkerAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -123,7 +123,7 @@ public class AddMarkerAction extends TextEditorAction { IResource resource= getResource(); if (resource == null) return; - Map attributes= getInitialAttributes(); + Map<String, Object> attributes= getInitialAttributes(); if (fAskForLabel) { if (!askForLabel(attributes)) return; @@ -134,10 +134,11 @@ public class AddMarkerAction extends TextEditorAction { final Shell shell= getTextEditor().getSite().getShell(); IAdaptable context= new IAdaptable() { + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Class adapter) { + public <T> T getAdapter(Class<T> adapter) { if (adapter == Shell.class) - return shell; + return (T) shell; return null; } }; @@ -168,7 +169,7 @@ public class AddMarkerAction extends TextEditorAction { * @param attributes the attributes map * @return <code>true</code> if a label has been entered */ - protected boolean askForLabel(Map attributes) { + protected boolean askForLabel(Map<String, Object> attributes) { Object o= attributes.get("message"); //$NON-NLS-1$ String proposal= (o instanceof String) ? (String) o : ""; //$NON-NLS-1$ @@ -204,9 +205,9 @@ public class AddMarkerAction extends TextEditorAction { * * @return the attributes the new marker will be initialized with */ - protected Map getInitialAttributes() { + protected Map<String, Object> getInitialAttributes() { - Map attributes= new HashMap(11); + Map<String, Object> attributes= new HashMap<>(11); ITextSelection selection= (ITextSelection) getTextEditor().getSelectionProvider().getSelection(); if (!selection.isEmpty()) { diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AddTaskAction.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AddTaskAction.java index 78acf6a9056..770092691e1 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AddTaskAction.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AddTaskAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2007 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -49,7 +49,7 @@ public class AddTaskAction extends AddMarkerAction { IResource resource= getResource(); if (resource == null) return; - Map attributes= getInitialAttributes(); + Map<String, Object> attributes= getInitialAttributes(); TaskPropertiesDialog dialog= new TaskPropertiesDialog(getTextEditor().getSite().getShell()); dialog.setResource(resource); diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AnnotationPreferenceLookup.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AnnotationPreferenceLookup.java index 17f8a9daea9..bf9cf4d7eaf 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AnnotationPreferenceLookup.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AnnotationPreferenceLookup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -30,7 +30,7 @@ import org.eclipse.ui.internal.texteditor.DelegatingAnnotationPreference; public class AnnotationPreferenceLookup { /** The map between annotation types and annotation preference fragments. */ - private Map fFragments; + private Map<Object, AnnotationPreference> fFragments; /** * Creates a new annotation preference lookup object. @@ -79,8 +79,8 @@ public class AnnotationPreferenceLookup { * @return the defined annotation preference fragment */ public AnnotationPreference getAnnotationPreferenceFragment(String annotationType) { - Map fragments= getPreferenceFragments(); - return (AnnotationPreference) fragments.get(annotationType); + Map<Object, AnnotationPreference> fragments= getPreferenceFragments(); + return fragments.get(annotationType); } /** @@ -98,15 +98,15 @@ public class AnnotationPreferenceLookup { * * @return the map between annotation type names and annotation preference fragments */ - private synchronized Map getPreferenceFragments() { + private synchronized Map<Object, AnnotationPreference> getPreferenceFragments() { if (fFragments == null) { - fFragments= new HashMap(); + fFragments= new HashMap<>(); MarkerAnnotationPreferences p= new MarkerAnnotationPreferences(); - Iterator e= p.getAnnotationPreferenceFragments().iterator(); + Iterator<AnnotationPreference> e= p.getAnnotationPreferenceFragments().iterator(); while (e.hasNext()) { - AnnotationPreference fragment= (AnnotationPreference) e.next(); + AnnotationPreference fragment= e.next(); Object annotationType = fragment.getAnnotationType(); - AnnotationPreference preference= (AnnotationPreference) fFragments.get(annotationType); + AnnotationPreference preference= fFragments.get(annotationType); if (preference == null) fFragments.put(annotationType, fragment); else diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AnnotationTypeLookup.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AnnotationTypeLookup.java index 40dbb02bf7c..adb808e64f5 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AnnotationTypeLookup.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/AnnotationTypeLookup.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -49,8 +49,11 @@ public final class AnnotationTypeLookup { } } - /** The lookup table for marker to annotation type mappings. */ - private Map fMapping; + /** + * The lookup table for marker to annotation type mappings. The value type is a {@link String} + * or a {@code Map<Integer, String>}. + */ + private Map<String, Object> fMapping; /** * Creates a new annotation lookup object. @@ -113,8 +116,9 @@ public final class AnnotationTypeLookup { return (String) value; if (value instanceof Map) { - Map severityMap= (Map) value; - return (String) severityMap.get(new Integer(severity)); + @SuppressWarnings("unchecked") + Map<Integer, String> severityMap= (Map<Integer, String>) value; + return severityMap.get(Integer.valueOf(severity)); } return null; @@ -125,18 +129,19 @@ public final class AnnotationTypeLookup { * annotation types. */ private void initializeMapping() { - fMapping= new HashMap(); - List mappings= getAnnotationTypeMappings(); + fMapping= new HashMap<>(); + List<AnnotationTypeMapping> mappings= getAnnotationTypeMappings(); for (int i= 0, l= mappings.size(); i < l; i++) { - AnnotationTypeMapping atm= (AnnotationTypeMapping) mappings.get(i); + AnnotationTypeMapping atm= mappings.get(i); if (atm.isMarkerSeverityDefined()) { Object severityMap= fMapping.get(atm.fMarkerType); if (!(severityMap instanceof Map)) { - severityMap= new HashMap(); + severityMap= new HashMap<>(); fMapping.put(atm.fMarkerType, severityMap); } - Map map= (Map) severityMap; - map.put(new Integer(atm.fMarkerSeverity), atm.fAnnotationType); + @SuppressWarnings("unchecked") + Map<Integer, String> map= (Map<Integer, String>) severityMap; + map.put(Integer.valueOf(atm.fMarkerSeverity), atm.fAnnotationType); } else { fMapping.put(atm.fMarkerType, atm.fAnnotationType); } @@ -149,8 +154,8 @@ public final class AnnotationTypeLookup { * * @return a list of annotation type mappings */ - private List getAnnotationTypeMappings() { - List annotationTypeMappings= new ArrayList(); + private List<AnnotationTypeMapping> getAnnotationTypeMappings() { + List<AnnotationTypeMapping> annotationTypeMappings= new ArrayList<>(); // read compatibility mode readExtensionPoint(annotationTypeMappings, "markerAnnotationSpecification", "annotationType"); //$NON-NLS-1$ //$NON-NLS-2$ // read new extension point @@ -168,7 +173,7 @@ public final class AnnotationTypeLookup { * @param typeAttributeName the name of attribute specifying the annotation * type */ - private void readExtensionPoint(List annotationTypeMappings, String extensionPointName, String typeAttributeName) { + private void readExtensionPoint(List<AnnotationTypeMapping> annotationTypeMappings, String extensionPointName, String typeAttributeName) { IExtensionPoint extensionPoint= Platform.getExtensionRegistry().getExtensionPoint(EditorsUI.PLUGIN_ID, extensionPointName); if (extensionPoint != null) { IConfigurationElement[] elements= extensionPoint.getConfigurationElements(); diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ChainedPreferenceStore.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ChainedPreferenceStore.java index 5b616c2c24e..6705e52f01d 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ChainedPreferenceStore.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ChainedPreferenceStore.java @@ -41,7 +41,7 @@ public class ChainedPreferenceStore implements IPreferenceStore { private ListenerList fClientListeners= new ListenerList(ListenerList.IDENTITY); /** Listeners on the child preference stores. */ - private List fChildListeners= new ArrayList(); + private List<PropertyChangeListener> fChildListeners= new ArrayList<>(); /** * Listener on the chained preference stores. Forwards only the events @@ -470,9 +470,9 @@ public class ChainedPreferenceStore implements IPreferenceStore { * Register the child listeners on the child preference stores. */ private void registerChildListeners() { - Iterator iter= fChildListeners.iterator(); + Iterator<PropertyChangeListener> iter= fChildListeners.iterator(); while (iter.hasNext()) { - PropertyChangeListener listener= (PropertyChangeListener) iter.next(); + PropertyChangeListener listener= iter.next(); listener.register(); } } @@ -481,9 +481,9 @@ public class ChainedPreferenceStore implements IPreferenceStore { * Unregister the child listeners from the child preference stores. */ private void unregisterChildListeners() { - Iterator iter= fChildListeners.iterator(); + Iterator<PropertyChangeListener> iter= fChildListeners.iterator(); while (iter.hasNext()) { - PropertyChangeListener listener= (PropertyChangeListener) iter.next(); + PropertyChangeListener listener= iter.next(); listener.unregister(); } } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/DefaultMarkerAnnotationAccess.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/DefaultMarkerAnnotationAccess.java index d180e03c4f9..a8466602c4d 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/DefaultMarkerAnnotationAccess.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/DefaultMarkerAnnotationAccess.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -100,10 +100,10 @@ public class DefaultMarkerAnnotationAccess implements IAnnotationAccess, IAnnota * * @since 3.0 */ - private final static Map MAPPING; + private final static Map<String, String> MAPPING; static { - MAPPING= new HashMap(); + MAPPING= new HashMap<>(); MAPPING.put(ERROR_SYSTEM_IMAGE, ISharedImages.IMG_OBJS_ERROR_TSK); MAPPING.put(WARNING_SYSTEM_IMAGE, ISharedImages.IMG_OBJS_WARN_TSK); MAPPING.put(INFO_SYSTEM_IMAGE, ISharedImages.IMG_OBJS_INFO_TSK); @@ -235,8 +235,8 @@ public class DefaultMarkerAnnotationAccess implements IAnnotationAccess, IAnnota // backward compatibility, ignore exceptions, just return default layer try { - Method method= annotation.getClass().getMethod("getLayer", null); //$NON-NLS-1$ - Integer result= (Integer) method.invoke(annotation, null); + Method method= annotation.getClass().getMethod("getLayer"); //$NON-NLS-1$ + Integer result= (Integer) method.invoke(annotation); return result.intValue(); } catch (SecurityException x) { @@ -340,7 +340,7 @@ public class DefaultMarkerAnnotationAccess implements IAnnotationAccess, IAnnota */ public static String getSharedImageName(String symbolicImageName) { Assert.isLegal(symbolicImageName != null); - String sharedImageName= (String)MAPPING.get(symbolicImageName); + String sharedImageName= MAPPING.get(symbolicImageName); Assert.isLegal(sharedImageName != null); return sharedImageName; } @@ -360,7 +360,7 @@ public class DefaultMarkerAnnotationAccess implements IAnnotationAccess, IAnnota if (annotation instanceof AnnotationBag) { AnnotationBag bag= (AnnotationBag)annotation; if (!bag.isEmpty()) - annotation= (Annotation)bag.iterator().next(); + annotation= bag.iterator().next(); } ImageRegistry registry= EditorsPlugin.getDefault().getImageRegistry(); diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/DocumentProviderRegistry.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/DocumentProviderRegistry.java index f15e9a6b612..b0dc84bbc75 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/DocumentProviderRegistry.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/DocumentProviderRegistry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -69,11 +69,11 @@ public class DocumentProviderRegistry { /** The mapping between name extensions and configuration elements. */ - private Map fExtensionMapping= new HashMap(); + private Map<String, Set<IConfigurationElement>> fExtensionMapping= new HashMap<>(); /** The mapping between editor input type names and configuration elements. */ - private Map fInputTypeMapping= new HashMap(); + private Map<String, Set<IConfigurationElement>> fInputTypeMapping= new HashMap<>(); /** The mapping between configuration elements and instantiated document providers. */ - private Map fInstances= new HashMap(); + private Map<IConfigurationElement, IDocumentProvider> fInstances= new HashMap<>(); /** @@ -93,16 +93,16 @@ public class DocumentProviderRegistry { * @param element the configuration element * @param attributeName the attribute name */ - private void read(Map map, IConfigurationElement element, String attributeName) { + private void read(Map<String, Set<IConfigurationElement>> map, IConfigurationElement element, String attributeName) { String value= element.getAttribute(attributeName); if (value != null) { StringTokenizer tokenizer= new StringTokenizer(value, ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { String token= tokenizer.nextToken().trim(); - Set s= (Set) map.get(token); + Set<IConfigurationElement> s= map.get(token); if (s == null) { - s= new HashSet(); + s= new HashSet<>(); map.put(token, s); } s.add(element); @@ -144,7 +144,7 @@ public class DocumentProviderRegistry { * @return the document provider for the given entry */ private IDocumentProvider getDocumentProvider(IConfigurationElement entry) { - IDocumentProvider provider= (IDocumentProvider) fInstances.get(entry); + IDocumentProvider provider= fInstances.get(entry); if (provider == null) { try { provider= (IDocumentProvider) entry.createExecutableExtension("class"); //$NON-NLS-1$ @@ -161,10 +161,10 @@ public class DocumentProviderRegistry { * @param set the set * @return the first configuration element in the set or <code>null</code> if none */ - private IConfigurationElement selectConfigurationElement(Set set) { + private IConfigurationElement selectConfigurationElement(Set<IConfigurationElement> set) { if (set != null && !set.isEmpty()) { - Iterator e= set.iterator(); - return (IConfigurationElement) e.next(); + Iterator<IConfigurationElement> e= set.iterator(); + return e.next(); } return null; } @@ -177,7 +177,7 @@ public class DocumentProviderRegistry { */ public IDocumentProvider getDocumentProvider(String extension) { - Set set= (Set) fExtensionMapping.get(extension); + Set<IConfigurationElement> set= fExtensionMapping.get(extension); if (set != null) { IConfigurationElement entry= selectConfigurationElement(set); return getDocumentProvider(entry); @@ -192,11 +192,11 @@ public class DocumentProviderRegistry { * @param type the type * @return a list containing the super class hierarchy */ - private List computeClassList(Class type) { + private List<Class<?>> computeClassList(Class<?> type) { - List result= new ArrayList(); + List<Class<?>> result= new ArrayList<>(); - Class c= type; + Class<?> c= type; while (c != null) { result.add(c); c= c.getSuperclass(); @@ -213,14 +213,14 @@ public class DocumentProviderRegistry { * @param classes a list of {@link java.lang.Class} objects * @return a list with elements of type <code>Class</code> */ - private List computeInterfaceList(List classes) { + private List<Class<?>> computeInterfaceList(List<Class<?>> classes) { - List result= new ArrayList(4); - Hashtable visited= new Hashtable(4); + List<Class<?>> result= new ArrayList<>(4); + Hashtable<Class<?>, Class<?>> visited= new Hashtable<>(4); - Iterator e= classes.iterator(); + Iterator<Class<?>> e= classes.iterator(); while (e.hasNext()) { - Class c= (Class) e.next(); + Class<?> c= e.next(); computeInterfaceList(c.getInterfaces(), result, visited); } @@ -235,12 +235,12 @@ public class DocumentProviderRegistry { * @param result the result list * @param visited map of visited interfaces */ - private void computeInterfaceList(Class[] interfaces, List result, Hashtable visited) { + private void computeInterfaceList(Class<?>[] interfaces, List<Class<?>> result, Hashtable<Class<?>, Class<?>> visited) { - List toBeVisited= new ArrayList(interfaces.length); + List<Class<?>> toBeVisited= new ArrayList<>(interfaces.length); for (int i= 0; i < interfaces.length; i++) { - Class iface= interfaces[i]; + Class<?> iface= interfaces[i]; if (visited.get(iface) == null) { visited.put(iface, iface); result.add(iface); @@ -248,9 +248,9 @@ public class DocumentProviderRegistry { } } - Iterator e= toBeVisited.iterator(); + Iterator<Class<?>> e= toBeVisited.iterator(); while(e.hasNext()) { - Class iface= (Class) e.next(); + Class<?> iface= e.next(); computeInterfaceList(iface.getInterfaces(), result, visited); } } @@ -262,11 +262,11 @@ public class DocumentProviderRegistry { * @param classes a list of {@link java.lang.Class} objects * @return an input type mapping or <code>null</code> */ - private Object getFirstInputTypeMapping(List classes) { - Iterator e= classes.iterator(); + private Set<IConfigurationElement> getFirstInputTypeMapping(List<Class<?>> classes) { + Iterator<Class<?>> e= classes.iterator(); while (e.hasNext()) { - Class c= (Class) e.next(); - Object mapping= fInputTypeMapping.get(c.getName()); + Class<?> c= e.next(); + Set<IConfigurationElement> mapping= fInputTypeMapping.get(c.getName()); if (mapping != null) return mapping; } @@ -281,16 +281,16 @@ public class DocumentProviderRegistry { * @param type a {@link java.lang.Class} object * @return an input type mapping or <code>null</code> */ - private Object findInputTypeMapping(Class type) { + private Set<IConfigurationElement> findInputTypeMapping(Class<?> type) { if (type == null) return null; - Object mapping= fInputTypeMapping.get(type.getName()); + Set<IConfigurationElement> mapping= fInputTypeMapping.get(type.getName()); if (mapping != null) return mapping; - List classList= computeClassList(type); + List<Class<?>> classList= computeClassList(type); mapping= getFirstInputTypeMapping(classList); if (mapping != null) return mapping; @@ -313,7 +313,7 @@ public class DocumentProviderRegistry { provider= getDocumentProvider(file.getFileExtension()); if (provider == null) { - Set set= (Set) findInputTypeMapping(editorInput.getClass()); + Set<IConfigurationElement> set= findInputTypeMapping(editorInput.getClass()); if (set != null) { IConfigurationElement entry= selectConfigurationElement(set); provider= getDocumentProvider(entry); diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerAnnotation.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerAnnotation.java index d4ec1e35f0f..5fcf71bddf6 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerAnnotation.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerAnnotation.java @@ -57,7 +57,7 @@ public class MarkerAnnotation extends SimpleMarkerAnnotation implements IQuickFi public final static int PROBLEM_LAYER= 5; /** Internal image registry. */ - private static Map fgImageRegistry; + private static Map<ImageDescriptor, Image> fgImageRegistry; /** * Returns an image for the given display as specified by the given image @@ -72,8 +72,8 @@ public class MarkerAnnotation extends SimpleMarkerAnnotation implements IQuickFi */ @Deprecated protected static Image getImage(Display display, ImageDescriptor descriptor) { - Map map= getImageRegistry(display); - Image image= (Image) map.get(descriptor); + Map<ImageDescriptor, Image> map= getImageRegistry(display); + Image image= map.get(descriptor); if (image == null) { image= descriptor.createImage(); map.put(descriptor, image); @@ -92,18 +92,18 @@ public class MarkerAnnotation extends SimpleMarkerAnnotation implements IQuickFi * {@link org.eclipse.jface.text.source.IAnnotationPresentation} */ @Deprecated - protected static Map getImageRegistry(Display display) { + protected static Map<ImageDescriptor, Image> getImageRegistry(Display display) { if (fgImageRegistry == null) { - fgImageRegistry= new HashMap(); + fgImageRegistry= new HashMap<>(); display.disposeExec(new Runnable() { @Override public void run() { if (fgImageRegistry != null) { - Map map= fgImageRegistry; + Map<ImageDescriptor, Image> map= fgImageRegistry; fgImageRegistry= null; - Iterator e= map.values().iterator(); + Iterator<Image> e= map.values().iterator(); while (e.hasNext()) { - Image image= (Image) e.next(); + Image image= e.next(); if (!image.isDisposed()) image.dispose(); } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerAnnotationPreferences.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerAnnotationPreferences.java index 17b7e5a3dab..0048f909ef2 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerAnnotationPreferences.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerAnnotationPreferences.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -57,9 +57,9 @@ public class MarkerAnnotationPreferences { boolean ignoreQuickDiffPrefPage= store.getBoolean(AbstractDecoratedTextEditorPreferenceConstants.USE_QUICK_DIFF_PREFERENCE_PAGE); MarkerAnnotationPreferences preferences= EditorsPlugin.getDefault().getMarkerAnnotationPreferences(); - Iterator e= preferences.getAnnotationPreferences().iterator(); + Iterator<AnnotationPreference> e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); if (ignoreAnnotationsPrefPage && info.isIncludeOnPreferencePage() && isComplete(info)) continue; @@ -111,9 +111,9 @@ public class MarkerAnnotationPreferences { store.putValue(AbstractDecoratedTextEditorPreferenceConstants.USE_ANNOTATIONS_PREFERENCE_PAGE, Boolean.toString(true)); MarkerAnnotationPreferences preferences= EditorsPlugin.getDefault().getMarkerAnnotationPreferences(); - Iterator e= preferences.getAnnotationPreferences().iterator(); + Iterator<AnnotationPreference> e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); // Only reset annotations shown on Annotations preference page if (!info.isIncludeOnPreferencePage() || !isComplete(info)) @@ -160,9 +160,9 @@ public class MarkerAnnotationPreferences { store.putValue(AbstractDecoratedTextEditorPreferenceConstants.USE_QUICK_DIFF_PREFERENCE_PAGE, Boolean.toString(true)); MarkerAnnotationPreferences preferences= EditorsPlugin.getDefault().getMarkerAnnotationPreferences(); - Iterator e= preferences.getAnnotationPreferences().iterator(); + Iterator<AnnotationPreference> e= preferences.getAnnotationPreferences().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); // Only reset annotations shown on Quick Diff preference page @@ -192,7 +192,7 @@ public class MarkerAnnotationPreferences { private static final class AccessChecker extends SecurityManager { @Override - public Class[] getClassContext() { + public Class<?>[] getClassContext() { return super.getClassContext(); } } @@ -203,7 +203,7 @@ public class MarkerAnnotationPreferences { * @since 3.0 */ private static void checkAccess() throws IllegalStateException { - Class[] elements = new AccessChecker().getClassContext(); + Class<?>[] elements = new AccessChecker().getClassContext(); if (!(elements[3].equals(EditorsUI.class) || elements[4].equals(EditorsUI.class))) throw new IllegalStateException(); @@ -211,9 +211,9 @@ public class MarkerAnnotationPreferences { /** The list of extension fragments. */ - private List/*<AnnotationPreference>*/ fFragments; + private List<AnnotationPreference> fFragments; /** The list of extensions. */ - private List/*<AnnotationPreference>*/ fPreferences; + private List<AnnotationPreference> fPreferences; /** * Creates a new marker annotation preferences to access @@ -239,9 +239,8 @@ public class MarkerAnnotationPreferences { * Returns all extensions provided for the <code>markerAnnotationSpecification</code> extension point. * * @return all extensions provided for the <code>markerAnnotationSpecification</code> extension point - * (element type: {@link AnnotationPreference}) */ - public List getAnnotationPreferences() { + public List<AnnotationPreference> getAnnotationPreferences() { if (fPreferences == null) initialize(); return fPreferences; @@ -254,9 +253,9 @@ public class MarkerAnnotationPreferences { * change the presentation part. * * @return all extensions provided for the <code>markerAnnotationSpecification</code> - * extension point including fragments (element type: {@link AnnotationPreference}) + * extension point including fragments */ - public List getAnnotationPreferenceFragments() { + public List<AnnotationPreference> getAnnotationPreferenceFragments() { if (fFragments == null) initialize(); return fFragments; @@ -281,8 +280,8 @@ public class MarkerAnnotationPreferences { private void initializeSharedMakerAnnotationPreferences() { // initialize lists - indicates that the initialization happened - fFragments= new ArrayList(2); - fPreferences= new ArrayList(2); + fFragments= new ArrayList<>(2); + fPreferences= new ArrayList<>(2); // populate list IExtensionPoint extensionPoint= Platform.getExtensionRegistry().getExtensionPoint(EditorsUI.PLUGIN_ID, "markerAnnotationSpecification"); //$NON-NLS-1$ @@ -305,13 +304,13 @@ public class MarkerAnnotationPreferences { * @return the cloned list of cloned annotation preferences * @since 3.1 */ - private List cloneAnnotationPreferences(List annotationPreferences) { + private List<AnnotationPreference> cloneAnnotationPreferences(List<AnnotationPreference> annotationPreferences) { if (annotationPreferences == null) return null; - List clone= new ArrayList(annotationPreferences.size()); - Iterator iter= annotationPreferences.iterator(); + List<AnnotationPreference> clone= new ArrayList<>(annotationPreferences.size()); + Iterator<AnnotationPreference> iter= annotationPreferences.iterator(); while (iter.hasNext()) - clone.add(clone(((AnnotationPreference)iter.next()))); + clone.add(clone(iter.next())); return clone; } diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerRulerAction.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerRulerAction.java index 2c0de048e7e..033b413a032 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerRulerAction.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerRulerAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -77,7 +77,7 @@ public class MarkerRulerAction extends ResourceAction implements IUpdate { /** The of the marker to be created/removed. */ private String fMarkerType; /** The cached list of markers covering a particular vertical ruler position. */ - private List fMarkers; + private List<IMarker> fMarkers; /** The flag indicating whether user interaction is required. */ private boolean fAskForLabel; /** The action's resource bundle. */ @@ -212,10 +212,10 @@ public class MarkerRulerAction extends ResourceAction implements IUpdate { * @return boolean <code>true</code> if they are all editable * @since 3.2 */ - private boolean markersUserEditable(List markers) { - Iterator iter= markers.iterator(); + private boolean markersUserEditable(List<IMarker> markers) { + Iterator<IMarker> iter= markers.iterator(); while (iter.hasNext()) { - if (!isUserEditable((IMarker)iter.next())) + if (!isUserEditable(iter.next())) return false; } return true; @@ -333,9 +333,9 @@ public class MarkerRulerAction extends ResourceAction implements IUpdate { * * @return all a list of markers which include the ruler's line of activity */ - protected List getMarkers() { + protected List<IMarker> getMarkers() { - List markers= new ArrayList(); + List<IMarker> markers= new ArrayList<>(); IResource resource= getResource(); IDocument document= getDocument(); @@ -367,7 +367,7 @@ public class MarkerRulerAction extends ResourceAction implements IUpdate { IResource resource= getResource(); if (resource == null) return; - Map attributes= getInitialAttributes(); + Map<String, Object> attributes= getInitialAttributes(); if (fAskForLabel) { if (!askForLabel(attributes)) return; @@ -380,8 +380,8 @@ public class MarkerRulerAction extends ResourceAction implements IUpdate { * * @param markers the markers to be deleted */ - protected void removeMarkers(final List markers) { - IMarker[] markersArray= (IMarker[])markers.toArray(new IMarker[markers.size()]); + protected void removeMarkers(final List<? extends IMarker> markers) { + IMarker[] markersArray= markers.toArray(new IMarker[markers.size()]); execute(new DeleteMarkersOperation(markersArray, getOperationName())); } @@ -394,7 +394,7 @@ public class MarkerRulerAction extends ResourceAction implements IUpdate { * @param attributes the map of attributes * @return <code>true</code> if the map of attributes has successfully been initialized */ - protected boolean askForLabel(Map attributes) { + protected boolean askForLabel(Map<String, Object> attributes) { Object o= attributes.get("message"); //$NON-NLS-1$ String proposal= (o instanceof String) ? (String) o : ""; //$NON-NLS-1$ @@ -427,12 +427,11 @@ public class MarkerRulerAction extends ResourceAction implements IUpdate { * Returns the attributes with which a newly created marker will be * initialized. * - * @return the initial marker attributes (key type: <code>String</code>, value type: - * <code>Object</code>) + * @return the initial marker attributes */ - protected Map getInitialAttributes() { + protected Map<String, Object> getInitialAttributes() { - Map attributes= new HashMap(11); + Map<String, Object> attributes= new HashMap<>(11); IDocumentProvider provider= fTextEditor.getDocumentProvider(); IDocument document= provider.getDocument(fTextEditor.getEditorInput()); @@ -503,10 +502,11 @@ public class MarkerRulerAction extends ResourceAction implements IUpdate { private void execute(IUndoableOperation operation) { final Shell shell= getTextEditor().getSite().getShell(); IAdaptable context= new IAdaptable() { + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Class adapter) { + public <T> T getAdapter(Class<T> adapter) { if (adapter == Shell.class) - return shell; + return (T) shell; return null; } }; diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerUtilities.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerUtilities.java index c02d4371b3b..2ea3f56a8b3 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerUtilities.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/MarkerUtilities.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -53,11 +53,11 @@ public final class MarkerUtilities { */ private static class MarkerTypeHierarchy { - private Map fTypeMap; - private Map fSuperTypesCache= new HashMap(); + private Map<String, String[]> fTypeMap; + private Map<String, String[]> fSuperTypesCache= new HashMap<>(); public String[] getSuperTypes(String typeName) { - String[] cachedTypes= (String[]) fSuperTypesCache.get(typeName); + String[] cachedTypes= fSuperTypesCache.get(typeName); if (cachedTypes == null) { cachedTypes= computeSuperTypes(typeName); fSuperTypesCache.put(typeName, cachedTypes); @@ -66,11 +66,11 @@ public final class MarkerUtilities { } private String[] computeSuperTypes(String typeName) { - ArrayList types= new ArrayList(); + ArrayList<String> types= new ArrayList<>(); appendAll(types, getDirectSuperTypes(typeName)); int index= 0; while (index < types.size()) { - String type= (String) types.get(index++); + String type= types.get(index++); appendAll(types, getDirectSuperTypes(type)); } @@ -80,33 +80,33 @@ public final class MarkerUtilities { } private String[] getDirectSuperTypes(String typeName) { - return (String[]) getTypeMap().get(typeName); + return getTypeMap().get(typeName); } - private void appendAll(List list, Object[] objects) { + private <T> void appendAll(List<T> list, T[] objects) { if (objects == null) return; for (int i= 0; i < objects.length; i++) { - Object o= objects[i]; + T o= objects[i]; if (!list.contains(o)) list.add(o); } } - private Map getTypeMap() { + private Map<String, String[]> getTypeMap() { if (fTypeMap == null) fTypeMap= readTypes(); return fTypeMap; } - private Map readTypes() { - HashMap allTypes= new HashMap(); + private Map<String, String[]> readTypes() { + HashMap<String, String[]> allTypes= new HashMap<>(); IExtensionPoint point= Platform.getExtensionRegistry().getExtensionPoint(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_MARKERS); if (point != null) { IExtension[] extensions = point.getExtensions(); for (int i= 0; i < extensions.length; i++) { IExtension extension= extensions[i]; - ArrayList types= new ArrayList(); + ArrayList<String> types= new ArrayList<>(); IConfigurationElement[] configElements= extension.getConfigurationElements(); for (int j= 0; j < configElements.length; ++j) { IConfigurationElement element= configElements[j]; @@ -287,12 +287,11 @@ public final class MarkerUtilities { * Sets the ending character offset in the given map using the standard * marker attribute name as the key. * - * @param map the map (key type: <code>String</code>, value type: - * <code>Object</code>) + * @param map the map * @param charEnd the ending character offset * @see IMarker#CHAR_END */ - public static void setCharEnd(Map map, int charEnd) { + public static void setCharEnd(Map<String, Object> map, int charEnd) { map.put(IMarker.CHAR_END, new Integer(charEnd)); } @@ -312,12 +311,11 @@ public final class MarkerUtilities { * Sets the starting character offset in the given map using the standard * marker attribute name as the key. * - * @param map the map (key type: <code>String</code>, value type: - * <code>Object</code>) + * @param map the map * @param charStart the starting character offset * @see IMarker#CHAR_START */ - public static void setCharStart(Map map, int charStart) { + public static void setCharStart(Map<String, Object> map, int charStart) { map.put(IMarker.CHAR_START, new Integer(charStart)); } @@ -353,12 +351,11 @@ public final class MarkerUtilities { * Sets the line number in the given map using the standard marker attribute * name as the key. * - * @param map the map (key type: <code>String</code>, value type: - * <code>Object</code>) + * @param map the map * @param lineNum the line number * @see IMarker#LINE_NUMBER */ - public static void setLineNumber(Map map, int lineNum) { + public static void setLineNumber(Map<String, Object> map, int lineNum) { map.put(IMarker.LINE_NUMBER, new Integer(lineNum)); } @@ -366,12 +363,11 @@ public final class MarkerUtilities { * Sets the message in the given map using the standard marker attribute name * as the key. * - * @param map the map (key type: <code>String</code>, value type: - * <code>Object</code>) + * @param map the map * @param message the message * @see IMarker#MESSAGE */ - public static void setMessage(Map map, String message) { + public static void setMessage(Map<String, Object> map, String message) { map.put(IMarker.MESSAGE, message); } @@ -381,13 +377,12 @@ public final class MarkerUtilities { * This method modifies the workspace (progress is not reported to the user).</p> * * @param resource the resource - * @param attributes the attribute map (key type: <code>String</code>, - * value type: <code>Object</code>) + * @param attributes the attribute map * @param markerType the type of marker * @throws CoreException if this method fails * @see IResource#createMarker(java.lang.String) */ - public static void createMarker(final IResource resource, final Map attributes, final String markerType) throws CoreException { + public static void createMarker(final IResource resource, final Map<String, Object> attributes, final String markerType) throws CoreException { IWorkspaceRunnable r= new IWorkspaceRunnable() { @Override diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ResourceMarkerAnnotationModel.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ResourceMarkerAnnotationModel.java index 819ee7a70a7..ea352062831 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ResourceMarkerAnnotationModel.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/ResourceMarkerAnnotationModel.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -27,6 +27,7 @@ import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.jface.text.Position; +import org.eclipse.jface.text.source.Annotation; @@ -116,8 +117,8 @@ public class ResourceMarkerAnnotationModel extends AbstractMarkerAnnotationModel * @param markerDeltas the array of marker deltas */ private void batchedUpdate(IMarkerDelta[] markerDeltas) { - HashSet removedMarkers= new HashSet(markerDeltas.length); - HashSet modifiedMarkers= new HashSet(markerDeltas.length); + HashSet<IMarker> removedMarkers= new HashSet<>(markerDeltas.length); + HashSet<IMarker> modifiedMarkers= new HashSet<>(markerDeltas.length); for (int i= 0; i < markerDeltas.length; i++) { IMarkerDelta delta= markerDeltas[i]; @@ -137,7 +138,7 @@ public class ResourceMarkerAnnotationModel extends AbstractMarkerAnnotationModel if (modifiedMarkers.isEmpty() && removedMarkers.isEmpty()) return; - Iterator e= getAnnotationIterator(false); + Iterator<Annotation> e= getAnnotationIterator(false); while (e.hasNext()) { Object o= e.next(); if (o instanceof MarkerAnnotation) { @@ -161,9 +162,9 @@ public class ResourceMarkerAnnotationModel extends AbstractMarkerAnnotationModel } } - Iterator iter= modifiedMarkers.iterator(); + Iterator<IMarker> iter= modifiedMarkers.iterator(); while (iter.hasNext()) - addMarkerAnnotation((IMarker)iter.next()); + addMarkerAnnotation(iter.next()); } @Override diff --git a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/SelectMarkerRulerAction.java b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/SelectMarkerRulerAction.java index d2db5b778da..c526d80b5d4 100644 --- a/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/SelectMarkerRulerAction.java +++ b/org.eclipse.ui.editors/src/org/eclipse/ui/texteditor/SelectMarkerRulerAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -190,7 +190,7 @@ public class SelectMarkerRulerAction extends ResourceAction implements IUpdate { * @param markers the list of markers to choose from * @return the chosen marker or <code>null</code> if none of the given markers has a marker annotation in the model */ - protected final IMarker chooseMarker(List markers) { + protected final IMarker chooseMarker(List<? extends IMarker> markers) { AbstractMarkerAnnotationModel model= getAnnotationModel(); IAnnotationAccessExtension access= getAnnotationAccessExtension(); @@ -198,9 +198,9 @@ public class SelectMarkerRulerAction extends ResourceAction implements IUpdate { IMarker marker= null; int maxLayer= 0; - Iterator iter= markers.iterator(); + Iterator<? extends IMarker> iter= markers.iterator(); while (iter.hasNext()) { - IMarker m= (IMarker) iter.next(); + IMarker m= iter.next(); Annotation a= model.getMarkerAnnotation(m); if (a != null) { if (access == null) { @@ -363,37 +363,36 @@ public class SelectMarkerRulerAction extends ResourceAction implements IUpdate { * Returns all markers which include the ruler's line of activity. * * @return an unmodifiable list with all markers which include the ruler's line of activity - * (element type: {@link IMarker}) */ - protected final List getMarkers() { + protected final List<IMarker> getMarkers() { final IResource resource= getResource(); if (resource == null || !resource.exists()) - return Collections.EMPTY_LIST; + return Collections.emptyList(); final IDocument document= getDocument(); if (document == null) - return Collections.EMPTY_LIST; + return Collections.emptyList(); final AbstractMarkerAnnotationModel model= getAnnotationModel(); if (model == null) - return Collections.EMPTY_LIST; + return Collections.emptyList(); final IMarker[] allMarkers; try { allMarkers= resource.findMarkers(null, true, IResource.DEPTH_ZERO); } catch (CoreException x) { handleCoreException(x, TextEditorMessages.SelectMarkerRulerAction_getMarker); - return Collections.EMPTY_LIST; + return Collections.emptyList(); } if (allMarkers.length == 0) - return Collections.EMPTY_LIST; + return Collections.emptyList(); final int activeLine= fRuler.getLineOfLastMouseButtonActivity(); if (activeLine == -1) - return Collections.EMPTY_LIST; + return Collections.emptyList(); - Iterator it; + Iterator<Annotation> it; try { IRegion line= document.getLineInformation(activeLine); it= model.getAnnotationIterator(line.getOffset(), line.getLength() + 1, true, true); @@ -404,14 +403,14 @@ public class SelectMarkerRulerAction extends ResourceAction implements IUpdate { it= model.getAnnotationIterator(); } - List markers= null; + List<IMarker> markers= null; while (it.hasNext()) { - Annotation annotation= (Annotation) it.next(); + Annotation annotation= it.next(); if (annotation instanceof MarkerAnnotation) { Position position= model.getPosition(annotation); if (includesLine(position, document, activeLine)) { if (markers == null) - markers= new ArrayList(10); + markers= new ArrayList<>(10); markers.add(((MarkerAnnotation) annotation).getMarker()); } @@ -419,16 +418,15 @@ public class SelectMarkerRulerAction extends ResourceAction implements IUpdate { } if (markers == null) - return Collections.EMPTY_LIST; + return Collections.emptyList(); return Collections.unmodifiableList(markers); } /** - * Returns all markers which include the ruler's line of activity. + * Returns <code>true</code> iff there are any markers which include the ruler's line of activity. * - * @return an unmodifiable list with all markers which include the ruler's line of activity - * (element type: {@link IMarker}) + * @return <code>true</code> iff there are any markers which include the ruler's line of activity. * @since 3.3 */ protected final boolean hasMarkers() { @@ -459,7 +457,7 @@ public class SelectMarkerRulerAction extends ResourceAction implements IUpdate { if (activeLine == -1) return false; - Iterator it; + Iterator<Annotation> it; try { IRegion line= document.getLineInformation(activeLine); it= model.getAnnotationIterator(line.getOffset(), line.getLength() + 1, true, true); @@ -469,7 +467,7 @@ public class SelectMarkerRulerAction extends ResourceAction implements IUpdate { } while (it.hasNext()) { - Annotation annotation= (Annotation) it.next(); + Annotation annotation= it.next(); if (annotation instanceof MarkerAnnotation) { Position position= model.getPosition(annotation); if (includesLine(position, document, activeLine)) { diff --git a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaContentOutlinePage.java b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaContentOutlinePage.java index 78ec2f00c4c..f6c19201b4c 100644 --- a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaContentOutlinePage.java +++ b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaContentOutlinePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -69,7 +69,7 @@ public class JavaContentOutlinePage extends ContentOutlinePage { protected final static String SEGMENTS= "__java_segments"; //$NON-NLS-1$ protected IPositionUpdater fPositionUpdater= new DefaultPositionUpdater(SEGMENTS); - protected List fContent= new ArrayList(10); + protected List<Segment> fContent= new ArrayList<>(10); protected void parse(IDocument document) { diff --git a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaEditor.java b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaEditor.java index 7153eb98e2c..69df362ec05 100644 --- a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaEditor.java +++ b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -189,19 +189,20 @@ public class JavaEditor extends TextEditor { * @param required the required type * @return an adapter for the required type or <code>null</code> */ + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Class required) { + public <T> T getAdapter(Class<T> required) { if (IContentOutlinePage.class.equals(required)) { if (fOutlinePage == null) { fOutlinePage= new JavaContentOutlinePage(getDocumentProvider(), this); if (getEditorInput() != null) fOutlinePage.setInput(getEditorInput()); } - return fOutlinePage; + return (T) fOutlinePage; } if (fProjectionSupport != null) { - Object adapter= fProjectionSupport.getAdapter(getSourceViewer(), required); + T adapter= fProjectionSupport.getAdapter(getSourceViewer(), required); if (adapter != null) return adapter; } diff --git a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaPartitionScanner.java b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaPartitionScanner.java index 66c0fc143e8..404a1c5fd08 100644 --- a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaPartitionScanner.java +++ b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/JavaPartitionScanner.java @@ -83,7 +83,7 @@ public class JavaPartitionScanner extends RuleBasedPartitionScanner { IToken javaDoc= new Token(JAVA_DOC); IToken comment= new Token(JAVA_MULTILINE_COMMENT); - List rules= new ArrayList(); + List<IPredicateRule> rules= new ArrayList<>(); // Add rule for single line comments. rules.add(new EndOfLineRule("//", Token.UNDEFINED)); //$NON-NLS-1$ diff --git a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/java/JavaCodeScanner.java b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/java/JavaCodeScanner.java index e3a0c413c45..1f22d8bd43d 100644 --- a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/java/JavaCodeScanner.java +++ b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/java/JavaCodeScanner.java @@ -52,7 +52,7 @@ public class JavaCodeScanner extends RuleBasedScanner { IToken comment= new Token(new TextAttribute(provider.getColor(JavaColorProvider.SINGLE_LINE_COMMENT))); IToken other= new Token(new TextAttribute(provider.getColor(JavaColorProvider.DEFAULT))); - List rules= new ArrayList(); + List<IRule> rules= new ArrayList<>(); // Add rule for single line comments. rules.add(new EndOfLineRule("//", comment)); //$NON-NLS-1$ diff --git a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/javadoc/JavaDocScanner.java b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/javadoc/JavaDocScanner.java index 85e6af4b351..44c25024ecc 100644 --- a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/javadoc/JavaDocScanner.java +++ b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/javadoc/JavaDocScanner.java @@ -64,7 +64,7 @@ public class JavaDocScanner extends RuleBasedScanner { IToken tag= new Token(new TextAttribute(provider.getColor(JavaColorProvider.JAVADOC_TAG))); IToken link= new Token(new TextAttribute(provider.getColor(JavaColorProvider.JAVADOC_LINK))); - List list= new ArrayList(); + List<IRule> list= new ArrayList<>(); // Add rule for tags. list.add(new SingleLineRule("<", ">", tag)); //$NON-NLS-2$ //$NON-NLS-1$ diff --git a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/util/JavaColorProvider.java b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/util/JavaColorProvider.java index d3e16d81c31..fd69adf7168 100644 --- a/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/util/JavaColorProvider.java +++ b/org.eclipse.ui.examples.javaeditor/Eclipse Java Editor Example/org/eclipse/ui/examples/javaeditor/util/JavaColorProvider.java @@ -35,15 +35,15 @@ public class JavaColorProvider { public static final RGB JAVADOC_LINK= new RGB(128, 128, 128); public static final RGB JAVADOC_DEFAULT= new RGB(0, 128, 128); - protected Map fColorTable= new HashMap(10); + protected Map<RGB, Color> fColorTable= new HashMap<>(10); /** * Release all of the color resources held onto by the receiver. */ public void dispose() { - Iterator e= fColorTable.values().iterator(); + Iterator<Color> e= fColorTable.values().iterator(); while (e.hasNext()) - ((Color) e.next()).dispose(); + e.next().dispose(); } /** @@ -54,7 +54,7 @@ public class JavaColorProvider { * @return the color stored in the color table for the given RGB value */ public Color getColor(RGB rgb) { - Color color= (Color) fColorTable.get(rgb); + Color color= fColorTable.get(rgb); if (color == null) { color= new Color(Display.getCurrent(), rgb); fColorTable.put(rgb, color); diff --git a/org.eclipse.ui.examples.javaeditor/Template Editor Example/org/eclipse/ui/examples/templateeditor/editors/ColorManager.java b/org.eclipse.ui.examples.javaeditor/Template Editor Example/org/eclipse/ui/examples/templateeditor/editors/ColorManager.java index 0757efeecd9..2ccf6461e56 100644 --- a/org.eclipse.ui.examples.javaeditor/Template Editor Example/org/eclipse/ui/examples/templateeditor/editors/ColorManager.java +++ b/org.eclipse.ui.examples.javaeditor/Template Editor Example/org/eclipse/ui/examples/templateeditor/editors/ColorManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -20,15 +20,15 @@ import org.eclipse.swt.widgets.Display; public class ColorManager { - protected Map fColorTable = new HashMap(10); + protected Map<RGB, Color> fColorTable = new HashMap<>(10); public void dispose() { - Iterator e = fColorTable.values().iterator(); + Iterator<Color> e = fColorTable.values().iterator(); while (e.hasNext()) - ((Color) e.next()).dispose(); + e.next().dispose(); } public Color getColor(RGB rgb) { - Color color = (Color) fColorTable.get(rgb); + Color color = fColorTable.get(rgb); if (color == null) { color = new Color(Display.getCurrent(), rgb); fColorTable.put(rgb, color); diff --git a/org.eclipse.ui.examples.javaeditor/Template Editor Example/org/eclipse/ui/examples/templateeditor/template/AntVariableResolver.java b/org.eclipse.ui.examples.javaeditor/Template Editor Example/org/eclipse/ui/examples/templateeditor/template/AntVariableResolver.java index f94551325e7..9e1623a1684 100644 --- a/org.eclipse.ui.examples.javaeditor/Template Editor Example/org/eclipse/ui/examples/templateeditor/template/AntVariableResolver.java +++ b/org.eclipse.ui.examples.javaeditor/Template Editor Example/org/eclipse/ui/examples/templateeditor/template/AntVariableResolver.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,11 +25,11 @@ public class AntVariableResolver extends TemplateVariableResolver { protected String[] resolveAll(TemplateContext context) { String[] proposals= new String[] { "${srcDir}", "${dstDir}" }; //$NON-NLS-1$ //$NON-NLS-2$ - Arrays.sort(proposals, new Comparator() { + Arrays.sort(proposals, new Comparator<String>() { @Override - public int compare(Object o1, Object o2) { - return getCommonPrefixLength(getType(), (String) o2) - getCommonPrefixLength(getType(), (String) o1); + public int compare(String o1, String o2) { + return getCommonPrefixLength(getType(), o2) - getCommonPrefixLength(getType(), o1); } private int getCommonPrefixLength(String type, String var) { diff --git a/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/HippieCompletionTest.java b/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/HippieCompletionTest.java index 3d335947217..56df24cb9e1 100644 --- a/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/HippieCompletionTest.java +++ b/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/HippieCompletionTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -16,10 +16,6 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - import org.eclipse.core.runtime.AssertionFailedException; import org.eclipse.text.tests.Accessor; @@ -30,6 +26,10 @@ import org.eclipse.jface.text.IDocument; import org.eclipse.ui.internal.texteditor.HippieCompletionEngine; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + /** * Tests for the Hippie completion action of the text editor. @@ -139,7 +139,7 @@ public class HippieCompletionTest extends TestCase { public void testSearchBackwards1() { try { - List list= fEngine.getCompletionsBackwards(documents[0], + List<String> list= fEngine.getCompletionsBackwards(documents[0], "pri", documents[0].get().indexOf("println") + 10); assertEquals(list.size(), 2); assertEquals(list.get(0), "ntln"); @@ -168,7 +168,7 @@ public class HippieCompletionTest extends TestCase { public void testSearchBackwards2() { try { - List list= fEngine.getCompletionsBackwards(documents[2], + List<String> list= fEngine.getCompletionsBackwards(documents[2], "plugi", documents[2].getLength()); assertEquals(8, list.size()); list= fEngine.makeUnique(list); @@ -186,7 +186,7 @@ public class HippieCompletionTest extends TestCase { public void testSearchBackwards3() { try { - List list= fEngine.getCompletionsBackwards(documents[1], + List<String> list= fEngine.getCompletionsBackwards(documents[1], "test", documents[1].getLength()); assertEquals("Number of backwards suggestions does not match", 2, list.size()); list= fEngine.getCompletionsBackwards(documents[1], @@ -202,8 +202,8 @@ public class HippieCompletionTest extends TestCase { } public void testSearch() { - ArrayList docsList= new ArrayList(Arrays.asList(this.documents)); - List result= createSuggestions("te", docsList); + ArrayList<IDocument> docsList= new ArrayList<>(Arrays.asList(this.documents)); + List<String> result= createSuggestions("te", docsList); assertEquals("Number of completions does not match", 15, result.size()); result= fEngine.makeUnique(result); assertEquals("Number of completions does not match", 7, result.size()); @@ -228,8 +228,8 @@ public class HippieCompletionTest extends TestCase { } public void testSearch2() { - ArrayList docsList= new ArrayList(Arrays.asList(this.documents)); - List result= createSuggestions("printe", docsList); + ArrayList<IDocument> docsList= new ArrayList<>(Arrays.asList(this.documents)); + List<String> result= createSuggestions("printe", docsList); assertEquals("Number of completions does not match", 0, result.size()); result= createSuggestions("s", docsList); @@ -242,7 +242,7 @@ public class HippieCompletionTest extends TestCase { public void testForwardSearch() { try { - List result= fEngine.getCompletionsForward(documents[0], + List<String> result= fEngine.getCompletionsForward(documents[0], "cl", documents[0].get().indexOf("cl"), true); assertEquals(2, result.size()); @@ -263,7 +263,7 @@ public class HippieCompletionTest extends TestCase { } public void testForwardSearchInternational() { - List result; + List<String> result; try { result= fEngine.getCompletionsForward(documents[4], "$", documents[4].get().indexOf('$'), true); @@ -350,7 +350,7 @@ public class HippieCompletionTest extends TestCase { public void testInternational() { IDocument intlDoc= documents[4]; - List result= createSuggestions("\u05D4", intlDoc); // hebrew letter heh + List<String> result= createSuggestions("\u05D4", intlDoc); // hebrew letter heh assertEquals("Number of completions does not match", 4, result.size()); assertEquals(result.get(0), "\u05DE\u05D7\u05DC\u05E7\u05D4"); assertEquals(result.get(1), "\u05D6\u05D5"); @@ -417,7 +417,7 @@ public class HippieCompletionTest extends TestCase { public void testInternationalBackwards() { IDocument intlDoc= documents[4]; try { - List list= fEngine.getCompletionsBackwards(intlDoc, + List<String> list= fEngine.getCompletionsBackwards(intlDoc, "\u043B\u0443", intlDoc.get().indexOf("129")); assertEquals(2, list.size()); assertEquals(list.get(0), "\u0447\u0448"); @@ -443,7 +443,7 @@ public class HippieCompletionTest extends TestCase { } } - private Accessor createAccessor(Iterator suggestions, int startOffset) { + private Accessor createAccessor(Iterator<String> suggestions, int startOffset) { return new Accessor("org.eclipse.ui.texteditor.HippieCompleteAction$CompletionState", getClass().getClassLoader(), new Class[] { Iterator.class, int.class }, new Object[] { suggestions, new Integer(startOffset) }); @@ -458,7 +458,7 @@ public class HippieCompletionTest extends TestCase { * Getting completions lazily */ public void testCompletionState() throws Exception { - ArrayList list= new ArrayList(); + ArrayList<String> list= new ArrayList<>(); Accessor state= null; try { @@ -527,7 +527,7 @@ public class HippieCompletionTest extends TestCase { "bar2\n" + ""); - Iterator suggestions= fEngine.getMultipleDocumentsIterator(openDocument, new ArrayList(), "bar", 3); + Iterator<String> suggestions= fEngine.getMultipleDocumentsIterator(openDocument, new ArrayList<IDocument>(), "bar", 3); assertEquals("1", suggestions.next()); assertEquals("2", suggestions.next()); assertEquals("", suggestions.next()); @@ -535,7 +535,7 @@ public class HippieCompletionTest extends TestCase { //Check with 2 documents - List otherDocuments= new ArrayList(); + List<IDocument> otherDocuments= new ArrayList<>(); otherDocuments.add(new Document("" + "bar3\n" + "bar4\n" + @@ -571,7 +571,7 @@ public class HippieCompletionTest extends TestCase { "bar0 bar1 bar" + ""); - suggestions= fEngine.getMultipleDocumentsIterator(openDocument, new ArrayList(), "bar", openDocument.getLength()); + suggestions= fEngine.getMultipleDocumentsIterator(openDocument, new ArrayList<IDocument>(), "bar", openDocument.getLength()); assertEquals("1", suggestions.next()); assertEquals("0", suggestions.next()); assertEquals("", suggestions.next()); @@ -583,14 +583,14 @@ public class HippieCompletionTest extends TestCase { return new TestSuite(HippieCompletionTest.class); } - private List createSuggestions(String prefix, IDocument doc) { + private List<String> createSuggestions(String prefix, IDocument doc) { return createSuggestions(prefix, Arrays.asList(new IDocument[]{doc})); } - private List createSuggestions(String prefix, List docsList) { - ArrayList results= new ArrayList(); - for (Iterator i= docsList.iterator(); i.hasNext();) { - IDocument doc= (IDocument) i.next(); + private List<String> createSuggestions(String prefix, List<IDocument> docsList) { + ArrayList<String> results= new ArrayList<>(); + for (Iterator<IDocument> i= docsList.iterator(); i.hasNext();) { + IDocument doc= i.next(); try { results.addAll(fEngine.getCompletionsForward(doc, prefix, 0, false)); } catch (BadLocationException e) { diff --git a/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/ScreenshotTest.java b/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/ScreenshotTest.java index b0adab96d9c..b465738616b 100644 --- a/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/ScreenshotTest.java +++ b/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/ScreenshotTest.java @@ -96,7 +96,7 @@ public class ScreenshotTest extends TestCase { * @param out print stream to use for diagnostics. * @return file system path to the screenshot file */ - public static String takeScreenshot(Class testClass, String name, PrintStream out) { + public static String takeScreenshot(Class<?> testClass, String name, PrintStream out) { File resultsHtmlDir= getJunitReportOutput(); // ends up in testresults/linux.gtk.x86_6.0/<class>.<test>.png if (resultsHtmlDir == null) { // Fallback. Warning: uses same file location on all test platforms: diff --git a/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/revisions/ChangeRegionTest.java b/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/revisions/ChangeRegionTest.java index 1ddac364e80..d67ef01f310 100644 --- a/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/revisions/ChangeRegionTest.java +++ b/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/revisions/ChangeRegionTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,19 +13,19 @@ package org.eclipse.ui.workbench.texteditor.tests.revisions; import java.util.Date; import java.util.List; -import junit.framework.Test; -import junit.framework.TestCase; -import junit.framework.TestSuite; - import org.eclipse.swt.graphics.RGB; import org.eclipse.jface.internal.text.revisions.ChangeRegion; import org.eclipse.jface.internal.text.revisions.Hunk; +import org.eclipse.jface.internal.text.revisions.Range; import org.eclipse.jface.text.revisions.Revision; -import org.eclipse.jface.text.source.ILineRange; import org.eclipse.jface.text.source.LineRange; +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + /** * * @since 3.2 @@ -85,36 +85,36 @@ public class ChangeRegionTest extends TestCase { ChangeRegion r= new ChangeRegion(fRevision, new LineRange(12, 3)); assertEquals(fRevision, r.getRevision()); - RangeUtil.assertEqualRange(new LineRange(12, 3), (ILineRange) r.getAdjustedRanges().get(0)); + RangeUtil.assertEqualRange(new LineRange(12, 3), r.getAdjustedRanges().get(0)); RangeUtil.assertEqualRange(new LineRange(12, 3), r.getAdjustedCoverage()); } public void testHunkAfter() throws Exception { ChangeRegion r= new ChangeRegion(fRevision, new LineRange(12, 3)); - List before= RangeUtil.deepClone(r.getAdjustedRanges()); + List<Range> before= RangeUtil.deepClone(r.getAdjustedRanges()); r.adjustTo(new Hunk(16, 3, 2)); RangeUtil.assertEqualRanges(before, r.getAdjustedRanges()); - RangeUtil.assertEqualRange((ILineRange) before.get(0), r.getAdjustedCoverage()); + RangeUtil.assertEqualRange(before.get(0), r.getAdjustedCoverage()); r= new ChangeRegion(fRevision, new LineRange(12, 3)); before= RangeUtil.deepClone(r.getAdjustedRanges()); r.adjustTo(new Hunk(16, -33, 2)); RangeUtil.assertEqualRanges(before, r.getAdjustedRanges()); - RangeUtil.assertEqualRange((ILineRange) before.get(0), r.getAdjustedCoverage()); + RangeUtil.assertEqualRange(before.get(0), r.getAdjustedCoverage()); } public void testHunkRightAfter() throws Exception { ChangeRegion r= new ChangeRegion(fRevision, new LineRange(12, 3)); - List before= RangeUtil.deepClone(r.getAdjustedRanges()); + List<Range> before= RangeUtil.deepClone(r.getAdjustedRanges()); r.adjustTo(new Hunk(15, 3, 2)); RangeUtil.assertEqualRanges(before, r.getAdjustedRanges()); - RangeUtil.assertEqualRange((ILineRange) before.get(0), r.getAdjustedCoverage()); + RangeUtil.assertEqualRange(before.get(0), r.getAdjustedCoverage()); r= new ChangeRegion(fRevision, new LineRange(12, 3)); before= RangeUtil.deepClone(r.getAdjustedRanges()); r.adjustTo(new Hunk(15, -3, 2)); RangeUtil.assertEqualRanges(before, r.getAdjustedRanges()); - RangeUtil.assertEqualRange((ILineRange) before.get(0), r.getAdjustedCoverage()); + RangeUtil.assertEqualRange(before.get(0), r.getAdjustedCoverage()); } public void testHunkBefore() throws Exception { diff --git a/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/revisions/RangeUtil.java b/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/revisions/RangeUtil.java index ecd458e220b..995325dca38 100644 --- a/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/revisions/RangeUtil.java +++ b/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/revisions/RangeUtil.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 IBM Corporation and others. + * Copyright (c) 2005, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -29,33 +29,33 @@ class RangeUtil extends Assert { assertEquals(expected.getNumberOfLines(), actual.getNumberOfLines()); } - static List deepClone(List ranges) { - List list= new ArrayList(ranges.size()); - for (Iterator it= ranges.iterator(); it.hasNext();) { - ILineRange range= (ILineRange) it.next(); + static List<Range> deepClone(List<Range> ranges) { + List<Range> list= new ArrayList<>(ranges.size()); + for (Iterator<Range> it= ranges.iterator(); it.hasNext();) { + ILineRange range= it.next(); list.add(Range.copy(range)); } return list; } - static void assertEqualRanges(ILineRange expected1, ILineRange expected2, List actual) { + static void assertEqualRanges(ILineRange expected1, ILineRange expected2, List<Range> actual) { assertEquals(2, actual.size()); - RangeUtil.assertEqualRange(expected1, (ILineRange) actual.get(0)); - RangeUtil.assertEqualRange(expected2, (ILineRange) actual.get(1)); + RangeUtil.assertEqualRange(expected1, actual.get(0)); + RangeUtil.assertEqualRange(expected2, actual.get(1)); } - static void assertEqualSingleRange(ILineRange expected, List actual) { + static void assertEqualSingleRange(ILineRange expected, List<Range> actual) { assertEquals(1, actual.size()); - RangeUtil.assertEqualRange(expected, (ILineRange) actual.get(0)); + RangeUtil.assertEqualRange(expected, actual.get(0)); } - static void assertEqualRanges(List expected, List actual) { + static void assertEqualRanges(List<Range> expected, List<Range> actual) { assertEquals(expected.size(), actual.size()); - Iterator it1= expected.iterator(); - Iterator it2= actual.iterator(); + Iterator<Range> it1= expected.iterator(); + Iterator<Range> it2= actual.iterator(); while (it1.hasNext()) { - ILineRange r1= (ILineRange) it1.next(); - ILineRange r2= (ILineRange) it2.next(); + ILineRange r1= it1.next(); + ILineRange r2= it2.next(); assertEqualRange(r1, r2); } } diff --git a/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/rulers/DAGTest.java b/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/rulers/DAGTest.java index ebb99a4c589..cb726bb0261 100644 --- a/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/rulers/DAGTest.java +++ b/org.eclipse.ui.workbench.texteditor.tests/src/org/eclipse/ui/workbench/texteditor/tests/rulers/DAGTest.java @@ -27,15 +27,15 @@ public class DAGTest extends TestCase { private static final Object B= "B"; private static final Object C= "C"; private static final Object D= "D"; - private static final Set AS= Collections.singleton(A); - private static final Set BS= Collections.singleton(B); - private static final Set CS= Collections.singleton(C); - private static final Set AD= new LinkedHashSet(Arrays.asList(new Object[] { A, D })); - private static final Set CD= new LinkedHashSet(Arrays.asList(new Object[] { C, D })); - private static final Set ACD= new LinkedHashSet(Arrays.asList(new Object[] { A, C, D })); - private static final Set BD= new LinkedHashSet(Arrays.asList(new Object[] { B, D })); + private static final Set<Object> AS= Collections.singleton(A); + private static final Set<Object> BS= Collections.singleton(B); + private static final Set<Object> CS= Collections.singleton(C); + private static final Set<Object> AD= new LinkedHashSet<>(Arrays.asList(new Object[] { A, D })); + private static final Set<Object> CD= new LinkedHashSet<>(Arrays.asList(new Object[] { C, D })); + private static final Set<Object> ACD= new LinkedHashSet<>(Arrays.asList(new Object[] { A, C, D })); + private static final Set<Object> BD= new LinkedHashSet<>(Arrays.asList(new Object[] { B, D })); - private DAG fDag= new DAG(); + private DAG<Object> fDag= new DAG<>(); public void testEmpty() throws Exception { assertTrue(fDag.getChildren(new Object()).isEmpty()); diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/HippieCompletionEngine.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/HippieCompletionEngine.java index aa3552d62f7..a8db1336b85 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/HippieCompletionEngine.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/HippieCompletionEngine.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -148,10 +148,10 @@ public final class HippieCompletionEngine { * @throws BadLocationException if there is some error scanning the * document. */ - public List getCompletionsForward(IDocument document, CharSequence prefix, + public List<String> getCompletionsForward(IDocument document, CharSequence prefix, int firstPosition, boolean currentWordLast) throws BadLocationException { - ArrayList res= new ArrayList(); - for (Iterator it= getForwardIterator(document, prefix, firstPosition, currentWordLast); it.hasNext();) { + ArrayList<String> res= new ArrayList<>(); + for (Iterator<String> it= getForwardIterator(document, prefix, firstPosition, currentWordLast); it.hasNext();) { res.add(it.next()); } return res; @@ -170,9 +170,9 @@ public final class HippieCompletionEngine { * The empty suggestion is not included in the results. * @throws BadLocationException if any error occurs */ - public List getCompletionsBackwards(IDocument document, CharSequence prefix, int firstPosition) throws BadLocationException { - ArrayList res= new ArrayList(); - for (Iterator it= getBackwardIterator(document, prefix, firstPosition); it.hasNext();) { + public List<String> getCompletionsBackwards(IDocument document, CharSequence prefix, int firstPosition) throws BadLocationException { + ArrayList<String> res= new ArrayList<>(); + for (Iterator<String> it= getBackwardIterator(document, prefix, firstPosition); it.hasNext();) { res.add(it.next()); } return res; @@ -210,12 +210,12 @@ public final class HippieCompletionEngine { * @param suggestions a list of suggestions ({@link String}). * @return a list of unique completion suggestions. */ - public List makeUnique(List suggestions) { - HashSet seenAlready= new HashSet(); - ArrayList uniqueSuggestions= new ArrayList(); + public List<String> makeUnique(List<String> suggestions) { + HashSet<String> seenAlready= new HashSet<>(); + ArrayList<String> uniqueSuggestions= new ArrayList<>(); - for (Iterator i= suggestions.iterator(); i.hasNext();) { - String suggestion= (String) i.next(); + for (Iterator<String> i= suggestions.iterator(); i.hasNext();) { + String suggestion= i.next(); if (!seenAlready.contains(suggestion)) { seenAlready.add(suggestion); uniqueSuggestions.add(suggestion); @@ -236,8 +236,8 @@ public final class HippieCompletionEngine { * is always the current document. * @since 3.6 */ - public static List computeDocuments(ITextEditor currentTextEditor) { - ArrayList documentsForSearch= new ArrayList(); + public static List<IDocument> computeDocuments(ITextEditor currentTextEditor) { + ArrayList<IDocument> documentsForSearch= new ArrayList<>(); if (currentTextEditor == null) { return documentsForSearch; } @@ -252,7 +252,7 @@ public final class HippieCompletionEngine { return documentsForSearch; } - List computedDocuments= new ArrayList(); + List<IDocument> computedDocuments= new ArrayList<>(); IWorkbenchWindow window= currentTextEditor.getSite().getWorkbenchWindow(); IEditorReference editorsArray[]= window.getActivePage().getEditorReferences(); @@ -295,7 +295,7 @@ public final class HippieCompletionEngine { * * @since 3.6 */ - public Iterator getForwardIterator(IDocument document, CharSequence prefix, int firstPosition, boolean currentWordLast) { + public Iterator<String> getForwardIterator(IDocument document, CharSequence prefix, int firstPosition, boolean currentWordLast) { return new HippieCompletionForwardIterator(document, prefix, firstPosition, currentWordLast); } @@ -312,7 +312,7 @@ public final class HippieCompletionEngine { * * @since 3.6 */ - public Iterator getBackwardIterator(IDocument document, CharSequence prefix, int firstPosition) { + public Iterator<String> getBackwardIterator(IDocument document, CharSequence prefix, int firstPosition) { return new HippieCompletionBackwardIterator(document, prefix, firstPosition); } @@ -331,7 +331,7 @@ public final class HippieCompletionEngine { * * @since 3.6 */ - public Iterator getMultipleDocumentsIterator(IDocument document, List otherDocuments, CharSequence prefix, int firstPosition) { + public Iterator<String> getMultipleDocumentsIterator(IDocument document, List<IDocument> otherDocuments, CharSequence prefix, int firstPosition) { return new MultipleDocumentsIterator(document, otherDocuments, prefix, firstPosition); } @@ -342,7 +342,7 @@ public final class HippieCompletionEngine { * * @since 3.6 */ - private final class MultipleDocumentsIterator implements Iterator { + private final class MultipleDocumentsIterator implements Iterator<String> { /** * This is the next token to be returned (when null, no more tokens should be returned) @@ -356,7 +356,7 @@ public final class HippieCompletionEngine { private int fCurrLocation= -1; /** These are the suggestions which we already loaded. */ - private final List fSuggestions; + private final List<String> fSuggestions; /** This marks the current suggestion to be returned */ private int fCurrSuggestion= 0; @@ -365,7 +365,7 @@ public final class HippieCompletionEngine { private final CharSequence fPrefix; /** The list of IDocuments that we should search */ - private final List fOtherDocuments; + private final List<IDocument> fOtherDocuments; /** * The document that's currently opened (that's the 1st we should look and we should 1st @@ -380,15 +380,15 @@ public final class HippieCompletionEngine { private boolean fAddedEmpty= false; /** The 'current' forward iterator. */ - private Iterator fCompletionsForwardIterator; + private Iterator<String> fCompletionsForwardIterator; /** The 'current' backward iterator. */ - private Iterator fCompletionsBackwardIterator; + private Iterator<String> fCompletionsBackwardIterator; - private MultipleDocumentsIterator(IDocument openDocument, List otherDocuments, + private MultipleDocumentsIterator(IDocument openDocument, List<IDocument> otherDocuments, CharSequence prefix, int selectionOffset) { this.fPrefix= prefix; - this.fSuggestions= new ArrayList(); + this.fSuggestions= new ArrayList<>(); this.fOtherDocuments= otherDocuments; this.fSelectionOffset= selectionOffset; this.fOpenDocument= openDocument; @@ -423,7 +423,7 @@ public final class HippieCompletionEngine { while (fCurrLocation < this.fOtherDocuments.size()) { fCompletionsForwardIterator= getForwardIterator( - ((IDocument)this.fOtherDocuments.get(fCurrLocation)), fPrefix, 0, false); + (this.fOtherDocuments.get(fCurrLocation)), fPrefix, 0, false); fCurrLocation++; if (checkNext()) { return; @@ -458,7 +458,7 @@ public final class HippieCompletionEngine { } if (fSuggestions.size() > fCurrSuggestion) { - fNext= (String)fSuggestions.get(fCurrSuggestion); + fNext= fSuggestions.get(fCurrSuggestion); fCurrSuggestion++; return true; } @@ -482,11 +482,11 @@ public final class HippieCompletionEngine { * @return the next suggestion */ @Override - public Object next() { + public String next() { if (fNext == null) { throw new NoSuchElementException("No more elements to iterate"); //$NON-NLS-1$ } - Object ret= fNext; + String ret= fNext; calculateNext(); return ret; } @@ -510,7 +510,7 @@ public final class HippieCompletionEngine { * * @since 3.6 */ - private abstract class HippieCompletionIterator implements Iterator { + private abstract class HippieCompletionIterator implements Iterator<String> { /** The document to be scanned */ protected IDocument fDocument; @@ -578,7 +578,7 @@ public final class HippieCompletionEngine { } @Override - public Object next() { + public String next() { if (!fHasNext) { throw new NoSuchElementException(); } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/TextEditorPlugin.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/TextEditorPlugin.java index 3b5f632d590..019841b7aea 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/TextEditorPlugin.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/TextEditorPlugin.java @@ -48,7 +48,7 @@ public final class TextEditorPlugin extends AbstractUIPlugin implements IRegistr /** The last edit position */ private EditPosition fLastEditPosition; /** The action which goes to the last edit position */ - private Set fLastEditPositionDependentActions; + private Set<IAction> fLastEditPositionDependentActions; /** * The quick diff extension registry. @@ -112,9 +112,9 @@ public final class TextEditorPlugin extends AbstractUIPlugin implements IRegistr public void setLastEditPosition(EditPosition lastEditPosition) { fLastEditPosition= lastEditPosition; if (fLastEditPosition != null && fLastEditPositionDependentActions != null) { - Iterator iter= fLastEditPositionDependentActions.iterator(); + Iterator<IAction> iter= fLastEditPositionDependentActions.iterator(); while (iter.hasNext()) - ((IAction)iter.next()).setEnabled(true); + iter.next().setEnabled(true); fLastEditPositionDependentActions= null; } } @@ -128,7 +128,7 @@ public final class TextEditorPlugin extends AbstractUIPlugin implements IRegistr if (fLastEditPosition != null) return; if (fLastEditPositionDependentActions == null) - fLastEditPositionDependentActions= new HashSet(); + fLastEditPositionDependentActions= new HashSet<>(); fLastEditPositionDependentActions.add(action); } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/DiffRegion.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/DiffRegion.java index 56b17981fff..cbf11320944 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/DiffRegion.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/DiffRegion.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -35,7 +35,7 @@ public final class DiffRegion extends Annotation implements ILineDiffInfo { private final int fOffset; - private final List fList; + private final List<QuickDiffRangeDifference> fList; private final IDocument fDocument; @@ -47,7 +47,7 @@ public final class DiffRegion extends Annotation implements ILineDiffInfo { * @param differences the list of differences * @param source the document */ - public DiffRegion(QuickDiffRangeDifference difference, int offset, List differences, IDocument source) { + public DiffRegion(QuickDiffRangeDifference difference, int offset, List<QuickDiffRangeDifference> differences, IDocument source) { super("org.eclipse.ui.workbench.texteditor.quickdiffChange", false, null); //$NON-NLS-1$ fOffset= offset; fDifference= difference; @@ -85,10 +85,10 @@ public final class DiffRegion extends Annotation implements ILineDiffInfo { return Math.max(fDifference.leftLength() - fDifference.rightLength(), 0); synchronized (fList) { - for (ListIterator it= fList.listIterator(); it.hasNext();) { + for (ListIterator<QuickDiffRangeDifference> it= fList.listIterator(); it.hasNext();) { if (fDifference.equals(it.next())) { if (it.hasNext()) { - QuickDiffRangeDifference next= (QuickDiffRangeDifference) it.next(); + QuickDiffRangeDifference next= it.next(); if (next.rightLength() == 0) return Math.max(next.leftLength() - next.rightLength(), 0); } @@ -113,10 +113,10 @@ public final class DiffRegion extends Annotation implements ILineDiffInfo { public int getRemovedLinesAbove() { if (getChangeType() == UNCHANGED && fOffset == 0) { synchronized (fList) { - for (ListIterator it= fList.listIterator(fList.size()); it.hasPrevious();) { + for (ListIterator<QuickDiffRangeDifference> it= fList.listIterator(fList.size()); it.hasPrevious();) { if (fDifference.equals(it.previous())) { if (it.hasPrevious()) { - QuickDiffRangeDifference previous= (QuickDiffRangeDifference) it.previous(); + QuickDiffRangeDifference previous= it.previous(); return Math.max(previous.leftLength() - previous.rightLength(), 0); } break; diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/DocumentLineDiffer.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/DocumentLineDiffer.java index 0a60484b609..1f4b5aab26a 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/DocumentLineDiffer.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/DocumentLineDiffer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -172,31 +172,31 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno */ private boolean fUpdateNeeded; /** The listeners on this annotation model. */ - private List fAnnotationModelListeners= new ArrayList(); + private List<IAnnotationModelListener> fAnnotationModelListeners= new ArrayList<>(); /** The job currently initializing the differ, or <code>null</code> if there is none. */ private Job fInitializationJob; /** Stores <code>DocumentEvents</code> while an initialization is going on. */ - private List fStoredEvents= new ArrayList(); + private List<DocumentEvent> fStoredEvents= new ArrayList<>(); /** * The differences between <code>fLeftDocument</code> and <code>fRightDocument</code>. * This is the model we work on. */ - private List fDifferences= new ArrayList(); + private List<QuickDiffRangeDifference> fDifferences= new ArrayList<>(); /** * The differences removed in one iteration. Stored to be able to send out differentiated * annotation events. */ - private List fRemoved= new ArrayList(); + private List<QuickDiffRangeDifference> fRemoved= new ArrayList<>(); /** * The differences added in one iteration. Stored to be able to send out differentiated * annotation events. */ - private List fAdded= new ArrayList(); + private List<QuickDiffRangeDifference> fAdded= new ArrayList<>(); /** * The differences changed in one iteration. Stored to be able to send out differentiated * annotation events. */ - private List fChanged= new ArrayList(); + private List<QuickDiffRangeDifference> fChanged= new ArrayList<>(); /** The first line affected by a document event. */ private int fFirstLine; /** The number of lines affected by a document event. */ @@ -330,13 +330,13 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno int rOffset= -1, rLength= -1, lOffset= -1, lLength= -1; QuickDiffRangeDifference diff= null; - final List differences= fDifferences; + final List<QuickDiffRangeDifference> differences= fDifferences; synchronized (differences) { - Iterator it= differences.iterator(); + Iterator<QuickDiffRangeDifference> it= differences.iterator(); // get start while (it.hasNext()) { - diff= (QuickDiffRangeDifference) it.next(); + diff= it.next(); if (line < diff.rightEnd()) { rOffset= fRightDocument.getLineOffset(line); int leftLine= Math.min(diff.leftStart() + line - diff.rightStart(), diff.leftEnd() - 1); @@ -351,7 +351,7 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno // get end / length int to= line + nLines - 1; while (it.hasNext()) { - diff= (QuickDiffRangeDifference) it.next(); + diff= it.next(); if (to < diff.rightEnd()) { int rEndOffset= fRightDocument.getLineOffset(to) + fRightDocument.getLineLength(to); rLength= rEndOffset - rOffset; @@ -382,13 +382,13 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno return 0; QuickDiffRangeDifference diff= null; - final List differences= fDifferences; + final List<QuickDiffRangeDifference> differences= fDifferences; synchronized (differences) { - for (Iterator it= differences.iterator(); it.hasNext();) { - diff= (QuickDiffRangeDifference) it.next(); + for (Iterator<QuickDiffRangeDifference> it= differences.iterator(); it.hasNext();) { + diff= it.next(); if (line >= diff.rightStart() && line < diff.rightEnd()) { if (diff.kind() == RangeDifference.NOCHANGE && it.hasNext()) - diff= (QuickDiffRangeDifference) it.next(); + diff= it.next(); break; } } @@ -626,7 +626,7 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno DocumentEquivalenceClass rightEquivalent= new DocumentEquivalenceClass(actual, hash); fRightEquivalent= rightEquivalent; IRangeComparator act= new DocEquivalenceComparator(rightEquivalent, null); - List diffs= new ArrayList(Arrays.asList(RangeDifferencer.findRanges(fRangeDiffFactory, monitor, ref, act))); + ArrayList<QuickDiffRangeDifference> diffs= asQuickDiffRangeDifference(RangeDifferencer.findRanges(fRangeDiffFactory, monitor, ref, act)); // 7: Reset the model to the just gotten differences // re-inject stored events to get up to date. synchronized (DocumentLineDiffer.this) { @@ -658,7 +658,7 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno break; } - event= (DocumentEvent) fStoredEvents.remove(0); + event= fStoredEvents.remove(0); } // access documents non synchronized: @@ -861,16 +861,16 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno // inform listeners about change if (fUpdateNeeded) { AnnotationModelEvent ame= new AnnotationModelEvent(this, false); - for (Iterator it= fAdded.iterator(); it.hasNext(); ) { - QuickDiffRangeDifference rd= (QuickDiffRangeDifference) it.next(); + for (Iterator<QuickDiffRangeDifference> it= fAdded.iterator(); it.hasNext(); ) { + QuickDiffRangeDifference rd= it.next(); ame.annotationAdded(rd.getDiffRegion(fDifferences, fLeftDocument)); } - for (Iterator it= fRemoved.iterator(); it.hasNext(); ) { - QuickDiffRangeDifference rd= (QuickDiffRangeDifference) it.next(); + for (Iterator<QuickDiffRangeDifference> it= fRemoved.iterator(); it.hasNext(); ) { + QuickDiffRangeDifference rd= it.next(); ame.annotationRemoved(rd.getDiffRegion(fDifferences, fLeftDocument)); } - for (Iterator it= fChanged.iterator(); it.hasNext(); ) { - QuickDiffRangeDifference rd= (QuickDiffRangeDifference) it.next(); + for (Iterator<QuickDiffRangeDifference> it= fChanged.iterator(); it.hasNext(); ) { + QuickDiffRangeDifference rd= it.next(); ame.annotationChanged(rd.getDiffRegion(fDifferences, fLeftDocument)); } fireModelChanged(ame); @@ -1006,29 +1006,29 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno // ">\n\n<" + right.get(rightRegion.getOffset(), rightRegion.getLength()) + ">\n"); //$NON-NLS-1$ //$NON-NLS-2$ // compare - List diffs= new ArrayList(Arrays.asList(RangeDifferencer.findRanges(fRangeDiffFactory, null, reference, change))); + List<QuickDiffRangeDifference> diffs= asQuickDiffRangeDifference(RangeDifferencer.findRanges(fRangeDiffFactory, null, reference, change)); if (diffs.size() == 0) { diffs.add(new QuickDiffRangeDifference(RangeDifference.CHANGE, 0, 0, 0, 0)); } // shift the partial diffs to the absolute document positions - for (Iterator it= diffs.iterator(); it.hasNext();) { - QuickDiffRangeDifference d= (QuickDiffRangeDifference) it.next(); + for (Iterator<QuickDiffRangeDifference> it= diffs.iterator(); it.hasNext();) { + QuickDiffRangeDifference d= it.next(); d.shiftLeft(leftStartLine); d.shiftRight(rightStartLine); } // undo optimization shifting if (shiftBefore > 0) { - QuickDiffRangeDifference first= (QuickDiffRangeDifference) diffs.get(0); + QuickDiffRangeDifference first= diffs.get(0); if (first.kind() == RangeDifference.NOCHANGE) first.extendStart(-shiftBefore); else diffs.add(0, new QuickDiffRangeDifference(RangeDifference.NOCHANGE, first.rightStart() - shiftBefore, shiftBefore, first.leftStart() - shiftBefore, shiftBefore)); } - QuickDiffRangeDifference last= (QuickDiffRangeDifference) diffs.get(diffs.size() - 1); + QuickDiffRangeDifference last= diffs.get(diffs.size() - 1); if (shiftAfter > 0) { if (last.kind() == RangeDifference.NOCHANGE) last.extendEnd(shiftAfter); @@ -1038,8 +1038,8 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno // replace changed diff range synchronized (fDifferences) { - final ListIterator it= fDifferences.listIterator(); - Iterator newIt= diffs.iterator(); + final ListIterator<QuickDiffRangeDifference> it= fDifferences.listIterator(); + Iterator<QuickDiffRangeDifference> newIt= diffs.iterator(); QuickDiffRangeDifference current; boolean changed= false; @@ -1048,7 +1048,7 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno // search for consistentBefore do { Assert.isTrue(it.hasNext()); - current= (QuickDiffRangeDifference) it.next(); + current= it.next(); } while (current != consistentBefore); Assert.isTrue(current == consistentBefore); @@ -1059,7 +1059,7 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno // replace until consistentAfter while (current != consistentAfter) { if (newIt.hasNext()) { - Object o= newIt.next(); + QuickDiffRangeDifference o= newIt.next(); if (!current.equals(o)) { fRemoved.add(current); fAdded.add(o); @@ -1072,13 +1072,13 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno changed= true; } Assert.isTrue(it.hasNext()); - current= (QuickDiffRangeDifference) it.next(); + current= it.next(); } // replace consistentAfter Assert.isTrue(current == consistentAfter); if (newIt.hasNext()) { - Object o= newIt.next(); + QuickDiffRangeDifference o= newIt.next(); if (!current.equals(o)) { fRemoved.add(current); fAdded.add(o); @@ -1093,7 +1093,7 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno // add remaining new diffs while (newIt.hasNext()) { - Object next= newIt.next(); + QuickDiffRangeDifference next= newIt.next(); fAdded.add(next); it.add(next); changed= true; @@ -1104,7 +1104,7 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno int leftShift= 0; int rightShift= 0; while (it.hasNext()) { - current= (QuickDiffRangeDifference) it.next(); + current= it.next(); if (init) { init= false; leftShift= last.leftEnd() - current.leftStart(); @@ -1126,6 +1126,19 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno } /** + * Converts a {@code RangeDifference[]} into an {@code ArrayList<QuickDiffRangeDifference>}. + * This is unsafe in general, but OK if used carefully. + * Workaround for <a href="https://bugs.eclipse.org/483319">bug 483319</a>. + * + * @param ranges the ranges, <em>must</em> be of type {@link QuickDiffRangeDifference} + * @return the ranges as a modifiable list + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static ArrayList<QuickDiffRangeDifference> asQuickDiffRangeDifference(RangeDifference[] ranges) { + return new ArrayList(Arrays.asList(ranges)); + } + + /** * Finds a consistent range of at least size before <code>line</code> in the left document. * * @param line the line before which the range has to occur @@ -1135,8 +1148,8 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno private QuickDiffRangeDifference findConsistentRangeBeforeLeft(int line, int size) { QuickDiffRangeDifference found= null; - for (ListIterator it= fDifferences.listIterator(); it.hasNext();) { - QuickDiffRangeDifference difference= (QuickDiffRangeDifference) it.next(); + for (ListIterator<QuickDiffRangeDifference> it= fDifferences.listIterator(); it.hasNext();) { + QuickDiffRangeDifference difference= it.next(); if (found == null || difference.kind() == RangeDifference.NOCHANGE && (difference.leftEnd() < line && difference.leftLength() >= size || difference.leftEnd() >= line && line - difference.leftStart() >= size)) @@ -1159,8 +1172,8 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno private QuickDiffRangeDifference findConsistentRangeAfterLeft(int line, int size) { QuickDiffRangeDifference found= null; - for (ListIterator it= fDifferences.listIterator(fDifferences.size()); it.hasPrevious();) { - QuickDiffRangeDifference difference= (QuickDiffRangeDifference) it.previous(); + for (ListIterator<QuickDiffRangeDifference> it= fDifferences.listIterator(fDifferences.size()); it.hasPrevious();) { + QuickDiffRangeDifference difference= it.previous(); if (found == null || difference.kind() == RangeDifference.NOCHANGE && (difference.leftStart() > line && difference.leftLength() >= size || difference.leftStart() <= line && difference.leftEnd() - line >= size)) @@ -1185,8 +1198,8 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno QuickDiffRangeDifference found= null; int unchanged= -1; // the number of unchanged lines before line - for (ListIterator it= fDifferences.listIterator(); it.hasNext();) { - QuickDiffRangeDifference difference= (QuickDiffRangeDifference) it.next(); + for (ListIterator<QuickDiffRangeDifference> it= fDifferences.listIterator(); it.hasNext();) { + QuickDiffRangeDifference difference= it.next(); if (found == null) found= difference; else if (difference.kind() == RangeDifference.NOCHANGE) { @@ -1213,8 +1226,8 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno QuickDiffRangeDifference found= null; int unchanged= -1; // the number of unchanged lines after line - for (ListIterator it= fDifferences.listIterator(fDifferences.size()); it.hasPrevious();) { - QuickDiffRangeDifference difference= (QuickDiffRangeDifference) it.previous(); + for (ListIterator<QuickDiffRangeDifference> it= fDifferences.listIterator(fDifferences.size()); it.hasPrevious();) { + QuickDiffRangeDifference difference= it.previous(); if (found == null) found= difference; else if (difference.kind() == RangeDifference.NOCHANGE) { @@ -1273,7 +1286,7 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno * * Q: what if we have a prefix to a repetition field? Probably does not matter. */ - LinkedList window= new LinkedList(); + LinkedList<String> window= new LinkedList<>(); int nLines= doc.getNumberOfLines(); int repetition= line - 1; int l= line; @@ -1337,8 +1350,8 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno * @return the corresponding RangeDifference, or <code>null</code> */ private QuickDiffRangeDifference getRangeDifferenceForLeftLine(int leftLine) { - for (Iterator it= fDifferences.iterator(); it.hasNext();) { - QuickDiffRangeDifference d= (QuickDiffRangeDifference) it.next(); + for (Iterator<QuickDiffRangeDifference> it= fDifferences.iterator(); it.hasNext();) { + QuickDiffRangeDifference d= it.next(); if (leftLine >= d.leftStart() && leftLine < d.leftEnd()) { return d; } @@ -1353,10 +1366,10 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno * @return the corresponding RangeDifference, or <code>null</code> */ private QuickDiffRangeDifference getRangeDifferenceForRightLine(int rightLine) { - final List differences= fDifferences; + final List<QuickDiffRangeDifference> differences= fDifferences; synchronized (differences) { - for (Iterator it= differences.iterator(); it.hasNext();) { - QuickDiffRangeDifference d= (QuickDiffRangeDifference) it.next(); + for (Iterator<QuickDiffRangeDifference> it= differences.iterator(); it.hasNext();) { + QuickDiffRangeDifference d= it.next(); if (rightLine >= d.rightStart() && rightLine < d.rightEnd()) { return d; } @@ -1449,14 +1462,14 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno } @Override - public Iterator getAnnotationIterator() { - final List copy; - List differences= fDifferences; // atomic + public Iterator<Annotation> getAnnotationIterator() { + final List<QuickDiffRangeDifference> copy; + List<QuickDiffRangeDifference> differences= fDifferences; // atomic synchronized (differences) { - copy= new ArrayList(differences); + copy= new ArrayList<>(differences); } - final Iterator iter= copy.iterator(); - return new Iterator() { + final Iterator<QuickDiffRangeDifference> iter= copy.iterator(); + return new Iterator<Annotation>() { @Override public void remove() { @@ -1469,8 +1482,8 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno } @Override - public Object next() { - QuickDiffRangeDifference diff= (QuickDiffRangeDifference) iter.next(); + public Annotation next() { + QuickDiffRangeDifference diff= iter.next(); return diff.getDiffRegion(copy, fLeftDocument); } @@ -1507,10 +1520,10 @@ public class DocumentLineDiffer implements ILineDiffer, IDocumentListener, IAnno * @param event the event to be sent out to the listeners */ protected void fireModelChanged(AnnotationModelEvent event) { - ArrayList v= new ArrayList(fAnnotationModelListeners); - Iterator e= v.iterator(); + ArrayList<IAnnotationModelListener> v= new ArrayList<>(fAnnotationModelListeners); + Iterator<IAnnotationModelListener> e= v.iterator(); while (e.hasNext()) { - IAnnotationModelListener l= (IAnnotationModelListener)e.next(); + IAnnotationModelListener l= e.next(); if (l instanceof IAnnotationModelListenerExtension) ((IAnnotationModelListenerExtension)l).modelChanged(event); else diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/QuickDiffExtensionsRegistry.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/QuickDiffExtensionsRegistry.java index 5598cf7894f..a7f3c96b561 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/QuickDiffExtensionsRegistry.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/QuickDiffExtensionsRegistry.java @@ -32,7 +32,7 @@ public class QuickDiffExtensionsRegistry { /** The default reference provider's descriptor. */ private ReferenceProviderDescriptor fDefaultDescriptor; /** The list returned to callers of <code>getExtensions</code>. */ - private List fDescriptors; + private List<ReferenceProviderDescriptor> fDescriptors; /** * Creates a new instance. @@ -56,7 +56,7 @@ public class QuickDiffExtensionsRegistry { * * @return the list of extensions to the <code>quickDiffReferenceProvider</code> extension point. */ - public synchronized List getReferenceProviderDescriptors() { + public synchronized List<ReferenceProviderDescriptor> getReferenceProviderDescriptors() { ensureRegistered(); return fDescriptors; } @@ -79,7 +79,7 @@ public class QuickDiffExtensionsRegistry { public synchronized void reloadExtensions() { fDefaultDescriptor= null; IExtensionRegistry registry= Platform.getExtensionRegistry(); - List list= new ArrayList(); + List<ReferenceProviderDescriptor> list= new ArrayList<>(); IConfigurationElement[] elements= registry.getConfigurationElementsFor(TextEditorPlugin.PLUGIN_ID, TextEditorPlugin.REFERENCE_PROVIDER_EXTENSION_POINT); for (int i= 0; i < elements.length; i++) { diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/QuickDiffRangeDifference.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/QuickDiffRangeDifference.java index fd1bb329944..76d2d5d9009 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/QuickDiffRangeDifference.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/QuickDiffRangeDifference.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -117,7 +117,7 @@ public class QuickDiffRangeDifference extends org.eclipse.compare.rangedifferenc * @param source the original document (left document) that this difference refers to * @return a <code>DiffRegion</code> corresponding to this difference */ - public DiffRegion getDiffRegion(List differences, IDocument source) { + public DiffRegion getDiffRegion(List<QuickDiffRangeDifference> differences, IDocument source) { if (fRegion == null) fRegion= new DiffRegion(this, 0, differences, source); return fRegion; diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/compare/equivalence/DocumentEquivalenceClass.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/compare/equivalence/DocumentEquivalenceClass.java index 440cb70f6ac..29fa1f82a84 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/compare/equivalence/DocumentEquivalenceClass.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/quickdiff/compare/equivalence/DocumentEquivalenceClass.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -29,7 +29,7 @@ public final class DocumentEquivalenceClass { private static final boolean DEBUG= false; - private final ArrayList fHashes; + private final ArrayList<Hash> fHashes; private IDocument fDocument; private final IHashFunction fHashFunction; @@ -39,8 +39,8 @@ public final class DocumentEquivalenceClass { public DocumentEquivalenceClass(IDocument document, IHashFunction hashFunction) { fDocument= document; - Object[] nulls= new Object[fDocument.getNumberOfLines()]; - fHashes= new ArrayList(Arrays.asList(nulls)); + Hash[] nulls= new Hash[fDocument.getNumberOfLines()]; + fHashes= new ArrayList<>(Arrays.asList(nulls)); if (hashFunction == null) throw new NullPointerException("hashFunction"); //$NON-NLS-1$ @@ -67,7 +67,7 @@ public final class DocumentEquivalenceClass { } private Hash internalGetHash(int line) throws BadLocationException { - Hash hash= (Hash) fHashes.get(line); + Hash hash= fHashes.get(line); if (hash == null) { if (fDocument == null) throw new AssertionError("hash cannot be null after loadAndForget"); //$NON-NLS-1$ @@ -108,7 +108,7 @@ public final class DocumentEquivalenceClass { int changed= Math.min(linesAfter, linesBefore); if (delta > 0) { - Object[] nulls= new Object[delta]; + Hash[] nulls= new Hash[delta]; fHashes.addAll(firstLine + changed, Arrays.asList(nulls)); } else if (delta < 0) { fHashes.subList(firstLine, firstLine - delta).clear(); diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/DAG.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/DAG.java index 144db9644d2..aa5024239dd 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/DAG.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/DAG.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2008 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,15 +21,18 @@ import org.eclipse.core.runtime.Assert; /** * A directed acyclic graph. See http://en.wikipedia.org/wiki/Directed_acyclic_graph + * @param <E> type of the vertices * * @since 3.3 */ -public final class DAG { +public final class DAG<E> { /** * Multimap, supports <code>null</code> key, but not <code>null</code> values. + * @param <K> key type + * @param <V> values type */ - private static final class MultiMap { - private final Map fMap= new LinkedHashMap(); + private static final class MultiMap<K, V> { + private final Map<K, Set<V>> fMap= new LinkedHashMap<>(); /** * Adds <code>val</code> to the values mapped to by <code>key</code>. If @@ -39,10 +42,10 @@ public final class DAG { * @param key the key * @param val the value */ - public void put(Object key, Object val) { - Set values= (Set) fMap.get(key); + public void put(K key, V val) { + Set<V> values= fMap.get(key); if (values == null) { - values= new LinkedHashSet(); + values= new LinkedHashSet<>(); fMap.put(key, values); } if (val != null) @@ -55,12 +58,12 @@ public final class DAG { * @param key the key * @return the mappings for <code>key</code> */ - public Set get(Object key) { - Set values= (Set) fMap.get(key); - return values == null ? Collections.EMPTY_SET : values; + public Set<V> get(K key) { + Set<V> values= fMap.get(key); + return values == null ? Collections.emptySet() : values; } - public Set keySet() { + public Set<K> keySet() { return fMap.keySet(); } @@ -71,9 +74,9 @@ public final class DAG { * @param key the key to remove * @return the removed mappings */ - public Set removeAll(Object key) { - Set values= (Set) fMap.remove(key); - return values == null ? Collections.EMPTY_SET : values; + public Set<V> removeAll(K key) { + Set<V> values= fMap.remove(key); + return values == null ? Collections.emptySet() : values; } /** @@ -83,8 +86,8 @@ public final class DAG { * @param key the key * @param val the value */ - public void remove(Object key, Object val) { - Set values= (Set) fMap.get(key); + public void remove(K key, V val) { + Set<V> values= fMap.get(key); if (values != null) values.remove(val); } @@ -95,8 +98,8 @@ public final class DAG { } } - private final MultiMap fOut= new MultiMap(); - private final MultiMap fIn= new MultiMap(); + private final MultiMap<E, E> fOut= new MultiMap<>(); + private final MultiMap<E, E> fIn= new MultiMap<>(); /** * Adds a directed edge from <code>origin</code> to <code>target</code>. The vertices are not @@ -109,7 +112,7 @@ public final class DAG { * edge was not added because it would have violated the acyclic nature of the * receiver. */ - public boolean addEdge(Object origin, Object target) { + public boolean addEdge(E origin, E target) { Assert.isLegal(origin != null); Assert.isLegal(target != null); @@ -129,7 +132,7 @@ public final class DAG { * * @param vertex the new vertex */ - public void addVertex(Object vertex) { + public void addVertex(E vertex) { Assert.isLegal(vertex != null); fOut.put(vertex, null); fIn.put(vertex, null); @@ -140,12 +143,12 @@ public final class DAG { * * @param vertex the vertex to remove */ - public void removeVertex(Object vertex) { - Set targets= fOut.removeAll(vertex); - for (Iterator it= targets.iterator(); it.hasNext();) + public void removeVertex(E vertex) { + Set<E> targets= fOut.removeAll(vertex); + for (Iterator<E> it= targets.iterator(); it.hasNext();) fIn.remove(it.next(), vertex); - Set origins= fIn.removeAll(vertex); - for (Iterator it= origins.iterator(); it.hasNext();) + Set<E> origins= fIn.removeAll(vertex); + for (Iterator<E> it= origins.iterator(); it.hasNext();) fOut.remove(it.next(), vertex); } @@ -155,7 +158,7 @@ public final class DAG { * * @return the sources of the receiver */ - public Set getSources() { + public Set<E> getSources() { return computeZeroEdgeVertices(fIn); } @@ -165,15 +168,15 @@ public final class DAG { * * @return the sinks of the receiver */ - public Set getSinks() { + public Set<E> getSinks() { return computeZeroEdgeVertices(fOut); } - private Set computeZeroEdgeVertices(MultiMap map) { - Set candidates= map.keySet(); - Set roots= new LinkedHashSet(candidates.size()); - for (Iterator it= candidates.iterator(); it.hasNext();) { - Object candidate= it.next(); + private static <T> Set<T> computeZeroEdgeVertices(MultiMap<T, T> map) { + Set<T> candidates= map.keySet(); + Set<T> roots= new LinkedHashSet<>(candidates.size()); + for (Iterator<T> it= candidates.iterator(); it.hasNext();) { + T candidate= it.next(); if (map.get(candidate).isEmpty()) roots.add(candidate); } @@ -186,17 +189,17 @@ public final class DAG { * @param vertex the parent vertex * @return the direct children of <code>vertex</code> */ - public Set getChildren(Object vertex) { + public Set<E> getChildren(E vertex) { return Collections.unmodifiableSet(fOut.get(vertex)); } - private boolean hasPath(Object start, Object end) { + private boolean hasPath(E start, E end) { // break condition if (start == end) return true; - Set children= fOut.get(start); - for (Iterator it= children.iterator(); it.hasNext();) + Set<E> children= fOut.get(start); + for (Iterator<E> it= children.iterator(); it.hasNext();) // recursion if (hasPath(it.next(), end)) return true; diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/RulerColumnPlacement.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/RulerColumnPlacement.java index feed84be7f2..29a810b0344 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/RulerColumnPlacement.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/RulerColumnPlacement.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2008 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -37,12 +37,12 @@ public final class RulerColumnPlacement { /** The placement gravity. */ private final float fGravity; - /** The placement constraints (element type: {@link RulerColumnPlacementConstraint}). */ - private final Set fConstraints; + /** The placement constraints. */ + private final Set<RulerColumnPlacementConstraint> fConstraints; public RulerColumnPlacement() { fGravity= 1f; - fConstraints= Collections.EMPTY_SET; + fConstraints= Collections.emptySet(); } public RulerColumnPlacement(IConfigurationElement element) throws InvalidRegistryObjectException, CoreException { @@ -55,8 +55,8 @@ public final class RulerColumnPlacement { fConstraints= readIds(element.getChildren()); } - private Set readIds(IConfigurationElement[] children) throws CoreException { - Set constraints= new LinkedHashSet((int) (children.length / 0.75) + 1, 0.75f); + private Set<RulerColumnPlacementConstraint> readIds(IConfigurationElement[] children) throws CoreException { + Set<RulerColumnPlacementConstraint> constraints= new LinkedHashSet<>((int) (children.length / 0.75) + 1, 0.75f); for (int i= 0; i < children.length; i++) { IConfigurationElement child= children[i]; String name= child.getName(); @@ -90,7 +90,7 @@ public final class RulerColumnPlacement { * @return the unmodifiable set of placement constraints in the order that they appear in the * extension declaration */ - public Set getConstraints() { + public Set<RulerColumnPlacementConstraint> getConstraints() { return fConstraints; } } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/RulerColumnTarget.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/RulerColumnTarget.java index 82022b3266e..a33af906d00 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/RulerColumnTarget.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/RulerColumnTarget.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2008 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -23,7 +23,7 @@ import org.eclipse.core.runtime.content.IContentType; public abstract class RulerColumnTarget { public abstract boolean matchesEditorId(String editorId); public abstract boolean matchesContentType(IContentType contentType); - public abstract boolean matchesClass(Class clazz); + public abstract boolean matchesClass(Class<?> clazz); /* package visible */ RulerColumnTarget() { @@ -70,7 +70,7 @@ final class AllTarget extends RulerColumnTarget { } @Override - public boolean matchesClass(Class clazz) { + public boolean matchesClass(Class<?> clazz) { return true; } @@ -102,7 +102,7 @@ final class OrTarget extends RulerColumnTarget { } @Override - public boolean matchesClass(Class clazz) { + public boolean matchesClass(Class<?> clazz) { return fEither.matchesClass(clazz) || fOr.matchesClass(clazz); } @@ -131,7 +131,7 @@ final class EditorIdTarget extends RulerColumnTarget { } @Override - public boolean matchesClass(Class clazz) { + public boolean matchesClass(Class<?> clazz) { return false; } @@ -160,7 +160,7 @@ final class ClassTarget extends RulerColumnTarget { } @Override - public boolean matchesClass(Class clazz) { + public boolean matchesClass(Class<?> clazz) { Assert.isLegal(clazz != null); do { @@ -197,7 +197,7 @@ final class ContentTypeTarget extends RulerColumnTarget { } @Override - public boolean matchesClass(Class clazz) { + public boolean matchesClass(Class<?> clazz) { return false; } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/StringSetSerializer.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/StringSetSerializer.java index 7da15e2310d..628469844d5 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/StringSetSerializer.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/rulers/StringSetSerializer.java @@ -22,20 +22,20 @@ public final class StringSetSerializer { private StringSetSerializer() { } - public static String serialize(Set strings) { + public static String serialize(Set<String> strings) { Assert.isLegal(strings != null); StringBuffer buf= new StringBuffer(strings.size() * 20); - for (Iterator it= strings.iterator(); it.hasNext();) { - buf.append((String) it.next()); + for (Iterator<String> it= strings.iterator(); it.hasNext();) { + buf.append(it.next()); if (it.hasNext()) buf.append(DELIM); } return buf.toString(); } - public static Set deserialize(String serialized) { + public static Set<String> deserialize(String serialized) { Assert.isLegal(serialized != null); - Set marked= new HashSet(); + Set<String> marked= new HashSet<>(); StringTokenizer tok= new StringTokenizer(serialized, DELIM); while (tok.hasMoreTokens()) marked.add(tok.nextToken()); @@ -43,13 +43,13 @@ public final class StringSetSerializer { } public static String[] getDifference(String oldValue, String newValue) { - Set oldSet= deserialize(oldValue); - Set newSet= deserialize(newValue); - Set intersection= new HashSet(oldSet); + Set<String> oldSet= deserialize(oldValue); + Set<String> newSet= deserialize(newValue); + Set<String> intersection= new HashSet<>(oldSet); intersection.retainAll(newSet); oldSet.removeAll(intersection); newSet.removeAll(intersection); oldSet.addAll(newSet); - return (String[]) oldSet.toArray(new String[oldSet.size()]); + return oldSet.toArray(new String[oldSet.size()]); } } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/spelling/SpellingEngineRegistry.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/spelling/SpellingEngineRegistry.java index 7ef9e660e61..ce33b3beaf0 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/spelling/SpellingEngineRegistry.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/internal/texteditor/spelling/SpellingEngineRegistry.java @@ -40,7 +40,7 @@ public class SpellingEngineRegistry { public static final String SPELLING_ENGINE_EXTENSION_POINT= "spellingEngine"; //$NON-NLS-1$ /** Ids mapped to descriptors */ - private Map fDescriptorsMap; + private Map<String, SpellingEngineDescriptor> fDescriptorsMap; /** Default descriptor or <code>null</code> */ private SpellingEngineDescriptor fDefaultDescriptor; @@ -60,7 +60,7 @@ public class SpellingEngineRegistry { */ public SpellingEngineDescriptor getDescriptor(String id) { ensureExtensionsLoaded(); - return (SpellingEngineDescriptor) fDescriptorsMap.get(id); + return fDescriptorsMap.get(id); } /** @@ -91,8 +91,8 @@ public class SpellingEngineRegistry { * </p> */ public synchronized void reloadExtensions() { - List descriptors= new ArrayList(); - fDescriptorsMap= new HashMap(); + List<SpellingEngineDescriptor> descriptors= new ArrayList<>(); + fDescriptorsMap= new HashMap<>(); fDefaultDescriptor= null; IConfigurationElement[] elements= Platform.getExtensionRegistry().getConfigurationElementsFor(TextEditorPlugin.PLUGIN_ID, SPELLING_ENGINE_EXTENSION_POINT); for (int i= 0; i < elements.length; i++) { @@ -102,7 +102,7 @@ public class SpellingEngineRegistry { if (fDefaultDescriptor == null && descriptor.isDefault()) fDefaultDescriptor= descriptor; } - fDescriptors= (SpellingEngineDescriptor[]) descriptors.toArray(new SpellingEngineDescriptor[descriptors.size()]); + fDescriptors= descriptors.toArray(new SpellingEngineDescriptor[descriptors.size()]); fLoaded= true; if (fDefaultDescriptor == null && fDescriptors.length > 0) fDefaultDescriptor= fDescriptors[0]; diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractDocumentProvider.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractDocumentProvider.java index 67817ccf1fa..3b54aa99d8e 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractDocumentProvider.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractDocumentProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -186,9 +186,9 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo /** Element information of all connected elements */ - private Map fElementInfoMap= new HashMap(); + private Map<Object, ElementInfo> fElementInfoMap= new HashMap<>(); /** The element state listeners */ - private List fElementStateListeners= new ArrayList(); + private List<IElementStateListener> fElementStateListeners= new ArrayList<>(); /** * The current progress monitor * @since 2.1 @@ -306,7 +306,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo * @return the element info object, or <code>null</code> if none */ protected ElementInfo getElementInfo(Object element) { - return (ElementInfo) fElementInfoMap.get(element); + return fElementInfoMap.get(element); } /** @@ -374,11 +374,11 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo /** * Enumerates the elements connected via this document provider. * - * @return the list of elements (element type: <code>Object</code>) + * @return the list of elements */ - protected Iterator getConnectedElements() { - Set s= new HashSet(); - Set keys= fElementInfoMap.keySet(); + protected Iterator<Object> getConnectedElements() { + Set<Object> s= new HashSet<>(); + Set<Object> keys= fElementInfoMap.keySet(); if (keys != null) s.addAll(keys); return s.iterator(); @@ -386,7 +386,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo @Override public final void connect(Object element) throws CoreException { - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); if (info == null) { info= createElementInfo(element); @@ -418,7 +418,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo */ @Override public final void disconnect(Object element) { - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); if (info == null) return; @@ -451,7 +451,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo if (element == null) return null; - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); return (info != null ? info.fDocument : null); } @@ -461,7 +461,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo if (element == null) return false; - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); return (info != null ? info.fCount == 1 && info.fCanBeSaved : false); } @@ -471,7 +471,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo if (element == null) return null; - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); return (info != null ? info.fModel : null); } @@ -481,7 +481,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo if (element == null) return false; - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); return (info != null ? info.fCanBeSaved : false); } @@ -494,7 +494,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo * @since 3.0 */ protected void doResetDocument(Object element, IProgressMonitor monitor) throws CoreException { - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); if (info != null) { IDocument original= null; @@ -581,7 +581,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo @Override protected void execute(IProgressMonitor pm) throws CoreException { - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); if (info != null) { if (info.fDocument != document) { Status status= new Status(IStatus.WARNING, TextEditorPlugin.PLUGIN_ID, IStatus.ERROR, EditorMessages.AbstractDocumentProvider_error_save_inuse, null); @@ -655,9 +655,9 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo * @see IElementStateListener#elementDirtyStateChanged(Object, boolean) */ protected void fireElementDirtyStateChanged(Object element, boolean isDirty) { - Iterator e= new ArrayList(fElementStateListeners).iterator(); + Iterator<IElementStateListener> e= new ArrayList<>(fElementStateListeners).iterator(); while (e.hasNext()) { - IElementStateListener l= (IElementStateListener) e.next(); + IElementStateListener l= e.next(); l.elementDirtyStateChanged(element, isDirty); } } @@ -670,9 +670,9 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo * @see IElementStateListener#elementContentAboutToBeReplaced(Object) */ protected void fireElementContentAboutToBeReplaced(Object element) { - Iterator e= new ArrayList(fElementStateListeners).iterator(); + Iterator<IElementStateListener> e= new ArrayList<>(fElementStateListeners).iterator(); while (e.hasNext()) { - IElementStateListener l= (IElementStateListener) e.next(); + IElementStateListener l= e.next(); l.elementContentAboutToBeReplaced(element); } } @@ -685,9 +685,9 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo * @see IElementStateListener#elementContentReplaced(Object) */ protected void fireElementContentReplaced(Object element) { - Iterator e= new ArrayList(fElementStateListeners).iterator(); + Iterator<IElementStateListener> e= new ArrayList<>(fElementStateListeners).iterator(); while (e.hasNext()) { - IElementStateListener l= (IElementStateListener) e.next(); + IElementStateListener l= e.next(); l.elementContentReplaced(element); } } @@ -700,9 +700,9 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo * @see IElementStateListener#elementDeleted(Object) */ protected void fireElementDeleted(Object element) { - Iterator e= new ArrayList(fElementStateListeners).iterator(); + Iterator<IElementStateListener> e= new ArrayList<>(fElementStateListeners).iterator(); while (e.hasNext()) { - IElementStateListener l= (IElementStateListener) e.next(); + IElementStateListener l= e.next(); l.elementDeleted(element); } } @@ -715,9 +715,9 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo * @see IElementStateListener#elementMoved(Object, Object) */ protected void fireElementMoved(Object originalElement, Object movedElement) { - Iterator e= new ArrayList(fElementStateListeners).iterator(); + Iterator<IElementStateListener> e= new ArrayList<>(fElementStateListeners).iterator(); while (e.hasNext()) { - IElementStateListener l= (IElementStateListener) e.next(); + IElementStateListener l= e.next(); l.elementMoved(originalElement, movedElement); } } @@ -757,7 +757,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo */ @Override public boolean isStateValidated(Object element) { - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); if (info != null) return info.fIsStateValidated; return false; @@ -784,7 +784,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo @Override protected void execute(IProgressMonitor monitor) throws CoreException { - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); if (info == null) return; @@ -834,7 +834,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo @Override public final void updateStateCache(Object element) throws CoreException { - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); if (info != null) { boolean wasReadOnly= isReadOnly(element); doUpdateStateCache(element); @@ -848,7 +848,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo @Override public void setCanSaveDocument(Object element) { if (element != null) { - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); if (info != null) { info.fCanBeSaved= true; removeUnchangedElementListeners(element, info); @@ -867,7 +867,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo * @since 2.0 */ protected void fireElementStateValidationChanged(Object element, boolean isStateValidated) { - Iterator e= new ArrayList(fElementStateListeners).iterator(); + Iterator<IElementStateListener> e= new ArrayList<>(fElementStateListeners).iterator(); while (e.hasNext()) { Object o= e.next(); if (o instanceof IElementStateListenerExtension) { @@ -886,7 +886,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo * @since 2.0 */ protected void fireElementStateChanging(Object element) { - Iterator e= new ArrayList(fElementStateListeners).iterator(); + Iterator<IElementStateListener> e= new ArrayList<>(fElementStateListeners).iterator(); while (e.hasNext()) { Object o= e.next(); if (o instanceof IElementStateListenerExtension) { @@ -905,7 +905,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo * @since 2.0 */ protected void fireElementStateChangeFailed(Object element) { - Iterator e= new ArrayList(fElementStateListeners).iterator(); + Iterator<IElementStateListener> e= new ArrayList<>(fElementStateListeners).iterator(); while (e.hasNext()) { Object o= e.next(); if (o instanceof IElementStateListenerExtension) { @@ -917,7 +917,7 @@ public abstract class AbstractDocumentProvider implements IDocumentProvider, IDo @Override public IStatus getStatus(Object element) { - ElementInfo info= (ElementInfo) fElementInfoMap.get(element); + ElementInfo info= fElementInfoMap.get(element); if (info != null) { if (info.fStatus != null) return info.fStatus; diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractTextEditor.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractTextEditor.java index e629458d009..0ad6d352156 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractTextEditor.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AbstractTextEditor.java @@ -324,7 +324,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit private static final int SINGLE_CARET_WIDTH= 1; /** - * The symbolic name of the block seletion mode font. + * The symbolic name of the block selection mode font. * * @since 3.5 */ @@ -752,7 +752,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit ActionActivationCode code= null; int size= fActivationCodes.size(); for (int i= 0; i < size; i++) { - code= (ActionActivationCode) fActivationCodes.get(i); + code= fActivationCodes.get(i); if (code.matches(event)) { IAction action= getAction(code.fActionId); if (action != null) { @@ -1581,7 +1581,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit protected static class ColumnSupport implements IColumnSupport { private final AbstractTextEditor fEditor; private final RulerColumnRegistry fRegistry; - private final List fColumns; + private final List<IContributedRulerColumn> fColumns; /** * Creates a new column support for the given editor. Only the editor itself should normally @@ -1595,7 +1595,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit Assert.isLegal(registry != null); fEditor= editor; fRegistry= registry; - fColumns= new ArrayList(); + fColumns= new ArrayList<>(); } @Override @@ -1671,8 +1671,8 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * @return the matching column or <code>null</code> */ private IContributedRulerColumn getVisibleColumn(CompositeRuler ruler, RulerColumnDescriptor descriptor) { - for (Iterator it= ruler.getDecoratorIterator(); it.hasNext();) { - IVerticalRulerColumn column= (IVerticalRulerColumn)it.next(); + for (Iterator<IVerticalRulerColumn> it= ruler.getDecoratorIterator(); it.hasNext();) { + IVerticalRulerColumn column= it.next(); if (column instanceof IContributedRulerColumn) { IContributedRulerColumn rulerColumn= (IContributedRulerColumn)column; RulerColumnDescriptor rcd= rulerColumn.getDescriptor(); @@ -1692,10 +1692,10 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit */ private int computeIndex(CompositeRuler ruler, RulerColumnDescriptor descriptor) { int index= 0; - List all= fRegistry.getColumnDescriptors(); + List<RulerColumnDescriptor> all= fRegistry.getColumnDescriptors(); int newPos= all.indexOf(descriptor); - for (Iterator it= ruler.getDecoratorIterator(); it.hasNext();) { - IVerticalRulerColumn column= (IVerticalRulerColumn) it.next(); + for (Iterator<IVerticalRulerColumn> it= ruler.getDecoratorIterator(); it.hasNext();) { + IVerticalRulerColumn column= it.next(); if (column instanceof IContributedRulerColumn) { RulerColumnDescriptor rcd= ((IContributedRulerColumn)column).getDescriptor(); if (rcd != null && all.indexOf(rcd) > newPos) @@ -1746,8 +1746,8 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit */ @Override public void dispose() { - for (Iterator iter= new ArrayList(fColumns).iterator(); iter.hasNext();) - removeColumn(getRuler(), (IContributedRulerColumn)iter.next()); + for (Iterator<IContributedRulerColumn> iter= new ArrayList<>(fColumns).iterator(); iter.hasNext();) + removeColumn(getRuler(), iter.next()); fColumns.clear(); } } @@ -2402,23 +2402,23 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit /** The editor's presentation mode. */ private boolean fShowHighlightRangeOnly; /** The actions registered with the editor. */ - private Map fActions= new HashMap(10); + private Map<String, IAction> fActions= new HashMap<>(10); /** The actions marked as selection dependent. */ - private List fSelectionActions= new ArrayList(5); + private List<String> fSelectionActions= new ArrayList<>(5); /** The actions marked as content dependent. */ - private List fContentActions= new ArrayList(5); + private List<String> fContentActions= new ArrayList<>(5); /** * The actions marked as property dependent. * @since 2.0 */ - private List fPropertyActions= new ArrayList(5); + private List<String> fPropertyActions= new ArrayList<>(5); /** * The actions marked as state dependent. * @since 2.0 */ - private List fStateActions= new ArrayList(5); + private List<String> fStateActions= new ArrayList<>(5); /** The editor's action activation codes. */ - private List fActivationCodes= new ArrayList(2); + private List<ActionActivationCode> fActivationCodes= new ArrayList<>(2); /** The verify key listener for activation code triggering. */ private ActivationCodeTrigger fActivationCodeTrigger= new ActivationCodeTrigger(); /** Context menu listener. */ @@ -2464,7 +2464,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * The map of the editor's status fields. * @since 2.0 */ - private Map fStatusFields; + private Map<String, IStatusField> fStatusFields; /** * The editor's cursor listener. * @since 2.0 @@ -2509,7 +2509,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * Ruler context menu listeners. * @since 2.0 */ - private List fRulerContextMenuListeners= new ArrayList(); + private List<IMenuListener> fRulerContextMenuListeners= new ArrayList<>(); /** * Indicates whether sanity checking in enabled. * @since 2.0 @@ -2549,7 +2549,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * The sequence of legal editor insert modes. * @since 3.0 */ - private List fLegalInsertModes= null; + private List<InsertMode> fLegalInsertModes= null; /** * The non-default caret. * @since 3.0 @@ -3217,7 +3217,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * @since 3.3 */ protected void updateContributedRulerColumns(CompositeRuler ruler) { - IColumnSupport support= (IColumnSupport)getAdapter(IColumnSupport.class); + IColumnSupport support= getAdapter(IColumnSupport.class); if (support == null) return; @@ -3226,9 +3226,9 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit adapter= new RulerColumnPreferenceAdapter(getPreferenceStore(), PREFERENCE_RULER_CONTRIBUTIONS); RulerColumnRegistry registry= RulerColumnRegistry.getDefault(); - List descriptors= registry.getColumnDescriptors(); - for (Iterator it= descriptors.iterator(); it.hasNext();) { - final RulerColumnDescriptor descriptor= (RulerColumnDescriptor) it.next(); + List<RulerColumnDescriptor> descriptors= registry.getColumnDescriptors(); + for (Iterator<RulerColumnDescriptor> it= descriptors.iterator(); it.hasNext();) { + final RulerColumnDescriptor descriptor= it.next(); support.setColumnVisible(descriptor, adapter == null || adapter.isEnabled(descriptor)); } } @@ -3277,7 +3277,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit if (dndService == null) return; - ITextEditorDropTargetListener listener= (ITextEditorDropTargetListener) getAdapter(ITextEditorDropTargetListener.class); + ITextEditorDropTargetListener listener= getAdapter(ITextEditorDropTargetListener.class); if (listener == null) { Object object= Platform.getAdapterManager().loadAdapter(this, "org.eclipse.ui.texteditor.ITextEditorDropTargetListener"); //$NON-NLS-1$ @@ -3552,7 +3552,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit if (fTextDragAndDropToken == null) { // Move in same editor - end compound change - IRewriteTarget target= (IRewriteTarget)getAdapter(IRewriteTarget.class); + IRewriteTarget target= getAdapter(IRewriteTarget.class); if (target != null) target.endCompoundChange(); } @@ -3614,7 +3614,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit } // Start compound change - IRewriteTarget target= (IRewriteTarget)getAdapter(IRewriteTarget.class); + IRewriteTarget target= getAdapter(IRewriteTarget.class); if (target != null) target.beginCompoundChange(); } @@ -4197,7 +4197,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit if (fIsOverwriting) toggleOverwriteMode(); - setInsertMode((InsertMode) getLegalInsertModes().get(0)); + setInsertMode(getLegalInsertModes().get(0)); updateCaret(); updateStatusField(ITextEditorActionConstants.STATUS_CATEGORY_ELEMENT_STATE); @@ -4592,7 +4592,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit if (PREFERENCE_RULER_CONTRIBUTIONS.equals(property)) { String[] difference= StringSetSerializer.getDifference((String) event.getOldValue(), (String) event.getNewValue()); - IColumnSupport support= (IColumnSupport) getAdapter(IColumnSupport.class); + IColumnSupport support= getAdapter(IColumnSupport.class); for (int i= 0; i < difference.length; i++) { RulerColumnDescriptor desc= RulerColumnRegistry.getDefault().getColumnDescriptor(difference[i]); if (desc != null && support.isColumnSupported(desc)) { @@ -5195,7 +5195,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit public void setAction(String actionID, IAction action) { Assert.isNotNull(actionID); if (action == null) { - action= (IAction) fActions.remove(actionID); + action= fActions.remove(actionID); if (action != null) fActivationCodeTrigger.unregisterActionFromKeyActivation(action); } else { @@ -5221,18 +5221,18 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit private void setActionActivation(boolean state) { if (state) { fActivationCodeTrigger.install(); - Iterator iter= fActions.values().iterator(); + Iterator<IAction> iter= fActions.values().iterator(); while (iter.hasNext()) { - IAction action= (IAction)iter.next(); + IAction action= iter.next(); if (action != null) fActivationCodeTrigger.registerActionForKeyActivation(action); } getEditorSite().getActionBarContributor().setActiveEditor(this); } else { getEditorSite().getActionBarContributor().setActiveEditor(null); - Iterator iter= fActions.values().iterator(); + Iterator<IAction> iter= fActions.values().iterator(); while (iter.hasNext()) { - IAction action= (IAction)iter.next(); + IAction action= iter.next(); if (action != null) fActivationCodeTrigger.unregisterActionFromKeyActivation(action); } @@ -5271,7 +5271,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit private ActionActivationCode findActionActivationCode(String actionID) { int size= fActivationCodes.size(); for (int i= 0; i < size; i++) { - ActionActivationCode code= (ActionActivationCode) fActivationCodes.get(i); + ActionActivationCode code= fActivationCodes.get(i); if (actionID.equals(code.fActionId)) return code; } @@ -5289,7 +5289,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit @Override public IAction getAction(String actionID) { Assert.isNotNull(actionID); - IAction action= (IAction) fActions.get(actionID); + IAction action= fActions.get(actionID); if (action == null) { action= findContributedAction(actionID); @@ -5309,7 +5309,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * @since 2.0 */ private IAction findContributedAction(String actionID) { - List actions= new ArrayList(); + List<IConfigurationElement> actions= new ArrayList<>(); IConfigurationElement[] elements= Platform.getExtensionRegistry().getConfigurationElementsFor(PlatformUI.PLUGIN_ID, "editorActions"); //$NON-NLS-1$ for (int i= 0; i < elements.length; i++) { IConfigurationElement element= elements[i]; @@ -5329,7 +5329,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit if (actionSize > 0) { IConfigurationElement element; if (actionSize > 1) { - IConfigurationElement[] actionArray= (IConfigurationElement[])actions.toArray(new IConfigurationElement[actionSize]); + IConfigurationElement[] actionArray= actions.toArray(new IConfigurationElement[actionSize]); ConfigurationElementSorter sorter= new ConfigurationElementSorter() { @Override public IConfigurationElement getConfigurationElement(Object object) { @@ -5339,7 +5339,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit sorter.sort(actionArray); element= actionArray[0]; } else - element= (IConfigurationElement)actions.get(0); + element= actions.get(0); try { return new ContributedAction(getSite(), element); @@ -5360,7 +5360,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit private void updateAction(String actionId) { Assert.isNotNull(actionId); if (fActions != null) { - IAction action= (IAction) fActions.get(actionId); + IAction action= fActions.get(actionId); if (action instanceof IUpdate) ((IUpdate) action).update(); } @@ -5433,9 +5433,9 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit */ protected void updateSelectionDependentActions() { if (fSelectionActions != null) { - Iterator e= fSelectionActions.iterator(); + Iterator<String> e= fSelectionActions.iterator(); while (e.hasNext()) - updateAction((String) e.next()); + updateAction(e.next()); } } @@ -5444,9 +5444,9 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit */ protected void updateContentDependentActions() { if (fContentActions != null) { - Iterator e= fContentActions.iterator(); + Iterator<String> e= fContentActions.iterator(); while (e.hasNext()) - updateAction((String) e.next()); + updateAction(e.next()); } } @@ -5456,9 +5456,9 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit */ protected void updatePropertyDependentActions() { if (fPropertyActions != null) { - Iterator e= fPropertyActions.iterator(); + Iterator<String> e= fPropertyActions.iterator(); while (e.hasNext()) - updateAction((String) e.next()); + updateAction(e.next()); } } @@ -5468,9 +5468,9 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit */ protected void updateStateDependentActions() { if (fStateActions != null) { - Iterator e= fStateActions.iterator(); + Iterator<String> e= fStateActions.iterator(); while (e.hasNext()) - updateAction((String) e.next()); + updateAction(e.next()); } } @@ -6046,8 +6046,8 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit menu.add(new Separator(ITextEditorActionConstants.GROUP_REST)); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); - for (Iterator i= fRulerContextMenuListeners.iterator(); i.hasNext();) - ((IMenuListener) i.next()).menuAboutToShow(menu); + for (Iterator<IMenuListener> i= fRulerContextMenuListeners.iterator(); i.hasNext();) + i.next().menuAboutToShow(menu); addAction(menu, ITextEditorActionConstants.RULER_MANAGE_BOOKMARKS); addAction(menu, ITextEditorActionConstants.RULER_MANAGE_TASKS); @@ -6097,8 +6097,9 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit return getEditorSite().getActionBars().getStatusLineManager(); } + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Class required) { + public <T> T getAdapter(Class<T> required) { if (IEditorStatusLine.class.equals(required)) { if (fEditorStatusLine == null) { @@ -6107,12 +6108,12 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit if (statusLineManager != null && selectionProvider != null) fEditorStatusLine= new EditorStatusLine(statusLineManager, selectionProvider); } - return fEditorStatusLine; + return (T) fEditorStatusLine; } if (IVerticalRulerInfo.class.equals(required)) { if (fVerticalRuler != null) - return fVerticalRuler; + return (T) fVerticalRuler; } if (IMarkRegionTarget.class.equals(required)) { @@ -6121,14 +6122,14 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit if (manager != null) fMarkRegionTarget= (fSourceViewer == null ? null : new MarkRegionTarget(fSourceViewer, manager)); } - return fMarkRegionTarget; + return (T) fMarkRegionTarget; } if (IDeleteLineTarget.class.equals(required)) { if (fDeleteLineTarget == null) { fDeleteLineTarget= new TextViewerDeleteLineTarget(fSourceViewer); } - return fDeleteLineTarget; + return (T) fDeleteLineTarget; } if (IncrementalFindTarget.class.equals(required)) { @@ -6137,7 +6138,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit if (manager != null) fIncrementalFindTarget= (fSourceViewer == null ? null : new IncrementalFindTarget(fSourceViewer, manager)); } - return fIncrementalFindTarget; + return (T) fIncrementalFindTarget; } if (IFindReplaceTarget.class.equals(required)) { @@ -6149,27 +6150,27 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit fFindReplaceTarget.setScopeHighlightColor(fFindScopeHighlightColor); } } - return fFindReplaceTarget; + return (T) fFindReplaceTarget; } if (ITextOperationTarget.class.equals(required)) - return (fSourceViewer == null ? null : fSourceViewer.getTextOperationTarget()); + return (fSourceViewer == null ? null : (T) fSourceViewer.getTextOperationTarget()); if (IRewriteTarget.class.equals(required)) { if (fSourceViewer instanceof ITextViewerExtension) { ITextViewerExtension extension= (ITextViewerExtension) fSourceViewer; - return extension.getRewriteTarget(); + return (T) extension.getRewriteTarget(); } return null; } if (Control.class.equals(required)) - return fSourceViewer != null ? fSourceViewer.getTextWidget() : null; + return fSourceViewer != null ? (T) fSourceViewer.getTextWidget() : null; if (IColumnSupport.class.equals(required)) { if (fColumnSupport == null) fColumnSupport= createColumnSupport(); - return fColumnSupport; + return (T) fColumnSupport; } return super.getAdapter(required); @@ -6342,7 +6343,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit if (field != null) { if (fStatusFields == null) - fStatusFields= new HashMap(3); + fStatusFields= new HashMap<>(3); fStatusFields.put(category, field); updateStatusField(category); @@ -6363,7 +6364,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit */ protected IStatusField getStatusField(String category) { if (category != null && fStatusFields != null) - return (IStatusField) fStatusFields.get(category); + return fStatusFields.get(category); return null; } @@ -6384,7 +6385,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit @Override public void setInsertMode(InsertMode newMode) { - List legalModes= getLegalInsertModes(); + List<InsertMode> legalModes= getLegalInsertModes(); if (!legalModes.contains(newMode)) throw new IllegalArgumentException(); @@ -6400,9 +6401,9 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * @return the set of legal insert modes * @since 3.0 */ - protected List getLegalInsertModes() { + protected List<InsertMode> getLegalInsertModes() { if (fLegalInsertModes == null) { - fLegalInsertModes= new ArrayList(); + fLegalInsertModes= new ArrayList<>(); fLegalInsertModes.add(SMART_INSERT); fLegalInsertModes.add(INSERT); } @@ -6412,7 +6413,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit private void switchToNextInsertMode() { InsertMode mode= getInsertMode(); - List legalModes= getLegalInsertModes(); + List<InsertMode> legalModes= getLegalInsertModes(); int i= 0; while (i < legalModes.size()) { @@ -6421,7 +6422,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit } i= (i + 1) % legalModes.size(); - InsertMode newMode= (InsertMode) legalModes.get(i); + InsertMode newMode= legalModes.get(i); setInsertMode(newMode); } @@ -6442,7 +6443,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * @since 3.0 */ protected void configureInsertMode(InsertMode mode, boolean legal) { - List legalModes= getLegalInsertModes(); + List<InsertMode> legalModes= getLegalInsertModes(); if (legal) { if (!legalModes.contains(mode)) legalModes.add(mode); @@ -6663,9 +6664,9 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit */ protected void updateStatusFields() { if (fStatusFields != null) { - Iterator e= fStatusFields.keySet().iterator(); + Iterator<String> e= fStatusFields.keySet().iterator(); while (e.hasNext()) - updateStatusField((String) e.next()); + updateStatusField(e.next()); } } @@ -6839,7 +6840,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * @since 3.2 */ protected void setStatusLineErrorMessage(String message) { - IEditorStatusLine statusLine= (IEditorStatusLine)getAdapter(IEditorStatusLine.class); + IEditorStatusLine statusLine= getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(true, message, null); } @@ -6851,7 +6852,7 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * @since 3.2 */ protected void setStatusLineMessage(String message) { - IEditorStatusLine statusLine= (IEditorStatusLine)getAdapter(IEditorStatusLine.class); + IEditorStatusLine statusLine= getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(false, message, null); } @@ -6905,9 +6906,9 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit int distance= Integer.MAX_VALUE; IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); - Iterator e= model.getAnnotationIterator(); + Iterator<Annotation> e= model.getAnnotationIterator(); while (e.hasNext()) { - Annotation a= (Annotation) e.next(); + Annotation a= e.next(); if (!isNavigationTarget(a)) continue; @@ -7150,15 +7151,16 @@ public abstract class AbstractTextEditor extends EditorPart implements ITextEdit * * @see org.eclipse.ui.Saveable#getAdapter(java.lang.Class) */ + @SuppressWarnings("unchecked") @Override - public Object getAdapter(Class adapter) { + public <T> T getAdapter(Class<T> adapter) { if (adapter == IDocument.class) { if (fDocument == null) { IDocumentProvider documentProvider= fTextEditor.getDocumentProvider(); if (documentProvider != null) fDocument= documentProvider.getDocument(fEditorInput); } - return fDocument; + return (T) fDocument; } return super.getAdapter(adapter); } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AnnotationPreference.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AnnotationPreference.java index 7f57fbad566..96183bb9ccf 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AnnotationPreference.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/AnnotationPreference.java @@ -317,7 +317,7 @@ public class AnnotationPreference { * The map of attributes. * @since 3.0 */ - private Map fAttributes= new HashMap(); + private Map<Object, Object> fAttributes= new HashMap<>(); diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/BasicTextEditorActionContributor.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/BasicTextEditorActionContributor.java index 29acfb5422c..0e178ecf129 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/BasicTextEditorActionContributor.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/BasicTextEditorActionContributor.java @@ -31,7 +31,6 @@ import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.part.EditorActionBarContributor; - /** * Manages the installation and removal of global actions for * the same type of editors. @@ -136,7 +135,7 @@ public class BasicTextEditorActionContributor extends EditorActionBarContributor * The map of status fields. * @since 2.0 */ - private Map fStatusFields; + private Map<StatusFieldDef, StatusLineContributionItem> fStatusFields; /** @@ -160,7 +159,7 @@ public class BasicTextEditorActionContributor extends EditorActionBarContributor fHippieCompletion= new RetargetTextEditorAction(EditorMessages.getBundleForConstructedKeys(), "Editor.HippieCompletion."); //$NON-NLS-1$ fHippieCompletion.setActionDefinitionId(ITextEditorActionDefinitionIds.HIPPIE_COMPLETION); - fStatusFields= new HashMap(3); + fStatusFields= new HashMap<>(3); for (int i= 0; i < STATUS_FIELD_DEFS.length; i++) { StatusFieldDef fieldDef= STATUS_FIELD_DEFS[i]; fStatusFields.put(fieldDef, new StatusLineContributionItem(fieldDef.category, fieldDef.visible, fieldDef.widthInChars)); @@ -226,7 +225,7 @@ public class BasicTextEditorActionContributor extends EditorActionBarContributor for (int i= 0; i < STATUS_FIELD_DEFS.length; i++) { if (fActiveEditorPart instanceof ITextEditorExtension) { - StatusLineContributionItem statusField= (StatusLineContributionItem) fStatusFields.get(STATUS_FIELD_DEFS[i]); + StatusLineContributionItem statusField= fStatusFields.get(STATUS_FIELD_DEFS[i]); statusField.setActionHandler(getAction(editor, STATUS_FIELD_DEFS[i].actionId)); ITextEditorExtension extension= (ITextEditorExtension) fActiveEditorPart; extension.setStatusField(statusField, STATUS_FIELD_DEFS[i].category); @@ -296,7 +295,7 @@ public class BasicTextEditorActionContributor extends EditorActionBarContributor public void contributeToStatusLine(IStatusLineManager statusLineManager) { super.contributeToStatusLine(statusLineManager); for (int i= 0; i < STATUS_FIELD_DEFS.length; i++) - statusLineManager.add((IContributionItem)fStatusFields.get(STATUS_FIELD_DEFS[i])); + statusLineManager.add(fStatusFields.get(STATUS_FIELD_DEFS[i])); } @Override diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java index 528157f8a60..c6839b2de92 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConfigurationElementSorter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -19,6 +19,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import org.osgi.framework.Bundle; @@ -69,10 +70,10 @@ public abstract class ConfigurationElementSorter { * Compare configuration elements according to the prerequisite relation * of their defining plug-ins. */ - private class ConfigurationElementComparator implements Comparator { + private class ConfigurationElementComparator implements Comparator<Object> { - private Map fDescriptorMapping; - private Map fPrereqsMapping; + private Map<Object, String> fDescriptorMapping; + private Map<String, Set<String>> fPrereqsMapping; public ConfigurationElementComparator(Object[] elements) { Assert.isNotNull(elements); @@ -104,14 +105,14 @@ public abstract class ConfigurationElementSorter { if (element0 == null || element1 == null) return false; - String pluginDesc0= (String)fDescriptorMapping.get(element0); - String pluginDesc1= (String)fDescriptorMapping.get(element1); + String pluginDesc0= fDescriptorMapping.get(element0); + String pluginDesc1= fDescriptorMapping.get(element1); // performance tuning - code below would give same result if (pluginDesc0.equals(pluginDesc1)) return false; - Set prereqUIds0= (Set)fPrereqsMapping.get(pluginDesc0); + Set<String> prereqUIds0= fPrereqsMapping.get(pluginDesc0); return prereqUIds0.contains(pluginDesc1); } @@ -123,9 +124,9 @@ public abstract class ConfigurationElementSorter { */ private void initialize(Object[] elements) { int length= elements.length; - fDescriptorMapping= new HashMap(length); - fPrereqsMapping= new HashMap(length); - Set fBundleSet= new HashSet(length); + fDescriptorMapping= new HashMap<>(length); + fPrereqsMapping= new HashMap<>(length); + Set<Bundle> fBundleSet= new HashSet<>(length); for (int i= 0; i < length; i++) { IConfigurationElement configElement= getConfigurationElement(elements[i]); @@ -134,12 +135,12 @@ public abstract class ConfigurationElementSorter { fBundleSet.add(bundle); } - Iterator iter= fBundleSet.iterator(); + Iterator<Bundle> iter= fBundleSet.iterator(); while (iter.hasNext()) { - Bundle bundle= (Bundle)iter.next(); - List toTest= new ArrayList(fBundleSet); + Bundle bundle= iter.next(); + List<Bundle> toTest= new ArrayList<>(fBundleSet); toTest.remove(bundle); - Set prereqUIds= new HashSet(Math.max(0, toTest.size() - 1)); + Set<String> prereqUIds= new HashSet<>(Math.max(0, toTest.size() - 1)); fPrereqsMapping.put(bundle.getSymbolicName(), prereqUIds); String requires = bundle.getHeaders().get(Constants.REQUIRE_BUNDLE); @@ -161,7 +162,7 @@ public abstract class ConfigurationElementSorter { while (i < manifestElements.length && !toTest.isEmpty()) { String prereqUId= manifestElements[i].getValue(); for (int j= 0; j < toTest.size();) { - Bundle toTest_j= (Bundle)toTest.get(j); + Bundle toTest_j= toTest.get(j); if (toTest_j.getSymbolicName().equals(prereqUId)) { toTest.remove(toTest_j); prereqUIds.add(toTest_j.getSymbolicName()); @@ -185,10 +186,10 @@ public abstract class ConfigurationElementSorter { if (bundle != null) { String bundleName= bundle.getSymbolicName(); if (bundleName != null) { - Set entries= fDescriptorMapping.entrySet(); - Iterator iter= entries.iterator(); + Set<Entry<Object, String>> entries= fDescriptorMapping.entrySet(); + Iterator<Entry<Object, String>> iter= entries.iterator(); while (iter.hasNext()) { - Map.Entry entry= (Map.Entry)iter.next(); + Entry<Object, String> entry= iter.next(); if (bundleName.equals(entry.getValue())) { IExtension extension = getConfigurationElement(entry.getKey()).getDeclaringExtension(); return extension.getExtensionPointUniqueIdentifier(); diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConvertLineDelimitersAction.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConvertLineDelimitersAction.java index 526f9714165..1aff469ad87 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConvertLineDelimitersAction.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/ConvertLineDelimitersAction.java @@ -28,6 +28,7 @@ import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.TextUtilities; @@ -147,7 +148,7 @@ public class ConvertLineDelimitersAction extends TextEditorAction { fRewriteTarget.setRedraw(false); fRewriteTarget.beginCompoundChange(); - Map partitioners= TextUtilities.removeDocumentPartitioners(document); + Map<String, IDocumentPartitioner> partitioners= TextUtilities.removeDocumentPartitioners(document); try { for (int i= 0; i < lineCount; i++) { diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindNextAction.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindNextAction.java index d72befd6911..82b678c8d54 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindNextAction.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindNextAction.java @@ -55,7 +55,7 @@ public class FindNextAction extends ResourceAction implements IUpdate { /** The dialog settings to retrieve the last search */ private IDialogSettings fDialogSettings; /** The find history as initially given in the dialog settings. */ - private List fFindHistory= new ArrayList(); + private List<String> fFindHistory= new ArrayList<>(); /** The find string as initially given in the dialog settings. */ private String fFindString; /** The search direction as initially given in the dialog settings. */ @@ -130,7 +130,7 @@ public class FindNextAction extends ResourceAction implements IUpdate { String fullSelection= fTarget.getSelectionText(); String firstLine= getFirstLine(fullSelection); if ((firstLine.length() == 0 || fRegExSearch && fullSelection.equals(fSelection)) && !fFindHistory.isEmpty()) - return (String) fFindHistory.get(0); + return fFindHistory.get(0); else if (fRegExSearch && fullSelection.length() > 0) return FindReplaceDocumentAdapter.escapeForRegExPattern(fullSelection); else diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceAction.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceAction.java index c8c8ff4d5b8..f2099d0603d 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceAction.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceAction.java @@ -111,7 +111,7 @@ public class FindReplaceAction extends ResourceAction implements IUpdate { } private void partActivated(IWorkbenchPart part) { - IFindReplaceTarget target= part == null ? null : (IFindReplaceTarget) part.getAdapter(IFindReplaceTarget.class); + IFindReplaceTarget target= part == null ? null : part.getAdapter(IFindReplaceTarget.class); fPreviousPart= fPart; fPart= target == null ? null : part; diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceDialog.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceDialog.java index ccb9e673787..757d37af271 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceDialog.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/FindReplaceDialog.java @@ -166,8 +166,8 @@ class FindReplaceDialog extends Dialog { */ boolean fIsRegExInit; - private List fFindHistory; - private List fReplaceHistory; + private List<String> fFindHistory; + private List<String> fReplaceHistory; private IRegion fOldScope; private boolean fIsTargetEditable; @@ -222,7 +222,7 @@ class FindReplaceDialog extends Dialog { * Holds the mnemonic/button pairs for all buttons. * @since 3.7 */ - private HashMap fMnemonicButtonMap= new HashMap(); + private HashMap<Character, Button> fMnemonicButtonMap= new HashMap<>(); /** @@ -236,8 +236,8 @@ class FindReplaceDialog extends Dialog { fTarget= null; fDialogPositionInit= null; - fFindHistory= new ArrayList(HISTORY_SIZE - 1); - fReplaceHistory= new ArrayList(HISTORY_SIZE - 1); + fFindHistory= new ArrayList<>(HISTORY_SIZE - 1); + fReplaceHistory= new ArrayList<>(HISTORY_SIZE - 1); fWrapInit= false; fCaseInit= false; @@ -438,7 +438,7 @@ class FindReplaceDialog extends Dialog { else if (e.detail == SWT.TRAVERSE_MNEMONIC) { Character mnemonic= new Character(Character.toLowerCase(e.character)); if (fMnemonicButtonMap.containsKey(mnemonic)) { - Button button= (Button)fMnemonicButtonMap.get(mnemonic); + Button button= fMnemonicButtonMap.get(mnemonic); if ((fFindField.isFocusControl() || fReplaceField.isFocusControl() || (button.getStyle() & SWT.PUSH) != 0) && button.isEnabled()) { Event event= new Event(); @@ -985,7 +985,7 @@ class FindReplaceDialog extends Dialog { * Returns the dialog's history. * @return the dialog's history */ - private List getFindHistory() { + private List<String> getFindHistory() { return fFindHistory; } @@ -1006,7 +1006,7 @@ class FindReplaceDialog extends Dialog { * Returns the dialog's replace history. * @return the dialog's replace history */ - private List getReplaceHistory() { + private List<String> getReplaceHistory() { return fReplaceHistory; } @@ -1130,7 +1130,7 @@ class FindReplaceDialog extends Dialog { } else { if ("".equals(fFindField.getText())) { //$NON-NLS-1$ if (fFindHistory.size() > 0) - fFindField.setText((String) fFindHistory.get(0)); + fFindField.setText(fFindHistory.get(0)); else fFindField.setText(""); //$NON-NLS-1$ } @@ -1628,7 +1628,7 @@ class FindReplaceDialog extends Dialog { * @param combo combo to be updated * @param content to be put into the combo */ - private void updateCombo(Combo combo, List content) { + private void updateCombo(Combo combo, List<String> content) { combo.removeAll(); for (int i= 0; i < content.size(); i++) { combo.add(content.get(i).toString()); @@ -1669,7 +1669,7 @@ class FindReplaceDialog extends Dialog { * @param combo to be updated * @param history to be put into the combo */ - private void updateHistory(Combo combo, List history) { + private void updateHistory(Combo combo, List<String> history) { String findString= combo.getText(); int index= history.indexOf(findString); if (index != 0) { @@ -1812,7 +1812,7 @@ class FindReplaceDialog extends Dialog { String[] findHistory= s.getArray("findhistory"); //$NON-NLS-1$ if (findHistory != null) { - List history= getFindHistory(); + List<String> history= getFindHistory(); history.clear(); for (int i= 0; i < findHistory.length; i++) history.add(findHistory[i]); @@ -1820,7 +1820,7 @@ class FindReplaceDialog extends Dialog { String[] replaceHistory= s.getArray("replacehistory"); //$NON-NLS-1$ if (replaceHistory != null) { - List history= getReplaceHistory(); + List<String> history= getReplaceHistory(); history.clear(); for (int i= 0; i < replaceHistory.length; i++) history.add(replaceHistory[i]); @@ -1839,7 +1839,7 @@ class FindReplaceDialog extends Dialog { s.put("incremental", fIncrementalInit); //$NON-NLS-1$ s.put("isRegEx", fIsRegExInit); //$NON-NLS-1$ - List history= getFindHistory(); + List<String> history= getFindHistory(); String findString= getFindString(); if (findString.length() > 0) history.add(0, findString); @@ -1860,11 +1860,11 @@ class FindReplaceDialog extends Dialog { * @param sectionName the section name * @since 3.2 */ - private void writeHistory(List history, IDialogSettings settings, String sectionName) { + private void writeHistory(List<String> history, IDialogSettings settings, String sectionName) { int itemCount= history.size(); - Set distinctItems= new HashSet(itemCount); + Set<String> distinctItems= new HashSet<>(itemCount); for (int i= 0; i < itemCount; i++) { - String item= (String)history.get(i); + String item= history.get(i); if (distinctItems.contains(item)) { history.remove(i--); itemCount--; diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HippieCompleteAction.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HippieCompleteAction.java index dc9abcd00ca..fdac907f881 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HippieCompleteAction.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HippieCompleteAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -67,14 +67,14 @@ final class HippieCompleteAction extends TextEditorAction { * * @since 3.6 */ - private final Iterator suggestions; + private final Iterator<String> suggestions; /** * List of Strings with the suggestions that are already consumed from the iterator * * @since 3.6 */ - private final List consumedSuggestions; + private final List<String> consumedSuggestions; /** * Do we have only 1 (empty) completion available? @@ -88,7 +88,7 @@ final class HippieCompleteAction extends TextEditorAction { * * @since 3.6 */ - private final HashSet alreadyFound; + private final HashSet<String> alreadyFound; /** * Create a new completion state object @@ -97,10 +97,10 @@ final class HippieCompleteAction extends TextEditorAction { * @param startOffset the position in the parent document at which the completions will be * inserted. */ - CompletionState(Iterator suggestions, int startOffset) { + CompletionState(Iterator<String> suggestions, int startOffset) { this.suggestions= suggestions; - this.consumedSuggestions= new ArrayList(); - this.alreadyFound= new HashSet(); + this.consumedSuggestions= new ArrayList<>(); + this.alreadyFound= new HashSet<>(); this.startOffset= startOffset; this.length= 0; this.nextSuggestion= 0; @@ -108,7 +108,7 @@ final class HippieCompleteAction extends TextEditorAction { //Let's see if only 1 is available. if (this.suggestions.hasNext()) { - addNewToken((String)this.suggestions.next()); + addNewToken(this.suggestions.next()); boolean hasOnly1Temp= true; while (this.suggestions.hasNext()) { @@ -137,7 +137,7 @@ final class HippieCompleteAction extends TextEditorAction { String ret= null; if (this.consumedSuggestions.size() > nextSuggestion) { //We already consumed one that we didn't return - ret= (String)this.consumedSuggestions.get(nextSuggestion); + ret= this.consumedSuggestions.get(nextSuggestion); nextSuggestion++; } @@ -146,7 +146,7 @@ final class HippieCompleteAction extends TextEditorAction { this.consumedSuggestions.size() == nextSuggestion && this.suggestions.hasNext()) { //we're just in the place to get a new one from the iterator - String temp= (String)this.suggestions.next(); + String temp= this.suggestions.next(); if (this.alreadyFound.contains(temp)) { continue;//go to next iteration } @@ -158,7 +158,7 @@ final class HippieCompleteAction extends TextEditorAction { if (ret == null) { //we consumed all in the iterator, so, just start cycling. - ret= (String)this.consumedSuggestions.get(0); + ret= this.consumedSuggestions.get(0); nextSuggestion= 1; //we just got the 0, so, we can already skip to 1. } @@ -359,12 +359,12 @@ final class HippieCompleteAction extends TextEditorAction { clearState(); - List documents= HippieCompletionEngine.computeDocuments(getTextEditor()); + List<IDocument> documents= HippieCompletionEngine.computeDocuments(getTextEditor()); if (documents.size() > 0) { - fDocument= (IDocument)documents.remove(0); + fDocument= documents.remove(0); - Iterator suggestions; + Iterator<String> suggestions; try { String prefix= getCurrentPrefix(); if (prefix == null) { diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HippieProposalProcessor.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HippieProposalProcessor.java index afc6350bcfa..0e410a74739 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HippieProposalProcessor.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HippieProposalProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2008 IBM Corporation and others. + * Copyright (c) 2005, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -180,16 +180,16 @@ public final class HippieProposalProcessor implements IContentAssistProcessor { if (prefix == null || prefix.length() == 0) return NO_PROPOSALS; - List suggestions= getSuggestions(viewer, offset, prefix); + List<String> suggestions= getSuggestions(viewer, offset, prefix); - List result= new ArrayList(); - for (Iterator it= suggestions.iterator(); it.hasNext();) { - String string= (String) it.next(); + List<ICompletionProposal> result= new ArrayList<>(); + for (Iterator<String> it= suggestions.iterator(); it.hasNext();) { + String string= it.next(); if (string.length() > 0) result.add(createProposal(string, prefix, offset)); } - return (ICompletionProposal[]) result.toArray(new ICompletionProposal[result.size()]); + return result.toArray(new ICompletionProposal[result.size()]); } catch (BadLocationException x) { // ignore and return no proposals @@ -244,9 +244,9 @@ public final class HippieProposalProcessor implements IContentAssistProcessor { * @return all possible completions that were found in the current document * @throws BadLocationException if accessing the document fails */ - private ArrayList createSuggestionsFromOpenDocument(ITextViewer viewer, int offset, String prefix) throws BadLocationException { + private ArrayList<String> createSuggestionsFromOpenDocument(ITextViewer viewer, int offset, String prefix) throws BadLocationException { IDocument document= viewer.getDocument(); - ArrayList completions= new ArrayList(); + ArrayList<String> completions= new ArrayList<>(); completions.addAll(fEngine.getCompletionsBackwards(document, prefix, offset)); completions.addAll(fEngine.getCompletionsForward(document, prefix, offset - prefix.length(), true)); @@ -263,9 +263,9 @@ public final class HippieProposalProcessor implements IContentAssistProcessor { * @return the list of all possible suggestions in the currently open editors * @throws BadLocationException if accessing the current document fails */ - private List getSuggestions(ITextViewer viewer, int offset, String prefix) throws BadLocationException { + private List<String> getSuggestions(ITextViewer viewer, int offset, String prefix) throws BadLocationException { - ArrayList suggestions= createSuggestionsFromOpenDocument(viewer, offset, prefix); + ArrayList<String> suggestions= createSuggestionsFromOpenDocument(viewer, offset, prefix); IDocument currentDocument= viewer.getDocument(); IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); @@ -284,7 +284,7 @@ public final class HippieProposalProcessor implements IContentAssistProcessor { // add the empty suggestion suggestions.add(""); //$NON-NLS-1$ - List uniqueSuggestions= fEngine.makeUnique(suggestions); + List<String> uniqueSuggestions= fEngine.makeUnique(suggestions); return uniqueSuggestions; } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorDescriptor.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorDescriptor.java index 8d1aedce284..37f2c025c2c 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorDescriptor.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorDescriptor.java @@ -221,7 +221,7 @@ public final class HyperlinkDetectorDescriptor { private static HyperlinkDetectorDescriptor[] createDescriptors(IConfigurationElement[] elements) { HyperlinkDetectorTargetDescriptor[] targets= HyperlinkDetectorTargetDescriptor.getContributedHyperlinkDetectorTargets(); - List result= new ArrayList(elements.length); + List<HyperlinkDetectorDescriptor> result= new ArrayList<>(elements.length); for (int i= 0; i < elements.length; i++) { IConfigurationElement element= elements[i]; if (HYPERLINK_DETECTOR_ELEMENT.equals(element.getName())) { @@ -237,7 +237,7 @@ public final class HyperlinkDetectorDescriptor { TextEditorPlugin.getDefault().getLog().log(new Status(IStatus.ERROR, TextEditorPlugin.PLUGIN_ID, IStatus.OK, message, null)); } } - return (HyperlinkDetectorDescriptor[])result.toArray(new HyperlinkDetectorDescriptor[result.size()]); + return result.toArray(new HyperlinkDetectorDescriptor[result.size()]); } } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorRegistry.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorRegistry.java index 0d67929896c..f38b02b48cb 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorRegistry.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorRegistry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -158,7 +158,7 @@ public final class HyperlinkDetectorRegistry { Assert.isLegal(targetId != null); initHyperlinkDetectorDescriptors(); - List result= new ArrayList(); + List<HyperlinkDetectorDelegate> result= new ArrayList<>(); for (int i= 0; i < fHyperlinkDetectorDescriptors.length; i++) { if (targetId.equals(fHyperlinkDetectorDescriptors[i].getTargetId())) { HyperlinkDetectorDelegate detector= new HyperlinkDetectorDelegate(fHyperlinkDetectorDescriptors[i]); @@ -166,7 +166,7 @@ public final class HyperlinkDetectorRegistry { detector.setContext(context); } } - return (IHyperlinkDetector[])result.toArray(new IHyperlinkDetector[result.size()]); + return result.toArray(new IHyperlinkDetector[result.size()]); } } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorTargetDescriptor.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorTargetDescriptor.java index c0027e40210..b41e49a93db 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorTargetDescriptor.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/HyperlinkDetectorTargetDescriptor.java @@ -123,7 +123,7 @@ public final class HyperlinkDetectorTargetDescriptor { } private static HyperlinkDetectorTargetDescriptor[] createDescriptors(IConfigurationElement[] elements) { - List result= new ArrayList(elements.length); + List<HyperlinkDetectorTargetDescriptor> result= new ArrayList<>(elements.length); for (int i= 0; i < elements.length; i++) { IConfigurationElement element= elements[i]; if (TARGET_ELEMENT.equals(element.getName())) { @@ -140,7 +140,7 @@ public final class HyperlinkDetectorTargetDescriptor { } } - return (HyperlinkDetectorTargetDescriptor[])result.toArray(new HyperlinkDetectorTargetDescriptor[result.size()]); + return result.toArray(new HyperlinkDetectorTargetDescriptor[result.size()]); } private boolean isValid() { diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/IncrementalFindTarget.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/IncrementalFindTarget.java index 818e5ae51ff..3b0b219927b 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/IncrementalFindTarget.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/IncrementalFindTarget.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -114,7 +114,7 @@ class IncrementalFindTarget implements IFindReplaceTarget, IFindReplaceTargetExt */ private boolean fSearching; /** The current find stack */ - private Stack fSessionStack; + private Stack<SearchResult> fSessionStack; /** * The previous search string * @since 2.1 @@ -182,7 +182,7 @@ class IncrementalFindTarget implements IFindReplaceTarget, IFindReplaceTargetExt SearchResult searchResult= null; if (!fSessionStack.empty()) - searchResult= (SearchResult) fSessionStack.pop(); + searchResult= fSessionStack.pop(); if (searchResult == null) { text.getDisplay().beep(); @@ -272,7 +272,7 @@ class IncrementalFindTarget implements IFindReplaceTarget, IFindReplaceTargetExt } fFindString.setLength(0); - fSessionStack= new Stack(); + fSessionStack= new Stack<>(); fCasePosition= -1; fWrapPosition= -1; fFound= true; diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/KeyBindingSupportForAssistant.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/KeyBindingSupportForAssistant.java index 0ebdb6cf283..5ac90b26052 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/KeyBindingSupportForAssistant.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/KeyBindingSupportForAssistant.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2009 IBM Corporation and others. + * Copyright (c) 2007, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -81,7 +81,7 @@ public final class KeyBindingSupportForAssistant implements ICompletionListener } - private List fReplacedCommands; + private List<ReplacedCommand> fReplacedCommands; private ContentAssistantFacade fContentAssistantFacade; private IQuickAssistAssistant fQuickAssistAssistant; @@ -133,7 +133,7 @@ public final class KeyBindingSupportForAssistant implements ICompletionListener public void assistSessionStarted(ContentAssistEvent event) { ICommandService commandService= PlatformUI.getWorkbench().getService(ICommandService.class); IHandler handler= getHandler(ContentAssistant.SELECT_NEXT_PROPOSAL_COMMAND_ID); - fReplacedCommands= new ArrayList(10); + fReplacedCommands= new ArrayList<>(10); fReplacedCommands.add(new ReplacedCommand(ITextEditorActionDefinitionIds.LINE_DOWN, handler, commandService)); handler= getHandler(ContentAssistant.SELECT_PREVIOUS_PROPOSAL_COMMAND_ID); fReplacedCommands.add(new ReplacedCommand(ITextEditorActionDefinitionIds.LINE_UP, handler, commandService)); @@ -170,9 +170,9 @@ public final class KeyBindingSupportForAssistant implements ICompletionListener if (fReplacedCommands == null) return; - Iterator iter= fReplacedCommands.iterator(); + Iterator<ReplacedCommand> iter= fReplacedCommands.iterator(); while (iter.hasNext()) - ((ReplacedCommand)iter.next()).activate(); + iter.next().activate(); fReplacedCommands= null; } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/SourceViewerDecorationSupport.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/SourceViewerDecorationSupport.java index b1b93af7f7a..a8ceb1c6c95 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/SourceViewerDecorationSupport.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/SourceViewerDecorationSupport.java @@ -220,7 +220,7 @@ public class SourceViewerDecorationSupport { private ICharacterPairMatcher fCharacterPairMatcher; /** Map with annotation type preference per annotation type */ - private Map fAnnotationTypeKeyMap= new LinkedHashMap(); + private Map<Object, AnnotationPreference> fAnnotationTypeKeyMap= new LinkedHashMap<>(); /** Preference key for the cursor line highlighting */ private String fCursorLinePainterEnableKey; /** Preference key for the cursor line background color */ @@ -311,7 +311,7 @@ public class SourceViewerDecorationSupport { else hideMargin(); - Iterator e= fAnnotationTypeKeyMap.keySet().iterator(); + Iterator<Object> e= fAnnotationTypeKeyMap.keySet().iterator(); while (e.hasNext()) { Object type= e.next(); if (areAnnotationsHighlighted(type) || areAnnotationsShown(type)) @@ -336,7 +336,7 @@ public class SourceViewerDecorationSupport { return null; if (areAnnotationsShown(annotationType) && fPreferenceStore != null) { - AnnotationPreference info= (AnnotationPreference) fAnnotationTypeKeyMap.get(annotationType); + AnnotationPreference info= fAnnotationTypeKeyMap.get(annotationType); if (info != null) { String key= info.getTextStylePreferenceKey(); if (key != null) @@ -353,7 +353,7 @@ public class SourceViewerDecorationSupport { */ public void updateOverviewDecorations() { if (fOverviewRuler != null) { - Iterator e= fAnnotationTypeKeyMap.keySet().iterator(); + Iterator<Object> e= fAnnotationTypeKeyMap.keySet().iterator(); while (e.hasNext()) { Object type= e.next(); if (isAnnotationOverviewShown(type)) @@ -510,9 +510,9 @@ public class SourceViewerDecorationSupport { * @return the annotation preference */ private AnnotationPreference getAnnotationPreferenceInfo(String preferenceKey) { - Iterator e= fAnnotationTypeKeyMap.values().iterator(); + Iterator<AnnotationPreference> e= fAnnotationTypeKeyMap.values().iterator(); while (e.hasNext()) { - AnnotationPreference info= (AnnotationPreference) e.next(); + AnnotationPreference info= e.next(); if (info != null && info.isPreferenceKey(preferenceKey)) return info; } @@ -664,7 +664,7 @@ public class SourceViewerDecorationSupport { * @return the color of the annotation type */ private Color getAnnotationTypeColor(Object annotationType) { - AnnotationPreference info= (AnnotationPreference) fAnnotationTypeKeyMap.get(annotationType); + AnnotationPreference info= fAnnotationTypeKeyMap.get(annotationType); if (info != null) return getColor( info.getColorPreferenceKey()); return null; @@ -679,7 +679,7 @@ public class SourceViewerDecorationSupport { * @return the layer */ private int getAnnotationTypeLayer(Object annotationType) { - AnnotationPreference info= (AnnotationPreference) fAnnotationTypeKeyMap.get(annotationType); + AnnotationPreference info= fAnnotationTypeKeyMap.get(annotationType); if (info != null) return info.getPresentationLayer(); return 0; @@ -938,7 +938,7 @@ public class SourceViewerDecorationSupport { */ private boolean areAnnotationsShown(Object annotationType) { if (fPreferenceStore != null) { - AnnotationPreference info= (AnnotationPreference) fAnnotationTypeKeyMap.get(annotationType); + AnnotationPreference info= fAnnotationTypeKeyMap.get(annotationType); if (info != null) { String key= info.getTextPreferenceKey(); return key != null && fPreferenceStore.getBoolean(key); @@ -956,7 +956,7 @@ public class SourceViewerDecorationSupport { */ private boolean areAnnotationsHighlighted(Object annotationType) { if (fPreferenceStore != null) { - AnnotationPreference info= (AnnotationPreference)fAnnotationTypeKeyMap.get(annotationType); + AnnotationPreference info= fAnnotationTypeKeyMap.get(annotationType); if (info != null) return info.getHighlightPreferenceKey() != null && fPreferenceStore.getBoolean(info.getHighlightPreferenceKey()); } @@ -971,7 +971,7 @@ public class SourceViewerDecorationSupport { */ private boolean isAnnotationOverviewShown(Object annotationType) { if (fPreferenceStore != null && fOverviewRuler != null) { - AnnotationPreference info= (AnnotationPreference) fAnnotationTypeKeyMap.get(annotationType); + AnnotationPreference info= fAnnotationTypeKeyMap.get(annotationType); if (info != null) return fPreferenceStore.getBoolean(info.getOverviewRulerPreferenceKey()); } @@ -1012,7 +1012,7 @@ public class SourceViewerDecorationSupport { */ public void hideAnnotationOverview() { if (fOverviewRuler != null) { - Iterator e= fAnnotationTypeKeyMap.keySet().iterator(); + Iterator<Object> e= fAnnotationTypeKeyMap.keySet().iterator(); while (e.hasNext()) fOverviewRuler.removeAnnotationType(e.next()); fOverviewRuler.update(); diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/quickdiff/QuickDiff.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/quickdiff/QuickDiff.java index 57146ee777c..cda9cfac1df 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/quickdiff/QuickDiff.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/quickdiff/QuickDiff.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -66,12 +66,12 @@ public class QuickDiff { * * @return the non-modifiable list of extensions to the <code>quickDiffReferenceProvider</code> extension point. */ - public List getReferenceProviderDescriptors() { + public List<ReferenceProviderDescriptor> getReferenceProviderDescriptors() { QuickDiffExtensionsRegistry registry= TextEditorPlugin.getDefault().getQuickDiffExtensionRegistry(); if (registry != null) return registry.getReferenceProviderDescriptors(); - return Collections.EMPTY_LIST; + return Collections.emptyList(); } /** @@ -91,10 +91,10 @@ public class QuickDiff { Assert.isNotNull(editor); Assert.isNotNull(id); - List descs= getReferenceProviderDescriptors(); + List<ReferenceProviderDescriptor> descs= getReferenceProviderDescriptors(); // try to fetch preferred provider; load if needed - for (Iterator iter= descs.iterator(); iter.hasNext();) { - ReferenceProviderDescriptor desc= (ReferenceProviderDescriptor) iter.next(); + for (Iterator<ReferenceProviderDescriptor> iter= descs.iterator(); iter.hasNext();) { + ReferenceProviderDescriptor desc= iter.next(); if (desc.getId().equals(id)) { IQuickDiffReferenceProvider provider= desc.createProvider(); if (provider != null) { @@ -107,8 +107,8 @@ public class QuickDiff { } } - for (ListIterator iter= descs.listIterator(descs.size()); iter.hasPrevious();) { - ReferenceProviderDescriptor desc= (ReferenceProviderDescriptor) iter.previous(); + for (ListIterator<ReferenceProviderDescriptor> iter= descs.listIterator(descs.size()); iter.hasPrevious();) { + ReferenceProviderDescriptor desc= iter.previous(); IQuickDiffReferenceProvider provider= desc.createProvider(); if (provider != null) { provider.setActiveEditor(editor); diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/quickdiff/QuickDiffToggleAction.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/quickdiff/QuickDiffToggleAction.java index 21fc95c6201..3678d4d1350 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/quickdiff/QuickDiffToggleAction.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/quickdiff/QuickDiffToggleAction.java @@ -96,9 +96,9 @@ public class QuickDiffToggleAction implements IEditorActionDelegate, IUpdate { // create quickdiff menu menu= new MenuManager(QuickDiffMessages.quickdiff_menu_label, MENU_ID); - List descriptors= new QuickDiff().getReferenceProviderDescriptors(); - for (Iterator it= descriptors.iterator(); it.hasNext();) { - ReferenceProviderDescriptor desc= (ReferenceProviderDescriptor) it.next(); + List<ReferenceProviderDescriptor> descriptors= new QuickDiff().getReferenceProviderDescriptors(); + for (Iterator<ReferenceProviderDescriptor> it= descriptors.iterator(); it.hasNext();) { + ReferenceProviderDescriptor desc= it.next(); ReferenceSelectionAction action= new ReferenceSelectionAction(desc, fEditor); if (action.isEnabled()) menu.add(action); diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnPreferenceAdapter.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnPreferenceAdapter.java index 08a64d8cef3..acc93796617 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnPreferenceAdapter.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnPreferenceAdapter.java @@ -64,7 +64,7 @@ public final class RulerColumnPreferenceAdapter { Assert.isLegal(descriptor != null); String id= descriptor.getId(); String preference= fStore.getString(fKey); - Set marked= StringSetSerializer.deserialize(preference); + Set<String> marked= StringSetSerializer.deserialize(preference); boolean shouldMark= enabled ^ descriptor.getDefaultEnablement(); boolean isMarked= marked.contains(id); if (isMarked != shouldMark) { diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnRegistry.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnRegistry.java index 1ee546c4c3d..9baa4e649c5 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnRegistry.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/rulers/RulerColumnRegistry.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -73,14 +73,13 @@ public final class RulerColumnRegistry { } /** - * All descriptors (element type: - * {@link RulerColumnDescriptor}). + * All descriptors. */ - private List fDescriptors= null; + private List<RulerColumnDescriptor> fDescriptors= null; /** - * All descriptors by id (element type: {@link RulerColumnDescriptor}). + * All descriptors by id. */ - private Map fDescriptorMap= null; + private Map<String, RulerColumnDescriptor> fDescriptorMap= null; /** * <code>true</code> if this registry has been loaded. @@ -103,9 +102,8 @@ public final class RulerColumnRegistry { * </p> * * @return the sorted list of extensions to the <code>rulerColumns</code> extension point - * (element type: {@link RulerColumnDescriptor}) */ - public List getColumnDescriptors() { + public List<RulerColumnDescriptor> getColumnDescriptors() { ensureExtensionPointRead(); return fDescriptors; } @@ -121,7 +119,7 @@ public final class RulerColumnRegistry { public RulerColumnDescriptor getColumnDescriptor(String id) { Assert.isLegal(id != null); ensureExtensionPointRead(); - return (RulerColumnDescriptor) fDescriptorMap.get(id); + return fDescriptorMap.get(id); } /** @@ -147,13 +145,13 @@ public final class RulerColumnRegistry { */ public void reload() { IExtensionRegistry registry= Platform.getExtensionRegistry(); - List elements= new ArrayList(Arrays.asList(registry.getConfigurationElementsFor(TextEditorPlugin.PLUGIN_ID, EXTENSION_POINT))); + List<IConfigurationElement> elements= new ArrayList<>(Arrays.asList(registry.getConfigurationElementsFor(TextEditorPlugin.PLUGIN_ID, EXTENSION_POINT))); - List descriptors= new ArrayList(); - Map descriptorMap= new HashMap(); + List<RulerColumnDescriptor> descriptors= new ArrayList<>(); + Map<String, RulerColumnDescriptor> descriptorMap= new HashMap<>(); - for (Iterator iter= elements.iterator(); iter.hasNext();) { - IConfigurationElement element= (IConfigurationElement) iter.next(); + for (Iterator<IConfigurationElement> iter= elements.iterator(); iter.hasNext();) { + IConfigurationElement element= iter.next(); try { RulerColumnDescriptor desc= new RulerColumnDescriptor(element, this); String id= desc.getId(); @@ -189,7 +187,7 @@ public final class RulerColumnRegistry { * * @param descriptors the descriptors to sort */ - private void sort(List descriptors) { + private void sort(List<RulerColumnDescriptor> descriptors) { /* * Topological sort of the DAG defined by the plug-in dependencies * 1. TopoSort descriptors by plug-in dependency @@ -202,25 +200,25 @@ public final class RulerColumnRegistry { return ((RulerColumnDescriptor) object).getConfigurationElement(); } }; - Object[] array= descriptors.toArray(); + RulerColumnDescriptor[] array= descriptors.toArray(new RulerColumnDescriptor[descriptors.size()]); sorter.sort(array); - Map descriptorsById= new HashMap(); + Map<String, RulerColumnDescriptor> descriptorsById= new HashMap<>(); for (int i= 0; i < array.length; i++) { - RulerColumnDescriptor desc= (RulerColumnDescriptor) array[i]; + RulerColumnDescriptor desc= array[i]; descriptorsById.put(desc.getId(), desc); } - DAG dag= new DAG(); + DAG<RulerColumnDescriptor> dag= new DAG<>(); for (int i= 0; i < array.length; i++) { - RulerColumnDescriptor desc= (RulerColumnDescriptor) array[i]; + RulerColumnDescriptor desc= array[i]; dag.addVertex(desc); - Set before= desc.getPlacement().getConstraints(); - for (Iterator it= before.iterator(); it.hasNext();) { - RulerColumnPlacementConstraint constraint= (RulerColumnPlacementConstraint) it.next(); + Set<RulerColumnPlacementConstraint> before= desc.getPlacement().getConstraints(); + for (Iterator<RulerColumnPlacementConstraint> it= before.iterator(); it.hasNext();) { + RulerColumnPlacementConstraint constraint= it.next(); String id= constraint.getId(); - RulerColumnDescriptor target= (RulerColumnDescriptor) descriptorsById.get(id); + RulerColumnDescriptor target= descriptorsById.get(id); if (target == null) { noteUnknownTarget(desc, id); } else { @@ -235,10 +233,10 @@ public final class RulerColumnRegistry { } } - Comparator gravityComp= new Comparator() { + Comparator<RulerColumnDescriptor> gravityComp= new Comparator<RulerColumnDescriptor>() { @Override - public int compare(Object o1, Object o2) { - float diff= ((RulerColumnDescriptor) o1).getPlacement().getGravity() - ((RulerColumnDescriptor) o2).getPlacement().getGravity(); + public int compare(RulerColumnDescriptor o1, RulerColumnDescriptor o2) { + float diff= o1.getPlacement().getGravity() - o2.getPlacement().getGravity(); if (diff == 0) return 0; if (diff < 0) @@ -248,10 +246,10 @@ public final class RulerColumnRegistry { }; /* Topological sort - always select the source with the least gravity */ - Set toProcess= dag.getSources(); + Set<RulerColumnDescriptor> toProcess= dag.getSources(); int index= 0; while (!toProcess.isEmpty()) { - Object next= Collections.min(toProcess, gravityComp); + RulerColumnDescriptor next= Collections.min(toProcess, gravityComp); array[index]= next; index++; dag.removeVertex(next); @@ -259,7 +257,7 @@ public final class RulerColumnRegistry { } Assert.isTrue(index == array.length); - ListIterator it= descriptors.listIterator(); + ListIterator<RulerColumnDescriptor> it= descriptors.listIterator(); for (int i= 0; i < index; i++) { it.next(); it.set(array[i]); diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingCorrectionProcessor.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingCorrectionProcessor.java index 2b4f689f560..164377bd864 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingCorrectionProcessor.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingCorrectionProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2009 IBM Corporation and others. + * Copyright (c) 2006, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -55,23 +55,23 @@ public final class SpellingCorrectionProcessor implements IQuickAssistProcessor if (model == null) return fgNoSuggestionsProposal; - List proposals= computeProposals(context, model); + List<ICompletionProposal> proposals= computeProposals(context, model); if (proposals.isEmpty()) return fgNoSuggestionsProposal; - return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]); + return proposals.toArray(new ICompletionProposal[proposals.size()]); } private boolean isAtPosition(int offset, Position pos) { return (pos != null) && (offset >= pos.getOffset() && offset <= (pos.getOffset() + pos.getLength())); } - private List computeProposals(IQuickAssistInvocationContext context, IAnnotationModel model) { + private List<ICompletionProposal> computeProposals(IQuickAssistInvocationContext context, IAnnotationModel model) { int offset= context.getOffset(); - ArrayList annotationList= new ArrayList(); - Iterator iter= model.getAnnotationIterator(); + ArrayList<SpellingProblem> annotationList= new ArrayList<>(); + Iterator<Annotation> iter= model.getAnnotationIterator(); while (iter.hasNext()) { - Annotation annotation= (Annotation)iter.next(); + Annotation annotation= iter.next(); if (canFix(annotation)) { Position pos= model.getPosition(annotation); if (isAtPosition(offset, pos)) { @@ -79,17 +79,17 @@ public final class SpellingCorrectionProcessor implements IQuickAssistProcessor } } } - SpellingProblem[] spellingProblems= (SpellingProblem[]) annotationList.toArray(new SpellingProblem[annotationList.size()]); + SpellingProblem[] spellingProblems= annotationList.toArray(new SpellingProblem[annotationList.size()]); return computeProposals(context, spellingProblems); } - private void collectSpellingProblems(Annotation annotation, List problems) { + private void collectSpellingProblems(Annotation annotation, List<SpellingProblem> problems) { if (annotation instanceof SpellingAnnotation) problems.add(((SpellingAnnotation)annotation).getSpellingProblem()); } - private List computeProposals(IQuickAssistInvocationContext context, SpellingProblem[] spellingProblems) { - List proposals= new ArrayList(); + private List<ICompletionProposal> computeProposals(IQuickAssistInvocationContext context, SpellingProblem[] spellingProblems) { + List<ICompletionProposal> proposals= new ArrayList<>(); for (int i= 0; i < spellingProblems.length; i++) proposals.addAll(Arrays.asList(spellingProblems[i].getProposals(context))); diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingProblem.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingProblem.java index 5f7df930308..1e432e8d04f 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingProblem.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingProblem.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -83,10 +83,10 @@ public abstract class SpellingProblem { return; boolean supportsBatchReplace= (model instanceof IAnnotationModelExtension); - List toBeRemovedAnnotations= new ArrayList(); - Iterator iter= model.getAnnotationIterator(); + List<Annotation> toBeRemovedAnnotations= new ArrayList<>(); + Iterator<Annotation> iter= model.getAnnotationIterator(); while (iter.hasNext()) { - Annotation annotation= (Annotation) iter.next(); + Annotation annotation= iter.next(); if (SpellingAnnotation.TYPE.equals(annotation.getType())) { boolean doRemove= word == null; if (word == null) @@ -111,7 +111,7 @@ public abstract class SpellingProblem { } if (supportsBatchReplace && !toBeRemovedAnnotations.isEmpty()) { - Annotation[] annotationArray= (Annotation[])toBeRemovedAnnotations.toArray(new Annotation[toBeRemovedAnnotations.size()]); + Annotation[] annotationArray= toBeRemovedAnnotations.toArray(new Annotation[toBeRemovedAnnotations.size()]); ((IAnnotationModelExtension)model).replaceAnnotations(annotationArray, null); } } @@ -136,10 +136,10 @@ public abstract class SpellingProblem { return; boolean supportsBatchReplace= (model instanceof IAnnotationModelExtension); - List toBeRemovedAnnotations= new ArrayList(); - Iterator iter= model.getAnnotationIterator(); + List<Annotation> toBeRemovedAnnotations= new ArrayList<>(); + Iterator<Annotation> iter= model.getAnnotationIterator(); while (iter.hasNext()) { - Annotation annotation= (Annotation) iter.next(); + Annotation annotation= iter.next(); if (SpellingAnnotation.TYPE.equals(annotation.getType())) { boolean doRemove= word == null; if (word == null) @@ -164,7 +164,7 @@ public abstract class SpellingProblem { } if (supportsBatchReplace && !toBeRemovedAnnotations.isEmpty()) { - Annotation[] annotationArray= (Annotation[])toBeRemovedAnnotations.toArray(new Annotation[toBeRemovedAnnotations.size()]); + Annotation[] annotationArray= toBeRemovedAnnotations.toArray(new Annotation[toBeRemovedAnnotations.size()]); ((IAnnotationModelExtension)model).replaceAnnotations(annotationArray, null); } } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingReconcileStrategy.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingReconcileStrategy.java index d777e9ae0d6..92ec1cfe3d9 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingReconcileStrategy.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/spelling/SpellingReconcileStrategy.java @@ -54,7 +54,7 @@ public class SpellingReconcileStrategy implements IReconcilingStrategy, IReconci private IAnnotationModel fAnnotationModel; /** Annotations to add. */ - private Map fAddAnnotations; + private Map<Annotation, Position> fAddAnnotations; /** Lock object for modifying the annotations. */ private Object fLockObject; @@ -80,22 +80,22 @@ public class SpellingReconcileStrategy implements IReconcilingStrategy, IReconci @Override public void beginCollecting() { - fAddAnnotations= new HashMap(); + fAddAnnotations= new HashMap<>(); } @Override public void endCollecting() { - List toRemove= new ArrayList(); + List<Annotation> toRemove= new ArrayList<>(); synchronized (fLockObject) { - Iterator iter= fAnnotationModel.getAnnotationIterator(); + Iterator<Annotation> iter= fAnnotationModel.getAnnotationIterator(); while (iter.hasNext()) { - Annotation annotation= (Annotation)iter.next(); + Annotation annotation= iter.next(); if (SpellingAnnotation.TYPE.equals(annotation.getType())) toRemove.add(annotation); } - Annotation[] annotationsToRemove= (Annotation[])toRemove.toArray(new Annotation[toRemove.size()]); + Annotation[] annotationsToRemove= toRemove.toArray(new Annotation[toRemove.size()]); if (fAnnotationModel instanceof IAnnotationModelExtension) ((IAnnotationModelExtension)fAnnotationModel).replaceAnnotations(annotationsToRemove, fAddAnnotations); @@ -103,8 +103,8 @@ public class SpellingReconcileStrategy implements IReconcilingStrategy, IReconci for (int i= 0; i < annotationsToRemove.length; i++) fAnnotationModel.removeAnnotation(annotationsToRemove[i]); for (iter= fAddAnnotations.keySet().iterator(); iter.hasNext();) { - Annotation annotation= (Annotation)iter.next(); - fAnnotationModel.addAnnotation(annotation, (Position)fAddAnnotations.get(annotation)); + Annotation annotation= iter.next(); + fAnnotationModel.addAnnotation(annotation, fAddAnnotations.get(annotation)); } } } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/AbstractTemplatesPage.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/AbstractTemplatesPage.java index 7600c5ded4c..d873cc51c50 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/AbstractTemplatesPage.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/AbstractTemplatesPage.java @@ -344,13 +344,13 @@ public abstract class AbstractTemplatesPage extends Page implements ITemplatesPa } private TemplatePersistenceData[] getTemplates(String contextId) { - List templateList= new ArrayList(); + List<TemplatePersistenceData> templateList= new ArrayList<>(); TemplatePersistenceData[] datas= getTemplateStore().getTemplateData(false); for (int i= 0; i < datas.length; i++) { if (datas[i].isEnabled() && datas[i].getTemplate().getContextTypeId().equals(contextId)) templateList.add(datas[i]); } - return (TemplatePersistenceData[]) templateList + return templateList .toArray(new TemplatePersistenceData[templateList.size()]); } @@ -386,10 +386,10 @@ public abstract class AbstractTemplatesPage extends Page implements ITemplatesPa @Override public Object[] getElements(Object inputElement) { - List contextTypes= new ArrayList(); + List<TemplateContextType> contextTypes= new ArrayList<>(); - for (Iterator iterator= getContextTypeRegistry().contextTypes(); iterator.hasNext();) { - TemplateContextType contextType= (TemplateContextType) iterator.next(); + for (Iterator<TemplateContextType> iterator= getContextTypeRegistry().contextTypes(); iterator.hasNext();) { + TemplateContextType contextType= iterator.next(); if (!fLinkWithEditorAction.isChecked() || isActiveContext(contextType)) contextTypes.add(contextType); } @@ -435,7 +435,7 @@ public abstract class AbstractTemplatesPage extends Page implements ITemplatesPa private Action fCopyAction; /* Current active context types for the editor */ - private List fActiveTypes; + private List<String> fActiveTypes; /* Preference stores */ private IPreferenceStore fPreferenceStore; @@ -1198,7 +1198,7 @@ public abstract class AbstractTemplatesPage extends Page implements ITemplatesPa private void setSelectedTemplates() { IStructuredSelection selection= (IStructuredSelection) fTreeViewer.getSelection(); - Iterator it= selection.iterator(); + Iterator<?> it= selection.iterator(); TemplatePersistenceData[] data= new TemplatePersistenceData[selection.size()]; int i= 0; while (it.hasNext()) { @@ -1247,7 +1247,7 @@ public abstract class AbstractTemplatesPage extends Page implements ITemplatesPa Object item; if (selection.size() == 0) - return ((TemplateContextType) getContextTypeRegistry().contextTypes().next()).getId(); + return getContextTypeRegistry().contextTypes().next().getId(); if (selection.size() == 1) { item= selection.getFirstElement(); @@ -1255,14 +1255,14 @@ public abstract class AbstractTemplatesPage extends Page implements ITemplatesPa return ((TemplatePersistenceData) item).getTemplate().getContextTypeId(); return ((TemplateContextType) item).getId(); } - Iterator it= selection.iterator(); + Iterator<?> it= selection.iterator(); String contextId= null; while (it.hasNext()) { item= it.next(); if (contextId == null) contextId= getContextId(item); else if (!contextId.equals(getContextId(item))) - return ((TemplateContextType) getContextTypeRegistry().contextTypes().next()) + return getContextTypeRegistry().contextTypes().next() .getId(); } return contextId; diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/ColumnLayout.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/ColumnLayout.java index e8e3d64194c..f4075c9b01e 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/ColumnLayout.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/ColumnLayout.java @@ -63,7 +63,7 @@ final class ColumnLayout extends Layout { COLUMN_TRIM= 3; } - private List columns= new ArrayList(); + private List<ColumnLayoutData> columns= new ArrayList<>(); /** * Adds a new column of data to this table layout. @@ -80,7 +80,7 @@ final class ColumnLayout extends Layout { int width= 0; int size= columns.size(); for (int i= 0; i < size; ++i) { - ColumnLayoutData layoutData= (ColumnLayoutData) columns.get(i); + ColumnLayoutData layoutData= columns.get(i); if (layoutData instanceof ColumnPixelData) { ColumnPixelData col= (ColumnPixelData) layoutData; width += col.width; @@ -113,7 +113,7 @@ final class ColumnLayout extends Layout { // First calc space occupied by fixed columns for (int i= 0; i < size; i++) { - ColumnLayoutData col= (ColumnLayoutData) columns.get(i); + ColumnLayoutData col= columns.get(i); if (col instanceof ColumnPixelData) { ColumnPixelData cpd= (ColumnPixelData) col; int pixels= cpd.width; diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/TemplatePreferencePage.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/TemplatePreferencePage.java index 6d3da8c01fb..56c34f9e740 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/TemplatePreferencePage.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/TemplatePreferencePage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -128,6 +128,7 @@ import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchCommandConstants; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.PlatformUI; +import org.eclipse.ui.handlers.IHandlerActivation; import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.internal.texteditor.NLSUtility; import org.eclipse.ui.internal.texteditor.SWTUtil; @@ -222,8 +223,8 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I private StatusInfo fValidationStatus; private boolean fSuppressError= true; // #4354 - private Map fGlobalActions= new HashMap(10); - private List fSelectionActions = new ArrayList(3); + private Map<String, TextViewerAction> fGlobalActions= new HashMap<>(10); + private List<String> fSelectionActions = new ArrayList<>(3); private String[][] fContextTypes; private ContextTypeRegistry fContextTypeRegistry; @@ -253,19 +254,19 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I fOriginalTemplate= template; fIsNameModifiable= isNameModifiable; - List contexts= new ArrayList(); - for (Iterator it= registry.contextTypes(); it.hasNext();) { - TemplateContextType type= (TemplateContextType) it.next(); + List<String[]> contexts= new ArrayList<>(); + for (Iterator<TemplateContextType> it= registry.contextTypes(); it.hasNext();) { + TemplateContextType type= it.next(); contexts.add(new String[] { type.getId(), type.getName() }); } - Collections.sort(contexts, new Comparator() { + Collections.sort(contexts, new Comparator<String[]>() { Collator fCollator= Collator.getInstance(); @Override - public int compare(Object o1, Object o2) { - return fCollator.compare(((String[])o1)[1], ((String[])o2)[1]); + public int compare(String[] o1, String[] o2) { + return fCollator.compare(o1[1], o2[1]); } }); - fContextTypes= (String[][]) contexts.toArray(new String[contexts.size()][]); + fContextTypes= contexts.toArray(new String[contexts.size()][]); fValidationStatus= new StatusInfo(); @@ -550,7 +551,7 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I } private void initializeActions() { - final ArrayList handlerActivations= new ArrayList(3); + final ArrayList<IHandlerActivation> handlerActivations= new ArrayList<>(3); final IHandlerService handlerService= PlatformUI.getWorkbench().getAdapter(IHandlerService.class); final Expression expression= new ActiveShellExpression(fPatternEditor.getControl().getShell()); @@ -570,11 +571,11 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I @Override public void focusGained(FocusEvent e) { - IAction action= (IAction)fGlobalActions.get(ITextEditorActionConstants.REDO); + IAction action= fGlobalActions.get(ITextEditorActionConstants.REDO); handlerActivations.add(handlerService.activateHandler(IWorkbenchCommandConstants.EDIT_REDO, new ActionHandler(action), expression)); - action= (IAction)fGlobalActions.get(ITextEditorActionConstants.UNDO); + action= fGlobalActions.get(ITextEditorActionConstants.UNDO); handlerActivations.add(handlerService.activateHandler(IWorkbenchCommandConstants.EDIT_UNDO, new ActionHandler(action), expression)); - action= (IAction)fGlobalActions.get(ITextEditorActionConstants.CONTENT_ASSIST); + action= fGlobalActions.get(ITextEditorActionConstants.CONTENT_ASSIST); handlerActivations.add(handlerService.activateHandler(ITextEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS, new ActionHandler(action), expression)); } }); @@ -628,27 +629,27 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I private void fillContextMenu(IMenuManager menu) { menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction)fGlobalActions.get(ITextEditorActionConstants.REDO)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, fGlobalActions.get(ITextEditorActionConstants.UNDO)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, fGlobalActions.get(ITextEditorActionConstants.REDO)); menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE)); - menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, fGlobalActions.get(ITextEditorActionConstants.CUT)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, fGlobalActions.get(ITextEditorActionConstants.COPY)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, fGlobalActions.get(ITextEditorActionConstants.PASTE)); + menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL)); menu.add(new Separator("templates")); //$NON-NLS-1$ - menu.appendToGroup("templates", (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ //$NON-NLS-2$ + menu.appendToGroup("templates", fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ //$NON-NLS-2$ } private void updateSelectionDependentActions() { - Iterator iterator= fSelectionActions.iterator(); + Iterator<String> iterator= fSelectionActions.iterator(); while (iterator.hasNext()) - updateAction((String)iterator.next()); + updateAction(iterator.next()); } private void updateAction(String actionId) { - IAction action= (IAction) fGlobalActions.get(actionId); + IAction action= fGlobalActions.get(actionId); if (action instanceof IUpdate) ((IUpdate) action).update(); } @@ -1069,9 +1070,9 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I */ private int computeMinimumContextColumnWidth(GC gc) { int width= gc.stringExtent(TemplatesMessages.TemplatePreferencePage_column_context).x; - Iterator iter= getContextTypeRegistry().contextTypes(); + Iterator<TemplateContextType> iter= getContextTypeRegistry().contextTypes(); while (iter.hasNext()) { - TemplateContextType contextType= (TemplateContextType)iter.next(); + TemplateContextType contextType= iter.next(); width= Math.max(width, gc.stringExtent(contextType.getName()).x); } return width; @@ -1106,13 +1107,13 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I } private TemplatePersistenceData[] getEnabledTemplates() { - List enabled= new ArrayList(); + List<TemplatePersistenceData> enabled= new ArrayList<>(); TemplatePersistenceData[] datas= fTemplateStore.getTemplateData(false); for (int i= 0; i < datas.length; i++) { if (datas[i].isEnabled()) enabled.add(datas[i]); } - return (TemplatePersistenceData[]) enabled.toArray(new TemplatePersistenceData[enabled.size()]); + return enabled.toArray(new TemplatePersistenceData[enabled.size()]); } private SourceViewer doCreateViewer(Composite parent) { @@ -1201,7 +1202,7 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I int itemCount= fTableViewer.getTable().getItemCount(); boolean canRestore= fTemplateStore.getTemplateData(true).length != fTemplateStore.getTemplateData(false).length; boolean canRevert= false; - for (Iterator it= selection.iterator(); it.hasNext();) { + for (Iterator<?> it= selection.iterator(); it.hasNext();) { TemplatePersistenceData data= (TemplatePersistenceData) it.next(); if (data.isModified()) { canRevert= true; @@ -1218,9 +1219,9 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I private void add() { - Iterator it= fContextTypeRegistry.contextTypes(); + Iterator<TemplateContextType> it= fContextTypeRegistry.contextTypes(); if (it.hasNext()) { - Template template= new Template("", "", ((TemplateContextType) it.next()).getId(), "", true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + Template template= new Template("", "", it.next().getId(), "", true); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ Template newTemplate= editTemplate(template, false, true); if (newTemplate != null) { @@ -1310,7 +1311,7 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I return; try { - ArrayList selection= new ArrayList(); + ArrayList<TemplatePersistenceData> selection= new ArrayList<>(); TemplateReaderWriter reader= new TemplateReaderWriter(); File file= new File(path); if (file.exists()) { @@ -1418,7 +1419,7 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I private void remove() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); - Iterator elements= selection.iterator(); + Iterator<?> elements= selection.iterator(); while (elements.hasNext()) { TemplatePersistenceData data= (TemplatePersistenceData) elements.next(); fTemplateStore.delete(data); @@ -1433,7 +1434,7 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I TemplatePersistenceData[] newTemplates= fTemplateStore.getTemplateData(false); fTableViewer.refresh(); fTableViewer.setCheckedElements(getEnabledTemplates()); - ArrayList selection= new ArrayList(); + ArrayList<TemplatePersistenceData> selection= new ArrayList<>(); selection.addAll(Arrays.asList(newTemplates)); selection.removeAll(Arrays.asList(oldTemplates)); fTableViewer.setSelection(new StructuredSelection(selection), true); @@ -1443,7 +1444,7 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I private void revert() { IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection(); - Iterator elements= selection.iterator(); + Iterator<?> elements= selection.iterator(); while (elements.hasNext()) { TemplatePersistenceData data= (TemplatePersistenceData) elements.next(); data.revert(); @@ -1585,6 +1586,7 @@ public abstract class TemplatePreferencePage extends PreferencePage implements I String left= ((TemplateLabelProvider)baseLabel).getColumnText(e1, fSortColumn); String right= ((TemplateLabelProvider)baseLabel).getColumnText(e2, fSortColumn); + @SuppressWarnings("unchecked") int sortResult= getComparator().compare(left, right); return sortResult * fSortOrder; } diff --git a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/TemplateVariableProcessor.java b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/TemplateVariableProcessor.java index 45a35d38228..2a4f66cfd64 100644 --- a/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/TemplateVariableProcessor.java +++ b/org.eclipse.ui.workbench.texteditor/src/org/eclipse/ui/texteditor/templates/TemplateVariableProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. + * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -37,12 +37,9 @@ import org.eclipse.jface.text.templates.TemplateVariableResolver; */ final class TemplateVariableProcessor implements IContentAssistProcessor { - private static Comparator fgTemplateVariableProposalComparator= new Comparator() { + private static Comparator<TemplateVariableProposal> fgTemplateVariableProposalComparator= new Comparator<TemplateVariableProposal>() { @Override - public int compare(Object arg0, Object arg1) { - TemplateVariableProposal proposal0= (TemplateVariableProposal) arg0; - TemplateVariableProposal proposal1= (TemplateVariableProposal) arg1; - + public int compare(TemplateVariableProposal proposal0, TemplateVariableProposal proposal1) { return proposal0.getDisplayString().compareTo(proposal1.getDisplayString()); } @@ -89,7 +86,7 @@ final class TemplateVariableProcessor implements IContentAssistProcessor { if (fContextType == null) return null; - List proposals= new ArrayList(); + List<TemplateVariableProposal> proposals= new ArrayList<>(); String text= viewer.getDocument().get(); int start= getStart(text, documentOffset); @@ -103,15 +100,15 @@ final class TemplateVariableProcessor implements IContentAssistProcessor { int offset= start; int length= end - start; - for (Iterator iterator= fContextType.resolvers(); iterator.hasNext(); ) { - TemplateVariableResolver variable= (TemplateVariableResolver) iterator.next(); + for (Iterator<TemplateVariableResolver> iterator= fContextType.resolvers(); iterator.hasNext(); ) { + TemplateVariableResolver variable= iterator.next(); if (prefix == null || variable.getType().startsWith(prefix)) proposals.add(new TemplateVariableProposal(variable, offset, length, viewer)); } Collections.sort(proposals, fgTemplateVariableProposalComparator); - return (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]); + return proposals.toArray(new ICompletionProposal[proposals.size()]); } /* Guesses the start position of the completion */ |