diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2TestBase.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2TestBase.java index 9e3ef8a38bb..32ec86c2db2 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2TestBase.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/ast2/AST2TestBase.java @@ -51,13 +51,13 @@ import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit; import org.eclipse.cdt.core.dom.ast.IASTTypeId; import org.eclipse.cdt.core.dom.ast.IASTTypeIdExpression; import org.eclipse.cdt.core.dom.ast.IASTUnaryExpression; +import org.eclipse.cdt.core.dom.ast.IBasicType.Kind; import org.eclipse.cdt.core.dom.ast.IBinding; import org.eclipse.cdt.core.dom.ast.ICompositeType; import org.eclipse.cdt.core.dom.ast.IField; import org.eclipse.cdt.core.dom.ast.IFunctionType; import org.eclipse.cdt.core.dom.ast.IProblemBinding; import org.eclipse.cdt.core.dom.ast.IType; -import org.eclipse.cdt.core.dom.ast.IBasicType.Kind; import org.eclipse.cdt.core.dom.ast.IVariable; import org.eclipse.cdt.core.dom.ast.c.ICASTTypeIdInitializerExpression; import org.eclipse.cdt.core.dom.ast.cpp.ICPPASTLinkageSpecification; @@ -114,7 +114,7 @@ public class AST2TestBase extends BaseTestCase { private static final ScannerInfo SCANNER_INFO = new ScannerInfo(getStdMap()); private static Map getGnuMap() { - Map map= new HashMap(); + Map map= new HashMap<>(); map.put("__GNUC__", Integer.toString(GPPLanguage.GNU_LATEST_VERSION_MAJOR)); map.put("__GNUC_MINOR__", Integer.toString(GPPLanguage.GNU_LATEST_VERSION_MINOR)); map.put("__SIZEOF_SHORT__", "2"); @@ -125,7 +125,7 @@ public class AST2TestBase extends BaseTestCase { } private static Map getStdMap() { - Map map= new HashMap(); + Map map= new HashMap<>(); map.put("__SIZEOF_SHORT__", "2"); map.put("__SIZEOF_INT__", "4"); map.put("__SIZEOF_LONG__", "8"); @@ -173,7 +173,7 @@ public class AST2TestBase extends BaseTestCase { } else { config = new ANSICPPParserExtensionConfiguration(); } - parser = new GNUCPPSourceParser(scanner, ParserMode.COMPLETE_PARSE, NULL_LOG,config, null); + parser = new GNUCPPSourceParser(scanner, ParserMode.COMPLETE_PARSE, NULL_LOG, config, null); } else { ICParserExtensionConfiguration config = null; @@ -312,7 +312,7 @@ public class AST2TestBase extends BaseTestCase { this.shouldVisitImplicitNames = shouldVisitImplicitNames; } - public List nameList = new ArrayList(); + public List nameList = new ArrayList<>(); @Override public int visit(IASTName name) { @@ -408,7 +408,7 @@ public class AST2TestBase extends BaseTestCase { } public int numProblemBindings; public int numNullBindings; - public List nameList = new ArrayList(); + public List nameList = new ArrayList<>(); @Override public int visit(IASTName name) { @@ -438,7 +438,7 @@ public class AST2TestBase extends BaseTestCase { } public int numProblemBindings; public int numNullBindings; - public List nameList = new ArrayList(); + public List nameList = new ArrayList<>(); @Override public int visit(IASTName name) { diff --git a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/scanner/PreprocessorTestsBase.java b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/scanner/PreprocessorTestsBase.java index 550e1a84020..8b2a7c65ee3 100644 --- a/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/scanner/PreprocessorTestsBase.java +++ b/core/org.eclipse.cdt.core.tests/parser/org/eclipse/cdt/core/parser/tests/scanner/PreprocessorTestsBase.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Markus Schorn - initial API and implementation + * Markus Schorn - initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.parser.tests.scanner; @@ -37,7 +37,6 @@ import org.eclipse.cdt.internal.core.parser.scanner.CPreprocessor; import org.eclipse.cdt.internal.core.parser.scanner.ILocationResolver; public abstract class PreprocessorTestsBase extends BaseTestCase { - private static final IParserLogService NULL_LOG = new NullLogService(); protected CPreprocessor fScanner; protected ILocationResolver fLocationResolver; @@ -78,11 +77,10 @@ public abstract class PreprocessorTestsBase extends BaseTestCase { IncludeFileContentProvider readerFactory= FileCodeReaderFactory.getInstance(); //IScannerExtensionConfiguration scannerConfig; - if(scannerConfig == null) { + if (scannerConfig == null) { if (lang == ParserLanguage.C) { scannerConfig= GCCScannerExtensionConfiguration.getInstance(); - } - else { + } else { scannerConfig= GPPScannerExtensionConfiguration.getInstance(scannerInfo); } } @@ -106,10 +104,10 @@ public abstract class PreprocessorTestsBase extends BaseTestCase { protected void fullyTokenize() throws Exception { try { - for(;;) { + for (;;) { IToken t= fScanner.nextToken(); } - } catch ( EndOfFileException e){ + } catch (EndOfFileException e) { } } @@ -176,8 +174,7 @@ public abstract class PreprocessorTestsBase extends BaseTestCase { try { IToken t= fScanner.nextToken(); fail("superfluous token " + t); - } - catch(EndOfFileException e) { + } catch(EndOfFileException e) { } } @@ -211,5 +208,4 @@ public abstract class PreprocessorTestsBase extends BaseTestCase { assertEquals(detail, problem.getArguments()[0]); } } - } diff --git a/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/CProjectHelper.java b/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/CProjectHelper.java index 9efeb754287..656b14e9e02 100644 --- a/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/CProjectHelper.java +++ b/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/CProjectHelper.java @@ -18,8 +18,6 @@ import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.zip.ZipFile; -import junit.framework.Assert; - import org.eclipse.cdt.core.CCProjectNature; import org.eclipse.cdt.core.CCorePlugin; import org.eclipse.cdt.core.CProjectNature; @@ -61,7 +59,9 @@ import org.eclipse.ui.dialogs.IOverwriteQuery; import org.eclipse.ui.wizards.datatransfer.FileSystemStructureProvider; import org.eclipse.ui.wizards.datatransfer.ImportOperation; import org.eclipse.ui.wizards.datatransfer.ZipFileStructureProvider; +import org.junit.Assert; import org.osgi.framework.Bundle; + /** * Helper methods to set up a ICProject. */ @@ -357,7 +357,7 @@ public class CProjectHelper { * @throws InterruptedException */ public static ITranslationUnit findTranslationUnit(ICProject testProject, String name) throws CModelException, InterruptedException { - for (int j=0; j<20; j++) { + for (int j = 0; j < 20; j++) { ICElement[] sourceRoots = testProject.getChildren(); for (int i = 0; i < sourceRoots.length; i++) { ISourceRoot root = (ISourceRoot) sourceRoots[i]; diff --git a/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/Main.java b/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/Main.java index 588257516eb..cbcc95ddf61 100644 --- a/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/Main.java +++ b/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/Main.java @@ -8,7 +8,6 @@ * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ - package org.eclipse.cdt.core.testplugin; // copied from startup.jar. planned to be removed soon @@ -73,51 +72,51 @@ public class Main { /** * Indicates whether this instance is running in debug mode. */ - protected boolean debug = false; - + protected boolean debug; + /** * The location of the launcher to run. */ - protected String bootLocation = null; - + protected String bootLocation; + /** * The identifier of the application to run. */ protected String application; - + /** * The path for finding find plugins. */ protected URL pluginPathLocation; - + /** * The boot path location. */ protected String location; - + /** * Indicates whether items for UNinstallation should be looked for. */ - protected boolean uninstall = false; - + protected boolean uninstall; + /** * The item to be uninstalled. */ protected String uninstallCookie; - + /** * The class path entries. */ - protected String devClassPath = null; - + protected String devClassPath; + /** * Indicates whether this instance is running in development mode. */ - protected boolean inDevelopmentMode = false; + protected boolean inDevelopmentMode; // static token describing how to take down the splash screen - private static String endSplash = null; - + private static String endSplash; + // constants private static final String APPLICATION = "-application"; private static final String BOOT = "-boot"; @@ -152,390 +151,398 @@ public class Main { } } -/** - * Executes the launch. - * - * @return the result of performing the launch - * @param args command-line arguments - * @exception Exception thrown if a problem occurs during the launch - */ -protected Object basicRun(String[] args) throws Exception { - Class clazz = getBootLoader(bootLocation); - Method method = clazz.getDeclaredMethod("run", new Class[] { String.class, URL.class, String.class, String[].class }); - try { - return method.invoke(clazz, new Object[] { application, pluginPathLocation, location, args }); - } catch (InvocationTargetException e) { - if (e.getTargetException() instanceof Error) - throw (Error) e.getTargetException(); - else - throw e; + /** + * Executes the launch. + * + * @return the result of performing the launch + * @param args command-line arguments + * @exception Exception thrown if a problem occurs during the launch + */ + protected Object basicRun(String[] args) throws Exception { + Class clazz = getBootLoader(bootLocation); + Method method = clazz.getDeclaredMethod("run", new Class[] { String.class, URL.class, String.class, String[].class }); + try { + return method.invoke(clazz, new Object[] { application, pluginPathLocation, location, args }); + } catch (InvocationTargetException e) { + if (e.getTargetException() instanceof Error) + throw (Error) e.getTargetException(); + else + throw e; + } } -} -/** - * Returns the result of converting a list of comma-separated tokens into an array - * - * @return the array of string tokens - * @param prop the initial comma-separated string - */ -private String[] getArrayFromList(String prop) { - if (prop == null || prop.trim().equals("")) - return new String[0]; - List list = new ArrayList(); - StringTokenizer tokens = new StringTokenizer(prop, ","); - while (tokens.hasMoreTokens()) { - String token = tokens.nextToken().trim(); - if (!token.equals("")) - list.add(token); + /** + * Returns the result of converting a list of comma-separated tokens into an array + * + * @return the array of string tokens + * @param prop the initial comma-separated string + */ + private String[] getArrayFromList(String prop) { + if (prop == null || prop.trim().equals("")) + return new String[0]; + List list = new ArrayList<>(); + StringTokenizer tokens = new StringTokenizer(prop, ","); + while (tokens.hasMoreTokens()) { + String token = tokens.nextToken().trim(); + if (!token.equals("")) + list.add(token); + } + return list.toArray(new String[list.size()]); } - return list.toArray(new String[list.size()]); -} -/** - * Creates and returns a platform BootLoader which can be used to start - * up and run the platform. The given base, if not null, - * is the location of the boot loader code. If the value is null - * then the boot loader is located relative to this class. - * - * @return the new boot loader - * @param base the location of the boot loader - */ -public Class getBootLoader(String base) throws Exception { - URLClassLoader loader = new URLClassLoader(getBootPath(base), null); - return loader.loadClass(BOOTLOADER); -} -/** - * Returns the URL-based class path describing where the boot classes - * are located when running in development mode. - * - * @return the url-based class path - * @param base the base location - * @exception MalformedURLException if a problem occurs computing the class path - */ -protected URL[] getDevPath(URL base) throws MalformedURLException { - URL url; - String devBase = base.toExternalForm(); - if (!inDevelopmentMode) { + + /** + * Creates and returns a platform BootLoader which can be used to start + * up and run the platform. The given base, if not null, + * is the location of the boot loader code. If the value is null + * then the boot loader is located relative to this class. + * + * @return the new boot loader + * @param base the location of the boot loader + */ + public Class getBootLoader(String base) throws Exception { + try (URLClassLoader loader = new URLClassLoader(getBootPath(base), null)) { + return loader.loadClass(BOOTLOADER); + } + } + + /** + * Returns the URL-based class path describing where the boot classes + * are located when running in development mode. + * + * @return the url-based class path + * @param base the base location + * @exception MalformedURLException if a problem occurs computing the class path + */ + protected URL[] getDevPath(URL base) throws MalformedURLException { + URL url; + String devBase = base.toExternalForm(); + if (!inDevelopmentMode) { + url = new URL(devBase + "boot.jar"); + return new URL[] {url}; + } + String[] locations = getArrayFromList(devClassPath); + ArrayList result = new ArrayList(locations.length); + for (int i = 0; i < locations.length; i++) { + String spec = devBase + locations[i]; + char lastChar = spec.charAt(spec.length() - 1); + if ((spec.endsWith(".jar") || (lastChar == '/' || lastChar == '\\'))) + url = new URL (spec); + else + url = new URL(spec + "/"); + //make sure URL exists before adding to path + if (new java.io.File(url.getFile()).exists()) + result.add(url); + } url = new URL(devBase + "boot.jar"); - return new URL[] {url}; - } - String[] locations = getArrayFromList(devClassPath); - ArrayList result = new ArrayList(locations.length); - for (int i = 0; i < locations.length; i++) { - String spec = devBase + locations[i]; - char lastChar = spec.charAt(spec.length() - 1); - if ((spec.endsWith(".jar") || (lastChar == '/' || lastChar == '\\'))) - url = new URL (spec); - else - url = new URL(spec + "/"); - //make sure URL exists before adding to path if (new java.io.File(url.getFile()).exists()) result.add(url); + return (URL[])result.toArray(new URL[result.size()]); } - url = new URL(devBase + "boot.jar"); - if (new java.io.File(url.getFile()).exists()) - result.add(url); - return (URL[])result.toArray(new URL[result.size()]); -} -/** - * Returns the URL-based class path describing where the boot classes are located. - * - * @return the url-based class path - * @param base the base location - * @exception MalformedURLException if a problem occurs computing the class path - */ -protected URL[] getBootPath(String base) throws MalformedURLException { - URL url = null; - // if the given location is not null, assume it is correct and use it. - if (base != null) { - url = new URL(base); - if (debug) - System.out.println("Boot URL: " + url.toExternalForm()); - return new URL[] {url}; - } - // Create a URL based on the location of this class' code. - // strip off jar file and/or last directory to get - // to the directory containing projects. - URL[] result = null; - url = getClass().getProtectionDomain().getCodeSource().getLocation(); - String path = url.getFile(); - if (path.endsWith(".jar")) - path = path.substring(0, path.lastIndexOf("/")); - else - if (path.endsWith("/")) - path = path.substring(0, path.length() - 1); - if (inVAJ || inVAME) { - int ix = path.lastIndexOf("/"); - path = path.substring(0, ix + 1); - path = path + PROJECT_NAME + "/"; - url = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); - result = new URL[] {url}; - } else { - path = searchForPlugins(path); - path = searchForBoot(path); - // add on any dev path elements - url = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); - result = getDevPath(url); - } - if (debug) { - System.out.println("Boot URL:"); - for (int i = 0; i < result.length; i++) - System.out.println(" " + result[i].toExternalForm()); - } - return result; -} - -/** - * Searches for a plugins root starting at a given location. If one is - * found then this location is returned; otherwise an empty string is - * returned. - * - * @return the location where plugins were found, or an empty string - * @param start the location to begin searching at - */ -protected String searchForPlugins(String start) { - File path = new File(start); - while (path != null) { - File test = new File(path, "plugins"); - if (test.exists()) - return test.toString(); - path = path.getParentFile(); - path = (path == null || path.length() == 1) ? null : path; - } - return ""; -} -/** - * Searches for a boot directory starting at a given location. If one - * is found then this location is returned; otherwise an empty string - * is returned. - * - * @return the location where plugins were found, or an empty string - * @param start the location to begin searching at - */ -protected String searchForBoot(String start) { - FileFilter filter = new FileFilter() { - @Override - public boolean accept(File candidate) { - return candidate.getName().startsWith(PI_BOOT); + /** + * Returns the URL-based class path describing where the boot classes are located. + * + * @return the url-based class path + * @param base the base location + * @exception MalformedURLException if a problem occurs computing the class path + */ + protected URL[] getBootPath(String base) throws MalformedURLException { + URL url = null; + // if the given location is not null, assume it is correct and use it. + if (base != null) { + url = new URL(base); + if (debug) + System.out.println("Boot URL: " + url.toExternalForm()); + return new URL[] {url}; } - }; - File[] boots = new File(start).listFiles(filter); - String result = null; - String maxVersion = null; - for (int i = 0; i < boots.length; i++) { - String name = boots[i].getName(); - int index = name.lastIndexOf('_'); - if (index == -1) { - result = boots[i].getAbsolutePath(); - i = boots.length; + // Create a URL based on the location of this class' code. + // strip off jar file and/or last directory to get + // to the directory containing projects. + URL[] result = null; + url = getClass().getProtectionDomain().getCodeSource().getLocation(); + String path = url.getFile(); + if (path.endsWith(".jar")) + path = path.substring(0, path.lastIndexOf("/")); + else + if (path.endsWith("/")) + path = path.substring(0, path.length() - 1); + if (inVAJ || inVAME) { + int ix = path.lastIndexOf("/"); + path = path.substring(0, ix + 1); + path = path + PROJECT_NAME + "/"; + url = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + result = new URL[] {url}; } else { - if (index > 0) { - String version = name.substring(index + 1); - if (maxVersion == null) { - result = boots[i].getAbsolutePath(); - maxVersion = version; - } else - if (maxVersion.compareTo(version) == -1) { + path = searchForPlugins(path); + path = searchForBoot(path); + // add on any dev path elements + url = new URL(url.getProtocol(), url.getHost(), url.getPort(), path); + result = getDevPath(url); + } + if (debug) { + System.out.println("Boot URL:"); + for (int i = 0; i < result.length; i++) + System.out.println(" " + result[i].toExternalForm()); + } + return result; + } + + /** + * Searches for a plugins root starting at a given location. If one is + * found then this location is returned; otherwise an empty string is + * returned. + * + * @return the location where plugins were found, or an empty string + * @param start the location to begin searching at + */ + protected String searchForPlugins(String start) { + File path = new File(start); + while (path != null) { + File test = new File(path, "plugins"); + if (test.exists()) + return test.toString(); + path = path.getParentFile(); + path = (path == null || path.length() == 1) ? null : path; + } + return ""; + } + /** + * Searches for a boot directory starting at a given location. If one + * is found then this location is returned; otherwise an empty string + * is returned. + * + * @return the location where plugins were found, or an empty string + * @param start the location to begin searching at + */ + protected String searchForBoot(String start) { + FileFilter filter = new FileFilter() { + @Override + public boolean accept(File candidate) { + return candidate.getName().startsWith(PI_BOOT); + } + }; + File[] boots = new File(start).listFiles(filter); + String result = null; + String maxVersion = null; + for (int i = 0; i < boots.length; i++) { + String name = boots[i].getName(); + int index = name.lastIndexOf('_'); + if (index == -1) { + result = boots[i].getAbsolutePath(); + i = boots.length; + } else { + if (index > 0) { + String version = name.substring(index + 1); + if (maxVersion == null) { result = boots[i].getAbsolutePath(); maxVersion = version; - } + } else + if (maxVersion.compareTo(version) == -1) { + result = boots[i].getAbsolutePath(); + maxVersion = version; + } + } } } + if (result == null) + throw new RuntimeException("Could not find bootstrap code. Check location of boot plug-in or specify -boot."); + return result.replace(File.separatorChar, '/') + "/"; } - if (result == null) - throw new RuntimeException("Could not find bootstrap code. Check location of boot plug-in or specify -boot."); - return result.replace(File.separatorChar, '/') + "/"; -} -/** - * Returns the update loader for the given boot path. - * - * @return the update loader - * @param base the boot path base - * @exception Exception thrown is a problem occurs determining this loader - */ -public Class getUpdateLoader(String base) throws Exception { - URLClassLoader loader = new URLClassLoader(getBootPath(base), null); - return loader.loadClass(UPDATELOADER); -} -/** - * Runs the platform with the given arguments. The arguments must identify - * an application to run (e.g., -application com.example.application). - * After running the application System.exit(N) is executed. - * The value of N is derived from the value returned from running the application. - * If the application's return value is an Integer, N is this value. - * In all other cases, N = 0. - *

- * Clients wishing to run the platform without a following System.exit - * call should use run(). - * - * @see #run - * - * @param args the command line arguments - */ -public static void main(String[] args) { - Object result = null; - try { - result = new Main().run(args); - } catch (Throwable e) { - // try and take down the splash screen. - endSplash(); - System.out.println("Exception launching the Eclipse Platform:"); - e.printStackTrace(); - } - int exitCode = result instanceof Integer ? ((Integer) result).intValue() : 0; - System.exit(exitCode); -} -/** - * Tears down the currently-displayed splash screen. - */ -public static void endSplash() { - if (endSplash == null) - return; - try { - Runtime.getRuntime().exec(endSplash); - } catch (Exception e) { - } -} -/** - * Runs this launcher with the arguments specified in the given string. - * - * @param argString the arguments string - * @exception Exception thrown if a problem occurs during launching - */ -public static void main(String argString) throws Exception { - List list = new ArrayList(5); - for (StringTokenizer tokens = new StringTokenizer(argString, " "); tokens.hasMoreElements();) - list.add((String) tokens.nextElement()); - main(list.toArray(new String[list.size()])); -} - -/** - * Processes the command line arguments - * - * @return the arguments to pass through to the launched application - * @param args the command line arguments - */ -protected String[] processCommandLine(String[] args) throws Exception { - int[] configArgs = new int[100]; - configArgs[0] = -1; // need to initialize the first element to something that could not be an index. - int configArgIndex = 0; - for (int i = 0; i < args.length; i++) { - boolean found = false; - // check for args without parameters (i.e., a flag arg) - // check if debug should be enabled for the entire platform - if (args[i].equalsIgnoreCase(DEBUG)) { - debug = true; - // passed thru this arg (i.e., do not set found = true - continue; - } - - // check if development mode should be enabled for the entire platform - // If this is the last arg or there is a following arg (i.e., arg+1 has a leading -), - // simply enable development mode. Otherwise, assume that that the following arg is - // actually some additional development time class path entries. This will be processed below. - if (args[i].equalsIgnoreCase(DEV) && ((i + 1 == args.length) || ((i + 1 < args.length) && (args[i + 1].startsWith("-"))))) { - inDevelopmentMode = true; - // do not mark the arg as found so it will be passed through - continue; - } - - // done checking for args. Remember where an arg was found - if (found) { - configArgs[configArgIndex++] = i; - continue; - } - // check for args with parameters. If we are at the last argument or if the next one - // has a '-' as the first character, then we can't have an arg with a parm so continue. - if (i == args.length - 1 || args[i + 1].startsWith("-")) - continue; - String arg = args[++i]; - - // look for the laucher to run - if (args[i - 1].equalsIgnoreCase(BOOT)) { - bootLocation = arg; - found = true; - } - - // look for the development mode and class path entries. - if (args[i - 1].equalsIgnoreCase(DEV)) { - inDevelopmentMode = true; - devClassPath = arg; - continue; - } - - // look for the application to run - if (args[i - 1].equalsIgnoreCase(APPLICATION)) { - application = arg; - found = true; - } - - // look for token to use to end the splash screen - if (args[i - 1].equalsIgnoreCase(ENDSPLASH)) { - endSplash = arg; - continue; - } - - // look for items to uninstall - if (args[i - 1].equalsIgnoreCase(UNINSTALL)) { - uninstall = true; - uninstallCookie = arg; - found = true; - } - - // done checking for args. Remember where an arg was found - if (found) { - configArgs[configArgIndex++] = i - 1; - configArgs[configArgIndex++] = i; + /** + * Returns the update loader for the given boot path. + * + * @return the update loader + * @param base the boot path base + * @exception Exception thrown is a problem occurs determining this loader + */ + public Class getUpdateLoader(String base) throws Exception { + try (URLClassLoader loader = new URLClassLoader(getBootPath(base), null)) { + return loader.loadClass(UPDATELOADER); } } - // remove all the arguments consumed by this argument parsing - if (configArgIndex == 0) - return args; - String[] passThruArgs = new String[args.length - configArgIndex]; - configArgIndex = 0; - int j = 0; - for (int i = 0; i < args.length; i++) { - if (i == configArgs[configArgIndex]) - configArgIndex++; + + /** + * Runs the platform with the given arguments. The arguments must identify + * an application to run (e.g., -application com.example.application). + * After running the application System.exit(N) is executed. + * The value of N is derived from the value returned from running the application. + * If the application's return value is an Integer, N is this value. + * In all other cases, N = 0. + *

+ * Clients wishing to run the platform without a following System.exit + * call should use run(). + * + * @see #run + * + * @param args the command line arguments + */ + public static void main(String[] args) { + Object result = null; + try { + result = new Main().run(args); + } catch (Throwable e) { + // try and take down the splash screen. + endSplash(); + System.out.println("Exception launching the Eclipse Platform:"); + e.printStackTrace(); + } + int exitCode = result instanceof Integer ? ((Integer) result).intValue() : 0; + System.exit(exitCode); + } + /** + * Tears down the currently-displayed splash screen. + */ + public static void endSplash() { + if (endSplash == null) + return; + try { + Runtime.getRuntime().exec(endSplash); + } catch (Exception e) { + } + } + + /** + * Runs this launcher with the arguments specified in the given string. + * + * @param argString the arguments string + * @exception Exception thrown if a problem occurs during launching + */ + public static void main(String argString) throws Exception { + List list = new ArrayList(5); + for (StringTokenizer tokens = new StringTokenizer(argString, " "); tokens.hasMoreElements();) + list.add((String) tokens.nextElement()); + main(list.toArray(new String[list.size()])); + } + + /** + * Processes the command line arguments + * + * @return the arguments to pass through to the launched application + * @param args the command line arguments + */ + protected String[] processCommandLine(String[] args) throws Exception { + int[] configArgs = new int[100]; + configArgs[0] = -1; // need to initialize the first element to something that could not be an index. + int configArgIndex = 0; + for (int i = 0; i < args.length; i++) { + boolean found = false; + // check for args without parameters (i.e., a flag arg) + // check if debug should be enabled for the entire platform + if (args[i].equalsIgnoreCase(DEBUG)) { + debug = true; + // passed thru this arg (i.e., do not set found = true + continue; + } + + // check if development mode should be enabled for the entire platform + // If this is the last arg or there is a following arg (i.e., arg+1 has a leading -), + // simply enable development mode. Otherwise, assume that that the following arg is + // actually some additional development time class path entries. This will be processed below. + if (args[i].equalsIgnoreCase(DEV) && ((i + 1 == args.length) || ((i + 1 < args.length) && (args[i + 1].startsWith("-"))))) { + inDevelopmentMode = true; + // do not mark the arg as found so it will be passed through + continue; + } + + // done checking for args. Remember where an arg was found + if (found) { + configArgs[configArgIndex++] = i; + continue; + } + // check for args with parameters. If we are at the last argument or if the next one + // has a '-' as the first character, then we can't have an arg with a parm so continue. + if (i == args.length - 1 || args[i + 1].startsWith("-")) + continue; + String arg = args[++i]; + + // look for the laucher to run + if (args[i - 1].equalsIgnoreCase(BOOT)) { + bootLocation = arg; + found = true; + } + + // look for the development mode and class path entries. + if (args[i - 1].equalsIgnoreCase(DEV)) { + inDevelopmentMode = true; + devClassPath = arg; + continue; + } + + // look for the application to run + if (args[i - 1].equalsIgnoreCase(APPLICATION)) { + application = arg; + found = true; + } + + // look for token to use to end the splash screen + if (args[i - 1].equalsIgnoreCase(ENDSPLASH)) { + endSplash = arg; + continue; + } + + // look for items to uninstall + if (args[i - 1].equalsIgnoreCase(UNINSTALL)) { + uninstall = true; + uninstallCookie = arg; + found = true; + } + + // done checking for args. Remember where an arg was found + if (found) { + configArgs[configArgIndex++] = i - 1; + configArgs[configArgIndex++] = i; + } + } + // remove all the arguments consumed by this argument parsing + if (configArgIndex == 0) + return args; + String[] passThruArgs = new String[args.length - configArgIndex]; + configArgIndex = 0; + int j = 0; + for (int i = 0; i < args.length; i++) { + if (i == configArgs[configArgIndex]) + configArgIndex++; + else + passThruArgs[j++] = args[i]; + } + return passThruArgs; + } + + /** + * Runs the application to be launched. + * + * @return the return value from the launched application + * @param args the arguments to pass to the application + * @exception thrown if a problem occurs during launching + */ + public Object run(String[] args) throws Exception { + String[] passThruArgs = processCommandLine(args); + if (uninstall) + return updateRun(UNINSTALL, uninstallCookie, passThruArgs); else - passThruArgs[j++] = args[i]; + return basicRun(passThruArgs); } - return passThruArgs; -} -/** - * Runs the application to be launched. - * - * @return the return value from the launched application - * @param args the arguments to pass to the application - * @exception thrown if a problem occurs during launching - */ -public Object run(String[] args) throws Exception { - String[] passThruArgs = processCommandLine(args); - if (uninstall) - return updateRun(UNINSTALL, uninstallCookie, passThruArgs); - else - return basicRun(passThruArgs); -} -/** - * Performs an update run. - * - * @return the return value from the update loader - * @param flag flag to give to the update loader - * @param value value to give to the update loader - * @param args arguments to give to the update loader. - * @exception Exception thrown if a problem occurs during execution - */ -protected Object updateRun(String flag, String value, String[] args) throws Exception { - Class clazz = getUpdateLoader(bootLocation); - Method method = clazz.getDeclaredMethod("run", new Class[] { String.class, String.class, String.class, String[].class }); - try { - return method.invoke(clazz, new Object[] { flag, value, location, args }); - } catch (InvocationTargetException e) { - if (e.getTargetException() instanceof Error) - throw (Error) e.getTargetException(); - else - throw e; + + /** + * Performs an update run. + * + * @return the return value from the update loader + * @param flag flag to give to the update loader + * @param value value to give to the update loader + * @param args arguments to give to the update loader. + * @exception Exception thrown if a problem occurs during execution + */ + protected Object updateRun(String flag, String value, String[] args) throws Exception { + Class clazz = getUpdateLoader(bootLocation); + Method method = clazz.getDeclaredMethod("run", new Class[] { String.class, String.class, String.class, String[].class }); + try { + return method.invoke(clazz, new Object[] { flag, value, location, args }); + } catch (InvocationTargetException e) { + if (e.getTargetException() instanceof Error) + throw (Error) e.getTargetException(); + else + throw e; + } } } -} diff --git a/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/TestScannerProvider.java b/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/TestScannerProvider.java index bc8f98a75da..f0d8008e6e5 100644 --- a/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/TestScannerProvider.java +++ b/core/org.eclipse.cdt.core.tests/suite/org/eclipse/cdt/core/testplugin/TestScannerProvider.java @@ -24,7 +24,7 @@ public class TestScannerProvider extends AbstractCExtension implements IScannerI public static String[] sIncludes; public static String[] sIncludeFiles; public static String[] sMacroFiles; - public static Map sDefinedSymbols = new HashMap(); + public static Map sDefinedSymbols = new HashMap<>(); public final static String SCANNER_ID = CTestPlugin.PLUGIN_ID + ".TestScanner"; public static void clear() { diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/CSourceEntry.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/CSourceEntry.java index f0fcdfc3646..ad7613cfd42 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/CSourceEntry.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/CSourceEntry.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Intel Corporation - Initial API and implementation + * Intel Corporation - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.settings.model; diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/ICPathEntry.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/ICPathEntry.java index 81bb7e5a7a4..e40912017e0 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/ICPathEntry.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/ICPathEntry.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Intel Corporation - Initial API and implementation + * Intel Corporation - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.settings.model; @@ -15,7 +15,6 @@ import org.eclipse.core.runtime.IPath; /** * Helper interface capturing 'path' characteristic for {@link ICSettingEntry} * and {@link ICLanguageSettingEntry} interfaces. - * */ public interface ICPathEntry extends ICSettingEntry { IPath getFullPath(); @@ -23,5 +22,4 @@ public interface ICPathEntry extends ICSettingEntry { IPath getLocation(); boolean isValueWorkspacePath(); - } diff --git a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/util/CDataUtil.java b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/util/CDataUtil.java index df806313cad..891731a5835 100644 --- a/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/util/CDataUtil.java +++ b/core/org.eclipse.cdt.core/model/org/eclipse/cdt/core/settings/model/util/CDataUtil.java @@ -6,7 +6,7 @@ * http://www.eclipse.org/legal/epl-v10.html * * Contributors: - * Intel Corporation - Initial API and implementation + * Intel Corporation - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.core.settings.model.util; @@ -76,16 +76,16 @@ public class CDataUtil { private static final String DELIM = " "; //$NON-NLS-1$ private static Random randomNumber; - public static final String[] EMPTY_STRING_ARRAY = new String[0]; + public static final String[] EMPTY_STRING_ARRAY = {}; /** * Pool of setting entries implemented as WeakHashSet. That allows to gain memory savings * at the expense of CPU time. WeakHashSet handles garbage collection when a list is not * referenced anywhere else. See JavaDoc {@link java.lang.ref.WeakReference} about weak reference objects. */ - private static WeakHashSet settingEntriesPool = new WeakHashSetSynchronized(); + private static WeakHashSet settingEntriesPool = new WeakHashSetSynchronized<>(); - public static int genRandomNumber(){ + public static int genRandomNumber() { if (randomNumber == null) { // Set the random number seed randomNumber = new Random(); @@ -98,68 +98,68 @@ public class CDataUtil { return i; } - public static String genId(String baseId){ + public static String genId(String baseId) { String suffix = new Integer(genRandomNumber()).toString(); return baseId != null ? - new StringBuffer(baseId).append(".").append(suffix).toString() //$NON-NLS-1$ - : suffix; + new StringBuilder(baseId).append(".").append(suffix).toString() : //$NON-NLS-1$ + suffix; } - public static boolean objectsEqual(Object o1, Object o2){ - if(o1 == null) + public static boolean objectsEqual(Object o1, Object o2) { + if (o1 == null) return o2 == null; return o1.equals(o2); } - public static String arrayToString(String[] array, String separator){ + public static String arrayToString(String[] array, String separator) { return arrayToString((Object[])array, separator); } - public static String arrayToString(Object[] array, String separator){ - if(array == null) + public static String arrayToString(Object[] array, String separator) { + if (array == null) return null; - if(array.length == 0) + if (array.length == 0) return ""; //$NON-NLS-1$ - if(array.length == 1) + if (array.length == 1) return array[0].toString(); - StringBuffer buf = new StringBuffer(); + StringBuilder buf = new StringBuilder(); buf.append(array[0]); - for(int i = 1; i < array.length; i++){ + for (int i = 1; i < array.length; i++) { buf.append(separator).append(array[i]); } return buf.toString(); } - public static String[] stringToArray(String string, String separator){ - if(string == null) + public static String[] stringToArray(String string, String separator) { + if (string == null) return null; - if(string.length() == 0) + if (string.length() == 0) return EMPTY_STRING_ARRAY; StringTokenizer t = new StringTokenizer(string, separator); - List list = new ArrayList(t.countTokens()); + List list = new ArrayList<>(t.countTokens()); while (t.hasMoreElements()) { list.add(t.nextToken()); } return list.toArray(new String[list.size()]); } - public static ICSettingEntry[] resolveEntries(ICSettingEntry entries[], ICConfigurationDescription cfgDes){ - if(entries.length == 0) + public static ICSettingEntry[] resolveEntries(ICSettingEntry entries[], ICConfigurationDescription cfgDes) { + if (entries.length == 0) return entries; - ArrayList out = new ArrayList(entries.length); + ArrayList out = new ArrayList<>(entries.length); ICdtVariableManager mngr = CCorePlugin.getDefault().getCdtVariableManager(); - for(int i = 0; i < entries.length; i++){ + for (int i = 0; i < entries.length; i++) { ICSettingEntry entry = entries[i]; out.addAll(Arrays.asList(createResolvedEntry(entry, cfgDes, mngr))); } return out.toArray(new ICSettingEntry[out.size()]); } - public static ICLanguageSettingEntry[] resolveEntries(ICLanguageSettingEntry entries[], ICConfigurationDescription cfgDes){ - if(entries.length == 0) + public static ICLanguageSettingEntry[] resolveEntries(ICLanguageSettingEntry entries[], ICConfigurationDescription cfgDes) { + if (entries.length == 0) return entries; ICSettingEntry[] resolved = resolveEntries((ICSettingEntry[])entries, cfgDes); @@ -168,8 +168,8 @@ public class CDataUtil { return resolvedLangEntries; } - public static ICSourceEntry[] resolveEntries(ICSourceEntry entries[], ICConfigurationDescription cfgDes){ - if(entries.length == 0) + public static ICSourceEntry[] resolveEntries(ICSourceEntry entries[], ICConfigurationDescription cfgDes) { + if (entries.length == 0) return entries; ICSettingEntry[] resolved = resolveEntries((ICSettingEntry[])entries, cfgDes); @@ -178,8 +178,8 @@ public class CDataUtil { return resolvedLangEntries; } - public static ICOutputEntry[] resolveEntries(ICOutputEntry entries[], ICConfigurationDescription cfgDes){ - if(entries.length == 0) + public static ICOutputEntry[] resolveEntries(ICOutputEntry entries[], ICConfigurationDescription cfgDes) { + if (entries.length == 0) return entries; ICSettingEntry[] resolved = resolveEntries((ICSettingEntry[])entries, cfgDes); @@ -188,8 +188,8 @@ public class CDataUtil { return resolvedLangEntries; } - private static ICSettingEntry[] createResolvedEntry(ICSettingEntry entry, ICConfigurationDescription cfg, ICdtVariableManager mngr){ - if(entry.isResolved()) + private static ICSettingEntry[] createResolvedEntry(ICSettingEntry entry, ICConfigurationDescription cfg, ICdtVariableManager mngr) { + if (entry.isResolved()) return new ICSettingEntry[] { entry }; String name = entry.getName(); @@ -227,17 +227,17 @@ public class CDataUtil { srcPath = libFile.getSourceAttachmentPath(); srcRootPath = libFile.getSourceAttachmentRootPath(); srcPrefixMapping = libFile.getSourceAttachmentPrefixMapping(); - if(srcPath != null) + if (srcPath != null) srcPath = resolvePath(mngr, cfg, srcPath); - if(srcRootPath != null) + if (srcRootPath != null) srcRootPath = resolvePath(mngr, cfg, srcRootPath); - if(srcPrefixMapping != null) + if (srcPrefixMapping != null) srcPrefixMapping = resolvePath(mngr, cfg, srcPrefixMapping); break; case ICSettingEntry.SOURCE_PATH: case ICSettingEntry.OUTPUT_PATH: exclusionFilters = ((ICExclusionPatternPathEntry)entry).getExclusionPatterns(); - for(int i = 0; i < exclusionFilters.length; i++){ + for (int i = 0; i < exclusionFilters.length; i++) { String exclString = exclusionFilters[i].toString(); try { exclString = mngr.resolveValue(exclString, EMPTY, DELIM, cfg); @@ -255,14 +255,14 @@ public class CDataUtil { return result; } - private static IPath resolvePath(ICdtVariableManager mngr, ICConfigurationDescription cfg, IPath path){ - if(path == null) + private static IPath resolvePath(ICdtVariableManager mngr, ICConfigurationDescription cfg, IPath path) { + if (path == null) return null; try { String unresolved = path.toString(); String resolved = mngr.resolveValue(unresolved, EMPTY, DELIM, cfg); - if(resolved != null && !resolved.equals(unresolved)) + if (resolved != null && !resolved.equals(unresolved)) path = new Path(resolved); } catch (CdtVariableException e) { CCorePlugin.log(e); @@ -347,7 +347,7 @@ public class CDataUtil { */ public static ICSettingEntry createEntry(int kind, String name, String value, IPath[] exclusionPatterns, int flags, IPath sourceAttachmentPath, IPath sourceAttachmentRootPath, IPath sourceAttachmentPrefixMapping) { ICSettingEntry entry = null; - switch (kind){ + switch (kind) { case ICLanguageSettingEntry.INCLUDE_PATH: entry = new CIncludePathEntry(name, flags); break; @@ -441,35 +441,35 @@ public class CDataUtil { public static String[] getSourceExtensions(IProject project, CLanguageData data) { String[] exts = null; String[] typeIds = data.getSourceContentTypeIds(); - if(typeIds != null && typeIds.length != 0){ + if (typeIds != null && typeIds.length != 0) { exts = getExtensionsFromContentTypes(project, typeIds); } else { exts = data.getSourceExtensions(); - if(exts != null && exts.length != 0) + if (exts != null && exts.length != 0) exts = exts.clone(); else exts = CDefaultLanguageData.EMPTY_STRING_ARRAY; } - if(exts == null) + if (exts == null) exts = CDefaultLanguageData.EMPTY_STRING_ARRAY; return exts; } - public static String[] getExtensionsFromContentTypes(IProject project, String[] typeIds){ + public static String[] getExtensionsFromContentTypes(IProject project, String[] typeIds) { String[] exts = null; - if(typeIds != null && typeIds.length != 0){ + if (typeIds != null && typeIds.length != 0) { IContentTypeManager manager = Platform.getContentTypeManager(); IContentType type; - if(typeIds.length == 1){ + if (typeIds.length == 1) { type = manager.getContentType(typeIds[0]); - if(type != null) + if (type != null) exts = getContentTypeFileSpecs(project, type); } else { - List list = new ArrayList(); - for(int i = 0; i < typeIds.length; i++){ + List list = new ArrayList<>(); + for (int i = 0; i < typeIds.length; i++) { type = manager.getContentType(typeIds[i]); - if(type != null) { + if (type != null) { list.addAll(Arrays.asList(getContentTypeFileSpecs(project, type))); } } @@ -477,7 +477,7 @@ public class CDataUtil { } } - if(exts == null) + if (exts == null) exts = CDefaultLanguageData.EMPTY_STRING_ARRAY; return exts; } @@ -511,45 +511,45 @@ public class CDataUtil { return globalSpecs; } - public static CLanguageData findLanguagDataForFile(String fileName, IProject project, CFolderData fData){ + public static CLanguageData findLanguagDataForFile(String fileName, IProject project, CFolderData fData) { return findLanguagDataForFile(fileName, project, fData.getLanguageDatas()); } - public static CLanguageData findLanguagDataForFile(String fileName, IProject project, CLanguageData datas[]){ - // if(cType != null){ + public static CLanguageData findLanguagDataForFile(String fileName, IProject project, CLanguageData datas[]) { + // if (cType != null) { // setting = findLanguageSettingForContentTypeId(cType.getId(), settings, true); - // if(setting == null) + // if (setting == null) // setting = findLanguageSettingForContentTypeId(cType.getId(), settings, false); // } CLanguageData data = null; int index = fileName.lastIndexOf('.'); - if(index > 0){ + if (index > 0) { String ext = fileName.substring(index + 1).trim(); - if(ext.length() > 0){ + if (ext.length() > 0) { data = findLanguageDataForExtension(ext, datas); } } return data; } - public static CLanguageData findLanguageDataForExtension(String ext, CLanguageData datas[]/*, boolean src*/){ + public static CLanguageData findLanguageDataForExtension(String ext, CLanguageData datas[]/*, boolean src*/) { CLanguageData data; - for(int i = 0; i < datas.length; i++){ + for (int i = 0; i < datas.length; i++) { data = datas[i]; String exts[] = data.getSourceExtensions(); -/* if(src){ - if(setting.getSourceContentType() == null){ +/* if (src) { + if (setting.getSourceContentType() == null) { exts = setting.getSourceExtensions(); } } else { - if(setting.getHeaderContentType() == null){ + if (setting.getHeaderContentType() == null) { exts = setting.getHeaderExtensions(); } } */ - if(exts != null && exts.length != 0){ - for(int j = 0; j < exts.length; j++){ - if(ext.equals(exts[j])) + if (exts != null && exts.length != 0) { + for (int j = 0; j < exts.length; j++) { + if (ext.equals(exts[j])) return data; } } @@ -557,25 +557,25 @@ public class CDataUtil { return null; } - public static Map createPathRcDataMap(CConfigurationData data){ - Map map = new HashMap(); + public static Map createPathRcDataMap(CConfigurationData data) { + Map map = new HashMap<>(); CResourceData[] rcDatas = data.getResourceDatas(); CResourceData rcData; - for(int i = 0; i < rcDatas.length; i++){ + for (int i = 0; i < rcDatas.length; i++) { rcData = rcDatas[i]; map.put(rcData.getPath(), rcData); } return map; } - public static PathSettingsContainer createRcDataHolder(CConfigurationData data){ + public static PathSettingsContainer createRcDataHolder(CConfigurationData data) { PathSettingsContainer h = PathSettingsContainer.createRootContainer(); h.setValue(data.getRootFolderData()); CResourceData[] rcDatas = data.getResourceDatas(); CResourceData rcData; PathSettingsContainer child; - for(int i = 0; i < rcDatas.length; i++){ + for (int i = 0; i < rcDatas.length; i++) { rcData = rcDatas[i]; child = h.getChildContainer(rcData.getPath(), true, true); child.setValue(rcData); @@ -583,41 +583,41 @@ public class CDataUtil { return h; } - public static CConfigurationData createEmptyData(String id, String name, CDataFactory factory, boolean performLangAdjustment){ - if(id == null) + public static CConfigurationData createEmptyData(String id, String name, CDataFactory factory, boolean performLangAdjustment) { + if (id == null) id = genId(null); CConfigurationData data = factory.createConfigurationdata(id, name, null, false); - if(data.getRootFolderData() == null){ + if (data.getRootFolderData() == null) { CFolderData foData = factory.createFolderData(data, null, genId(data.getId()), false, Path.EMPTY); factory.link(data, foData); } - if(data.getBuildData() == null){ + if (data.getBuildData() == null) { CBuildData bData = factory.createBuildData(data, null, genId(data.getId()), null, false); factory.link(data, bData); } - if(data.getTargetPlatformData() == null){ + if (data.getTargetPlatformData() == null) { CTargetPlatformData tpData = factory.createTargetPlatformData(data, null, genId(data.getId()), null, false); factory.link(data, tpData); } - if(performLangAdjustment) + if (performLangAdjustment) adjustConfig(data, factory); return data; } - public static CConfigurationData adjustConfig(CConfigurationData cfg, CDataFactory factory){ + public static CConfigurationData adjustConfig(CConfigurationData cfg, CDataFactory factory) { LanguageManager mngr = LanguageManager.getInstance(); ILanguageDescriptor dess[] = mngr.getLanguageDescriptors(); Map map = mngr.getContentTypeIdToLanguageDescriptionsMap(); CResourceData[] rcDatas = cfg.getResourceDatas(); - for(int i = 0; i < rcDatas.length; i++){ - if(rcDatas[i].getType() == ICSettingBase.SETTING_FOLDER){ - adjustFolderData(cfg, (CFolderData)rcDatas[i], factory, dess, new HashMap(map)); + for (int i = 0; i < rcDatas.length; i++) { + if (rcDatas[i].getType() == ICSettingBase.SETTING_FOLDER) { + adjustFolderData(cfg, (CFolderData)rcDatas[i], factory, dess, new HashMap<>(map)); } } @@ -625,26 +625,26 @@ public class CDataUtil { } - private static void adjustFolderData(CConfigurationData cfgData, CFolderData data, CDataFactory factory, ILanguageDescriptor dess[], HashMap map){ - Map langMap = new HashMap(); - for(int i = 0; i < dess.length; i++){ + private static void adjustFolderData(CConfigurationData cfgData, CFolderData data, CDataFactory factory, ILanguageDescriptor dess[], HashMap map) { + Map langMap = new HashMap<>(); + for (int i = 0; i < dess.length; i++) { langMap.put(dess[i].getId(), dess[i]); } CLanguageData lDatas[] = data.getLanguageDatas(); - for(int i = 0; i < lDatas.length; i++){ + for (int i = 0; i < lDatas.length; i++) { CLanguageData lData = lDatas[i]; String langId = lData.getLanguageId(); - if(langId != null){ + if (langId != null) { ILanguageDescriptor des = langMap.remove(langId); adjustLanguageData(data, lData, des); continue; } else { String[] cTypeIds = lData.getSourceContentTypeIds(); - for(int c = 0; c < cTypeIds.length; c++){ + for (int c = 0; c < cTypeIds.length; c++) { String cTypeId = cTypeIds[c]; ILanguageDescriptor[] langs = map.remove(cTypeId); - if(langs != null && langs.length != 0){ - for(int q = 0; q < langs.length; q++){ + if (langs != null && langs.length != 0) { + for (int q = 0; q < langs.length; q++) { langMap.remove(langs[q].getId()); } @@ -654,49 +654,49 @@ public class CDataUtil { } } - if(!langMap.isEmpty()){ + if (!langMap.isEmpty()) { addLangs(cfgData, data, factory, langMap, map); } } - private static CLanguageData adjustLanguageData(CFolderData data, CLanguageData lData, ILanguageDescriptor des){ + private static CLanguageData adjustLanguageData(CFolderData data, CLanguageData lData, ILanguageDescriptor des) { String [] cTypeIds = des.getContentTypeIds(); String srcIds[] = lData.getSourceContentTypeIds(); - Set landTypes = new HashSet(Arrays.asList(cTypeIds)); + Set landTypes = new HashSet<>(Arrays.asList(cTypeIds)); landTypes.removeAll(Arrays.asList(srcIds)); - if(landTypes.size() != 0){ - List srcList = new ArrayList(); + if (landTypes.size() != 0) { + List srcList = new ArrayList<>(); srcList.addAll(landTypes); lData.setSourceContentTypeIds(srcList.toArray(new String[srcList.size()])); } - if(!des.getId().equals(lData.getLanguageId())){ + if (!des.getId().equals(lData.getLanguageId())) { lData.setLanguageId(des.getId()); } return lData; } - private static void addLangs(CConfigurationData cfgData, CFolderData data, CDataFactory factory, Map langMap, Map cTypeToLangMap){ - List list = new ArrayList(langMap.values()); + private static void addLangs(CConfigurationData cfgData, CFolderData data, CDataFactory factory, Map langMap, Map cTypeToLangMap) { + List list = new ArrayList<>(langMap.values()); ILanguageDescriptor des; - while(list.size() != 0){ + while(list.size() != 0) { des = list.remove(list.size() - 1); String[] ctypeIds = des.getContentTypeIds(); boolean addLang = false; - for(int i = 0; i < ctypeIds.length; i++){ + for (int i = 0; i < ctypeIds.length; i++) { ILanguageDescriptor[] langs = cTypeToLangMap.remove(ctypeIds[i]); - if(langs != null && langs.length != 0){ + if (langs != null && langs.length != 0) { addLang = true; - for(int q = 0; q < langs.length; q++){ + for (int q = 0; q < langs.length; q++) { list.remove(langs[q]); } } } - if(addLang){ + if (addLang) { CLanguageData lData = factory.createLanguageData(cfgData, data, genId(data.getId()), des.getName(), des.getId(), ICSettingEntry.INCLUDE_FILE | ICSettingEntry.INCLUDE_PATH @@ -708,45 +708,45 @@ public class CDataUtil { } } - public static boolean isExcluded(IPath path, ICSourceEntry[] entries){ - for(int i = 0; i < entries.length; i++){ - if(!isExcluded(path, entries[i])) + public static boolean isExcluded(IPath path, ICSourceEntry[] entries) { + for (int i = 0; i < entries.length; i++) { + if (!isExcluded(path, entries[i])) return false; } return true; } - public static boolean isExcluded(IPath path, ICSourceEntry entry){ + public static boolean isExcluded(IPath path, ICSourceEntry entry) { IPath entryPath = new Path(entry.getName()); - if(path.isPrefixOf(entryPath)) + if (path.isPrefixOf(entryPath)) return false; - if(!entryPath.isPrefixOf(path)) + if (!entryPath.isPrefixOf(path)) return true; - if(path.segmentCount() == 0) + if (path.segmentCount() == 0) return false; char[][] exclusions = entry.fullExclusionPatternChars(); return CoreModelUtil.isExcluded(path, exclusions); } - public static boolean isOnSourceEntry(IPath path, ICSourceEntry entry){ + public static boolean isOnSourceEntry(IPath path, ICSourceEntry entry) { IPath entryPath = new Path(entry.getName()); - if(path.equals(entryPath)) + if (path.equals(entryPath)) return true; - if(!entryPath.isPrefixOf(path)) + if (!entryPath.isPrefixOf(path)) return false; - if(path.segmentCount() == 0) + if (path.segmentCount() == 0) return true; char[][] exclusions = entry.fullExclusionPatternChars(); return !CoreModelUtil.isExcluded(path, exclusions); } - public static boolean canExclude(IPath path, boolean isFolder, boolean excluded, ICSourceEntry[] entries){ + public static boolean canExclude(IPath path, boolean isFolder, boolean excluded, ICSourceEntry[] entries) { try { ICSourceEntry[] out = setExcluded(path, isFolder, excluded, entries, false); return !isEqual(entries, out); @@ -761,9 +761,11 @@ public class CDataUtil { * @return - true if they are equal */ public static boolean isEqual(ICSourceEntry[] ein, ICSourceEntry[] aus) { - if (ein == null || aus == null) return (ein == null && aus == null); - if (ein.length != aus.length) return false; - for (int i=0; i includeList = new ArrayList(entries.length); - List excludeList = new ArrayList(entries.length); + if (excluded) { + List includeList = new ArrayList<>(entries.length); + List excludeList = new ArrayList<>(entries.length); sortEntries(path, false, entries, includeList, excludeList); - for(int i = 0; i < includeList.size(); i++){ + for (int i = 0; i < includeList.size(); i++) { ICSourceEntry oldEntry = includeList.get(i); List tmp = new ArrayList(1); tmp.add(path); ICSourceEntry newEntry = addExcludePaths(oldEntry, tmp, true); - if(newEntry != null) + if (newEntry != null) excludeList.add(newEntry); } newEntries = excludeList.toArray(new ICSourceEntry[excludeList.size()]); } else { - List includeList = new ArrayList(entries.length + 1); - List excludeList = new ArrayList(entries.length); + List includeList = new ArrayList<>(entries.length + 1); + List excludeList = new ArrayList<>(entries.length); sortIncludingExcludingEntries(path, entries, includeList, excludeList); boolean included = false; - if(includeList.size() != 0){ - if(includeExclusion(path, includeList) >= 0) + if (includeList.size() != 0) { + if (includeExclusion(path, includeList) >= 0) included = true; } - if(!included){ - if(isFolder){ + if (!included) { + if (isFolder) { includeList.add(new CSourceEntry(path, null, ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.RESOLVED)); } else { - if(throwExceptionOnErr) + if (throwExceptionOnErr) throw ExceptionFactory.createCoreException("can not create a source entry for individual file"); //$NON-NLS-1$ return null; } @@ -844,11 +846,11 @@ public class CDataUtil { return newEntries; } - private static int includeExclusion(IPath path, List entries){ - for(int i = 0; i < entries.size(); i++){ + private static int includeExclusion(IPath path, List entries) { + for (int i = 0; i < entries.size(); i++) { ICSourceEntry entry = entries.get(i); entry = include(path, entry); - if(entry != null) { + if (entry != null) { entries.set(i, entry); return i; } @@ -856,17 +858,17 @@ public class CDataUtil { return -1; } - private static ICSourceEntry include(IPath path, ICSourceEntry entry){ + private static ICSourceEntry include(IPath path, ICSourceEntry entry) { IPath[] exclusions = entry.getExclusionPatterns(); IPath entryPath = new Path(entry.getName()); IPath relPath = path.removeFirstSegments(entryPath.segmentCount()).makeRelative(); - for(int k = 0; k < exclusions.length; k++){ - if(exclusions[k].equals(relPath)){ + for (int k = 0; k < exclusions.length; k++) { + if (exclusions[k].equals(relPath)) { IPath updatedExclusions[] = new IPath[exclusions.length - 1]; System.arraycopy(exclusions, 0, updatedExclusions, 0, k); System.arraycopy(exclusions, k + 1, updatedExclusions, k, updatedExclusions.length - k); ICSourceEntry updatedEntry = new CSourceEntry(entry.getName(), updatedExclusions, entry.getFlags()); - if(isOnSourceEntry(path, updatedEntry)) + if (isOnSourceEntry(path, updatedEntry)) return updatedEntry; exclusions = updatedExclusions; entry = updatedEntry; @@ -875,93 +877,96 @@ public class CDataUtil { return null; } - private static void sortIncludingExcludingEntries(IPath path, ICSourceEntry[] entries, List including, List excluding){ - for(int i = 0; i < entries.length; i++){ + private static void sortIncludingExcludingEntries(IPath path, ICSourceEntry[] entries, List including, List excluding) { + for (int i = 0; i < entries.length; i++) { IPath entryPath = new Path(entries[i].getName()); - if(entryPath.isPrefixOf(path)) + if (entryPath.isPrefixOf(path)) { including.add(entries[i]); - else + } else { excluding.add(entries[i]); + } } } - public static ICSourceEntry[] adjustEntries(ICSourceEntry entries[]){ + public static ICSourceEntry[] adjustEntries(ICSourceEntry entries[]) { return adjustEntries(entries, false, null); } - private static ICSourceEntry[] getDefaultSourceEntries(boolean absolute, IProject project){ + private static ICSourceEntry[] getDefaultSourceEntries(boolean absolute, IProject project) { ICSourceEntry entry; - if(absolute){ - if(project != null) + if (absolute) { + if (project != null) { entry = new CSourceEntry(project.getFullPath(), null, ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.RESOLVED); - else + } else { entry = new CSourceEntry(Path.EMPTY, null, ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.RESOLVED); + } } else { entry = new CSourceEntry(Path.EMPTY, null, ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.RESOLVED); } - return new ICSourceEntry[]{entry}; + return new ICSourceEntry[] { entry }; } - private static ICOutputEntry[] getDefaultOutputEntries(boolean absolute, IProject project){ + private static ICOutputEntry[] getDefaultOutputEntries(boolean absolute, IProject project) { ICOutputEntry entry; - if(absolute){ - if(project != null) + if (absolute) { + if (project != null) { entry = new COutputEntry(project.getFullPath(), null, ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.RESOLVED); - else + } else { entry = new COutputEntry(Path.EMPTY, null, ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.RESOLVED); + } } else { entry = new COutputEntry(Path.EMPTY, null, ICSettingEntry.VALUE_WORKSPACE_PATH | ICSettingEntry.RESOLVED); } - return new ICOutputEntry[]{entry}; + return new ICOutputEntry[] { entry }; } - public static ICOutputEntry[] adjustEntries(ICOutputEntry entries[], boolean makeAbsolute, IProject project){ - if(entries == null || entries.length == 0) + public static ICOutputEntry[] adjustEntries(ICOutputEntry entries[], boolean makeAbsolute, IProject project) { + if (entries == null || entries.length == 0) return getDefaultOutputEntries(makeAbsolute, project); return makeAbsolute ? makeAbsolute(project, entries) : makeRelative(project, entries); } - public static ICSourceEntry[] adjustEntries(ICSourceEntry entries[], boolean makeAbsolute, IProject project){ - if(entries == null || entries.length == 0) + public static ICSourceEntry[] adjustEntries(ICSourceEntry entries[], boolean makeAbsolute, IProject project) { + if (entries == null || entries.length == 0) return getDefaultSourceEntries(makeAbsolute, project); ICSourceEntry ei, ej; - LinkedHashMap> map = new LinkedHashMap>(); - for(int i = 0; i < entries.length; i++){ + LinkedHashMap> map = new LinkedHashMap<>(); + for (int i = 0; i < entries.length; i++) { ei = entries[i]; List list = null; - for(int j = 0; j < entries.length; j++){ + for (int j = 0; j < entries.length; j++) { ej = entries[j]; - if(ei == ej) + if (ei == ej) continue; IPath ejPath = new Path(ej.getName()); - if(!isExcluded(ejPath, ei)){ - if(list == null) - list = new ArrayList(); + if (!isExcluded(ejPath, ei)) { + if (list == null) + list = new ArrayList<>(); list.add(ejPath); } } map.put(ei, list); } - List resultList = new ArrayList(entries.length); - for(Iterator>> iter = map.entrySet().iterator(); iter.hasNext();){ + List resultList = new ArrayList<>(entries.length); + for (Iterator>> iter = map.entrySet().iterator(); iter.hasNext();) { Map.Entry> entry = iter.next(); List list = entry.getValue(); - if(list == null) + if (list == null) { resultList.add(entry.getKey()); - else { + } else { ICSourceEntry se = entry.getKey(); se = addExcludePaths(se, list, true); - if(se != null) + if (se != null) resultList.add(se); } } - if(makeAbsolute){ - if(project != null) + if (makeAbsolute) { + if (project != null) resultList = makeAbsolute(project, resultList); } else { resultList = makeRelative(project, resultList); @@ -978,62 +983,62 @@ public class CDataUtil { return resultArray; } - private static List makeRelative(IProject project, List list){ + private static List makeRelative(IProject project, List list) { int size = list.size(); - for(int i = 0; i < size; i++){ + for (int i = 0; i < size; i++) { list.set(i, makeRelative(project, list.get(i))); } return list; } - private static List makeAbsolute(IProject project, List list){ + private static List makeAbsolute(IProject project, List list) { int size = list.size(); - for(int i = 0; i < size; i++){ + for (int i = 0; i < size; i++) { list.set(i, makeAbsolute(project, list.get(i))); } return list; } - public static ICSourceEntry makeAbsolute(IProject project, ICSourceEntry entry){ + public static ICSourceEntry makeAbsolute(IProject project, ICSourceEntry entry) { return (ICSourceEntry)makeAbsolute(project, entry, true); } - public static ICSourceEntry makeRelative(IProject project, ICSourceEntry entry){ + public static ICSourceEntry makeRelative(IProject project, ICSourceEntry entry) { return (ICSourceEntry)makeRelative(project, entry, true); } - public static ICSourceEntry[] makeRelative(IProject project, ICSourceEntry[] entries){ + public static ICSourceEntry[] makeRelative(IProject project, ICSourceEntry[] entries) { return (ICSourceEntry[])makeRelative(project, entries, true); } - public static ICSourceEntry[] makeAbsolute(IProject project, ICSourceEntry[] entries){ + public static ICSourceEntry[] makeAbsolute(IProject project, ICSourceEntry[] entries) { return (ICSourceEntry[])makeAbsolute(project, entries, true); } - public static ICOutputEntry makeAbsolute(IProject project, ICOutputEntry entry){ + public static ICOutputEntry makeAbsolute(IProject project, ICOutputEntry entry) { return (ICOutputEntry)makeAbsolute(project, entry, true); } - public static ICOutputEntry makeRelative(IProject project, ICOutputEntry entry){ + public static ICOutputEntry makeRelative(IProject project, ICOutputEntry entry) { return (ICOutputEntry)makeRelative(project, entry, true); } - public static ICOutputEntry[] makeAbsolute(IProject project, ICOutputEntry[] entries){ + public static ICOutputEntry[] makeAbsolute(IProject project, ICOutputEntry[] entries) { return (ICOutputEntry[])makeAbsolute(project, entries, true); } - public static ICOutputEntry[] makeRelative(IProject project, ICOutputEntry[] entries){ + public static ICOutputEntry[] makeRelative(IProject project, ICOutputEntry[] entries) { return (ICOutputEntry[])makeRelative(project, entries, true); } - private static Collection removePrefix(IPath prefix, Collection paths, Collection result){ - if(result == null) - result = new ArrayList(paths.size()); - for(Iterator iter = paths.iterator(); iter.hasNext(); ){ + private static Collection removePrefix(IPath prefix, Collection paths, Collection result) { + if (result == null) + result = new ArrayList<>(paths.size()); + for (Iterator iter = paths.iterator(); iter.hasNext(); ) { IPath path = iter.next(); - if(prefix.isPrefixOf(path)) + if (prefix.isPrefixOf(path)) result.add(path.removeFirstSegments(prefix.segmentCount())); // else // result.add(path); @@ -1041,20 +1046,20 @@ public class CDataUtil { return result; } - public static ICSourceEntry addExcludePaths(ICSourceEntry entry, Collection paths, boolean removePrefix){ + public static ICSourceEntry addExcludePaths(ICSourceEntry entry, Collection paths, boolean removePrefix) { IPath entryPath = new Path(entry.getName()); IPath[] oldExclusions = entry.getExclusionPatterns(); // List newExList = new ArrayList(oldExclusions.length + paths.size()); - LinkedHashSet newSet = new LinkedHashSet(); - if(removePrefix){ + LinkedHashSet newSet = new LinkedHashSet<>(); + if (removePrefix) { removePrefix(entryPath, paths, newSet); } else { newSet.addAll(paths); } - for(Iterator iter = newSet.iterator(); iter.hasNext();){ + for (Iterator iter = newSet.iterator(); iter.hasNext();) { IPath path = iter.next(); - if(path.segmentCount() == 0) + if (path.segmentCount() == 0) return null; } @@ -1064,58 +1069,58 @@ public class CDataUtil { return new CSourceEntry(entry.getName(), newExclusions, entry.getFlags()); } - private static void sortEntries(IPath path, boolean byExclude, ICSourceEntry[] entries, List included, List excluded){ - for(int i = 0; i < entries.length; i++){ - if(byExclude ? isExcluded(path, entries[i]) : !isOnSourceEntry(path, entries[i])){ - if(excluded != null) + private static void sortEntries(IPath path, boolean byExclude, ICSourceEntry[] entries, List included, List excluded) { + for (int i = 0; i < entries.length; i++) { + if (byExclude ? isExcluded(path, entries[i]) : !isOnSourceEntry(path, entries[i])) { + if (excluded != null) excluded.add(entries[i]); } else { - if(included != null) + if (included != null) included.add(entries[i]); } } } - public static Map fillEntriesMapByNameKey(Map map, ICSettingEntry[] entries){ - if(map == null) - map = new LinkedHashMap(); + public static Map fillEntriesMapByNameKey(Map map, ICSettingEntry[] entries) { + if (map == null) + map = new LinkedHashMap<>(); - for(int i = 0; i < entries.length; i++){ + for (int i = 0; i < entries.length; i++) { ICSettingEntry entry = entries[i]; map.put(new EntryNameKey(entry), entry); } return map; } - public static Map fillEntriesMapByContentsKey(Map map, ICSettingEntry[] entries){ - if(map == null) - map = new LinkedHashMap(); + public static Map fillEntriesMapByContentsKey(Map map, ICSettingEntry[] entries) { + if (map == null) + map = new LinkedHashMap<>(); - for(int i = 0; i < entries.length; i++){ + for (int i = 0; i < entries.length; i++) { ICSettingEntry entry = entries[i]; map.put(new EntryContentsKey(entry), entry); } return map; } - public static boolean getBoolean(ICStorageElement el, String attr, boolean defaultValue){ - if(el != null){ + public static boolean getBoolean(ICStorageElement el, String attr, boolean defaultValue) { + if (el != null) { String tmp = el.getAttribute(attr); - if(tmp != null){ + if (tmp != null) { return Boolean.valueOf(tmp).booleanValue(); } } return defaultValue; } - public static void setBoolean(ICStorageElement el, String attr, boolean value){ + public static void setBoolean(ICStorageElement el, String attr, boolean value) { el.setAttribute(attr, Boolean.valueOf(value).toString()); } - public static int getInteger(ICStorageElement el, String attr, int defaultValue){ - if(el != null){ + public static int getInteger(ICStorageElement el, String attr, int defaultValue) { + if (el != null) { String tmp = el.getAttribute(attr); - if(tmp != null){ + if (tmp != null) { try { return Integer.parseInt(tmp); } catch (NumberFormatException e) { @@ -1125,12 +1130,12 @@ public class CDataUtil { return defaultValue; } - public static void setInteger(ICStorageElement el, String attr, int value){ + public static void setInteger(ICStorageElement el, String attr, int value) { el.setAttribute(attr, new Integer(value).toString()); } public static ICExclusionPatternPathEntry addRemoveExclusionsToEntry(ICExclusionPatternPathEntry entry, IPath[] paths, boolean add) throws IllegalArgumentException{ - if(paths == null || paths.length == 0) + if (paths == null || paths.length == 0) return entry; Set set = mergeRemovingDups(entry.getExclusionPatterns(), paths, add); @@ -1139,63 +1144,65 @@ public class CDataUtil { return (ICExclusionPatternPathEntry)createEntry(entry.getKind(), entry.getName(), null, exclusions, entry.getFlags()); } - private static Set mergeRemovingDups(IPath[] o1, IPath[] o2, boolean add){ - LinkedHashSet set = new LinkedHashSet(); + private static Set mergeRemovingDups(IPath[] o1, IPath[] o2, boolean add) { + LinkedHashSet set = new LinkedHashSet<>(); set.addAll(Arrays.asList(o1)); - if(add) + if (add) { set.addAll(Arrays.asList(o2)); - else + } else { set.removeAll(Arrays.asList(o2)); + } return set; } - public static ICExclusionPatternPathEntry makeAbsolute(IProject project, ICExclusionPatternPathEntry entry, boolean force){ - if(!entry.isValueWorkspacePath() && !force) + public static ICExclusionPatternPathEntry makeAbsolute(IProject project, ICExclusionPatternPathEntry entry, boolean force) { + if (!entry.isValueWorkspacePath() && !force) return entry; IPath path = new Path(entry.getName()); IPath projPath = project.getFullPath(); - if(!path.isAbsolute() || (force && !projPath.isPrefixOf(path))){ + if (!path.isAbsolute() || (force && !projPath.isPrefixOf(path))) { path = projPath.append(path).makeAbsolute(); - return (ICExclusionPatternPathEntry)CDataUtil.createEntry(entry.getKind(), path.toString(), null, entry.getExclusionPatterns(), entry.getFlags()); + return (ICExclusionPatternPathEntry) createEntry(entry.getKind(), path.toString(), null, entry.getExclusionPatterns(), entry.getFlags()); } return entry; } - public static ICExclusionPatternPathEntry makeRelative(IProject project, ICExclusionPatternPathEntry entry, boolean force){ - if(!entry.isValueWorkspacePath() && !force) + public static ICExclusionPatternPathEntry makeRelative(IProject project, ICExclusionPatternPathEntry entry, boolean force) { + if (!entry.isValueWorkspacePath() && !force) return entry; IPath path = new Path(entry.getName()); IPath projPath = project.getFullPath(); - if(path.isAbsolute()){ - if(projPath.isPrefixOf(path)) + if (path.isAbsolute()) { + if (projPath.isPrefixOf(path)) { path = path.removeFirstSegments(projPath.segmentCount()).makeRelative(); - else if (force) + } else if (force) { path = path.makeRelative(); - return (ICExclusionPatternPathEntry)CDataUtil.createEntry(entry.getKind(), path.toString(), null, entry.getExclusionPatterns(), entry.getFlags()); + } + return (ICExclusionPatternPathEntry) createEntry(entry.getKind(), path.toString(), null, entry.getExclusionPatterns(), entry.getFlags()); } return entry; } - public static ICExclusionPatternPathEntry[] makeRelative(IProject project, ICExclusionPatternPathEntry[] entries, boolean force){ - if(entries == null) + public static ICExclusionPatternPathEntry[] makeRelative(IProject project, ICExclusionPatternPathEntry[] entries, boolean force) { + if (entries == null) return null; ICExclusionPatternPathEntry[] relEntries = (ICExclusionPatternPathEntry[])Array.newInstance(entries.getClass().getComponentType(), entries.length); - for(int i = 0; i < entries.length; i++){ + for (int i = 0; i < entries.length; i++) { relEntries[i] = makeRelative(project, entries[i], force); } return relEntries; } - public static ICExclusionPatternPathEntry[] makeAbsolute(IProject project, ICExclusionPatternPathEntry[] entries, boolean force){ - if(entries == null) + public static ICExclusionPatternPathEntry[] makeAbsolute(IProject project, ICExclusionPatternPathEntry[] entries, boolean force) { + if (entries == null) return null; ICExclusionPatternPathEntry[] relEntries = (ICExclusionPatternPathEntry[])Array.newInstance(entries.getClass().getComponentType(), entries.length); - for(int i = 0; i < entries.length; i++){ + for (int i = 0; i < entries.length; i++) { relEntries[i] = makeAbsolute(project, entries[i], force); } return relEntries; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOMIndexer.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOMIndexer.java index d930ac474a4..d902f816b83 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOMIndexer.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/IPDOMIndexer.java @@ -33,8 +33,7 @@ public interface IPDOMIndexer { public ICProject getProject(); /** - * Return the unique ID of type of this indexer - * @return the unique ID of type of this indexer + * Returns the unique ID of type of this indexer */ public String getID(); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTComment.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTComment.java index edd4e20257b..6a5e11f883f 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTComment.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/core/dom/ast/IASTComment.java @@ -18,29 +18,23 @@ package org.eclipse.cdt.core.dom.ast; * @noimplement This interface is not intended to be implemented by clients. */ public interface IASTComment extends IASTNode { - /** - * @since 5.4 - */ + /** @since 5.4 */ public final IASTComment[] EMPTY_COMMENT_ARRAY = {}; /** - * Set the comment. + * Sets the comment. * - * @param comment + * @param comment the text of the comment */ public void setComment(char[] comment); /** - * Return a char array representation of the comment. - * - * @return char array representation of the comment + * Returns a char array representation of the comment. */ public char[] getComment(); /** - * Return true if this is a blockcomment. - * - * @return true if this is a blockcomment + * Returns true if this is a block comment. */ public boolean isBlockComment(); } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTTranslationUnit.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTTranslationUnit.java index e783cb96070..f89158eec9a 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTTranslationUnit.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/dom/parser/ASTTranslationUnit.java @@ -320,7 +320,7 @@ public abstract class ASTTranslationUnit extends ASTNode implements IASTTranslat if (fLocationResolver != null) { return fLocationResolver.getComments(); } - return new IASTComment[0]; + return IASTComment.EMPTY_COMMENT_ARRAY; } @Override diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/CIndex.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/CIndex.java index e5abb567a16..70272400702 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/CIndex.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/CIndex.java @@ -104,7 +104,7 @@ public class CIndex implements IIndex { if (SPECIALCASE_SINGLES && fFragments.length == 1) { return fFragments[0].findBindings(patterns, isFullyQualified, filter, monitor); } else { - List result = new ArrayList(); + List result = new ArrayList<>(); ILinkage[] linkages = Linkage.getIndexerLinkages(); for (ILinkage linkage : linkages) { if (filter.acceptLinkage(linkage)) { @@ -134,7 +134,7 @@ public class CIndex implements IIndex { if (SPECIALCASE_SINGLES && fFragments.length == 1) { return fFragments[0].findMacroContainers(pattern, filter, monitor); } else { - List result = new ArrayList(); + List result = new ArrayList<>(); ILinkage[] linkages = Linkage.getIndexerLinkages(); for (ILinkage linkage : linkages) { if (filter.acceptLinkage(linkage)) { @@ -160,14 +160,14 @@ public class CIndex implements IIndex { @Override public IIndexName[] findNames(IBinding binding, int flags) throws CoreException { - ArrayList result= new ArrayList(); + ArrayList result= new ArrayList<>(); if (binding instanceof ICPPUsingDeclaration) { IBinding[] bindings= ((ICPPUsingDeclaration) binding).getDelegates(); if (bindings == null || bindings.length == 0) { - return new IIndexName[0]; + return IIndexName.EMPTY_ARRAY; } if (bindings.length > 1) { - ArrayList multi= new ArrayList(); + ArrayList multi= new ArrayList<>(); for (IBinding b : bindings) { multi.addAll(Arrays.asList(findNames(b, flags))); } @@ -182,7 +182,7 @@ public class CIndex implements IIndex { // Read only fragments can be superseded by what the indexer writes into // a writable fragment. Therefore names from a read-only fragment are // ignored if there is a match in a writable fragment. - HashSet encounteredNames = new HashSet(); + HashSet encounteredNames = new HashSet<>(); for (IIndexFragment fragment : fFragments) { if (fragment instanceof IWritableIndexFragment) { final IIndexFragmentName[] names = fragment.findNames(binding, flags); @@ -250,8 +250,8 @@ public class CIndex implements IIndex { if (location == null) { return IIndexFile.EMPTY_FILE_ARRAY; } - Set handled = new HashSet(); - ArrayList result= new ArrayList(); + Set handled = new HashSet<>(); + ArrayList result= new ArrayList<>(); for (IIndexFragment fragment : fFragments) { IIndexFragmentFile[] candidates= fragment.getFiles(linkageID, location); for (IIndexFragmentFile candidate : candidates) { @@ -274,8 +274,8 @@ public class CIndex implements IIndex { if (location == null) { return IIndexFile.EMPTY_FILE_ARRAY; } - Set keys = new HashSet(); - ArrayList result= new ArrayList(); + Set keys = new HashSet<>(); + ArrayList result= new ArrayList<>(); for (IIndexFragment fragment : fFragments) { IIndexFragmentFile[] candidates= fragment.getFiles(location); for (IIndexFragmentFile candidate : candidates) { @@ -313,7 +313,7 @@ public class CIndex implements IIndex { @Override public IIndexInclude[] findIncludedBy(IIndexFile file, int depth) throws CoreException { - List result= new ArrayList(); + List result= new ArrayList<>(); findIncludedBy(file.getLinkageID(), Collections.singletonList(file), result, depth, new HashSet()); return result.toArray(new IIndexInclude[result.size()]); @@ -354,8 +354,8 @@ public class CIndex implements IIndex { @Override public IIndexInclude[] findIncludes(IIndexFile file, int depth) throws CoreException { - List result= new ArrayList(); - findIncludes(Collections.singletonList(file), result, depth, new HashSet()); + List result= new ArrayList<>(); + findIncludes(Collections.singletonList(file), result, depth, new HashSet<>()); return result.toArray(new IIndexInclude[result.size()]); } @@ -454,7 +454,7 @@ public class CIndex implements IIndex { if (monitor == null) { monitor= new NullProgressMonitor(); } - List result = new ArrayList(); + List result = new ArrayList<>(); ILinkage[] linkages = Linkage.getIndexerLinkages(); monitor.beginTask(Messages.CIndex_FindBindingsTask_label, fFragments.length * linkages.length); for (ILinkage linkage : linkages) { @@ -529,7 +529,7 @@ public class CIndex implements IIndex { } public IIndexFragmentBinding[] findEquivalentBindings(IBinding binding) throws CoreException { - List result = new ArrayList(); + List result = new ArrayList<>(); for (IIndexFragment fragment : fFragments) { IIndexFragmentBinding adapted = fragment.adaptBinding(binding); if (adapted != null) { @@ -583,7 +583,7 @@ public class CIndex implements IIndex { if (SPECIALCASE_SINGLES && fFragments.length == 1) { return fFragments[0].findBindingsForPrefix(prefix, filescope, filter, monitor); } else { - List result = new ArrayList(); + List result = new ArrayList<>(); ILinkage[] linkages = Linkage.getIndexerLinkages(); for (ILinkage linkage : linkages) { if (filter.acceptLinkage(linkage)) { @@ -613,7 +613,7 @@ public class CIndex implements IIndex { if (SPECIALCASE_SINGLES && fFragments.length == 1) { return fFragments[0].findBindingsForContentAssist(prefix, filescope, filter, monitor); } else { - List result = new ArrayList(); + List result = new ArrayList<>(); ILinkage[] linkages = Linkage.getIndexerLinkages(); for (ILinkage linkage : linkages) { if (filter.acceptLinkage(linkage)) { @@ -643,7 +643,7 @@ public class CIndex implements IIndex { if (SPECIALCASE_SINGLES && fFragments.length == 1) { return fFragments[0].findBindings(name, filescope, filter, monitor); } else { - List result = new ArrayList(); + List result = new ArrayList<>(); ILinkage[] linkages = Linkage.getIndexerLinkages(); for (ILinkage linkage : linkages) { if (filter.acceptLinkage(linkage)) { @@ -685,11 +685,11 @@ public class CIndex implements IIndex { if (monitor == null) { monitor= new NullProgressMonitor(); } - List result = new ArrayList(); - HashSet handledIFLs= new HashSet(); + List result = new ArrayList<>(); + HashSet handledIFLs= new HashSet<>(); monitor.beginTask(Messages.CIndex_FindBindingsTask_label, fFragments.length); for (IIndexFragment fragment : fFragments) { - HashSet allowedFiles= new HashSet(); + HashSet allowedFiles= new HashSet<>(); try { IIndexMacro[] macros= fragment.findMacros(name, isPrefix, caseSensitive, filter, new SubProgressMonitor(monitor, 1)); @@ -747,7 +747,7 @@ public class CIndex implements IIndex { @Override public IIndexFile[] getAllFiles() throws CoreException { - HashMap result= new HashMap(); + HashMap result= new HashMap<>(); for (IIndexFragment fragment : fFragments) { for (IIndexFragmentFile file : fragment.getAllFiles()) { if (file.hasContent()) { @@ -760,7 +760,7 @@ public class CIndex implements IIndex { @Override public IIndexFile[] getDefectiveFiles() throws CoreException { - HashMap result= new HashMap(); + HashMap result= new HashMap<>(); for (IIndexFragment fragment : fFragments) { for (IIndexFragmentFile file : fragment.getDefectiveFiles()) { if (file.hasContent()) { @@ -773,7 +773,7 @@ public class CIndex implements IIndex { @Override public IIndexFile[] getFilesWithUnresolvedIncludes() throws CoreException { - HashMap result= new HashMap(); + HashMap result= new HashMap<>(); for (IIndexFragment fragment : fFragments) { for (IIndexFragmentFile file : fragment.getFilesWithUnresolvedIncludes()) { if (file.hasContent()) { diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/IIndexFragmentFile.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/IIndexFragmentFile.java index 0577e408b1b..cb4477ea4e3 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/IIndexFragmentFile.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/index/IIndexFragmentFile.java @@ -40,19 +40,19 @@ public interface IIndexFragmentFile extends IIndexFile { /** * Returns the hash-code computed by combining the file size and the file encoding. - * @return hashcode a hash-code or 0 if it is unknown. + * @return a hash-code or {@code 0} if it is unknown. */ int getSizeAndEncodingHashcode() throws CoreException; /** * Sets the hash-code computed by combining the file size and the file encoding. - * @param hashcode a hash-code or 0 if it is unknown. + * @param hashcode a hash-code or {@code 0} if it is unknown. */ void setSizeAndEncodingHashcode(int hashcode) throws CoreException; /** - * Sets the flag that determines whether the file is a header with #pragma once statement - * or an include guard, or it is a source file and parsed only once because of that. + * Sets the flag that determines whether the file is a header with {@code #pragma once} + * statement or an include guard, or it is a source file and parsed only once because of that. */ void setPragmaOnceSemantics(boolean value) throws CoreException; @@ -85,5 +85,4 @@ public interface IIndexFragmentFile extends IIndexFile { * The file 'source' must belong to the same fragment as this file. */ void transferContext(IIndexFragmentFile source) throws CoreException; - } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/AbstractIndexerTask.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/AbstractIndexerTask.java index f61986b6a1e..54899757905 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/AbstractIndexerTask.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/AbstractIndexerTask.java @@ -1057,16 +1057,12 @@ public abstract class AbstractIndexerTask extends PDOMWriter { writeToIndex(lang.getLinkageID(), ast, codeReader, ctx, pm); resultCacheCleared = true; // The cache was cleared while writing to the index. } - } catch (CoreException e) { - th= e; } catch (RuntimeException e) { final Throwable cause = e.getCause(); if (cause instanceof DependsOnOutdatedFileException) return (DependsOnOutdatedFileException) cause; th= e; - } catch (StackOverflowError e) { - th= e; - } catch (AssertionError e) { + } catch (StackOverflowError | CoreException | AssertionError e) { th= e; } catch (OutOfMemoryError e) { if (--fSwallowOutOfMemoryError < 0) @@ -1247,16 +1243,10 @@ public abstract class AbstractIndexerTask extends PDOMWriter { if (storageLinkageID != ILinkage.NO_LINKAGE_ID) addSymbols(data, storageLinkageID, ctx, fTodoTaskUpdater, pm); } - } catch (CoreException e) { + } catch (CoreException | RuntimeException | Error e) { // Avoid parsing files again, that caused an exception to be thrown. withdrawRequests(linkageID, fileKeys); throw e; - } catch (RuntimeException e) { - withdrawRequests(linkageID, fileKeys); - throw e; - } catch (Error e) { - withdrawRequests(linkageID, fileKeys); - throw e; } } diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/ITodoTaskUpdater.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/ITodoTaskUpdater.java index 2d0cf36f5b8..e8897c5eea9 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/ITodoTaskUpdater.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/ITodoTaskUpdater.java @@ -8,7 +8,6 @@ * Contributors: * Sergey Prigogin (Google) - initial API and implementation *******************************************************************************/ - package org.eclipse.cdt.internal.core.pdom; import org.eclipse.cdt.core.dom.ast.IASTComment; diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java index 98c5b9bda63..9458226a88b 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/PDOMWriter.java @@ -135,26 +135,27 @@ abstract public class PDOMWriter implements IPDOMASTProcessor { public static int SKIP_NO_REFERENCES= 0; private static class Symbols { - final ArrayList fNames= new ArrayList(); - final ArrayList fMacros= new ArrayList(); - final ArrayList fIncludes= new ArrayList(); + final ArrayList fNames= new ArrayList<>(); + final ArrayList fMacros= new ArrayList<>(); + final ArrayList fIncludes= new ArrayList<>(); } protected static class Data implements IIndexSymbols { final IASTTranslationUnit fAST; final FileInAST[] fSelectedFiles; final IWritableIndex fIndex; - final Map fSymbolMap = new HashMap(); - final Set fContextIncludes = new HashSet(); - final List fStati= new ArrayList(); + final Map fSymbolMap = new HashMap<>(); + final Set fContextIncludes = new HashSet<>(); + final List fStatuses= new ArrayList<>(); public Data(IASTTranslationUnit ast, FileInAST[] selectedFiles, IWritableIndex index) { fAST= ast; fSelectedFiles= selectedFiles; fIndex= index; - for(FileInAST file : selectedFiles) + for (FileInAST file : selectedFiles) { fSymbolMap.put(file.includeStatement, new Symbols()); + } } @Override @@ -175,7 +176,7 @@ abstract public class PDOMWriter implements IPDOMASTProcessor { public void add(IASTPreprocessorIncludeStatement owner, IASTName name, IASTName caller) { Symbols lists= fSymbolMap.get(owner); if (lists != null) - lists.fNames.add(new IASTName[]{ name, caller }); + lists.fNames.add(new IASTName[] { name, caller }); } @Override @@ -272,14 +273,14 @@ abstract public class PDOMWriter implements IPDOMASTProcessor { // Tasks update. if (taskUpdater != null) { - Set locations= new HashSet(); + Set locations= new HashSet<>(); for (FileInAST file : data.fSelectedFiles) { locations.add(file.fileContentKey.getLocation()); } taskUpdater.updateTasks(data.fAST.getComments(), locations.toArray(new IIndexFileLocation[locations.size()])); } - if (!data.fStati.isEmpty()) { - List stati = data.fStati; + if (!data.fStatuses.isEmpty()) { + List stati = data.fStatuses; String path= null; if (data.fSelectedFiles.length > 0) { path= data.fSelectedFiles[data.fSelectedFiles.length - 1].fileContentKey.getLocation().getURI().getPath(); @@ -352,7 +353,7 @@ abstract public class PDOMWriter implements IPDOMASTProcessor { lock.release(); } if (th != null) { - data.fStati.add(createStatus(NLS.bind(Messages.PDOMWriter_errorWhileParsing, + data.fStatuses.add(createStatus(NLS.bind(Messages.PDOMWriter_errorWhileParsing, fileInAST.fileContentKey.getLocation().getURI().getPath()), th)); } fStatistics.fAddToIndexTime += lock.getCumulativeLockTime(); @@ -414,7 +415,7 @@ abstract public class PDOMWriter implements IPDOMASTProcessor { } if (th != null) { if (!reported) { - data.fStati.add(CCorePlugin.createStatus(NLS.bind(Messages.PDOMWriter_errorResolvingName, + data.fStatuses.add(CCorePlugin.createStatus(NLS.bind(Messages.PDOMWriter_errorResolvingName, name.toString(), file.fileContentKey.getLocation().getURI().getPath()), th)); } reported= true; @@ -593,7 +594,7 @@ abstract public class PDOMWriter implements IPDOMASTProcessor { } } - List includeInfos= new ArrayList(); + List includeInfos= new ArrayList<>(); for (int i= 0; i < lists.fIncludes.size(); i++) { final IASTPreprocessorIncludeStatement stmt = lists.fIncludes.get(i); if (!stmt.isResolved()) { diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/db/ShortString.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/db/ShortString.java index ca7978cefd7..fe096f3c211 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/db/ShortString.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/db/ShortString.java @@ -40,7 +40,7 @@ public class ShortString implements IString { final int n = chars.length; this.db = db; - this.record = db.malloc(CHARS + (useBytes ? n : 2*n)); + this.record = db.malloc(CHARS + (useBytes ? n : 2 * n)); Chunk chunk = db.getChunk(record); chunk.putInt(record + LENGTH, useBytes ? -n : n); long p = record + CHARS; @@ -134,7 +134,7 @@ public class ShortString implements IString { chars = getChars(); final int len = chars.length; for (int i = 0; i < len; i++) { - h = 31*h + chars[i]; + h = 31 * h + chars[i]; } } catch (CoreException e) { } @@ -145,7 +145,7 @@ public class ShortString implements IString { public static int compare(final char[] chars, char[] other, boolean caseSensitive) { final int n = Math.min(chars.length, other.length); - for (int i=0; i union = new HashSet(added.length + changed.length); + HashSet union = new HashSet<>(added.length + changed.length); union.addAll(Arrays.asList(added)); union.addAll(Arrays.asList(changed)); final ITranslationUnit[] result = union.toArray(new ITranslationUnit[union.size()]); @@ -166,7 +167,7 @@ public abstract class PDOMIndexerTask extends AbstractIndexerTask implements IPD private Set getStringSet(String key) { String prefSetting = getIndexer().getProperty(key); if (prefSetting != null && !prefSetting.isEmpty()) { - return new HashSet(Arrays.asList(prefSetting.split(","))); //$NON-NLS-1$ + return new HashSet<>(Arrays.asList(prefSetting.split(","))); //$NON-NLS-1$ } return Collections.emptySet(); @@ -249,7 +250,7 @@ public abstract class PDOMIndexerTask extends AbstractIndexerTask implements IPD // tracing if (checkDebugOption(IPDOMIndexerTask.TRACE_STATISTICS, TRUE)) { - String ident= " "; //$NON-NLS-1$ + String indent= " "; //$NON-NLS-1$ final long totalTime = System.currentTimeMillis() - start; final IndexerProgress info= getProgressInformation(); final int sum= fStatistics.fDeclarationCount + fStatistics.fReferenceCount + fStatistics.fProblemBindingCount; @@ -265,7 +266,7 @@ public abstract class PDOMIndexerTask extends AbstractIndexerTask implements IPD boolean skipImplRefs= skipRefs || checkProperty(IndexerPreferences.KEY_SKIP_IMPLICIT_REFERENCES); boolean skipTypeRefs= skipRefs || checkProperty(IndexerPreferences.KEY_SKIP_TYPE_REFERENCES); boolean skipMacroRefs= skipRefs || checkProperty(IndexerPreferences.KEY_SKIP_MACRO_REFERENCES); - System.out.println(ident + " Options: " //$NON-NLS-1$ + System.out.println(indent + " Options: " //$NON-NLS-1$ + "indexer='" + kind //$NON-NLS-1$ + "', parseAllFiles=" + indexFilesWithoutConfiguration() //$NON-NLS-1$ + ", unusedHeaders=" + getIndexHeadersWithoutContext() //$NON-NLS-1$ @@ -274,25 +275,25 @@ public abstract class PDOMIndexerTask extends AbstractIndexerTask implements IPD + ", skipTypeReferences=" + skipTypeRefs //$NON-NLS-1$ + ", skipMacroReferences=" + skipMacroRefs //$NON-NLS-1$ + "."); //$NON-NLS-1$ - System.out.println(ident + " Database: " + dbSize + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ - System.out.println(ident + " Timings: " //$NON-NLS-1$ + System.out.println(indent + " Database: " + dbSize + " bytes"); //$NON-NLS-1$ //$NON-NLS-2$ + System.out.println(indent + " Timings: " //$NON-NLS-1$ + totalTime + " total, " //$NON-NLS-1$ + fStatistics.fParsingTime + " parser, " //$NON-NLS-1$ + fStatistics.fResolutionTime + " resolution, " //$NON-NLS-1$ + fStatistics.fAddToIndexTime + " index update."); //$NON-NLS-1$ - System.out.println(ident + " Errors: " //$NON-NLS-1$ + System.out.println(indent + " Errors: " //$NON-NLS-1$ + fStatistics.fErrorCount + " internal, " //$NON-NLS-1$ + fStatistics.fUnresolvedIncludesCount + " include, " //$NON-NLS-1$ + fStatistics.fPreprocessorProblemCount + " scanner, " //$NON-NLS-1$ + fStatistics.fSyntaxProblemsCount + " syntax errors."); //$NON-NLS-1$ if (fStatistics.fTooManyTokensCount > 0) - System.out.println(ident + " Tokens: " //$NON-NLS-1$ + System.out.println(indent + " Tokens: " //$NON-NLS-1$ + fStatistics.fTooManyTokensCount + " TUs with too many tokens."); //$NON-NLS-1$ NumberFormat nfPercent= NumberFormat.getPercentInstance(); nfPercent.setMaximumFractionDigits(2); nfPercent.setMinimumFractionDigits(2); - System.out.println(ident + " Names: " //$NON-NLS-1$ + System.out.println(indent + " Names: " //$NON-NLS-1$ + fStatistics.fDeclarationCount + " declarations, " //$NON-NLS-1$ + fStatistics.fReferenceCount + " references, " //$NON-NLS-1$ + fStatistics.fProblemBindingCount + "(" + nfPercent.format(problemPct) + ") unresolved."); //$NON-NLS-1$ //$NON-NLS-2$ @@ -301,7 +302,7 @@ public abstract class PDOMIndexerTask extends AbstractIndexerTask implements IPD long hits= index.getCacheHits(); long tries= misses + hits; double missPct= tries == 0 ? 0.0 : (double) misses / (double) tries; - System.out.println(ident + " Cache[" //$NON-NLS-1$ + System.out.println(indent + " Cache[" //$NON-NLS-1$ + ChunkCache.getSharedInstance().getMaxSize() / 1024 / 1024 + "MB]: " + //$NON-NLS-1$ + hits + " hits, " //$NON-NLS-1$ + misses + "(" + nfPercent.format(missPct) + ") misses."); //$NON-NLS-1$ //$NON-NLS-2$ diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/PDOMRebuildTask.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/PDOMRebuildTask.java index 1d3b17ff230..f1213fc6a31 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/PDOMRebuildTask.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/PDOMRebuildTask.java @@ -37,7 +37,7 @@ import org.eclipse.osgi.util.NLS; */ public class PDOMRebuildTask implements IPDOMIndexerTask { protected static final String TRUE= String.valueOf(true); - protected static final ITranslationUnit[] NO_TUS = new ITranslationUnit[0]; + protected static final ITranslationUnit[] NO_TUS = {}; private final IPDOMIndexer fIndexer; private final IndexerProgress fProgress; @@ -78,7 +78,7 @@ public class PDOMRebuildTask implements IPDOMIndexerTask { createDelegate(cproject, monitor); } } - // remove task-tags. + // Remove task-tags. TodoTaskUpdater.removeTasksFor(project); } catch (CoreException e) { CCorePlugin.log(NLS.bind(Messages.PDOMRebuildTask_0, cproject.getElementName() ), e); @@ -112,7 +112,7 @@ public class PDOMRebuildTask implements IPDOMIndexerTask { boolean allFiles = TRUE.equals(fIndexer.getProperty(IndexerPreferences.KEY_INDEX_UNUSED_HEADERS_WITH_DEFAULT_LANG)) || TRUE.equals(fIndexer.getProperty(IndexerPreferences.KEY_INDEX_UNUSED_HEADERS_WITH_ALTERNATE_LANG)); - List sources= new ArrayList(); + List sources= new ArrayList<>(); List headers= allFiles ? sources : null; TranslationUnitCollector collector= new TranslationUnitCollector(sources, headers, monitor); project.accept(collector); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/TodoTaskParser.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/TodoTaskParser.java index 110bd4fa561..7ccdfaf19c8 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/TodoTaskParser.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/TodoTaskParser.java @@ -75,8 +75,7 @@ public class TodoTaskParser { return tasks.toArray(new Task[tasks.size()]); } - private void parse(char[] comment, String filename, int offset, int lineNumber, - List tasks) { + private void parse(char[] comment, String filename, int offset, int lineNumber, List tasks) { int commentLength = comment.length; int foundTaskIndex = tasks.size(); diff --git a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/TodoTaskUpdater.java b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/TodoTaskUpdater.java index 07099d456f2..d56cb04960d 100644 --- a/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/TodoTaskUpdater.java +++ b/core/org.eclipse.cdt.core/parser/org/eclipse/cdt/internal/core/pdom/indexer/TodoTaskUpdater.java @@ -9,7 +9,6 @@ * Sergey Prigogin (Google) - initial API and implementation * Markus Schorn (Wind River Systems) *******************************************************************************/ - package org.eclipse.cdt.internal.core.pdom.indexer; import java.util.ArrayList; @@ -100,12 +99,14 @@ public class TodoTaskUpdater implements ITodoTaskUpdater { class TaskList { IFile fFile; List fTasks; + public TaskList(IFile file) { fFile= file; } + public void add(Task task) { if (fTasks == null) { - fTasks= new ArrayList(); + fTasks= new ArrayList<>(); } fTasks.add(task); } @@ -113,9 +114,9 @@ public class TodoTaskUpdater implements ITodoTaskUpdater { final IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); - // first collect all valid file-locations - final Map pathToTaskList= new HashMap(); - final Set projects= new HashSet(); + // First collect all valid file-locations. + final Map pathToTaskList= new HashMap<>(); + final Set projects= new HashSet<>(); for (final IIndexFileLocation indexFileLocation : filesToUpdate) { final String filepath = indexFileLocation.getFullPath(); if (filepath != null) { @@ -137,7 +138,7 @@ public class TodoTaskUpdater implements ITodoTaskUpdater { } } - // run this in a job in order not to block the indexer (bug 210730). + // Update markers in a job in order not to block the indexer (bug 210730). if (!pathToTaskList.isEmpty()) { WorkspaceJob job= new WorkspaceJob(Messages.TodoTaskUpdater_UpdateJob) { @Override @@ -174,8 +175,7 @@ public class TodoTaskUpdater implements ITodoTaskUpdater { private void applyTask(Task task, IResource resource) throws CoreException { IMarker marker = resource.createMarker(ICModelMarker.TASK_MARKER); - String description = NLS.bind(Messages.TodoTaskUpdater_taskFormat, - task.getTag(), task.getMessage()); + String description = NLS.bind(Messages.TodoTaskUpdater_taskFormat, task.getTag(), task.getMessage()); marker.setAttributes( TASK_MARKER_ATTRIBUTE_NAMES, new Object[] { @@ -203,7 +203,7 @@ public class TodoTaskUpdater implements ITodoTaskUpdater { return; } - // run this in a job in order not to block the indexer (bug 210730). + // Delete markers in a job in order not to block the indexer (bug 210730). WorkspaceJob job= new WorkspaceJob(Messages.TodoTaskUpdater_DeleteJob) { @Override public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException { diff --git a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/includes/IncludesTestBase.java b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/includes/IncludesTestBase.java index e4594327976..05a0131d8b3 100644 --- a/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/includes/IncludesTestBase.java +++ b/core/org.eclipse.cdt.ui.tests/ui/org/eclipse/cdt/ui/tests/refactoring/includes/IncludesTestBase.java @@ -64,7 +64,7 @@ public abstract class IncludesTestBase extends BaseTestCase { protected TestSourceFile selectedFile; private StringBuilder[] testData; private boolean cpp = true; - private final Set testFiles = new LinkedHashSet(); + private final Set testFiles = new LinkedHashSet<>(); protected IncludesTestBase() { super(); diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/HeaderSubstitutor.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/HeaderSubstitutor.java index bb69d62520d..7500f189e8f 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/HeaderSubstitutor.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/HeaderSubstitutor.java @@ -107,7 +107,7 @@ public class HeaderSubstitutor { IncludeInfo includeInfo = fContext.getIncludeForHeaderFile(path); if (includeInfo == null) return path; - List candidates = new ArrayList(); + List candidates = new ArrayList<>(); candidates.add(includeInfo); IncludeMap[] maps = fIncludeMaps; for (IncludeMap map : maps) { @@ -150,8 +150,8 @@ public class HeaderSubstitutor { public IPath getPreferredRepresentativeHeaderByHeuristic(InclusionRequest request) { Set indexFiles = request.getDeclaringFiles().keySet(); String symbolName = request.getBinding().getName(); - ArrayDeque front = new ArrayDeque(); - HashSet processed = new HashSet(); + ArrayDeque front = new ArrayDeque<>(); + HashSet processed = new HashSet<>(); try { // Look for headers without an extension and a matching name. diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/IncludeCreationContext.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/IncludeCreationContext.java index 5b895abbd05..24bd35a4f25 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/IncludeCreationContext.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/IncludeCreationContext.java @@ -42,9 +42,9 @@ public class IncludeCreationContext extends InclusionContext { public IncludeCreationContext(ITranslationUnit tu, IIndex index) { super(tu); fIndex = index; - fHeadersToInclude = new HashSet(); - fHeadersAlreadyIncluded = new HashSet(); - fHeadersIncludedPreviously = new HashSet(); + fHeadersToInclude = new HashSet<>(); + fHeadersAlreadyIncluded = new HashSet<>(); + fHeadersIncludedPreviously = new HashSet<>(); } public String getSourceContents() { @@ -67,7 +67,7 @@ public class IncludeCreationContext extends InclusionContext { */ public void removeExportedHeaders() throws CoreException { // Index files keyed by their absolute paths. - Map filesByPath = new HashMap(); + Map filesByPath = new HashMap<>(); for (IIndexFile file : fIndex.getAllFiles()) { IPath path = getPath(file); filesByPath.put(path, file); @@ -79,12 +79,12 @@ public class IncludeCreationContext extends InclusionContext { private void removeExportedHeaders(Set exportingHeaders, Map filesByPath) throws CoreException { - Set exportedHeaders = new HashSet(); + Set exportedHeaders = new HashSet<>(); for (IPath path : exportingHeaders) { if (!exportedHeaders.contains(path)) { IIndexFile file = filesByPath.get(path); if (file != null) { // file can be null if the header was not indexed. - ArrayDeque queue = new ArrayDeque(); + ArrayDeque queue = new ArrayDeque<>(); queue.add(file); while ((file = queue.pollFirst()) != null) { for (IIndexInclude include : file.getIncludes()) { diff --git a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/IncludeMap.java b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/IncludeMap.java index 1e01bad6560..44ad5dab870 100644 --- a/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/IncludeMap.java +++ b/core/org.eclipse.cdt.ui/src/org/eclipse/cdt/internal/ui/refactoring/includes/IncludeMap.java @@ -39,7 +39,7 @@ public class IncludeMap { public IncludeMap(boolean unconditionalSubstitution) { this.unconditionalSubstitution = unconditionalSubstitution; - this.map = new LinkedHashMap>(); + this.map = new LinkedHashMap<>(); } /** @@ -51,7 +51,7 @@ public class IncludeMap { if (keysAndValues.length % 2 != 0) throw new IllegalArgumentException("More keys than values"); //$NON-NLS-1$ this.unconditionalSubstitution = unconditionalSubstitution; - this.map = new LinkedHashMap>(keysAndValues.length / 2); + this.map = new LinkedHashMap<>(keysAndValues.length / 2); for (int i = 0; i < keysAndValues.length;) { String key = keysAndValues[i++]; addMapping(key, keysAndValues[i++]); @@ -60,7 +60,7 @@ public class IncludeMap { public IncludeMap(IncludeMap other) { this.unconditionalSubstitution = other.unconditionalSubstitution; - this.map = new LinkedHashMap>(other.map.size()); + this.map = new LinkedHashMap<>(other.map.size()); addAllMappings(other); } @@ -75,7 +75,7 @@ public class IncludeMap { return; // Don't allow mapping to itself. List list = map.get(from); if (list == null) { - list = new ArrayList(2); + list = new ArrayList<>(2); map.put(from, list); } list.add(to); @@ -158,7 +158,7 @@ public class IncludeMap { * Writes the map to a memento. The {@link #isUnconditionalSubstitution()} flag is not written. */ public void saveToMemento(IMemento memento) { - List keys = new ArrayList(map.keySet()); + List keys = new ArrayList<>(map.keySet()); Collections.sort(keys); for (IncludeInfo key : keys) { for (IncludeInfo value : map.get(key)) { @@ -189,7 +189,7 @@ public class IncludeMap { List otherTargets = entry.getValue(); List targets = map.get(source); if (targets == null) { - targets = new ArrayList(otherTargets); + targets = new ArrayList<>(otherTargets); map.put(source, targets); } else { targets.addAll(otherTargets); @@ -201,12 +201,12 @@ public class IncludeMap { for (Entry> entry : map.entrySet()) { IncludeInfo source = entry.getKey(); List targets = entry.getValue(); - ArrayDeque queue = new ArrayDeque(targets); + ArrayDeque queue = new ArrayDeque<>(targets); targets.clear(); - HashSet processed = new HashSet(); + HashSet processed = new HashSet<>(); if (!unconditionalSubstitution) processed.add(source); // Don't allow mapping to itself. - HashSet seenTargets = new HashSet(); + HashSet seenTargets = new HashSet<>(); IncludeInfo target; queueLoop: while ((target = queue.pollFirst()) != null) { if (processed.contains(target)) @@ -263,7 +263,7 @@ public class IncludeMap { public String toString() { StringBuilder buf = new StringBuilder(); buf.append("upconditionalSubstitution = ").append(unconditionalSubstitution); //$NON-NLS-1$ - ArrayList sources = new ArrayList(map.keySet()); + ArrayList sources = new ArrayList<>(map.keySet()); Collections.sort(sources); for (IncludeInfo source : sources) { buf.append('\n');