Reports for loops which iterate over collections or arrays, and can be replaced with an enhanced for loop (i.e. the foreach iteration syntax).
Signed-off-by: Lars Grefer <eclipse@larsgrefer.de>
private List<String> getConfigFilesList(String[] configFiles) {
List<String> configs = new ArrayList<String>();
- for (int i = 0; i < configFiles.length; i++) {
- if (configFiles[i].endsWith(BuildConfigManager.CONFIG_FILE_SUFFIX)) {
- configs.add(configFiles[i]);
+ for (String configFile : configFiles) {
+ if (configFile.endsWith(BuildConfigManager.CONFIG_FILE_SUFFIX)) {
+ configs.add(configFile);
}
}
return configs;
return false;
}
int numConfigFiles = 0;
- for (int i = 0; i < args.length; i++) {
- if ((null != args[i]) && args[i].endsWith(".lst")) {
+ for (String arg : args) {
+ if ((null != arg) && arg.endsWith(".lst")) {
numConfigFiles++;
}
}
classpath.append(userPath);
}
List<File> outputDirs = getOutputLocationManager().getAllOutputLocations();
- for (Iterator<File> iterator = outputDirs.iterator(); iterator.hasNext();) {
- File dir = (File) iterator.next();
+ for (File dir : outputDirs) {
classpath.append(File.pathSeparator + dir.getAbsolutePath() + File.pathSeparator);
}
classpath.append(System.getProperty("java.class.path", "."));
private void createList(List<IMessage> messages) {
list = new JList();
listModel = new DefaultListModel();
- for (Iterator<IMessage> iterator = messages.iterator(); iterator.hasNext();) {
- listModel.addElement(iterator.next());
+ for (IMessage message : messages) {
+ listModel.addElement(message);
}
}
args = new String[l.size() + xmlfiles.size() + 1];
// TODO speedup
int p = 0;
- for (int i = 0; i < l.size(); i++) {
- args[p++] = l.get(i);
+ for (String s : l) {
+ args[p++] = s;
}
- for (int i = 0; i < xmlfiles.size(); i++) {
- args[p++] = xmlfiles.get(i);
+ for (String xmlfile : xmlfiles) {
+ args[p++] = xmlfile;
}
args[p++] = "-xmlConfigured";
} else {
String contents[] = from.list();
if (contents == null)
return;
- for (int i = 0; i < contents.length; i++) {
- String string = contents[i];
+ for (String string : contents) {
File f = new File(from, string);
File t = new File(to, string);
public List<String> getSourceFileList(String[] files) {
List<String> sourceFiles = new ArrayList<String>();
- for (int i = 0; i < files.length; i++) {
- sourceFiles.add(getAbsoluteProjectDir() + File.separator + files[i]);
+ for (String file : files) {
+ sourceFiles.add(getAbsoluteProjectDir() + File.separator + file);
}
return sourceFiles;
}
/* Allow the user to override the testProjectPath by using sourceRoots */
File[] srcBase = new File[] { new File(projectPath + File.separator + srcDirName) };
- for (int j = 0; j < srcBase.length; j++) {
- File[] fromResources = FileUtil.listFiles(srcBase[j], new FileFilter() {
+ for (File file : srcBase) {
+ File[] fromResources = FileUtil.listFiles(file, new FileFilter() {
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
return !name.endsWith(".class") && !name.endsWith(".java") && !name.endsWith(".aj")
&& !name.endsWith(".lst") && !name.endsWith(".jar");
}
});
- for (int i = 0; i < fromResources.length; i++) {
- String normPath = FileUtil.normalizedPath(fromResources[i], srcBase[j]);
- sourcePathResources.put(normPath, fromResources[i]);
+ for (File fromResource : fromResources) {
+ String normPath = FileUtil.normalizedPath(fromResource, file);
+ sourcePathResources.put(normPath, fromResource);
}
}
compilerConfig.setSourcePathResources(m);
AjBuildConfig buildConfig = genAjBuildConfig();
Map<String, File> found = buildConfig.getSourcePathResources();
- for (Iterator<String> i = found.keySet().iterator(); i.hasNext();) {
- String resource = i.next();
+ for (String resource : found.keySet()) {
assertEquals("expected to find resource with name newFile.txt but " + "found " + resource, "newFile.txt", resource);
File from = buildConfig.getSourcePathResources().get(resource);
assertEquals("expected to find resource with file " + getWorkingDir() + "but found " + from, getWorkingDir(), from);
File binBase = openFile(outdirName);
String[] toResources = FileUtil.listFiles(binBase);
- for (int i = 0; i < toResources.length; i++) {
- String fileName = toResources[i];
+ for (String fileName : toResources) {
if (fileName.indexOf("CVS") == -1) {
boolean b = expectedOutdirContents.remove(fileName);
assertTrue("Extraneous resources: " + fileName, b);
private void listSourceResources(String indirName, Set<String> resources) {
File srcBase = openFile(indirName);
File[] fromResources = FileUtil.listFiles(srcBase, aspectjResourceFileFilter);
- for (int i = 0; i < fromResources.length; i++) {
- String name = FileUtil.normalizedPath(fromResources[i], srcBase);
+ for (File fromResource : fromResources) {
+ String name = FileUtil.normalizedPath(fromResource, srcBase);
// System.err.println("Checking "+name);
if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
resources.add(name);
HashSet<String> resources = new HashSet<>();
listSourceResources(indirName, resources);
- for (int i = 0; i < toResources.length; i++) {
- String fileName = FileUtil.normalizedPath(toResources[i], binBase);
+ for (File toResource : toResources) {
+ String fileName = FileUtil.normalizedPath(toResource, binBase);
boolean b = resources.remove(fileName);
assertTrue("Extraneous resources: " + fileName, b);
}
private void listSourceResources(String indirName, Set<String> resources) {
File srcBase = openFile(indirName);
File[] fromResources = FileUtil.listFiles(srcBase, aspectjResourceFileFilter);
- for (int i = 0; i < fromResources.length; i++) {
- String name = FileUtil.normalizedPath(fromResources[i], srcBase);
+ for (File fromResource : fromResources) {
+ String name = FileUtil.normalizedPath(fromResource, srcBase);
if (!name.startsWith("CVS/") && (-1 == name.indexOf("/CVS/")) && !name.endsWith("/CVS")) {
resources.add(name);
}
File binBase = openFile(outdirName);
File[] toResources = FileUtil.listFiles(binBase, aspectjResourceFileFilter);
- for (int i = 0; i < toResources.length; i++) {
- String fileName = FileUtil.normalizedPath(toResources[i], binBase);
+ for (File toResource : toResources) {
+ String fileName = FileUtil.normalizedPath(toResource, binBase);
/* Ensure we copied the right JAR manifest */
if (fileName.equalsIgnoreCase("meta-inf/Manifest.mf")) {
- byte[] outManifest = FileUtil.readAsByteArray(toResources[i]);
+ byte[] outManifest = FileUtil.readAsByteArray(toResource);
assertTrue("Wrong manifest has been copied", Arrays.equals(inManifest, outManifest));
}
boolean b = resources.remove(fileName);
// See if the messages match
int msgCount = 0;
List<TestMessageHandler.TestMessage> l = handler.getMessages();
- for (Iterator<TestMessageHandler.TestMessage> iter = l.iterator(); iter.hasNext();) {
- IMessage msg = iter.next().getContainedMessage();
+ for (TestMessageHandler.TestMessage testMessage : l) {
+ IMessage msg = testMessage.getContainedMessage();
if (debugTests)
System.out.println("Looking at [" + msg + "]");
if (msg.getKind().equals(IMessage.WEAVEINFO)) {
try {
fw = new FileWriter(f);
List<TestMessageHandler.TestMessage> l = handler.getMessages();
- for (Iterator<TestMessageHandler.TestMessage> iter = l.iterator(); iter.hasNext();) {
- IMessage msg = iter.next().getContainedMessage();
+ for (TestMessageHandler.TestMessage testMessage : l) {
+ IMessage msg = testMessage.getContainedMessage();
if (msg.getKind().equals(IMessage.WEAVEINFO)) {
fw.write(msg.getMessage() + "\n");
}
.findElementForLabel(aspect, IProgramElement.Kind.ADVICE, beforeExec);
assertNotNull(beforeExecNode);
IRelationship rel = manager.getRelationshipMap().get(beforeExecNode, IRelationship.Kind.ADVICE, relName);
- for (Iterator<String> it = rel.getTargets().iterator(); it.hasNext();) {
- String currHandle = it.next();
+ for (String currHandle : rel.getTargets()) {
if (manager.getHierarchy().findElementForHandle(currHandle).toLabelString().equals(to))
return;
}
// String set = to;
IRelationship rel2 = manager.getRelationshipMap().get(clazz, IRelationship.Kind.DECLARE_INTER_TYPE, backRelName);
// String handle2 = (String)rel2.getTargets().get(0);
- for (Iterator<String> it = rel2.getTargets().iterator(); it.hasNext();) {
- String currHandle = it.next();
+ for (String currHandle : rel2.getTargets()) {
if (manager.getHierarchy().findElementForHandle(currHandle).toLabelString().equals(from))
return;
}
}
private void testModelIntegrityHelper(IProgramElement node) throws Exception {
- for (Iterator<IProgramElement> it = node.getChildren().iterator(); it.hasNext();) {
- IProgramElement child = (IProgramElement) it.next();
+ for (IProgramElement child : node.getChildren()) {
if (node == child.getParent()) {
testModelIntegrityHelper(child);
} else {
public void preProcess(IProgramElement node) {
if (node.getChildren() == null)
return;
- for (Iterator<IProgramElement> it = node.getChildren().iterator(); it.hasNext();) {
- if (it.next() == null)
+ for (IProgramElement iProgramElement : node.getChildren()) {
+ if (iProgramElement == null)
throw new NullPointerException("null child on node: " + node.getName());
}
}
} else {
StringBuffer sb = new StringBuffer();
List outputDirs = compilerConfig.getOutputLocationManager().getAllOutputLocations();
- for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
- File dir = (File) iterator.next();
+ for (Object outputDir : outputDirs) {
+ File dir = (File) outputDir;
sb.append(dir.getAbsolutePath() + File.pathSeparator);
}
classpath = LangUtil.makeClasspath(null, compilerConfig.getClasspath(), sb.toString(), compilerConfig.getOutJar());
* Adds an entry to multiple build configuration files.
*/
public void updateBuildConfigFiles(List buildConfigFiles, List<String> filesToUpdate, boolean addToConfiguration) {
- for (int i = 0; i < buildConfigFiles.size(); i++) {
- List<String> fileContents = readConfigFile((String) buildConfigFiles.get(i));
+ for (Object buildConfigFile : buildConfigFiles) {
+ List<String> fileContents = readConfigFile((String) buildConfigFile);
if (addToConfiguration) {
- for (int j = 0; j < filesToUpdate.size(); j++) {
- fileContents.add(filesToUpdate.get(j));
+ for (String s : filesToUpdate) {
+ fileContents.add(s);
}
} else {
- for (int k = 0; k < filesToUpdate.size(); k++) {
- if (fileContents.contains(filesToUpdate.get(k))) {
- fileContents.remove(filesToUpdate.get(k));
+ for (String s : filesToUpdate) {
+ if (fileContents.contains(s)) {
+ fileContents.remove(s);
}
}
}
- writeConfigFile((String) buildConfigFiles.get(i), fileContents);
+ writeConfigFile((String) buildConfigFile, fileContents);
}
}
String fileContentsString = "";
// List filesToWrite = null;
Set<String> includedFiles = new HashSet<>();
- for (Iterator<BuildConfigNode> it = importedNodes.iterator(); it.hasNext();) {
- BuildConfigNode node = it.next();
+ for (BuildConfigNode node : importedNodes) {
fileContentsString += '@' + node.getResourcePath() + "\n";
String parentPath = new File(filePath).getParent();
String importedFilePath = parentPath + File.separator + node.getResourcePath();
includedFiles.addAll(getIncludedFiles(importedFilePath, parentPath));
}
- for (Iterator<BuildConfigNode> it = files.iterator(); it.hasNext();) {
- BuildConfigNode node = it.next();
+ for (BuildConfigNode node : files) {
if (node.getName().endsWith(".lst") && !node.getResourcePath().startsWith("..")) {
fileContentsString += '@';
fileContentsString += node.getResourcePath() + "\n";
configParser.parseConfigFile(new File(path));
List<File> files = configParser.getFiles();
List<String> relativeFiles = new ArrayList<String>();
- for (Iterator<File> it = files.iterator(); it.hasNext();) {
- relativeFiles.add(relativizePath(it.next().getPath(), rootPath));
+ for (File file : files) {
+ relativeFiles.add(relativizePath(file.getPath(), rootPath));
}
return relativeFiles;
} catch (ConfigParser.ParseException pe) {
}
node.addChild(dir);
// boolean foundMatch = false;
- for (Iterator it = importedFiles.iterator(); it.hasNext();) {
- File importedFile = (File) it.next();
+ for (Object file : importedFiles) {
+ File importedFile = (File) file;
if (importedFile.getParentFile().getAbsolutePath().equals(dir2.getAbsolutePath())) {
// foundMatch = true;
BuildConfigNode importedFileNode = new BuildConfigNode(importedFile.getName(), BuildConfigNode.Kind.FILE_LST,
}
private void addFilesToDirTree(BuildConfigModel model, List configFiles, List badEntries) {
- for (Iterator it = configFiles.iterator(); it.hasNext();) {
- String path = (String) it.next();
+ for (Object configFile : configFiles) {
+ String path = (String) configFile;
if (path.startsWith("..")) {
File file = new File(path);
BuildConfigNode node = new BuildConfigNode(file.getName(), BuildConfigNode.Kind.FILE_JAVA, path);
}
}
if (node != null && node.getChildren() != null) {
- for (Iterator<IProgramElement> it = node.getChildren().iterator(); it.hasNext();) {
- IProgramElement nextNode = it.next();
+ for (IProgramElement nextNode : node.getChildren()) {
if (nextNode != null) {
findMatchesHelper(nextNode, pattern, kind, matches);
}
}
if (node != null && node.getChildren() != null) {
- for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
- IStructureViewNode foundNode = findCorrespondingViewNodeHelper((IStructureViewNode)it.next(), pNode);
+ for (Object o : node.getChildren()) {
+ IStructureViewNode foundNode = findCorrespondingViewNodeHelper((IStructureViewNode) o, pNode);
if (foundNode != null) return foundNode;
}
}
public void elementsUpdated(IHierarchy model) {
// updating structure views:
- for (Iterator it = structureViews.iterator(); it.hasNext();) {
- treeViewBuilder.buildView((StructureView) it.next(), (AspectJElementHierarchy) model);
+ for (Object structureView : structureViews) {
+ treeViewBuilder.buildView((StructureView) structureView, (AspectJElementHierarchy) model);
}
}
};
}
}
- for (Iterator it = structureViews.iterator(); it.hasNext();) {
- StructureView view = (StructureView) it.next();
+ for (Object structureView : structureViews) {
+ StructureView view = (StructureView) structureView;
if (!(view instanceof GlobalStructureView) || !recordHistory || defaultFileView == null) {
if (node.getKind().equals(IProgramElement.Kind.CODE)) {
IProgramElement parentNode = node.getParent();
IRelationshipMap relMap = (manager == null ? null : manager.getRelationshipMap());
List relationships = (relMap == null ? null : relMap.get(nodeHandle));
if (relationships != null) {
- for (Iterator it = relationships.iterator(); it.hasNext();) {
- IRelationship rel = (IRelationship) it.next();
+ for (Object relationship : relationships) {
+ IRelationship rel = (IRelationship) relationship;
if (rel != null && rel.getTargets().size() > 0) {
IStructureViewNode relNode = createRelationship(rel, iconRegistry.getIcon(rel.getKind()));
if (relNode != null) {
svNode.add(relNode, 0);
- for (Iterator it2 = rel.getTargets().iterator(); it2.hasNext();) {
- String handle = (String) it2.next();
+ for (String handle : rel.getTargets()) {
IProgramElement link = Ajde.getDefault().getModel().getHierarchy().findElementForHandle(handle);
if (link != null) {
IStructureViewNode linkNode = createLink(link, iconRegistry.getStructureIcon(link.getKind(),
private void sortView(IStructureViewNode node, Comparator<IStructureViewNode> comparator) {
if (node == null || node.getChildren() == null) return;
Collections.sort(node.getChildren(), comparator);
- for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
- IStructureViewNode nextNode = (IStructureViewNode)it.next();
+ for (Object o : node.getChildren()) {
+ IStructureViewNode nextNode = (IStructureViewNode) o;
if (nextNode != null) sortView(nextNode, comparator);
}
}
@Override
public void setProjectMultivalPreference(String name, List values) {
String valuesString = "";
- for (Iterator it = values.iterator(); it.hasNext(); ) {
- valuesString += (String)it.next() + ';';
+ for (Object value : values) {
+ valuesString += (String) value + ';';
}
properties.setProperty(name, valuesString);
saveProperties();
public void saveOptions() throws IOException {
Set s = warningComboBoxes.entrySet();
- for (Iterator iterator = s.iterator(); iterator.hasNext();) {
- Map.Entry entry = (Entry) iterator.next();
+ for (Object o : s) {
+ Entry entry = (Entry) o;
String javaOption = (String) entry.getKey();
- JComboBox combo = (JComboBox)entry.getValue();
+ JComboBox combo = (JComboBox) entry.getValue();
String value = (String) combo.getSelectedItem();
javaBuildOptions.setOption(javaOption, value);
}
view_comboBox = new JComboBox();
view_comboBox.setFont(AjdeWidgetStyles.DEFAULT_LABEL_FONT);
- for (Iterator it = structureViews.iterator(); it.hasNext(); ) {
- view_comboBox.addItem(it.next());
+ for (Object structureView : structureViews) {
+ view_comboBox.addItem(structureView);
}
try {
private JPopupMenu createFilterMenu() {
JPopupMenu filterMenu = new JPopupMenu();
IProgramElement.Accessibility[] accessibility = IProgramElement.Accessibility.ALL;
- for (int i = 0; i < accessibility.length; i++) {
- CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(accessibility[i]);
- menuItem.setIcon(Ajde.getDefault().getIconRegistry().getAccessibilitySwingIcon(accessibility[i]));
+ for (IProgramElement.Accessibility value : accessibility) {
+ CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(value);
+ menuItem.setIcon(Ajde.getDefault().getIconRegistry().getAccessibilitySwingIcon(value));
filterMenu.add(menuItem);
}
filterMenu.add(new JSeparator());
IProgramElement.Kind[] kinds = IProgramElement.Kind.ALL;
- for (int i = 0; i < kinds.length; i++) {
- if (kinds[i].isMember()) {
- CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(kinds[i]);
- menuItem.setIcon((Icon)Ajde.getDefault().getIconRegistry().getIcon(kinds[i]).getIconResource());
+ for (IProgramElement.Kind kind : kinds) {
+ if (kind.isMember()) {
+ CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(kind);
+ menuItem.setIcon((Icon) Ajde.getDefault().getIconRegistry().getIcon(kind).getIconResource());
filterMenu.add(menuItem);
}
}
filterMenu.add(new JSeparator());
IProgramElement.Modifiers[] modifiers = IProgramElement.Modifiers.ALL;
- for (int i = 0; i < modifiers.length; i++) {
- CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(modifiers[i]);
+ for (IProgramElement.Modifiers modifier : modifiers) {
+ CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(modifier);
filterMenu.add(menuItem);
}
return filterMenu;
JPopupMenu relationsMenu = new JPopupMenu();
java.util.List relations = Ajde.getDefault().getStructureViewManager().getAvailableRelations();
- for (Iterator it = relations.iterator(); it.hasNext(); ) {
- IRelationship.Kind relation = (IRelationship.Kind)it.next();
+ for (Object o : relations) {
+ IRelationship.Kind relation = (IRelationship.Kind) o;
CheckBoxSelectionMenuButton menuItem = new CheckBoxSelectionMenuButton(relation);
- menuItem.setIcon((Icon)Ajde.getDefault().getIconRegistry().getIcon(relation).getIconResource());
+ menuItem.setIcon((Icon) Ajde.getDefault().getIconRegistry().getIcon(relation).getIconResource());
relationsMenu.add(menuItem);
}
StructureViewProperties.Granularity[] granularity = StructureViewProperties.Granularity.ALL;
ButtonGroup group = new ButtonGroup();
- for (int i = 0; i < granularity.length; i++) {
- RadioSelectionMenuButton menuItem = new RadioSelectionMenuButton(granularity[i], group);
+ for (StructureViewProperties.Granularity value : granularity) {
+ RadioSelectionMenuButton menuItem = new RadioSelectionMenuButton(value, group);
orderMenu.add(menuItem);
- if (granularity[i].equals(StructureViewProperties.Granularity.MEMBER)) {
+ if (value.equals(StructureViewProperties.Granularity.MEMBER)) {
menuItem.setSelected(true);
}
}
public void updateConfigs(java.util.List configsList) {
configs_comboBox.removeAllItems();
- for (Iterator it = configsList.iterator(); it.hasNext(); ) {
- configs_comboBox.addItem(it.next());
- }
+ for (Object o : configsList) {
+ configs_comboBox.addItem(o);
+ }
}
public void setSelectedConfig(String config) {
public BrowserViewPanel(IconRegistry icons, java.util.List views, StructureViewProperties.Hierarchy visibleViewHierarchy) {
try {
view_comboBox = new JComboBox(views.toArray());
- for (Iterator it = views.iterator(); it.hasNext(); ) {
- StructureViewProperties.Hierarchy hierarchy = (StructureViewProperties.Hierarchy)it.next();
- if (hierarchy == visibleViewHierarchy) {
- view_comboBox.setSelectedItem(hierarchy);
- }
- }
+ for (Object view : views) {
+ StructureViewProperties.Hierarchy hierarchy = (StructureViewProperties.Hierarchy) view;
+ if (hierarchy == visibleViewHierarchy) {
+ view_comboBox.setSelectedItem(hierarchy);
+ }
+ }
//GlobalViewProperties visibleView = (GlobalViewProperties)viewProperties.get(visibleViewHierarchy.toString());
treeManager = new StructureTreeManager();//, visibleView);
jbInit();
public BuildConfigPopupMenu(final AbstractAction action) {
List configFiles = Ajde.getDefault().getBuildConfigManager().getAllBuildConfigFiles();
- for (Iterator it = configFiles.iterator(); it.hasNext(); ) {
- final String buildConfig = (String)it.next();
- JMenuItem buildItem = new JMenuItem(buildConfig);
- buildItem.setFont(AjdeWidgetStyles.DEFAULT_LABEL_FONT);
- buildItem.addActionListener(
- new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- Ajde.getDefault().getBuildConfigManager().setActiveConfigFile(buildConfig);
- // A separate thread is required here because the buildProgresssMonitor
- // that monitors the build needs to be in a different thread
- // to that which is doing the build (swing threading issues)
- Ajde.getDefault().runBuildInDifferentThread(buildConfig, true);
- action.actionPerformed(e);
- }
- });
- buildItem.setIcon((Icon)Ajde.getDefault().getIconRegistry().getIcon(IProgramElement.Kind.FILE_LST).getIconResource());
- this.add(buildItem);
+ for (Object configFile : configFiles) {
+ final String buildConfig = (String) configFile;
+ JMenuItem buildItem = new JMenuItem(buildConfig);
+ buildItem.setFont(AjdeWidgetStyles.DEFAULT_LABEL_FONT);
+ buildItem.addActionListener(
+ new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ Ajde.getDefault().getBuildConfigManager().setActiveConfigFile(buildConfig);
+ // A separate thread is required here because the buildProgresssMonitor
+ // that monitors the build needs to be in a different thread
+ // to that which is doing the build (swing threading issues)
+ Ajde.getDefault().runBuildInDifferentThread(buildConfig, true);
+ action.actionPerformed(e);
+ }
+ });
+ buildItem.setIcon((Icon) Ajde.getDefault().getIconRegistry().getIcon(IProgramElement.Kind.FILE_LST).getIconResource());
+ this.add(buildItem);
}
}
}
private void saveOptions() {
try {
Component[] components = main_tabbedPane.getComponents();
- for (int i = 0; i < components.length; i++) {
- if (components[i] instanceof OptionsPanel) {
- ((OptionsPanel)components[i]).saveOptions();
+ for (Component component : components) {
+ if (component instanceof OptionsPanel) {
+ ((OptionsPanel) component).saveOptions();
}
}
} catch (IOException ioe) {
public StructureViewPanel(java.util.List structureViews) {
// this.structureViews = structureViews;
- for (Iterator it = structureViews.iterator(); it.hasNext(); ) {
- initView((StructureView)it.next());
+ for (Object structureView : structureViews) {
+ initView((StructureView) structureView);
}
currentView = (StructureView)structureViews.get(0);
structureToolBar_panel = new BrowserStructureViewToolPanel(structureViews, currentView, this);
this.kind = Kind.DECLARATION;
if (children != null) {
- for (Iterator it = children.iterator(); it.hasNext(); ) {
- SwingTreeViewNode child = (SwingTreeViewNode)it.next();
+ for (Object o : children) {
+ SwingTreeViewNode child = (SwingTreeViewNode) o;
if (StructureViewNodeFactory.acceptNode(programElement, child.getStructureNode())) {
- super.add(child);
+ super.add(child);
}
}
}
private ConfigTreeNode buildTree(BuildConfigNode node) {
ConfigTreeNode treeNode = new ConfigTreeNode(node);
- for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) {
- BuildConfigNode childNode = (BuildConfigNode)it.next();
- treeNode.add(buildTree(childNode));
- }
+ for (BuildConfigNode childNode : node.getChildren()) {
+ treeNode.add(buildTree(childNode));
+ }
return treeNode;
}
String contents[] = from.list();
if (contents == null)
return;
- for (int i = 0; i < contents.length; i++) {
- String string = contents[i];
+ for (String string : contents) {
File f = new File(from, string);
File t = new File(to, string);
private IProgramElement getChild(IProgramElement parent, String s) {
List<IProgramElement> kids = parent.getChildren();
- for (Iterator<IProgramElement> iter = kids.iterator(); iter.hasNext();) {
- IProgramElement element = (IProgramElement) iter.next();
+ for (IProgramElement element : kids) {
if (element.getName().indexOf(s) != -1)
return element;
}
}
if (ipe.getChildren() != null) {
List kids = ipe.getChildren();
- for (Iterator iter = kids.iterator(); iter.hasNext();) {
- IProgramElement element = (IProgramElement) iter.next();
+ for (Object kid : kids) {
+ IProgramElement element = (IProgramElement) kid;
findChild(s, element);
}
}
System.out.println(ipe.toLabelString());// getName());
if (ipe.getChildren() != null) {
List kids = ipe.getChildren();
- for (Iterator iter = kids.iterator(); iter.hasNext();) {
- IProgramElement element = (IProgramElement) iter.next();
+ for (Object kid : kids) {
+ IProgramElement element = (IProgramElement) kid;
walkit(element, indent + 2);
}
}
}
private void testModelIntegrityHelper(IProgramElement node) throws Exception {
- for (Iterator it = node.getChildren().iterator(); it.hasNext();) {
- IProgramElement child = (IProgramElement) it.next();
+ for (IProgramElement child : node.getChildren()) {
if (node == child.getParent()) {
testModelIntegrityHelper(child);
} else {
}
public boolean containsMessage(String prefix,String distinguishingMarks) {
- for (Iterator iter = messagesReceived.iterator(); iter.hasNext();) {
- String element = (String) iter.next();
+ for (Object o : messagesReceived) {
+ String element = (String) o;
if (element.startsWith(prefix) &&
- element.indexOf(distinguishingMarks)!=-1) return true;
+ element.indexOf(distinguishingMarks) != -1) return true;
}
return false;
}
public void dumpMessages() {
System.out.println("ProgressMonitorMessages");
- for (Iterator iter = messagesReceived.iterator(); iter.hasNext();) {
- String element = (String) iter.next();
+ for (Object o : messagesReceived) {
+ String element = (String) o;
System.out.println(element);
}
}
/* Allow the user to override the testProjectPath by using sourceRoots */
File[] srcBase = new File[] { new File(projectPath + File.separator + srcDirName) };
- for (int j = 0; j < srcBase.length; j++) {
- File[] fromResources = FileUtil.listFiles(srcBase[j], new FileFilter() {
+ for (File file : srcBase) {
+ File[] fromResources = FileUtil.listFiles(file, new FileFilter() {
public boolean accept(File pathname) {
String name = pathname.getName().toLowerCase();
return !name.endsWith(".class") && !name.endsWith(".java") && !name.endsWith(".aj")
&& !name.endsWith(".lst") && !name.endsWith(".jar");
}
});
- for (int i = 0; i < fromResources.length; i++) {
- String normPath = FileUtil.normalizedPath(fromResources[i], srcBase[j]);
- sourcePathResources.put(normPath, fromResources[i]);
+ for (File fromResource : fromResources) {
+ String normPath = FileUtil.normalizedPath(fromResource, file);
+ sourcePathResources.put(normPath, fromResource);
}
}
rootDir = newRootDir;
declIDTable = table;
docVisibilityModifier = docModifier;
- for (int i = 0; i < inputFiles.length; i++) {
- decorateHTMLFromIPEs(getProgramElements(model, inputFiles[i].getCanonicalPath()), rootDir.getCanonicalPath()
+ for (File inputFile : inputFiles) {
+ decorateHTMLFromIPEs(getProgramElements(model, inputFile.getCanonicalPath()), rootDir.getCanonicalPath()
+ Config.DIR_SEP_CHAR, docModifier, false);
}
}
static void decorateHTMLFromIPEs(IProgramElement[] decls, String base, String docModifier, boolean exceededNestingLevel)
throws IOException {
if (decls != null) {
- for (int i = 0; i < decls.length; i++) {
- IProgramElement decl = decls[i];
+ for (IProgramElement decl : decls) {
decorateHTMLFromIPE(decl, base, docModifier, exceededNestingLevel);
}
}
if (fieldsDeclaredOn != null && !constDeclaredOn.isEmpty()) {
insertDeclarationsSummary(fileBuffer, constDeclaredOn, ITD_CONSTRUCTOR_SUMMARY, index);
}
- for (Iterator<IProgramElement> it = node.getChildren().iterator(); it.hasNext();) {
- IProgramElement member = it.next();
+ for (IProgramElement member : node.getChildren()) {
if (member.getKind().equals(IProgramElement.Kind.POINTCUT)) {
pointcuts.add(member);
} else if (member.getKind().equals(IProgramElement.Kind.ADVICE)) {
insertIndex += tableHead.length();
// insert the body of the table
- for (int i = 0; i < decls.size(); i++) {
- IProgramElement decl = (IProgramElement) decls.get(i);
+ for (Object o : decls) {
+ IProgramElement decl = (IProgramElement) o;
if (isAboveVisibility(decl)) {
// insert the table row accordingly
String comment = generateSummaryComment(decl);
private static boolean declsAboveVisibilityExist(List decls) {
boolean exist = false;
- for (Iterator it = decls.iterator(); it.hasNext();) {
- IProgramElement element = (IProgramElement) it.next();
+ for (Object decl : decls) {
+ IProgramElement element = (IProgramElement) decl;
if (isAboveVisibility(element))
exist = true;
}
static String generateHREFName(IProgramElement decl) {
StringBuffer hrefLinkBuffer = new StringBuffer();
char[] declChars = decl.toLabelString().toCharArray();
- for (int i = 0; i < declChars.length; i++) {
- if (declChars[i] == '"') {
+ for (char declChar : declChars) {
+ if (declChar == '"') {
hrefLinkBuffer.append("quot;");
} else {
- hrefLinkBuffer.append(declChars[i]);
+ hrefLinkBuffer.append(declChar);
}
}
return hrefLinkBuffer.toString();
*/
private static void packageHTML(AsmManager model, File[] inputFiles) throws IOException {
ArrayList<String> dirList = new ArrayList<String>();
- for (int i = 0; i < inputFiles.length; i++) {
- String packageName = StructureUtil.getPackageDeclarationFromFile(model, inputFiles[i]);
+ for (File inputFile : inputFiles) {
+ String packageName = StructureUtil.getPackageDeclarationFromFile(model, inputFile);
// Only copy the package.html file once.
if (dirList.contains(packageName))
continue;
// Check to see if there exist a package.html file for this package.
- String dir = inputFiles[i].getAbsolutePath().substring(0, inputFiles[i].getAbsolutePath().lastIndexOf(File.separator));
+ String dir = inputFile.getAbsolutePath().substring(0, inputFile.getAbsolutePath().lastIndexOf(File.separator));
File input = new File(dir + Config.DIR_SEP_CHAR + "package.html");
File inDir = new File(dir + Config.DIR_SEP_CHAR + "doc-files");
// If it does not exist lets go to the next package.
for (; i < ajcOptions.size(); i++) {
argsToCompiler[i] = ajcOptions.elementAt(i);
}
- for (int j = 0; j < inputFiles.length; j++) {
- argsToCompiler[i] = inputFiles[j].getAbsolutePath();
+ for (File inputFile : inputFiles) {
+ argsToCompiler[i] = inputFile.getAbsolutePath();
// System.out.println(">> file to ajc: " + inputFiles[j].getAbsolutePath());
i++;
}
for (int k = 0; k < signatureFiles.length; k++) {
javadocargs[options.size() + k] = StructureUtil.translateAjPathName(signatureFiles[k].getCanonicalPath());
}
- for (int k = 0; k < signatureFiles.length; k++) {
- files.add(StructureUtil.translateAjPathName(signatureFiles[k].getCanonicalPath()));
+ for (File signatureFile : signatureFiles) {
+ files.add(StructureUtil.translateAjPathName(signatureFile.getCanonicalPath()));
}
}
if (LangUtil.is19VMOrGreater()) {
return f.getName().equals("package-summary.html");
}
});
- for (int j = 0; j < files.length; j++) {
- removeDeclIDsFromFile(files[j].getAbsolutePath(), false);
+ for (File file : files) {
+ removeDeclIDsFromFile(file.getAbsolutePath(), false);
}
}
}
// System.err.println(argList);
args = new String[argList.size()];
int counter = 0;
- for (Iterator<String> it = argList.iterator(); it.hasNext();) {
- args[counter] = it.next();
+ for (String s : argList) {
+ args[counter] = s;
counter++;
}
} catch (FileNotFoundException e) {
if (vargs.size() == 0) {
displayHelpAndExit(null);
}
- for (int i = 0; i < vargs.size(); i++) {
- String arg = (String) vargs.get(i);
+ for (Object varg : vargs) {
+ String arg = (String) varg;
ignoreArg = false;
if (addNextAsDocDir) {
docDir = arg;
int index2 = name.length();
if ((index1 >= 0 && index2 >= 0)
&& (name.substring(index1, index2).equals(".java") || name.substring(index1, index2)
- .equals(".aj"))) {
+ .equals(".aj"))) {
return true;
} else {
return false;
}
}
});
- for (int j = 0; j < files.length; j++) {
+ for (String file : files) {
filenames.addElement(sourcepath.elementAt(c) + Config.DIR_SEP_CHAR + arg
- + Config.DIR_SEP_CHAR + files[j]);
+ + Config.DIR_SEP_CHAR + file);
}
} else if (c == sourcepath.size()) { // last element on classpath
System.out.println("ajdoc: No package, class, or source file " + "found named " + arg + ".");
if (rels != null) {
relations.addAll(rels);
}
- for (Iterator<IProgramElement> iter = node.getChildren().iterator(); iter.hasNext();) {
- IProgramElement child = (IProgramElement) iter.next();
+ for (IProgramElement child : node.getChildren()) {
// if we're not a type, or if we are and the child is code, then
// we want to get the relationships for this child - this means that the
// correct relationships appear against the type in the ajdoc
if (!node.getKind().isType() || child.getKind().equals(IProgramElement.Kind.CODE)) {
List<IRelationship> childRelations = node.getModel().getRelationshipMap().get(child);
if (childRelations != null) {
- for (Iterator<IRelationship> iterator = childRelations.iterator(); iterator.hasNext();) {
- IRelationship rel = (IRelationship) iterator.next();
+ for (IRelationship rel : childRelations) {
if (!relations.contains(rel)) {
relations.add(rel);
}
if (relations == null || relations.isEmpty())
return null;
List<String> targets = new ArrayList<String>();
- for (Iterator<IRelationship> it = relations.iterator(); it.hasNext();) {
- IRelationship rtn = (IRelationship) it.next();
+ for (IRelationship rtn : relations) {
if (rtn.getKind().equals(kind) && ((relName != null && relName.equals(rtn.getName())) || relName == null)) {
List<String> targs = rtn.getTargets();
- for (String element: targs) {
+ for (String element : targs) {
if (!targets.contains(element)) {
targets.add(element);
}
}
String modifiers = "";
- for (Iterator modIt = node.getModifiers().iterator(); modIt.hasNext();) {
- modifiers += modIt.next() + " ";
+ for (IProgramElement.Modifiers value : node.getModifiers()) {
+ modifiers += value + " ";
}
if (node.getKind().equals(IProgramElement.Kind.METHOD) || node.getKind().equals(IProgramElement.Kind.FIELD)) {
}
IProgramElement fileNode = model.getHierarchy().findElementForSourceFile(inputFile.getAbsolutePath());
- for (Iterator it = fileNode.getChildren().iterator(); it.hasNext();) {
- IProgramElement node = (IProgramElement) it.next();
+ for (IProgramElement node : fileNode.getChildren()) {
if (node.getKind().isPackageDeclaration()) {
// skip
} else if (node.getKind().equals(IProgramElement.Kind.IMPORT_REFERENCE)) {
private static void processImportDeclaration(IProgramElement node, PrintWriter writer) throws IOException {
List imports = node.getChildren();
- for (Iterator i = imports.iterator(); i.hasNext();) {
- IProgramElement importNode = (IProgramElement) i.next();
+ for (Object anImport : imports) {
+ IProgramElement importNode = (IProgramElement) anImport;
writer.println(importNode.getSourceSignature());
}
}
private static void processMembers(List/* IProgramElement */members, PrintWriter writer, boolean declaringTypeIsInterface)
throws DocException {
- for (Iterator it = members.iterator(); it.hasNext();) {
- IProgramElement member = (IProgramElement) it.next();
+ for (Object o : members) {
+ IProgramElement member = (IProgramElement) o;
if (member.getKind().isType()) {
if (!member.getParent().getKind().equals(IProgramElement.Kind.METHOD) && !StructureUtil.isAnonymous(member)) {// don't
*/
public static List<String> getMissingStringsInFile(File htmlFile, String[] requiredStrings) throws Exception {
List<String> missingStrings = new ArrayList<String>();
- for (int i = 0; i < requiredStrings.length; i++) {
- String string = requiredStrings[i];
+ for (String string : requiredStrings) {
if (!containsString(htmlFile, string)) {
missingStrings.add(string);
}
public static List<String> getMissingStringsInSection(File htmlFile,
String[] requiredStrings, String sectionHeader) throws Exception {
List<String> missingStrings = new ArrayList<String>();
- for (int i = 0; i < requiredStrings.length; i++) {
- String string = requiredStrings[i];
- if (!containsStringWithinSection(htmlFile,string,sectionHeader)) {
+ for (String string : requiredStrings) {
+ if (!containsStringWithinSection(htmlFile, string, sectionHeader)) {
missingStrings.add(string);
}
}
String contents[] = from.list();
if (contents == null)
return;
- for (int i = 0; i < contents.length; i++) {
- String string = contents[i];
+ for (String string : contents) {
File f = new File(from, string);
File t = new File(to, string);
if (inputFiles.length == 0) {
fail("need to pass some files into ajdoc");
}
- for (int i = 0; i < inputFiles.length; i++) {
- if (!inputFiles[i].exists()) {
- fail(inputFiles[i].getAbsolutePath() + " does not exist");
+ for (File inputFile : inputFiles) {
+ if (!inputFile.exists()) {
+ fail(inputFile.getAbsolutePath() + " does not exist");
}
}
public void runAjdoc(List options) {
String[] args = new String[options.size()];
int i = 0;
- for (Iterator iter = options.iterator(); iter.hasNext();) {
- String element = (String) iter.next();
+ for (Object option : options) {
+ String element = (String) option;
args[i] = element;
i++;
}
IProgramElement fileNode = node;
ArrayList<IProgramElement> peNodes = new ArrayList<IProgramElement>();
getAllStructureChildren(fileNode, peNodes, showSubMember, showMemberAndType);
- for (Iterator<IProgramElement> it = peNodes.iterator(); it.hasNext();) {
- IProgramElement peNode = it.next();
+ for (IProgramElement peNode : peNodes) {
List<IProgramElement> entries = new ArrayList<IProgramElement>();
entries.add(peNode);
ISourceLocation sourceLoc = peNode.getSourceLocation();
if (relationshipsToRemove.size() == relationships.size()) {
sourcesToRemove.add(hid);
} else {
- for (int i = 0; i < relationshipsToRemove.size(); i++) {
- relationships.remove(relationshipsToRemove.get(i));
+ for (IRelationship iRelationship : relationshipsToRemove) {
+ relationships.remove(iRelationship);
}
}
}
if (relationshipsToRemove.size() == relationships.size()) {
sourcesToRemove.add(hid);
} else {
- for (int i = 0; i < relationshipsToRemove.size(); i++) {
- relationships.remove(relationshipsToRemove.get(i));
+ for (IRelationship iRelationship : relationshipsToRemove) {
+ relationships.remove(iRelationship);
}
}
}
List<IRelationship> relationshipsToRemove = new ArrayList<IRelationship>();
// Iterate through the relationships against this source
// handle
- for (Iterator<IRelationship> reliter = relationships.iterator(); reliter.hasNext();) {
- IRelationship rel = reliter.next();
+ for (IRelationship rel : relationships) {
List<String> targets = rel.getTargets();
List<String> targetsToRemove = new ArrayList<String>();
// Iterate through the targets for this relationship
- for (Iterator<String> targetIter = targets.iterator(); targetIter.hasNext();) {
- String targethid = targetIter.next();
-// tgthandlecounter++;
+ for (String targethid : targets) {
+ // tgthandlecounter++;
// Do we already know it doesn't exist?
if (nonExistingHandles.contains(targethid)) {
if (dumpDeltaProcessing) {
} else {
// MEMORY LEAK - we don't remove the
// relationships !!
- for (int i = 0; i < relationshipsToRemove.size(); i++) {
- IRelationship irel = relationshipsToRemove.get(i);
+ for (IRelationship irel : relationshipsToRemove) {
verifyAssumption(mapper.remove(hid, irel), "Failed to remove relationship " + irel.getName()
+ " for shid " + hid);
}
}
}
// Remove sources that have no valid relationships any more
- for (Iterator<String> srciter = sourcesToRemove.iterator(); srciter.hasNext();) {
- String hid = srciter.next();
+ for (String hid : sourcesToRemove) {
mapper.removeAll(hid);
IProgramElement ipe = hierarchy.getElement(hid);
if (ipe != null) {
};
public static Kind getKindForString(String kindString) {
- for (int i = 0; i < ALL.length; i++) {
- if (ALL[i].toString().equals(kindString)) {
- return ALL[i];
- }
- }
+ for (Kind kind : ALL) {
+ if (kind.toString().equals(kindString)) {
+ return kind;
+ }
+ }
return ERROR;
}
* @return the Kind instance
*/
public static Kind getKindFor(String stringFormOfRelationshipKind) {
- for (int i = 0; i < ALL.length; i++) {
- if (ALL[i].name.equals(stringFormOfRelationshipKind)) {
- return ALL[i];
+ for (Kind kind : ALL) {
+ if (kind.name.equals(stringFormOfRelationshipKind)) {
+ return kind;
}
}
return null;
List<char[]> parameterTypes = ipe.getParameterSignatures();
StringBuffer sb = new StringBuffer();
if (sourceRefs != null) {
- for (int i = 0; i < sourceRefs.size(); i++) {
- String sourceRef = sourceRefs.get(i);
+ for (String sourceRef : sourceRefs) {
sb.append(HandleProviderDelimiter.getDelimiter(ipe));
sb.append(sourceRef);
}
if (ipe.getKind().isInterTypeMember()) {
int count = 1;
List<IProgramElement> kids = ipe.getParent().getChildren();
- for (Iterator<IProgramElement> iterator = kids.iterator(); iterator.hasNext();) {
- IProgramElement object = iterator.next();
+ for (IProgramElement object : kids) {
if (object.equals(ipe)) {
break;
}
if (children == null) {
return;
}
- for (Iterator<IProgramElement> it = children.iterator(); it.hasNext();) {
- (it.next()).setParent(this);
+ for (IProgramElement child : children) {
+ child.setParent(this);
}
}
return Collections.emptyList();
}
List<char[]> params = new ArrayList<char[]>();
- for (Iterator<char[]> iter = l.iterator(); iter.hasNext();) {
- char[] param = iter.next();
+ for (char[] param : l) {
params.add(NameConvertor.convertFromSignature(param));
}
return params;
super.put(source, relationships);
return rel;
} else {
- for (Iterator<IRelationship> it = relationships.iterator(); it.hasNext();) {
- IRelationship curr = it.next();
+ for (IRelationship curr : relationships) {
if (curr.getKind() == kind && curr.getName().equals(relationshipName) && curr.hasRuntimeTest() == runtimeTest) {
return curr;
}
file.writeShort(0);
} else {
file.writeShort(attributes.length);
- for (int i = 0; i < attributes.length; i++) {
- attributes[i].dump(file);
+ for (Attribute attribute : attributes) {
+ attribute.dump(file);
}
}
}
public static Signature getSignatureAttribute(Attribute[] attributes) {
- for (int i = 0; i < attributes.length; i++) {
- if (attributes[i].tag == Constants.ATTR_SIGNATURE) {
- return (Signature) attributes[i];
+ for (Attribute attribute : attributes) {
+ if (attribute.tag == Constants.ATTR_SIGNATURE) {
+ return (Signature) attribute;
}
}
return null;
}
public static Code getCodeAttribute(Attribute[] attributes) {
- for (int i = 0; i < attributes.length; i++) {
- if (attributes[i].tag == Constants.ATTR_CODE) {
- return (Code) attributes[i];
+ for (Attribute attribute : attributes) {
+ if (attribute.tag == Constants.ATTR_CODE) {
+ return (Code) attribute;
}
}
return null;
}
public static ExceptionTable getExceptionTableAttribute(Attribute[] attributes) {
- for (int i = 0; i < attributes.length; i++) {
- if (attributes[i].tag == Constants.ATTR_EXCEPTIONS) {
- return (ExceptionTable) attributes[i];
+ for (Attribute attribute : attributes) {
+ if (attribute.tag == Constants.ATTR_EXCEPTIONS) {
+ return (ExceptionTable) attribute;
}
}
return null;
}
public static ConstantValue getConstantValueAttribute(Attribute[] attributes) {
- for (int i = 0; i < attributes.length; i++) {
- if (attributes[i].getTag() == Constants.ATTR_CONSTANT_VALUE) {
- return (ConstantValue) attributes[i];
+ for (Attribute attribute : attributes) {
+ if (attribute.getTag() == Constants.ATTR_CONSTANT_VALUE) {
+ return (ConstantValue) attribute;
}
}
return null;
}
public static void accept(Attribute[] attributes, ClassVisitor visitor) {
- for (int i = 0; i < attributes.length; i++) {
- attributes[i].accept(visitor);
+ for (Attribute attribute : attributes) {
+ attribute.accept(visitor);
}
}
public static boolean hasSyntheticAttribute(Attribute[] attributes) {
- for (int i = 0; i < attributes.length; i++) {
- if (attributes[i].tag == Constants.ATTR_SYNTHETIC) {
+ for (Attribute attribute : attributes) {
+ if (attribute.tag == Constants.ATTR_SYNTHETIC) {
return true;
}
}
}
public static SourceFile getSourceFileAttribute(Attribute[] attributes) {
- for (int i = 0; i < attributes.length; i++) {
- if (attributes[i].tag == Constants.ATTR_SOURCE_FILE) {
- return (SourceFile) attributes[i];
+ for (Attribute attribute : attributes) {
+ if (attribute.tag == Constants.ATTR_SOURCE_FILE) {
+ return (SourceFile) attribute;
}
}
return null;
file.writeShort(bootstrapMethodRef);
int len = bootstrapArguments.length;
file.writeShort(len);
- for (int i=0;i<len;i++) {
- file.writeShort(bootstrapArguments[i]);
+ for (int bootstrapArgument : bootstrapArguments) {
+ file.writeShort(bootstrapArgument);
}
}
} else {
int blen = bootstrapMethods.length;
file.writeShort(blen);
- for (int i = 0; i < blen; i++) {
- bootstrapMethods[i].dump(file);
+ for (BootstrapMethod bootstrapMethod : bootstrapMethods) {
+ bootstrapMethod.dump(file);
}
}
}
int [] args = bm.getBootstrapArguments();
line.append(" argcount:").append(args==null?0:args.length).append(" ");
if (args!=null) {
- for (int a=0;a<args.length;a++) {
- line.append(args[a]).append("(").append(getConstantPool().getConstant(args[a])).append(") ");
+ for (int arg : args) {
+ line.append(arg).append("(").append(getConstantPool().getConstant(arg)).append(") ");
}
}
file.write(code, 0, code.length);
file.writeShort(exceptionTable.length);
- for (int i = 0; i < exceptionTable.length; i++) {
- exceptionTable[i].dump(file);
+ for (CodeException e : exceptionTable) {
+ e.dump(file);
}
file.writeShort(attributes.length);
- for (int i = 0; i < attributes.length; i++) {
- attributes[i].dump(file);
+ for (Attribute attribute : attributes) {
+ attribute.dump(file);
}
}
* @return LineNumberTable of Code, if it has one
*/
public LineNumberTable getLineNumberTable() {
- for (int i = 0; i < attributes.length; i++) {
- if (attributes[i].tag == Constants.ATTR_LINE_NUMBER_TABLE) {
- return (LineNumberTable) attributes[i];
+ for (Attribute attribute : attributes) {
+ if (attribute.tag == Constants.ATTR_LINE_NUMBER_TABLE) {
+ return (LineNumberTable) attribute;
}
}
return null;
* @return LocalVariableTable of Code, if it has one
*/
public LocalVariableTable getLocalVariableTable() {
- for (int i = 0; i < attributes.length; i++) {
- if (attributes[i].tag == Constants.ATTR_LOCAL_VARIABLE_TABLE) {
- return (LocalVariableTable) attributes[i];
+ for (Attribute attribute : attributes) {
+ if (attribute.tag == Constants.ATTR_LOCAL_VARIABLE_TABLE) {
+ return (LocalVariableTable) attribute;
}
}
return null;
private final int calculateLength() {
int len = 0;
if (attributes != null) {
- for (int i = 0; i < attributes.length; i++) {
- len += attributes[i].length + 6 /* attribute header size */;
+ for (Attribute attribute : attributes) {
+ len += attribute.length + 6 /* attribute header size */;
}
}
return len + getInternalLength();
if (exceptionTable.length > 0) {
buf.append("\nException handler(s) = \n" + "From\tTo\tHandler\tType\n");
- for (int i = 0; i < exceptionTable.length; i++) {
- buf.append(exceptionTable[i].toString(cpool, verbose) + "\n");
+ for (CodeException e : exceptionTable) {
+ buf.append(e.toString(cpool, verbose) + "\n");
}
}
if (attributes.length > 0) {
buf.append("\nAttribute(s) = \n");
- for (int i = 0; i < attributes.length; i++) {
- buf.append(attributes[i].toString() + "\n");
+ for (Attribute attribute : attributes) {
+ buf.append(attribute.toString() + "\n");
}
}
codeString.append(Utility.codeToString(code, cpool, 0, -1, true));
if (exceptionTable.length > 0) {
codeString.append("\n").append("Exception entries = ").append(exceptionTable.length).append("\n");
- for (int i = 0; i < exceptionTable.length; i++) {
- CodeException exc = exceptionTable[i];
+ for (CodeException exc : exceptionTable) {
int type = exc.getCatchType();
String name = "finally";
if (type != 0) {
if (annotations == null) {
// Find attributes that contain annotation data
List<AnnotationGen> accumulatedAnnotations = new ArrayList<AnnotationGen>();
- for (int i = 0; i < attributes.length; i++) {
- Attribute attribute = attributes[i];
+ for (Attribute attribute : attributes) {
if (attribute instanceof RuntimeAnnos) {
RuntimeAnnos runtimeAnnotations = (RuntimeAnnos) attribute;
accumulatedAnnotations.addAll(runtimeAnnotations.getAnnotations());
file.writeShort(superclassnameIdx);
file.writeShort(interfaces.length);
- for (int i = 0; i < interfaces.length; i++) {
- file.writeShort(interfaces[i]);
+ for (int anInterface : interfaces) {
+ file.writeShort(anInterface);
}
file.writeShort(fields.length);
- for (int i = 0; i < fields.length; i++) {
- fields[i].dump(file);
+ for (Field field : fields) {
+ field.dump(file);
}
file.writeShort(methods.length);
- for (int i = 0; i < methods.length; i++) {
- methods[i].dump(file);
+ for (Method method : methods) {
+ method.dump(file);
}
AttributeUtils.writeAttributes(attributes, file);
if (annotationsOutOfDate) {
// Find attributes that contain annotation data
List<AnnotationGen> accumulatedAnnotations = new ArrayList<AnnotationGen>();
- for (int i = 0; i < attributes.length; i++) {
- Attribute attribute = attributes[i];
+ for (Attribute attribute : attributes) {
if (attribute instanceof RuntimeAnnos) {
RuntimeAnnos runtimeAnnotations = (RuntimeAnnos) attribute;
accumulatedAnnotations.addAll(runtimeAnnotations.getAnnotations());
* @return A org.aspectj.apache.bcel.classfile.Method corresponding to java.lang.reflect.Method if any
*/
public Method getMethod(java.lang.reflect.Method m) {
- for (int i = 0; i < methods.length; i++) {
- Method method = methods[i];
-
+ for (Method method : methods) {
if (m.getName().equals(method.getName()) && m.getModifiers() == method.getModifiers()
&& Type.getSignature(m).equals(method.getSignature())) {
return method;
}
public Method getMethod(java.lang.reflect.Constructor<?> c) {
- for (int i = 0; i < methods.length; i++) {
- Method method = methods[i];
+ for (Method method : methods) {
if (method.getName().equals("<init>") && c.getModifiers() == method.getModifiers()
&& Type.getSignature(c).equals(method.getSignature())) {
return method;
if (attributes.length > 0) {
buf.append("\nAttribute(s):\n");
- for (int i = 0; i < attributes.length; i++) {
- buf.append(indent(attributes[i]));
+ for (Attribute attribute : attributes) {
+ buf.append(indent(attribute));
}
}
if (annotations != null && annotations.length > 0) {
buf.append("\nAnnotation(s):\n");
- for (int i = 0; i < annotations.length; i++) {
- buf.append(indent(annotations[i]));
+ for (AnnotationGen annotation : annotations) {
+ buf.append(indent(annotation));
}
}
if (fields.length > 0) {
buf.append("\n" + fields.length + " fields:\n");
- for (int i = 0; i < fields.length; i++) {
- buf.append("\t" + fields[i] + '\n');
+ for (Field field : fields) {
+ buf.append("\t" + field + '\n');
}
}
if (methods.length > 0) {
buf.append("\n" + methods.length + " methods:\n");
- for (int i = 0; i < methods.length; i++) {
- buf.append("\t" + methods[i] + '\n');
+ for (Method method : methods) {
+ buf.append("\t" + method + '\n');
}
}
return;
}
// Attribute[] attrs = attributes.getAttributes();
- for (int i = 0; i < attributes.length; i++) {
- if (attributes[i] instanceof InnerClasses) {
- InnerClass[] innerClasses = ((InnerClasses) attributes[i]).getInnerClasses();
- for (int j = 0; j < innerClasses.length; j++) {
+ for (Attribute attribute : attributes) {
+ if (attribute instanceof InnerClasses) {
+ InnerClass[] innerClasses = ((InnerClasses) attribute).getInnerClasses();
+ for (InnerClass innerClass : innerClasses) {
boolean innerClassAttributeRefersToMe = false;
- String inner_class_name = cpool.getConstantString(innerClasses[j].getInnerClassIndex(),
+ String inner_class_name = cpool.getConstantString(innerClass.getInnerClassIndex(),
Constants.CONSTANT_Class);
inner_class_name = Utility.compactClassName(inner_class_name);
if (inner_class_name.equals(getClassName())) {
}
if (innerClassAttributeRefersToMe) {
this.isNested = true;
- if (innerClasses[j].getInnerNameIndex() == 0) {
+ if (innerClass.getInnerNameIndex() == 0) {
this.isAnonymous = true;
}
}
JavaClass[] super_classes = getSuperClasses();
- for (int i = 0; i < super_classes.length; i++) {
- if (super_classes[i].equals(super_class)) {
+ for (JavaClass superClass : super_classes) {
+ if (superClass.equals(super_class)) {
return true;
}
}
}
}
- for (int i = 0; i < interfaces.length; i++) {
- queue.add(interfaces[i]);
+ for (JavaClass anInterface : interfaces) {
+ queue.add(anInterface);
}
}
signature = Utility.methodSignatureToString(signature, name, access, true, getLocalVariableTable());
buf = new StringBuffer(signature);
- for (int i = 0; i < attributes.length; i++) {
- Attribute a = attributes[i];
- if (!((a instanceof Code) || (a instanceof ExceptionTable)))
- buf.append(" [" + a.toString() + "]");
- }
+ for (Attribute a : attributes) {
+ if (!((a instanceof Code) || (a instanceof ExceptionTable)))
+ buf.append(" [" + a.toString() + "]");
+ }
ExceptionTable e = getExceptionTable();
if (e != null) {
// Find attributes that contain annotation data
Attribute[] attrs = getAttributes();
- for (int i = 0; i < attrs.length; i++) {
- Attribute attribute = attrs[i];
- if (attribute instanceof RuntimeVisParamAnnos) {
- parameterAnnotationsVis = (RuntimeVisParamAnnos) attribute;
- } else if (attribute instanceof RuntimeInvisParamAnnos) {
- parameterAnnotationsInvis = (RuntimeInvisParamAnnos) attribute;
- }
- }
+ for (Attribute attribute : attrs) {
+ if (attribute instanceof RuntimeVisParamAnnos) {
+ parameterAnnotationsVis = (RuntimeVisParamAnnos) attribute;
+ }
+ else if (attribute instanceof RuntimeInvisParamAnnos) {
+ parameterAnnotationsInvis = (RuntimeInvisParamAnnos) attribute;
+ }
+ }
boolean foundSome = false;
// Build a list of annotation arrays, one per argument
file.writeShort(moduleVersionIndex);
file.writeShort(requires.length);
- for (int i = 0; i < requires.length; i++) {
- file.writeShort(requires[i].moduleIndex);
- file.writeShort(requires[i].flags);
- file.writeShort(requires[i].versionIndex);
+ for (Require require : requires) {
+ file.writeShort(require.moduleIndex);
+ file.writeShort(require.flags);
+ file.writeShort(require.versionIndex);
}
file.writeShort(exports.length);
for (Export export : exports) {
public final void dump(DataOutputStream stream) throws IOException {
super.dump(stream);
stream.writeShort(packageIndices.length);
- for (int i = 0; i < packageIndices.length; i++) {
- stream.writeShort(packageIndices[i]);
+ for (int packageIndex : packageIndices) {
+ stream.writeShort(packageIndex);
}
}
@Override
public final String toString() {
StringBuffer buf = new StringBuffer();
- for (int i = 0; i < packageIndices.length; i++) {
- buf.append(cpool.getPackageName(packageIndices[i]) + "\n");
+ for (int packageIndex : packageIndices) {
+ buf.append(cpool.getPackageName(packageIndex) + "\n");
}
return buf.toString();
}
char[] ch = label.toCharArray();
StringBuffer buf = new StringBuffer();
- for (int i = 0; i < ch.length; i++) {
- switch (ch[i]) {
- case '\n':
- buf.append("\\n");
- break;
- case '\r':
- buf.append("\\r");
- break;
- case '\"':
- buf.append("\\\"");
- break;
- case '\'':
- buf.append("\\'");
- break;
- case '\\':
- buf.append("\\\\");
- break;
- default:
- buf.append(ch[i]);
- break;
+ for (char c : ch) {
+ switch (c) {
+ case '\n':
+ buf.append("\\n");
+ break;
+ case '\r':
+ buf.append("\\r");
+ break;
+ case '\"':
+ buf.append("\\\"");
+ break;
+ case '\'':
+ buf.append("\\'");
+ break;
+ case '\\':
+ buf.append("\\\\");
+ break;
+ default:
+ buf.append(c);
+ break;
}
}
public void dump(DataOutputStream dos) throws IOException {
dos.writeShort(typeIndex); // u2 index of type name in cpool
dos.writeShort(pairs.size()); // u2 element_value pair count
- for (int i = 0; i < pairs.size(); i++) {
- NameValuePair envp = pairs.get(i);
+ for (NameValuePair envp : pairs) {
envp.dump(dos);
}
}
public void dump(DataOutputStream dos) throws IOException {
dos.writeByte(type); // u1 type of value (ARRAY == '[')
dos.writeShort(evalues.length);
- for (int i = 0; i < evalues.length; i++) {
- evalues[i].dump(dos);
+ for (ElementValue evalue : evalues) {
+ evalue.dump(dos);
}
}
dos.write(annotation_data, 0, length);
} else {
dos.writeShort(annotations.size());
- for (Iterator<AnnotationGen> i = annotations.iterator(); i.hasNext();) {
- AnnotationGen ann = i.next();
+ for (AnnotationGen ann : annotations) {
ann.dump(dos);
}
}
dos.write(annotation_data,0,length);
} else {
dos.writeByte(parameterAnnotations.size());
- for (int i=0; i<parameterAnnotations.size(); i++) {
- AnnotationGen[] annotations = parameterAnnotations.get(i);
+ for (AnnotationGen[] annotations : parameterAnnotations) {
dos.writeShort(annotations.length);
- for (int j=0; j<annotations.length;j++) {
- annotations[j].dump(dos);
+ for (AnnotationGen annotation : annotations) {
+ annotation.dump(dos);
}
}
}
dos.write(annotation_data,0,length);
} else {
dos.writeShort(typeAnnotations.length);
- for (int i=0; i<typeAnnotations.length; i++) {
- typeAnnotations[i].dump(dos);
+ for (TypeAnnotationGen typeAnnotation : typeAnnotations) {
+ typeAnnotation.dump(dos);
}
}
}
case LOCAL_VARIABLE:
case RESOURCE_VARIABLE:
dos.writeShort(localVarTarget.length/3);
- for (int i=0;i<localVarTarget.length;i++) {
- dos.writeShort(localVarTarget[i]);
+ for (int j : localVarTarget) {
+ dos.writeShort(j);
}
break;
case EXCEPTION_PARAMETER:
throw new IllegalStateException("nyi "+targetType);
}
dos.writeByte(typePath.length);
- for (int i=0;i<typePath.length;i++) {
- dos.writeByte(typePath[i]);
+ for (int j : typePath) {
+ dos.writeByte(j);
}
annotation.dump(dos);
}
Field[] fields = clazz.getFields();
String[] interfaces = clazz.getInterfaceNames();
- for (int i = 0; i < interfaces.length; i++) {
- addInterface(interfaces[i]);
+ for (String anInterface : interfaces) {
+ addInterface(anInterface);
}
// OPTIMIZE Could make unpacking lazy, done on first reference
}
}
- for (int i = 0; i < methods.length; i++) {
- addMethod(methods[i]);
+ for (Method method : methods) {
+ addMethod(method);
}
- for (int i = 0; i < fields.length; i++) {
- addField(fields[i]);
+ for (Field field : fields) {
+ addField(field);
}
}
public void setMethods(Method[] methods) {
methodsList.clear();
- for (int m = 0; m < methods.length; m++)
- addMethod(methods[m]);
+ for (Method method : methods) addMethod(method);
}
public void setFields(Field[] fs) {
fieldsList.clear();
- for (int m = 0; m < fs.length; m++)
- addField(fs[m]);
+ for (Field f : fs) addField(f);
}
public void setMethodAt(Method method, int pos) {
String[] names = getInterfaceNames();
if (names != null) {
Arrays.sort(names);
- for (int i = 0; i < names.length; i++)
- dos.writeUTF(names[i]);
+ for (String name : names) dos.writeUTF(name);
}
// 4. ordered list of fields (ignoring private static and private transient fields):
Attribute[] attrs = field.getAttributes();
- for (int i = 0; i < attrs.length; i++) {
- if (attrs[i] instanceof ConstantValue) {
- setValue(((ConstantValue) attrs[i]).getConstantValueIndex());
- } else if (attrs[i] instanceof RuntimeAnnos) {
- RuntimeAnnos runtimeAnnotations = (RuntimeAnnos) attrs[i];
+ for (Attribute attr : attrs) {
+ if (attr instanceof ConstantValue) {
+ setValue(((ConstantValue) attr).getConstantValueIndex());
+ } else if (attr instanceof RuntimeAnnos) {
+ RuntimeAnnos runtimeAnnotations = (RuntimeAnnos) attr;
List<AnnotationGen> l = runtimeAnnotations.getAnnotations();
- for (Iterator<AnnotationGen> it = l.iterator(); it.hasNext();) {
- AnnotationGen element = it.next();
+ for (AnnotationGen element : l) {
addAnnotation(new AnnotationGen(element, cp, false));
}
} else {
- addAttribute(attrs[i]);
+ addAttribute(attr);
}
}
}
return new InvokeInstruction(Constants.INVOKESTATIC, index);
case Constants.INVOKEINTERFACE:
int nargs = 0;
- for (int i = 0; i < arg_types.length; i++) {
- nargs += arg_types[i].getSize();
+ for (Type arg_type : arg_types) {
+ nargs += arg_type.getSize();
}
return new INVOKEINTERFACE(index, nargs + 1, 0);
default:
case Constants.INVOKEINTERFACE:
Type[] argumentTypes = Type.getArgumentTypes(signature);
int nargs = 0;
- for (int i = 0; i < argumentTypes.length; i++) {// Count size of arguments
- nargs += argumentTypes[i].getSize();
+ for (Type argumentType : argumentTypes) {// Count size of arguments
+ nargs += argumentType.getSize();
}
return new INVOKEINTERFACE(index, nargs + 1, 0);
default:
if (i instanceof InstructionSelect) {
InstructionHandle[] targets = ((InstructionSelect) i).getTargets();
- for (int j = 0; j < targets.length; j++) {
- inst = targets[j].instruction;
+ for (InstructionHandle target : targets) {
+ inst = target.instruction;
if (!contains(inst)) {
throw new ClassGenException("Branch target of " + Constants.OPCODE_NAMES[i.opcode] + ":" + inst
+ " not in instruction list");
* @see MethodGen
*/
public void redirectLocalVariables(LocalVariableGen[] lg, InstructionHandle old_target, InstructionHandle new_target) {
- for (int i = 0; i < lg.length; i++) {
- InstructionHandle start = lg[i].getStart();
- InstructionHandle end = lg[i].getEnd();
+ for (LocalVariableGen localVariableGen : lg) {
+ InstructionHandle start = localVariableGen.getStart();
+ InstructionHandle end = localVariableGen.getEnd();
if (start == old_target) {
- lg[i].setStart(new_target);
+ localVariableGen.setStart(new_target);
}
if (end == old_target) {
- lg[i].setEnd(new_target);
+ localVariableGen.setEnd(new_target);
}
}
}
* @see MethodGen
*/
public void redirectExceptionHandlers(CodeExceptionGen[] exceptions, InstructionHandle old_target, InstructionHandle new_target) {
- for (int i = 0; i < exceptions.length; i++) {
- if (exceptions[i].getStartPC() == old_target) {
- exceptions[i].setStartPC(new_target);
+ for (CodeExceptionGen exception : exceptions) {
+ if (exception.getStartPC() == old_target) {
+ exception.setStartPC(new_target);
}
- if (exceptions[i].getEndPC() == old_target) {
- exceptions[i].setEndPC(new_target);
+ if (exception.getEndPC() == old_target) {
+ exception.setEndPC(new_target);
}
- if (exceptions[i].getHandlerPC() == old_target) {
- exceptions[i].setHandlerPC(new_target);
+ if (exception.getHandlerPC() == old_target) {
+ exception.setHandlerPC(new_target);
}
}
}
super(opcode, target);
this.targets = targets;
- for (int i = 0; i < targets.length; i++) {
- notifyTarget(null, targets[i], this);
+ for (InstructionHandle instructionHandle : targets) {
+ notifyTarget(null, instructionHandle, this);
}
this.match = match;
return true;
}
- for (int i = 0; i < targets.length; i++) {
- if (targets[i] == ih) {
+ for (InstructionHandle target : targets) {
+ if (target == ih) {
return true;
}
}
void dispose() {
super.dispose();
- for (int i = 0; i < targets.length; i++) {
- targets[i].removeTargeter(this);
+ for (InstructionHandle target : targets) {
+ target.removeTargeter(this);
}
}
.getCode()) : null, cp);
Attribute[] attributes = m.getAttributes();
- for (int i = 0; i < attributes.length; i++) {
- Attribute a = attributes[i];
+ for (Attribute attribute : attributes) {
+ Attribute a = attribute;
if (a instanceof Code) {
Code code = (Code) a;
}
Attribute[] codeAttrs = code.getAttributes();
- for (int j = 0; j < codeAttrs.length; j++) {
- a = codeAttrs[j];
+ for (Attribute codeAttr : codeAttrs) {
+ a = codeAttr;
if (a instanceof LineNumberTable) {
LineNumber[] ln = ((LineNumberTable) a).getLineNumberTable();
if (useTags) {
// abracadabra, lets create tags rather than linenumbergens.
- for (int k = 0; k < ln.length; k++) {
- LineNumber l = ln[k];
+ for (LineNumber l : ln) {
int lnum = l.getLineNumber();
if (lnum > highestLineNumber) {
highestLineNumber = lnum;
il.findHandle(l.getStartPC(), arrayOfInstructions, true).addTargeter(lt);
}
} else {
- for (int k = 0; k < ln.length; k++) {
- LineNumber l = ln[k];
+ for (LineNumber l : ln) {
addLineNumber(il.findHandle(l.getStartPC(), arrayOfInstructions, true), l.getLineNumber());
}
}
if (useTags) {
LocalVariable[] lv = ((LocalVariableTable) a).getLocalVariableTable();
- for (int k = 0; k < lv.length; k++) {
- LocalVariable l = lv[k];
+ for (LocalVariable l : lv) {
Type t = Type.getType(l.getSignature());
LocalVariableTag lvt = new LocalVariableTag(t, l.getSignature(), l.getName(), l.getIndex(), l
.getStartPC());
removeLocalVariables();
- for (int k = 0; k < lv.length; k++) {
- LocalVariable l = lv[k];
+ for (LocalVariable l : lv) {
InstructionHandle start = il.findHandle(l.getStartPC(), arrayOfInstructions);
InstructionHandle end = il.findHandle(l.getStartPC() + l.getLength(), arrayOfInstructions);
// AMC, this actually gives us the first instruction AFTER the range,
}
} else if (a instanceof ExceptionTable) {
String[] names = ((ExceptionTable) a).getExceptionNames();
- for (int j = 0; j < names.length; j++) {
- addException(names[j]);
+ for (String s : names) {
+ addException(s);
}
} else if (a instanceof RuntimeAnnos) {
RuntimeAnnos runtimeAnnotations = (RuntimeAnnos) a;
}
Attribute[] attrs = Utility.getParameterAnnotationAttributes(cp, param_annotations);
if (attrs != null) {
- for (int i = 0; i < attrs.length; i++) {
- addAttribute(attrs[i]);
+ for (Attribute attr : attrs) {
+ addAttribute(attr);
}
}
}
* Each attribute causes 6 additional header bytes
*/
int attrs_len = 0;
- for (int i = 0; i < code_attrs.length; i++) {
- attrs_len += (code_attrs[i].getLength() + 6);
+ for (Attribute code_attr : code_attrs) {
+ attrs_len += (code_attr.getLength() + 6);
}
CodeException[] c_exc = getCodeExceptions();
if ((il != null) && !isAbstract()) {
// Remove any stale code attribute
List<Attribute> attributes = getAttributes();
- for (int i = 0; i < attributes.size(); i++) {
- Attribute a = attributes.get(i);
+ for (Attribute a : attributes) {
if (a instanceof Code) {
removeAttribute(a);
}
int max = isStatic() ? 0 : 1;
if (parameterTypes != null) {
- for (int i = 0; i < parameterTypes.length; i++) {
- max += parameterTypes[i].getSize();
+ for (Type parameterType : parameterTypes) {
+ max += parameterType.getSize();
}
}
* Initially, populate the branch stack with the exception handlers, because these aren't (necessarily) branched to
* explicitly. In each case, the stack will have depth 1, containing the exception object.
*/
- for (int i = 0, max = et.length; i < max; i++) {
- InstructionHandle handlerPos = et[i].getHandlerPC();
+ for (CodeExceptionGen codeExceptionGen : et) {
+ InstructionHandle handlerPos = codeExceptionGen.getHandlerPC();
if (handlerPos != null) {
// it must be at least 1 since there is an exception handler
maxStackDepth = 1;
// explore all of the select's targets. the default target is handled below.
InstructionSelect select = (InstructionSelect) branch;
InstructionHandle[] targets = select.getTargets();
- for (int i = 0; i < targets.length; i++) {
- branchTargets.push(targets[i], stackDepth);
+ for (InstructionHandle target : targets) {
+ branchTargets.push(target, stackDepth);
}
// nothing to fall through to.
ih = null;
StringBuffer buf = new StringBuffer(signature);
if (exceptionsThrown.size() > 0) {
- for (Iterator<String> e = exceptionsThrown.iterator(); e.hasNext();) {
- buf.append("\n\t\tthrows " + e.next());
+ for (String s : exceptionsThrown) {
+ buf.append("\n\t\tthrows " + s);
}
}
private List /* AnnotationGen */<AnnotationGen> makeMutableVersion(AnnotationGen[] mutableArray) {
List<AnnotationGen> result = new ArrayList<AnnotationGen>();
- for (int i = 0; i < mutableArray.length; i++) {
- result.add(new AnnotationGen(mutableArray[i], getConstantPool(), false));
+ for (AnnotationGen annotationGen : mutableArray) {
+ result.add(new AnnotationGen(annotationGen, getConstantPool(), false));
}
return result;
}
this_sups[0] = Repository.lookupClass(thiz.getClassName());
t_sups[0] = Repository.lookupClass(other.getClassName());
- for (int i = 0; i < t_sups.length; i++) {
- for (int j = 0; j < this_sups.length; j++) {
- if (this_sups[j].equals(t_sups[i])) {
- return new ObjectType(this_sups[j].getClassName());
+ for (JavaClass t_sup : t_sups) {
+ for (JavaClass this_sup : this_sups) {
+ if (this_sup.equals(t_sup)) {
+ return new ObjectType(this_sup.getClassName());
}
}
}
StringBuffer sb = new StringBuffer("(");
Class[] params = meth.getParameterTypes(); // avoid clone
- for (int j = 0; j < params.length; j++) {
- sb.append(getType(params[j]).getSignature());
+ for (Class param : params) {
+ sb.append(getType(param).getSignature());
}
sb.append(")");
StringBuffer sb = new StringBuffer("(");
Class<?>[] params = cons.getParameterTypes(); // avoid clone
- for (int j = 0; j < params.length; j++) {
- sb.append(getType(params[j]).getSignature());
+ for (Class<?> param : params) {
+ sb.append(getType(param).getSignature());
}
sb.append(")V");
public void clear() {
processQueue();
Set<Object> keys = map.keySet();
- for (Iterator<Object> iterator = keys.iterator(); iterator.hasNext();) {
- Object name = iterator.next();
+ for (Object name : keys) {
map.remove(name);
}
}
protected Method getMethod(JavaClass cl, String methodname) {
Method[] methods = cl.getMethods();
- for (int i = 0; i < methods.length; i++) {
- Method m = methods[i];
+ for (Method m : methods) {
if (m.getName().equals(methodname)) {
return m;
}
protected Field getField(JavaClass cl, String fieldname) {
Field[] fields = cl.getFields();
- for (int i = 0; i < fields.length; i++) {
- Field f = fields[i];
+ for (Field f : fields) {
if (f.getName().equals(fieldname)) {
return f;
}
protected Attribute[] findAttribute(String name, JavaClass clazz) {
Attribute[] all = clazz.getAttributes();
List<Attribute> chosenAttrsList = new ArrayList<Attribute>();
- for (int i = 0; i < all.length; i++) {
+ for (Attribute attribute : all) {
if (verbose)
- System.err.println("Attribute: " + all[i].getName());
- if (all[i].getName().equals(name))
- chosenAttrsList.add(all[i]);
+ System.err.println("Attribute: " + attribute.getName());
+ if (attribute.getName().equals(name))
+ chosenAttrsList.add(attribute);
}
return chosenAttrsList.toArray(new Attribute[] {});
}
protected Attribute findAttribute(String name, Attribute[] all) {
List<Attribute> chosenAttrsList = new ArrayList<Attribute>();
- for (int i = 0; i < all.length; i++) {
+ for (Attribute attribute : all) {
if (verbose)
- System.err.println("Attribute: " + all[i].getName());
- if (all[i].getName().equals(name))
- chosenAttrsList.add(all[i]);
+ System.err.println("Attribute: " + attribute.getName());
+ if (attribute.getName().equals(name))
+ chosenAttrsList.add(attribute);
}
assertTrue("Should be one match: " + chosenAttrsList.size(), chosenAttrsList.size() == 1);
return chosenAttrsList.get(0);
String annotationName,String annotationElementName,String annotationElementValue) {
Field[] fields = clazz.getFields();
- for (int i = 0; i < fields.length; i++) {
- Field f = fields[i];
+ for (Field f : fields) {
AnnotationGen[] fieldAnnotations = f.getAnnotations();
if (f.getName().equals(fieldname)) {
- checkAnnotation(fieldAnnotations[0],annotationName,annotationElementName,annotationElementValue);
-
+ checkAnnotation(fieldAnnotations[0], annotationName, annotationElementName, annotationElementValue);
+
}
}
}
// helper methods
public void checkValue(AnnotationGen a,String name,String tostring) {
- for (Iterator<NameValuePair> i = a.getValues().iterator(); i.hasNext();) {
- NameValuePair element = i.next();
+ for (NameValuePair element : a.getValues()) {
if (element.getNameString().equals(name)) {
if (!element.getValue().stringifyValue().equals(tostring)) {
- fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue());
+ fail("Expected element " + name + " to have value " + tostring + " but it had value " + element.getValue().stringifyValue());
}
return;
}
assertTrue("Expected one annotation but found " + annotations.length, annotations.length == 1);
List<NameValuePair> l = annotations[0].getValues();
boolean found = false;
- for (Iterator<NameValuePair> iter = l.iterator(); iter.hasNext();) {
- NameValuePair element = iter.next();
+ for (NameValuePair element : l) {
if (element.getNameString().equals("dval")) {
if (((SimpleElementValue) element.getValue()).stringifyValue().equals("33.4"))
found = true;
public Signature getSignatureAttribute(JavaClass clazz,String name) {
Method m = getMethod(clazz,name);
Attribute[] as = m.getAttributes();
- for (int i = 0; i < as.length; i++) {
- Attribute attribute = as[i];
+ for (Attribute attribute : as) {
if (attribute.getName().equals("Signature")) {
- return (Signature)attribute;
+ return (Signature) attribute;
}
}
return null;
char[] chars = brackets.toCharArray();
int count = 0;
boolean open = false;
-
- for(int i=0; i<chars.length; i++) {
- switch(chars[i]) {
- case '[':
- if (open) throw new RuntimeException("Illegally nested brackets:" + brackets);
- open = true;
- break;
-
- case ']':
- if (!open) throw new RuntimeException("Illegally nested brackets:" + brackets);
- open = false;
- count++;
- break;
-
- default:
- }
- }
+
+ for (char aChar : chars) {
+ switch (aChar) {
+ case '[':
+ if (open) throw new RuntimeException("Illegally nested brackets:" + brackets);
+ open = true;
+ break;
+
+ case ']':
+ if (!open) throw new RuntimeException("Illegally nested brackets:" + brackets);
+ open = false;
+ count++;
+ break;
+
+ default:
+ }
+ }
if (open) throw new RuntimeException("Illegally nested brackets:" + brackets);
StringBuffer buf = new StringBuffer("(");
if (methodArgs != null) {
- for (int i=0; i < methodArgs.length; i++) {
- String str = GenericSignatureParsingTest.getSignature(methodArgs[i]);
-
- if (str.equals("V")) // void can't be a method argument
- throw new ClassFormatException("Invalid type: " + methodArgs[i]);
-
- buf.append(str);
- }
+ for (String methodArg : methodArgs) {
+ String str = GenericSignatureParsingTest.getSignature(methodArg);
+
+ if (str.equals("V")) // void can't be a method argument
+ throw new ClassFormatException("Invalid type: " + methodArg);
+
+ buf.append(str);
+ }
}
buf.append(")" + GenericSignatureParsingTest.getSignature(returnType));
public Signature getSignatureAttribute(JavaClass clazz,String name) {
Method m = getMethod(clazz,name);
Attribute[] as = m.getAttributes();
- for (int i = 0; i < as.length; i++) {
- Attribute attribute = as[i];
+ for (Attribute attribute : as) {
if (attribute.getName().equals("Signature")) {
- return (Signature)attribute;
+ return (Signature) attribute;
}
}
return null;
boolean tc1OK = false;
boolean tc2OK = false;
String errormessage = null;
- for (int i = 0; i < lvtable.length; i++) {
- String sig = Utility.signatureToString(lvtable[i].getSignature());
- if (lvtable[i].getName().equals("tc1")) {
+ for (LocalVariable localVariable : lvtable) {
+ String sig = Utility.signatureToString(localVariable.getSignature());
+ if (localVariable.getName().equals("tc1")) {
if (!sig.equals("TreasureChest<String>")) {
- errormessage="Expected signature of 'TreasureChest<String>' for tc1 but got "+sig;
+ errormessage = "Expected signature of 'TreasureChest<String>' for tc1 but got " + sig;
} else {
tc1OK = true;
}
}
- if (lvtable[i].getName().equals("tc2")) {
+ if (localVariable.getName().equals("tc2")) {
if (!sig.equals("TreasureChest<Integer>")) {
- errormessage="Expected signature of 'TreasureChest<Integer>' for tc2 but got "+sig;
+ errormessage = "Expected signature of 'TreasureChest<Integer>' for tc2 but got " + sig;
} else {
tc2OK = true;
}
String annotationName,String annotationElementName,String annotationElementValue) {
Method[] methods = clazz.getMethods();
- for (int i = 0; i < methods.length; i++) {
- Method m = methods[i];
+ for (Method m : methods) {
AnnotationGen[] methodAnnotations = m.getAnnotations();
if (m.getName().equals(methodname)) {
- checkAnnotation(methodAnnotations[0],annotationName,annotationElementName,annotationElementValue);
-
+ checkAnnotation(methodAnnotations[0], annotationName, annotationElementName, annotationElementValue);
+
}
}
}
// helper methods
public void checkValue(AnnotationGen a,String name,String tostring) {
- for (Iterator<NameValuePair> i = a.getValues().iterator(); i.hasNext();) {
- NameValuePair element = i.next();
+ for (NameValuePair element : a.getValues()) {
if (element.getNameString().equals(name)) {
if (!element.getValue().stringifyValue().equals(tostring)) {
- fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue());
+ fail("Expected element " + name + " to have value " + tostring + " but it had value " + element.getValue().stringifyValue());
}
return;
}
private Method findMethod(ClassGen c,String mname) {
Method[] ms = c.getMethods();
- for (int i = 0; i < ms.length; i++) {
- if (ms[i].getName().equals(mname)) return ms[i];
+ for (Method m : ms) {
+ if (m.getName().equals(mname)) return m;
}
return null;
}
}
private void checkValue(AnnotationGen a,String name,String tostring) {
- for (Iterator<NameValuePair> i = a.getValues().iterator(); i.hasNext();) {
- NameValuePair element = i.next();
+ for (NameValuePair element : a.getValues()) {
if (element.getNameString().equals(name)) {
if (!element.getValue().stringifyValue().equals(tostring)) {
- fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue());
+ fail("Expected element " + name + " to have value " + tostring + " but it had value " + element.getValue().stringifyValue());
}
return;
}
public static List<String> getListOfAnnotationNames(AnnotationGen a) {
List<NameValuePair> l = a.getValues();
List<String> names = new ArrayList<String>();
- for (Iterator<NameValuePair> i = l.iterator(); i.hasNext();) {
- NameValuePair element = i.next();
+ for (NameValuePair element : l) {
names.add(element.getNameString());
}
return names;
Attribute[] rvaAttr = findAttribute("RuntimeVisibleParameterAnnotations",clazz);
Method[] methods = clazz.getMethods();
- for (int i = 0; i < methods.length; i++) {
- Method m = methods[i];
+ for (Method m : methods) {
if (m.getName().equals("foo")) {
- RuntimeVisParamAnnos paramAnns =
- (RuntimeVisParamAnnos) findAttribute("RuntimeVisibleParameterAnnotations",m.getAttributes());
- assertTrue("foo takes two parameters, not "+paramAnns.getParameterAnnotations().size(),
- paramAnns.getParameterAnnotations().size()==2);
+ RuntimeVisParamAnnos paramAnns =
+ (RuntimeVisParamAnnos) findAttribute("RuntimeVisibleParameterAnnotations", m.getAttributes());
+ assertTrue("foo takes two parameters, not " + paramAnns.getParameterAnnotations().size(),
+ paramAnns.getParameterAnnotations().size() == 2);
AnnotationGen[] firstParamAnnotations = paramAnns.getAnnotationsOnParameter(0);
- checkAnnotation(firstParamAnnotations[0],"SimpleAnnotation","id","2");
+ checkAnnotation(firstParamAnnotations[0], "SimpleAnnotation", "id", "2");
AnnotationGen[] secondParamAnnotations = paramAnns.getAnnotationsOnParameter(1);
- checkAnnotation(secondParamAnnotations[0],"SimpleAnnotation","id","3");
- checkAnnotation(secondParamAnnotations[1],"AnnotationEnumElement","enumval","LSimpleEnum;Red");
-
+ checkAnnotation(secondParamAnnotations[0], "SimpleAnnotation", "id", "3");
+ checkAnnotation(secondParamAnnotations[1], "AnnotationEnumElement", "enumval", "LSimpleEnum;Red");
+
}
if (m.getName().equals("main")) {
- RuntimeVisParamAnnos paramAnns =
- (RuntimeVisParamAnnos) findAttribute("RuntimeVisibleParameterAnnotations",m.getAttributes());
- assertTrue("main takes one parameter, not "+paramAnns.getParameterAnnotations().size(),
- paramAnns.getParameterAnnotations().size()==1);
+ RuntimeVisParamAnnos paramAnns =
+ (RuntimeVisParamAnnos) findAttribute("RuntimeVisibleParameterAnnotations", m.getAttributes());
+ assertTrue("main takes one parameter, not " + paramAnns.getParameterAnnotations().size(),
+ paramAnns.getParameterAnnotations().size() == 1);
AnnotationGen[] firstParamAnnotations = paramAnns.getAnnotationsOnParameter(0);
- checkAnnotation(firstParamAnnotations[0],"SimpleAnnotation","id","1");
+ checkAnnotation(firstParamAnnotations[0], "SimpleAnnotation", "id", "1");
}
}
}
public void checkFooMethod(JavaClass clazz) {
Method[] methods = clazz.getMethods();
- for (int i = 0; i < methods.length; i++) {
- Method m = methods[i];
+ for (Method m : methods) {
if (m.getName().equals("foo")) {
AnnotationGen[] firstParamAnnotations = m.getAnnotationsOnParameter(0);
- checkAnnotation(firstParamAnnotations[0],"SimpleAnnotation","id","2");
+ checkAnnotation(firstParamAnnotations[0], "SimpleAnnotation", "id", "2");
AnnotationGen[] secondParamAnnotations = m.getAnnotationsOnParameter(1);
- checkAnnotation(secondParamAnnotations[0],"SimpleAnnotation","id","3");
- checkAnnotation(secondParamAnnotations[1],"AnnotationEnumElement","enumval","LSimpleEnum;Red");
-
+ checkAnnotation(secondParamAnnotations[0], "SimpleAnnotation", "id", "3");
+ checkAnnotation(secondParamAnnotations[1], "AnnotationEnumElement", "enumval", "LSimpleEnum;Red");
+
}
}
}
// helper methods
public void checkValue(AnnotationGen a,String name,String tostring) {
- for (Iterator<NameValuePair> i = a.getValues().iterator(); i.hasNext();) {
- NameValuePair element = i.next();
+ for (NameValuePair element : a.getValues()) {
if (element.getNameString().equals(name)) {
if (!element.getValue().stringifyValue().equals(tostring)) {
- fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue());
+ fail("Expected element " + name + " to have value " + tostring + " but it had value " + element.getValue().stringifyValue());
}
return;
}
public void checkMarkedVarargs(JavaClass clazz,String methodname,boolean shouldBeMarked) {
Method[] methods = clazz.getMethods();
- for (int i = 0; i < methods.length; i++) {
- Method m = methods[i];
+ for (Method m : methods) {
if (m.getName().equals(methodname)) {
- assertTrue("Method '"+methodname+"' should answer varargs="+shouldBeMarked,
- m.isVarargs()==shouldBeMarked);
+ assertTrue("Method '" + methodname + "' should answer varargs=" + shouldBeMarked,
+ m.isVarargs() == shouldBeMarked);
}
}
}
// helper methods
public void checkValue(AnnotationGen a,String name,String tostring) {
- for (Iterator<NameValuePair> i = a.getValues().iterator(); i.hasNext();) {
- NameValuePair element = i.next();
+ for (NameValuePair element : a.getValues()) {
if (element.getNameString().equals(name)) {
if (!element.getValue().stringifyValue().equals(tostring)) {
- fail("Expected element "+name+" to have value "+tostring+" but it had value "+element.getValue().stringifyValue());
+ fail("Expected element " + name + " to have value " + tostring + " but it had value " + element.getValue().stringifyValue());
}
return;
}
return true;
}
boolean result = true;
- for (int i = 0; i < sources.length; i++) {
- if (!sink.handleMessage(sources[i])) {
+ for (IMessage source : sources) {
+ if (!sink.handleMessage(source)) {
if (fastFail) {
return false;
}
public void testKind_isSameOrLessThan() {
IMessage.Kind last;
IMessage.Kind next = null;
- for (Iterator<IMessage.Kind> iter = IMessage.KINDS.iterator(); iter.hasNext();) {
- last = next;
- next = iter.next();
- if (null == last) {
- continue;
- }
- String label = "last: " + last + " next: " + next;
- assertTrue(label, !next.isSameOrLessThan(null));
- assertTrue(label, !next.isSameOrLessThan(last));
- assertTrue(label, last.isSameOrLessThan(next));
- assertTrue(label, next.isSameOrLessThan(next));
- }
+ for (IMessage.Kind kind : IMessage.KINDS) {
+ last = next;
+ next = kind;
+ if (null == last) {
+ continue;
+ }
+ String label = "last: " + last + " next: " + next;
+ assertTrue(label, !next.isSameOrLessThan(null));
+ assertTrue(label, !next.isSameOrLessThan(last));
+ assertTrue(label, last.isSameOrLessThan(next));
+ assertTrue(label, next.isSameOrLessThan(next));
+ }
}
public void testMessageHandler() {
public boolean isTextFile(File file) {
String name = file.getName();
- for (int i = 0; i < TEXT_EXTENSIONS.length; i++) {
- if (name.endsWith(TEXT_EXTENSIONS[i])) {
+ for (String textExtension : TEXT_EXTENSIONS) {
+ if (name.endsWith(textExtension)) {
return true;
}
}
paths = unixPaths;
}
- for (int suffixIndex = 0; suffixIndex < suffixes.length; suffixIndex++) {
- String suffix = suffixes[suffixIndex];
- for (int prefixIndex = 0; prefixIndex < paths.length; prefixIndex++) {
- String prefix = paths[prefixIndex];
+ for (String suffix : suffixes) {
+ for (String path : paths) {
+ String prefix = path;
prefix = applyProperties(prefix);
File test = new File(prefix + suffix);
if (isLegalJavaHome(test)) {
StringBuffer buf = new StringBuffer();
buf.append(contentsBytes);
buf.append(NEWLINE);
- for (Iterator<String> i = contentsNames.iterator(); i.hasNext(); ) {
- String name = i.next();
- buf.append(name);
- buf.append(NEWLINE);
- }
+ for (String name : contentsNames) {
+ buf.append(name);
+ buf.append(NEWLINE);
+ }
zipFile(new StringBufferInputStream(buf.toString()), zOut, CONTENTS_FILE, System.currentTimeMillis());
}
}
protected void writeDirs(ZipOutputStream zOut, String[] dirs) throws IOException {
- for (int i = 0; i < dirs.length; i++) {
- File f = new File(baseDir,dirs[i]);
- String name = dirs[i].replace(File.separatorChar,'/')+"/";
- zipDir(f, zOut, name);
- }
+ for (String dir : dirs) {
+ File f = new File(baseDir, dir);
+ String name = dir.replace(File.separatorChar, '/') + "/";
+ zipDir(f, zOut, name);
+ }
}
protected void writeFiles(ZipOutputStream zOut, String[] files) throws IOException {
- for (int i = 0; i < files.length; i++) {
- File f = new File(baseDir,files[i]);
- String name = files[i].replace(File.separatorChar,'/');
- zipFile(f, zOut, name);
- }
+ for (String file : files) {
+ File f = new File(baseDir, file);
+ String name = file.replace(File.separatorChar, '/');
+ zipFile(f, zOut, name);
+ }
}
}
Result[] reqs = result.getRequired();
StringBuffer depends = new StringBuffer();
boolean first = true;
- for (int i = 0; i < reqs.length; i++) {
- Result reqResult = reqs[i];
+ for (Result reqResult : reqs) {
if (!first) {
depends.append(",");
} else {
targets.put(resultTargetName, target);
// then recursively add any required results
- for (int i = 0; i < reqs.length; i++) {
- Result reqResult = reqs[i];
+ for (Result reqResult : reqs) {
makeTargetsForResult(reqResult, targets);
}
}
public boolean setupClasspath(Result result, Path classpath) { // XXX fix test access
boolean hasLibraries = false;
// required libraries
- for (Iterator<File> iter = result.getLibJars().iterator(); iter.hasNext();) {
- File file = iter.next();
+ for (File file : result.getLibJars()) {
classpath.createPathElement().setLocation(file);
if (!hasLibraries) {
hasLibraries = true;
// Westodo Kind kind = result.getKind();
Result[] reqs = result.getRequired();
// required modules and their exported libraries
- for (int i = 0; i < reqs.length; i++) {
- Result requiredResult = reqs[i];
+ for (Result requiredResult : reqs) {
classpath.createPathElement().setLocation(requiredResult.getOutputFile());
if (!hasLibraries) {
hasLibraries = true;
}
// also put on classpath libraries exported from required module
// XXX exported modules not supported
- for (Iterator<File> iterator = requiredResult.getExportedLibJars().iterator(); iterator.hasNext();) {
- classpath.createPathElement().setLocation(iterator.next());
+ for (File file : requiredResult.getExportedLibJars()) {
+ classpath.createPathElement().setLocation(file);
}
}
return hasLibraries;
return new Result[0];
}
ArrayList<String> toReturn = new ArrayList<String>();
- for (Iterator<Target> iter = result.iterator(); iter.hasNext();) {
- Target target = iter.next();
+ for (Target target : result) {
String name = target.getName();
if (null == name) {
throw new Error("null name?");
return isOneOf(prop, trues) || isOneOf(prop, complement(falses));
}
private boolean isOneOf(String prop, String[] strings) {
- for (int i = 0; i < strings.length; i++) {
- if (strings[i].equals(prop)) {
- return true;
- }
- }
+ for (String string : strings) {
+ if (string.equals(prop)) {
+ return true;
+ }
+ }
return false;
}
private String[] complement(String[] strings) {
log("stripping " + files.length + " files");
int stripped = 0;
- for (int i = 0, len = files.length; i < len; i++) {
- if (processFile(files[i])) {
- stripped++;
- } else {
- log(files[i] + " not stripped");
- }
- }
+ for (String file : files) {
+ if (processFile(file)) {
+ stripped++;
+ } else {
+ log(file + " not stripped");
+ }
+ }
log(stripped + " files successfully stripped");
}
} finally {
if (0 < errors.size()) {
String label = "error building " + buildSpec + ": ";
- for (Iterator<String> iter = errors.iterator(); iter.hasNext();) {
- String m = label + iter.next();
- handler.error(m);
- }
+ for (String error : errors) {
+ String m = label + error;
+ handler.error(m);
+ }
}
}
}
*/
public boolean cleanup() {
boolean noErr = true;
- for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) {
- File file = (File) iter.next();
- if (!Util.deleteContents(file) || !file.delete()) {
- if (noErr) {
- noErr = false;
- }
- handler.log("unable to clean up " + file);
- }
- }
+ for (Object tempFile : tempFiles) {
+ File file = (File) tempFile;
+ if (!Util.deleteContents(file) || !file.delete()) {
+ if (noErr) {
+ noErr = false;
+ }
+ handler.log("unable to clean up " + file);
+ }
+ }
return noErr;
}
if (isLogging()) {
handler.log("modules to build: " + Arrays.asList(buildList));
}
- for (int i = 0; i < buildList.length; i++) {
- Result required = buildList[i];
- if (!buildingEnabled) {
- return false;
- }
- String requiredName = required.getName();
- if (!doneList.contains(requiredName)) {
- doneList.add(requiredName);
- if (!buildOnly(required, errors)) {
- return false;
- }
- }
- }
+ for (Result required : buildList) {
+ if (!buildingEnabled) {
+ return false;
+ }
+ String requiredName = required.getName();
+ if (!doneList.contains(requiredName)) {
+ doneList.add(requiredName);
+ if (!buildOnly(required, errors)) {
+ return false;
+ }
+ }
+ }
}
return true;
}
handler);
ProductModule[] productModules = discoverModules(buildSpec.productDir,
modules);
- for (int i = 0; i < productModules.length; i++) {
- if (buildSpec.verbose) {
- handler.log("building product module " + productModules[i]);
- }
- if (!buildProductModule(productModules[i])) {
- return false;
- }
- }
+ for (ProductModule module : productModules) {
+ if (buildSpec.verbose) {
+ handler.log("building product module " + module);
+ }
+ if (!buildProductModule(module)) {
+ return false;
+ }
+ }
if (buildSpec.verbose) {
handler.log("assembling product module for " + buildSpec);
}
String excludes = null;
{
StringBuffer buf = new StringBuffer();
- for (int i = 0; i < productModules.length; i++) {
- if (0 < buf.length()) {
- buf.append(",");
- }
- buf.append(productModules[i].relativePath);
- }
+ for (ProductModule productModule : productModules) {
+ if (0 < buf.length()) {
+ buf.append(",");
+ }
+ buf.append(productModule.relativePath);
+ }
if (0 < buf.length()) {
excludes = buf.toString();
}
}
// copy binaries associated with module flag files
- for (int i = 0; i < productModules.length; i++) {
- final ProductModule product = productModules[i];
- final Kind kind = Result.kind(Result.NORMAL, product.assembleAll);
- Result result = product.module.getResult(kind);
- String targPath = Util.path(targDirPath, product.relativePath);
- File jarFile = result.getOutputFile();
- copyFile(jarFile, new File(targPath), FILTER_OFF);
- }
+ for (final ProductModule product : productModules) {
+ final Kind kind = Result.kind(Result.NORMAL, product.assembleAll);
+ Result result = product.module.getResult(kind);
+ String targPath = Util.path(targDirPath, product.relativePath);
+ File jarFile = result.getOutputFile();
+ copyFile(jarFile, new File(targPath), FILTER_OFF);
+ }
handler.log("created product in " + targDir);
// ---- create installer
Result result = module.module.getResult(productKind);
return buildAll(result, errors);
} finally {
- for (Iterator<String> iter = errors.iterator(); iter.hasNext();) {
- handler.error("error building " + module + ": " + iter.next());
- }
+ for (String error : errors) {
+ handler.error("error building " + module + ": " + error);
+ }
}
}
File library = liter.next();
final String fname = library.getName();
if (null != fname) {
- for (Iterator<String> iter = SKIP_LIBRARIES.iterator(); iter.hasNext();) {
- String name = iter.next();
- if (fname.equals(name)) {
- liter.remove();
- break;
- }
- }
+ for (String name : SKIP_LIBRARIES) {
+ if (fname.equals(name)) {
+ liter.remove();
+ break;
+ }
+ }
}
}
}
return;
}
File[] files = srcDir.listFiles();
- for (int i = 0; i < files.length; i++) {
- if (files[i].isDirectory()) {
- sourceFiles(files[i], result);
- } else if (isSourceFile(files[i])) {
- result.add(files[i]);
- }
- }
+ for (File file : files) {
+ if (file.isDirectory()) {
+ sourceFiles(file, result);
+ } else if (isSourceFile(file)) {
+ result.add(file);
+ }
+ }
}
private static void addIfNew(List<File> source, List<File> sink) {
addIfNew(result.getLibJars(), known);
addIfNew(result.getExportedLibJars(), known);
Result[] reqs = result.getRequired();
- for (int i = 0; i < reqs.length; i++) {
- Result requiredResult = reqs[i];
- File requiredJar = requiredResult.getOutputFile();
- if (!known.contains(requiredJar)) {
- known.add(requiredJar);
- doFindJarRequirements(requiredResult, known);
- }
- }
+ for (Result requiredResult : reqs) {
+ File requiredJar = requiredResult.getOutputFile();
+ if (!known.contains(requiredJar)) {
+ known.add(requiredJar);
+ doFindJarRequirements(requiredResult, known);
+ }
+ }
}
/** @return true if this is a source file */
}
final long time = outputFile.lastModified();
File file;
- for (Iterator<File> iter = result.getSrcDirs().iterator(); iter.hasNext();) {
- File srcDir = iter.next();
- for (Iterator<File> srcFiles = sourceFiles(srcDir); srcFiles.hasNext();) {
- file = srcFiles.next();
- if (outOfDate(time, file)) {
- return true;
- }
- }
- }
+ for (File srcDir : result.getSrcDirs()) {
+ for (Iterator<File> srcFiles = sourceFiles(srcDir); srcFiles.hasNext(); ) {
+ file = srcFiles.next();
+ if (outOfDate(time, file)) {
+ return true;
+ }
+ }
+ }
// required modules
Result[] reqs = result.getRequired();
- for (int i = 0; i < reqs.length; i++) {
- Result requiredResult = reqs[i];
- file = requiredResult.getOutputFile();
- if (outOfDate(time, file)) {
- return true;
- }
- }
+ for (Result requiredResult : reqs) {
+ file = requiredResult.getOutputFile();
+ if (outOfDate(time, file)) {
+ return true;
+ }
+ }
// libraries
- for (Iterator<File> iter = result.getLibJars().iterator(); iter.hasNext();) {
- file = iter.next();
- if (outOfDate(time, file)) {
- return true;
- }
- }
+ for (File value : result.getLibJars()) {
+ file = value;
+ if (outOfDate(time, file)) {
+ return true;
+ }
+ }
return false;
}
Util.closeSilently(fin);
}
RequiredBundle[] bundles = bundle.getRequiredBundles();
- for (int i = 0; i < bundles.length; i++) {
- RequiredBundle required = bundles[i];
- update("src", "/" + required.name, required.text, false);
- }
+ for (RequiredBundle required : bundles) {
+ update("src", "/" + required.name, required.text, false);
+ }
String[] libs = bundle.getClasspath();
- for (int i = 0; i < libs.length; i++) {
- update("lib", libs[i], libs[i], false);
- }
+ for (String lib : libs) {
+ update("lib", lib, lib, false);
+ }
return true;
}
private void warnVariable(String path, String toString) {
String[] known = { "JRE_LIB", "ASPECTJRT_LIB", "JRE15_LIB" };
- for (int i = 0; i < known.length; i++) {
- if (known[i].equals(path)) {
- return;
- }
- }
+ for (String s : known) {
+ if (s.equals(path)) {
+ return;
+ }
+ }
messager.log("Module cannot handle var yet: " + toString);
}
public void acceptLine(String line) {
String[] tokens = tokenize(line);
- for (int i = 0; i < tokens.length; i++) {
- next(tokens[i]);
- }
+ for (String token : tokens) {
+ next(token);
+ }
}
private Properties attributesToProperties() {
return;
}
Samples result = new Samples();
- for (int i = 0; i < args.length; i++) {
- result = gather(new File(args[i]), result);
- }
+ for (String arg : args) {
+ result = gather(new File(arg), result);
+ }
StringBuffer sb = HTMLSamplesRenderer.ME.render(result, null);
}
} else if (source.isDirectory() && source.canRead()) {
File[] files = source.listFiles();
- for (int i = 0; i < files.length; i++) {
- doGather(files[i], sink);
- }
+ for (File file : files) {
+ doGather(file, sink);
+ }
}
}
}
String path = file.getName().toLowerCase();
String[] suffixes = Sample.Kind.SOURCE_SUFFIXES;
- for (int i = 0; i < suffixes.length; i++) {
- if (path.endsWith(suffixes[i])) {
- return true;
- }
- }
+ for (String suffix : suffixes) {
+ if (path.endsWith(suffix)) {
+ return true;
+ }
+ }
return false;
}
public static final String COPYRIGHT =
"<p><small>Copyright 2003 Contributors. All Rights Reserved. "
- + "This sample code is made available under the Common Public "\r + "License version 1.0 available at "
+ + "This sample code is made available under the Common Public "
+ + "License version 1.0 available at "
+ "<a href=\"http://www.eclipse.org/legal/epl-v10.html\">"
+ "http://www.eclipse.org/legal/epl-v10.html</a>."
+ "Contributors are listed in this document as authors. "
startList(samples, sink);
List<Sample> list = samples.getSortedSamples();
String anchorName = null;
- for (ListIterator<Sample> iter = list.listIterator();
- iter.hasNext();) {
- Sample sample = iter.next();
- String newAnchorName = sample.anchorName;
- if ((null == anchorName)
- || (!anchorName.equals(newAnchorName))) {
- endAnchorName(anchorName, sink);
- startAnchorName(newAnchorName, sample.anchorTitle, sink);
- anchorName = newAnchorName;
- }
- render(sample, sink);
- }
+ for (Sample sample : list) {
+ String newAnchorName = sample.anchorName;
+ if ((null == anchorName)
+ || (!anchorName.equals(newAnchorName))) {
+ endAnchorName(anchorName, sink);
+ startAnchorName(newAnchorName, sample.anchorTitle, sink);
+ anchorName = newAnchorName;
+ }
+ render(sample, sink);
+ }
endAnchorName(anchorName, sink);
endList(samples, sink);
return sink;
sampleSection.append(EOL);
if (doFlags) {
boolean flagHeaderDone = false;
- for (Iterator iter = sample.flags.iterator(); iter.hasNext();) {
- String flag = (String) iter.next();
- if (!flagHeaderDone) {
- sampleSection.append("<p>Comments flagged:<ul>");
- sampleSection.append(EOL);
- flagHeaderDone = true;
- }
- sampleSection.append("<li>");
- sampleSection.append(flag);
- sampleSection.append("</li>");
- }
+ for (String flag : sample.flags) {
+ if (!flagHeaderDone) {
+ sampleSection.append("<p>Comments flagged:<ul>");
+ sampleSection.append(EOL);
+ flagHeaderDone = true;
+ }
+ sampleSection.append("<li>");
+ sampleSection.append(flag);
+ sampleSection.append("</li>");
+ }
if (flagHeaderDone) {
sampleSection.append("</ul>");
sampleSection.append(EOL);
sink.append("<h2><a name=\"authorIndex\"></a>Author Index</h2>");
List<Sample> list = samples.getSortedSamples(Sample.AUTHOR_NAME_SOURCE_COMPARER);
String lastAuthor = null;
- for (ListIterator<Sample> iter = list.listIterator(); iter.hasNext();) {
- Sample sample = iter.next();
- String author = sample.author;
- if (!author.equals(lastAuthor)) {
- if (null != lastAuthor) {
- sink.append("</li></ul>");
- }
- sink.append("<li>");
- sink.append(author);
- sink.append(EOL);
- sink.append("<ul>");
- sink.append(EOL);
- lastAuthor = author;
- }
- sink.append(" <li><a href=\"#");
- sink.append(sample.anchorName);
- sink.append("\">");
- if (null == sample.anchorTitle) {
- sink.append(sample.anchorName);
- } else {
- sink.append(sample.anchorTitle);
- }
- sink.append("</a></li>");
- }
+ for (Sample sample : list) {
+ String author = sample.author;
+ if (!author.equals(lastAuthor)) {
+ if (null != lastAuthor) {
+ sink.append("</li></ul>");
+ }
+ sink.append("<li>");
+ sink.append(author);
+ sink.append(EOL);
+ sink.append("<ul>");
+ sink.append(EOL);
+ lastAuthor = author;
+ }
+ sink.append(" <li><a href=\"#");
+ sink.append(sample.anchorName);
+ sink.append("\">");
+ if (null == sample.anchorTitle) {
+ sink.append(sample.anchorName);
+ } else {
+ sink.append(sample.anchorTitle);
+ }
+ sink.append("</a></li>");
+ }
}
}
public static void simpleRender(Samples result, StringBuffer sink) {
List sortedSamples = result.getSortedSamples();
int i = 0;
- for (ListIterator iter = sortedSamples.listIterator();
- iter.hasNext();) {
- Sample sample = (Sample) iter.next();
- sink.append(i++ + ": " + sample);
- }
+ for (Object sortedSample : sortedSamples) {
+ Sample sample = (Sample) sortedSample;
+ sink.append(i++ + ": " + sample);
+ }
}
/** result struct for getPackagePath */
return false;
} else if (dir.isDirectory()) {
File[] files = dir.listFiles();
- for (int i = 0; i < files.length; i++) {
- if (!deleteContents(files[i]) || !files[i].delete()) {
- return false;
- }
+ for (File file : files) {
+ if (!deleteContents(file) || !file.delete()) {
+ return false;
+ }
}
}
return true;
if ((hits != expected.length) || (hits != actual.length)) {
sb.append("unexpected [");
String prefix = "";
- for (int i = 0; i < actual.length; i++) {
- if (null != actual[i]) {
- sb.append(prefix);
- prefix = ", ";
- sb.append("\"");
- sb.append(actual[i]);
- sb.append("\"");
- }
- }
+ for (String value : actual) {
+ if (null != value) {
+ sb.append(prefix);
+ prefix = ", ";
+ sb.append("\"");
+ sb.append(value);
+ sb.append("\"");
+ }
+ }
sb.append("] missing [");
prefix = "";
- for (int i = 0; i < expected.length; i++) {
- if (null != expected[i]) {
- sb.append(prefix);
- prefix = ", ";
- sb.append("\"");
- sb.append(expected[i]);
- sb.append("\"");
- }
- }
+ for (String s : expected) {
+ if (null != s) {
+ sb.append(prefix);
+ prefix = ", ";
+ sb.append("\"");
+ sb.append(s);
+ sb.append("\"");
+ }
+ }
sb.append("]");
return true;
}
public void testLicense_org_eclipse_jdt_core() {
final String mod = "org.eclipse.jdt.core";
final String pre = BASE_DIR + mod + File.separator;
- for (int i = 0; i < JDT_SOURCE_DIRS.length; i++) {
- checkSourceDirectory(new File(pre + JDT_SOURCE_DIRS[i]), mod);
+ for (String jdtSourceDir : JDT_SOURCE_DIRS) {
+ checkSourceDirectory(new File(pre + jdtSourceDir), mod);
}
}
void checkLicense(String module) {
File moduleDir = new File(Util.path("..", module));
File[] srcDirs = findSourceRoots(moduleDir);
- for (int i = 0; i < srcDirs.length; i++) {
- System.out.println(srcDirs[i]);
- checkSourceDirectory(srcDirs[i], module);
- }
+ for (File srcDir : srcDirs) {
+ System.out.println(srcDir);
+ checkSourceDirectory(srcDir, module);
+ }
}
void checkSourceDirectory(File srcDir, String module) {
}
void unknownFiles(File dir, ArrayList<File> results) {
File[] files = dir.listFiles(this);
- for (int j = 0; j < files.length; j++) {
- File file = files[j];
- if (file.isDirectory()) {
- String name = file.getName();
- if (!("CVS".equals(name))) {
- unknownFiles(file, results);
- }
- } else {
- results.add(file);
- }
- }
+ for (File file : files) {
+ if (file.isDirectory()) {
+ String name = file.getName();
+ if (!("CVS".equals(name))) {
+ unknownFiles(file, results);
+ }
+ } else {
+ results.add(file);
+ }
+ }
}
}
}
protected void deleteTempFiles() {
- for (Iterator iter = tempFiles.iterator(); iter.hasNext();) {
- File file = (File) iter.next();
- if (!Util.delete(file)) {
- File[] list = file.listFiles();
- if (!Util.isEmpty(list)) {
- StringBuffer sb = new StringBuffer();
- sb.append("warning: BuildModuleTest unable to delete ");
- sb.append(file.toString());
- sb.append("\n"); // XXX platform
- for (int i = 0; i < list.length; i++) {
- sb.append(" ");
- sb.append(list[i].toString());
- sb.append("\n"); // XXX platform
- }
- System.err.println(sb.toString());
- }
- }
- }
+ for (File file : tempFiles) {
+ if (!Util.delete(file)) {
+ File[] list = file.listFiles();
+ if (!Util.isEmpty(list)) {
+ StringBuffer sb = new StringBuffer();
+ sb.append("warning: BuildModuleTest unable to delete ");
+ sb.append(file.toString());
+ sb.append("\n"); // XXX platform
+ for (File value : list) {
+ sb.append(" ");
+ sb.append(value.toString());
+ sb.append("\n"); // XXX platform
+ }
+ System.err.println(sb.toString());
+ }
+ }
+ }
}
public void testAllJunitTests() {
printedMessage = true;
}
if (debugging()) {
- for (int i = 0; i < DEBUGS.length; i++) {
- if (target.equals(DEBUGS[i])) {
- return true;
- }
- }
+ for (String debug : DEBUGS) {
+ if (target.equals(debug)) {
+ return true;
+ }
+ }
return false;
} else {
- for (int i = 0; i < SKIPS.length; i++) {
- if (SKIPS[i].equals(target)) {
- if (printInfoMessages) {
- System.err.println(target + " skipped build test [" + getClass().getName() + ".shouldBuild(..)]");
- }
- return false;
- }
- }
+ for (String skip : SKIPS) {
+ if (skip.equals(target)) {
+ if (printInfoMessages) {
+ System.err.println(target + " skipped build test [" + getClass().getName() + ".shouldBuild(..)]");
+ }
+ return false;
+ }
+ }
}
return building;
}
java.setClasspath(cp);
java.setClassname(classname);
if (null != args) {
- for (int i = 0; i < args.length; i++) {
- Argument arg = java.createArg();
- arg.setValue(args[i]);
- }
+ for (String s : args) {
+ Argument arg = java.createArg();
+ arg.setValue(s);
+ }
}
try {
java.execute();
} else {
File[] files = file.listFiles();
boolean result = true;
- for (int i = 0; i < files.length; i++) {
- if (!ModulesTest.delete(files[i])
- && result) {
- result = false;
- }
- }
+ for (File value : files) {
+ if (!ModulesTest.delete(value)
+ && result) {
+ result = false;
+ }
+ }
return (file.delete() && result);
}
}
protected void tearDown() throws Exception {
super.tearDown();
- for (Iterator<File> iter = tempFiles.iterator(); iter.hasNext();) {
- File file = (File) iter.next();
- if (!ModulesTest.delete(file)) {
- System.err.println("warning: ModulesTest unable to delete " + file);
- }
+ for (File file : tempFiles) {
+ if (!ModulesTest.delete(file)) {
+ System.err.println("warning: ModulesTest unable to delete " + file);
+ }
}
}
File libDir = new File(distDir, "tools/lib");
String[] jars = { "tools", "rt", "weaver", "lib"};
- for (int i = 0; i < jars.length; i++) {
- File jar = new File(libDir, "aspectj" + jars[i] + ".jar");
- assertTrue(jar.getPath(), jar.canRead());
- if (10 > jar.length()) {
- assertTrue(jar + " too small", false);
- }
- }
+ for (String s : jars) {
+ File jar = new File(libDir, "aspectj" + s + ".jar");
+ assertTrue(jar.getPath(), jar.canRead());
+ if (10 > jar.length()) {
+ assertTrue(jar + " too small", false);
+ }
+ }
}
/**
* Show messages from the task.
"aspectjrt" }) {
void checkOthers(OSGIBundle osgiBundle, StringBuffer sb) {
RequiredBundle[] bundles = osgiBundle.getRequiredBundles();
- for (int i = 0; i < bundles.length; i++) {
- RequiredBundle bundle = bundles[i];
- if ("aspectjrt".equals(bundle.name)) {
- if (!bundle.optional) {
- sb
- .append("expected required bundle aspectjrt to be optional");
- }
- String version = "[1.5.0,1.5.5]";
- if (!(version.equals(bundle.versions))) {
- sb.append("expected version " + version
- + " got " + bundle.versions
- + " for required bundle aspectjrt");
- }
- }
- }
+ for (RequiredBundle bundle : bundles) {
+ if ("aspectjrt".equals(bundle.name)) {
+ if (!bundle.optional) {
+ sb
+ .append("expected required bundle aspectjrt to be optional");
+ }
+ String version = "[1.5.0,1.5.5]";
+ if (!(version.equals(bundle.versions))) {
+ sb.append("expected version " + version
+ + " got " + bundle.versions
+ + " for required bundle aspectjrt");
+ }
+ }
+ }
}
} };
/** disabled pending research */
public void skip_testOSGIManifests() throws Exception {
StringBuffer sb = new StringBuffer();
- for (int i = 0; i < TESTS.length; i++) {
- TESTS[i].run(sb);
- }
+ for (ManifestTest test : TESTS) {
+ test.run(sb);
+ }
if (0 < sb.length()) {
fail(sb.toString());
}
System.err.println("Weaver adaptors before queue processing:");
Map<AdaptorKey,ExplicitlyInitializedClassLoaderWeavingAdaptor> m = WeaverContainer.weavingAdaptors;
Set<AdaptorKey> keys = m.keySet();
- for (Iterator<AdaptorKey> iterator = keys.iterator(); iterator.hasNext();) {
- Object object = iterator.next();
+ for (Object object : keys) {
System.err.println(object + " = " + WeaverContainer.weavingAdaptors.get(object));
}
}
System.err.println("Weaver adaptors after queue processing:");
Map<AdaptorKey,ExplicitlyInitializedClassLoaderWeavingAdaptor> m = WeaverContainer.weavingAdaptors;
Set<AdaptorKey> keys = m.keySet();
- for (Iterator<AdaptorKey> iterator = keys.iterator(); iterator.hasNext();) {
- Object object = iterator.next();
+ for (Object object : keys) {
System.err.println(object + " = " + WeaverContainer.weavingAdaptors.get(object));
}
}
*/
List<String> getAspectClassNames(List<Definition> definitions) {
List<String> aspects = new LinkedList<String>();
- for (Iterator<Definition> it = definitions.iterator(); it.hasNext(); ) {
- Definition def = it.next();
+ for (Definition def : definitions) {
List<String> defAspects = def.getAspectClassNames();
if (defAspects != null) {
aspects.addAll(defAspects);
private void registerIncludeExclude(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
String fastMatchInfo = null;
for (Definition definition : definitions) {
- for (Iterator<String> iterator1 = definition.getIncludePatterns().iterator(); iterator1.hasNext();) {
+ for (String value : definition.getIncludePatterns()) {
hasIncludes = true;
- String include = iterator1.next();
+ String include = value;
fastMatchInfo = looksLikeStartsWith(include);
if (fastMatchInfo != null) {
includeStartsWith.add(fastMatchInfo);
includeTypePattern.add(includePattern);
}
}
- for (Iterator<String> iterator1 = definition.getExcludePatterns().iterator(); iterator1.hasNext();) {
+ for (String s : definition.getExcludePatterns()) {
hasExcludes = true;
- String exclude = iterator1.next();
+ String exclude = s;
fastMatchInfo = looksLikeStartsWith(exclude);
if (fastMatchInfo != null) {
excludeStartsWith.add(fastMatchInfo);
} else if (exclude
.equals("org.codehaus.groovy..* && !org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController*")) {
// TODO need a more sophisticated analysis here, to allow for similar situations
- excludeSpecial.add(new String[] { "org.codehaus.groovy.",
- "org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController" });
+ excludeSpecial.add(new String[]{"org.codehaus.groovy.",
+ "org.codehaus.groovy.grails.web.servlet.mvc.SimpleGrailsController"});
// for the related test:
// } else if (exclude.equals("testdata..* && !testdata.sub.Oran*")) {
// excludeSpecial.add(new String[] { "testdata.", "testdata.sub.Oran" });
*/
private void registerDump(final BcelWeaver weaver, final ClassLoader loader, final List<Definition> definitions) {
for (Definition definition : definitions) {
- for (Iterator<String> iterator1 = definition.getDumpPatterns().iterator(); iterator1.hasNext();) {
- String dump = iterator1.next();
+ for (String dump : definition.getDumpPatterns()) {
TypePattern pattern = new PatternParser(dump).parseTypePattern();
dumpTypePattern.add(pattern);
}
}
}
boolean fastAccept = false;// defaults to false if no fast include
- for (int i = 0; i < includeStartsWith.size(); i++) {
+ for (String s : includeStartsWith) {
didSomeIncludeMatching = true;
- fastAccept = fastClassName.startsWith(includeStartsWith.get(i));
+ fastAccept = fastClassName.startsWith(s);
if (fastAccept) {
return true;
}
}
}
}
- for (int i = 0; i < includeStartsWith.size(); i++) {
+ for (String s : includeStartsWith) {
didSomeIncludeMatching = true;
- boolean fastaccept = fastClassName.startsWith(includeStartsWith.get(i));
+ boolean fastaccept = fastClassName.startsWith(s);
if (fastaccept) {
return true;
}
// still try to avoid ResolvedType if we have simple patterns
// EXCLUDE: if one match then reject
String fastClassName = aspectClassName.replace('/', '.').replace('.', '$');
- for (int i = 0; i < aspectExcludeStartsWith.size(); i++) {
- if (fastClassName.startsWith(aspectExcludeStartsWith.get(i))) {
+ for (String value : aspectExcludeStartsWith) {
+ if (fastClassName.startsWith(value)) {
return false;
}
}
// INCLUDE: if one match then accept
- for (int i = 0; i < aspectIncludeStartsWith.size(); i++) {
- if (fastClassName.startsWith(aspectIncludeStartsWith.get(i))) {
+ for (String s : aspectIncludeStartsWith) {
+ if (fastClassName.startsWith(s)) {
return true;
}
}
// TODO AV - optimize for className.startWith only
ResolvedType classInfo = weaver.getWorld().resolve(UnresolvedType.forName(className), true);
// dump
- for (Iterator<TypePattern> iterator = dumpTypePattern.iterator(); iterator.hasNext();) {
- TypePattern typePattern = iterator.next();
+ for (TypePattern typePattern : dumpTypePattern) {
if (typePattern.matchesStatically(classInfo)) {
// dump match
return true;
}
if (parent.isParameterizedType()) {
UnresolvedType[] typeParameters = parent.getTypeParameters();
- for (int i = 0; i < typeParameters.length; i++) {
- UnresolvedType typeParameter = typeParameters[i];
+ for (UnresolvedType typeParameter : typeParameters) {
if (typeParameter instanceof ResolvedType && ((ResolvedType) typeParameter).isMissing()) {
reportError("Unablet to resolve type parameter '" + typeParameter.getName() + "' from " + stringify());
return false;
}
ResolvedMember[] rms = type.getDeclaredMethods();
if (rms != null) {
- for (int i = 0; i < rms.length; i++) {
- ResolvedMember member = rms[i];
+ for (ResolvedMember member : rms) {
String key = member.getName() + member.getSignature();
if (member.isAbstract()) {
collector.put(key, member);
if (as == null || as.length == 0) {
return false;
}
- for (int i = 0; i < as.length; i++) {
- if (as[i].getTypeSignature().equals("Lorg/aspectj/lang/annotation/Pointcut;")) {
+ for (AnnotationAJ a : as) {
+ if (a.getTypeSignature().equals("Lorg/aspectj/lang/annotation/Pointcut;")) {
return true;
}
}
cbody.append(InstructionConstants.RETURN);
cg.addMethodGen(init);
- for (Iterator<Definition.Pointcut> it = concreteAspect.pointcuts.iterator(); it.hasNext();) {
- Definition.Pointcut abstractPc = (Definition.Pointcut) it.next();
+ for (Definition.Pointcut abstractPc : concreteAspect.pointcuts) {
// TODO AV - respect visibility instead of opening up as public?
LazyMethodGen mg = new LazyMethodGen(Modifier.PUBLIC, Type.VOID, abstractPc.name, EMPTY_TYPES, EMPTY_STRINGS, cg);
SimpleElementValue svg = new SimpleElementValue(ElementValue.STRING, cg.getConstantPool(), abstractPc.expression);
value = value.substring(equalsIndex+1).trim();
}
boolean keyIsOk = false;
- for (int m=0;m<rms.length;m++) {
+ for (ResolvedMember rm : rms) {
NameValuePair nvp = null;
- if (rms[m].getName().equals(key)) {
+ if (rm.getName().equals(key)) {
// found it!
- keyIsOk=true;
- UnresolvedType rt = rms[m].getReturnType();
+ keyIsOk = true;
+ UnresolvedType rt = rm.getReturnType();
if (rt.isPrimitiveType()) {
switch (rt.getSignature().charAt(0)) {
- case 'J': // long
- try {
- long longValue = Long.parseLong(value);
- nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_LONG,cp,longValue),cp);
- } catch (NumberFormatException nfe) {
- reportError("unable to interpret annotation value '"+value+"' as a long");
- return null;
- }
- break;
- case 'S': // short
- try {
- short shortValue = Short.parseShort(value);
- nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_SHORT,cp,shortValue),cp);
- } catch (NumberFormatException nfe) {
- reportError("unable to interpret annotation value '"+value+"' as a short");
- return null;
- }
- break;
- case 'F': // float
- try {
- float floatValue = Float.parseFloat(value);
- nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_FLOAT,cp,floatValue),cp);
- } catch (NumberFormatException nfe) {
- reportError("unable to interpret annotation value '"+value+"' as a float");
- return null;
- }
- break;
- case 'D': // double
- try {
- double doubleValue = Double.parseDouble(value);
- nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_DOUBLE,cp,doubleValue),cp);
- } catch (NumberFormatException nfe) {
- reportError("unable to interpret annotation value '"+value+"' as a double");
- return null;
- }
- break;
- case 'I': // integer
- try {
- int intValue = Integer.parseInt(value);
- nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_INT,cp,intValue),cp);
- } catch (NumberFormatException nfe) {
- reportError("unable to interpret annotation value '"+value+"' as an integer");
- return null;
- }
- break;
- case 'B': // byte
- try {
- byte byteValue = Byte.parseByte(value);
- nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_BYTE,cp,byteValue),cp);
- } catch (NumberFormatException nfe) {
- reportError("unable to interpret annotation value '"+value+"' as a byte");
- return null;
- }
- break;
- case 'C': // char
- if (value.length()<2) {
- reportError("unable to interpret annotation value '"+value+"' as a char");
- return null;
- }
- nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_CHAR,cp,value.charAt(1)),cp);
- break;
- case 'Z': // boolean
- try {
- boolean booleanValue = Boolean.parseBoolean(value);
- nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.PRIMITIVE_BOOLEAN,cp,booleanValue),cp);
- } catch (NumberFormatException nfe) {
- reportError("unable to interpret annotation value '"+value+"' as a boolean");
- return null;
- }
- break;
+ case 'J': // long
+ try {
+ long longValue = Long.parseLong(value);
+ nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_LONG, cp, longValue), cp);
+ } catch (NumberFormatException nfe) {
+ reportError("unable to interpret annotation value '" + value + "' as a long");
+ return null;
+ }
+ break;
+ case 'S': // short
+ try {
+ short shortValue = Short.parseShort(value);
+ nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_SHORT, cp, shortValue), cp);
+ } catch (NumberFormatException nfe) {
+ reportError("unable to interpret annotation value '" + value + "' as a short");
+ return null;
+ }
+ break;
+ case 'F': // float
+ try {
+ float floatValue = Float.parseFloat(value);
+ nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_FLOAT, cp, floatValue), cp);
+ } catch (NumberFormatException nfe) {
+ reportError("unable to interpret annotation value '" + value + "' as a float");
+ return null;
+ }
+ break;
+ case 'D': // double
+ try {
+ double doubleValue = Double.parseDouble(value);
+ nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_DOUBLE, cp, doubleValue), cp);
+ } catch (NumberFormatException nfe) {
+ reportError("unable to interpret annotation value '" + value + "' as a double");
+ return null;
+ }
+ break;
+ case 'I': // integer
+ try {
+ int intValue = Integer.parseInt(value);
+ nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_INT, cp, intValue), cp);
+ } catch (NumberFormatException nfe) {
+ reportError("unable to interpret annotation value '" + value + "' as an integer");
+ return null;
+ }
+ break;
+ case 'B': // byte
+ try {
+ byte byteValue = Byte.parseByte(value);
+ nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_BYTE, cp, byteValue), cp);
+ } catch (NumberFormatException nfe) {
+ reportError("unable to interpret annotation value '" + value + "' as a byte");
+ return null;
+ }
+ break;
+ case 'C': // char
+ if (value.length() < 2) {
+ reportError("unable to interpret annotation value '" + value + "' as a char");
+ return null;
+ }
+ nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_CHAR, cp, value.charAt(1)), cp);
+ break;
+ case 'Z': // boolean
+ try {
+ boolean booleanValue = Boolean.parseBoolean(value);
+ nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.PRIMITIVE_BOOLEAN, cp, booleanValue), cp);
+ } catch (NumberFormatException nfe) {
+ reportError("unable to interpret annotation value '" + value + "' as a boolean");
+ return null;
+ }
+ break;
default:
- reportError("not yet supporting XML setting of annotation values of type "+rt.getName());
+ reportError("not yet supporting XML setting of annotation values of type " + rt.getName());
return null;
}
} else if (UnresolvedType.JL_STRING.equals(rt)) {
- if (value.length()<2) {
- reportError("Invalid string value specified in annotation string: "+annotationString);
+ if (value.length() < 2) {
+ reportError("Invalid string value specified in annotation string: " + annotationString);
return null;
}
- value = value.substring(1,value.length()-1); // trim the quotes off
- nvp = new NameValuePair(key,new SimpleElementValue(ElementValue.STRING,cp,value),cp);
+ value = value.substring(1, value.length() - 1); // trim the quotes off
+ nvp = new NameValuePair(key, new SimpleElementValue(ElementValue.STRING, cp, value), cp);
} else if (UnresolvedType.JL_CLASS.equals(rt)) {
// format of class string:
// Foo.class
// java.lang.Foo.class
- if (value.length()<6) {
- reportError("Not a well formed class value for an annotation '"+value+"'");
+ if (value.length() < 6) {
+ reportError("Not a well formed class value for an annotation '" + value + "'");
return null;
}
- String clazz = value.substring(0,value.length()-6);
- boolean qualified = clazz.indexOf(".")!=-1;
+ String clazz = value.substring(0, value.length() - 6);
+ boolean qualified = clazz.indexOf(".") != -1;
if (!qualified) {
// if not qualified, have to assume java.lang
- clazz = "java.lang."+clazz;
+ clazz = "java.lang." + clazz;
}
- nvp = new NameValuePair(key,new ClassElementValue(new ObjectType(clazz),cp),cp);
+ nvp = new NameValuePair(key, new ClassElementValue(new ObjectType(clazz), cp), cp);
}
}
- if (nvp!=null) {
+ if (nvp != null) {
aaj.addElementNameValuePair(nvp);
}
}
// Generate code to load the parameters
int pos = 1; // first slot after 'this'
- for (int i = 0; i < paramTypes.size(); i++) {
- adviceBody.append(InstructionFactory.createLoad(paramTypes.get(i), pos));
- pos += paramTypes.get(i).getSize();
+ for (Type paramType : paramTypes) {
+ adviceBody.append(InstructionFactory.createLoad(paramType, pos));
+ pos += paramType.getSize();
}
// Generate the delegate call
Collections.reverse(flags);
// do a first round on the message handler since it will report the options themselves
- for (Iterator<String> iterator = flags.iterator(); iterator.hasNext();) {
- String arg = iterator.next();
+ for (String arg : flags) {
if (arg.startsWith(OPTIONVALUED_messageHandler)) {
if (arg.length() > OPTIONVALUED_messageHandler.length()) {
String handlerClass = arg.substring(OPTIONVALUED_messageHandler.length()).trim();
}
// configure the other options
- for (Iterator<String> iterator = flags.iterator(); iterator.hasNext();) {
- String arg = iterator.next();
+ for (String arg : flags) {
if (arg.equals(OPTION_15)) {
weaverOption.java5 = true;
} else if (arg.equalsIgnoreCase(OPTION_lazyTjp)) {
super(clone.getParent());
URL[] urls = clone.getURLs();
- for (int i = 0; i < urls.length; i++) {
+ for (URL value : urls) {
Object pathElement;
- URL url = urls[i];
+ URL url = value;
if (debug)
System.out.println("JRockitClassLoader.JRockitClassLoader() url=" + url.getPath());
File file = new File(encode(url.getFile()));
buildManager = new AjBuildManager(handler);
savedArgs = new String[args.length];
System.arraycopy(args, 0, savedArgs, 0, savedArgs.length);
- for (int i = 0; i < args.length; i++) {
+ for (String arg : args) {
// AMC - PR58681. No need to abort on -help as the Eclipse compiler does the right thing.
// if ("-help".equals(args[i])) {
// // should be info, but handler usually suppresses
// MessageUtil.abort(handler, BuildArgParser.getUsage());
// return true;
-// } else
- if ("-X".equals(args[i])) {
- // should be info, but handler usually suppresses
- MessageUtil.abort(handler, BuildArgParser.getXOptionUsage());
- return true;
- }
- }
+// } else
+ if ("-X".equals(arg)) {
+ // should be info, but handler usually suppresses
+ MessageUtil.abort(handler, BuildArgParser.getXOptionUsage());
+ return true;
+ }
+ }
return doCommand(handler, false);
}
}
if (buildConfig.getSourceRoots() != null) {
- for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext();) {
- fileList.addAll(collectSourceRootFiles((File) i.next()));
+ for (File file : buildConfig.getSourceRoots()) {
+ fileList.addAll(collectSourceRootFiles(file));
}
}
if (parser.classpath == null) {
addClasspath(System.getProperty("java.class.path", ""), ret);
List fixedList = new ArrayList();
- for (Iterator it = ret.iterator(); it.hasNext();) {
- String entry = (String) it.next();
+ for (Object o : ret) {
+ String entry = (String) o;
if (!entry.endsWith("aspectjtools.jar")) {
fixedList.add(entry);
}
File dirFile = new File(tokenizer.nextToken());
if (dirFile.canRead() && dirFile.isDirectory()) {
File[] files = dirFile.listFiles(FileUtil.ZIP_FILTER);
- for (int i = 0; i < files.length; i++) {
- classpathCollector.add(files[i].getAbsolutePath());
+ for (File file : files) {
+ classpathCollector.add(file.getAbsolutePath());
}
} else {
// XXX alert on invalid -extdirs entries
public void parseCommandLine(String[] argsArray) throws ParseException {
location = new CommandLineLocation();
LinkedList<Arg> args = new LinkedList<Arg>();
- for (int i = 0; i < argsArray.length; i++) {
- args.add(new Arg(argsArray[i], location));
+ for (String s : argsArray) {
+ args.add(new Arg(s, location));
}
String aspectjOptions = null;
try {
showWarning("no matching files found in: " + dir);
}
- for (int i = 0; i < files.length; i++) {
- addFile(files[i]);
+ for (File file : files) {
+ addFile(file);
}
}
}
try {
// not great ... but one more check before we continue, see pr132314
if (!reportedErrors && units != null) {
- for (int i = 0; i < units.length; i++) {
- if (units[i] != null && units[i].compilationResult != null && units[i].compilationResult.hasErrors()) {
+ for (CompilationUnitDeclaration unit : units) {
+ if (unit != null && unit.compilationResult != null && unit.compilationResult.hasErrors()) {
reportedErrors = true;
break;
}
private List getBinarySourcesFrom(Map binarySourceEntries) {
// Map is fileName |-> List<UnwovenClassFile>
List ret = new ArrayList();
- for (Iterator binIter = binarySourceEntries.keySet().iterator(); binIter.hasNext();) {
- String sourceFileName = (String) binIter.next();
+ for (Object o : binarySourceEntries.keySet()) {
+ String sourceFileName = (String) o;
List unwovenClassFiles = (List) binarySourceEntries.get(sourceFileName);
// XXX - see bugs 57432,58679 - final parameter on next call should be "compiler.options.maxProblemsPerUnit"
CompilationResult result = new CompilationResult(sourceFileName.toCharArray(), 0, 0, Integer.MAX_VALUE);
}
private void notifyRequestor() {
- for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) {
- InterimCompilationResult iresult = (InterimCompilationResult) iter.next();
+ for (Object o : resultsPendingWeave) {
+ InterimCompilationResult iresult = (InterimCompilationResult) o;
compiler.requestor.acceptResult(iresult.result().tagAsAccepted());
}
}
private void weave() throws IOException {
// ensure weaver state is set up correctly
- for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) {
- InterimCompilationResult iresult = (InterimCompilationResult) iter.next();
+ for (Object o : resultsPendingWeave) {
+ InterimCompilationResult iresult = (InterimCompilationResult) o;
for (int i = 0; i < iresult.unwovenClassFiles().length; i++) {
weaver.addClassFile(iresult.unwovenClassFiles()[i], false);
}
}
if (!reportedErrors && units != null) {
- for (int i = 0; i < units.length; i++) {
- if (units[i] != null && units[i].compilationResult != null && units[i].compilationResult.hasErrors()) {
+ for (CompilationUnitDeclaration unit : units) {
+ if (unit != null && unit.compilationResult != null && unit.compilationResult.hasErrors()) {
reportedErrors = true;
break; // TODO break or exit here?
}
// Break the units into two lists...
List<CompilationUnitDeclaration> aspects = new ArrayList<CompilationUnitDeclaration>();
List<CompilationUnitDeclaration> nonaspects = new ArrayList<CompilationUnitDeclaration>();
- for (int i = 0; i < units.length; i++) {
- if (containsAnAspect(units[i])) {
- aspects.add(units[i]);
+ for (CompilationUnitDeclaration unit : units) {
+ if (containsAnAspect(unit)) {
+ aspects.add(unit);
} else {
- nonaspects.add(units[i]);
+ nonaspects.add(unit);
}
}
int sourceStart = md.sourceStart;
int[] separators = md.compilationResult.lineSeparatorPositions;
int declarationStartLine = 1;
- for (int i = 0; i < separators.length; i++) {
- if (sourceStart < separators[i]) {
+ for (int separator : separators) {
+ if (sourceStart < separator) {
break;
}
declarationStartLine++;
try {
// not great ... but one more check before we continue, see pr132314
if (!reportedErrors && units != null) {
- for (int i = 0; i < units.length; i++) {
- if (units[i] != null && units[i].compilationResult != null && units[i].compilationResult.hasErrors()) {
+ for (CompilationUnitDeclaration unit : units) {
+ if (unit != null && unit.compilationResult != null && unit.compilationResult.hasErrors()) {
reportedErrors = true;
break;
}
private List<InterimCompilationResult> getBinarySourcesFrom(Map<String, List<UnwovenClassFile>> binarySourceEntries) {
// Map is fileName |-> List<UnwovenClassFile>
List<InterimCompilationResult> ret = new ArrayList<InterimCompilationResult>();
- for (Iterator<String> binIter = binarySourceEntries.keySet().iterator(); binIter.hasNext();) {
- String sourceFileName = binIter.next();
+ for (String sourceFileName : binarySourceEntries.keySet()) {
List<UnwovenClassFile> unwovenClassFiles = binarySourceEntries.get(sourceFileName);
// XXX - see bugs 57432,58679 - final parameter on next call should be "compiler.options.maxProblemsPerUnit"
CompilationResult result = new CompilationResult(sourceFileName.toCharArray(), 0, 0, Integer.MAX_VALUE);
}
private void notifyRequestor() {
- for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) {
- InterimCompilationResult iresult = (InterimCompilationResult) iter.next();
+ for (InterimCompilationResult iresult : resultsPendingWeave) {
compiler.requestor.acceptResult(iresult.result().tagAsAccepted());
}
}
if (debugPipeline) {
System.err.println(">.weaveQueuedEntries()");
}
- for (Iterator iter = resultsPendingWeave.iterator(); iter.hasNext();) {
- InterimCompilationResult iresult = (InterimCompilationResult) iter.next();
+ for (InterimCompilationResult iresult : resultsPendingWeave) {
for (int i = 0; i < iresult.unwovenClassFiles().length; i++) {
weaver.addClassFile(iresult.unwovenClassFiles()[i], false);
}
private boolean containsAnAspect(CompilationUnitDeclaration cud) {
TypeDeclaration[] typeDecls = cud.types;
if (typeDecls != null) {
- for (int i = 0; i < typeDecls.length; i++) { // loop through top level types in the file
- TypeDeclaration declaration = typeDecls[i];
+ for (TypeDeclaration declaration : typeDecls) { // loop through top level types in the file
if (isAspect(declaration)) {
return true;
}
if (declaration.memberTypes != null) {
TypeDeclaration[] memberTypes = declaration.memberTypes;
- for (int j = 0; j < memberTypes.length; j++) { // loop through inner types
- if (containsAnAspect(memberTypes[j])) {
+ for (TypeDeclaration memberType : memberTypes) { // loop through inner types
+ if (containsAnAspect(memberType)) {
return true;
}
}
}
if (tDecl.memberTypes != null) {
TypeDeclaration[] memberTypes = tDecl.memberTypes;
- for (int j = 0; j < memberTypes.length; j++) { // loop through inner types
- if (containsAnAspect(memberTypes[j])) {
+ for (TypeDeclaration memberType : memberTypes) { // loop through inner types
+ if (containsAnAspect(memberType)) {
return true;
}
}
ClassFile[] cfs = result.getClassFiles();
UnwovenClassFile[] ret = new UnwovenClassFile[result.compiledTypes.size()];
int i=0;
- for (Iterator iterator = result.compiledTypes.keySet().iterator(); iterator.hasNext();) {
- char[] className = (char[])iterator.next();
- ClassFile cf = (ClassFile)result.compiledTypes.get(className);
+ for (Object o : result.compiledTypes.keySet()) {
+ char[] className = (char[]) o;
+ ClassFile cf = (ClassFile) result.compiledTypes.get(className);
// OPTIMIZE use char[] for classname
ClassFileBasedByteCodeProvider p = new ClassFileBasedByteCodeProvider(cf);
String fileName = nameProvider.getOutputClassFileName(cf.fileName(), result);
- ret[i++] = new UnwovenClassFileWithThirdPartyManagedBytecode(fileName,new String(className).replace('/','.'),p);
+ ret[i++] = new UnwovenClassFileWithThirdPartyManagedBytecode(fileName, new String(className).replace('/', '.'), p);
}
return ret;
}
protected StringBuilder printAnnotations(Annotation[] annotations) {
int length = annotations.length;
- for (int i = 0; i < length; i++) {
- printAnnotation(annotations[i]);
+ for (Annotation annotation : annotations) {
+ printAnnotation(annotation);
output.append(" "); //$NON-NLS-1$
}
return output;
return true;
}
char[] victim = null;
- for (Iterator iter = aMap.keySet().iterator(); iter.hasNext();) {
- char[] thisKey = (char[]) iter.next();
+ for (Object o : aMap.keySet()) {
+ char[] thisKey = (char[]) o;
if (CharOperation.equals(thisKey, key)) {
// if (skey.equals(new String(thisKey))) {
victim = thisKey;
boolean usedBinarySourceFileName) {
List<IProblem> ret = new ArrayList<IProblem>();
- for (int i = 0; i < sourceLocations.size(); i++) {
- ISourceLocation loc = (ISourceLocation) sourceLocations.get(i);
+ for (Object sourceLocation : sourceLocations) {
+ ISourceLocation loc = (ISourceLocation) sourceLocation;
if (loc != null) {
- DefaultProblem dp = new DefaultProblem(loc.getSourceFile().getPath().toCharArray(), "see also", 0, new String[] {},
+ DefaultProblem dp = new DefaultProblem(loc.getSourceFile().getPath().toCharArray(), "see also", 0, new String[]{},
ProblemSeverities.Ignore, getStartPos(loc, null), getEndPos(loc, null), loc.getLine(), loc.getColumn());
ret.add(dp);
} else {
proceedInInners = false;
declaredExceptions = new UnresolvedType[0];
- for (int i = 0; i < n; i++) {
- Proceed call = proceedCalls.get(i);
+ for (Proceed call : proceedCalls) {
if (call.inInner) {
// System.err.println("proceed in inner: " + call);
proceedInInners = true;
int[] separators = compilationResult().lineSeparatorPositions;
int declarationStartLine = 1;
- for (int i = 0; i < separators.length; i++) {
- if (sourceStart < separators[i]) break;
+ for (int separator : separators) {
+ if (sourceStart < separator) break;
declarationStartLine++;
}
int[] separators = compilationResult().lineSeparatorPositions;
int declarationStartLine = 1;
- for (int i = 0; i < separators.length; i++) {
- if (sourceStart < separators[i]) break;
+ for (int separator : separators) {
+ if (sourceStart < separator) break;
declarationStartLine++;
}
}
}
if (memberTypes != null) {
- for (int i = 0; i < memberTypes.length; i++) {
- if (memberTypes[i] instanceof IntertypeMemberClassDeclaration) {
- IntertypeMemberClassDeclaration itdMemberClassDeclaration = (IntertypeMemberClassDeclaration) memberTypes[i];
+ for (TypeDeclaration memberType : memberTypes) {
+ if (memberType instanceof IntertypeMemberClassDeclaration) {
+ IntertypeMemberClassDeclaration itdMemberClassDeclaration = (IntertypeMemberClassDeclaration) memberType;
AjAttribute attribute = itdMemberClassDeclaration.getAttribute();
if (attribute != null) {
classFile.extraAttributes.add(new EclipseAttributeAdapter(attribute));
*/
@SuppressWarnings("unchecked")
private void addVersionAttributeIfNecessary(ClassFile classFile) {
- for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) {
- EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next();
+ for (Object o : classFile.extraAttributes) {
+ EclipseAttributeAdapter element = (EclipseAttributeAdapter) o;
if (CharOperation.equals(element.getNameChars(), weaverVersionChars)) {
return;
}
private static char[] weaverVersionChars = "org.aspectj.weaver.WeaverVersion".toCharArray();
private void generateInlineAccessMembers(ClassFile classFile) {
- for (Iterator<SuperAccessMethodPair> i = superAccessForInline.values().iterator(); i.hasNext();) {
- AccessForInlineVisitor.SuperAccessMethodPair pair = i.next();
+ for (SuperAccessMethodPair pair : superAccessForInline.values()) {
generateSuperAccessMethod(classFile, pair.accessMethod, pair.originalMethod);
}
- for (Iterator<Map.Entry<ResolvedMember, Binding>> i = accessForInline.entrySet().iterator(); i.hasNext();) {
- Map.Entry<ResolvedMember, Binding> e = i.next();
+ for (Map.Entry<ResolvedMember, Binding> e : accessForInline.entrySet()) {
generateInlineAccessMethod(classFile, e.getValue(), e.getKey());
}
}
public void processIntertypeMemberTypes(ClassScope classScope) {
factory = EclipseFactory.fromScopeLookupEnvironment(scope);
if (memberTypes != null) {
- for (int i = 0; i < memberTypes.length; i++) {
- if (memberTypes[i] instanceof IntertypeMemberClassDeclaration) {
- EclipseTypeMunger m = ((IntertypeMemberClassDeclaration) memberTypes[i]).build(classScope);
+ for (TypeDeclaration memberType : memberTypes) {
+ if (memberType instanceof IntertypeMemberClassDeclaration) {
+ EclipseTypeMunger m = ((IntertypeMemberClassDeclaration) memberType).build(classScope);
if (m != null) {
mungeNewInnerClass(m, factory);
concreteName.typeMungers.add(m);
buildPerClause(scope);
if (methods != null) {
- for (int i = 0; i < methods.length; i++) {
- if (methods[i] instanceof InterTypeDeclaration) {
- EclipseTypeMunger m = ((InterTypeDeclaration) methods[i]).build(classScope);
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration method : methods) {
+ if (method instanceof InterTypeDeclaration) {
+ EclipseTypeMunger m = ((InterTypeDeclaration) method).build(classScope);
if (m != null) {
concreteName.typeMungers.add(m);
}
- } else if (methods[i] instanceof DeclareDeclaration) {
- Declare d = ((DeclareDeclaration) methods[i]).build(classScope);
+ } else if (method instanceof DeclareDeclaration) {
+ Declare d = ((DeclareDeclaration) method).build(classScope);
if (d != null) {
concreteName.declares.add(d);
}
// TODO should probably avoid putting it onto BTBs at all (since already there)
if (!(targetSourceTypeBinding instanceof BinaryTypeBinding)) {
ReferenceBinding[] existingMemberTypes = targetSourceTypeBinding.memberTypes();
- for (int i = 0; i < existingMemberTypes.length; i++) {
- char[] compounded = CharOperation.concatWith(existingMemberTypes[i].compoundName, '.');
+ for (ReferenceBinding existingMemberType : existingMemberTypes) {
+ char[] compounded = CharOperation.concatWith(existingMemberType.compoundName, '.');
if (CharOperation.endsWith(compounded, mungerMemberTypeName)) {
scope.problemReporter().signalError(sourceStart(), sourceEnd(),
"target type already declares a member type with the name '" + munger.getMemberTypeName() + "'");
private boolean suppressingNoExplicitConstructorCall() {
if (this.annotations == null)
return false;
- for (int i = 0; i < this.annotations.length; i++) {
- if (new String(this.annotations[i].resolvedType.signature()).equals(SUPPRESSAJWARNINGS)) {
- if (this.annotations[i] instanceof MarkerAnnotation) {
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation annotation : this.annotations) {
+ if (new String(annotation.resolvedType.signature()).equals(SUPPRESSAJWARNINGS)) {
+ if (annotation instanceof MarkerAnnotation) {
return true;
- } else if (this.annotations[i] instanceof SingleMemberAnnotation) {
- SingleMemberAnnotation sma = (SingleMemberAnnotation) this.annotations[i];
+ } else if (annotation instanceof SingleMemberAnnotation) {
+ SingleMemberAnnotation sma = (SingleMemberAnnotation) annotation;
if (sma.memberValue instanceof ArrayInitializer) {
ArrayInitializer memberValue = (ArrayInitializer) sma.memberValue;
for (int j = 0; j < memberValue.expressions.length; j++) {
ParameterizedSingleTypeReference paramRef = (ParameterizedSingleTypeReference) onType;
TypeReference[] rb = paramRef.typeArguments;
typeVariableAliases = new ArrayList();
- for (int i = 0; i < rb.length; i++) {
- typeVariableAliases.add(CharOperation.toString(rb[i].getTypeName()));
+ for (TypeReference typeReference : rb) {
+ typeVariableAliases.add(CharOperation.toString(typeReference.getTypeName()));
}
} else if (onType instanceof ParameterizedQualifiedTypeReference) {
ParameterizedQualifiedTypeReference paramRef = (ParameterizedQualifiedTypeReference) onType;
} else {
if (!onTypeBinding.isInterface()) {
FieldBinding[] existingFields = onTypeBinding.fields();
- for (int f = 0; f < existingFields.length; f++) {
- FieldBinding fieldBinding = existingFields[f];
+ for (FieldBinding fieldBinding : existingFields) {
if (CharOperation.equals(fieldBinding.name, sig.getName().toCharArray())) {
fieldMunger.version = NewFieldTypeMunger.VersionOne;
}
ReferenceBinding supertype = onTypeBinding.superclass();
while (supertype != null && reportError) {
MethodBinding[] possibles = supertype.getMethods(declaredSelector);
- for (int i = 0; i < possibles.length; i++) {
- MethodBinding mb = possibles[i];
-
+ for (MethodBinding mb : possibles) {
boolean couldBeMatch = true;
if (mb.parameters.length != realthing.parameters.length)
couldBeMatch = false;
Argument[] itdArgs = this.arguments;
if (itdArgs != null) {
- for (int a = 0; a < itdArgs.length; a++) {
- LocalVariableBinding lvb = itdArgs[a].binding;
+ for (Argument itdArg : itdArgs) {
+ LocalVariableBinding lvb = itdArg.binding;
LocalVariableBinding lvbCopy = new LocalVariableBinding(lvb.name, lvb.type, lvb.modifiers, true);
// e37: have to create a declaration so that the check in ClassFile (line 2538) won't skip it
- lvbCopy.declaration = new LocalDeclaration(itdArgs[a].name,0,0);
+ lvbCopy.declaration = new LocalDeclaration(itdArg.name, 0, 0);
codeStream.record(lvbCopy);
lvbCopy.recordInitializationStartPC(0);
lvbCopy.resolvedPosition = lvb.resolvedPosition;
codeStream.aload_0();
resolvedPosition = 1;
}
- for (int i = 0; i < length; i++) {
- codeStream.load(parameters[i], resolvedPosition);
- if ((parameters[i] == TypeBinding.DOUBLE) || (parameters[i] == TypeBinding.LONG))
+ for (TypeBinding parameter : parameters) {
+ codeStream.load(parameter, resolvedPosition);
+ if ((parameter == TypeBinding.DOUBLE) || (parameter == TypeBinding.LONG))
resolvedPosition += 2;
else
resolvedPosition++;
* is added. So, this method adds the attribute if someone else hasn't already.
*/
private void addVersionAttributeIfNecessary(ClassFile classFile) {
- for (Iterator iter = classFile.extraAttributes.iterator(); iter.hasNext();) {
- EclipseAttributeAdapter element = (EclipseAttributeAdapter) iter.next();
+ for (Object o : classFile.extraAttributes) {
+ EclipseAttributeAdapter element = (EclipseAttributeAdapter) o;
if (CharOperation.equals(element.getNameChars(), weaverVersionChars))
return;
}
}
boolean argsContainCast = false;
- for (int i=0; i<arguments.length;i++) {
- if (arguments[i] instanceof CastExpression) argsContainCast = true;
- // if (arguments[i].constant==null) arguments[i].constant=Constant.NotAConstant;
+ for (Expression argument : arguments) {
+ if (argument instanceof CastExpression) argsContainCast = true;
+ // if (arguments[i].constant==null) arguments[i].constant=Constant.NotAConstant;
}
// TypeBinding[] argumentTypes = Binding.NO_PARAMETERS;
// if (this.arguments != null) {
public void postParse(TypeDeclaration typeDec, MethodDeclaration enclosingDec) {
int counter = 0; // Counter can be used by postParse as a value to compute uniqueness (if required)
- for (int i=0, len=tokens.length; i < len; i++) {
- counter+=tokens[i].postParse(typeDec, enclosingDec, counter);
+ for (PseudoToken token : tokens) {
+ counter += token.postParse(typeDec, enclosingDec, counter);
}
}
localTypeDeclaration.binding.modifiers |=Modifier.PUBLIC;
MethodBinding[] bindings = localTypeDeclaration.binding.methods;
if (bindings!=null) {
- for (int i=0,max=bindings.length;i<max;i++) {
- if (CharOperation.equals(bindings[i].selector,ctor)) {
- bindings[i].modifiers|=Modifier.PUBLIC;
+ for (MethodBinding binding : bindings) {
+ if (CharOperation.equals(binding.selector, ctor)) {
+ binding.modifiers |= Modifier.PUBLIC;
}
}
}
if (arguments == null) {
return names;
} else {
- for (int i = 0; i < arguments.length; i++) {
- names.add(new String(arguments[i].name));
+ for (Argument argument : arguments) {
+ names.add(new String(argument.name));
}
return names;
}
MemberValuePair[] mvps = ann.memberValuePairs;
if (mvps == null)
return null;
- for (int i = 0; i < mvps.length; i++) {
- if (CharOperation.equals(memberName.toCharArray(), mvps[i].name)) {
- if (mvps[i].value instanceof StringLiteral) {
- StringLiteral sv = (StringLiteral) mvps[i].value;
+ for (MemberValuePair mvp : mvps) {
+ if (CharOperation.equals(memberName.toCharArray(), mvp.name)) {
+ if (mvp.value instanceof StringLiteral) {
+ StringLiteral sv = (StringLiteral) mvp.value;
location[0] = sv.sourceStart;
location[1] = sv.sourceEnd;
return new String(sv.source());
public AspectJAnnotations(Annotation[] annotations) {
if (annotations == null)
return;
- for (int i = 0; i < annotations.length; i++) {
- if (annotations[i].resolvedType == null)
+ for (Annotation annotation : annotations) {
+ if (annotation.resolvedType == null)
continue; // user messed up annotation declaration
- char[] sig = annotations[i].resolvedType.signature();
+ char[] sig = annotation.resolvedType.signature();
if (CharOperation.equals(afterAdviceSig, sig)) {
adviceKind = AdviceKind.After;
- addAdviceAnnotation(annotations[i]);
+ addAdviceAnnotation(annotation);
} else if (CharOperation.equals(afterReturningAdviceSig, sig)) {
adviceKind = AdviceKind.AfterReturning;
- addAdviceAnnotation(annotations[i]);
+ addAdviceAnnotation(annotation);
} else if (CharOperation.equals(afterThrowingAdviceSig, sig)) {
adviceKind = AdviceKind.AfterThrowing;
- addAdviceAnnotation(annotations[i]);
+ addAdviceAnnotation(annotation);
} else if (CharOperation.equals(beforeAdviceSig, sig)) {
adviceKind = AdviceKind.Before;
- addAdviceAnnotation(annotations[i]);
+ addAdviceAnnotation(annotation);
} else if (CharOperation.equals(aroundAdviceSig, sig)) {
adviceKind = AdviceKind.Around;
- addAdviceAnnotation(annotations[i]);
+ addAdviceAnnotation(annotation);
} else if (CharOperation.equals(adviceNameSig, sig)) {
hasAdviceNameAnnotation = true;
- adviceNameAnnotation = annotations[i];
+ adviceNameAnnotation = annotation;
} else if (CharOperation.equals(declareParentsSig, sig)) {
hasDeclareParents = true;
} else if (CharOperation.equals(aspectSig, sig)) {
if (hasAspectAnnotation) {
hasMultipleAspectAnnotations = true;
- duplicateAspectAnnotation = annotations[i];
+ duplicateAspectAnnotation = annotation;
} else {
hasAspectAnnotation = true;
- aspectAnnotation = annotations[i];
+ aspectAnnotation = annotation;
}
} else if (CharOperation.equals(pointcutSig, sig)) {
if (hasPointcutAnnotation) {
hasMultiplePointcutAnnotations = true;
- duplicatePointcutAnnotation = annotations[i];
+ duplicatePointcutAnnotation = annotation;
} else {
hasPointcutAnnotation = true;
- pointcutAnnotation = annotations[i];
+ pointcutAnnotation = annotation;
}
}
// them in the factory
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
- for (int j = 0; j < b.length; j++) {
- factory.addSourceTypeBinding(b[j], units[i]);
- if (b[j].superclass instanceof MissingTypeBinding) {
+ for (SourceTypeBinding sourceTypeBinding : b) {
+ factory.addSourceTypeBinding(sourceTypeBinding, units[i]);
+ if (sourceTypeBinding.superclass instanceof MissingTypeBinding) {
// e37: Undoing the work in ClassScope.connectSuperClass() as it will lead to cascade errors
// TODO allow MissingTypeBinding through here and cope with it in all situations later?
- b[j].superclass = units[i].scope.getJavaLangObject();
+ sourceTypeBinding.superclass = units[i].scope.getJavaLangObject();
}
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
CompilationUnitScope cus = units[i].scope;
SourceTypeBinding[] stbs = cus.topLevelTypes;
- for (int j = 0; j < stbs.length; j++) {
- SourceTypeBinding stb = stbs[j];
+ for (SourceTypeBinding stb : stbs) {
typesToProcess.add(stb);
TypeDeclaration typeDeclaration = stb.scope.referenceContext;
if (typeDeclaration instanceof AspectDeclaration) {
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
CompilationUnitScope cus = units[i].scope;
SourceTypeBinding[] stbs = cus.topLevelTypes;
- for (int j = 0; j < stbs.length; j++) {
- SourceTypeBinding stb = stbs[j];
+ for (SourceTypeBinding stb : stbs) {
typesToProcess.add(stb);
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
- for (int j = 0; j < b.length; j++) {
+ for (SourceTypeBinding sourceTypeBinding : b) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(
- CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, b[j].sourceName);
- resolvePointcutDeclarations(b[j].scope);
+ CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, sourceTypeBinding.sourceName);
+ resolvePointcutDeclarations(sourceTypeBinding.scope);
CompilationAndWeavingContext.leavingPhase(tok);
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
- for (int j = 0; j < b.length; j++) {
+ for (SourceTypeBinding sourceTypeBinding : b) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(
- CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, b[j].sourceName);
- addAdviceLikeDeclares(b[j].scope);
+ CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, sourceTypeBinding.sourceName);
+ addAdviceLikeDeclares(sourceTypeBinding.scope);
CompilationAndWeavingContext.leavingPhase(tok);
}
}
// now check our membertypes (pr119570)
ReferenceBinding[] memberTypes = sourceType.memberTypes;
- for (int i = 0, length = memberTypes.length; i < length; i++) {
- SourceTypeBinding rb = (SourceTypeBinding) memberTypes[i];
+ for (ReferenceBinding memberType : memberTypes) {
+ SourceTypeBinding rb = (SourceTypeBinding) memberType;
if (!rb.superclass().equals(sourceType)) {
doSupertypesFirst(rb.superclass(), yetToProcess);
}
}
// Then look at the superinterface list
ReferenceBinding[] interfaceTypes = typeToWeave.superInterfaces();
- for (int i = 0; i < interfaceTypes.length; i++) {
- ReferenceBinding binding = interfaceTypes[i];
+ for (ReferenceBinding binding : interfaceTypes) {
if (typesToProcess.contains(binding) && binding instanceof SourceTypeBinding) {
// System.err.println("Recursing to superinterface "+new
// String(binding.getFileName()));
weaveIntertypes(typesToProcess, (SourceTypeBinding) binding, typeMungers, declareParents, declareAnnotationOnTypes,
mode);
- }
- else if (binding instanceof ParameterizedTypeBinding && (((ParameterizedTypeBinding)binding).type instanceof SourceTypeBinding) && typesToProcess.contains(((ParameterizedTypeBinding)binding).type)) {
- weaveIntertypes(typesToProcess, (SourceTypeBinding) ((ParameterizedTypeBinding)binding).type, typeMungers, declareParents, declareAnnotationOnTypes, mode);
+ } else if (binding instanceof ParameterizedTypeBinding && (((ParameterizedTypeBinding) binding).type instanceof SourceTypeBinding) && typesToProcess.contains(((ParameterizedTypeBinding) binding).type)) {
+ weaveIntertypes(typesToProcess, (SourceTypeBinding) ((ParameterizedTypeBinding) binding).type, typeMungers, declareParents, declareAnnotationOnTypes, mode);
}
}
weaveInterTypeDeclarations(typeToWeave, typeMungers, declareParents, declareAnnotationOnTypes, false, mode);
SourceTypeBinding sourceType = s.referenceContext.binding;
ReferenceBinding[] memberTypes = sourceType.memberTypes;
- for (int i = 0, length = memberTypes.length; i < length; i++) {
- addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope);
+ for (ReferenceBinding memberType : memberTypes) {
+ addAdviceLikeDeclares(((SourceTypeBinding) memberType).scope);
}
}
SourceTypeBinding sourceType = s.referenceContext.binding;
ReferenceBinding[] memberTypes = sourceType.memberTypes;
- for (int i = 0, length = memberTypes.length; i < length; i++) {
- addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope);
+ for (ReferenceBinding memberType : memberTypes) {
+ addCrosscuttingStructures(((SourceTypeBinding) memberType).scope);
}
}
AbstractMethodDeclaration[] methods = dec.methods;
boolean initializedMethods = false;
if (methods != null) {
- for (int i = 0; i < methods.length; i++) {
- if (methods[i] instanceof PointcutDeclaration) {
+ for (AbstractMethodDeclaration method : methods) {
+ if (method instanceof PointcutDeclaration) {
hasPointcuts = true;
if (!initializedMethods) {
sourceType.methods(); // force initialization
initializedMethods = true;
}
- ((PointcutDeclaration) methods[i]).resolvePointcut(s);
+ ((PointcutDeclaration) method).resolvePointcut(s);
}
}
}
}
ReferenceBinding[] memberTypes = sourceType.memberTypes;
- for (int i = 0, length = memberTypes.length; i < length; i++) {
- resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope);
+ for (ReferenceBinding memberType : memberTypes) {
+ resolvePointcutDeclarations(((SourceTypeBinding) memberType).scope);
}
}
System.err.println("Unexpectedly found null for memberTypes of " + sourceType.debugName());
}
if (memberTypes != null) {
- for (int i = 0, length = memberTypes.length; i < length; i++) {
- buildInterTypeAndPerClause(((SourceTypeBinding) memberTypes[i]).scope);
+ for (ReferenceBinding memberType : memberTypes) {
+ buildInterTypeAndPerClause(((SourceTypeBinding) memberType).scope);
}
}
}
// Check if the type we are looking at is the topMostImplementor of a
// dangerous interface -
// report a problem if it is.
- for (Iterator i = dangerousInterfaces.entrySet().iterator(); i.hasNext();) {
- Map.Entry entry = (Map.Entry) i.next();
+ for (Object o : dangerousInterfaces.entrySet()) {
+ Map.Entry entry = (Map.Entry) o;
ResolvedType interfaceType = (ResolvedType) entry.getKey();
if (onType.isTopmostImplementor(interfaceType)) {
factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null);
}
}
if (mode == 0 || mode == 2) {
- for (Iterator<ConcreteTypeMunger> i = typeMungers.iterator(); i.hasNext();) {
- EclipseTypeMunger munger = (EclipseTypeMunger) i.next();
+ for (ConcreteTypeMunger typeMunger : typeMungers) {
+ EclipseTypeMunger munger = (EclipseTypeMunger) typeMunger;
if (munger.matches(onType)) {
// if (needOldStyleWarning) {
// factory.showMessage(IMessage.WARNING, "The class for " + onType
}
onType.checkInterTypeMungers();
- for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) {
- EclipseTypeMunger munger = (EclipseTypeMunger) i.next();
+ for (ConcreteTypeMunger concreteTypeMunger : onType.getInterTypeMungers()) {
+ EclipseTypeMunger munger = (EclipseTypeMunger) concreteTypeMunger;
if (munger.getMunger() == null || munger.getMunger().getKind() != ResolvedTypeMunger.InnerClass) {
if (munger.munge(sourceType, onType)) {
if (factory.pushinCollector != null) {
}
ReferenceBinding[] memberTypes = sourceType.memberTypes;
- for (int i = 0, length = memberTypes.length; i < length; i++) {
- if (memberTypes[i] instanceof SourceTypeBinding) {
- weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents,
+ for (ReferenceBinding memberType : memberTypes) {
+ if (memberType instanceof SourceTypeBinding) {
+ weaveInterTypeDeclarations((SourceTypeBinding) memberType, typeMungers, declareParents,
declareAnnotationOnTypes, false, mode);
}
}
private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType, ResolvedType onType) {
List<ConcreteTypeMunger> previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType);
- for (Iterator<ConcreteTypeMunger> i = previouslyAppliedMungers.iterator(); i.hasNext();) {
- ConcreteTypeMunger m = i.next();
+ for (ConcreteTypeMunger m : previouslyAppliedMungers) {
EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m);
if (munger.munge(sourceType, onType)) {
if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) {
ResolvedType resolvedSourceType = factory.fromEclipse(sourceType);
List<ResolvedType> newParents = declareParents.findMatchingNewParents(resolvedSourceType, false);
if (!newParents.isEmpty()) {
- for (Iterator<ResolvedType> i = newParents.iterator(); i.hasNext();) {
- ResolvedType parent = i.next();
+ for (ResolvedType parent : newParents) {
if (dangerousInterfaces.containsKey(parent)) {
ResolvedType onType = factory.fromEclipse(sourceType);
factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent),
Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations;
if (currentAnnotations != null) {
- for (int i = 0; i < currentAnnotations.length; i++) {
- Annotation annotation = currentAnnotations[i];
+ for (Annotation annotation : currentAnnotations) {
String a = CharOperation.toString(annotation.type.getTypeName());
String b = CharOperation.toString(toAdd[0].type.getTypeName());
// FIXME asc we have a lint for attempting to add an annotation
ResolvedMember[] methods = rt.getDeclaredMethods();
ResolvedMember decaMethod = null;
String nameToLookFor = decA.getAnnotationMethod();
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals(nameToLookFor)) {
- decaMethod = methods[i];
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals(nameToLookFor)) {
+ decaMethod = method;
break;
}
}
MemberValuePair[] memberValuePairs = normalAnnotation.memberValuePairs;
if (memberValuePairs != null) {
int memberValuePairsLength = memberValuePairs.length;
- for (int i = 0; i < memberValuePairsLength; i++) {
- MemberValuePair memberValuePair = memberValuePairs[i];
+ for (MemberValuePair memberValuePair : memberValuePairs) {
MethodBinding methodBinding = memberValuePair.binding;
if (methodBinding == null) {
// is this just a marker annotation?
throw new MissingImplementationException(
"Please raise an AspectJ bug. AspectJ does not know how to convert this annotation [" + annotation
- + "]");
+ + "]");
} else {
AnnotationValue av = generateElementValue(memberValuePair.value, methodBinding.returnType);
AnnotationNameValuePair anvp = new AnnotationNameValuePair(new String(memberValuePair.name), av);
}
UnresolvedType[] typeArguments = typeX.getTypeParameters();
if (typeArguments != null) {
- for (int i = 0; i < typeArguments.length; i++) {
- if (typeArguments[i].isTypeVariableReference()) {
+ for (UnresolvedType typeArgument : typeArguments) {
+ if (typeArgument.isTypeVariableReference()) {
return true;
}
}
}
ReferenceBinding[] memberTypes = binding.memberTypes;
- for (int i = 0, length = memberTypes.length; i < length; i++) {
- addSourceTypeBinding((SourceTypeBinding) memberTypes[i], unit);
+ for (ReferenceBinding memberType : memberTypes) {
+ addSourceTypeBinding((SourceTypeBinding) memberType, unit);
}
}
if (annotationTypes == null) {
return false;
}
- for (int i = 0; i < annotationTypes.length; i++) {
- ResolvedType type = annotationTypes[i];
+ for (ResolvedType type : annotationTypes) {
if (type.equals(ofType)) {
return true;
}
if (annos == null) {
return null;
}
- for (int i = 0; i < annos.length; i++) {
- Annotation anno = annos[i];
+ for (Annotation anno : annos) {
UnresolvedType ut = UnresolvedType.forSignature(new String(anno.resolvedType.signature()));
if (w.resolve(ut).equals(ofType)) {
// Found the one
// Grab the set of bindings with matching selector
MethodBinding[] mb = ((MethodBinding) realBinding).declaringClass.getMethods(methodBinding.selector);
if (mb != null) {
- for (int m = 0, max = mb.length; m < max; m++) {
- MethodBinding candidate = mb[m];
+ for (MethodBinding candidate : mb) {
if (candidate instanceof InterTypeMethodBinding) {
- if (InterTypeMemberFinder.matches(mb[m], methodBinding)) {
+ if (InterTypeMemberFinder.matches(candidate, methodBinding)) {
InterTypeMethodBinding intertypeMethodBinding = (InterTypeMethodBinding) candidate;
Annotation[] annos = intertypeMethodBinding.sourceMethod.annotations;
return annos;
}
ImportBinding[] imports = cuScope.imports;
- for (int i = 0; i < imports.length; i++) {
- ImportBinding importBinding = imports[i];
+ for (ImportBinding importBinding : imports) {
String importName = new String(CharOperation.concatWith(importBinding.compoundName, '.'));
// XXX wrong behavior for java.util.Map.*
}
TypeBinding[] topTypes = cuScope.topLevelTypes;
- for (int i = 0; i < topTypes.length; i++) {
- importedNamesList.add(world.fromBinding(topTypes[i]).getName());
+ for (TypeBinding topType : topTypes) {
+ importedNamesList.add(world.fromBinding(topType).getName());
}
importedNames = importedNamesList.toArray(new String[importedNamesList.size()]);
addClassAndParentsToPrefixes(binding.superclass(), importedPrefixesList);
ReferenceBinding[] superinterfaces = binding.superInterfaces();
if (superinterfaces != null) {
- for (int i = 0; i < superinterfaces.length; i++) {
- addClassAndParentsToPrefixes(superinterfaces[i], importedPrefixesList);
+ for (ReferenceBinding superinterface : superinterfaces) {
+ addClassAndParentsToPrefixes(superinterface, importedPrefixesList);
}
}
}
// XXX add good errors when would bind to extra parameters
@Override
public FormalBinding lookupFormal(String name) {
- for (int i = 0, len = bindings.length; i < len; i++) {
- if (bindings[i].getName().equals(name))
- return bindings[i];
+ for (FormalBinding binding : bindings) {
+ if (binding.getName().equals(name))
+ return binding;
}
return null;
}
return false;
}
ResolvedType[] annotations = getAnnotationTypes();
- for (int i = 0; i < annotations.length; i++) {
- if ("org.aspectj.lang.annotation.Aspect".equals(annotations[i].getName())) {
+ for (ResolvedType annotation : annotations) {
+ if ("org.aspectj.lang.annotation.Aspect".equals(annotation.getName())) {
return true;
}
}
if (ans == null) {
return "";
}
- for (int i = 0; i < ans.length; i++) {
- if (ans[i].resolvedType == null) {
+ for (Annotation an : ans) {
+ if (an.resolvedType == null) {
continue; // XXX happens if we do this very early from
}
// buildInterTypeandPerClause
// may prevent us from resolving references made in @Pointcuts to
// an @Pointcut in a code-style aspect
- char[] sig = ans[i].resolvedType.signature();
+ char[] sig = an.resolvedType.signature();
if (CharOperation.equals(pointcutSig, sig)) {
- if (ans[i].memberValuePairs().length == 0) {
+ if (an.memberValuePairs().length == 0) {
return ""; // empty pointcut expression
}
- Expression expr = ans[i].memberValuePairs()[0].value;
+ Expression expr = an.memberValuePairs()[0].value;
if (expr instanceof StringLiteral) {
StringLiteral sLit = ((StringLiteral) expr);
return new String(sLit.source());
if (annotations == null) {
return false;
}
- for (int i = 0; i < annotations.length; i++) {
- if (annotations[i].resolvedType == null) {
+ for (Annotation annotation : annotations) {
+ if (annotation.resolvedType == null) {
continue; // XXX happens if we do this very early from
}
// buildInterTypeandPerClause
// may prevent us from resolving references made in @Pointcuts to
// an @Pointcut in a code-style aspect
- char[] sig = annotations[i].resolvedType.signature();
+ char[] sig = annotation.resolvedType.signature();
if (CharOperation.equals(pointcutSig, sig)) {
return true;
}
// sure bindings are completed
AbstractMethodDeclaration[] methods = declaration.methods;
if (methods != null) {
- for (int i = 0, len = methods.length; i < len; i++) {
- AbstractMethodDeclaration amd = methods[i];
+ for (AbstractMethodDeclaration amd : methods) {
if (amd == null || amd.ignoreFurtherInvestigation) {
continue;
}
if (isEnum()) {
// The bindings for the eclipse binding will include values/valueof
- for (int m=0,len=ms.length;m<len;m++) {
- MethodBinding mb = ms[m];
+ for (MethodBinding mb : ms) {
if ((mb instanceof SyntheticMethodBinding) && mb.isStatic()) { // cannot use .isSynthetic() because it isn't truly synthetic
- if (CharOperation.equals(mb.selector,valuesCharArray) && mb.parameters.length==0 && mb.returnType.isArrayType() && ((ArrayBinding)mb.returnType).leafComponentType()==binding) {
+ if (CharOperation.equals(mb.selector, valuesCharArray) && mb.parameters.length == 0 && mb.returnType.isArrayType() && ((ArrayBinding) mb.returnType).leafComponentType() == binding) {
// static <EnumType>[] values()
ResolvedMember valuesMember = factory.makeResolvedMember(mb);
valuesMember.setSourceContext(new EclipseSourceContext(unit.compilationResult, 0));
valuesMember.setPosition(0, 0);
declaredMethods.add(valuesMember);
- } else if (CharOperation.equals(mb.selector,valueOfCharArray) && mb.parameters.length==1 && CharOperation.equals(mb.parameters[0].signature(),jlString) && mb.returnType==binding) {
+ } else if (CharOperation.equals(mb.selector, valueOfCharArray) && mb.parameters.length == 1 && CharOperation.equals(mb.parameters[0].signature(), jlString) && mb.returnType == binding) {
// static <EnumType> valueOf(String)
ResolvedMember valueOfMember = factory.makeResolvedMember(mb);
valueOfMember.setSourceContext(new EclipseSourceContext(unit.compilationResult, 0));
}
FieldBinding[] fields = binding.fields();
- for (int i = 0, len = fields.length; i < len; i++) {
- FieldBinding f = fields[i];
+ for (FieldBinding f : fields) {
declaredFields.add(factory.makeResolvedMember(f));
}
@Override
public boolean hasAnnotation(UnresolvedType ofType) {
ensureAnnotationTypesResolved();
- for (int a = 0, max = annotationTypes.length; a < max; a++) {
- if (ofType.equals(annotationTypes[a])) {
+ for (ResolvedType annotationType : annotationTypes) {
+ if (ofType.equals(annotationType)) {
return true;
}
}
MemberValuePair[] memberValuePairs = normalAnnotation.memberValuePairs;
if (memberValuePairs != null) {
int memberValuePairsLength = memberValuePairs.length;
- for (int i = 0; i < memberValuePairsLength; i++) {
- MemberValuePair memberValuePair = memberValuePairs[i];
+ for (MemberValuePair memberValuePair : memberValuePairs) {
MethodBinding methodBinding = memberValuePair.binding;
if (methodBinding == null) {
// is this just a marker annotation?
ajAnnotationType.isAnnotationWithRuntimeRetention());
MemberValuePair[] pairs = normalAnnotation.memberValuePairs;
if (pairs != null) {
- for (int p = 0; p < pairs.length; p++) {
- MemberValuePair pair = pairs[p];
+ for (MemberValuePair pair : pairs) {
Expression valueEx = pair.value;
AnnotationValue pairValue = null;
if (valueEx instanceof Literal) {
// Can happen if an aspect is extending a regular class
return null;
}
- for (int i = 0; i < annotations.length; i++) {
- Annotation annotation = annotations[i];
+ for (Annotation annotation : annotations) {
if (annotation != null && annotation.resolvedType != null
&& CharOperation.equals(aspectSig, annotation.resolvedType.signature())) {
// found @Aspect(...)
// safe
// ?
return determinePerClause(typeDeclaration, clause);
- } else if (annotation instanceof NormalAnnotation) {
+ } else if (annotation instanceof NormalAnnotation) {
// this kind if it was added by the visitor!
// it is an @Aspect(...something...)
NormalAnnotation theAnnotation = (NormalAnnotation) annotation;
MethodBinding binding = world.makeMethodBinding(munger.getSignature(), munger.getTypeVariableAliases());
findOrCreateInterTypeMemberFinder(sourceType).addInterTypeMethod(binding);
TypeVariableBinding[] typeVariables = binding.typeVariables;
- for (int i = 0; i < typeVariables.length; i++) {
- TypeVariableBinding tv = typeVariables[i];
+ for (TypeVariableBinding tv : typeVariables) {
String name = new String(tv.sourceName);
TypeVariableBinding[] tv2 = sourceMethod.binding.typeVariables;
- for (int j = 0; j < tv2.length; j++) {
- if (new String(tv2[j].sourceName).equals(name)) {
- typeVariables[i].declaringElement = binding;
+ for (TypeVariableBinding typeVariableBinding : tv2) {
+ if (new String(typeVariableBinding.sourceName).equals(name)) {
+ tv.declaringElement = binding;
}
}
}
- for (int i = 0; i < typeVariables.length; i++) {
- if (typeVariables[i].declaringElement == null) {
+ for (TypeVariableBinding typeVariable : typeVariables) {
+ if (typeVariable.declaringElement == null) {
throw new RuntimeException("Declaring element not set");
}
}
int fieldLength = fieldName.length;
- for (int i = 0, len = interTypeFields.size(); i < len; i++) {
- FieldBinding field = interTypeFields.get(i);
+ for (FieldBinding field : interTypeFields) {
if (field.name.length == fieldLength && CharOperation.prefixEquals(field.name, fieldName)) {
retField = resolveConflicts(sourceTypeBinding, retField, field, site, scope);
}
// if (interTypeMethods.isEmpty()) return orig;
List<MethodBinding> ret = new ArrayList<MethodBinding>(Arrays.asList(orig));
- for (int i = 0, len = interTypeMethods.size(); i < len; i++) {
- MethodBinding method = interTypeMethods.get(i);
+ for (MethodBinding method : interTypeMethods) {
ret.add(method);
}
ReferenceBinding[] interfaces = sourceTypeBinding.superInterfaces();
- for (int i = 0; i < interfaces.length; i++) {
- if (interfaces[i] instanceof SourceTypeBinding) {
- SourceTypeBinding intSTB = (SourceTypeBinding) interfaces[i];
+ for (ReferenceBinding anInterface : interfaces) {
+ if (anInterface instanceof SourceTypeBinding) {
+ SourceTypeBinding intSTB = (SourceTypeBinding) anInterface;
addPublicITDSFrom(intSTB, ret);
}
}
Set<MethodBinding> ret = new HashSet<MethodBinding>(Arrays.asList(orig));
// System.err.println("declared method: " + ret + " inters = " + interTypeMethods);
- for (int i = 0, len = interTypeMethods.size(); i < len; i++) {
- MethodBinding method = interTypeMethods.get(i);
-
+ for (MethodBinding method : interTypeMethods) {
if (CharOperation.equals(selector, method.selector)) {
ret.add(method);
}
MethodBinding ret = sourceTypeBinding.getExactMethodBase(selector, argumentTypes, refScope);
// An intertype declaration may override an inherited member (Bug#50776)
- for (int i = 0, len = interTypeMethods.size(); i < len; i++) {
- MethodBinding im = interTypeMethods.get(i);
+ for (MethodBinding im : interTypeMethods) {
if (matches(im, selector, argumentTypes)) {
return im;
}
// Ok, we need to set the typevariable declaring elements
// 1st set:
// If the typevariable is one declared on the source method, then we know we are the declaring element
- for (int i = 0; i < typeVariables.length; i++) {
- typeVariables[i].declaringElement = this;
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding variable : typeVariables) {
+ variable.declaringElement = this;
}
- for (int i = 0; i < typeVariables.length; i++) {
- if (typeVariables[i].declaringElement == null)
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeVariableBinding typeVariable : typeVariables) {
+ if (typeVariable.declaringElement == null)
throw new RuntimeException("Declaring element not set");
}
int len = m.size();
ResolvedMember[] ret = new ResolvedMember[len];
int index = 0;
- for (Iterator i = m.iterator(); i.hasNext();) {
- ret[index++] = (ResolvedMember) i.next();
+ for (Object o : m) {
+ ret[index++] = (ResolvedMember) o;
}
return ret;
}
// so we don't have to worry about interfaces, just the superclass.
onTypeX = factory.fromEclipse(type.superclass()); // abstractMethod.declaringClass);
}
- for (Iterator i = onTypeX.getInterTypeMungersIncludingSupers().iterator(); i.hasNext();) {
- ConcreteTypeMunger m = (ConcreteTypeMunger) i.next();
+ for (ConcreteTypeMunger m : onTypeX.getInterTypeMungersIncludingSupers()) {
ResolvedMember sig = m.getSignature();
if (!Modifier.isAbstract(sig.getModifiers())) {
if (ResolvedType.matches(
ResolvedType supertypeToLookAt = onTypeX.getSuperclass();
while (supertypeToLookAt != null) {
List<ConcreteTypeMunger> itMungers = supertypeToLookAt.getInterTypeMungers();
- for (Iterator<ConcreteTypeMunger> i = itMungers.iterator(); i.hasNext();) {
- ConcreteTypeMunger m = (ConcreteTypeMunger) i.next();
- if (m.getMunger()!=null && m.getMunger().getKind()== ResolvedTypeMunger.PrivilegedAccess) {
+ for (ConcreteTypeMunger m : itMungers) {
+ if (m.getMunger() != null && m.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) {
continue;
}
ResolvedMember sig = m.getSignature();
AspectDeclaration ad = (AspectDeclaration) typeDecl.enclosingType;
if (ad.concreteName != null) {
List<Declare> declares = ad.concreteName.declares;
- for (Iterator<Declare> iter = declares.iterator(); iter.hasNext();) {
- Object dec = iter.next();
+ for (Object dec : declares) {
if (dec instanceof DeclareParents) {
DeclareParents decp = (DeclareParents) dec;
TypePattern[] newparents = decp.getParents().getTypePatterns();
- for (int i = 0; i < newparents.length; i++) {
- TypePattern pattern = newparents[i];
+ for (TypePattern pattern : newparents) {
UnresolvedType ut = pattern.getExactType();
if (ut == null)
continue;
weaverType = factory.fromEclipse(type.superclass());
}
Set checked = new HashSet();
- for (Iterator i = weaverType.getInterTypeMungersIncludingSupers().iterator(); i.hasNext();) {
- ConcreteTypeMunger m = (ConcreteTypeMunger) i.next();
+ for (ConcreteTypeMunger m : weaverType.getInterTypeMungersIncludingSupers()) {
ResolvedType theAspect = m.getAspectType();
if (!checked.contains(theAspect)) {
TypeBinding tb = factory.makeTypeBinding(m.getAspectType());
Collection/* ResolvedMember */privvies = ((ReferenceType) theAspect).getPrivilegedAccesses();
// On an incremental compile the information is in the bcel delegate
if (privvies != null) {
- for (Iterator iterator = privvies.iterator(); iterator.hasNext();) {
- ResolvedMember priv = (ResolvedMember) iterator.next();
+ for (Object privvy : privvies) {
+ ResolvedMember priv = (ResolvedMember) privvy;
if (priv.getName().equals(fname)) {
return;
}
return pathname.getPath().endsWith(".class");
}
};
- for (Iterator<File> iter = inPath.iterator(); iter.hasNext();) {
- File inpathElement = iter.next();
+ for (File inpathElement : inPath) {
if (inpathElement.isDirectory()) {
File[] files = FileUtil.listFiles(inpathElement, filter);
- for (int i = 0; i < files.length; i++) {
- binaryFiles.add(new BinarySourceFile(inpathElement, files[i]));
+ for (File file : files) {
+ binaryFiles.add(new BinarySourceFile(inpathElement, file));
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
void join(Collection local, Collection global) {
- for (Iterator iter = global.iterator(); iter.hasNext();) {
- Object next = iter.next();
+ for (Object next : global) {
if (!local.contains(next)) {
local.add(next);
}
allPaths = FileSystem.ClasspathNormalizer.normalize(allPaths);
this.checkedClasspaths = new FileSystem.Classpath[allPaths.size()];
allPaths.toArray(this.checkedClasspaths);
- for (int i=0;i<checkedClasspaths.length;i++) {
- if (checkedClasspaths[i] == null) {
+ for (Classpath checkedClasspath : checkedClasspaths) {
+ if (checkedClasspath == null) {
throw new IllegalStateException();
}
}
private void copyResourcesToDestination() throws IOException {
// resources that we need to copy are contained in the injars and inpath only
- for (Iterator i = buildConfig.getInJars().iterator(); i.hasNext();) {
- File inJar = (File) i.next();
- copyResourcesFromJarFile(inJar);
- }
-
- for (Iterator i = buildConfig.getInpath().iterator(); i.hasNext();) {
- File inPathElement = (File) i.next();
- if (inPathElement.isDirectory()) {
- copyResourcesFromDirectory(inPathElement);
- } else {
- copyResourcesFromJarFile(inPathElement);
- }
- }
+ for (File inJar : buildConfig.getInJars()) {
+ copyResourcesFromJarFile(inJar);
+ }
+
+ for (File inPathElement : buildConfig.getInpath()) {
+ if (inPathElement.isDirectory()) {
+ copyResourcesFromDirectory(inPathElement);
+ }
+ else {
+ copyResourcesFromJarFile(inPathElement);
+ }
+ }
if (buildConfig.getSourcePathResources() != null) {
- for (Iterator i = buildConfig.getSourcePathResources().keySet().iterator(); i.hasNext();) {
- String resource = (String) i.next();
- File from = buildConfig.getSourcePathResources().get(resource);
- copyResourcesFromFile(from, resource, from);
- }
+ for (String resource : buildConfig.getSourcePathResources().keySet()) {
+ File from = buildConfig.getSourcePathResources().get(resource);
+ copyResourcesFromFile(from, resource, from);
+ }
}
writeManifest();
});
// For each file, add it either as a real .class file or as a resource
- for (int i = 0; i < files.length; i++) {
- // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
- // or we are in trouble...
- String filename = files[i].getAbsolutePath().substring(dir.getAbsolutePath().length() + 1);
- copyResourcesFromFile(files[i], filename, dir);
- }
+ for (File file : files) {
+ // ASSERT: files[i].getAbsolutePath().startsWith(inFile.getAbsolutePath()
+ // or we are in trouble...
+ String filename = file.getAbsolutePath().substring(dir.getAbsolutePath().length() + 1);
+ copyResourcesFromFile(file, filename, dir);
+ }
}
private void copyResourcesFromFile(File f, String filename, File src) throws IOException {
Map<File, List<String>> outputDirsAndAspects = findOutputDirsForAspects();
Set<Map.Entry<File, List<String>>> outputDirs = outputDirsAndAspects.entrySet();
- for (Iterator<Map.Entry<File, List<String>>> iterator = outputDirs.iterator(); iterator.hasNext();) {
- Map.Entry<File, List<String>> entry = iterator.next();
- File outputDir = entry.getKey();
- List<String> aspects = entry.getValue();
- ByteArrayOutputStream baos = getOutxmlContents(aspects);
- if (zos != null) {
- ZipEntry newEntry = new ZipEntry(filename);
-
- zos.putNextEntry(newEntry);
- zos.write(baos.toByteArray());
- zos.closeEntry();
- } else {
- File outputFile = new File(outputDir, filename);
- OutputStream fos = FileUtil.makeOutputStream(outputFile);
- fos.write(baos.toByteArray());
- fos.close();
- if (buildConfig.getCompilationResultDestinationManager() != null) {
- buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputFile.getPath(),
- CompilationResultDestinationManager.FILETYPE_RESOURCE);
- }
- }
- }
+ for (Map.Entry<File, List<String>> entry : outputDirs) {
+ File outputDir = entry.getKey();
+ List<String> aspects = entry.getValue();
+ ByteArrayOutputStream baos = getOutxmlContents(aspects);
+ if (zos != null) {
+ ZipEntry newEntry = new ZipEntry(filename);
+
+ zos.putNextEntry(newEntry);
+ zos.write(baos.toByteArray());
+ zos.closeEntry();
+ }
+ else {
+ File outputFile = new File(outputDir, filename);
+ OutputStream fos = FileUtil.makeOutputStream(outputFile);
+ fos.write(baos.toByteArray());
+ fos.close();
+ if (buildConfig.getCompilationResultDestinationManager() != null) {
+ buildConfig.getCompilationResultDestinationManager().reportFileWrite(outputFile.getPath(),
+ CompilationResultDestinationManager.FILETYPE_RESOURCE);
+ }
+ }
+ }
}
private ByteArrayOutputStream getOutxmlContents(List aspectNames) {
ps.println("<aspectj>");
ps.println("<aspects>");
if (aspectNames != null) {
- for (Iterator i = aspectNames.iterator(); i.hasNext();) {
- String name = (String) i.next();
- ps.println("<aspect name=\"" + name + "\"/>");
- }
+ for (Object aspectName : aspectNames) {
+ String name = (String) aspectName;
+ ps.println("<aspect name=\"" + name + "\"/>");
+ }
}
ps.println("</aspects>");
ps.println("</aspectj>");
outputDirsToAspects.put(outputDir, aspectNames);
} else {
List outputDirs = buildConfig.getCompilationResultDestinationManager().getAllOutputLocations();
- for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
- File outputDir = (File) iterator.next();
- outputDirsToAspects.put(outputDir, new ArrayList<String>());
- }
+ for (Object dir : outputDirs) {
+ File outputDir = (File) dir;
+ outputDirsToAspects.put(outputDir, new ArrayList<String>());
+ }
if (aspectNamesToFileNames != null) {
Set<Map.Entry<String, char[]>> entrySet = aspectNamesToFileNames.entrySet();
- for (Iterator<Map.Entry<String, char[]>> iterator = entrySet.iterator(); iterator.hasNext();) {
- Map.Entry<String, char[]> entry = iterator.next();
- String aspectName = entry.getKey();
- char[] fileName = entry.getValue();
- File outputDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(
- new File(new String(fileName)));
- if (!outputDirsToAspects.containsKey(outputDir)) {
- outputDirsToAspects.put(outputDir, new ArrayList<String>());
- }
- ((List) outputDirsToAspects.get(outputDir)).add(aspectName);
- }
+ for (Map.Entry<String, char[]> entry : entrySet) {
+ String aspectName = entry.getKey();
+ char[] fileName = entry.getValue();
+ File outputDir = buildConfig.getCompilationResultDestinationManager().getOutputLocationForClass(
+ new File(new String(fileName)));
+ if (!outputDirsToAspects.containsKey(outputDir)) {
+ outputDirsToAspects.put(outputDir, new ArrayList<String>());
+ }
+ ((List) outputDirsToAspects.get(outputDir)).add(aspectName);
+ }
}
}
return outputDirsToAspects;
// (they are like 'source' files then), and enables a cleaner incremental treatment of
// class file changes in indirs.
File[] binSrcs = FileUtil.listFiles(inPathElement, binarySourceFilter);
- for (int j = 0; j < binSrcs.length; j++) {
- UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrcs[j], inPathElement, outputDir);
- List<UnwovenClassFile> ucfl = new ArrayList<UnwovenClassFile>();
- ucfl.add(ucf);
- state.recordBinarySource(binSrcs[j].getPath(), ucfl);
- }
+ for (File binSrc : binSrcs) {
+ UnwovenClassFile ucf = bcelWeaver.addClassFile(binSrc, inPathElement, outputDir);
+ List<UnwovenClassFile> ucfl = new ArrayList<UnwovenClassFile>();
+ ucfl.add(ucf);
+ state.recordBinarySource(binSrc.getPath(), ucfl);
+ }
}
}
// Translate from strings to File objects
String[] filenames = new String[files.size()];
int idx = 0;
- for (Iterator<File> fIterator = files.iterator(); fIterator.hasNext();) {
- File f = fIterator.next();
- filenames[idx++] = f.getPath();
- }
+ for (File f : files) {
+ filenames[idx++] = f.getPath();
+ }
environment = state.getNameEnvironment();
if (!hasErrors || proceedOnError()) {
Collection<ClassFile> classFiles = unitResult.compiledTypes.values();
boolean shouldAddAspectName = (buildConfig.getOutxmlName() != null);
- for (Iterator<ClassFile> iter = classFiles.iterator(); iter.hasNext();) {
- ClassFile classFile = iter.next();
- String filename = new String(classFile.fileName());
- String classname = filename.replace('/', '.');
- filename = filename.replace('/', File.separatorChar) + ".class";
-
- try {
- if (buildConfig.getOutputJar() == null) {
- String outfile = writeDirectoryEntry(unitResult, classFile, filename);
- getWorld().classWriteEvent(classFile.getCompoundName());
- if (environmentSupportsIncrementalCompilation) {
- if (!classname.endsWith("$ajcMightHaveAspect")) {
- ResolvedType type = getBcelWorld().resolve(classname);
- if (type.isAspect()) {
- state.recordAspectClassFile(outfile);
- }
- }
- }
- } else {
- writeZipEntry(classFile, filename);
- }
- if (shouldAddAspectName && !classname.endsWith("$ajcMightHaveAspect")) {
- addAspectName(classname, unitResult.getFileName());
- }
- } catch (IOException ex) {
- IMessage message = EclipseAdapterUtils.makeErrorMessage(new String(unitResult.fileName),
- CANT_WRITE_RESULT, ex);
- handler.handleMessage(message);
- }
-
- }
+ for (ClassFile classFile : classFiles) {
+ String filename = new String(classFile.fileName());
+ String classname = filename.replace('/', '.');
+ filename = filename.replace('/', File.separatorChar) + ".class";
+
+ try {
+ if (buildConfig.getOutputJar() == null) {
+ String outfile = writeDirectoryEntry(unitResult, classFile, filename);
+ getWorld().classWriteEvent(classFile.getCompoundName());
+ if (environmentSupportsIncrementalCompilation) {
+ if (!classname.endsWith("$ajcMightHaveAspect")) {
+ ResolvedType type = getBcelWorld().resolve(classname);
+ if (type.isAspect()) {
+ state.recordAspectClassFile(outfile);
+ }
+ }
+ }
+ }
+ else {
+ writeZipEntry(classFile, filename);
+ }
+ if (shouldAddAspectName && !classname.endsWith("$ajcMightHaveAspect")) {
+ addAspectName(classname, unitResult.getFileName());
+ }
+ } catch (IOException ex) {
+ IMessage message = EclipseAdapterUtils.makeErrorMessage(new String(unitResult.fileName),
+ CANT_WRITE_RESULT, ex);
+ handler.handleMessage(message);
+ }
+
+ }
state.noteNewResult(unitResult);
unitResult.compiledTypes.clear(); // free up references to AjClassFile instances
}
if (unitResult.hasProblems() || unitResult.hasTasks()) {
IProblem[] problems = unitResult.getAllProblems();
- for (int i = 0; i < problems.length; i++) {
- IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problems[i], getBcelWorld(),
- progressListener);
- handler.handleMessage(message);
- }
+ for (IProblem problem : problems) {
+ IMessage message = EclipseAdapterUtils.makeMessage(unitResult.compilationUnit, problem, getBcelWorld(),
+ progressListener);
+ handler.handleMessage(message);
+ }
}
}
}
StringBuffer buf = new StringBuffer();
boolean first = true;
- for (Iterator it = buildConfig.getFullClasspath().iterator(); it.hasNext();) {
- if (first) {
- first = false;
- } else {
- buf.append(File.pathSeparator);
- }
- buf.append(it.next().toString());
- }
+ for (String s : buildConfig.getFullClasspath()) {
+ if (first) {
+ first = false;
+ }
+ else {
+ buf.append(File.pathSeparator);
+ }
+ buf.append(s.toString());
+ }
return buf.toString();
}
}
String ret = null;
- for (Iterator<String> it = buildConfig.getFullClasspath().iterator(); it.hasNext();) {
- File p = new File(it.next());
- // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar
- if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) {
-
- try {
- String version = null;
- Manifest manifest = new JarFile(p).getManifest();
- if (manifest == null) {
- ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.getText();
- continue;
- }
- Attributes attr = manifest.getAttributes("org/aspectj/lang/");
- if (null != attr) {
- version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
- if (null != version) {
- version = version.trim();
- }
- }
- // assume that users of development aspectjrt.jar know what they're doing
- if (version != null && (Version.DEVELOPMENT.equals(version) || version.endsWith("BUILD-SNAPSHOT"))) {
- // MessageUtil.info(holder,
- // "running with development version of aspectjrt.jar in " +
- // p.getAbsolutePath());
- return null;
- } else if (!Version.getText().equals(version)) {
- ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.getText() + " found "
- + version;
- continue;
- }
- } catch (IOException ioe) {
- ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
- }
- return null; // this is the "OK" return value!
- } else if (p.isFile() && p.getName().indexOf("org.aspectj.runtime") != -1) {
- // likely to be a variant from the springsource bundle repo b272591
- return null;
- } else {
- // might want to catch other classpath errors
- }
- }
+ for (String s : buildConfig.getFullClasspath()) {
+ File p = new File(s);
+ // pr112830, allow variations on aspectjrt.jar of the form aspectjrtXXXXXX.jar
+ if (p.isFile() && p.getName().startsWith("aspectjrt") && p.getName().endsWith(".jar")) {
+
+ try {
+ String version = null;
+ Manifest manifest = new JarFile(p).getManifest();
+ if (manifest == null) {
+ ret = "no manifest found in " + p.getAbsolutePath() + ", expected " + Version.getText();
+ continue;
+ }
+ Attributes attr = manifest.getAttributes("org/aspectj/lang/");
+ if (null != attr) {
+ version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
+ if (null != version) {
+ version = version.trim();
+ }
+ }
+ // assume that users of development aspectjrt.jar know what they're doing
+ if (version != null && (Version.DEVELOPMENT.equals(version) || version.endsWith("BUILD-SNAPSHOT"))) {
+ // MessageUtil.info(holder,
+ // "running with development version of aspectjrt.jar in " +
+ // p.getAbsolutePath());
+ return null;
+ }
+ else if (!Version.getText().equals(version)) {
+ ret = "bad version number found in " + p.getAbsolutePath() + " expected " + Version.getText() + " found "
+ + version;
+ continue;
+ }
+ } catch (IOException ioe) {
+ ret = "bad jar file found in " + p.getAbsolutePath() + " error: " + ioe;
+ }
+ return null; // this is the "OK" return value!
+ }
+ else if (p.isFile() && p.getName().indexOf("org.aspectj.runtime") != -1) {
+ // likely to be a variant from the springsource bundle repo b272591
+ return null;
+ }
+ else {
+ // might want to catch other classpath errors
+ }
+ }
if (ret != null) {
return ret; // last error found in potentially matching jars...
AjBuildConfig config = (AjBuildConfig) data;
List classpath = config.getClasspath();
sb.append("with classpath: ");
- for (Iterator iter = classpath.iterator(); iter.hasNext();) {
- sb.append(iter.next().toString());
- sb.append(File.pathSeparator);
- }
+ for (Object o : classpath) {
+ sb.append(o.toString());
+ sb.append(File.pathSeparator);
+ }
return sb.toString();
}
if (modifiedFiles == null) {
// do not know, so need to go looking
// not our job to account for new and deleted files
- for (Iterator<File> i = buildConfig.getFiles().iterator(); i.hasNext();) {
- File file = i.next();
+ for (File file : buildConfig.getFiles()) {
if (!file.exists()) {
continue;
}
Collection<BinarySourceFile> getModifiedBinaryFiles(long lastBuildTime) {
List<BinarySourceFile> ret = new ArrayList<BinarySourceFile>();
// not our job to account for new and deleted files
- for (Iterator<BinarySourceFile> i = buildConfig.getBinaryFiles().iterator(); i.hasNext();) {
- AjBuildConfig.BinarySourceFile bsfile = i.next();
+ for (BinarySourceFile bsfile : buildConfig.getBinaryFiles()) {
File file = bsfile.binSrc;
if (!file.exists()) {
continue;
List<File> classFiles = FileUtil.listClassFiles(dir);
- for (Iterator<File> iterator = classFiles.iterator(); iterator.hasNext();) {
- File classFile = iterator.next();
+ for (File classFile : classFiles) {
if (CHECK_STATE_FIRST && state != null) {
// Next section reworked based on bug 270033:
// if it is an aspect we may or may not be in trouble depending on whether (a) we depend on it (b) it is on the
simpleNames = ReferenceCollection.internSimpleNames(simpleNames, true);
}
int newlyAffectedFiles = 0;
- for (Iterator<Map.Entry<File, ReferenceCollection>> i = references.entrySet().iterator(); i.hasNext();) {
- Map.Entry<File, ReferenceCollection> entry = i.next();
+ for (Map.Entry<File, ReferenceCollection> entry : references.entrySet()) {
ReferenceCollection refs = entry.getValue();
if (refs != null && refs.includes(qualifiedNames, simpleNames)) {
if (listenerDefined()) {
*/
private boolean hasAnyStructuralChangesSince(long lastSuccessfulBuildTime) {
Set<Map.Entry<String, Long>> entries = structuralChangesSinceLastFullBuild.entrySet();
- for (Iterator<Map.Entry<String, Long>> iterator = entries.iterator(); iterator.hasNext();) {
- Map.Entry<String, Long> entry = iterator.next();
+ for (Map.Entry<String, Long> entry : entries) {
Long l = entry.getValue();
if (l != null) {
long lvalue = l.longValue();
// are also capturing project dependencies - when a project we depend on is rebuilt, we can just check
// it as a standalone element on our classpath rather than going through them all
List<String> modifiedCpElements = newConfig.getClasspathElementsWithModifiedContents();
- for (Iterator<String> iterator = modifiedCpElements.iterator(); iterator.hasNext();) {
- File cpElement = new File(iterator.next());
+ for (String modifiedCpElement : modifiedCpElements) {
+ File cpElement = new File(modifiedCpElement);
if (cpElement.exists() && !cpElement.isDirectory()) {
if (cpElement.lastModified() > lastSuccessfulBuildTime) {
return true;
}
if (config.getCompilationResultDestinationManager() != null) {
List<File> dirs = config.getCompilationResultDestinationManager().getAllOutputLocations();
- for (Iterator<File> iterator = dirs.iterator(); iterator.hasNext();) {
- File f = iterator.next();
+ for (File f : dirs) {
try {
File cf = f.getCanonicalFile();
if (!outputLocs.contains(cf)) {
// }
if (addedFiles != null) {
- for (Iterator<File> fIter = addedFiles.iterator(); fIter.hasNext();) {
- File o = fIter.next();
+ for (File o : addedFiles) {
// TODO isn't it a set?? why do this
if (!thisTime.contains(o)) {
thisTime.add(o);
List<BinarySourceFile> addedOrModified = new ArrayList<BinarySourceFile>();
addedOrModified.addAll(addedBinaryFiles);
addedOrModified.addAll(getModifiedBinaryFiles());
- for (Iterator<BinarySourceFile> iter = addedOrModified.iterator(); iter.hasNext();) {
- AjBuildConfig.BinarySourceFile bsf = iter.next();
+ for (BinarySourceFile bsf : addedOrModified) {
UnwovenClassFile ucf = createUnwovenClassFile(bsf);
if (ucf == null) {
continue;
*/
private void removeAllResultsOfLastBuild() {
// remove all binarySourceFiles, and all classesFromName...
- for (Iterator<List<ClassFile>> iter = this.inputClassFilesBySource.values().iterator(); iter.hasNext();) {
- List<ClassFile> cfs = iter.next();
+ for (List<ClassFile> cfs : this.inputClassFilesBySource.values()) {
for (ClassFile cf : cfs) {
cf.deleteFromFileSystem(buildConfig);
}
}
- for (Iterator<File> iterator = classesFromName.values().iterator(); iterator.hasNext();) {
- File f = iterator.next();
+ for (File f : classesFromName.values()) {
new ClassFile("", f).deleteFromFileSystem(buildConfig);
}
Set<Map.Entry<String, File>> resourceEntries = resources.entrySet();
- for (Iterator<Map.Entry<String, File>> iter = resourceEntries.iterator(); iter.hasNext();) {
- Map.Entry<String, File> resourcePair = iter.next();
+ for (Map.Entry<String, File> resourcePair : resourceEntries) {
File sourcePath = resourcePair.getValue();
File outputLoc = getOutputLocationFor(buildConfig, sourcePath);
if (outputLoc != null) {
// range of bsf is ucfs, domain is files (.class and jars) in inpath/jars
for (BinarySourceFile deletedFile : deletedBinaryFiles) {
List<ClassFile> cfs = this.inputClassFilesBySource.get(deletedFile.binSrc.getPath());
- for (Iterator<ClassFile> iterator = cfs.iterator(); iterator.hasNext();) {
- deleteClassFile(iterator.next());
+ for (ClassFile cf : cfs) {
+ deleteClassFile(cf);
}
this.inputClassFilesBySource.remove(deletedFile.binSrc.getPath());
}
references.put(sourceFile, new ReferenceCollection(cr.qualifiedReferences, cr.simpleNameReferences,cr.rootReferences));
UnwovenClassFile[] unwovenClassFiles = result.unwovenClassFiles();
- for (int i = 0; i < unwovenClassFiles.length; i++) {
- File lastTimeRound = classesFromName.get(unwovenClassFiles[i].getClassName());
- recordClassFile(unwovenClassFiles[i], lastTimeRound);
- String name = unwovenClassFiles[i].getClassName();
+ for (UnwovenClassFile unwovenClassFile : unwovenClassFiles) {
+ File lastTimeRound = classesFromName.get(unwovenClassFile.getClassName());
+ recordClassFile(unwovenClassFile, lastTimeRound);
+ String name = unwovenClassFile.getClassName();
if (lastTimeRound == null) {
deltaAddedClasses.add(name);
}
- classesFromName.put(name, new File(unwovenClassFiles[i].getFilename()));
+ classesFromName.put(name, new File(unwovenClassFile.getFilename()));
}
// need to do this before types are deleted from the World...
List<ClassFile> classFiles = this.fullyQualifiedTypeNamesResultingFromCompilationUnit.get(sourceFile);
if (classFiles != null) {
- for (int i = 0; i < unwovenClassFiles.length; i++) {
+ for (UnwovenClassFile unwovenClassFile : unwovenClassFiles) {
// deleting also deletes types from the weaver... don't do this if they are
// still present this time around...
- removeFromClassFilesIfPresent(unwovenClassFiles[i].getClassName(), classFiles);
+ removeFromClassFilesIfPresent(unwovenClassFile.getClassName(), classFiles);
}
for (ClassFile cf : classFiles) {
recordTypeChanged(cf.fullyQualifiedTypeName);
private void recordFQNsResultingFromCompilationUnit(File sourceFile, InterimCompilationResult icr) {
List<ClassFile> classFiles = new ArrayList<ClassFile>();
UnwovenClassFile[] types = icr.unwovenClassFiles();
- for (int i = 0; i < types.length; i++) {
- classFiles.add(new ClassFile(types[i].getClassName(), new File(types[i].getFilename())));
+ for (UnwovenClassFile type : types) {
+ classFiles.add(new ClassFile(type.getClassName(), new File(type.getFilename())));
}
this.fullyQualifiedTypeNamesResultingFromCompilationUnit.put(sourceFile, classFiles);
}
if (cr != null) {
Map compiledTypes = cr.compiledTypes;
if (compiledTypes != null) {
- for (Iterator<char[]> iterator = compiledTypes.keySet().iterator(); iterator.hasNext();) {
- char[] className = iterator.next();
+ for (char[] className : (Iterable<char[]>) compiledTypes.keySet()) {
String typeName = new String(className).replace('/', '.');
if (typeName.indexOf(BcelWeaver.SYNTHETIC_CLASS_POSTFIX) == -1) {
ResolvedType rt = world.resolve(typeName);
if (existingIfs.length != newIfsAsChars.length) {
return true;
}
- new_interface_loop: for (int i = 0; i < newIfsAsChars.length; i++) {
- for (int j = 0; j < existingIfs.length; j++) {
- if (CharOperation.equals(existingIfs[j], newIfsAsChars[i])) {
+ new_interface_loop:
+ for (char[] newIfsAsChar : newIfsAsChars) {
+ for (char[] existingIf : existingIfs) {
+ if (CharOperation.equals(existingIf, newIfsAsChar)) {
continue new_interface_loop;
}
}
if (newFields.length != existingFs.length) {
return true;
}
- new_field_loop: for (int i = 0; i < newFields.length; i++) {
- IBinaryField field = newFields[i];
+ new_field_loop:
+ for (IBinaryField field : newFields) {
char[] fieldName = field.getName();
- for (int j = 0; j < existingFs.length; j++) {
- if (CharOperation.equals(existingFs[j].getName(), fieldName)) {
- IBinaryField existing = existingFs[j];
+ for (IBinaryField existingF : existingFs) {
+ if (CharOperation.equals(existingF.getName(), fieldName)) {
+ IBinaryField existing = existingF;
if (!modifiersEqual(field.getModifiers(), existing.getModifiers())) {
return true;
}
if (newMethods.length != existingMs.length) {
return true;
}
- new_method_loop: for (int i = 0; i < newMethods.length; i++) {
- IBinaryMethod method = newMethods[i];
+ new_method_loop:
+ for (IBinaryMethod method : newMethods) {
char[] methodName = method.getSelector();
- for (int j = 0; j < existingMs.length; j++) {
- if (CharOperation.equals(existingMs[j].getSelector(), methodName)) {
+ for (IBinaryMethod existingM : existingMs) {
+ if (CharOperation.equals(existingM.getSelector(), methodName)) {
// candidate match
- if (!CharOperation.equals(method.getMethodDescriptor(), existingMs[j].getMethodDescriptor())) {
+ if (!CharOperation.equals(method.getMethodDescriptor(), existingM.getMethodDescriptor())) {
// ok, the descriptors don't match, but is this a funky ctor on a non-static inner
// type?
// boolean mightBeOK =
continue; // might be overloading
} else {
// matching sigs
- IBinaryMethod existing = existingMs[j];
+ IBinaryMethod existing = existingM;
if (!modifiersEqual(method.getModifiers(), existing.getModifiers())) {
return true;
}
if (existingIfs.length != newIfsAsChars.length) {
return true;
}
- new_interface_loop: for (int i = 0; i < newIfsAsChars.length; i++) {
- for (int j = 0; j < existingIfs.length; j++) {
- if (CharOperation.equals(existingIfs[j], newIfsAsChars[i])) {
+ new_interface_loop:
+ for (char[] newIfsAsChar : newIfsAsChars) {
+ for (char[] existingIf : existingIfs) {
+ if (CharOperation.equals(existingIf, newIfsAsChar)) {
continue new_interface_loop;
}
}
- logAnalysis(filename,"set of interfaces changed. old="+stringify(existingIfs)+" new="+stringify(newIfsAsChars));
+ logAnalysis(filename, "set of interfaces changed. old=" + stringify(existingIfs) + " new=" + stringify(newIfsAsChars));
return true;
}
logAnalysis(filename,"number of fields changed. old="+stringify(existingFs)+" new="+stringify(newFields));
return true;
}
- new_field_loop: for (int i = 0; i < newFields.length; i++) {
- IBinaryField field = newFields[i];
+ new_field_loop:
+ for (IBinaryField field : newFields) {
char[] fieldName = field.getName();
- for (int j = 0; j < existingFs.length; j++) {
- if (CharOperation.equals(existingFs[j].getName(), fieldName)) {
- IBinaryField existing = existingFs[j];
+ for (IBinaryField existingF : existingFs) {
+ if (CharOperation.equals(existingF.getName(), fieldName)) {
+ IBinaryField existing = existingF;
if (!modifiersEqual(field.getModifiers(), existing.getModifiers())) {
- logAnalysis(filename,"field modifiers changed '"+existing+"' old=0x"+Integer.toHexString(existing.getModifiers())+" new=0x"+Integer.toHexString(field.getModifiers()));
+ logAnalysis(filename, "field modifiers changed '" + existing + "' old=0x" + Integer.toHexString(existing.getModifiers()) + " new=0x" + Integer.toHexString(field.getModifiers()));
return true;
}
if (!CharOperation.equals(existing.getTypeName(), field.getTypeName())) {
- logAnalysis(filename,"field type changed '"+existing+"' old="+new String(existing.getTypeName())+" new="+new String(field.getTypeName()));
+ logAnalysis(filename, "field type changed '" + existing + "' old=" + new String(existing.getTypeName()) + " new=" + new String(field.getTypeName()));
return true;
}
char[] existingGSig = existing.getGenericSignature();
char[] fieldGSig = field.getGenericSignature();
if ((existingGSig == null && fieldGSig != null) || (existingGSig != null && fieldGSig == null)) {
- logAnalysis(filename,"field generic sig changed '"+existing+"' old="+
- (existingGSig==null?"null":new String(existingGSig))+" new="+(fieldGSig==null?"null":new String(fieldGSig)));
+ logAnalysis(filename, "field generic sig changed '" + existing + "' old=" +
+ (existingGSig == null ? "null" : new String(existingGSig)) + " new=" + (fieldGSig == null ? "null" : new String(fieldGSig)));
return true;
}
if (existingGSig != null) {
if (!CharOperation.equals(existingGSig, fieldGSig)) {
- logAnalysis(filename,"field generic sig changed '"+existing+"' old="+
- (existingGSig==null?"null":new String(existingGSig))+" new="+(fieldGSig==null?"null":new String(fieldGSig)));
+ logAnalysis(filename, "field generic sig changed '" + existing + "' old=" +
+ (existingGSig == null ? "null" : new String(existingGSig)) + " new=" + (fieldGSig == null ? "null" : new String(fieldGSig)));
return true;
}
}
continue new_field_loop;
}
}
- logAnalysis(filename,"field changed. New field detected '"+field+"'");
+ logAnalysis(filename, "field changed. New field detected '" + field + "'");
return true;
}
logAnalysis(filename,"number of methods changed. old="+stringify(existingMs)+" new="+stringify(newMethods));
return true;
}
- new_method_loop: for (int i = 0; i < newMethods.length; i++) {
- IBinaryMethod method = newMethods[i];
+ new_method_loop:
+ for (IBinaryMethod method : newMethods) {
char[] methodName = method.getSelector();
- for (int j = 0; j < existingMs.length; j++) {
- if (CharOperation.equals(existingMs[j].getSelector(), methodName)) {
+ for (IBinaryMethod existingM : existingMs) {
+ if (CharOperation.equals(existingM.getSelector(), methodName)) {
// candidate match
- if (!CharOperation.equals(method.getMethodDescriptor(), existingMs[j].getMethodDescriptor())) {
+ if (!CharOperation.equals(method.getMethodDescriptor(), existingM.getMethodDescriptor())) {
// ok, the descriptors don't match, but is this a funky ctor on a non-static inner
// type?
// boolean mightBeOK =
continue; // might be overloading
} else {
// matching sigs
- IBinaryMethod existing = existingMs[j];
+ IBinaryMethod existing = existingM;
if (!modifiersEqual(method.getModifiers(), existing.getModifiers())) {
- logAnalysis(filename,"method modifiers changed '"+existing+"' old=0x"+Integer.toHexString(existing.getModifiers())+" new=0x"+Integer.toHexString(method.getModifiers()));
+ logAnalysis(filename, "method modifiers changed '" + existing + "' old=0x" + Integer.toHexString(existing.getModifiers()) + " new=0x" + Integer.toHexString(method.getModifiers()));
return true;
}
if (exceptionClausesDiffer(existing, method)) {
- logAnalysis(filename,"method exception clauses changed '"+existing+"' old="+existing+" new="+method);
+ logAnalysis(filename, "method exception clauses changed '" + existing + "' old=" + existing + " new=" + method);
return true;
}
char[] existingGSig = existing.getGenericSignature();
char[] methodGSig = method.getGenericSignature();
if ((existingGSig == null && methodGSig != null) || (existingGSig != null && methodGSig == null)) {
- logAnalysis(filename,"method generic sig changed '"+existing+"' old="+
- (existingGSig==null?"null":new String(existingGSig))+" new="+(methodGSig==null?"null":new String(methodGSig)));
+ logAnalysis(filename, "method generic sig changed '" + existing + "' old=" +
+ (existingGSig == null ? "null" : new String(existingGSig)) + " new=" + (methodGSig == null ? "null" : new String(methodGSig)));
return true;
}
if (existingGSig != null) {
if (!CharOperation.equals(existingGSig, methodGSig)) {
- logAnalysis(filename,"method generic sig changed '"+existing+"' old="+
- (existingGSig==null?"null":new String(existingGSig))+" new="+(methodGSig==null?"null":new String(methodGSig)));
+ logAnalysis(filename, "method generic sig changed '" + existing + "' old=" +
+ (existingGSig == null ? "null" : new String(existingGSig)) + " new=" + (methodGSig == null ? "null" : new String(methodGSig)));
return true;
}
}
// TODO missing a return true here? Meaning we have a field in the new that we can't find in the old!
}
- logAnalysis(filename,"method changed. New method detected '"+stringify(method)+"' (might be a rename)");
+ logAnalysis(filename, "method changed. New method detected '" + stringify(method) + "' (might be a rename)");
return true; // (no match found)
}
// System.err.println("simple: " + simpleStrings);
// System.err.println("qualif: " + qualifiedStrings);
- for (Iterator<Map.Entry<File, ReferenceCollection>> i = references.entrySet().iterator(); i.hasNext();) {
- Map.Entry<File, ReferenceCollection> entry = i.next();
+ for (Map.Entry<File, ReferenceCollection> entry : references.entrySet()) {
ReferenceCollection refs = entry.getValue();
if (refs != null && refs.includes(qualifiedNames, simpleNames)) {
File file = entry.getKey();
}
});
if (weaverGenerated != null) {
- for (int i = 0; i < weaverGenerated.length; i++) {
- weaverGenerated[i].delete();
+ for (File file : weaverGenerated) {
+ file.delete();
if (buildConfig != null && buildConfig.getCompilationResultDestinationManager() != null) {
- buildConfig.getCompilationResultDestinationManager().reportFileRemove(weaverGenerated[i].getPath(),
+ buildConfig.getCompilationResultDestinationManager().reportFileRemove(file.getPath(),
CompilationResultDestinationManager.FILETYPE_CLASS);
}
}
TypeReference[] typeRefs = pstr.typeArguments;
if (typeRefs != null && typeRefs.length > 0) {
handleSig.append("\\<");
- for (int i = 0; i < typeRefs.length; i++) {
- TypeReference typeR = typeRefs[i];
+ for (TypeReference typeR : typeRefs) {
TypeBinding typeB = typeR.resolvedType;
if (typeB == null) {
typeB = typeR.resolveType(scope);
TypeReference[] typeRefs = pstr.typeArguments[i];
if (typeRefs != null && typeRefs.length > 0) {
handleSig.append("\\<");
- for (int j = 0; j < typeRefs.length; j++) {
- TypeReference typeR = typeRefs[j];
+ for (TypeReference typeR : typeRefs) {
TypeBinding typeB = typeR.resolvedType;
if (typeB == null) {
typeB = typeR.resolveType(scope);
List<char[]> paramSigs = new ArrayList<char[]>();
List<String> paramSourceRefs = new ArrayList<String>();
boolean problemWithSourceRefs = false;
- for (int i = 0; i < argArray.length; i++) {
- String argName = new String(argArray[i].name);
+ for (Argument argument : argArray) {
+ String argName = new String(argument.name);
// String argType = "<UnknownType>"; // pr135052
- if (acceptArgument(argName, argArray[i].type.toString())) {
- TypeReference typeR = argArray[i].type;
+ if (acceptArgument(argName, argument.type.toString())) {
+ TypeReference typeR = argument.type;
if (typeR != null && md.scope != null) {
TypeBinding typeB = typeR.resolvedType;
if (typeB == null) {
// Check if already there
IProgramElement sourceFolderNode = null;
List<IProgramElement> kids = root.getChildren();
- for (Iterator<IProgramElement> iterator = kids.iterator(); iterator.hasNext();) {
- IProgramElement child = (IProgramElement) iterator.next();
+ for (IProgramElement child : kids) {
if (child.getKind() == IProgramElement.Kind.SOURCE_FOLDER && child.getName().equals(sourceFolder)) {
sourceFolderNode = child;
break;
IProgramElement pkgNode = null;
if (structureModel != null && structureModel.getHierarchy().getRoot() != null && rootForSource.getChildren() != null) {
- for (Iterator<IProgramElement> it = rootForSource.getChildren().iterator(); it.hasNext();) {
- IProgramElement currNode = (IProgramElement) it.next();
+ for (IProgramElement currNode : rootForSource.getChildren()) {
if (pkgName.equals(currNode.getName())) {
pkgNode = currNode;
break;
}
ResolvedMember[] members = onType.resolve(world).getDeclaredPointcuts();
if (members != null) {
- for (int i = 0; i < members.length; i++) {
- if (members[i].getName().equals(rp.name)) {
- return members[i];
+ for (ResolvedMember member : members) {
+ if (member.getName().equals(rp.name)) {
+ return member;
}
}
}
// If the user has turned off classfile line number gen, then we may not be able to tell them
// about all secondary locations (pr209372)
int validPlaces = 0;
- for (int ii = 0; ii < seeAlso.length; ii++) {
- if (seeAlso[ii].getSourceLineNumber() >= 0)
+ for (IProblem value : seeAlso) {
+ if (value.getSourceLineNumber() >= 0)
validPlaces++;
}
ISourceLocation[] seeAlsoLocations = new ISourceLocation[validPlaces];
int pos = 0;
- for (int i = 0; i < seeAlso.length; i++) {
- if (seeAlso[i].getSourceLineNumber() >= 0) {
- seeAlsoLocations[pos++] = new SourceLocation(new File(new String(seeAlso[i].getOriginatingFileName())), seeAlso[i]
+ for (IProblem iProblem : seeAlso) {
+ if (iProblem.getSourceLineNumber() >= 0) {
+ seeAlsoLocations[pos++] = new SourceLocation(new File(new String(iProblem.getOriginatingFileName())), iProblem
.getSourceLineNumber());
}
}
if (result == null) return;
IProblem[] probs = result.getProblems();
if (probs!=null) {
- for (int i = 0; i < probs.length; i++) {
- IProblem problem = probs[i];
+ for (IProblem problem : probs) {
if (problem == null) continue;
- if (problem.getID() == IProblem.UnusedMethodDeclaredThrownException
+ if (problem.getID() == IProblem.UnusedMethodDeclaredThrownException
|| problem.getID() == IProblem.UnusedConstructorDeclaredThrownException) {
if (problem.getSourceLineNumber() == problemLineNumber) {
- UnusedDeclaredThrownExceptionFilter filter =
- new UnusedDeclaredThrownExceptionFilter(problem);
- result.removeProblems(filter);
+ UnusedDeclaredThrownExceptionFilter filter =
+ new UnusedDeclaredThrownExceptionFilter(problem);
+ result.removeProblems(filter);
}
}
}
try {
// Set fileSet = StructureModelManager.INSTANCE.getStructureModel().getFileMap().entrySet();
Set fileSet = model.getHierarchy().getFileMapEntrySet();
- for (Iterator it = fileSet.iterator(); it.hasNext();) {
- IProgramElement peNode = (IProgramElement) ((Map.Entry) it.next()).getValue();
+ for (Object o : fileSet) {
+ IProgramElement peNode = (IProgramElement) ((Map.Entry) o).getValue();
dumpStructureToFile(peNode);
}
} catch (IOException ioe) {
private void printDecls(IProgramElement node) {
print("(");
- for (Iterator it = node.getChildren().iterator(); it.hasNext();) {
+ for (Object nodeObject : node.getChildren()) {
// this ignores relations on the compile unit
- Object nodeObject = it.next();
// throw new RuntimeException("unimplemented");
// if (nodeObject instanceof IProgramElement) {
IProgramElement child = (IProgramElement) nodeObject;
public static void persist() {
// check serialization works
Set<Map.Entry<String, AjState>> entries = incrementalStates.entrySet();
- for (Iterator<Map.Entry<String, AjState>> iterator = entries.iterator(); iterator.hasNext();) {
- Map.Entry<String, AjState> entry = iterator.next();
+ for (Map.Entry<String, AjState> entry : entries) {
System.out.println("Name " + entry.getKey());
File f = new File("n:/temp/foo.ajstate");
try {
}
public static void clearIncrementalStates() {
- for (Iterator iter = incrementalStates.values().iterator(); iter.hasNext();) {
- AjState element = (AjState) iter.next();
+ for (AjState element : incrementalStates.values()) {
element.wipeAllKnowledge();
}
incrementalStates.clear();
System.err.println("> findStateManagingOutputLocation(" + location + ") has " + allStates.size()
+ " states to look through");
}
- for (Iterator<AjState> iter = allStates.iterator(); iter.hasNext();) {
- AjState element = iter.next();
+ for (AjState element : allStates) {
AjBuildConfig ajbc = element.getBuildConfig();
if (ajbc == null) {
// FIXME asc why can it ever be null?
CompilationResultDestinationManager outputManager = ajbc.getCompilationResultDestinationManager();
if (outputManager != null) {
List outputDirs = outputManager.getAllOutputLocations();
- for (Iterator iterator = outputDirs.iterator(); iterator.hasNext();) {
- File dir = (File) iterator.next();
+ for (Object o : outputDirs) {
+ File dir = (File) o;
if (dir.equals(location)) {
if (debugIncrementalStates) {
System.err.println("< findStateManagingOutputLocation(" + location + ") returning " + element);
adviceDecl.setFlags(adviceDecl.getFlags() | ASTNode.MALFORMED);
break;
case AST.JLS3:
- for (int i = 0, max = typeParameters.length; i < max; i++) {
- ((AroundAdviceDeclaration) adviceDecl).typeParameters().add(convert(typeParameters[i]));
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter typeParameter : typeParameters) {
+ ((AroundAdviceDeclaration) adviceDecl).typeParameters().add(convert(typeParameter));
}
}
}
org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference[] thrownExceptions = adviceDeclaration.thrownExceptions;
if (thrownExceptions != null) {
int thrownExceptionsLength = thrownExceptions.length;
- for (int i = 0; i < thrownExceptionsLength; i++) {
- adviceDecl.thrownExceptions().add(convert(thrownExceptions[i]));
+ for (TypeReference thrownException : thrownExceptions) {
+ adviceDecl.thrownExceptions().add(convert(thrownException));
}
}
org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument[] parameters = adviceDeclaration.arguments;
if (parameters != null) {
int parametersLength = parameters.length;
- for (int i = 0; i < parametersLength; i++) {
- adviceDecl.parameters().add(convert(parameters[i]));
+ for (Argument parameter : parameters) {
+ adviceDecl.parameters().add(convert(parameter));
}
}
int start = adviceDeclaration.sourceStart;
methodDecl.setFlags(methodDecl.getFlags() | ASTNode.MALFORMED);
break;
default :
- for (int i = 0, max = typeParameters.length; i < max; i++) {
- methodDecl.typeParameters().add(convert(typeParameters[i]));
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter typeParameter : typeParameters) {
+ methodDecl.typeParameters().add(convert(typeParameter));
}
}
}
}
TypePattern[] weaverTypePatterns = dp.getParents().getTypePatterns();
List typePatterns = ((DeclareParentsDeclaration) declareDeclaration).parentTypePatterns();
- for (int i = 0; i < weaverTypePatterns.length; i++) {
- typePatterns.add(convert(weaverTypePatterns[i]));
+ for (TypePattern weaverTypePattern : weaverTypePatterns) {
+ typePatterns.add(convert(weaverTypePattern));
}
} else if (declare instanceof DeclarePrecedence) {
declareDeclaration = new org.aspectj.org.eclipse.jdt.core.dom.DeclarePrecedenceDeclaration(this.ast);
DeclarePrecedence dp = (DeclarePrecedence) declare;
TypePattern[] weaverTypePatterns = dp.getPatterns().getTypePatterns();
List typePatterns = ((DeclarePrecedenceDeclaration) declareDeclaration).typePatterns();
- for (int i = 0; i < weaverTypePatterns.length; i++) {
- typePatterns.add(convert(weaverTypePatterns[i]));
+ for (TypePattern weaverTypePattern : weaverTypePatterns) {
+ typePatterns.add(convert(weaverTypePattern));
}
} else if (declare instanceof DeclareSoft) {
declareDeclaration = new DeclareSoftDeclaration(this.ast);
org.aspectj.org.eclipse.jdt.internal.compiler.ast.Argument[] parameters = pointcutDeclaration.arguments;
if (parameters != null) {
int parametersLength = parameters.length;
- for (int i = 0; i < parametersLength; i++) {
- pointcutDecl.parameters().add(convert(parameters[i]));
+ for (Argument parameter : parameters) {
+ pointcutDecl.parameters().add(convert(parameter));
}
}
org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] expressions = expression.expressions;
if (expressions != null) {
int length = expressions.length;
- for (int i = 0; i < length; i++) {
- Expression expr = super.convert(expressions[i]);
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression value : expressions) {
+ Expression expr = super.convert(value);
if (this.resolveBindings) {
- recordNodes(expr, expressions[i]);
+ recordNodes(expr, value);
}
arrayInitializer.expressions().add(expr);
}
org.aspectj.org.eclipse.jdt.internal.compiler.ast.ImportReference[] imports = unit.imports;
if (imports != null) {
int importLength = imports.length;
- for (int i = 0; i < importLength; i++) {
- compilationUnit.imports().add(convertImport(imports[i]));
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.ImportReference anImport : imports) {
+ compilationUnit.imports().add(convertImport(anImport));
}
}
org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration[] types = unit.types;
if (types != null) {
int typesLength = types.length;
- for (int i = 0; i < typesLength; i++) {
- org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration declaration = types[i];
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration declaration : types) {
if (CharOperation.equals(declaration.name, TypeConstants.PACKAGE_INFO_NAME)) {
continue;
}
forStatement.initializers().add(variableDeclarationExpression);
} else {
int initializationsLength = initializations.length;
- for (int i = 0; i < initializationsLength; i++) {
- Expression initializer = convertToExpression(initializations[i]);
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement initialization : initializations) {
+ Expression initializer = convertToExpression(initialization);
if (initializer != null) {
forStatement.initializers().add(initializer);
} else {
org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement[] increments = statement.increments;
if (increments != null) {
int incrementsLength = increments.length;
- for (int i = 0; i < incrementsLength; i++) {
- forStatement.updaters().add(convertToExpression(increments[i]));
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement increment : increments) {
+ forStatement.updaters().add(convertToExpression(increment));
}
}
forStatement.setBody(convert(statement.action));
setTypeNameForAnnotation(annotation, normalAnnotation);
org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair[] memberValuePairs = annotation.memberValuePairs;
if (memberValuePairs != null) {
- for (int i = 0, max = memberValuePairs.length; i < max; i++) {
- normalAnnotation.values().add(convert(memberValuePairs[i]));
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.MemberValuePair memberValuePair : memberValuePairs) {
+ normalAnnotation.values().add(convert(memberValuePair));
}
}
int start = annotation.sourceStart;
org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression[] arguments = allocation.arguments;
if (arguments != null) {
int length = arguments.length;
- for (int i = 0; i < length; i++) {
- Expression argument = super.convert(arguments[i]);
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Expression expression : arguments) {
+ Expression argument = super.convert(expression);
if (this.resolveBindings) {
- recordNodes(argument, arguments[i]);
+ recordNodes(argument, expression);
}
classInstanceCreation.arguments().add(argument);
}
org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement[] statements = statement.statements;
if (statements != null) {
int statementsLength = statements.length;
- for (int i = 0; i < statementsLength; i++) {
- switchStatement.statements().add(convert(statements[i]));
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.Statement value : statements) {
+ switchStatement.statements().add(convert(value));
}
}
return switchStatement;
if (superInterfaces != null) {
switch(this.ast.apiLevel) {
case AST.JLS2_INTERNAL :
- for (int index = 0, length = superInterfaces.length; index < length; index++) {
- typeDecl.internalSuperInterfaces().add(convert(superInterfaces[index]));
+ for (TypeReference anInterface : superInterfaces) {
+ typeDecl.internalSuperInterfaces().add(convert(anInterface));
}
break;
default :
- for (int index = 0, length = superInterfaces.length; index < length; index++) {
- typeDecl.superInterfaceTypes().add(convertType(superInterfaces[index]));
+ for (TypeReference superInterface : superInterfaces) {
+ typeDecl.superInterfaceTypes().add(convertType(superInterface));
}
}
}
typeDecl.setFlags(typeDecl.getFlags() | ASTNode.MALFORMED);
break;
default :
- for (int index = 0, length = typeParameters.length; index < length; index++) {
- typeDecl.typeParameters().add(convert(typeParameters[index]));
+ for (org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeParameter typeParameter : typeParameters) {
+ typeDecl.typeParameters().add(convert(typeParameter));
}
}
}
TypeReference[] bounds = typeParameter.bounds;
if (bounds != null) {
Type type = null;
- for (int index = 0, length = bounds.length; index < length; index++) {
- type = convertType(bounds[index]);
+ for (TypeReference bound : bounds) {
+ type = convertType(bound);
typeParameter2.typeBounds().add(type);
end = type.getStartPosition() + type.getLength() - 1;
}
TypeReference[] typeArguments = parameterizedSingleTypeReference.typeArguments;
if (typeArguments != null) {
Type type2 = null;
- for (int i = 0, max = typeArguments.length; i < max; i++) {
- type2 = convertType(typeArguments[i]);
+ for (TypeReference typeArgument : typeArguments) {
+ type2 = convertType(typeArgument);
((ParameterizedType) type).typeArguments().add(type2);
end = type2.getStartPosition() + type2.getLength() - 1;
}
int numberOfEnclosingType = 0;
int startingIndex = 0;
int endingIndex = 0;
- for (int i = 0, max = typeArguments.length; i < max; i++) {
- if (typeArguments[i] != null) {
+ for (TypeReference[] typeArgument : typeArguments) {
+ if (typeArgument != null) {
numberOfEnclosingType++;
} else if (numberOfEnclosingType == 0) {
endingIndex++;
private void lookupForScopes() {
if (this.pendingNameScopeResolution != null) {
- for (Iterator iterator = this.pendingNameScopeResolution.iterator(); iterator.hasNext();) {
- Name name = (Name) iterator.next();
+ for (Object o : this.pendingNameScopeResolution) {
+ Name name = (Name) o;
this.ast.getBindingResolver().recordScope(name, lookupScope(name));
}
}
if (this.pendingThisExpressionScopeResolution != null) {
- for (Iterator iterator = this.pendingThisExpressionScopeResolution.iterator(); iterator.hasNext();) {
- ThisExpression thisExpression = (ThisExpression) iterator.next();
+ for (Object o : this.pendingThisExpressionScopeResolution) {
+ ThisExpression thisExpression = (ThisExpression) o;
this.ast.getBindingResolver().recordScope(thisExpression, lookupScope(thisExpression));
}
}
* (element type: <code>IExtendedModifiers</code>)
*/
void printModifiers(List ext) {
- for (Iterator it = ext.iterator(); it.hasNext(); ) {
- ASTNode p = (ASTNode) it.next();
+ for (Object o : ext) {
+ ASTNode p = (ASTNode) o;
p.accept(this);
this.buffer.append(" ");//$NON-NLS-1$
}
this.buffer.append("@interface ");//$NON-NLS-1$
node.getName().accept(this);
this.buffer.append(" {");//$NON-NLS-1$
- for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
- BodyDeclaration d = (BodyDeclaration) it.next();
+ for (Object o : node.bodyDeclarations()) {
+ BodyDeclaration d = (BodyDeclaration) o;
d.accept(this);
}
this.buffer.append("}\n");//$NON-NLS-1$
public boolean visit(AnonymousClassDeclaration node) {
this.buffer.append("{\n");//$NON-NLS-1$
this.indent++;
- for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
- BodyDeclaration b = (BodyDeclaration) it.next();
+ for (Object o : node.bodyDeclarations()) {
+ BodyDeclaration b = (BodyDeclaration) o;
b.accept(this);
}
this.indent--;
int dims = at.getDimensions();
Type elementType = at.getElementType();
elementType.accept(this);
- for (Iterator it = node.dimensions().iterator(); it.hasNext(); ) {
+ for (Object o : node.dimensions()) {
this.buffer.append("[");//$NON-NLS-1$
- Expression e = (Expression) it.next();
+ Expression e = (Expression) o;
e.accept(this);
this.buffer.append("]");//$NON-NLS-1$
dims--;
public boolean visit(Block node) {
this.buffer.append("{\n");//$NON-NLS-1$
this.indent++;
- for (Iterator it = node.statements().iterator(); it.hasNext(); ) {
- Statement s = (Statement) it.next();
+ for (Object o : node.statements()) {
+ Statement s = (Statement) o;
s.accept(this);
}
this.indent--;
if (node.getPackage() != null) {
node.getPackage().accept(this);
}
- for (Iterator it = node.imports().iterator(); it.hasNext(); ) {
- ImportDeclaration d = (ImportDeclaration) it.next();
+ for (Object value : node.imports()) {
+ ImportDeclaration d = (ImportDeclaration) value;
d.accept(this);
}
- for (Iterator it = node.types().iterator(); it.hasNext(); ) {
- AbstractTypeDeclaration d = (AbstractTypeDeclaration) it.next();
+ for (Object o : node.types()) {
+ AbstractTypeDeclaration d = (AbstractTypeDeclaration) o;
d.accept(this);
}
return false;
}
if (!node.bodyDeclarations().isEmpty()) {
this.buffer.append("; ");//$NON-NLS-1$
- for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
- BodyDeclaration d = (BodyDeclaration) it.next();
+ for (Object o : node.bodyDeclarations()) {
+ BodyDeclaration d = (BodyDeclaration) o;
d.accept(this);
// other body declarations include trailing punctuation
}
final List extendedOperands = node.extendedOperands();
if (extendedOperands.size() != 0) {
this.buffer.append(' ');
- for (Iterator it = extendedOperands.iterator(); it.hasNext(); ) {
+ for (Object extendedOperand : extendedOperands) {
this.buffer.append(node.getOperator().toString()).append(' ');
- Expression e = (Expression) it.next();
+ Expression e = (Expression) extendedOperand;
e.accept(this);
}
}
public boolean visit(Javadoc node) {
printIndent();
this.buffer.append("/** ");//$NON-NLS-1$
- for (Iterator it = node.tags().iterator(); it.hasNext(); ) {
- ASTNode e = (ASTNode) it.next();
+ for (Object o : node.tags()) {
+ ASTNode e = (ASTNode) o;
e.accept(this);
}
this.buffer.append("\n */\n");//$NON-NLS-1$
if (node.getJavadoc() != null) {
node.getJavadoc().accept(this);
}
- for (Iterator it = node.annotations().iterator(); it.hasNext(); ) {
- Annotation p = (Annotation) it.next();
+ for (Object o : node.annotations()) {
+ Annotation p = (Annotation) o;
p.accept(this);
this.buffer.append(" ");//$NON-NLS-1$
}
this.buffer.append(") ");//$NON-NLS-1$
this.buffer.append("{\n");//$NON-NLS-1$
this.indent++;
- for (Iterator it = node.statements().iterator(); it.hasNext(); ) {
- Statement s = (Statement) it.next();
+ for (Object o : node.statements()) {
+ Statement s = (Statement) o;
s.accept(this);
this.indent--; // incremented in visit(SwitchCase)
}
previousRequiresWhiteSpace = true;
}
boolean previousRequiresNewLine = false;
- for (Iterator it = node.fragments().iterator(); it.hasNext(); ) {
- ASTNode e = (ASTNode) it.next();
+ for (Object o : node.fragments()) {
+ ASTNode e = (ASTNode) o;
// assume text elements include necessary leading and trailing whitespace
// but Name, MemberRef, MethodRef, and nested TagElement do not include white space
boolean currentIncludesWhiteSpace = (e instanceof TextElement);
this.buffer.append("try ");//$NON-NLS-1$
node.getBody().accept(this);
this.buffer.append(" ");//$NON-NLS-1$
- for (Iterator it = node.catchClauses().iterator(); it.hasNext(); ) {
- CatchClause cc = (CatchClause) it.next();
+ for (Object o : node.catchClauses()) {
+ CatchClause cc = (CatchClause) o;
cc.accept(this);
}
if (node.getFinally() != null) {
this.buffer.append("{\n");//$NON-NLS-1$
this.indent++;
BodyDeclaration prev = null;
- for (Iterator it = node.bodyDeclarations().iterator(); it.hasNext(); ) {
- BodyDeclaration d = (BodyDeclaration) it.next();
+ for (Object o : node.bodyDeclarations()) {
+ BodyDeclaration d = (BodyDeclaration) o;
if (prev instanceof EnumConstantDeclaration) {
// enum constant declarations do not include punctuation
if (d instanceof EnumConstantDeclaration) {
List bd = bodyDeclarations();
// ajh02: 0 bodyDeclarations :-/
int pointcutCount = 0;
- for (Iterator it = bd.listIterator(); it.hasNext(); ) {
- if (it.next() instanceof PointcutDeclaration) {
+ for (Object o : bd) {
+ if (o instanceof PointcutDeclaration) {
pointcutCount++;
}
}
PointcutDeclaration[] pointcuts = new PointcutDeclaration[pointcutCount];
int next = 0;
- for (Iterator it = bd.listIterator(); it.hasNext(); ) {
- Object decl = it.next();
+ for (Object decl : bd) {
if (decl instanceof PointcutDeclaration) {
pointcuts[next++] = (PointcutDeclaration) decl;
}
// ajh02: method added
List bd = bodyDeclarations();
List advice = new ArrayList();
- for (Iterator it = bd.listIterator(); it.hasNext();) {
- Object decl = it.next();
+ for (Object decl : bd) {
if (decl instanceof AdviceDeclaration) {
advice.add(decl);
}
}
IMessage[] messages = holder.getMessages(kind, orGreater);
if (!LangUtil.isEmpty(messages)) {
- for (int i = 0; i < messages.length; i++) {
- sink.add(MessagePrinter.render(messages[i]));
+ for (IMessage message : messages) {
+ sink.add(MessagePrinter.render(message));
}
}
}
boolean skipExit = false;
if (useSystemExit && !LangUtil.isEmpty(args)) { // sigh - pluck -noExit
- for (int i = 0; i < args.length; i++) {
- if ("-noExit".equals(args[i])) {
+ for (String arg : args) {
+ if ("-noExit".equals(arg)) {
skipExit = true;
break;
}
List cp = config.getClasspath();
boolean jar1Found = false;
boolean jar2Found = false;
- for (Iterator iter = cp.iterator(); iter.hasNext();) {
- String element = (String) iter.next();
- if (element.indexOf("1.jar") != -1) jar1Found = true;
- if (element.indexOf("2.jar") != -1) jar2Found = true;
- }
+ for (Object o : cp) {
+ String element = (String) o;
+ if (element.indexOf("1.jar") != -1) jar1Found = true;
+ if (element.indexOf("2.jar") != -1) jar2Found = true;
+ }
assertTrue(
config.getClasspath().toString(),
jar1Found);
List cp = config.getClasspath();
boolean jar1Found = false;
boolean jar2Found = false;
- for (Iterator iter = cp.iterator(); iter.hasNext();) {
- String element = (String) iter.next();
- if (element.indexOf("1.jar") != -1) jar1Found = true;
- if (element.indexOf("2.jar") != -1) jar2Found = true;
- }
+ for (Object o : cp) {
+ String element = (String) o;
+ if (element.indexOf("1.jar") != -1) jar1Found = true;
+ if (element.indexOf("2.jar") != -1) jar2Found = true;
+ }
assertTrue(
config.getClasspath().toString(),
jar1Found);
String b = new File(TEST_DIR + "../bug-40257/d1/d2/B.java").getCanonicalPath();
String c = new File(TEST_DIR + "../bug-40257/d3/C.java").getCanonicalPath();
List pathList = new ArrayList();
- for (Iterator it = config.getFiles().iterator(); it.hasNext(); ) {
- pathList.add(((File)it.next()).getCanonicalPath());
+ for (File file : config.getFiles()) {
+ pathList.add(file.getCanonicalPath());
}
assertTrue(pathList.contains(a));
assertTrue(pathList.contains(b));
private void checkPathSubset(List path) throws IOException {
String files[] = { "aspectjJar.file", "jarChild", "parent.zip" };
- for (int i = 0; i < files.length; i++) {
- File file = new File(NONSTANDARD_JAR_DIR+files[i]);
- assertTrue("bad path: " + path, path.contains(file.getCanonicalPath()));
+ for (String s : files) {
+ File file = new File(NONSTANDARD_JAR_DIR + s);
+ assertTrue("bad path: " + path, path.contains(file.getCanonicalPath()));
}
}
args.add("-g"); // XXX need this to get sourcefile and line numbers, shouldn't
- for (int i = 0; i < extraArgs.length; i++) {
- args.add(extraArgs[i]);
+ for (String extraArg : extraArgs) {
+ args.add(extraArg);
}
args.add(Constants.TESTDATA_PATH + "/" + source);
assertTrue("expected error", nErrors > 0);
} else {
List errors = new ArrayList(Arrays.asList(myHandler.getErrors()));
- for (int i = 0, len = expectedErrors.length; i < len; i++) {
- int line = expectedErrors[i];
+ for (int line : expectedErrors) {
boolean found = false;
- for (Iterator iter = errors.iterator(); iter.hasNext();) {
+ for (Iterator iter = errors.iterator(); iter.hasNext(); ) {
IMessage m = (IMessage) iter.next();
if (m.getSourceLocation() != null && m.getSourceLocation().getLine() == line) {
found = true;
// ///////////////////////////////////////////////////////////////////////////
// Check the error messages are comparable (allow for differing orderings)
if (compareErrors) {
- for (Iterator<IMessage> iter = binaryErrorMessages.iterator(); iter.hasNext();) {
- IMessage binaryMessage = iter.next();
+ for (IMessage binaryMessage : binaryErrorMessages) {
IMessage correctSourceMessage = null;
- for (Iterator<IMessage> iterator = sourceErrorMessages.iterator(); iterator.hasNext() && correctSourceMessage == null;) {
+ for (Iterator<IMessage> iterator = sourceErrorMessages.iterator(); iterator.hasNext() && correctSourceMessage == null; ) {
IMessage sourceMessage = iterator.next();
if (sourceMessage.getMessage().equals(binaryMessage.getMessage())) {
sourceErrorMessages.remove(correctSourceMessage);
}
if (sourceErrorMessages.size() > 0) {
- for (Iterator<IMessage> iter = sourceErrorMessages.iterator(); iter.hasNext();) {
- IMessage srcMsg = iter.next();
+ for (IMessage srcMsg : sourceErrorMessages) {
System.err.println("This error message from source compilation '" + srcMsg
+ "' didn't occur during binary weaving.");
}
MessageHandler h = new MessageHandler();
// boolean result;
StringBuffer sb = new StringBuffer();
- for (int i = 0; i < args.length; i++) {
- sb.append("\n###### results for " + args[i]);
- sb.append("\n" + me.run(new File(args[i]), h) + ": " + h);
+ for (String arg : args) {
+ sb.append("\n###### results for " + arg);
+ sb.append("\n" + me.run(new File(arg), h) + ": " + h);
}
System.err.flush();
System.out.flush();
List<String> normalizeFilenames(String[] ra) { // XXX util
ArrayList<String> result = new ArrayList<>();
if (null != ra) {
- for (int i = 0; i < ra.length; i++) {
- result.add(normalizeFilename(ra[i]));
- }
+ for (String s : ra) {
+ result.add(normalizeFilename(s));
+ }
if (1 < ra.length) {
Collections.sort(result);
}
info(handler, context);
BitSet foundSet = new BitSet(10);
- for (int i = 0; i < exp.length; i++) {
- final int expLine = exp[i];
+ for (final int expLine : exp) {
boolean found = false;
for (int j = 0; !found && (j < messages.length); j++) {
ISourceLocation sl = messages[j].getSourceLocation();
found = ((null != sl) && (expLine == sl.getLine()));
if (found) {
- info(handler, "found " + label + " for: " + exp[i]);
+ info(handler, "found " + label + " for: " + expLine);
if (foundSet.get(j)) {
info(
- handler,
- "duplicate " + label + " expected: " + exp[i]);
+ handler,
+ "duplicate " + label + " expected: " + expLine);
}
foundSet.set(j);
}
}
if (!found) {
String s =
- "expected "
- + label
- + " not found: "
- + exp[i]
- + context;
+ "expected "
+ + label
+ + " not found: "
+ + expLine
+ + context;
fail(handler, s); // bad short-circuit
if (!result) {
result = false;
args.add("-classpath");
args.add(Constants.aspectjrtClasspath());
-
- for (int i=0; i < argfiles.length; i++) {
- args.add("@" + examplesDir + argfiles[i]);
+
+ for (String argfile : argfiles) {
+ args.add("@" + examplesDir + argfile);
}
CommandTestCase.runCompiler(args, CommandTestCase.NO_ERRORS);
- for (int i=0; i < classes.length; i++) {
- TestUtil.runMain("out", classes[i]);
+ for (String aClass : classes) {
+ TestUtil.runMain("out", aClass);
}
}
AjAST ajast = createAjAST();
AspectDeclaration d = ajast.newAspectDeclaration();
List props = AspectDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof ChildPropertyDescriptor) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)o;
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("perClause")) {
assertNull("AspectDeclaration's " + element.getId() + " property" +
- "should be null since we haven't set it yet",
- d.getStructuralProperty(element));
+ "should be null since we haven't set it yet",
+ d.getStructuralProperty(element));
}
} else if (o instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor element = (SimplePropertyDescriptor)o;
+ SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
assertNotNull("AspectDeclaration's " + element.getId() + " property" +
- "should not be null since it is a boolean",
+ "should not be null since it is a boolean",
d.getStructuralProperty(element));
}
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof ChildPropertyDescriptor) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("perClause")) {
PerTypeWithin ptw = ajast.newPerTypeWithin();
- d.setStructuralProperty(element,ptw);
+ d.setStructuralProperty(element, ptw);
assertEquals("AspectDeclaration's perClause property should" +
- " now be a perTypeWithin",ptw,d.getStructuralProperty(element));
+ " now be a perTypeWithin", ptw, d.getStructuralProperty(element));
} else if (element.getId().equals("javadoc")) {
// do nothing since makes no sense to have javadoc
- }
+ }
} else if (o instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor element = (SimplePropertyDescriptor)o;
- if (element.getId().equals("privileged")) {
+ SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
+ if (element.getId().equals("privileged")) {
Boolean b = new Boolean(true);
- d.setStructuralProperty(element,b);
+ d.setStructuralProperty(element, b);
assertEquals("AspectDeclaration's isPrivileged property should" +
- " now be a boolean",b,d.getStructuralProperty(element));
- }
+ " now be a boolean", b, d.getStructuralProperty(element));
+ }
}
}
}
AjAST ajast = createAjAST();
AjTypeDeclaration d = ajast.newAjTypeDeclaration();
List props = AjTypeDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof SimplePropertyDescriptor) {
SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
if (element.getId().equals("aspect")) {
assertNotNull("AjTypeDeclaration's " + element.getId() + " property" +
- " should not be null since it is a boolean",
- d.getStructuralProperty(element));
- }
+ " should not be null since it is a boolean",
+ d.getStructuralProperty(element));
+ }
}
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof SimplePropertyDescriptor) {
SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
if (element.getId().equals("aspect")) {
Boolean b = new Boolean(true);
- d.setStructuralProperty(element,b);
+ d.setStructuralProperty(element, b);
assertEquals("AjTypeDeclaration's aspect property should" +
- " now be a SignaturePattern",b,d.getStructuralProperty(element));
+ " now be a SignaturePattern", b, d.getStructuralProperty(element));
}
}
}
AjAST ajast = createAjAST();
DeclareParentsDeclaration d = ajast.newDeclareParentsDeclaration();
List props = DeclareParentsDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof ChildPropertyDescriptor) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor)o;
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
assertNull("DeclareParentsDeclaration's " + element.getId() + " property" +
- "should be null since we haven't set it yet",
- d.getStructuralProperty(element));
+ "should be null since we haven't set it yet",
+ d.getStructuralProperty(element));
} else if (o instanceof ChildListPropertyDescriptor) {
- ChildListPropertyDescriptor element = (ChildListPropertyDescriptor)o;
+ ChildListPropertyDescriptor element = (ChildListPropertyDescriptor) o;
assertNotNull("DeclareParentsDeclaration's " + element.getId() + " property" +
- "should not be null since it is a list",
+ "should not be null since it is a list",
d.getStructuralProperty(element));
assertEquals("should only be able to put TypePattern's into the list",
- TypePattern.class,element.getElementType());
+ TypePattern.class, element.getElementType());
} else if (o instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor element = (SimplePropertyDescriptor)o;
+ SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
assertNotNull("DeclareParentsDeclaration's " + element.getId() + " property" +
- "should not be null since it is a boolean",
- d.getStructuralProperty(element));
+ "should not be null since it is a boolean",
+ d.getStructuralProperty(element));
} else {
fail("unknown PropertyDescriptor associated with DeclareParentsDeclaration: " + o);
}
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof ChildPropertyDescriptor) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("childTypePattern")) {
DefaultTypePattern dtp = ajast.newDefaultTypePattern();
- d.setStructuralProperty(element,dtp);
+ d.setStructuralProperty(element, dtp);
assertEquals("DeclareParentsDeclaration's typePattern property should" +
- " now be a DefaultTypePattern",dtp,d.getStructuralProperty(element));
+ " now be a DefaultTypePattern", dtp, d.getStructuralProperty(element));
} else if (element.getId().equals("javadoc")) {
// do nothing since makes no sense to have javadoc
} else {
fail("unknown property for DeclareParentsDeclaration");
- }
+ }
} else if (o instanceof SimplePropertyDescriptor) {
- SimplePropertyDescriptor element = (SimplePropertyDescriptor)o;
- if (element.getId().equals("isExtends")) {
+ SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
+ if (element.getId().equals("isExtends")) {
Boolean b = new Boolean(true);
- d.setStructuralProperty(element,b);
+ d.setStructuralProperty(element, b);
assertEquals("DeclareParentsDeclaration's isExtends property should" +
- " now be a boolean",b,d.getStructuralProperty(element));
- }
+ " now be a boolean", b, d.getStructuralProperty(element));
+ }
}
}
}
boolean foundName = false;
boolean foundParamList = false;
boolean foundDesignator = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if ((o instanceof ChildPropertyDescriptor)) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
String id = element.getId();
AjAST ajast = createAjAST();
PointcutDeclaration d = ajast.newPointcutDeclaration();
List props = PointcutDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof ChildPropertyDescriptor) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("name")) {
fail("unknown PropertyDescriptor associated with PointcutDeclaration: " + o);
}
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof ChildPropertyDescriptor) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("designator")) {
boolean foundPerClause = false;
boolean foundIsPrivileged = false;
boolean foundIsAspect = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if ((o instanceof ChildPropertyDescriptor)) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
String id = element.getId();
ajast.newAjTypeDeclaration();
List props = AjTypeDeclaration.propertyDescriptors(AST.JLS3);
boolean foundAspect = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof SimplePropertyDescriptor) {
SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
String id = element.getId();
boolean foundPrivileged = false;
boolean foundPerClause = false;
// boolean foundAspect = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof SimplePropertyDescriptor) {
SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
String id = element.getId();
ajast.newTypeDeclaration();
List props = TypeDeclaration.propertyDescriptors(AST.JLS3);
boolean foundAspect = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof SimplePropertyDescriptor) {
SimplePropertyDescriptor element = (SimplePropertyDescriptor) o;
String id = element.getId();
boolean foundJavadoc = false;
boolean foundPattern = false;
boolean foundAnnotationName = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
AjAST ajast = createAjAST();
DeclareAtFieldDeclaration d = ajast.newDeclareAtFieldDeclaration();
List props = DeclareAtFieldDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object o : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("annotationName")) {
assertNotNull("DeclareAtFieldDeclaration's " + element.getId() + " property"
+ " should not be null since it is lazily created", d.getStructuralProperty(element));
+ " should be null since we haven't set it yet", d.getStructuralProperty(element));
}
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
if (element.getId().equals("pattern")) {
SignaturePattern p = ajast.newSignaturePattern();
d.setStructuralProperty(element, p);
boolean foundJavadoc = false;
boolean foundPattern = false;
boolean foundAnnotationName = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
AjAST ajast = createAjAST();
DeclareAtMethodDeclaration d = ajast.newDeclareAtMethodDeclaration();
List props = DeclareAtMethodDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object o : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("annotationName")) {
assertNotNull("DeclareAtMethodDeclaration's " + element.getId() + " property"
+ " should not be null since it is lazily created", d.getStructuralProperty(element));
+ " should be null since we haven't set it yet", d.getStructuralProperty(element));
}
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
if (element.getId().equals("pattern")) {
SignaturePattern p = ajast.newSignaturePattern();
d.setStructuralProperty(element, p);
boolean foundJavadoc = false;
boolean foundPattern = false;
boolean foundAnnotationName = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
AjAST ajast = createAjAST();
DeclareAtConstructorDeclaration d = ajast.newDeclareAtConstructorDeclaration();
List props = DeclareAtConstructorDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object o : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("annotationName")) {
assertNotNull("DeclareAtConstructorDeclaration's " + element.getId() + " property"
+ " should not be null since it is lazily created", d.getStructuralProperty(element));
+ " should be null since we haven't set it yet", d.getStructuralProperty(element));
}
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
if (element.getId().equals("pattern")) {
SignaturePattern p = ajast.newSignaturePattern();
d.setStructuralProperty(element, p);
boolean foundJavadoc = false;
boolean foundPattern = false;
boolean foundAnnotationName = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
AjAST ajast = createAjAST();
DeclareAtTypeDeclaration d = ajast.newDeclareAtTypeDeclaration();
List props = DeclareAtTypeDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object o : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
if (element.getId().equals("annotationName")) {
assertNotNull("DeclareAtTypeDeclaration's " + element.getId() + " property"
+ " should not be null since it is lazily created", d.getStructuralProperty(element));
+ " should be null since we haven't set it yet", d.getStructuralProperty(element));
}
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
if (element.getId().equals("pattern")) {
DefaultTypePattern p = ajast.newDefaultTypePattern();
d.setStructuralProperty(element, p);
boolean foundJavadoc = false;
boolean foundPointcut = false;
boolean foundMessage = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
AjAST ajast = createAjAST();
DeclareErrorDeclaration d = ajast.newDeclareErrorDeclaration();
List props = DeclareErrorDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object o : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
assertNull("DeclareErrorDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet",
d.getStructuralProperty(element));
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
if (element.getId().equals("pointcut")) {
AndPointcut p = ajast.newAndPointcut();
d.setStructuralProperty(element, p);
boolean foundTypePattern = false;
boolean foundIsExtends = false;
boolean foundTypePatternList = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if ((o instanceof ChildPropertyDescriptor)) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
String id = element.getId();
List props = DeclarePrecedenceDeclaration.propertyDescriptors(AST.JLS3);
boolean foundJavadoc = false;
boolean foundTypePatterns = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if ((o instanceof ChildPropertyDescriptor) && ((ChildPropertyDescriptor) o).getId().equals("javadoc")) {
foundJavadoc = true;
} else if ((o instanceof ChildListPropertyDescriptor)
AjAST ajast = createAjAST();
DeclarePrecedenceDeclaration d = ajast.newDeclarePrecedenceDeclaration();
List props = DeclarePrecedenceDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : props) {
if (o instanceof ChildPropertyDescriptor) {
ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
assertNull("DeclareErrorDeclaration's " + element.getId() + " property"
boolean foundJavadoc = false;
boolean foundPointcut = false;
boolean foundTypePattern = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
AjAST ajast = createAjAST();
DeclareSoftDeclaration d = ajast.newDeclareSoftDeclaration();
List props = DeclareSoftDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object o : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
assertNull("DeclareSoftDeclaration's " + element.getId() + " property" + "should be null since we haven't set it yet",
d.getStructuralProperty(element));
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
if (element.getId().equals("pointcut")) {
AndPointcut p = ajast.newAndPointcut();
d.setStructuralProperty(element, p);
boolean foundJavadoc = false;
boolean foundPointcut = false;
boolean foundMessage = false;
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
String id = element.getId();
if (id.equals("javadoc")) {
foundJavadoc = true;
AjAST ajast = createAjAST();
DeclareWarningDeclaration d = ajast.newDeclareWarningDeclaration();
List props = DeclareWarningDeclaration.propertyDescriptors(AST.JLS3);
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object o : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) o;
assertNull("DeclareWarningDeclaration's " + element.getId() + " property"
+ "should be null since we haven't set it yet", d.getStructuralProperty(element));
}
- for (Iterator iter = props.iterator(); iter.hasNext();) {
- ChildPropertyDescriptor element = (ChildPropertyDescriptor) iter.next();
+ for (Object prop : props) {
+ ChildPropertyDescriptor element = (ChildPropertyDescriptor) prop;
if (element.getId().equals("pointcut")) {
AndPointcut p = ajast.newAndPointcut();
d.setStructuralProperty(element, p);
protected List<SourceRange> getSourceRanges(int[][] sourceRanges) {
List<SourceRange> convertedRanges = new ArrayList<SourceRange>();
- for (int i = 0; i < sourceRanges.length; i++) {
- convertedRanges.add(new SourceRange(sourceRanges[i][0],
- sourceRanges[i][1]));
+ for (int[] sourceRange : sourceRanges) {
+ convertedRanges.add(new SourceRange(sourceRange[0],
+ sourceRange[1]));
}
return convertedRanges;
}
private boolean hasSpecifiedIncremental(String[] args) {
if (args == null)
return false;
- for (int i = 0; i < args.length; i++) {
- if (args[i].equals("-incremental"))
+ for (String arg : args) {
+ if (arg.equals("-incremental"))
return true;
}
return false;
}
private void addMessagesTo(List<IMessage> aList, IMessage[] messages) {
- for (int i = 0; i < messages.length; i++) {
- aList.add(messages[i]);
+ for (IMessage message : messages) {
+ aList.add(message);
}
}
private boolean isIncremental(String[] args) {
- for (int i = 0; i < args.length; i++) {
- if (args[i].trim().equals("-incremental"))
+ for (String arg : args) {
+ if (arg.trim().equals("-incremental"))
return true;
}
return false;
return (toMatch.equals(prefix));
}
});
- for (int i = 0; i < toCopy.length; i++) {
- String toPath = relativeToPath + toCopy[i];
+ for (String s : toCopy) {
+ String toPath = relativeToPath + s;
to = new File(sandbox, toPath);
- FileUtil.copyFile(new File(from.getParentFile(), toCopy[i]), to);
+ FileUtil.copyFile(new File(from.getParentFile(), s), to);
}
} else {
FileUtil.copyFile(from, ret);
System.out.println("start of AJDE structure model:" + prefix); //$NON-NLS-1$
IRelationshipMap asmRelMap = model.getRelationshipMap();
- for (Iterator<String> iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
- String sourceOfRelationship = iter.next();
+ for (String sourceOfRelationship : asmRelMap.getEntries()) {
System.err.println("Examining source relationship handle: " + sourceOfRelationship);
List<IRelationship> relationships = null;
if (useHandles) {
relationships = asmRelMap.get(ipe);
}
if (relationships != null) {
- for (Iterator<IRelationship> iterator = relationships.iterator(); iterator.hasNext();) {
- Relationship rel = (Relationship) iterator.next();
+ for (IRelationship relationship : relationships) {
+ Relationship rel = (Relationship) relationship;
List<String> targets = rel.getTargets();
- for (Iterator<String> iterator2 = targets.iterator(); iterator2.hasNext();) {
- String t = (String) iterator2.next();
+ for (String t : targets) {
IProgramElement link = model.getHierarchy().findElementForHandle(t);
System.out.println(""); //$NON-NLS-1$
System.out.println(" sourceOfRelationship " + sourceOfRelationship); //$NON-NLS-1$
buff.append("Unexpected ");
buff.append(type);
buff.append(" messages:\n");
- for (Iterator iter = messages.iterator(); iter.hasNext();) {
+ for (Object message : messages) {
buff.append("\t");
- buff.append(iter.next().toString());
+ buff.append(message.toString());
buff.append("\n");
}
}
}
buff.append("\n");
int msgNo = 1;
- for (Iterator iter = failMessages.iterator(); iter.hasNext();) {
+ for (IMessage failMessage : failMessages) {
buff.append("[fail ");
buff.append(msgNo++);
buff.append("] ");
- buff.append(iter.next().toString());
+ buff.append(failMessage.toString());
buff.append("\n");
}
msgNo = 1;
- for (Iterator iter = errorMessages.iterator(); iter.hasNext();) {
+ for (IMessage errorMessage : errorMessages) {
buff.append("[error ");
buff.append(msgNo++);
buff.append("] ");
- buff.append(iter.next().toString());
+ buff.append(errorMessage.toString());
buff.append("\n");
}
msgNo = 1;
- for (Iterator iter = warningMessages.iterator(); iter.hasNext();) {
+ for (IMessage warningMessage : warningMessages) {
buff.append("[warning ");
buff.append(msgNo++);
buff.append("] ");
- buff.append(iter.next().toString());
+ buff.append(warningMessage.toString());
buff.append("\n");
}
msgNo = 1;
- for (Iterator iter = infoMessages.iterator(); iter.hasNext();) {
+ for (IMessage infoMessage : infoMessages) {
buff.append("[info ");
buff.append(msgNo++);
buff.append("] ");
- buff.append(iter.next().toString());
+ buff.append(infoMessage.toString());
buff.append("\n");
}
msgNo = 1;
- for (Iterator iter = weaveMessages.iterator(); iter.hasNext();) {
+ for (IMessage weaveMessage : weaveMessages) {
buff.append("[weaveInfo ");
buff.append(msgNo++);
buff.append("] ");
- buff.append(iter.next().toString());
+ buff.append(weaveMessage.toString());
buff.append("\n");
}
buff.append("\ncommand was: 'ajc");
- for (int i = 0; i < args.length; i++) {
+ for (String arg : args) {
buff.append(' ');
- buff.append(args[i]);
+ buff.append(arg);
}
buff.append("'\n");
return buff.toString();
public void close() throws IOException {
target.close();
-
- for (Iterator i = delegates.iterator(); i.hasNext();) {
- OutputStream delegate = (OutputStream)i.next();
+
+ for (Object o : delegates) {
+ OutputStream delegate = (OutputStream) o;
delegate.close();
}
}
public void flush() throws IOException {
target.flush();
-
- for (Iterator i = delegates.iterator(); i.hasNext();) {
- OutputStream delegate = (OutputStream)i.next();
+
+ for (Object o : delegates) {
+ OutputStream delegate = (OutputStream) o;
delegate.flush();
}
}
public void write(byte[] b, int off, int len) throws IOException {
if (verbose) target.write(b, off, len);
-
- for (Iterator i = delegates.iterator(); i.hasNext();) {
- OutputStream delegate = (OutputStream)i.next();
- delegate.write(b,off,len);
+
+ for (Object o : delegates) {
+ OutputStream delegate = (OutputStream) o;
+ delegate.write(b, off, len);
}
}
public void write(byte[] b) throws IOException {
if (verbose) target.write(b);
-
- for (Iterator i = delegates.iterator(); i.hasNext();) {
- OutputStream delegate = (OutputStream)i.next();
+
+ for (Object o : delegates) {
+ OutputStream delegate = (OutputStream) o;
delegate.write(b);
}
}
public void write(int b) throws IOException {
if (verbose) target.write(b);
-
- for (Iterator i = delegates.iterator(); i.hasNext();) {
- OutputStream delegate = (OutputStream)i.next();
+
+ for (Object o : delegates) {
+ OutputStream delegate = (OutputStream) o;
delegate.write(b);
}
}
*/
private final AnnotationAJ retrieveAnnotationOnAnnotation(UnresolvedType requiredAnnotationSignature) {
AnnotationAJ[] annos = type.getAnnotations();
- for (int i = 0; i < annos.length; i++) {
- AnnotationAJ a = annos[i];
+ for (AnnotationAJ a : annos) {
if (a.getTypeSignature().equals(requiredAnnotationSignature.getSignature())) {
- return annos[i];
+ return a;
}
}
return null;
AbstractReferenceTypeDelegate outerObjectType = (AbstractReferenceTypeDelegate) outerDelegate;
if (outerObjectType.isNested()) {
GenericSignature.FormalTypeParameter[] parentParams = outerObjectType.getFormalTypeParametersFromOuterClass();
- for (int i = 0; i < parentParams.length; i++) {
- typeParameters.add(parentParams[i]);
+ for (GenericSignature.FormalTypeParameter parentParam : parentParams) {
+ typeParameters.add(parentParam);
}
}
GenericSignature.ClassSignature outerSig = outerObjectType.getGenericClassTypeSignature();
}
s.writeInt(lineBreaks.length);
int previous = 0;
- for (int i = 0, max = lineBreaks.length; i < max; i++) {
- s.writeShort(lineBreaks[i] - previous);
- previous = lineBreaks[i];
+ for (int lineBreak : lineBreaks) {
+ s.writeShort(lineBreak - previous);
+ previous = lineBreak;
}
}
public TypeVariable[] getTypeVariables() {
if (this.typeVariables == null && componentType.getTypeVariables() != null) {
this.typeVariables = componentType.getTypeVariables();
- for (int i = 0; i < this.typeVariables.length; i++) {
- this.typeVariables[i].resolve(world);
+ for (TypeVariable typeVariable : this.typeVariables) {
+ typeVariable.resolve(world);
}
}
return this.typeVariables;
if (kind==SUPER){
ret.append("-");
ret.append(lowerBound.getSignatureForAttribute());
- for (int i=0;i<additionalInterfaceBounds.length;i++) {
- ret.append(additionalInterfaceBounds[i].getSignatureForAttribute());
+ for (ReferenceType additionalInterfaceBound : additionalInterfaceBounds) {
+ ret.append(additionalInterfaceBound.getSignatureForAttribute());
}
} else if (kind==EXTENDS) {
ret.append("+");
ret.append(upperBound.getSignatureForAttribute());
- for (int i=0;i<additionalInterfaceBounds.length;i++) {
- ret.append(additionalInterfaceBounds[i].getSignatureForAttribute());
+ for (ReferenceType additionalInterfaceBound : additionalInterfaceBounds) {
+ ret.append(additionalInterfaceBound.getSignatureForAttribute());
}
} else if (kind==UNBOUND) {
ret.append("*");
}
// Check we haven't already got a munger for this:
String signatureToLookFor = typeToExpose.getSignature();
- for (Iterator<ConcreteTypeMunger> iterator = typeMungers.iterator(); iterator.hasNext();) {
- ConcreteTypeMunger cTM = iterator.next();
+ for (ConcreteTypeMunger cTM : typeMungers) {
ResolvedTypeMunger rTM = cTM.getMunger();
if (rTM != null && rTM instanceof ExposeTypeMunger) {
String exposedType = ((ExposeTypeMunger) rTM).getExposedTypeSignature();
Set<Object> theseTypeMungers = new HashSet<Object>();
Set<Object> otherTypeMungers = new HashSet<Object>();
if (!careAboutShadowMungers) {
- for (Iterator<ConcreteTypeMunger> iter = typeMungers.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : typeMungers) {
if (o instanceof ConcreteTypeMunger) {
ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) o;
if (!typeMunger.existsToSupportShadowMunging()) {
}
}
- for (Iterator<ConcreteTypeMunger> iter = other.typeMungers.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : other.typeMungers) {
if (o instanceof ConcreteTypeMunger) {
ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) o;
if (!typeMunger.existsToSupportShadowMunging()) {
if (!careAboutShadowMungers) {
// this means we are in front end compilation and if the differences are purely mixin parents, we can continue OK
Set<DeclareParents> trimmedThis = new HashSet<DeclareParents>();
- for (Iterator<DeclareParents> iterator = declareParents.iterator(); iterator.hasNext();) {
- DeclareParents decp = iterator.next();
+ for (DeclareParents decp : declareParents) {
if (!decp.isMixin()) {
trimmedThis.add(decp);
}
}
Set<DeclareParents> trimmedOther = new HashSet<DeclareParents>();
- for (Iterator<DeclareParents> iterator = other.declareParents.iterator(); iterator.hasNext();) {
- DeclareParents decp = iterator.next();
+ for (DeclareParents decp : other.declareParents) {
if (!decp.isMixin()) {
trimmedOther.add(decp);
}
if (theseInlinedAroundMungers.size() != otherInlinedAroundMungers.size()) {
return false;
}
- for (Iterator<ShadowMunger> iter = theseInlinedAroundMungers.iterator(); iter.hasNext();) {
- Advice thisAdvice = (Advice) iter.next();
+ for (ShadowMunger theseInlinedAroundMunger : theseInlinedAroundMungers) {
+ Advice thisAdvice = (Advice) theseInlinedAroundMunger;
boolean foundIt = false;
- for (Iterator<ShadowMunger> iterator = otherInlinedAroundMungers.iterator(); iterator.hasNext();) {
- Advice otherAdvice = (Advice) iterator.next();
+ for (ShadowMunger otherInlinedAroundMunger : otherInlinedAroundMungers) {
+ Advice otherAdvice = (Advice) otherInlinedAroundMunger;
if (thisAdvice.equals(otherAdvice)) {
if (thisAdvice.getSignature() instanceof ResolvedMemberImpl) {
if (((ResolvedMemberImpl) thisAdvice.getSignature()).isEquivalentTo(otherAdvice.getSignature())) {
// System.err.println("Looking at descendants of "+aspectType.getName());
Set<ResolvedType> knownAspects = members.keySet();
Set<ResolvedType> toBeReplaced = new HashSet<ResolvedType>();
- for (Iterator<ResolvedType> it = knownAspects.iterator(); it.hasNext();) {
- ResolvedType candidateDescendant = it.next();
+ for (ResolvedType candidateDescendant : knownAspects) {
// allowMissing = true - if something is missing, it really probably is not a descendant
if ((candidateDescendant != aspectType) && (aspectType.isAssignableFrom(candidateDescendant, true))) {
toBeReplaced.add(candidateDescendant);
}
}
boolean change = false;
- for (Iterator<ResolvedType> it = toBeReplaced.iterator(); it.hasNext();) {
- ResolvedType next = it.next();
+ for (ResolvedType next : toBeReplaced) {
boolean thisChange = addOrReplaceAspect(next, inWeavePhase);
change = change || thisChange;
}
public List<ShadowMunger> getShadowMungers() {
if (shadowMungers == null) {
List<ShadowMunger> ret = new ArrayList<ShadowMunger>();
- for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) {
- ret.addAll(i.next().getShadowMungers());
+ for (CrosscuttingMembers crosscuttingMembers : members.values()) {
+ ret.addAll(crosscuttingMembers.getShadowMungers());
}
shadowMungers = ret;
}
public List<ConcreteTypeMunger> getLateTypeMungers() {
if (lateTypeMungers == null) {
List<ConcreteTypeMunger> ret = new ArrayList<ConcreteTypeMunger>();
- for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) {
- ret.addAll(i.next().getLateTypeMungers());
+ for (CrosscuttingMembers crosscuttingMembers : members.values()) {
+ ret.addAll(crosscuttingMembers.getLateTypeMungers());
}
lateTypeMungers = ret;
}
public List<DeclareSoft> getDeclareSofts() {
if (declareSofts == null) {
Set<DeclareSoft> ret = new HashSet<DeclareSoft>();
- for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) {
- ret.addAll(i.next().getDeclareSofts());
+ for (CrosscuttingMembers crosscuttingMembers : members.values()) {
+ ret.addAll(crosscuttingMembers.getDeclareSofts());
}
declareSofts = new ArrayList<DeclareSoft>();
declareSofts.addAll(ret);
public List<DeclareParents> getDeclareParents() {
if (declareParents == null) {
Set<DeclareParents> ret = new HashSet<DeclareParents>();
- for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) {
- ret.addAll(i.next().getDeclareParents());
+ for (CrosscuttingMembers crosscuttingMembers : members.values()) {
+ ret.addAll(crosscuttingMembers.getDeclareParents());
}
declareParents = new ArrayList<DeclareParents>();
declareParents.addAll(ret);
public List<DeclareAnnotation> getDeclareAnnotationOnTypes() {
if (declareAnnotationOnTypes == null) {
Set<DeclareAnnotation> ret = new LinkedHashSet<DeclareAnnotation>();
- for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) {
- ret.addAll(i.next().getDeclareAnnotationOnTypes());
+ for (CrosscuttingMembers crosscuttingMembers : members.values()) {
+ ret.addAll(crosscuttingMembers.getDeclareAnnotationOnTypes());
}
declareAnnotationOnTypes = new ArrayList<DeclareAnnotation>();
declareAnnotationOnTypes.addAll(ret);
public List<DeclareAnnotation> getDeclareAnnotationOnFields() {
if (declareAnnotationOnFields == null) {
Set<DeclareAnnotation> ret = new LinkedHashSet<DeclareAnnotation>();
- for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) {
- ret.addAll(i.next().getDeclareAnnotationOnFields());
+ for (CrosscuttingMembers crosscuttingMembers : members.values()) {
+ ret.addAll(crosscuttingMembers.getDeclareAnnotationOnFields());
}
declareAnnotationOnFields = new ArrayList<DeclareAnnotation>();
declareAnnotationOnFields.addAll(ret);
public List<DeclareAnnotation> getDeclareAnnotationOnMethods() {
if (declareAnnotationOnMethods == null) {
Set<DeclareAnnotation> ret = new LinkedHashSet<DeclareAnnotation>();
- for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) {
- ret.addAll(i.next().getDeclareAnnotationOnMethods());
+ for (CrosscuttingMembers crosscuttingMembers : members.values()) {
+ ret.addAll(crosscuttingMembers.getDeclareAnnotationOnMethods());
}
declareAnnotationOnMethods = new ArrayList<DeclareAnnotation>();
declareAnnotationOnMethods.addAll(ret);
public List<DeclareTypeErrorOrWarning> getDeclareTypeEows() {
if (declareTypeEows == null) {
Set<DeclareTypeErrorOrWarning> ret = new HashSet<DeclareTypeErrorOrWarning>();
- for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) {
- ret.addAll(i.next().getDeclareTypeErrorOrWarning());
+ for (CrosscuttingMembers crosscuttingMembers : members.values()) {
+ ret.addAll(crosscuttingMembers.getDeclareTypeErrorOrWarning());
}
declareTypeEows = new ArrayList<DeclareTypeErrorOrWarning>();
declareTypeEows.addAll(ret);
public List<Declare> getDeclareDominates() {
if (declareDominates == null) {
List<Declare> ret = new ArrayList<Declare>();
- for (Iterator<CrosscuttingMembers> i = members.values().iterator(); i.hasNext();) {
- ret.addAll(i.next().getDeclareDominates());
+ for (CrosscuttingMembers crosscuttingMembers : members.values()) {
+ ret.addAll(crosscuttingMembers.getDeclareDominates());
}
declareDominates = ret;
}
public ResolvedType findAspectDeclaringParents(DeclareParents p) {
Set<ResolvedType> keys = this.members.keySet();
- for (Iterator<ResolvedType> iter = keys.iterator(); iter.hasNext();) {
- ResolvedType element = iter.next();
- for (Iterator i = members.get(element).getDeclareParents().iterator(); i.hasNext();) {
- DeclareParents dp = (DeclareParents) i.next();
+ for (ResolvedType element : keys) {
+ for (DeclareParents dp : members.get(element).getDeclareParents()) {
if (dp.equals(p)) {
return element;
}
if (verificationList == null) {
return;
}
- for (Iterator<IVerificationRequired> iter = verificationList.iterator(); iter.hasNext();) {
- IVerificationRequired element = iter.next();
+ for (IVerificationRequired element : verificationList) {
element.verify();
}
verificationList = null;
public void write(CompressingDataOutputStream stream) throws IOException {
// stream.writeInt(serializationVersion);
stream.writeInt(shadowMungers.size());
- for (Iterator iterator = shadowMungers.iterator(); iterator.hasNext();) {
- ShadowMunger shadowMunger = (ShadowMunger) iterator.next();
+ for (ShadowMunger shadowMunger : shadowMungers) {
shadowMunger.write(stream);
}
// // private List /* ShadowMunger */shadowMungers = null;
private void dumpCompilerMessages(IMessageHolder messageHolder) {
println("---- Compiler Messages ---");
if (messageHolder != null) {
- for (Iterator<IMessage> i = messageHolder.getUnmodifiableListView().iterator(); i.hasNext();) {
- IMessage message = i.next();
+ for (IMessage message : messageHolder.getUnmodifiableListView()) {
println(message.toString());
}
} else {
return;
}
- for (int i = 0; i < array.length; i++) {
- print.println(array[i]);
+ for (Object o : array) {
+ print.println(o);
}
}
if (list == null || list.isEmpty()) {
println(NULL_OR_EMPTY);
} else {
- for (Iterator i = list.iterator(); i.hasNext();) {
- Object o = i.next();
+ for (Object o : list) {
if (o instanceof Exception) {
println((Exception) o);
} else {
@SuppressWarnings("rawtypes")
public void setFromProperties(Properties properties) {
- for (Iterator i = properties.entrySet().iterator(); i.hasNext();) {
- Map.Entry entry = (Map.Entry) i.next();
+ for (Map.Entry<Object, Object> objectObjectEntry : properties.entrySet()) {
+ Map.Entry entry = (Map.Entry) objectObjectEntry;
Kind kind = kinds.get(entry.getKey());
if (kind == null) {
MessageUtil.error(world.getMessageHandler(), WeaverMessages.format(WeaverMessages.XLINT_KEY_ERROR, entry.getKey()));
public static String typesToSignature(UnresolvedType[] paramTypes) {
StringBuffer buf = new StringBuffer();
buf.append("(");
- for (int i = 0; i < paramTypes.length; i++) {
- buf.append(paramTypes[i].getSignature());
+ for (UnresolvedType paramType : paramTypes) {
+ buf.append(paramType.getSignature());
}
buf.append(")");
return buf.toString();
public ResolvedMember getDelegateFactoryMethod(World w) {
ResolvedType aspectType = w.resolve(aspect);
ResolvedMember[] methods = aspectType.getDeclaredMethods();
- for (int i = 0; i < methods.length; i++) {
- ResolvedMember rm = methods[i];
+ for (ResolvedMember rm : methods) {
if (rm.getName().equals(factoryMethodName) && rm.getSignature().equals(factoryMethodSignature)) {
return rm;
}
return true;
}
if (annotationTypes != null) {
- for (int i = 0; i < annotationTypes.length; i++) {
- if (annotationTypes[i].equals(ofType)) {
+ for (ResolvedType annotationType : annotationTypes) {
+ if (annotationType.equals(ofType)) {
return true;
}
}
public AnnotationAJ getAnnotationOfType(UnresolvedType ofType) {
AnnotationAJ[] axs = getDelegate().getAnnotations();
if (axs != null) {
- for (int i = 0; i < axs.length; i++) {
- if (axs[i].getTypeSignature().equals(ofType.getSignature())) {
- return axs[i];
+ for (AnnotationAJ ax : axs) {
+ if (ax.getTypeSignature().equals(ofType.getSignature())) {
+ return ax;
}
}
}
if (annotations != null) {
String searchSig = ofType.getSignature();
- for (int i = 0; i < annotations.length; i++) {
- if (annotations[i].getTypeSignature().equals(searchSig)) {
- return annotations[i];
+ for (AnnotationAJ annotation : annotations) {
+ if (annotation.getTypeSignature().equals(searchSig)) {
+ return annotation;
}
}
}
// ??? needs to be Methods, not just declared methods? JLS 5.5 unclear
ResolvedMember[] a = getDeclaredMethods();
ResolvedMember[] b = other.getDeclaredMethods();
- for (int ai = 0, alen = a.length; ai < alen; ai++) {
- for (int bi = 0, blen = b.length; bi < blen; bi++) {
- if (!b[bi].isCompatibleWith(a[ai])) {
+ for (ResolvedMember member : a) {
+ for (ResolvedMember resolvedMember : b) {
+ if (!resolvedMember.isCompatibleWith(member)) {
return false;
}
}
if (((ReferenceType) this.getRawType()).isAssignableFrom(other)) {
boolean wildcardsAllTheWay = true;
ResolvedType[] myParameters = this.getResolvedTypeParameters();
- for (int i = 0; i < myParameters.length; i++) {
- if (!myParameters[i].isGenericWildcard()) {
+ for (ResolvedType myParameter : myParameters) {
+ if (!myParameter.isGenericWildcard()) {
wildcardsAllTheWay = false;
} else {
- BoundedReferenceType boundedRT = (BoundedReferenceType) myParameters[i];
+ BoundedReferenceType boundedRT = (BoundedReferenceType) myParameter;
if (boundedRT.isExtends() || boundedRT.isSuper()) {
wildcardsAllTheWay = false;
}
public TypeVariable[] getTypeVariables() {
if (typeVariables == null) {
typeVariables = getDelegate().getTypeVariables();
- for (int i = 0; i < this.typeVariables.length; i++) {
- typeVariables[i].resolve(world);
+ for (TypeVariable typeVariable : this.typeVariables) {
+ typeVariable.resolve(world);
}
}
return typeVariables;
ret.append(PARAMETERIZED_TYPE_IDENTIFIER);
ret.append(rawSignature.substring(1, rawSignature.length() - 1));
ret.append("<");
- for (int i = 0; i < someParameters.length; i++) {
- ret.append(someParameters[i].getSignature());
+ for (ResolvedType someParameter : someParameters) {
+ ret.append(someParameter.getSignature());
}
ret.append(">;");
return ret.toString();
String rawSig = aGenericType.getErasureSignature();
ret.append(rawSig.substring(0, rawSig.length() - 1));
ret.append("<");
- for (int i = 0; i < someParameters.length; i++) {
- if (someParameters[i] instanceof ReferenceType) {
- ret.append(((ReferenceType) someParameters[i])
+ for (UnresolvedType someParameter : someParameters) {
+ if (someParameter instanceof ReferenceType) {
+ ret.append(((ReferenceType) someParameter)
.getSignatureForAttribute());
- } else if (someParameters[i] instanceof Primitive) {
- ret.append(((Primitive) someParameters[i])
+ } else if (someParameter instanceof Primitive) {
+ ret.append(((Primitive) someParameter)
.getSignatureForAttribute());
} else {
throw new IllegalStateException(
"DebugFor325731: expected a ReferenceType or Primitive but was "
- + someParameters[i] + " of type "
- + someParameters[i].getClass().getName());
+ + someParameter + " of type "
+ + someParameter.getClass().getName());
}
}
ret.append(">;");
} else {
ResolvedType[] existing = getDelegate().getDeclaredInterfaces();
if (existing != null) {
- for (int i = 0; i < existing.length; i++) {
- if (existing[i].equals(newParent)) {
+ for (ResolvedType resolvedType : existing) {
+ if (resolvedType.equals(newParent)) {
return; // already has this interface
}
}
return backingGenericMember.hasAnnotation(ofType);
}
if (annotationTypes != null) {
- for (int i = 0, max = annotationTypes.length; i < max; i++) {
- if (annotationTypes[i].equals(ofType)) {
+ for (ResolvedType annotationType : annotationTypes) {
+ if (annotationType.equals(ofType)) {
return true;
}
}
s.writeByte(0);
} else {
s.writeByte(typeVariables.length);
- for (int i = 0; i < typeVariables.length; i++) {
- typeVariables[i].write(s);
+ for (TypeVariable typeVariable : typeVariables) {
+ typeVariable.write(s);
}
}
String gsig = getGenericSignature();
s.writeByte(0xff);
} else {
s.writeByte(parameterTypes.length);
- for (int i = 0; i < parameterTypes.length; i++) {
+ for (UnresolvedType parameterType : parameterTypes) {
if (s.canCompress()) {
- s.writeCompressedSignature(parameterTypes[i].getSignature());
+ s.writeCompressedSignature(parameterType.getSignature());
} else {
- UnresolvedType array_element = parameterTypes[i];
+ UnresolvedType array_element = parameterType;
array_element.write(s);
}
}
StringBuffer sb = new StringBuffer();
if (typeVariables != null) {
sb.append("<");
- for (int i = 0; i < typeVariables.length; i++) {
- sb.append(typeVariables[i].getSignatureForAttribute()); // need
+ for (TypeVariable typeVariable : typeVariables) {
+ sb.append(typeVariable.getSignatureForAttribute()); // need
// a
// 'getSignatureForAttribute()'
}
sb.append(">");
}
sb.append("(");
- for (int i = 0; i < parameterTypes.length; i++) {
- ResolvedType ptype = (ResolvedType) parameterTypes[i];
+ for (UnresolvedType parameterType : parameterTypes) {
+ ResolvedType ptype = (ResolvedType) parameterType;
sb.append(ptype.getSignatureForAttribute());
}
sb.append(")");
StringBuffer sb = new StringBuffer();
if (typeVariables != null) {
sb.append("<");
- for (int i = 0; i < typeVariables.length; i++) {
- sb.append(typeVariables[i].getSignature());
+ for (TypeVariable typeVariable : typeVariables) {
+ sb.append(typeVariable.getSignature());
}
sb.append(">");
}
sb.append("(");
- for (int i = 0; i < parameterTypes.length; i++) {
- UnresolvedType ptype = parameterTypes[i];
+ for (UnresolvedType ptype : parameterTypes) {
sb.append(ptype.getSignature());
}
sb.append(")");
public static void writeArray(ResolvedMember[] members, CompressingDataOutputStream s) throws IOException {
s.writeInt(members.length);
- for (int i = 0, len = members.length; i < len; i++) {
- members[i].write(s);
+ for (ResolvedMember member : members) {
+ member.write(s);
}
}
}
StringBuffer sig = new StringBuffer();
UnresolvedType[] myParameterTypes = getGenericParameterTypes();
- for (int i = 0; i < myParameterTypes.length; i++) {
- appendSigWithTypeVarBoundsRemoved(myParameterTypes[i], sig, new HashSet<UnresolvedType>());
+ for (UnresolvedType myParameterType : myParameterTypes) {
+ appendSigWithTypeVarBoundsRemoved(myParameterType, sig, new HashSet<UnresolvedType>());
}
myParameterSignatureWithBoundsRemoved = sig.toString();
return myParameterSignatureWithBoundsRemoved;
public TypeVariable getTypeVariableNamed(String name) {
// Check locally...
if (typeVariables != null) {
- for (int i = 0; i < typeVariables.length; i++) {
- if (typeVariables[i].getName().equals(name)) {
- return typeVariables[i];
+ for (TypeVariable typeVariable : typeVariables) {
+ if (typeVariable.getName().equals(name)) {
+ return typeVariable;
}
}
}
}
// Go through the interfaces on the way back down
ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces();
- for (int i = 0; i < interfaces.length; i++) {
- ResolvedType iface = interfaces[i];
+ for (ResolvedType anInterface : interfaces) {
+ ResolvedType iface = anInterface;
if (!genericsAware && iface.isParameterizedOrGenericType()) {
iface = iface.getRawType();
}
}
// Go through the interfaces on the way back down
ResolvedType[] interfaces = resolvedType.getDeclaredInterfaces();
- for (int i = 0; i < interfaces.length; i++) {
- ResolvedType iface = interfaces[i];
+ for (ResolvedType anInterface : interfaces) {
+ ResolvedType iface = anInterface;
if (!genericsAware && (iface.isParameterizedType() || iface.isGenericType())) {
iface = iface.getRawType();
}
if (!type.isMissing()) {
ResolvedMember[] methods = type.getDeclaredMethods();
if (methods != null) {
- for (int i = 0; i < methods.length; i++) {
- ResolvedMember method = methods[i];
+ for (ResolvedMember method : methods) {
if (matches(method, m)) {
return method;
}
// Queue any interfaces not already checked:
ResolvedType[] superinterfaces = type.getDeclaredInterfaces();
if (superinterfaces != null) {
- for (int i = 0; i < superinterfaces.length; i++) {
- ResolvedType interf = superinterfaces[i];
+ for (ResolvedType interf : superinterfaces) {
if (!typesTolookat.contains(interf)) {
typesTolookat.add(interf);
}
* return null if not found
*/
private ResolvedMember lookupMember(Member m, ResolvedMember[] a) {
- for (int i = 0; i < a.length; i++) {
- ResolvedMember f = a[i];
+ for (ResolvedMember f : a) {
if (matches(f, m)) {
return f;
}
while (typeIterator.hasNext()) {
ResolvedType ty = typeIterator.next();
// System.out.println("super: " + ty + ", " + );
- for (Iterator<Declare> i = ty.getDeclares().iterator(); i.hasNext();) {
- Declare dec = i.next();
+ for (Declare dec : ty.getDeclares()) {
if (dec.isAdviceLike()) {
if (includeAdviceLike) {
ret.add(dec);
methods = getGenericType().getDeclaredMethods();
}
Map<String, UnresolvedType> typeVariableMap = getAjMemberParameterizationMap();
- for (int i = 0, len = methods.length; i < len; i++) {
- ShadowMunger munger = methods[i].getAssociatedShadowMunger();
+ for (ResolvedMember method : methods) {
+ ShadowMunger munger = method.getAssociatedShadowMunger();
if (munger != null) {
if (ajMembersNeedParameterization()) {
// munger.setPointcut(munger.getPointcut().parameterizeWith(
if (munger instanceof Advice) {
Advice advice = (Advice) munger;
// update to use the parameterized signature...
- UnresolvedType[] ptypes = methods[i].getGenericParameterTypes();
+ UnresolvedType[] ptypes = method.getGenericParameterTypes();
UnresolvedType[] newPTypes = new UnresolvedType[ptypes.length];
for (int j = 0; j < ptypes.length; j++) {
if (ptypes[j] instanceof TypeVariableReferenceType) {
private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) {
List<ResolvedMember> l = new ArrayList<ResolvedMember>();
- for (int i = 0, len = ms.length; i < len; i++) {
- if (!ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) {
- l.add(ms[i]);
+ for (ResolvedMember m : ms) {
+ if (!m.isAjSynthetic() && m.getAssociatedShadowMunger() == null) {
+ l.add(m);
}
}
return l.toArray(new ResolvedMember[l.size()]);
if (ret == null) {
// try interfaces then, but only ITDs now...
ResolvedType[] superInterfaces = onType.getDeclaredInterfaces();
- for (int i = 0; i < superInterfaces.length; i++) {
- ret = superInterfaces[i].lookupMethodInITDs(member);
+ for (ResolvedType superInterface : superInterfaces) {
+ ret = superInterface.lookupMethodInITDs(member);
if (ret != null) {
return ret;
}
}
ResolvedType[] superIs = getDeclaredInterfaces();
- for (int i = 0; i < superIs.length; i++) {
- ResolvedType superI = superIs[i];
+ for (ResolvedType superI : superIs) {
if (superI.genericTypeEquals(lookingFor)) {
return superI;
}
ResolvedType runtimeException = world.resolve("java.lang.RuntimeException");
ResolvedType error = world.resolve("java.lang.Error");
- outer: for (int i = 0, leni = childExceptions.length; i < leni; i++) {
+ outer:
+ for (ResolvedType childException : childExceptions) {
// System.err.println("checking: " + childExceptions[i]);
- if (runtimeException.isAssignableFrom(childExceptions[i])) {
+ if (runtimeException.isAssignableFrom(childException)) {
continue;
}
- if (error.isAssignableFrom(childExceptions[i])) {
+ if (error.isAssignableFrom(childException)) {
continue;
}
- for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) {
- if (parentExceptions[j].isAssignableFrom(childExceptions[i])) {
+ for (ResolvedType parentException : parentExceptions) {
+ if (parentException.isAssignableFrom(childException)) {
continue outer;
}
}
}
private void addPointcutsResolvingConflicts(List<ResolvedMember> acc, List<ResolvedMember> added, boolean isOverriding) {
- for (Iterator<ResolvedMember> i = added.iterator(); i.hasNext();) {
- ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next();
- for (Iterator<ResolvedMember> j = acc.iterator(); j.hasNext();) {
+ for (ResolvedMember resolvedMember : added) {
+ ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) resolvedMember;
+ for (Iterator<ResolvedMember> j = acc.iterator(); j.hasNext(); ) {
ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next();
if (toAdd == null || existing == null || existing == toAdd) {
continue;
return this;
}
boolean workToDo = false;
- for (int i = 0; i < typeParameters.length; i++) {
- if (typeParameters[i].isTypeVariableReference() || (typeParameters[i] instanceof BoundedReferenceType) || typeParameters[i].isParameterizedType()) {
+ for (UnresolvedType typeParameter : typeParameters) {
+ if (typeParameter.isTypeVariableReference() || (typeParameter instanceof BoundedReferenceType) || typeParameter.isParameterizedType()) {
workToDo = true;
}
}
return false;
}
- for (int i = 0; i < typeParameters.length; i++) {
- ResolvedType aType = (ResolvedType) typeParameters[i];
+ for (UnresolvedType typeParameter : typeParameters) {
+ ResolvedType aType = (ResolvedType) typeParameter;
if (aType.isTypeVariableReference()
- // Changed according to the problems covered in bug 222648
- // Don't care what kind of type variable - the fact that there
- // is one
- // at all means we can't risk caching it against we get confused
- // later
- // by another variation of the parameterization that just
- // happens to
- // use the same type variable name
-
- // assume the worst - if its definetly not a type declared one,
- // it could be anything
- // && ((TypeVariableReference)aType).getTypeVariable().
- // getDeclaringElementKind()!=TypeVariable.TYPE
+ // Changed according to the problems covered in bug 222648
+ // Don't care what kind of type variable - the fact that there
+ // is one
+ // at all means we can't risk caching it against we get confused
+ // later
+ // by another variation of the parameterization that just
+ // happens to
+ // use the same type variable name
+
+ // assume the worst - if its definetly not a type declared one,
+ // it could be anything
+ // && ((TypeVariableReference)aType).getTypeVariable().
+ // getDeclaringElementKind()!=TypeVariable.TYPE
) {
parameterizedWithTypeVariable = FuzzyBoolean.YES;
return true;
*/
public static int howMany(int i) {
int count = 0;
- for (int j = 0; j < SHADOW_KINDS.length; j++) {
- if ((i & SHADOW_KINDS[j].bit) != 0) {
- count++;
- }
- }
+ for (Kind shadowKind : SHADOW_KINDS) {
+ if ((i & shadowKind.bit) != 0) {
+ count++;
+ }
+ }
return count;
}
*/
protected boolean checkMunger(ShadowMunger munger) {
if (munger.mustCheckExceptions()) {
- for (Iterator<ResolvedType> i = munger.getThrownExceptions().iterator(); i.hasNext();) {
- if (!checkCanThrow(munger, i.next())) {
- return false;
- }
- }
+ for (ResolvedType resolvedType : munger.getThrownExceptions()) {
+ if (!checkCanThrow(munger, resolvedType)) {
+ return false;
+ }
+ }
}
return true;
}
private boolean isDeclaredException(ResolvedType resolvedTypeX, Member member) {
ResolvedType[] excs = getIWorld().resolve(member.getExceptions(getIWorld()));
- for (int i = 0, len = excs.length; i < len; i++) {
- if (excs[i].isAssignableFrom(resolvedTypeX)) {
- return true;
- }
- }
+ for (ResolvedType exc : excs) {
+ if (exc.isAssignableFrom(resolvedTypeX)) {
+ return true;
+ }
+ }
return false;
}
}
}
}
- for (Iterator<String> iter = clashingAspects.iterator(); iter.hasNext();) {
- String element = iter.next();
- String aspect1 = element.substring(0, element.indexOf(":"));
- String aspect2 = element.substring(element.indexOf(":") + 1);
- getIWorld().getLint().unorderedAdviceAtShadow.signal(new String[] { this.toString(), aspect1, aspect2 },
- this.getSourceLocation(), null);
- }
+ for (String element : clashingAspects) {
+ String aspect1 = element.substring(0, element.indexOf(":"));
+ String aspect2 = element.substring(element.indexOf(":") + 1);
+ getIWorld().getLint().unorderedAdviceAtShadow.signal(new String[]{this.toString(), aspect1, aspect2},
+ this.getSourceLocation(), null);
+ }
}
}
if (types == null)
return "";
StringBuffer buf = new StringBuffer();
- for (int i = 0, len = types.length; i < len; i++) {
- buf.append(makeString(types[i]));
+ for (UnresolvedType type : types) {
+ buf.append(makeString(type));
buf.append(':');
}
return buf.toString();
if (names == null)
return "";
StringBuffer buf = new StringBuffer();
- for (int i = 0, len = names.length; i < len; i++) {
- buf.append(names[i]);
+ for (String name : names) {
+ buf.append(name);
buf.append(':');
}
return buf.toString();
if (nvPairs == null) {
return false;
}
- for (int i = 0; i < nvPairs.size(); i++) {
- AnnotationNameValuePair pair = nvPairs.get(i);
+ for (AnnotationNameValuePair pair : nvPairs) {
if (pair.getName().equals(n)) {
return true;
}
if (nvPairs == null) {
return false;
}
- for (int i = 0; i < nvPairs.size(); i++) {
- AnnotationNameValuePair pair = nvPairs.get(i);
+ for (AnnotationNameValuePair pair : nvPairs) {
if (pair.getName().equals(n)) {
if (pair.getValue().stringify().equals(v)) {
return true;
ArrayAnnotationValue aav = (ArrayAnnotationValue) nvp.getValue();
AnnotationValue[] avs = aav.getValues();
Set<String> targets = new HashSet<String>();
- for (int i = 0; i < avs.length; i++) {
- EnumAnnotationValue value = (EnumAnnotationValue)avs[i];
+ for (AnnotationValue av : avs) {
+ EnumAnnotationValue value = (EnumAnnotationValue) av;
targets.add(value.getValue());
}
return targets;
parameterizedSig.append(baseTypeSignature.substring(1, baseTypeSignature.length() - 1));
if (arguments.length > 0) {
parameterizedSig.append("<");
- for (int i = 0; i < arguments.length; i++) {
- parameterizedSig.append(arguments[i].getSignature());
+ for (UnresolvedType argument : arguments) {
+ parameterizedSig.append(argument.getSignature());
}
parameterizedSig.append(">");
}
UnresolvedType declaring = (UnresolvedType) declaringElement;
ReferenceType rd = (ReferenceType) declaring.resolve(world);
TypeVariable[] tVars = rd.getTypeVariables();
- for (int i = 0; i < tVars.length; i++) {
- if (tVars[i].getName().equals(getName())) {
- resolvedTVar = tVars[i];
+ for (TypeVariable tVar : tVars) {
+ if (tVar.getName().equals(getName())) {
+ resolvedTVar = tVar;
break;
}
}
// look for type variable on method...
ResolvedMember declaring = (ResolvedMember) declaringElement;
TypeVariable[] tvrts = declaring.getTypeVariables();
- for (int i = 0; i < tvrts.length; i++) {
- if (tvrts[i].getName().equals(getName())) {
- resolvedTVar = tvrts[i];
+ for (TypeVariable tvrt : tvrts) {
+ if (tvrt.getName().equals(getName())) {
+ resolvedTVar = tvrt;
// if (tvrts[i].isTypeVariableReference()) {
// TypeVariableReferenceType tvrt = (TypeVariableReferenceType) tvrts[i].resolve(inSomeWorld);
// TypeVariable tv = tvrt.getTypeVariable();
return false;
}
// candidate is a subtype of all superInterfaces
- for (int i = 0; i < superInterfaces.length; i++) {
- if (!isASubtypeOf(superInterfaces[i], candidate)) {
+ for (UnresolvedType superInterface : superInterfaces) {
+ if (!isASubtypeOf(superInterface, candidate)) {
return false;
}
}
ret.append(" extends ");
ret.append(getFirstBound().getName());
if (superInterfaces != null) {
- for (int i = 0; i < superInterfaces.length; i++) {
- if (!getFirstBound().equals(superInterfaces[i])) {
+ for (UnresolvedType superInterface : superInterfaces) {
+ if (!getFirstBound().equals(superInterface)) {
ret.append(" & ");
- ret.append(superInterfaces[i].getName());
+ ret.append(superInterface.getName());
}
}
}
sb.append(superclass.getSignature());
}
if (superInterfaces.length != 0) {
- for (int i = 0; i < superInterfaces.length; i++) {
+ for (UnresolvedType superInterface : superInterfaces) {
sb.append(":");
- UnresolvedType iBound = superInterfaces[i];
+ UnresolvedType iBound = superInterface;
sb.append(iBound.getSignature());
}
}
sb.append(((ReferenceType)superclass).getSignatureForAttribute());
}
if (superInterfaces.length != 0) {
- for (int i = 0; i < superInterfaces.length; i++) {
+ for (UnresolvedType superInterface : superInterfaces) {
sb.append(":");
- ResolvedType iBound = (ResolvedType) superInterfaces[i];
+ ResolvedType iBound = (ResolvedType) superInterface;
sb.append(iBound.getSignatureForAttribute());
}
}
s.writeInt(0);
} else {
s.writeInt(superInterfaces.length);
- for (int i = 0; i < superInterfaces.length; i++) {
- UnresolvedType ibound = superInterfaces[i];
+ for (UnresolvedType ibound : superInterfaces) {
ibound.write(s);
}
}
typeVariable.resolve(world);
ResolvedType annotationType = ResolvedType.ANNOTATION.resolve(world);
UnresolvedType[] ifBounds = typeVariable.getSuperInterfaces();// AdditionalBounds();
- for (int i = 0; i < ifBounds.length; i++) {
- if (((ReferenceType) ifBounds[i]).isAnnotation()) {
+ for (UnresolvedType ifBound : ifBounds) {
+ if (((ReferenceType) ifBound).isAnnotation()) {
return true;
}
- if (ifBounds[i].equals(annotationType)) {
+ if (ifBound.equals(annotationType)) {
return true; // annotation itself does not have the annotation flag set in Java!
}
}
if (vars == null || vars.length == 0) {
return null;
}
- for (int i = 0; i < vars.length; i++) {
- TypeVariable aVar = vars[i];
- if (aVar.getName().equals(name)) {
- return aVar;
- }
- }
+ for (TypeVariable aVar : vars) {
+ if (aVar.getName().equals(name)) {
+ return aVar;
+ }
+ }
return null;
}
return false;
}
// Go through the annotation types on the advice
- for (int i = 0; i < anns.length; i++) {
- if (UnresolvedType.SUPPRESS_AJ_WARNINGS.getSignature().equals(anns[i].getTypeSignature())) {
+ for (AnnotationAJ ann : anns) {
+ if (UnresolvedType.SUPPRESS_AJ_WARNINGS.getSignature().equals(ann.getTypeSignature())) {
// Two possibilities:
// 1. there are no values specified (i.e. @SuppressAjWarnings)
// 2. there are values specified (i.e. @SuppressAjWarnings("A") or @SuppressAjWarnings({"A","B"})
- String value = anns[i].getStringFormOfValue("value");
+ String value = ann.getStringFormOfValue("value");
// Slightly lazy, just doing a string indexof
if (value == null || value.indexOf(lintkey) != -1) {
return true;
public AnnotationPatternList(AnnotationTypePattern[] arguments) {
this.typePatterns = arguments;
- for (int i = 0; i < arguments.length; i++) {
- if (arguments[i] == AnnotationTypePattern.ELLIPSIS) {
+ for (AnnotationTypePattern argument : arguments) {
+ if (argument == AnnotationTypePattern.ELLIPSIS) {
ellipsisCount++;
}
}
}
public void resolve(World inWorld) {
- for (int i = 0; i < typePatterns.length; i++) {
- typePatterns[i].resolve(inWorld);
+ for (AnnotationTypePattern typePattern : typePatterns) {
+ typePattern.resolve(inWorld);
}
}
// now work through the args and the patterns, skipping at ellipsis
FuzzyBoolean ret = FuzzyBoolean.YES;
int argsIndex = 0;
- for (int i = 0; i < typePatterns.length; i++) {
- if (typePatterns[i] == AnnotationTypePattern.ELLIPSIS) {
+ for (AnnotationTypePattern typePattern : typePatterns) {
+ if (typePattern == AnnotationTypePattern.ELLIPSIS) {
// match ellipsisMatchCount args
argsIndex += numArgsMatchedByEllipsis;
- } else if (typePatterns[i] == AnnotationTypePattern.ANY) {
+ } else if (typePattern == AnnotationTypePattern.ANY) {
argsIndex++;
} else {
// match the argument type at argsIndex with the ExactAnnotationTypePattern
if (someArgs[argsIndex].isPrimitiveType()) {
return FuzzyBoolean.NO; // can never match
}
- ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern) typePatterns[i];
+ ExactAnnotationTypePattern ap = (ExactAnnotationTypePattern) typePattern;
FuzzyBoolean matches = ap.matchesRuntimeType(someArgs[argsIndex]);
if (matches == FuzzyBoolean.NO) {
return FuzzyBoolean.MAYBE; // could still match at runtime
public int hashCode() {
int result = 41;
- for (int i = 0, len = typePatterns.length; i < len; i++) {
- result = 37 * result + typePatterns[i].hashCode();
+ for (AnnotationTypePattern typePattern : typePatterns) {
+ result = 37 * result + typePattern.hashCode();
}
return result;
}
public void write(CompressingDataOutputStream s) throws IOException {
s.writeShort(typePatterns.length);
- for (int i = 0; i < typePatterns.length; i++) {
- typePatterns[i].write(s);
+ for (AnnotationTypePattern typePattern : typePatterns) {
+ typePattern.write(s);
}
writeLocation(s);
}
public Object traverse(PatternNodeVisitor visitor, Object data) {
Object ret = accept(visitor, data);
- for (int i = 0; i < typePatterns.length; i++) {
- typePatterns[i].traverse(visitor, ret);
+ for (AnnotationTypePattern typePattern : typePatterns) {
+ typePattern.traverse(visitor, ret);
}
return ret;
}
if (kind == Shadow.FieldGet || kind == Shadow.FieldSet) {
// FIXME asc should include supers with getInterTypeMungersIncludingSupers ?
List mungers = rMember.getDeclaringType().resolve(shadow.getIWorld()).getInterTypeMungers();
- for (Iterator iter = mungers.iterator(); iter.hasNext();) {
- ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) iter.next();
+ for (Object munger : mungers) {
+ ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) munger;
if (typeMunger.getMunger() instanceof NewFieldTypeMunger) {
ResolvedMember fakerm = typeMunger.getSignature();
if (fakerm.equals(member)) {
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
- for (int i = 0; i < decMethods.length; i++) {
- ResolvedMember member = decMethods[i];
+ for (ResolvedMember member : decMethods) {
if (member.equals(ajcMethod)) {
return member;
}
public List<BindingPattern> getBindingAnnotationTypePatterns() {
List<BindingPattern> l = new ArrayList<BindingPattern>();
AnnotationTypePattern[] pats = arguments.getAnnotationPatterns();
- for (int i = 0; i < pats.length; i++) {
- if (pats[i] instanceof BindingAnnotationTypePattern) {
- l.add((BindingPattern)pats[i]);
+ for (AnnotationTypePattern pat : pats) {
+ if (pat instanceof BindingAnnotationTypePattern) {
+ l.add((BindingPattern) pat);
}
}
return l;
// want to ignore.
if (shadow.getKind() == Shadow.AdviceExecution) {
int numExtraArgs = 0;
- for (int i = 0; i < argumentsToMatchAgainst.length; i++) {
- String argumentSignature = argumentsToMatchAgainst[i].getSignature();
+ for (ResolvedType resolvedType : argumentsToMatchAgainst) {
+ String argumentSignature = resolvedType.getSignature();
if (argumentSignature.startsWith(ASPECTJ_JP_SIGNATURE_PREFIX)
|| argumentSignature.startsWith(ASPECTJ_SYNTHETIC_SIGNATURE_PREFIX)) {
numExtraArgs++;
public List<BindingTypePattern> getBindingTypePatterns() {
List<BindingTypePattern> l = new ArrayList<BindingTypePattern>();
TypePattern[] pats = arguments.getTypePatterns();
- for (int i = 0; i < pats.length; i++) {
- if (pats[i] instanceof BindingTypePattern) {
- l.add((BindingTypePattern)pats[i]);
+ for (TypePattern pat : pats) {
+ if (pat instanceof BindingTypePattern) {
+ l.add((BindingTypePattern) pat);
}
}
return l;
public UnresolvedType[] getUsedFormalTypes() {
UnresolvedType[] ret = new UnresolvedType[bindings.length];
int index = 0;
- for (int i = 0, len = bindings.length; i < len; i++) {
- if (bindings[i] != null) {
- ret[index++] = ((BindingTypePattern) bindings[i]).getExactType();
+ for (BindingPattern binding : bindings) {
+ if (binding != null) {
+ ret[index++] = ((BindingTypePattern) binding).getExactType();
}
}
UnresolvedType[] newRet = new UnresolvedType[index];
ResolvedMember[] annotationFields = theAnnotationType.getDeclaredMethods();
field = null;
boolean looksAmbiguous = false;
- for (int i = 0; i < annotationFields.length; i++) {
- ResolvedMember resolvedMember = annotationFields[i];
+ for (ResolvedMember resolvedMember : annotationFields) {
if (resolvedMember.getReturnType().equals(formalBinding.getType())) {
if (field != null) {
boolean haveProblem = true;
if (parameterAnnotations == null) {
return FuzzyBoolean.NO;
}
- for (int i = 0; i < parameterAnnotations.length; i++) {
- if (annotationType.equals(parameterAnnotations[i])) {
+ for (ResolvedType parameterAnnotation : parameterAnnotations) {
+ if (annotationType.equals(parameterAnnotation)) {
// Are we also matching annotation values?
if (annotationValues != null) {
- parameterAnnotations[i]
+ parameterAnnotation
.getWorld()
.getMessageHandler()
.handleMessage(
} else {
s.writeInt(annotationValues.size());
Set<String> key = annotationValues.keySet();
- for (Iterator<String> keys = key.iterator(); keys.hasNext();) {
- String k = keys.next();
+ for (String k : key) {
s.writeUTF(k);
s.writeUTF(annotationValues.get(k));
}
}
public boolean isFullySetUp() {
- for (int i = 0; i < vars.length; i++) {
- if (vars[i] == null)
+ for (Var var : vars) {
+ if (var == null)
return false;
}
return true;
}
// try itds before we give up (this doesnt find annotations - the signature returned may not include them)
List<ConcreteTypeMunger> mungers = type.getInterTypeMungersIncludingSupers();
- for (Iterator<ConcreteTypeMunger> iter = mungers.iterator(); iter.hasNext();) {
- ConcreteTypeMunger munger = iter.next();
+ for (ConcreteTypeMunger munger : mungers) {
Member member = munger.getSignature();
if (signaturePattern.matches(member, type.getWorld(), false)) {
if (!Modifier.isPublic(member.getModifiers())) {
public NamePattern(char[] pattern) {
this.pattern = pattern;
- for (int i = 0, len = pattern.length; i < len; i++) {
- if (pattern[i] == '*') {
+ for (char c : pattern) {
+ if (c == '*') {
starCount++;
}
}
SortedSet<Pointcut> nodes = new TreeSet<Pointcut>(new PointcutEvaluationExpenseComparator());
collectAndNodes(apc, nodes);
// look for A and !A, or IfFalse
- for (Iterator<Pointcut> iter = nodes.iterator(); iter.hasNext();) {
- Pointcut element = iter.next();
+ for (Pointcut element : nodes) {
if (element instanceof NotPointcut) {
Pointcut body = ((NotPointcut) element).getNegatedPointcut();
if (nodes.contains(body)) {
patternNode.traverse(visitor, null);
if (visitor.containedIncorrectTargetKind()) {
Set<ExactAnnotationTypePattern> keys = visitor.getIncorrectTargetKinds().keySet();
- for (Iterator<ExactAnnotationTypePattern> iter = keys.iterator(); iter.hasNext();) {
- PatternNode node = iter.next();
+ for (PatternNode node : keys) {
AnnotationTargetKind[] targetKinds = visitor.getIncorrectTargetKinds().get(node);
reportUnmatchedTargetKindMessage(targetKinds, node, scope, false);
}
return data;
}
List<AnnotationTargetKind> incorrectTargets = new ArrayList<AnnotationTargetKind>();
- for (int i = 0; i < targetKinds.length; i++) {
- if (targetKinds[i].getName().equals(kind.getName())
- || (targetKinds[i].getName().equals("PARAMETER") && node.isForParameterAnnotationMatch())) {
+ for (AnnotationTargetKind targetKind : targetKinds) {
+ if (targetKind.getName().equals(kind.getName())
+ || (targetKind.getName().equals("PARAMETER") && node.isForParameterAnnotationMatch())) {
return data;
}
- incorrectTargets.add(targetKinds[i]);
+ incorrectTargets.add(targetKind);
}
if (incorrectTargets.isEmpty()) {
return data;
}
// exception here is if parameter annotations are allowed
if (parameterTargettingAnnotationsAllowed) {
- for (int i = 0; i < targetKinds.length; i++) {
- AnnotationTargetKind annotationTargetKind = targetKinds[i];
+ for (AnnotationTargetKind annotationTargetKind : targetKinds) {
if (annotationTargetKind.getName().equals("PARAMETER") && node.isForParameterAnnotationMatch()) {
return data;
}
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
- for (int i = 0; i < decMethods.length; i++) {
- ResolvedMember member = decMethods[i];
+ for (ResolvedMember member : decMethods) {
if (member.equals(ajcMethod)) {
return member;
}
}
public UnresolvedType lookupType(String name, IHasPosition location) {
- for (int i = 0; i < importedNames.length; i++) {
- String importedName = importedNames[i];
+ for (String importedName : importedNames) {
// make sure we're matching against the type name rather than part of it
// if (importedName.endsWith("." + name)) {
if (importedName.endsWith(name)) {
}
public FormalBinding lookupFormal(String name) {
- for (int i = 0, len = bindings.length; i < len; i++) {
- if (bindings[i].getName().equals(name)) {
- return bindings[i];
+ for (FormalBinding binding : bindings) {
+ if (binding.getName().equals(name)) {
+ return binding;
}
}
return null;
public TypePatternList(TypePattern[] arguments) {
this.typePatterns = arguments;
- for (int i = 0; i < arguments.length; i++) {
- if (arguments[i] == TypePattern.ELLIPSIS) {
+ for (TypePattern argument : arguments) {
+ if (argument == TypePattern.ELLIPSIS) {
ellipsisCount++;
}
}
}
public void postRead(ResolvedType enclosingType) {
- for (int i = 0; i < typePatterns.length; i++) {
- TypePattern p = typePatterns[i];
+ for (TypePattern p : typePatterns) {
p.postRead(enclosingType);
}
}
@Override
public int hashCode() {
int result = 41;
- for (int i = 0, len = typePatterns.length; i < len; i++) {
- result = 37 * result + typePatterns[i].hashCode();
+ for (TypePattern typePattern : typePatterns) {
+ result = 37 * result + typePattern.hashCode();
}
return result;
}
@Override
public void write(CompressingDataOutputStream s) throws IOException {
s.writeShort(typePatterns.length);
- for (int i = 0; i < typePatterns.length; i++) {
- typePatterns[i].write(s);
+ for (TypePattern typePattern : typePatterns) {
+ typePattern.write(s);
}
// writeLocation(s);
}
public List<UnresolvedType> getExactTypes() {
List<UnresolvedType> ret = new ArrayList<UnresolvedType>();
- for (int i = 0; i < typePatterns.length; i++) {
- UnresolvedType t = typePatterns[i].getExactType();
+ for (TypePattern typePattern : typePatterns) {
+ UnresolvedType t = typePattern.getExactType();
if (!ResolvedType.isMissing(t)) {
ret.add(t);
}
@Override
public Object traverse(PatternNodeVisitor visitor, Object data) {
Object ret = accept(visitor, data);
- for (int i = 0; i < typePatterns.length; i++) {
- typePatterns[i].traverse(visitor, ret);
+ for (TypePattern typePattern : typePatterns) {
+ typePattern.traverse(visitor, ret);
}
return ret;
}
public boolean areAllExactWithNoSubtypesAllowed() {
- for (int i = 0; i < typePatterns.length; i++) {
- TypePattern array_element = typePatterns[i];
+ for (TypePattern array_element : typePatterns) {
if (!(array_element instanceof ExactTypePattern)) {
return false;
} else {
}
public Question anyChanges() {
- for (Iterator<Map.Entry<Question,FuzzyBoolean>> i = questionsAndAnswers.entrySet().iterator(); i.hasNext(); ) {
- Map.Entry<Question,FuzzyBoolean> entry = i.next();
- Question question = (Question)entry.getKey();
- FuzzyBoolean expectedAnswer = (FuzzyBoolean)entry.getValue();
-
+ for (Map.Entry<Question, FuzzyBoolean> entry : questionsAndAnswers.entrySet()) {
+ Question question = (Question) entry.getKey();
+ FuzzyBoolean expectedAnswer = (FuzzyBoolean) entry.getValue();
+
FuzzyBoolean currentAnswer = question.ask();
//System.out.println(question + ":" + currentAnswer);
if (currentAnswer != expectedAnswer) {
hashCode = hashCode * 37 + lowerBound.hashCode();
}
if (interfaceBounds != null) {
- for (int i = 0; i < interfaceBounds.length; i++) {
- hashCode = 37 * hashCode + interfaceBounds[i].hashCode();
+ for (TypePattern interfaceBound : interfaceBounds) {
+ hashCode = 37 * hashCode + interfaceBound.hashCode();
}
}
return hashCode;
s.writeInt(0);
} else {
s.writeInt(interfaceBounds.length);
- for (int i = 0; i < interfaceBounds.length; i++) {
- interfaceBounds[i].write(s);
+ for (TypePattern interfaceBound : interfaceBounds) {
+ interfaceBound.write(s);
}
}
s.writeBoolean(hasLowerBound());
}
public TypeVariablePattern lookupTypeVariable(String name) {
- for (int i = 0; i < patterns.length; i++) {
- if (patterns[i].getName().equals(name)) {
- return patterns[i];
+ for (TypeVariablePattern pattern : patterns) {
+ if (pattern.getName().equals(name)) {
+ return pattern;
}
}
return null;
public void write(CompressingDataOutputStream s) throws IOException {
s.writeInt(patterns.length);
- for (int i = 0; i < patterns.length; i++) {
- patterns[i].write(s);
+ for (TypeVariablePattern pattern : patterns) {
+ pattern.write(s);
}
writeLocation(s);
}
public Object traverse(PatternNodeVisitor visitor, Object data) {
Object ret = accept(visitor, data);
- for (int i = 0; i < patterns.length; i++) {
- patterns[i].traverse(visitor, ret);
+ for (TypeVariablePattern pattern : patterns) {
+ pattern.traverse(visitor, ret);
}
return ret;
}
}
String v = annotationValues.get(k);
boolean validKey = false;
- for (int i = 0; i < ms.length; i++) {
- ResolvedMember resolvedMember = ms[i];
+ for (ResolvedMember resolvedMember : ms) {
if (resolvedMember.getName().equals(key) && resolvedMember.isAbstract()) {
validKey = true;
ResolvedType t = resolvedMember.getReturnType().resolve(scope.getWorld());
// }
// replacementValues.put(k, rt.getSignature());
} else {
- scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.UNSUPPORTED_ANNOTATION_VALUE_TYPE,t), getSourceLocation()));
- replacementValues.put(k,"");
+ scope.message(MessageUtil.error(WeaverMessages.format(WeaverMessages.UNSUPPORTED_ANNOTATION_VALUE_TYPE, t), getSourceLocation()));
+ replacementValues.put(k, "");
}
}
}
}
if (isForParameterAnnotationMatch()) {
if (parameterAnnotations != null && parameterAnnotations.length != 0) {
- for (int i = 0; i < parameterAnnotations.length; i++) {
- if (typePattern.matches(parameterAnnotations[i], TypePattern.STATIC).alwaysTrue()) {
+ for (ResolvedType parameterAnnotation : parameterAnnotations) {
+ if (typePattern.matches(parameterAnnotation, TypePattern.STATIC).alwaysTrue()) {
return FuzzyBoolean.YES;
}
}
// matched by the typePattern.
ResolvedType[] annTypes = annotated.getAnnotationTypes();
if (annTypes != null && annTypes.length != 0) {
- for (int i = 0; i < annTypes.length; i++) {
- if (typePattern.matches(annTypes[i], TypePattern.STATIC).alwaysTrue()) {
+ for (ResolvedType annType : annTypes) {
+ if (typePattern.matches(annType, TypePattern.STATIC).alwaysTrue()) {
return FuzzyBoolean.YES;
}
}
} else {
s.writeInt(annotationValues.size());
Set<String> key = annotationValues.keySet();
- for (Iterator<String> keys = key.iterator(); keys.hasNext();) {
- String k = keys.next();
+ for (String k : key) {
s.writeUTF(k);
s.writeUTF(annotationValues.get(k));
}
this.namePatterns = namePatterns;
this.dim = dim;
ellipsisCount = 0;
- for (int i = 0; i < namePatterns.length; i++) {
- if (namePatterns[i] == NamePattern.ELLIPSIS) {
+ for (NamePattern namePattern : namePatterns) {
+ if (namePattern == NamePattern.ELLIPSIS) {
ellipsisCount++;
}
}
// we've already ruled out "*", and no other name pattern should match an anonymous type
return false;
}
- for (int i = 0, len = knownMatches.length; i < len; i++) {
- if (knownMatches[i].equals(targetTypeName)) {
+ for (String knownMatch : knownMatches) {
+ if (knownMatch.equals(targetTypeName)) {
return true;
}
}
} else {
- for (int i = 0, len = knownMatches.length; i < len; i++) {
- String knownMatch = knownMatches[i];
+ for (String knownMatch : knownMatches) {
// String knownPrefix = knownMatches[i] + "$";
// if (targetTypeName.startsWith(knownPrefix)) {
if (targetTypeName.startsWith(knownMatch) && targetTypeName.length() > knownMatch.length()
// if any prefixes match, strip the prefix and check that the rest matches
// assumes that prefixes have a dot at the end
- for (int i = 0, len = importedPrefixes.length; i < len; i++) {
- String prefix = importedPrefixes[i];
+ for (String prefix : importedPrefixes) {
// System.err.println("prefix match? " + prefix + " to " + targetTypeName);
if (targetTypeName.startsWith(prefix)) {
canCreateExactTypePattern = false;
}
if (additionalInterfaceBounds != null) {
- for (int i = 0; i < additionalInterfaceBounds.length; i++) {
- if (ResolvedType.isMissing(additionalInterfaceBounds[i].getExactType())) {
+ for (TypePattern additionalInterfaceBound : additionalInterfaceBounds) {
+ if (ResolvedType.isMissing(additionalInterfaceBound.getExactType())) {
canCreateExactTypePattern = false;
}
}
int minRequiredTypeParameters = typeParameters.size();
boolean foundEllipsis = false;
TypePattern[] typeParamPatterns = typeParameters.getTypePatterns();
- for (int i = 0; i < typeParamPatterns.length; i++) {
- if (typeParamPatterns[i] instanceof WildTypePattern) {
- WildTypePattern wtp = (WildTypePattern) typeParamPatterns[i];
+ for (TypePattern typeParamPattern : typeParamPatterns) {
+ if (typeParamPattern instanceof WildTypePattern) {
+ WildTypePattern wtp = (WildTypePattern) typeParamPattern;
if (wtp.ellipsisCount > 0) {
foundEllipsis = true;
minRequiredTypeParameters--;
// if (namePatterns.length != 1) return CollectionUtil.NO_STRINGS;
List<String> ret = new ArrayList<String>();
- for (int i = 0, len = possibleMatches.length; i < len; i++) {
- char[][] names = splitNames(possibleMatches[i], true); // ??? not most efficient
+ for (String possibleMatch : possibleMatches) {
+ char[][] names = splitNames(possibleMatch, true); // ??? not most efficient
if (namePatterns[0].matches(names[names.length - 1])) {
- ret.add(possibleMatches[i]);
+ ret.add(possibleMatch);
continue;
}
- if (possibleMatches[i].indexOf("$") != -1) {
- names = splitNames(possibleMatches[i], false); // ??? not most efficient
+ if (possibleMatch.indexOf("$") != -1) {
+ names = splitNames(possibleMatch, false); // ??? not most efficient
if (namePatterns[0].matches(names[names.length - 1])) {
- ret.add(possibleMatches[i]);
+ ret.add(possibleMatch);
}
}
}
@Override
public int hashCode() {
int result = 17;
- for (int i = 0, len = namePatterns.length; i < len; i++) {
- result = 37 * result + namePatterns[i].hashCode();
+ for (NamePattern namePattern : namePatterns) {
+ result = 37 * result + namePattern.hashCode();
}
result = 37 * result + annotationPattern.hashCode();
if (upperBound != null) {
s.writeByte(TypePattern.WILD);
s.writeByte(VERSION);
s.writeShort(namePatterns.length);
- for (int i = 0; i < namePatterns.length; i++) {
- namePatterns[i].write(s);
+ for (NamePattern namePattern : namePatterns) {
+ namePattern.write(s);
}
s.writeBoolean(includeSubtypes);
s.writeInt(dim);
}
s.writeInt(additionalInterfaceBounds == null ? 0 : additionalInterfaceBounds.length);
if (additionalInterfaceBounds != null) {
- for (int i = 0; i < additionalInterfaceBounds.length; i++) {
- additionalInterfaceBounds[i].write(s);
+ for (TypePattern additionalInterfaceBound : additionalInterfaceBounds) {
+ additionalInterfaceBound.write(s);
}
}
}
*/
private StandardPointcutParser(Set/* <PointcutPrimitives> */supportedPointcutKinds, World world) {
supportedPrimitives = supportedPointcutKinds;
- for (Iterator iter = supportedPointcutKinds.iterator(); iter.hasNext();) {
- PointcutPrimitive element = (PointcutPrimitive) iter.next();
+ for (Object supportedPointcutKind : supportedPointcutKinds) {
+ PointcutPrimitive element = (PointcutPrimitive) supportedPointcutKind;
if ((element == PointcutPrimitive.IF) || (element == PointcutPrimitive.CFLOW)
|| (element == PointcutPrimitive.CFLOW_BELOW)) {
throw new UnsupportedOperationException("Cannot handle if, cflow, and cflowbelow primitives");
private ResolvedMember getMethod(ResolvedType type, String methodName, String methodSignature) {
ResolvedMember[] methods = type.getDeclaredMethods();
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals(methodName)
- && (methodSignature == null || methodSignature.equals(methods[i].getSignature()))) {
- return methods[i];
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals(methodName)
+ && (methodSignature == null || methodSignature.equals(method.getSignature()))) {
+ return method;
}
}
return null;
private ResolvedMember getMethod(ResolvedType type, String methodName, String methodSignature) {
ResolvedMember[] methods = type.getDeclaredMethods();
- for (int i = 0; i < methods.length; i++) {
- System.out.println(methods[i].getName() + methods[i].getSignature());
- if (methods[i].getName().equals(methodName)
- && (methodSignature == null || methodSignature.equals(methods[i].getSignature()))) {
- return methods[i];
+ for (ResolvedMember method : methods) {
+ System.out.println(method.getName() + method.getSignature());
+ if (method.getName().equals(methodName)
+ && (methodSignature == null || methodSignature.equals(method.getSignature()))) {
+ return method;
}
}
return null;
public void testPrimitiveTypes() {
ResolvedType[] primitives = world.resolve(primitiveTypes);
- for (int i = 0, len = primitives.length; i < len; i++) {
- ResolvedType ty = primitives[i];
+ for (ResolvedType ty : primitives) {
modifiersTest(ty, Modifier.PUBLIC | Modifier.FINAL);
fieldsTest(ty, ResolvedMember.NONE);
methodsTest(ty, ResolvedMember.NONE);
isInterfaceTest(ty, false);
isClassTest(ty, false);
isAspectTest(ty, false);
- for (int j = 0; j < len; j++) {
- ResolvedType ty1 = primitives[j];
+ for (ResolvedType ty1 : primitives) {
if (ty.equals(ty1)) {
isCoerceableFromTest(ty, ty1, true);
} else if (ty.equals(UnresolvedType.BOOLEAN) || ty1.equals(UnresolvedType.BOOLEAN)
// Result of this depends on whether autoboxing is supported
// isCoerceableFromTest(ty, UnresolvedType.OBJECT, getSupportsAutoboxing());
- primAssignTest("B", new String[] {});
- primAssignTest("S", new String[] { "B" });
- primAssignTest("C", new String[] { "B" });
- primAssignTest("I", new String[] { "B", "S", "C" });
- primAssignTest("J", new String[] { "B", "S", "C", "I" });
- primAssignTest("F", new String[] { "B", "S", "C", "I", "J" });
- primAssignTest("D", new String[] { "B", "S", "C", "I", "J", "F" });
- primAssignTest("Z", new String[] {});
- primAssignTest("V", new String[] {});
+ primAssignTest("B", new String[]{});
+ primAssignTest("S", new String[]{"B"});
+ primAssignTest("C", new String[]{"B"});
+ primAssignTest("I", new String[]{"B", "S", "C"});
+ primAssignTest("J", new String[]{"B", "S", "C", "I"});
+ primAssignTest("F", new String[]{"B", "S", "C", "I", "J"});
+ primAssignTest("D", new String[]{"B", "S", "C", "I", "J", "F"});
+ primAssignTest("Z", new String[]{});
+ primAssignTest("V", new String[]{});
}
}
public void testPrimitiveArrays() {
ResolvedType[] primitives = world.resolve(primitiveTypes);
- for (int i = 0, len = primitives.length; i < len; i++) {
- ResolvedType ty = primitives[i];
+ for (ResolvedType ty : primitives) {
UnresolvedType tx = UnresolvedType.forSignature("[" + ty.getSignature());
ResolvedType aty = world.resolve(tx, true);
assertTrue("Couldnt find type " + tx, !aty.isMissing());
methodsTest(aty, ResolvedMember.NONE);
interfaceTest(
aty,
- new ResolvedType[] { world.getCoreType(UnresolvedType.CLONEABLE),
- world.getCoreType(UnresolvedType.SERIALIZABLE) });
+ new ResolvedType[]{world.getCoreType(UnresolvedType.CLONEABLE),
+ world.getCoreType(UnresolvedType.SERIALIZABLE)});
superclassTest(aty, UnresolvedType.OBJECT);
pointcutsTest(aty, ResolvedMember.NONE);
isInterfaceTest(aty, false);
isClassTest(aty, false);
isAspectTest(aty, false);
- for (int j = 0; j < len; j++) {
- ResolvedType ty1 = primitives[j];
+ for (ResolvedType ty1 : primitives) {
isCoerceableFromTest(aty, ty1, false);
tx = UnresolvedType.forSignature("[" + ty1.getSignature());
ResolvedType aty1 = getWorld().resolve(tx, true);
}
}
// double dimension arrays
- for (int i = 0, len = primitives.length; i < len; i++) {
- ResolvedType ty = primitives[i];
+ for (ResolvedType ty : primitives) {
UnresolvedType tx = UnresolvedType.forSignature("[[" + ty.getSignature());
ResolvedType aty = world.resolve(tx, true);
assertTrue("Couldnt find type " + tx, !aty.isMissing());
methodsTest(aty, ResolvedMember.NONE);
interfaceTest(
aty,
- new ResolvedType[] { world.getCoreType(UnresolvedType.CLONEABLE),
- world.getCoreType(UnresolvedType.SERIALIZABLE) });
+ new ResolvedType[]{world.getCoreType(UnresolvedType.CLONEABLE),
+ world.getCoreType(UnresolvedType.SERIALIZABLE)});
superclassTest(aty, UnresolvedType.OBJECT);
pointcutsTest(aty, ResolvedMember.NONE);
isInterfaceTest(aty, false);
isClassTest(aty, false);
isAspectTest(aty, false);
- for (int j = 0; j < len; j++) {
- ResolvedType ty1 = primitives[j];
+ for (ResolvedType ty1 : primitives) {
isCoerceableFromTest(aty, ty1, false);
tx = UnresolvedType.forSignature("[[" + ty1.getSignature());
ResolvedType aty1 = getWorld().resolve(tx, true);
protected void interfaceTest(ResolvedType type, ResolvedType[] expectedInterfaces) {
ResolvedType[] interfaces = type.getDeclaredInterfaces();
- for (int i = 0; i < expectedInterfaces.length; i++) {
+ for (ResolvedType expectedInterface : expectedInterfaces) {
boolean wasMissing = true;
- for (int j = 0; j < interfaces.length; j++) {
- if (interfaces[j].getSignature().equals(expectedInterfaces[i].getSignature())) {
+ for (ResolvedType anInterface : interfaces) {
+ if (anInterface.getSignature().equals(expectedInterface.getSignature())) {
wasMissing = false;
}
}
if (wasMissing) {
- fail("Expected declared interface " + expectedInterfaces[i] + " but it wasn't found in "
+ fail("Expected declared interface " + expectedInterface + " but it wasn't found in "
+ Arrays.asList(interfaces));
}
}
"(if(true) && set(int BaseApp.i))"
};
- for (int i = 0; i < s.length; i++) {
- check(s[i]);
+ for (String value : s) {
+ check(value);
}
}
}
private void checkMatch(ModifiersPattern p, int[] matches, boolean shouldMatch) {
- for (int i = 0; i < matches.length; i++) {
- boolean result = p.matches(matches[i]);
- String msg = "matches " + p + " to " + Modifier.toString(matches[i]) + " expected ";
+ for (int match : matches) {
+ boolean result = p.matches(match);
+ String msg = "matches " + p + " to " + Modifier.toString(match) + " expected ";
if (shouldMatch) {
assertTrue(msg + shouldMatch, result);
} else {
public void testSerialization() throws IOException {
String[] patterns = new String[] { "", "!public", "public", "public static", "private !static !strictfp", };
- for (int i = 0, len = patterns.length; i < len; i++) {
- checkSerialization(patterns[i]);
+ for (String pattern : patterns) {
+ checkSerialization(pattern);
}
}
* @param b
*/
private void checkMatch(String[] patterns) {
- for (int i = 0, len = patterns.length; i < len; i++) {
- String pattern = patterns[i];
+ for (String pattern : patterns) {
ITokenSource tokenSource = BasicTokenSource.makeTokenSource(
pattern, null);
NamePattern p1 = new PatternParser(tokenSource).parseNamePattern();
* @param b
*/
private void checkMatch(String string, String[] patterns, boolean shouldMatch) {
- for (int i = 0, len = patterns.length; i < len; i++) {
- NamePattern p = new NamePattern(patterns[i]);
+ for (String pattern : patterns) {
+ NamePattern p = new NamePattern(pattern);
checkMatch(string, p, shouldMatch);
}
}
}
private void checkSerialization(String[] patterns) throws IOException {
- for (int i = 0, len = patterns.length; i < len; i++) {
- NamePattern p = new NamePattern(patterns[i]);
+ for (String pattern : patterns) {
+ NamePattern p = new NamePattern(pattern);
checkSerialization(p);
}
}
public void testKindSetOfThis() {
Pointcut p = getPointcut("this(Foo)");
Set matches = Shadow.toSet(p.couldMatchKinds());
- for (Iterator iter = matches.iterator(); iter.hasNext();) {
- Shadow.Kind kind = (Shadow.Kind) iter.next();
+ for (Object o : matches) {
+ Shadow.Kind kind = (Shadow.Kind) o;
assertFalse("No kinds that don't have a this", kind.neverHasThis());
}
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
// + @
p = getPointcut("@this(Foo)");
matches = Shadow.toSet(p.couldMatchKinds());
- for (Iterator iter = matches.iterator(); iter.hasNext();) {
- Shadow.Kind kind = (Shadow.Kind) iter.next();
+ for (Object match : matches) {
+ Shadow.Kind kind = (Shadow.Kind) match;
assertFalse("No kinds that don't have a this", kind.neverHasThis());
}
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
public void testKindSetOfTarget() {
Pointcut p = getPointcut("target(Foo)");
Set matches = Shadow.toSet(p.couldMatchKinds());
- for (Iterator iter = matches.iterator(); iter.hasNext();) {
- Shadow.Kind kind = (Shadow.Kind) iter.next();
+ for (Object o : matches) {
+ Shadow.Kind kind = (Shadow.Kind) o;
assertFalse("No kinds that don't have a target", kind.neverHasTarget());
}
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
// + @
p = getPointcut("@target(Foo)");
matches = Shadow.toSet(p.couldMatchKinds());
- for (Iterator iter = matches.iterator(); iter.hasNext();) {
- Shadow.Kind kind = (Shadow.Kind) iter.next();
+ for (Object match : matches) {
+ Shadow.Kind kind = (Shadow.Kind) match;
assertFalse("No kinds that don't have a target", kind.neverHasTarget());
}
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
public void testKindSetOfWithinCode() {
Pointcut p = getPointcut("withincode(* foo(..))");
Set matches = Shadow.toSet(p.couldMatchKinds());
- for (Iterator iter = matches.iterator(); iter.hasNext();) {
- Shadow.Kind kind = (Shadow.Kind) iter.next();
+ for (Object o : matches) {
+ Shadow.Kind kind = (Shadow.Kind) o;
assertFalse("No kinds that are themselves enclosing",
(kind.isEnclosingKind() && kind != Shadow.ConstructorExecution && kind != Shadow.Initialization));
}
// + @
p = getPointcut("@withincode(Foo)");
matches = Shadow.toSet(p.couldMatchKinds());
- for (Iterator iter = matches.iterator(); iter.hasNext();) {
- Shadow.Kind kind = (Shadow.Kind) iter.next();
+ for (Object match : matches) {
+ Shadow.Kind kind = (Shadow.Kind) match;
assertFalse("No kinds that are themselves enclosing", kind.isEnclosingKind());
}
for (int i = 0; i < Shadow.SHADOW_KINDS.length; i++) {
public void checkMatch(SignaturePattern p, Member[] yes, Member[] no) throws IOException {
p = p.resolveBindings(new TestScope(world, new FormalBinding[0]), new Bindings(0));
- for (int i = 0; i < yes.length; i++) {
- checkMatch(p, yes[i], true);
+ for (Member value : yes) {
+ checkMatch(p, value, true);
}
- for (int i = 0; i < no.length; i++) {
- checkMatch(p, no[i], false);
+ for (Member member : no) {
+ checkMatch(p, member, false);
}
checkSerialization(p);
public void checkMatch(SignaturePattern p, Member[] yes, Member[] no) throws IOException {
p = p.resolveBindings(new TestScope(world, new FormalBinding[0]), new Bindings(0));
- for (int i = 0; i < yes.length; i++) {
- checkMatch(p, yes[i], true);
+ for (Member value : yes) {
+ checkMatch(p, value, true);
}
- for (int i = 0; i < no.length; i++) {
- checkMatch(p, no[i], false);
+ for (Member member : no) {
+ checkMatch(p, member, false);
}
checkSerialization(p);
"(int, .., .., ..)", "(int, .., .., int)", "(int, .., int, ..)", "(int, .., int, int)",
"(int, int, .., ..)", "(int, int, .., int)", "(int, int, int, ..)", "(int, int, int, int)" };
- for (int i = 0, len = patterns.length; i < len; i++) {
- checkSerialization(patterns[i]);
+ for (String pattern : patterns) {
+ checkSerialization(pattern);
}
}
String[] patterns = new String[] { "java.lang.Object", "java.lang.Object+", "java.lang.Integer", "int", "java..*",
"java..util..*", "*.*.Object", "*", };
- for (int i = 0, len = patterns.length; i < len; i++) {
- checkSerialization(patterns[i]);
+ for (String pattern : patterns) {
+ checkSerialization(pattern);
}
}
} catch (ClassNotFoundException e) {
// could be a type variable
TypeVariable[] tVars = classScope.getTypeParameters();
- for (int i = 0; i < tVars.length; i++) {
- if (tVars[i].getName().equals(typeName)) {
- return tVars[i];
+ for (TypeVariable tVar : tVars) {
+ if (tVar.getName().equals(typeName)) {
+ return tVar;
}
}
throw new ClassNotFoundException(typeName);
Thread t = (Thread)e.nextElement();
if (!t.isAlive()) dead_stacks.add(t);
}
- for (Iterator e = dead_stacks.iterator(); e.hasNext(); ) {
- Thread t = (Thread)e.next();
+ for (Object dead_stack : dead_stacks) {
+ Thread t = (Thread) dead_stack;
counters.remove(t);
}
change_count = 0;
}
Class[] superinterfaces = type.getInterfaces();
if (superinterfaces != null) {
- for (int i = 0; i < superinterfaces.length; i++) {
- m = search(superinterfaces[i], name, params, searched);
+ for (Class superinterface : superinterfaces) {
+ m = search(superinterface, name, params, searched);
if (m != null) {
return m;
}
assertEquals(10,ms.length);
//AV was corrupted, cannot rely on ordering
String match = "";
- for (int i = 0; i < ms.length; i++) {
- match = match + "--" + ms[i].getName();
- }
+ for (Method m : ms) {
+ match = match + "--" + m.getName();
+ }
assertTrue(match.indexOf("aMethod") >=0);
}
int numargfiles = 0;
if (argfiles != null) {
- for (Iterator i = argfiles.iterator(); i.hasNext();) {
- String name = i.next()+"";
- File argfile = project.resolveFile(name);
- if (check(argfile, name, false, location)) {
- cmd.createArgument().setValue("-argfile");
- cmd.createArgument().setFile(argfile);
- numargfiles++;
- }
- }
+ for (Object o : argfiles) {
+ String name = o + "";
+ File argfile = project.resolveFile(name);
+ if (check(argfile, name, false, location)) {
+ cmd.createArgument().setValue("-argfile");
+ cmd.createArgument().setFile(argfile);
+ numargfiles++;
+ }
+ }
}
int numfiles = 0;
if (srcdir != null) {
// todo: ignore any srcdir if any argfiles and no explicit includes
String[] dirs = srcdir.list();
- for (int i = 0; i < dirs.length; i++) {
- File dir = project.resolveFile(dirs[i]);
- check(dir, dirs[i], true, location);
- String[] files = getDirectoryScanner(dir).getIncludedFiles();
- for (int j = 0; j < files.length; j++) {
- File file = new File(dir, files[j]);
- if (FileUtil.hasSourceSuffix(file)) {
- cmd.createArgument().setFile(file);
- numfiles++;
- }
- }
- }
+ for (String value : dirs) {
+ File dir = project.resolveFile(value);
+ check(dir, value, true, location);
+ String[] files = getDirectoryScanner(dir).getIncludedFiles();
+ for (String s : files) {
+ File file = new File(dir, s);
+ if (FileUtil.hasSourceSuffix(file)) {
+ cmd.createArgument().setFile(file);
+ numfiles++;
+ }
+ }
+ }
}
if ((null != ignoredOptions) && (ignoredOptions.size() > 0)) {
log("The following attributes were ignored " + ignoredOptions,
public static String render(String[] args) {
if (null == args) return "";
StringBuffer sb = new StringBuffer();
- for (int i = 0; i < args.length; i++) {
- sb.append(args[i]);
- sb.append(" ");
- }
+ for (String arg : args) {
+ sb.append(arg);
+ sb.append(" ");
+ }
return sb.toString();
}
// Otherwise we want to add all .java files to the compileList
else {
- for (int i = 0; i < files.length; i++) {
- File newFile = new File(srcDir, files[i]);
- if (newFile != null &&
- newFile.exists() &&
- newFile.getName().endsWith(".java")) {
- newFiles.add(newFile);
- }
- }
+ for (String file : files) {
+ File newFile = new File(srcDir, file);
+ if (newFile != null &&
+ newFile.exists() &&
+ newFile.getName().endsWith(".java")) {
+ newFiles.add(newFile);
+ }
+ }
}
// Add the new included files
tempAjc.setIncludeantruntime(javac.getIncludeantruntime()); // XXX unsupported
File[] files = javac.getFileList();
if (null != files) {
- for (int i = 0; i < files.length; i++) {
- tempAjc.backdoorSetFile(files[i]);
- }
+ for (File file : files) {
+ tempAjc.backdoorSetFile(file);
+ }
}
ajc = tempAjc;
}
String[] makeCommand() {
ArrayList result = new ArrayList();
if (0 < ignored.size()) {
- for (Iterator iter = ignored.iterator(); iter.hasNext();) {
- logVerbose("ignored: " + iter.next());
- }
+ for (Object o : ignored) {
+ logVerbose("ignored: " + o);
+ }
}
// when copying resources, use temp jar for class output
// then copy temp jar contents and resources to output jar
}
}
if (0 < adapterFiles.size()) {
- for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) {
- File file = (File) iter.next();
- if (file.canRead() && FileUtil.hasSourceSuffix(file)) {
- list.add(file.getAbsolutePath());
- } else {
- this.logger.warning("skipping file: " + file);
- }
- }
+ for (Object adapterFile : adapterFiles) {
+ File file = (File) adapterFile;
+ if (file.canRead() && FileUtil.hasSourceSuffix(file)) {
+ list.add(file.getAbsolutePath());
+ }
+ else {
+ this.logger.warning("skipping file: " + file);
+ }
+ }
}
}
File baseDir = fs.getDir(getProject());
DirectoryScanner ds = fs.getDirectoryScanner(getProject());
String[] files = ds.getIncludedFiles();
- for (int i = 0; i < files.length; i++) {
- sourcefiles.add((new File(baseDir, files[i])).getAbsolutePath());
- }
+ for (String file : files) {
+ sourcefiles.add((new File(baseDir, file)).getAbsolutePath());
+ }
}
}
cmd.createArgument().setValue("-docletpath");
cmd.createArgument().setPath(doclet.path);
}
- for (Iterator i = doclet.params.iterator(); i.hasNext();) {
- Param param = (Param)i.next();
- if (param.name == null) {
- throw new BuildException("Doclet params cannot be null!",
- getLocation());
- }
- cmd.createArgument().setValue(param.name);
- if (param.value == null) {
- cmd.createArgument().setValue(param.value);
- }
- }
+ for (Param param : doclet.params) {
+ if (param.name == null) {
+ throw new BuildException("Doclet params cannot be null!",
+ getLocation());
+ }
+ cmd.createArgument().setValue(param.name);
+ if (param.value == null) {
+ cmd.createArgument().setValue(param.value);
+ }
+ }
}
Map<String,List<String>> groupMap = new HashMap<String,List<String>>();
for (Group group: groups) {
cmd.createArgument().setValue(pkgstr);
}
if (argfiles != null) {
- for (Iterator i = argfiles.iterator(); i.hasNext();) {
- String name = i.next()+"";
- File argfile = getProject().resolveFile(name);
- if (check(argfile, name, false, getLocation())) {
- cmd.createArgument().setValue("-argfile");
- cmd.createArgument().setFile(argfile);
- }
- }
+ for (File file : argfiles) {
+ String name = file + "";
+ File argfile = getProject().resolveFile(name);
+ if (check(argfile, name, false, getLocation())) {
+ cmd.createArgument().setValue("-argfile");
+ cmd.createArgument().setFile(argfile);
+ }
+ }
}
if (packageList != null) {
cmd.createArgument().setValue("@" + packageList);
}
if (null != packagenames) {
- for (Iterator<String> i = packagenames.iterator(); i.hasNext();) {
- cmd.createArgument().setValue((String)i.next());
- }
+ for (String packagename : packagenames) {
+ cmd.createArgument().setValue(packagename);
+ }
}
// support for include parameter as a MatchingTask
int numfiles = 0;
if (sourcepath != null) {
String[] dirs = sourcepath.list();
- for (int i = 0; i < dirs.length; i++) {
- File dir = getProject().resolveFile(dirs[i]);
- check(dir, dirs[i], true, getLocation());
- String[] files = getDirectoryScanner(dir).getIncludedFiles();
- for (int j = 0; j < files.length; j++) {
- File file = new File(dir, files[j]);
- if (file.getName().endsWith(".java")
- || file.getName().endsWith(".aj")) {
- cmd.createArgument().setFile(file);
- numfiles++;
- }
- }
- }
+ for (String value : dirs) {
+ File dir = getProject().resolveFile(value);
+ check(dir, value, true, getLocation());
+ String[] files = getDirectoryScanner(dir).getIncludedFiles();
+ for (String s : files) {
+ File file = new File(dir, s);
+ if (file.getName().endsWith(".java")
+ || file.getName().endsWith(".aj")) {
+ cmd.createArgument().setFile(file);
+ numfiles++;
+ }
+ }
+ }
}
addFileSets();
if (sourcefiles != null) {
- for (Iterator<String> i = sourcefiles.iterator(); i.hasNext();) {
- // let ajdoc resolve sourcefiles relative to sourcepath,
- cmd.createArgument().setValue(i.next());
- }
+ for (String sourcefile : sourcefiles) {
+ // let ajdoc resolve sourcefiles relative to sourcepath,
+ cmd.createArgument().setValue(sourcefile);
+ }
}
// XXX PR682 weak way to report errors - need to refactor
int result = compile();
niceSourceList.append(" to be compiled:");
niceSourceList.append(lSep);
- for (int i=0; i < compileList.length; i++) {
-
- // DefaultCompilerAdapter only expects .java files but we must deal
- // with .lst files also
- File file = compileList[i];
-
- if (file == null) continue;
-
- String arg = file.getAbsolutePath();
- String rest = "";
- String name = file.getName();
-
- // For .java files take the default behavior and add that
- // file to the command line
- if (name.endsWith(".java")) {
- cmd.createArgument().setValue(arg);
- }
- niceSourceList.append(" " + arg + rest + lSep);
- }
+ for (File file : compileList) {
+
+ // DefaultCompilerAdapter only expects .java files but we must deal
+ // with .lst files also
+ if (file == null) continue;
+
+ String arg = file.getAbsolutePath();
+ String rest = "";
+ String name = file.getName();
+
+ // For .java files take the default behavior and add that
+ // file to the command line
+ if (name.endsWith(".java")) {
+ cmd.createArgument().setValue(arg);
+ }
+ niceSourceList.append(" " + arg + rest + lSep);
+ }
attributes.log(niceSourceList.toString(), Project.MSG_VERBOSE);
}
}
}
public void tearDown() {
- for (Iterator iter = tempFiles.iterator(); iter.hasNext();) {
- File file = (File) iter.next();
- FileUtil.deleteContents(file);
- file.delete();
- }
+ for (Object tempFile : tempFiles) {
+ File file = (File) tempFile;
+ FileUtil.deleteContents(file);
+ file.delete();
+ }
}
// public void testCompilerAdapterWithJavac() { // XXX requires tools.jar
}
private void checkContains(String[] cmd, String option, boolean contains) {
- for (int i = 0; i < cmd.length; i++) {
- if (option.equals(cmd[i])) {
- if (contains) {
- return;
- } else {
- assertTrue(
- "not expecting " + option + " in " + Arrays.asList(cmd),
- false);
- }
- }
- }
+ for (String s : cmd) {
+ if (option.equals(s)) {
+ if (contains) {
+ return;
+ } else {
+ assertTrue(
+ "not expecting " + option + " in " + Arrays.asList(cmd),
+ false);
+ }
+ }
+ }
if (contains) {
assertTrue(
"expecting " + option + " in " + Arrays.asList(cmd),
AjcTask task = getTask(NOFILE, null);
String[] cmd = task.makeCommand();
- for (int i = 0; i < cmd.length; i++) {
- assertTrue(!"-d".equals(cmd[i]));
+ for (String s : cmd) {
+ assertTrue(!"-d".equals(s));
}
}
String[] expected = {"copyMe.htm", "pack/includeme",
"pack/Pack.class", "Default.class"};
String[] unexpected = {"doNotCopy", "skipTxtFiles.txt", "pack/something.txt"};
- for (int i = 0; i < expected.length; i++) {
- JarEntry entry = jarFile.getJarEntry(expected[i]);
- assertTrue(expected[i] + " not found", null != entry);
- }
- for (int i = 0; i < unexpected.length; i++) {
- JarEntry entry = jarFile.getJarEntry(unexpected[i]);
- assertTrue(unexpected[i] + " found", null == entry);
- }
+ for (String value : expected) {
+ JarEntry entry = jarFile.getJarEntry(value);
+ assertTrue(value + " not found", null != entry);
+ }
+ for (String s : unexpected) {
+ JarEntry entry = jarFile.getJarEntry(s);
+ assertTrue(s + " found", null == entry);
+ }
}
public void testInpathDirCopyFilterError() {
public void testVersions() {
String[] inputs = AjcTask.TARGET_INPUTS;
- for (int i = 0; i < inputs.length; i++) {
+ for (String value : inputs) {
AjcTask task = getTask(NOFILE);
- task.setTarget(inputs[i]);
+ task.setTarget(value);
String[] cmd = task.makeCommand();
- checkContains(cmd, "-target", true);
- checkContains(cmd, inputs[i], true);
+ checkContains(cmd, "-target", true);
+ checkContains(cmd, value, true);
}
inputs = AjcTask.SOURCE_INPUTS;
- for (int i = 0; i < inputs.length; i++) {
- AjcTask task = getTask(NOFILE);
- task.setSource(inputs[i]);
- String[] cmd = task.makeCommand();
- checkContains(cmd, "-source", true);
- checkContains(cmd, inputs[i], true);
- }
+ for (String s : inputs) {
+ AjcTask task = getTask(NOFILE);
+ task.setSource(s);
+ String[] cmd = task.makeCommand();
+ checkContains(cmd, "-source", true);
+ checkContains(cmd, s, true);
+ }
inputs = AjcTask.COMPLIANCE_INPUTS;
- for (int i = 0; i < inputs.length; i++) {
- AjcTask task = getTask(NOFILE);
- task.setCompliance(inputs[i]);
- String[] cmd = task.makeCommand();
- checkContains(cmd, inputs[i], true);
- }
+ for (String input : inputs) {
+ AjcTask task = getTask(NOFILE);
+ task.setCompliance(input);
+ String[] cmd = task.makeCommand();
+ checkContains(cmd, input, true);
+ }
}
public void testClasspath() {
"reweavable:compress",
"noInline"
};
- for (int i = 0; i < xopts.length; i++) {
+ for (String xopt : xopts) {
AjcTask task = getTask(NOFILE);
- task.setX(xopts[i]);
+ task.setX(xopt);
String[] cmd = task.makeCommand();
- checkContains(cmd,"-X" + xopts[i],true);
+ checkContains(cmd, "-X" + xopt, true);
}
}
public static final String VERBOSE = "-verbose";
@Override
public String[] editCommand(String[] command) {
- for (int i = 0; i < command.length; i++) {
- if (VERBOSE.equals(command[i])) {
+ for (String s : command) {
+ if (VERBOSE.equals(s)) {
return command;
}
}
/** add expected events */
public static void expectEvents(Object[] events) {
if (null != events) {
- for (int i = 0; i < events.length; i++) {
- if (null != events[i]) {
- expectEvent(events[i].toString());
- }
+ for (Object event : events) {
+ if (null != event) {
+ expectEvent(event.toString());
+ }
}
}
}
/** add expected events */
public static void expectEvents(String[] events) {
if (null != events) {
- for (int i = 0; i < events.length; i++) {
- if (null != events[i]) {
- expectEvent(events[i].toString());
- }
- }
+ for (String event : events) {
+ if (null != event) {
+ expectEvent(event.toString());
+ }
+ }
}
}
/** XXX deprecated */
public static void printEvents() { // XXX no clients?
- for (Iterator<String> i = actualEvents.iterator(); i.hasNext(); ) {
- System.out.println(i.next()); // XXX System.out
- }
+ for (String actualEvent : actualEvents) {
+ System.out.println(actualEvent); // XXX System.out
+ }
}
/**
*/
private void doEndSuite(File suiteFile, long elapsed) {
Collection c = features.values();
- for (Iterator iter = c.iterator(); iter.hasNext();) {
- Feature element = (Feature) iter.next();
+ for (Object o : c) {
+ Feature element = (Feature) o;
if (element.listener instanceof TestCompleteListener) {
- ((TestCompleteListener)element.listener).doEndSuite(suiteFile,elapsed);
+ ((TestCompleteListener) element.listener).doEndSuite(suiteFile, elapsed);
}
}
}
if (HarnessJUnitUtil.isEmpty(options)) {
options = new String[][] {new String[0]};
}
- for (int i = 0; i < suites.length; i++) {
- for (int j = 0; j < options.length; j++) {
- Test t = AjctestsAdapter.make(suites[i], options[j]);
- suite.addTest(t);
- }
- }
+ for (String s : suites) {
+ for (String[] option : options) {
+ Test t = AjctestsAdapter.make(s, option);
+ suite.addTest(t);
+ }
+ }
}
return suite;
}
String[] files = new String[] {
SELECT, INCREMENTAL, TITLE_LIST_ONE, TITLE_LIST_PLURAL
};
- for (int i = 0; i < files.length; i++) {
- assertTrue(files[i], new File(files[i]).canRead());
- }
+ for (String file : files) {
+ assertTrue(file, new File(file).canRead());
+ }
}
public void testIncrementalSuite() {
assertTrue(children.length + "!= expRun=" + exp.testsRun,
exp.testsRun == children.length);
int actPass = 0;
- for (int i = 0; i < children.length; i++) {
- if (RunValidator.NORMAL.runPassed(children[i])) {
- actPass++;
- }
+ for (IRunStatus child : children) {
+ if (RunValidator.NORMAL.runPassed(child)) {
+ actPass++;
+ }
}
if (exp.passed != actPass) {
assertTrue("exp.passed=" + exp.passed + " != actPass=" + actPass, false);
// TODO support others loaded dynamically
Map<String,Object> map = new HashMap<>();
- for (Iterator<Object> iter = LIB_RPATHS.keySet().iterator(); iter.hasNext();) {
- String key = (String) iter.next();
+ for (Object o : LIB_RPATHS.keySet()) {
+ String key = (String) o;
String path = LIB_RPATHS.getProperty(key);
File file = null;
URL url = null;
}
StringBuffer path = new StringBuffer();
boolean started = false;
- for (int i = 0; i < entries.length; i++) {
- if (null != entries[i]) {
+ for (Object entry : entries) {
+ if (null != entry) {
if (started) {
path.append(File.pathSeparator);
} else {
started = true;
}
- path.append(entries[i].toString());
+ path.append(entry.toString());
}
}
return path.toString();
}
String[] paths = FileUtil.listFiles(expectedBaseDir);
boolean result = true;
- for (int i = 0; i < paths.length; i++) {
- if (-1 != paths[i].indexOf("CVS")) {
+ for (String path : paths) {
+ if (-1 != path.indexOf("CVS")) {
continue;
}
- if (!sameFiles(handler, expectedBaseDir, actualBaseDir, paths[i]) && result) {
+ if (!sameFiles(handler, expectedBaseDir, actualBaseDir, path) && result) {
result = false;
if (fastFail) {
break;
public void testParseBoolean() {
{
String[] trues = {"true", "TRUE", "on", "ON" };
- for (int i = 0; i < trues.length; i++) {
- assertTrue(trues[i], TestUtil.parseBoolean(trues[i]));
- }
+ for (String aTrue : trues) {
+ assertTrue(aTrue, TestUtil.parseBoolean(aTrue));
+ }
}
{
String[] falses = {"false", "FALSE", "off", "off" };
- for (int i = 0; i < falses.length; i++) {
- assertTrue(falses[i], !TestUtil.parseBoolean(falses[i]));
- }
+ for (String fals : falses) {
+ assertTrue(fals, !TestUtil.parseBoolean(fals));
+ }
}
String[] errors = {"fals", "tru", "T", "on of" };
boolean fail = false;
String str = "";
if (files.size() > 0) {
str += "files:" + "\n";
- for (Iterator<File> i = files.iterator(); i.hasNext();) {
- str += "\t" + i.next() + "\n";
- }
+ for (File file : files) {
+ str += "\t" + file + "\n";
+ }
}
if (argfiles.size() > 0) {
str += "argfiles:" + "\n";
- for (Iterator<File> i = argfiles.iterator(); i.hasNext();) {
- str += "\t" + i.next() + "\n";
- }
+ for (File argfile : argfiles) {
+ str += "\t" + argfile + "\n";
+ }
}
if (args.size() > 0) {
str += "args:" + "\n";
- for (Iterator i = args.iterator(); i.hasNext();) {
- str += "\t" + i.next() + "\n";
- }
+ for (Argument arg : args) {
+ str += "\t" + arg + "\n";
+ }
}
if (testclasses.size() > 0) {
str += "classes:" + "\n";
- for (Iterator i = testclasses.iterator(); i.hasNext();) {
- str += "\t" + i.next() + "\n";
- }
+ for (Run testclass : testclasses) {
+ str += "\t" + testclass + "\n";
+ }
}
return str;
}
File src = getDir(project);
argfiles = new Vector<>();
files = new Vector<>();
- for(Iterator<Argfile> iter = argfileNames.iterator(); iter.hasNext();) {
- String name = iter.next().name;
- File argfile = new File(src, name);
- if (check(argfile, name, location)) argfiles.add(argfile);
- }
+ for (Argfile argfileName : argfileNames) {
+ String name = argfileName.name;
+ File argfile = new File(src, name);
+ if (check(argfile, name, location)) argfiles.add(argfile);
+ }
if (havecludes || argfiles.size() <= 0) {
String[] filenames =
getDirectoryScanner(project).getIncludedFiles();
- for (int j = 0; j < filenames.length; j++) {
- String name = filenames[j];
- if (name.endsWith(".java")) {
- File file = new File(src, name);
- if (check(file, name, location)) files.add(file);
- }
- }
- }
- for (Iterator i = Ajctest.this.testclasses.iterator();
- i.hasNext();) {
- this.testclasses.add((Run)i.next());
- }
+ for (String name : filenames) {
+ if (name.endsWith(".java")) {
+ File file = new File(src, name);
+ if (check(file, name, location)) files.add(file);
+ }
+ }
+ }
+ for (Run run : Ajctest.this.testclasses) {
+ this.testclasses.add(run);
+ }
if (this.classpath == null) {
setClasspath(Ajctest.this.classpath);
}
this.ajdoc = Ajctest.this.ajdoc;
}
if (this.fork) {
- for (Iterator<Run> i = this.testclasses.iterator(); i.hasNext();) {
- i.next().setFork(fork);
- }
+ for (Run testclass : this.testclasses) {
+ testclass.setFork(fork);
+ }
}
if (!this.noclean) {
this.noclean = Ajctest.this.noclean;
private void log(String space, List<?> list, String title) {
if (list == null || list.size() < 1) return;
log(space + title);
- for (Iterator<?> i = list.iterator(); i.hasNext();) {
- log(space + " " + i.next());
- }
+ for (Object o : list) {
+ log(space + " " + o);
+ }
}
private void execute(Testset testset, List<Arg> args) throws BuildException {
if (testset.files.size() > 0) {
log("\tfiles:");
- for (Iterator<File> i = testset.files.iterator(); i.hasNext();) {
- log("\t " + i.next());
- }
+ for (File file : testset.files) {
+ log("\t " + file);
+ }
}
if (testset.argfiles.size() > 0) {
log("\targfiles:");
- for (Iterator<File> i = testset.argfiles.iterator(); i.hasNext();) {
- log("\t " + i.next());
- }
+ for (File file : testset.argfiles) {
+ log("\t " + file);
+ }
}
if (args.size() > 0) {
log("\targs:");
- for (Iterator<Arg> i = args.iterator(); i.hasNext();) {
- log("\t " + i.next());
- }
+ for (Arg arg : args) {
+ log("\t " + arg);
+ }
}
if (testset.testclasses.size() > 0) {
log("\tclasses:");
- for (Iterator<Run> i = testset.testclasses.iterator(); i.hasNext();) {
- log("\t " + i.next());
- }
+ for (Run testclass : testset.testclasses) {
+ log("\t " + testclass);
+ }
}
if (!testset.noclean &&
(!isSet("noclean") && !isSet("nocompile"))) {
}
delete(workingdir);
make(workingdir);
- for (Iterator<String> i = testset.depends.iterator(); i.hasNext();) {
- String target = i.next()+"";
- // todo: capture failures here?
- project.executeTarget(target);
- }
+ for (String depend : testset.depends) {
+ String target = depend + "";
+ // todo: capture failures here?
+ project.executeTarget(target);
+ }
int exit;
if (!isSet("nodoc") && testset.ajdoc != null) {
log("\tdoc... " + testset.ajdoc);
-1, "run");
} else if (!isSet("norun")) {
- for (Iterator<Run> i = testset.testclasses.iterator(); i.hasNext();) {
- Run testclass = i.next();
- log("\ttest..." + testclass.classname());
- if (null != destdir) {
- testclass.setClassesDir(destdir.getAbsolutePath());
- }
- if ((exit = testclass.executeJava()) != 0) {
- post(testset, new Vector(), testclass.msgs, exit, "run");
- } else {
- fire("run.good");
- }
- fire("run.done");
- }
+ for (Run testclass : testset.testclasses) {
+ log("\ttest..." + testclass.classname());
+ if (null != destdir) {
+ testclass.setClassesDir(destdir.getAbsolutePath());
+ }
+ if ((exit = testclass.executeJava()) != 0) {
+ post(testset, new Vector(), testclass.msgs, exit, "run");
+ } else {
+ fire("run.good");
+ }
+ fire("run.done");
+ }
}
log("");
}
private List<List<Arg>> argcombo(List<Argument> arguments) {
List<Argument> combos = new Vector<>();
List<Arg> always = new Vector<>();
- for (Iterator<Argument> iter = arguments.iterator(); iter.hasNext();) {
- Argument arg = iter.next();
- if (arg.values.size() == 0) arg.values.add("");
- if (!arg.always && !arg.values.contains(null)) arg.values.add(null);
- if (arg.values.size() > 0) {
- combos.add(arg);
- } else if (arg.always) {
- always.add(new Arg(arg.name, arg.values.get(0)+"", arg.isj));
- }
- }
+ for (Argument arg : arguments) {
+ if (arg.values.size() == 0) arg.values.add("");
+ if (!arg.always && !arg.values.contains(null)) arg.values.add(null);
+ if (arg.values.size() > 0) {
+ combos.add(arg);
+ } else if (arg.always) {
+ always.add(new Arg(arg.name, arg.values.get(0) + "", arg.isj));
+ }
+ }
List<List<Arg>> argcombo = combinations(combos);
- for (Iterator<Arg> iter = always.iterator(); iter.hasNext();) {
- Arg arg = iter.next();
- for (Iterator<List<Arg>> comboiter = argcombo.iterator(); comboiter.hasNext();) {
- comboiter.next().add(arg);
- }
- }
+ for (Arg arg : always) {
+ for (List<Arg> argList : argcombo) {
+ argList.add(arg);
+ }
+ }
return argcombo;
}
public AjdocWrapper(Testset testset, List args) {
super(testset, ajdocArgs(args), true);
String[] cmds = testset.getAjdoc().getCommandline().getCommandline();
- for (int i = 0; i < cmds.length; i++) {
- this.args.add(cmds[i]);
- }
+ for (String cmd : cmds) {
+ this.args.add(cmd);
+ }
}
String getMainClassName() {
return "org.aspectj.tools.ajdoc.Main";
cp.append(Path.systemClasspath);
}
cmd.createArgument().setPath(cp);
- for (Iterator iter = args.iterator(); iter.hasNext();) {
- Arg arg = (Arg)iter.next();
- if (arg.isj) {
- cmd.createArgument().setValue(arg.name);
- if (!arg.value.equals("")) {
- cmd.createArgument().setValue(arg.value);
- }
- }
- }
+ for (Object item : args) {
+ Arg arg = (Arg) item;
+ if (arg.isj) {
+ cmd.createArgument().setValue(arg.name);
+ if (!arg.value.equals("")) {
+ cmd.createArgument().setValue(arg.value);
+ }
+ }
+ }
cmd.createArgument().setValue(getMainClassName());
boolean alreadySetDestDir = false;
boolean alreadySetClasspath = false;
- for (Iterator iter = args.iterator(); iter.hasNext();) {
- Arg arg = (Arg)iter.next();
- if (!arg.isj) {
- cmd.createArgument().setValue(arg.name);
- if (arg.name.equals("-d")) {
- setDestdir(arg.value+"");
- alreadySetDestDir = true;
- }
- if (arg.name.equals("-classpath")) {
- alreadySetClasspath = true;
- }
- if (!arg.value.equals("")) {
- cmd.createArgument().setValue(arg.value);
- }
- }
- }
+ for (Object o : args) {
+ Arg arg = (Arg) o;
+ if (!arg.isj) {
+ cmd.createArgument().setValue(arg.name);
+ if (arg.name.equals("-d")) {
+ setDestdir(arg.value + "");
+ alreadySetDestDir = true;
+ }
+ if (arg.name.equals("-classpath")) {
+ alreadySetClasspath = true;
+ }
+ if (!arg.value.equals("")) {
+ cmd.createArgument().setValue(arg.value);
+ }
+ }
+ }
if (destdir == null) {
setDestdir(".");
}
cmd.createArgument().setValue("-classpath");
cmd.createArgument().setPath(_cp);
}
- for (Iterator iter = testset.files.iterator(); iter.hasNext();) {
- cmd.createArgument().setFile((File)iter.next());
- }
- for (Iterator iter = testset.argfiles.iterator(); iter.hasNext();) {
- cmd.createArgument().setValue("-argfile");
- cmd.createArgument().setFile((File)iter.next());
- }
+ for (File value : testset.files) {
+ cmd.createArgument().setFile(value);
+ }
+ for (File file : testset.argfiles) {
+ cmd.createArgument().setValue("-argfile");
+ cmd.createArgument().setFile(file);
+ }
return cmd;
}
}
private List<List<Arg>> combinations(List<Argument> arglist) {
List<List<Arg>> result = new Vector<>();
result.add(new Vector<Arg>());
- for (Iterator<Argument> iter = arglist.iterator(); iter.hasNext();) {
- Argument arg = iter.next();
- int N = result.size();
- for (int i = 0; i < N; i++) {
- List<Arg> to = result.remove(0);
- for (Iterator<String> valiter = arg.values.iterator(); valiter.hasNext();) {
- List<Arg> newlist = new Vector<>(to);
- Object val = valiter.next();
- if (val != null) newlist.add(new Arg(arg.name, val+"", arg.isj));
- result.add(newlist);
- }
- }
- }
+ for (Argument arg : arglist) {
+ int N = result.size();
+ for (int i = 0; i < N; i++) {
+ List<Arg> to = result.remove(0);
+ for (String s : arg.values) {
+ List<Arg> newlist = new Vector<>(to);
+ Object val = s;
+ if (val != null) newlist.add(new Arg(arg.name, val + "", arg.isj));
+ result.add(newlist);
+ }
+ }
+ }
return result;
}
Object[] names = new String[] {
"Task", "Type", "Number", "Time"
};
- for (int i = 0; i < names.length; i++) {
- model.addColumn(names[i]);
- }
+ for (Object name : names) {
+ model.addColumn(name);
+ }
table = new TJable(model, failures);
this.add(new JScrollPane(table), BorderLayout.CENTER);
}
"Files",
"Classnames",
};
- for (int i = 0; i < os.length; i++) {
- String name = os[i]+"";
- JLabel label = new JLabel(name+":");
- JTextField comp = new JTextField(25);
- comp.setEditable(false);
- comp.setBackground(Color.white);
- comp.setBorder(BorderFactory.
- createBevelBorder(BevelBorder.LOWERED));
- label.setLabelFor(comp);
- fields.put(name, comp);
- add(label, gbc.forLabel());
- add(comp, gbc.forField());
- }
+ for (Object o : os) {
+ String name = o + "";
+ JLabel label = new JLabel(name + ":");
+ JTextField comp = new JTextField(25);
+ comp.setEditable(false);
+ comp.setBackground(Color.white);
+ comp.setBorder(BorderFactory.
+ createBevelBorder(BevelBorder.LOWERED));
+ label.setLabelFor(comp);
+ fields.put(name, comp);
+ add(label, gbc.forLabel());
+ add(comp, gbc.forField());
+ }
add(new JLabel(), gbc.forLastLabel());
}
}
Map<String,AjcTest> ajTests = wired.getSuiteTests();
- for (Iterator<Map.Entry<String,AjcTest>> iterator = ajTests.entrySet().iterator(); iterator.hasNext();) {
- final Map.Entry<String,AjcTest> entry = iterator.next();
-
- suite.addTest(
- new TestCase(entry.getKey().toString()) {
-
- protected void runTest() {
- entry.getValue().runTest(wired);
- }
-
- public String getName() {
- return entry.getKey();
- }
- }
- );
- }
+ for (final Map.Entry<String, AjcTest> entry : ajTests.entrySet()) {
+ suite.addTest(
+ new TestCase(entry.getKey().toString()) {
+
+ protected void runTest() {
+ entry.getValue().runTest(wired);
+ }
+
+ public String getName() {
+ return entry.getKey();
+ }
+ }
+ );
+ }
} catch (Throwable t) {
final String message = t.toString();
suite.addTest(
// this simple check avoids failure when no test.. method is found.
// it could be refined to lookup in the hierarchy as well, and excluding private method as JUnit does.
Method[] testMethods = testCaseClass.getDeclaredMethods();
- for (int i = 0; i < testMethods.length; i++) {
- Method testMethod = testMethods[i];
- if (testMethod.getName().startsWith("test")) {
- suite.addTestSuite(testCaseClass);
- break;
- }
- }
+ for (Method testMethod : testMethods) {
+ if (testMethod.getName().startsWith("test")) {
+ suite.addTestSuite(testCaseClass);
+ break;
+ }
+ }
TestSetup wrapper = new TestSetup(suite) {
/* (non-Javadoc)
private void collectClassFiles(File inDir, List<File> inList, List<File> toExclude) {
File[] contents = inDir.listFiles();
- for (int i = 0; i < contents.length; i++) {
- if (contents[i].getName().endsWith(".class")) {
- if (!toExclude.contains(contents[i])) {
- inList.add(contents[i]);
+ for (File content : contents) {
+ if (content.getName().endsWith(".class")) {
+ if (!toExclude.contains(content)) {
+ inList.add(content);
}
- } else if (contents[i].isDirectory()) {
- collectClassFiles(contents[i],inList, toExclude);
+ } else if (content.isDirectory()) {
+ collectClassFiles(content, inList, toExclude);
}
}
}
protected Method getMethodStartsWith(JavaClass jc, String prefix, int whichone) {
Method[] meths = jc.getMethods();
- for (int i = 0; i < meths.length; i++) {
- Method method = meths[i];
+ for (Method method : meths) {
System.out.println(method);
if (method.getName().startsWith(prefix)) {
whichone--;
- if (whichone==0) {
+ if (whichone == 0) {
return method;
}
}
public List<LocalVariable> sortedLocalVariables(LocalVariableTable lvt) {
List<LocalVariable> l = new ArrayList<LocalVariable>();
LocalVariable lv[] = lvt.getLocalVariableTable();
- for (int i = 0; i < lv.length; i++) {
- LocalVariable lvEntry = lv[i];
+ for (LocalVariable lvEntry : lv) {
l.add(lvEntry);
}
Collections.sort(l, new MyComparator());
StringBuffer sb = new StringBuffer();
sb.append("LocalVariableTable. Entries=#" + lvt.getTableLength()).append("\n");
LocalVariable lv[] = lvt.getLocalVariableTable();
- for (int i = 0; i < lv.length; i++) {
- LocalVariable lvEntry = lv[i];
+ for (LocalVariable lvEntry : lv) {
sb.append(lvEntry.getSignature()).append(" ").append(lvEntry.getName()).append("(").append(lvEntry.getIndex())
.append(") start=").append(lvEntry.getStartPC()).append(" len=").append(lvEntry.getLength()).append("\n");
}
protected Method getMethodFromClass(JavaClass clazz, String methodName) {
Method[] meths = clazz.getMethods();
- for (int i = 0; i < meths.length; i++) {
- Method method = meths[i];
+ for (Method method : meths) {
if (method.getName().equals(methodName)) {
- return meths[i];
+ return method;
}
}
return null;
try {
out = new FileOutputStream(result);
PrintStream outs = new PrintStream(out, true);
- for (int i = 0; i < args.length; i++) {
- outs.println(args[i]);
+ for (String arg : args) {
+ outs.println(arg);
}
return result;
} catch (IOException e) {
public void addMessages(List messages) {
if (null != messages) {
- for (Iterator iter = messages.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : messages) {
if (o instanceof IMessage) {
addMessage((IMessage) o);
} else {
this.ignoreWarnings = ignoreWarnings;
int fails = 0;
int errors = 0;
- for (Iterator iter = expectedMessagesAsList.iterator();
- iter.hasNext();
- ) {
- IMessage m = (IMessage) iter.next();
+ for (Object o : expectedMessagesAsList) {
+ IMessage m = (IMessage) o;
IMessage.Kind kind = m.getKind();
if (IMessage.FAIL.isSameOrLessThan(kind)) {
fails++;
private boolean expecting(IMessage message) {
boolean match = false;
if (null != message) {
- for (Iterator iter = expectedMessagesAsList.iterator();
- iter.hasNext();
- ) {
+ for (Object o : expectedMessagesAsList) {
// amc - we have to compare against all messages to consume multiple
// text matches on same line. Return true if any matches.
- if (0 == COMP_IMessage.compare(message, iter.next())) {
+ if (0 == COMP_IMessage.compare(message, o)) {
match = true;
}
}
// remove all expected fail+ (COSTLY)
ArrayList<IMessage> list = new ArrayList<>();
int leftToFilter = numExpectedFailed;
- for (int i = 0; i < result.length; i++) {
+ for (IMessage iMessage : result) {
if ((0 == leftToFilter)
- || !IMessage.FAIL.isSameOrLessThan(result[i].getKind())) {
- list.add(result[i]);
+ || !IMessage.FAIL.isSameOrLessThan(iMessage.getKind())) {
+ list.add(iMessage);
} else {
// see if this failure was expected
- if (expectedMessagesHasMatchFor(result[i])) {
+ if (expectedMessagesHasMatchFor(iMessage)) {
leftToFilter--; // ok, don't add
} else {
- list.add(result[i]);
+ list.add(iMessage);
}
}
}
* @return true if actual message is matched in the expected messages
*/
private boolean expectedMessagesHasMatchFor(IMessage actual) {
- for (Iterator iter = expectedMessagesAsList.iterator();
- iter.hasNext();
- ) {
- IMessage expected = (IMessage) iter.next();
+ for (Object o : expectedMessagesAsList) {
+ IMessage expected = (IMessage) o;
if (0 == COMP_IMessage.compare(expected, actual)) {
return true;
}
private void render(// LangUtil instead?
StringBuffer result, String prefix, String suffix, List items) {
if ((null != items)) {
- for (Iterator iter = items.iterator(); iter.hasNext();) {
- result.append(prefix + iter.next() + suffix);
+ for (Object item : items) {
+ result.append(prefix + item + suffix);
}
}
}
StringBuffer sb = new StringBuffer();
sb.append("[");
boolean first = true;
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- Object o = iter.next();
+ for (Object o : list) {
if (!first) {
sb.append(", ");
} else {
runtime.copy(parentRuntime);
String[] globalOptions = runtime.extractOptions(VALID_OPTIONS, true);
- for (int i = 0; i < globalOptions.length; i++) {
- String option = globalOptions[i];
- if (!option.startsWith(OPTION_PREFIX)) {
- throw new Error("only expecting " + OPTION_PREFIX + "..: " + option);
- }
- option = option.substring(OPTION_PREFIX.length());
- boolean keywordMustExist = false;
- List<String> permittedTitles = null;
- List<String> permittedTitleStrings = null;
- String havePr = null;
- if (option.startsWith(REQUIRE_KEYWORDS)) {
- option = option.substring(REQUIRE_KEYWORDS.length());
- keywordMustExist = true;
- } else if (option.startsWith(SKIP_KEYWORDS)) {
- option = option.substring(SKIP_KEYWORDS.length());
- } else if (option.startsWith(TITLE_LIST)) {
- option = option.substring(TITLE_LIST.length());
- permittedTitles = getTitles(option);
- } else if (option.startsWith(TITLE_FAIL_LIST)) {
- option = option.substring(TITLE_FAIL_LIST.length());
- permittedTitles = getTitles(option, true);
- } else if (option.startsWith(TITLE_CONTAINS)) {
- option = option.substring(TITLE_CONTAINS.length());
- permittedTitleStrings = getTitles(option);
- } else if (option.startsWith(PICK_PR)) {
- if (0 == bugId) {
- skipMessage(handler, "bugId required, but no bugId for this test");
- return false;
- } else {
- havePr = "" + bugId;
- }
- option = option.substring(PICK_PR.length());
- } else {
- throw new Error("unrecognized suffix: " + globalOptions[i]
- + " (expecting: " + OPTION_PREFIX + VALID_SUFFIXES + "...)");
- }
- if (null != permittedTitleStrings) {
- boolean gotHit = false;
- for (Iterator<String> iter = permittedTitleStrings.iterator();
- !gotHit && iter.hasNext();
- ) {
- String substring = (String) iter.next();
- if (-1 != this.description.indexOf(substring)) {
- gotHit = true;
- }
- }
- if (!gotHit) {
- String reason = "title "
- + this.description
- + " does not contain any of "
- + option;
- skipMessage(handler, reason);
- return false;
- }
- } else if (null != permittedTitles) {
- if (!permittedTitles.contains(this.description)) {
- String reason = "titlesList "
- + option
- + " did not contain "
- + this.description;
- skipMessage(handler, reason);
- return false;
- }
- } else {
- // all other options handled as comma-delimited lists
- List<String> specs = LangUtil.commaSplit(option);
- // XXX also throw Error on empty specs...
- for (Iterator<String> iter = specs.iterator(); iter.hasNext();) {
- String spec = (String) iter.next();
- if (null != havePr) {
- if (havePr.equals(spec)) { // String.equals()
- havePr = null;
- }
- } else if (keywordMustExist != keywords.contains(spec)) {
- String reason = "keyword " + spec
- + " was " + (keywordMustExist ? "not found" : "found");
- skipMessage(handler, reason);
- return false;
- }
- }
- if (null != havePr) {
- skipMessage(handler, "bugId required, but not matched for this test");
- return false;
- }
- }
- }
+ for (String globalOption : globalOptions) {
+ String option = globalOption;
+ if (!option.startsWith(OPTION_PREFIX)) {
+ throw new Error("only expecting " + OPTION_PREFIX + "..: " + option);
+ }
+ option = option.substring(OPTION_PREFIX.length());
+ boolean keywordMustExist = false;
+ List<String> permittedTitles = null;
+ List<String> permittedTitleStrings = null;
+ String havePr = null;
+ if (option.startsWith(REQUIRE_KEYWORDS)) {
+ option = option.substring(REQUIRE_KEYWORDS.length());
+ keywordMustExist = true;
+ } else if (option.startsWith(SKIP_KEYWORDS)) {
+ option = option.substring(SKIP_KEYWORDS.length());
+ } else if (option.startsWith(TITLE_LIST)) {
+ option = option.substring(TITLE_LIST.length());
+ permittedTitles = getTitles(option);
+ } else if (option.startsWith(TITLE_FAIL_LIST)) {
+ option = option.substring(TITLE_FAIL_LIST.length());
+ permittedTitles = getTitles(option, true);
+ } else if (option.startsWith(TITLE_CONTAINS)) {
+ option = option.substring(TITLE_CONTAINS.length());
+ permittedTitleStrings = getTitles(option);
+ } else if (option.startsWith(PICK_PR)) {
+ if (0 == bugId) {
+ skipMessage(handler, "bugId required, but no bugId for this test");
+ return false;
+ } else {
+ havePr = "" + bugId;
+ }
+ option = option.substring(PICK_PR.length());
+ } else {
+ throw new Error("unrecognized suffix: " + globalOption
+ + " (expecting: " + OPTION_PREFIX + VALID_SUFFIXES + "...)");
+ }
+ if (null != permittedTitleStrings) {
+ boolean gotHit = false;
+ for (Iterator<String> iter = permittedTitleStrings.iterator();
+ !gotHit && iter.hasNext();
+ ) {
+ String substring = (String) iter.next();
+ if (-1 != this.description.indexOf(substring)) {
+ gotHit = true;
+ }
+ }
+ if (!gotHit) {
+ String reason = "title "
+ + this.description
+ + " does not contain any of "
+ + option;
+ skipMessage(handler, reason);
+ return false;
+ }
+ } else if (null != permittedTitles) {
+ if (!permittedTitles.contains(this.description)) {
+ String reason = "titlesList "
+ + option
+ + " did not contain "
+ + this.description;
+ skipMessage(handler, reason);
+ return false;
+ }
+ } else {
+ // all other options handled as comma-delimited lists
+ List<String> specs = LangUtil.commaSplit(option);
+ // XXX also throw Error on empty specs...
+ for (String spec : specs) {
+ if (null != havePr) {
+ if (havePr.equals(spec)) { // String.equals()
+ havePr = null;
+ }
+ } else if (keywordMustExist != keywords.contains(spec)) {
+ String reason = "keyword " + spec
+ + " was " + (keywordMustExist ? "not found" : "found");
+ skipMessage(handler, reason);
+ return false;
+ }
+ }
+ if (null != havePr) {
+ skipMessage(handler, "bugId required, but not matched for this test");
+ return false;
+ }
+ }
+ }
return true;
}
return new String[0];
}
ArrayList result = new ArrayList();
- for (int i = 0; i < inputs.length; i++) {
- String input = inputs[i];
- if (null == input) {
- continue;
- }
- File inputFile = new File(baseDir, input);
- if (inputFile.canRead() && inputFile.isDirectory()) {
- result.add(input);
- }
- }
+ for (String input : inputs) {
+ if (null == input) {
+ continue;
+ }
+ File inputFile = new File(baseDir, input);
+ if (inputFile.canRead() && inputFile.isDirectory()) {
+ result.add(input);
+ }
+ }
return (String[]) result.toArray(new String[0]);
}
suffixes = temp;
}
ArrayList result = new ArrayList();
- for (int i = 0; i < inputs.length; i++) {
- String input = inputs[i];
- if (null == input) {
- continue;
- }
- if (!ignoreCase) {
- input = input.toLowerCase();
- }
- for (int j = 0; j < suffixes.length; j++) {
- String suffix = suffixes[j];
- if (null == suffix) {
- continue;
- }
- if (input.endsWith(suffix)) {
- result.add(input);
- break;
- }
- }
- }
+ for (String s : inputs) {
+ String input = s;
+ if (null == input) {
+ continue;
+ }
+ if (!ignoreCase) {
+ input = input.toLowerCase();
+ }
+ for (String suffix : suffixes) {
+ if (null == suffix) {
+ continue;
+ }
+ if (input.endsWith(suffix)) {
+ result.add(input);
+ break;
+ }
+ }
+ }
return (String[]) result.toArray(new String[0]);
}
return (first != last);
}
};
- for (int i = 0; i < sourcerootFiles.length; i++) {
- FileUtil.deleteContents(
- sourcerootFiles[i],
- pickIncFiles,
- false);
- }
+ for (File sourcerootFile : sourcerootFiles) {
+ FileUtil.deleteContents(
+ sourcerootFile,
+ pickIncFiles,
+ false);
+ }
if (0 < sourcerootFiles.length) {
FileUtil.sleepPastFinalModifiedTime(
sourcerootFiles);
}
if (!LangUtil.isEmpty(argFiles)) {
String[] ra = FileUtil.getPaths(argFiles);
- for (int j = 0; j < ra.length; j++) {
- arguments.add("@" + ra[j]);
- }
+ for (String s : ra) {
+ arguments.add("@" + s);
+ }
if (!spec.badInput && spec.isStaging) {
validator.fail(
"warning: files listed in argfiles not staged");
false,
slop);
if (!LangUtil.isEmpty(found)) {
- for (Iterator iter = found.iterator();
- iter.hasNext();
- ) {
- MessageUtil.info(
- status,
- Spec.SEEK_MESSAGE_PREFIX + iter.next());
- }
+ for (Object o : found) {
+ MessageUtil.info(
+ status,
+ Spec.SEEK_MESSAGE_PREFIX + o);
+ }
}
}
ICommand compiler = spec.reuseCompiler
boolean hasInvalidOptions(Values values, TestSetup result) {
// not supporting 1.0 options any more
- for (Iterator iter = CRSOPTIONS.invalidOptions.iterator();
- iter.hasNext();
- ) {
- Option option = (Option) iter.next();
- if (null != values.firstOption(option)) {
- result.failureReason =
- "invalid option in harness: " + option;
- return true;
- }
- }
+ for (Object o : CRSOPTIONS.invalidOptions) {
+ Option option = (Option) o;
+ if (null != values.firstOption(option)) {
+ result.failureReason =
+ "invalid option in harness: " + option;
+ return true;
+ }
+ }
return false;
}
return true;
}
// not supporting 1.0 options any more
- for (Iterator iter = CRSOPTIONS.ajc10Options.iterator();
- iter.hasNext();
- ) {
- Option option = (Option) iter.next();
- if (null != values.firstOption(option)) {
- result.failureReason = "old ajc 1.0 option: " + option;
- return true;
- }
- }
+ for (Object o : CRSOPTIONS.ajc10Options) {
+ Option option = (Option) o;
+ if (null != values.firstOption(option)) {
+ result.failureReason = "old ajc 1.0 option: " + option;
+ return true;
+ }
+ }
return false;
}
};
// among options not permitted: extdirs...
-
- for (int i = 0; i < options.length; i++) {
- crsOptions.addOption(options[i]);
- }
- for (Iterator iter = compilerOptions.iterator();
- iter.hasNext();
- ) {
- crsOptions.addOption((Option) iter.next());
- }
+
+ for (Option option : options) {
+ crsOptions.addOption(option);
+ }
+ for (Object compilerOption : compilerOptions) {
+ crsOptions.addOption((Option) compilerOption);
+ }
// these are recognized but records with them are skipped
- for (Iterator iter = ajc10Options.iterator();
- iter.hasNext();
- ) {
- crsOptions.addOption((Option) iter.next());
- }
+ for (Object ajc10Option : ajc10Options) {
+ crsOptions.addOption((Option) ajc10Option);
+ }
crsOptions.freeze();
}
Set options = crsOptions.compilerOptions();
assertTrue(null != options);
StringBuffer notLoaded = new StringBuffer();
- for (Iterator iter = options.iterator(); iter.hasNext();) {
- Option compilerOption = (Option) iter.next();
- if (!(crsOptions.compilerIsLoadable(compilerOption))) {
- notLoaded.append(" " + compilerOption);
- } else {
- String className = crsOptions.compilerClassName(compilerOption);
- String argValue = compilerOption.toString(); // XXX snoop
- String arg = Option.ON.render(argValue);
- checkCompilerOption(arg, className);
- }
- }
+ for (Object option : options) {
+ Option compilerOption = (Option) option;
+ if (!(crsOptions.compilerIsLoadable(compilerOption))) {
+ notLoaded.append(" " + compilerOption);
+ } else {
+ String className = crsOptions.compilerClassName(compilerOption);
+ String argValue = compilerOption.toString(); // XXX snoop
+ String arg = Option.ON.render(argValue);
+ checkCompilerOption(arg, className);
+ }
+ }
if (0 < notLoaded.length()) {
System.err.println(
getClass().getName()
new String[] { "-verbose", "-g:vars,source" },
};
// normal
- for (int i = 0; i < input.length; i++) {
- optionChecker.checkOptions(input[i], input[i]);
- }
- for (int i = 0; i < literalInput.length; i++) {
- optionChecker.checkOptions(literalInput[i], literalInput[i]);
- }
+ for (String[] value : input) {
+ optionChecker.checkOptions(value, value);
+ }
+ for (String[] strings : literalInput) {
+ optionChecker.checkOptions(strings, strings);
+ }
// force-on
String[][] forceInput = duplicate(input, "!");
for (int i = 0; i < input.length; i++) {
// final File expDir = ((!doCompare || (null == spec.expDir))
// ? null
// : new File(baseDir, spec.expDir));
- for (Iterator iter = pathList.iterator(); iter.hasNext();) {
- final String entry = (String) iter.next() ;
- String path = entry ;
- if (null != spec.defaultSuffix) {
- if (".class".equals(spec.defaultSuffix)) {
- path = path.replace('.', '/');
- }
- path = path + spec.defaultSuffix;
- }
- File actualFile = new File(baseDir, path);
- if (exists != (actualFile.canRead() && actualFile.isFile()
- && (expectStartEarlier
- ? startTime <= actualFile.lastModified()
- : startTime > actualFile.lastModified()
- ))) {
- failMessage(handler, exists, label, path, actualFile);
- if (result) {
- result = false;
- }
- } else if (exists && doCompare && (null != fileChecker)) {
- if (!fileChecker.checkFile(handler, path, actualFile) && result) {
- result = false;
- }
- }
- }
+ for (Object o : pathList) {
+ final String entry = (String) o;
+ String path = entry;
+ if (null != spec.defaultSuffix) {
+ if (".class".equals(spec.defaultSuffix)) {
+ path = path.replace('.', '/');
+ }
+ path = path + spec.defaultSuffix;
+ }
+ File actualFile = new File(baseDir, path);
+ if (exists != (actualFile.canRead() && actualFile.isFile()
+ && (expectStartEarlier
+ ? startTime <= actualFile.lastModified()
+ : startTime > actualFile.lastModified()
+ ))) {
+ failMessage(handler, exists, label, path, actualFile);
+ if (result) {
+ result = false;
+ }
+ } else if (exists && doCompare && (null != fileChecker)) {
+ if (!fileChecker.checkFile(handler, path, actualFile) && result) {
+ result = false;
+ }
+ }
+ }
}
return result;
}
return;
}
LangUtil.throwIaxIfNull(out, "out");
- for (Iterator<DirChanges.Spec> iter = dirChanges.iterator(); iter.hasNext();) {
- DirChanges.Spec spec = iter.next();
+ for (Spec spec : dirChanges) {
if (null == spec) {
- continue;
- }
- spec.writeXml(out);
+ continue;
+ }
+ spec.writeXml(out);
}
}
if (null != items) {
String[] classes = XMLWriter.unflattenList(items);
if (!LangUtil.isEmpty(classes)) {
- for (int i = 0; i < classes.length; i++) {
- if (!LangUtil.isEmpty(classes[i])) {
- list.add(classes[i]);
- }
- }
+ for (String aClass : classes) {
+ if (!LangUtil.isEmpty(aClass)) {
+ list.add(aClass);
+ }
+ }
}
}
}
Sandbox sandbox = new Sandbox(new File("testdata"), validator);
IRunListener listenerNULL = null;
ISourceLocation sl = new SourceLocation(suiteFile, 0, 0,0);
- for (Iterator iter = tests.iterator(); iter.hasNext();) {
- status = new RunStatus(handler, runner);
- AjcTest.Spec test = (AjcTest.Spec) iter.next();
- test.setSourceLocation(sl);
+ for (Object o : tests) {
+ status = new RunStatus(handler, runner);
+ AjcTest.Spec test = (AjcTest.Spec) o;
+ test.setSourceLocation(sl);
IRunIterator child = test.makeRunIterator(sandbox, validator);
- //test.setup(new String[0], validator); // XXX
+ //test.setup(new String[0], validator); // XXX
//IRun child = runner.wrap(test, null);
- // huh? runIterator not generating child status?
- //RunStatus childStatus = runner.makeChildStatus();
- runner.runIterator(child, status, listenerNULL);
- MessageUtil.print(System.err, status);
+ // huh? runIterator not generating child status?
+ //RunStatus childStatus = runner.makeChildStatus();
+ runner.runIterator(child, status, listenerNULL);
+ MessageUtil.print(System.err, status);
}
}
ArrayList result = new ArrayList();
NamesFilter filter = new NamesFilter(names);
File[] bases = { testBaseDir, sandboxDir };
- for (int i = 0; i < bases.length; i++) {
- File base = bases[i];
- if ((null == base) || !base.canRead()) {
- continue;
- }
- result.addAll(Arrays.asList(FileUtil.listFiles(base, filter)));
- }
+ for (File base : bases) {
+ if ((null == base) || !base.canRead()) {
+ continue;
+ }
+ result.addAll(Arrays.asList(FileUtil.listFiles(base, filter)));
+ }
return (File[]) result.toArray(new File[0]);
}
File getTestBaseSrcDir(JavaRun caller) {
assertState(null != compileClasspath, "classpath not set");
ArrayList result = new ArrayList();
File[] src = compileClasspath;
- for (int i = 0; i < src.length; i++) {
- File f = src[i];
- if ((null != f) && (f.isDirectory()) && (!readable || f.canRead())) {
- result.add(f);
- }
+ for (File f : src) {
+ if ((null != f) && (f.isDirectory()) && (!readable || f.canRead())) {
+ result.add(f);
+ }
}
if (includeOutput && (null != classesDir)
&& (!readable || classesDir.canRead())) {
assertState(null != compileClasspath, "classpath not set");
ArrayList result = new ArrayList();
File[][] src = new File[][] { compileClasspath, aspectpath };
- for (int i = 0; i < src.length; i++) {
- File[] paths = src[i];
- int len = (null == paths ? 0 : paths.length);
- for (int j = 0; j < len; j++) {
- File f = paths[j];
- if (FileUtil.isZipFile(f) && (!readable || f.canRead())) {
- result.add(f);
- }
+ for (File[] paths : src) {
+ int len = (null == paths ? 0 : paths.length);
+ for (int j = 0; j < len; j++) {
+ File f = paths[j];
+ if (FileUtil.isZipFile(f) && (!readable || f.canRead())) {
+ result.add(f);
+ }
}
- }
+ }
return (File[]) result.toArray(new File[0]);
}
if (null != file) {
String name = file.getName();
if ((null != name) && (null != names)) {
- for (int i = 0; i < names.length; i++) {
- if (name.equals(names[i])) {
- return true;
- }
- }
+ for (String s : names) {
+ if (name.equals(s)) {
+ return true;
+ }
+ }
}
}
return false;
public boolean nullcheck(Collection list, String message) {
if (nullcheck((Object) list, message + " list")) {
int i = 0;
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- if (!nullcheck(iter.next(), message + "[" + i++ + "]")) {
+ for (Object o : list) {
+ if (!nullcheck(o, message + "[" + i++ + "]")) {
return false;
}
}
public boolean canReadFiles(Collection dirs, String message) {
if (nullcheck((Object) dirs, message + " files")) {
int i = 0;
- for (Iterator iter = dirs.iterator(); iter.hasNext();) {
- Object o = iter.next();
- if (! (o instanceof File)) {
+ for (Object o : dirs) {
+ if (!(o instanceof File)) {
fail(i + ": not a file " + o);
}
if (!canRead((File) o, message + "[" + i++ + "]")) {
public boolean canReadDirs(Collection dirs, String message) {
if (nullcheck((Object) dirs, message + " dirs")) {
int i = 0;
- for (Iterator iter = dirs.iterator(); iter.hasNext();) {
- Object o = iter.next();
- if (! (o instanceof File)) {
+ for (Object o : dirs) {
+ if (!(o instanceof File)) {
fail(i + ": not a file " + o);
}
if (!canReadDir((File) o, message + "[" + i++ + "]")) {
public boolean canWriteFiles(Collection dirs, String message) {
if (nullcheck((Object) dirs, message + " files")) {
int i = 0;
- for (Iterator iter = dirs.iterator(); iter.hasNext();) {
- Object o = iter.next();
- if (! (o instanceof File)) {
+ for (Object o : dirs) {
+ if (!(o instanceof File)) {
fail(i + ": not a file " + o);
}
if (!canWrite((File) o, message + "[" + i++ + "]")) {
public boolean canWriteDirs(Collection dirs, String message) {
if (nullcheck((Object) dirs, message + " dirs")) {
int i = 0;
- for (Iterator iter = dirs.iterator(); iter.hasNext();) {
- Object o = iter.next();
- if (! (o instanceof File)) {
+ for (Object o : dirs) {
+ if (!(o instanceof File)) {
fail(i + ": not a file " + o);
}
if (!canWriteDir((File) o, message + "[" + i++ + "]")) {
}
if (includeChildren) {
IRunStatus[] kids = getChildren();
- for (int i = 0; i < kids.length; i++) {
- if (kids[i].hasAnyMessage(kind, orGreater, true)) {
+ for (IRunStatus kid : kids) {
+ if (kid.hasAnyMessage(kind, orGreater, true)) {
return true;
}
}
}
IRunStatus[] kids = getChildren();
- for (int i = 0; i < kids.length; i++) {
- result = kids[i].getMessages(kind, orGreater, includeChildren);
+ for (IRunStatus kid : kids) {
+ result = kid.getMessages(kind, orGreater, includeChildren);
if (!LangUtil.isEmpty(result)) {
sink.addAll(Arrays.asList(result));
}
if ((null != children) && (0 < children.size())) {
String label = "### --------- " + name;
int index = 0;
- for (Iterator iter = children.iterator(); iter.hasNext();) {
- IRunStatus childStatus = (IRunStatus) iter.next();
+ for (Object child : children) {
+ IRunStatus childStatus = (IRunStatus) child;
String childLabel = "\n" + label + " child[" + index++ + "] " + childStatus.getIdentifier();
sb.append(childLabel + " ---- start\n");
sb.append(childStatus.toString());
final int numTests = numIncomplete + numChildren + numSkips;
int numFails = 0;
if (!LangUtil.isEmpty(children)) {
- for (int i = 0; i < children.length; i++) {
- if (!RunValidator.NORMAL.runPassed(children[i])) {
- numFails++;
- }
+ for (IRunStatus child : children) {
+ if (!RunValidator.NORMAL.runPassed(child)) {
+ numFails++;
+ }
}
}
final int numPass = children.length - numFails;
Collections.sort(sink, MESSAGE_LINEKIND);
return sink;
}
- for (int i = 0; i < source.length; i++) {
- IMessage message = source[i];
+ for (IMessage message : source) {
IMessage.Kind mkind = message.getKind();
boolean skipping = false;
for (int j = 0; !skipping && (j < skip.length); j++) {
LangUtil.throwIaxIfNull(handler, "handler");
LangUtil.throwIaxIfNull(kind, "kind");
if (different) {
- for (Iterator iter = missing.iterator(); iter.hasNext();) {
- String s = MessageUtil.renderMessage((IMessage) iter.next());
+ for (Object value : missing) {
+ String s = MessageUtil.renderMessage((IMessage) value);
MessageUtil.fail(handler, "missing " + label + ": " + s);
}
- for (Iterator iter = unexpected.iterator(); iter.hasNext();) {
- String s = MessageUtil.renderMessage((IMessage) iter.next());
+ for (Object o : unexpected) {
+ String s = MessageUtil.renderMessage((IMessage) o);
MessageUtil.fail(handler, "unexpected " + label + ": " + s);
}
}
// normalize sources to ignore
final ArrayList expected = (!checkExpected ? null : new ArrayList());
if (checkExpected) {
- for (int i = 0; i < expectedPaths.length; i++) {
- String srcPath = expectedPaths[i];
- if (!LangUtil.isEmpty(srcPath)) {
- expected.add(org.aspectj.util.FileUtil.weakNormalize(srcPath));
- }
- }
+ for (String srcPath : expectedPaths) {
+ if (!LangUtil.isEmpty(srcPath)) {
+ expected.add(org.aspectj.util.FileUtil.weakNormalize(srcPath));
+ }
+ }
}
// gather, normalize paths changed
return false;
}
} else {
- for (Iterator iter = expected.iterator();
- iter.hasNext();
- ) {
- String exp = (String) iter.next();
- if (path.startsWith(exp)) {
- String suffix = path.substring(exp.length());
- if (-1 == suffix.indexOf("/")) { // normalized...
- expected.remove(path);
- // found - do not add to unexpected
- return false;
- }
- }
+ for (Object o : expected) {
+ String exp = (String) o;
+ if (path.startsWith(exp)) {
+ String suffix = path.substring(exp.length());
+ if (-1 == suffix.indexOf("/")) { // normalized...
+ expected.remove(path);
+ // found - do not add to unexpected
+ return false;
+ }
+ }
}
}
}
// go through files first
File[] files = file.listFiles(ValidFileFilter.FILE_EXISTS);
if (null != files) {
- for (int i = 0; i < files.length; i++) {
- if (!fileFilter.accept(files[i])) {
- return false;
- }
- }
+ for (File value : files) {
+ if (!fileFilter.accept(value)) {
+ return false;
+ }
+ }
}
// now recurse to handle directories
File[] dirs = file.listFiles(ValidFileFilter.DIR_EXISTS);
if (null != dirs) {
- for (int i = 0; i < dirs.length; i++) {
- if (userRecursion) {
- if (!fileFilter.accept(dirs[i])) {
- return false;
- }
- } else {
- if (!descendFileTree(dirs[i], fileFilter,userRecursion)) {
- return false;
- }
- }
- }
+ for (File dir : dirs) {
+ if (userRecursion) {
+ if (!fileFilter.accept(dir)) {
+ return false;
+ }
+ } else {
+ if (!descendFileTree(dir, fileFilter, userRecursion)) {
+ return false;
+ }
+ }
+ }
}
} // readable directory (ignore unreadable ones)
return true;
twoList.addAll(org.aspectj.util.LangUtil.arrayAsList(two));
ArrayList result = new ArrayList();
if (null != one) {
- for (int i = 0; i < one.length; i++) {
- if (null != one[i]) {
- twoList.remove(one[i]);
- result.add(one[i]);
- }
- }
+ for (String s : one) {
+ if (null != s) {
+ twoList.remove(s);
+ result.add(s);
+ }
+ }
}
- for (Iterator iterator = twoList.iterator(); iterator.hasNext(); ) {
- String element = (String) iterator.next();
+ for (Object o : twoList) {
+ String element = (String) o;
if (null != element) {
- result.add(element);
- }
+ result.add(element);
+ }
}
return (String[]) result.toArray(NONE);
}
public static Properties combine(Properties dest, Properties add, boolean respectExisting) { // XXX
if (null == add) return dest;
if (null == dest) return add;
- for (Iterator iterator = add.keySet().iterator(); iterator.hasNext(); ) {
- String key = (String) iterator.next();
- if (null == key) {
- continue;
- }
- String value = add.getProperty(key);
- if (null == value) {
- continue;
- }
- if (! respectExisting || (null == dest.getProperty(key))) {
- dest.setProperty(key, value);
- }
- }
+ for (Object o : add.keySet()) {
+ String key = (String) o;
+ if (null == key) {
+ continue;
+ }
+ String value = add.getProperty(key);
+ if (null == value) {
+ continue;
+ }
+ if (!respectExisting || (null == dest.getProperty(key))) {
+ dest.setProperty(key, value);
+ }
+ }
return dest;
}
public static void loadClasses(String[] args, StringBuffer out,
StringBuffer err) {
if (null != args) {
- for (int i = 0; i < args.length; i++) {
- try {
- Class c = Class.forName(args[i]);
- if (null != out) {
- out.append("\n");
- out.append(args[i]);
- out.append(": ");
- out.append(c.getName());
- }
- } catch (Throwable t) {
- if (null != err) {
- err.append("\n");
- FileUtil.render(t, err);
- }
- }
- }
+ for (String arg : args) {
+ try {
+ Class c = Class.forName(arg);
+ if (null != out) {
+ out.append("\n");
+ out.append(arg);
+ out.append(": ");
+ out.append(c.getName());
+ }
+ } catch (Throwable t) {
+ if (null != err) {
+ err.append("\n");
+ FileUtil.render(t, err);
+ }
+ }
+ }
}
}
}
int length = path.length() - ".class".length();
path = path.substring(prefix.length()+1, length);
- for (int i = 0; i < SEPS.length; i++) {
- path = path.replace(SEPS[i], '.');
- }
+ for (char sep : SEPS) {
+ path = path.replace(sep, '.');
+ }
return path;
}
public static void main (String[] args) { // todo remove as testing
StringBuffer err = new StringBuffer();
StringBuffer out = new StringBuffer();
- for (int i = 0; i < args.length; i++) {
- String[] names = classesIn(new File(args[i]));
- System.err.println(args[i] + " -> " + render(names));
- loadClasses(names, out, err);
- }
+ for (String arg : args) {
+ String[] names = classesIn(new File(arg));
+ System.err.println(arg + " -> " + render(names));
+ loadClasses(names, out, err);
+ }
if (0 < err.length()) {
System.err.println(err.toString());
}
return;
}
BitSet actualExpected = new BitSet();
- for (int i = 0; i < expectedListIn.size(); i++) {
- Object expect = expectedListIn.get(i);
+ for (Object expect : expectedListIn) {
int loc = actualListIn.indexOf(expect);
if (-1 == loc) {
if (null != missingListOut) {
// messages on the same line, but with different text content.
while (actualIter.hasNext()) {
act = actualIter.next();
- for (Iterator expectedIter = expected.iterator(); expectedIter.hasNext();) {
- Object exp = expectedIter.next();
- // if actual matches expected remove actual from extraListOut, and
- // remove expected from missingListOut
- int diff = comparator.compare(exp,act);
- if (diff == 0) {
- extraListOut.remove(act);
- missingListOut.remove(exp);
- } else if (diff > 0) {
- // since list is sorted, there can be no more matches...
- break;
- }
- }
+ for (Object exp : expected) {
+ // if actual matches expected remove actual from extraListOut, and
+ // remove expected from missingListOut
+ int diff = comparator.compare(exp, act);
+ if (diff == 0) {
+ extraListOut.remove(act);
+ missingListOut.remove(exp);
+ } else if (diff > 0) {
+ // since list is sorted, there can be no more matches...
+ break;
+ }
+ }
}
// while (((null != act) || actualIter.hasNext())
, new FTest("[1,2]", new String[] {"1,2"}, LIST)
, new FTest("[1, 2, 3]", new String[] {"1","2","3"}, LIST)
};
- for (int i = 0; i < tests.length; i++) {
- checkUnflatten(tests[i]);
+ for (FTest test : tests) {
+ checkUnflatten(test);
}
}
if (result == null)
return null;
result = result.trim();
- for (int i = 0; i < eolComments.length; i++) {
- int loc = result.indexOf(eolComments[i]);
- if (-1 != loc) {
- result = result.substring(0, loc);
- break;
- }
- }
+ for (String eolComment : eolComments) {
+ int loc = result.indexOf(eolComment);
+ if (-1 != loc) {
+ result = result.substring(0, loc);
+ break;
+ }
+ }
len = result.length();
if (0 < len) {
- for (int i = 0; i < leadComments.length; i++) {
- if (result.startsWith(leadComments[i])) {
- result = "";
- break;
- }
- }
+ for (String leadComment : leadComments) {
+ if (result.startsWith(leadComment)) {
+ result = "";
+ break;
+ }
+ }
len = result.length();
}
len = result.length();
messages.checkingLinks(linksToCheck.size());
list.clear();
list.addAll(linksToCheck);
- for (Iterator<Link> iter = list.iterator(); iter.hasNext();) {
- final Link link = iter.next();
- String urlString = link.url.toString();
- if (!checkedUrls.contains(urlString)) {
- checkedUrls.add(urlString);
- messages.checkingLink(link);
- checkLink(link);
- }
- }
+ for (final Link link : list) {
+ String urlString = link.url.toString();
+ if (!checkedUrls.contains(urlString)) {
+ checkedUrls.add(urlString);
+ messages.checkingLink(link);
+ checkLink(link);
+ }
+ }
linksToCheck.removeAll(list);
}
// now check that all named references are accounted for
- for (Iterator<String> iter = refsToCheck.iterator(); iter.hasNext();) {
- String ref = iter.next();
- if (!validRefs.contains(ref)) {
- messages.namedReferenceNotFound(ref);
- }
- }
+ for (String ref : refsToCheck) {
+ if (!validRefs.contains(ref)) {
+ messages.namedReferenceNotFound(ref);
+ }
+ }
}
/** @return null if link known or if unable to create */
MessageHandler getSampleMessages() {
MessageHandler result = new MessageHandler();
- for (Iterator kinds = IMessage.KINDS.iterator(); kinds.hasNext();) {
- IMessage.Kind kind = (IMessage.Kind) kinds.next();
- for (Iterator locs = getSampleLocations().iterator(); locs.hasNext();) {
- ISourceLocation sourceLoc = (ISourceLocation) locs.next();
- for (Iterator texts = getSampleMessageTexts().iterator();
- texts.hasNext();
- ) {
- String text = (String) texts.next();
- for (Iterator exs = getSampleExceptions().iterator();
- exs.hasNext();
- ) {
- Throwable thrown = (Throwable) exs.next();
- result.handleMessage(new Message(text, kind, thrown, sourceLoc));
+ for (IMessage.Kind kind : IMessage.KINDS) {
+ for (Object item : getSampleLocations()) {
+ ISourceLocation sourceLoc = (ISourceLocation) item;
+ for (Object value : getSampleMessageTexts()) {
+ String text = (String) value;
+ for (Object o : getSampleExceptions()) {
+ Throwable thrown = (Throwable) o;
+ result.handleMessage(new Message(text, kind, thrown, sourceLoc));
}
- result.handleMessage(new Message(text, kind, null, sourceLoc));
+ result.handleMessage(new Message(text, kind, null, sourceLoc));
}
- result.handleMessage(new Message("", kind, null, sourceLoc));
+ result.handleMessage(new Message("", kind, null, sourceLoc));
}
- result.handleMessage(new Message("", kind, null, null));
+ result.handleMessage(new Message("", kind, null, null));
}
return result;
}
ArrayList result = new ArrayList();
ObjectChecker collector = new StandardObjectChecker(String.class, result);
SFileReader me = new SFileReader(null);
- for (int i = 0; i < args.length; i++) {
- Node node = me.readNodes(new File(args[i]), null, true, System.err);
- if (!Node.visit(node, collector, null)) {
- System.err.println("halted during copy of " +args[i]);
- } else {
- String s = org.aspectj.testing.util.LangUtil.debugStr(null, "\n ", null,
- null, result.toArray(), "\n ", "");
- System.err.println(args[i] + ": " + s);
- }
+ for (String arg : args) {
+ Node node = me.readNodes(new File(arg), null, true, System.err);
+ if (!Node.visit(node, collector, null)) {
+ System.err.println("halted during copy of " + arg);
+ } else {
+ String s = org.aspectj.testing.util.LangUtil.debugStr(null, "\n ", null,
+ null, result.toArray(), "\n ", "");
+ System.err.println(arg + ": " + s);
+ }
}
}
public static Set getAspectsAffectingPackage(IProgramElement packageNode) {
List<IProgramElement> files = StructureModelUtil.getFilesInPackage(packageNode);
Set aspects = new HashSet();
- for (Iterator<IProgramElement> it = files.iterator(); it.hasNext();) {
- IProgramElement fileNode = (IProgramElement) it.next();
+ for (IProgramElement fileNode : files) {
Map adviceMap = getLinesToAspectMap(fileNode.getSourceLocation().getSourceFile().getAbsolutePath());
Collection values = adviceMap.values();
- for (Iterator it2 = values.iterator(); it2.hasNext();) {
- aspects.add(it2.next());
+ for (Object value : values) {
+ aspects.add(value);
}
}
return aspects;
matches.add(o);
}
- for (Iterator it = node.getChildren().iterator(); it.hasNext();) {
- IProgramElement nextNode = (IProgramElement) it.next();
+ for (IProgramElement nextNode : node.getChildren()) {
getPackagesHelper(nextNode, kind, prename, matches);
}
packageContents = packageNode.getChildren();
}
List<IProgramElement> files = new ArrayList<IProgramElement>();
- for (Iterator<IProgramElement> it = packageContents.iterator(); it.hasNext();) {
- IProgramElement packageItem = (IProgramElement) it.next();
+ for (IProgramElement packageItem : packageContents) {
if (packageItem.getKind() == IProgramElement.Kind.FILE_JAVA
|| packageItem.getKind() == IProgramElement.Kind.FILE_ASPECTJ) {
files.add(packageItem);
/** @return null if class not found or byte[] of class otherwise */
private byte[] readClass(String className) throws ClassNotFoundException {
final String fileName = className.replace('.', '/')+".class";
- for (Iterator iter = dirs.iterator(); iter.hasNext();) {
- File file = new File((File) iter.next(), fileName);
- if (file.canRead()) {
- return getClassData(file);
- }
- }
+ for (Object dir : dirs) {
+ File file = new File((File) dir, fileName);
+ if (file.canRead()) {
+ return getClassData(file);
+ }
+ }
return null;
}
final String suffix = " " + label;
final String LABEL = list.size() + suffix;
out.println("## START " + LABEL);
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- TestResult result = (TestResult) iter.next();
+ for (Object o : list) {
+ TestResult result = (TestResult) o;
out.println(" " + result.test + " ## " + suffix);
}
out.println("## END " + LABEL);
if (!LangUtil.isEmpty(input) && !LangUtil.isEmpty(trim)) {
for (ListIterator iter = result.listIterator(); iter.hasNext();) {
TestResult inputItem = (TestResult) iter.next();
- for (Iterator iterator = trim.iterator();
- iterator.hasNext();
- ) {
- TestResult trimItem = (TestResult) iterator.next();
+ for (Object o : trim) {
+ TestResult trimItem = (TestResult) o;
if (inputItem.test.equals(trimItem.test)) {
- iter.remove();
- break;
- }
+ iter.remove();
+ break;
+ }
}
}
}
/** split input List by whether the TestResult element passed or failed */
private static void split(List input, ArrayList pass, ArrayList fail) {
- for (ListIterator iter = input.listIterator(); iter.hasNext();) {
- TestResult result = (TestResult) iter.next();
- if (result.pass) {
- pass.add(result);
- } else {
- fail.add(result);
- }
+ for (Object o : input) {
+ TestResult result = (TestResult) o;
+ if (result.pass) {
+ pass.add(result);
+ } else {
+ fail.add(result);
+ }
}
}
return "no input permitted at " + position;
}
String[] permitted = permittedArguments[position];
- for (int i = 0; i < permitted.length; i++) {
- if (input.equals(permitted[i])) {
- return null;
- }
- }
+ for (String s : permitted) {
+ if (input.equals(s)) {
+ return null;
+ }
+ }
return input + " not permitted, expecting one of "
+ Arrays.asList(permitted);
}
private Option.Value firstMatch(String value) {
LangUtil.throwIaxIfNull(value, "value");
// ArrayList list = new ArrayList();
- for (Iterator iter = options.iterator(); iter.hasNext();) {
- Option option = (Option) iter.next();
- Option.Value result = option.acceptValue(value);
- if (null != result) {
- return result;
- }
- }
+ for (Object o : options) {
+ Option option = (Option) o;
+ Option.Value result = option.acceptValue(value);
+ if (null != result) {
+ return result;
+ }
+ }
return null;
}
}
new String[] { "-g:vars,source" },
new String[] { "-verbose", "-g:vars,source" },
};
- for (int i = 0; i < input.length; i++) {
- optionChecker.checkOptions(input[i], input[i]);
- }
+ for (String[] strings : input) {
+ optionChecker.checkOptions(strings, strings);
+ }
}
private OptionChecker getOptionChecker() {
input = new Value[length];
length = 0;
Value[] temp;
- for (int i = 0; i < values.length; i++) {
- temp = values[i].asArray();
- System.arraycopy(temp, 0, input, length, temp.length);
- length += temp.length;
- }
+ for (Values value : values) {
+ temp = value.asArray();
+ System.arraycopy(temp, 0, input, length, temp.length);
+ length += temp.length;
+ }
}
return new Values(input);
}
throw new IllegalArgumentException(
"expecting force-off: " + value);
}
- for (int i = 0; i < matches.length; i++) {
- Option.Value match = input[matches[i]];
- if ((null != match) && value.sameValueIdentifier(match)) {
- if (match.prefix.forceOn()) {
- return "force conflict between "
- + value
- + " and "
- + match;
- } else {
- input[matches[i]] = null; // unset matches[i]?
- }
- }
- }
+ for (int j : matches) {
+ Value match = input[j];
+ if ((null != match) && value.sameValueIdentifier(match)) {
+ if (match.prefix.forceOn()) {
+ return "force conflict between "
+ + value
+ + " and "
+ + match;
+ } else {
+ input[j] = null; // unset matches[i]?
+ }
+ }
+ }
return null;
}
*/
private static String[] render(Value[] values) {
ArrayList list = new ArrayList();
- for (int i = 0; i < values.length; i++) {
- if (null != values[i]) {
- String[] output = values[i].unflatten();
- if (LangUtil.isEmpty(output)) {
- throw new Error("no output for " + values[i]);
- }
-
- String s = values[i].prefix.render(output[0]);
- if (null != s) { // this means the prefix is set
- list.add(s);
- for (int j = 1; j < output.length; j++) {
- list.add(output[j]);
- }
- }
- }
- }
+ for (Value value : values) {
+ if (null != value) {
+ String[] output = value.unflatten();
+ if (LangUtil.isEmpty(output)) {
+ throw new Error("no output for " + value);
+ }
+
+ String s = value.prefix.render(output[0]);
+ if (null != s) { // this means the prefix is set
+ list.add(s);
+ for (int j = 1; j < output.length; j++) {
+ list.add(output[j]);
+ }
+ }
+ }
+ }
return (String[]) list.toArray(new String[list.size()]);
}
protected Option.Value[] find(Selector filter, boolean findAll) {
LangUtil.throwIaxIfNull(filter, "filter");
ArrayList result = new ArrayList();
- for (int i = 0; i < values.length; i++) {
- final boolean accepted;
- try {
- accepted = filter.accept(values[i]);
- } catch (Error e) {
- if (Selector.STOP != e) {
- throw e;
- }
- break;
- }
- if (accepted) {
- result.add(values[i]);
- if (findAll != FIND_ALL) {
- break;
- }
- }
- }
+ for (Value value : values) {
+ final boolean accepted;
+ try {
+ accepted = filter.accept(value);
+ } catch (Error e) {
+ if (Selector.STOP != e) {
+ throw e;
+ }
+ break;
+ }
+ if (accepted) {
+ result.add(value);
+ if (findAll != FIND_ALL) {
+ break;
+ }
+ }
+ }
return toArray(result);
}
private Option.Value[] valuesNotNull() {
if (null == valuesNotNull) {
ArrayList list = new ArrayList();
- for (int i = 0; i < this.values.length; i++) {
- if (null != this.values[i]) {
- list.add(this.values[i]);
- }
- }
+ for (Value value : this.values) {
+ if (null != value) {
+ list.add(value);
+ }
+ }
valuesNotNull = toArray(list);
}
return valuesNotNull;
"../../../tests", "tests", "modules/tests"
};
File baseDir;
- for (int j = 0; j < baseDirs.length; j++) {
- baseDir = baseDirs[j];
- if (!isDir(baseDir)) {
- continue;
- }
- for (int i = 0; i < locations.length; i++) {
- File dir = new File(baseDir, locations[i]);
- if (isDir(dir)) {
- File temp = new File(dir, NAME);
- if (temp.isFile() && temp.canRead()) {
- return temp.getPath();
- }
- }
- }
- }
+ for (File file : baseDirs) {
+ baseDir = file;
+ if (!isDir(baseDir)) {
+ continue;
+ }
+ for (String location : locations) {
+ File dir = new File(baseDir, location);
+ if (isDir(dir)) {
+ File temp = new File(dir, NAME);
+ if (temp.isFile() && temp.canRead()) {
+ return temp.getPath();
+ }
+ }
+ }
+ }
return null;
}
public InputSource resolveEntity(
public void tearDown() {
if (!LangUtil.isEmpty(tempFiles)) {
- for (Iterator<File> iter = tempFiles.iterator(); iter.hasNext();) {
- File file = (File) iter.next();
+ for (File file : tempFiles) {
if (file.canRead()) {
file.delete();
}
AjcSpecXmlReader.BProps[] expected
= AjcSpecXmlReader.expectedProperties();
PropertyDescriptor[] des;
- for (int i = 0; i < expected.length; i++) {
- Class<?> clazz = expected[i].cl;
- BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
- assertTrue(null != beanInfo);
- des = beanInfo.getPropertyDescriptors();
- for (int j = 0; j < expected[i].props.length; j++) {
- String name = expected[i].props[j];
- String fqn = clazz.getName() + "." + name;
- boolean gotIt = false;
- for (int k = 0; k < des.length; k++) {
- String desName = des[k].getName();
- if (name.equals(desName)) {
- assertTrue(fqn, null != des[k].getWriteMethod());
- gotIt = true;
- }
- }
- assertTrue("no such property: " + fqn, gotIt);
+ for (AjcSpecXmlReader.BProps bProps : expected) {
+ Class<?> clazz = bProps.cl;
+ BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
+ assertTrue(null != beanInfo);
+ des = beanInfo.getPropertyDescriptors();
+ for (int j = 0; j < bProps.props.length; j++) {
+ String name = bProps.props[j];
+ String fqn = clazz.getName() + "." + name;
+ boolean gotIt = false;
+ for (PropertyDescriptor de : des) {
+ String desName = de.getName();
+ if (name.equals(desName)) {
+ assertTrue(fqn, null != de.getWriteMethod());
+ gotIt = true;
+ }
+ }
+ assertTrue("no such property: " + fqn, gotIt);
}
}
assertTrue("CloneNotSupportedException: " + e.getMessage(), false);
}
- for (Iterator<File> iter = toDelete.iterator(); iter.hasNext();) {
- iter.next().delete();
- }
+ for (File file : toDelete) {
+ file.delete();
+ }
}
void checkRoundTrip(String path) throws IOException, Exception {
//System.err.println("----------------------- suite2 " + xml2Path);
AjcSpecTest.sameAjcSuiteSpec(suite1, suite2, this);
AjcSpecTest.sameAjcSuiteSpec(suite0, suite2, this);
-
- for (Iterator<File> iter = toDelete.iterator(); iter.hasNext();) {
- iter.next().delete();
+
+ for (File file : toDelete) {
+ file.delete();
}
}
}
public void tearDown() {
if (!LangUtil.isEmpty(tempFiles)) {
- for (Iterator iter = tempFiles.iterator(); iter.hasNext();) {
- File file = (File) iter.next();
+ for (Object tempFile : tempFiles) {
+ File file = (File) tempFile;
if (file.canRead()) {
file.delete();
}
return;
}
List list = messages.getUnmodifiableListView();
- for (Iterator iter = list.iterator(); iter.hasNext();) {
- writeXml(out, (IMessage) iter.next());
+ for (Object o : list) {
+ writeXml(out, (IMessage) o);
}
}
if ((null == out) || (null == messages)) {
return;
}
- for (int i = 0; i < messages.length; i++) {
- writeXml(out, messages[i]);
+ for (IMessage iMessage : messages) {
+ writeXml(out, iMessage);
}
}
List extras = message.getExtraSourceLocations();
if (!LangUtil.isEmpty(extras)) {
out.endAttributes();
- for (Iterator iter = extras.iterator(); iter.hasNext();) {
- /*ISourceLocation element = (ISourceLocation)*/ iter.next();
- SoftSourceLocation.writeXml(out, sl);
+ for (Object extra : extras) {
+ /*ISourceLocation element = (ISourceLocation)*/
+ SoftSourceLocation.writeXml(out, sl);
}
}
out.endElement(elementName);
if (null != input) {
String[] items = XMLWriter.unflattenList(input);
if (!LangUtil.isEmpty(items)) {
- for (int i = 0; i < items.length; i++) {
- if (!LangUtil.isEmpty(items[i])) {
- list.add(items[i]);
- }
- }
+ for (String item : items) {
+ if (!LangUtil.isEmpty(item)) {
+ list.add(item);
+ }
+ }
}
}
}
StringBuffer sb = new StringBuffer();
if (null != list) {
boolean printed = false;
- for (int i = 0; i < list.length; i++) {
- Object o = list[i];
- if (null != o) {
- if (printed) {
- sb.append(",");
- } else {
- printed = true;
- }
- String s = o.toString();
- if (-1 != s.indexOf(",")) {
- throw new IllegalArgumentException("comma in " + s);
- }
- sb.append(s);
- }
+ for (Object o : list) {
+ if (null != o) {
+ if (printed) {
+ sb.append(",");
+ } else {
+ printed = true;
+ }
+ String s = o.toString();
+ if (-1 != s.indexOf(",")) {
+ throw new IllegalArgumentException("comma in " + s);
+ }
+ sb.append(s);
+ }
}
}
return sb.toString();
boolean f = false;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "PR82570_1");
Method[] meths = jc.getMethods();
- for (int i = 0; i < meths.length; i++) {
- Method method = meths[i];
+ for (Method method : meths) {
if (f)
System.err.println("Line number table for " + method.getName() + method.getSignature() + " = "
+ method.getLineNumberTable());
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(),"Program");
Method[] meths = jc.getMethods();
- for (int i = 0; i < meths.length; i++) {
- Method method = meths[i];
+ for (Method method : meths) {
if (method.getName().equals("m1")) {
- assertTrue("Didn't have annotations - were they lost? method="+method.getName(),method.getAnnotations().length==1);
+ assertTrue("Didn't have annotations - were they lost? method=" + method.getName(), method.getAnnotations().length == 1);
}
}
}
JavaClass clazz = getClassFromDisk(ajc, classname);
Signature sigAttr = null;
Attribute[] attrs = clazz.getAttributes();
- for (int i = 0; i < attrs.length; i++) {
- Attribute attribute = attrs[i];
+ for (Attribute attribute : attrs) {
if (attribute.getName().equals("Signature")) {
sigAttr = (Signature) attribute;
}
private BcelTypeMunger getMungerFromLine(String classname, int linenumber) {
List allMungers = getTypeMunger(classname);
- for (Iterator iter = allMungers.iterator(); iter.hasNext();) {
- BcelTypeMunger element = (BcelTypeMunger) iter.next();
+ for (Object munger : allMungers) {
+ BcelTypeMunger element = (BcelTypeMunger) munger;
if (element.getMunger().getSourceLocation().getLine() == linenumber) {
return element;
}
}
- for (Iterator iter = allMungers.iterator(); iter.hasNext();) {
- BcelTypeMunger element = (BcelTypeMunger) iter.next();
+ for (Object allMunger : allMungers) {
+ BcelTypeMunger element = (BcelTypeMunger) allMunger;
System.err.println("Line: " + element.getMunger().getSourceLocation().getLine() + " > " + element);
}
fail("Couldn't find a type munger from line " + linenumber + " in class " + classname);
JavaClass theClass = getClassFromDisk(ajc, classname);
Hashtable<String,Field> retval = new Hashtable<>();
org.aspectj.apache.bcel.classfile.Field[] fs = theClass.getFields();
- for (int i = 0; i < fs.length; i++) {
- Field field = fs[i];
+ for (Field field : fs) {
retval.put(field.getName(), field);
}
return retval;
Class<?> clz = Class.forName(classname,false,cl);
java.lang.reflect.Method[] ms = clz.getDeclaredMethods();
if (ms!=null) {
- for (int i =0;i<ms.length;i++) {
- String methodString = ms[i].getReturnType().getName()+" "+ms[i].getDeclaringClass().getName()+"."+
- ms[i].getName()+"("+stringify(ms[i].getParameterTypes())+")"+
- (isBridge(ms[i])?" [BridgeMethod]":"");
+ for (java.lang.reflect.Method m : ms) {
+ String methodString = m.getReturnType().getName() + " " + m.getDeclaringClass().getName() + "." +
+ m.getName() + "(" + stringify(m.getParameterTypes()) + ")" +
+ (isBridge(m) ? " [BridgeMethod]" : "");
methodsFound.add(methodString);
debugString.append("\n[").append(methodString).append("]");
}
}
// check the methods specified do exist
- for (int i = 0; i < methods.length; i++) {
- String string = methods[i];
+ for (String string : methods) {
if (!methodsFound.remove(string)) {
- fail("Couldn't find ["+string+"] in the set of methods in "+classname+" => "+debugString);
+ fail("Couldn't find [" + string + "] in the set of methods in " + classname + " => " + debugString);
}
}
StringBuffer unexpectedMethods = new StringBuffer();
JavaClass clazz = getClass(ajc,classname);
Signature sigAttr = null;
Attribute[] attrs = clazz.getAttributes();
- for (int i = 0; i < attrs.length; i++) {
- Attribute attribute = attrs[i];
- if (attribute.getName().equals("Signature")) sigAttr = (Signature)attribute;
+ for (Attribute attribute : attrs) {
+ if (attribute.getName().equals("Signature")) sigAttr = (Signature) attribute;
}
return sigAttr;
}
Attribute[] attrs = clazz.getAttributes();
int signatureCount = 0;
StringBuffer sb = new StringBuffer();
- for (int i = 0; i < attrs.length; i++) {
- Attribute attribute = attrs[i];
+ for (Attribute attribute : attrs) {
if (attribute.getName().equals("Signature")) {
signatureCount++;
- sb.append("\n"+((Signature)attribute).getSignature());
+ sb.append("\n" + ((Signature) attribute).getSignature());
}
}
if (signatureCount>1) fail("Should be only one signature attribute but found "+signatureCount+sb.toString());
protected Method getMethod(JavaClass cl, String methodname) {
Method[] methods = cl.getMethods();
- for (int i = 0; i < methods.length; i++) {
- Method m = methods[i];
+ for (Method m : methods) {
if (m.getName().equals(methodname)) {
return m;
}
private String stringify(List<String> l) {
StringBuffer result = new StringBuffer();
- for (Iterator<String> iter = l.iterator(); iter.hasNext();) {
- String str = iter.next();
+ for (String str : l) {
result.append(str);
result.append("\n");
}
List children = parent.getChildren();
String handle1 = null;
String handle2 = null;
- for (Iterator iter = children.iterator(); iter.hasNext();) {
- IProgramElement element = (IProgramElement) iter.next();
+ for (Object child : children) {
+ IProgramElement element = (IProgramElement) child;
if (element.getKind().equals(IProgramElement.Kind.ADVICE)) {
if (handle1 == null) {
handle1 = element.getHandleIdentifier();
List children = parent.getChildren();
String handle1 = null;
String handle2 = null;
- for (Iterator iter = children.iterator(); iter.hasNext();) {
- IProgramElement element = (IProgramElement) iter.next();
+ for (Object child : children) {
+ IProgramElement element = (IProgramElement) child;
if (element.getKind().equals(IProgramElement.Kind.INITIALIZER)) {
if (handle1 == null) {
handle1 = element.getHandleIdentifier();
CustomMungerFactory factory = (CustomMungerFactory) compiler.getCustomMungerFactory();
assertTrue(factory.getAllCreatedCustomShadowMungers().size() > 0);
- for (Iterator<ShadowMunger> i = factory.getAllCreatedCustomShadowMungers().iterator(); i.hasNext();) {
- assertTrue(((DumbShadowMunger) i.next()).called);
+ for (ShadowMunger shadowMunger : factory.getAllCreatedCustomShadowMungers()) {
+ assertTrue(((DumbShadowMunger) shadowMunger).called);
}
assertTrue(factory.getAllCreatedCustomTypeMungers().size() > 0);
- for (Iterator<ConcreteTypeMunger> i = factory.getAllCreatedCustomTypeMungers().iterator(); i.hasNext();) {
- assertTrue(((DumbTypeMunger) i.next()).called);
+ for (ConcreteTypeMunger concreteTypeMunger : factory.getAllCreatedCustomTypeMungers()) {
+ assertTrue(((DumbTypeMunger) concreteTypeMunger).called);
}
}
toIgnore = "_" + (toIgnore == null ? "" : toIgnore) + "_";
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), classname);
Method[] methods = jc.getMethods();
- for (int i = 0; i < methods.length; i++) {
- Method method = methods[i];
+ for (Method method : methods) {
if (toIgnore.contains("_" + method.getName() + "_")) {
continue;
}
if (attrs == null) {
return false;
}
- for (int i = 0; i < attrs.length; i++) {
- Attribute attribute = attrs[i];
+ for (Attribute attribute : attrs) {
if (attribute.getName().equals(attributeName)) {
return true;
}
if (attribute.getName().equals("Code")) {
Code c = (Code) attribute;
Attribute[] codeAttributes = c.getAttributes();
- for (int j = 0; j < codeAttributes.length; j++) {
- Attribute codeAttribute = codeAttributes[j];
+ for (Attribute codeAttribute : codeAttributes) {
if (codeAttribute.getName().equals(attributeName)) {
return true;
// System.out.println(codeAttribute.getName());
Set entries = irm.getEntries();
boolean gotSomethingValid = false;
String expected = "<recursivepackage{RecursiveCatcher.java'RecursiveCatcher~recursiveCall~I?method-call(void recursivepackage.RecursiveCatcher.recursiveCall(int))";
- for (Iterator iterator = entries.iterator(); iterator.hasNext();) {
- String str = (String) iterator.next();
+ for (Object entry : entries) {
+ String str = (String) entry;
if (str.indexOf(expected) != -1) {
gotSomethingValid = true;
}
private Method getPreClinitMethod(JavaClass myClass) {
Method lm[] = myClass.getMethods();
- for (int i = 0; i < lm.length; i++) {
- if (lm[i].getName().equals("ajc$preClinit")) {
- return lm[i];
+ for (Method method : lm) {
+ if (method.getName().equals("ajc$preClinit")) {
+ return method;
}
}
return null;
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "X");
Method[] meths = jc.getMethods();
boolean checked = false;
- for (int i = 0; i < meths.length; i++) {
- Method method = meths[i];
+ for (Method method : meths) {
if (method.getName().equals("ajc$before$X$2$3444dde4")) {
System.out.println(method.getName());
System.out.println(stringify(method.getLocalVariableTable()));
JavaClass jc = Utils.getClassFrom(ajc.getSandboxDirectory().getAbsolutePath(), "Test");
Method[] ms = jc.getMethods();
Method m = null;
- for (int i = 0; i < ms.length; i++) {
- if (ms[i].getName().equals("sayHello")) {
- m = ms[i];
+ for (Method method : ms) {
+ if (method.getName().equals("sayHello")) {
+ m = method;
}
}
if (m.getLocalVariableTable() == null) {
private void print(LocalVariableTable localVariableTable) {
LocalVariable[] lvs = localVariableTable.getLocalVariableTable();
- for (int i = 0; i < lvs.length; i++) {
- LocalVariable localVariable = lvs[i];
+ for (LocalVariable localVariable : lvs) {
System.out.println(localVariable);
}
}
return whereToLook;
}
List<IProgramElement> kids = whereToLook.getChildren();
- for (Iterator<IProgramElement> iterator = kids.iterator(); iterator.hasNext();) {
- IProgramElement object = iterator.next();
+ for (IProgramElement object : kids) {
if (object.getSourceLocation() != null && object.getSourceLocation().getLine() == line) {
return object;
}
List<IMessage> ms = ajc.getLastCompilationResult().getWarningMessages();
boolean checked = true;
// Look for the message relating to 'List' and check the offsets
- for (int i = 0; i < ms.size(); i++) {
- LintMessage m = (LintMessage) ms.get(i);
+ for (IMessage iMessage : ms) {
+ LintMessage m = (LintMessage) iMessage;
if (m.toString().indexOf("List") != -1) {
// 225/228 on windows - 237/240 on linux
if (!(m.getSourceStart() == 225 || m.getSourceStart() == 237)) {
Method m = getMethodStartsWith(jc, "getName");
assertNotNull(m);
AnnotationGen[] ags = m.getAnnotations();
- for (int i=0;i<ags.length;i++) {
- System.out.println(ags[i]);
+ for (AnnotationGen ag : ags) {
+ System.out.println(ag);
}
assertEquals(1,ags.length);
assertEquals("LFoo;",ags[0].getTypeSignature());
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), "Program");
Method[] meths = jc.getMethods();
- for (int i = 0; i < meths.length; i++) {
- Method method = meths[i];
+ for (Method method : meths) {
if (method.getName().equals("m1")) {
assertTrue("Didn't have annotations - were they lost? method=" + method.getName(),
method.getAnnotations().length == 1);
try {
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), classname);
Method[] meths = jc.getMethods();
- for (int i = 0; i < meths.length; i++) {
- Method method = meths[i];
+ for (Method method : meths) {
if (method.getName().equals("ajc$preClinit")) {
String code = method.getCode().getCodeString();
- assertTrue("Expected to contain '"+text+"':\n"+code,code.contains(text));
+ assertTrue("Expected to contain '" + text + "':\n" + code, code.contains(text));
return;
}
}
toIgnore = "_" + (toIgnore == null ? "" : toIgnore) + "_";
JavaClass jc = getClassFrom(ajc.getSandboxDirectory(), classname);
Method[] methods = jc.getMethods();
- for (int i = 0; i < methods.length; i++) {
- Method method = methods[i];
+ for (Method method : methods) {
if (toIgnore.contains("_" + method.getName() + "_")) {
continue;
}
if (attrs == null) {
return false;
}
- for (int i = 0; i < attrs.length; i++) {
- Attribute attribute = attrs[i];
+ for (Attribute attribute : attrs) {
if (attribute.getName().equals(attributeName)) {
return true;
}
if (attribute.getName().equals("Code")) {
Code c = (Code) attribute;
Attribute[] codeAttributes = c.getAttributes();
- for (int j = 0; j < codeAttributes.length; j++) {
- Attribute codeAttribute = codeAttributes[j];
+ for (Attribute codeAttribute : codeAttributes) {
if (codeAttribute.getName().equals(attributeName)) {
return true;
// System.out.println(codeAttribute.getName());
// System.out.println("kvp: " + object + " = " + m.get(object));
// }
// }
- for (Iterator<IProgramElement> i = node.getChildren().iterator(); i.hasNext();) {
- dumptree( i.next(), indent + 2);
+ for (IProgramElement iProgramElement : node.getChildren()) {
+ dumptree(iProgramElement, indent + 2);
}
}
}
IRelationshipMap relmap = getModelFor(project).getRelationshipMap();
int ctr = 0;
Set<String> entries = relmap.getEntries();
- for (Iterator<String> iter = entries.iterator(); iter.hasNext();) {
- String hid = (String) iter.next();
+ for (String hid : entries) {
List<IRelationship> rels = relmap.get(hid);
- for (Iterator<IRelationship> iterator = rels.iterator(); iterator.hasNext();) {
- ctr+=iterator.next().getTargets().size();
+ for (IRelationship rel : rels) {
+ ctr += rel.getTargets().size();
}
}
return ctr;
String contents[] = location.list();
if (contents == null)
return;
- for (int i = 0; i < contents.length; i++) {
- String string = contents[i];
+ for (String string : contents) {
File f = new File(location, string);
if (f.isDirectory()) {
collectUpFiles(f, base, collectionPoint);
String contents[] = from.list();
if (contents == null)
return;
- for (int i = 0; i < contents.length; i++) {
- String string = contents[i];
+ for (String string : contents) {
File f = new File(from, string);
File t = new File(to, string);
List<String> filesForCompilation = new ArrayList<String>();
collectUpFiles(projectBase, projectBase, filesForCompilation);
boolean changed = false;
- for (int i = 0; i < filesForCompilation.size(); i++) {
- if (!currentFiles.contains(filesForCompilation.get(i))) {
+ for (String s : filesForCompilation) {
+ if (!currentFiles.contains(s)) {
changed = true;
}
}
- for (int i = 0; i < currentFiles.size(); i++) {
- if (!filesForCompilation.contains(currentFiles.get(i))) {
+ for (String currentFile : currentFiles) {
+ if (!filesForCompilation.contains(currentFile)) {
changed = true;
}
}
List<String> collector = new ArrayList<String>();
collectUpXmlFiles(projectBase, projectBase, collector);
boolean changed = false;
- for (int i = 0; i < collector.size(); i++) {
- if (!currentXmlFiles.contains(collector.get(i))) {
+ for (String s : collector) {
+ if (!currentXmlFiles.contains(s)) {
changed = true;
}
}
- for (int i = 0; i < currentXmlFiles.size(); i++) {
- if (!collector.contains(currentXmlFiles.get(i))) {
+ for (String currentXmlFile : currentXmlFiles) {
+ if (!collector.contains(currentXmlFile)) {
changed = true;
}
}
if (contents == null) {
return;
}
- for (int i = 0; i < contents.length; i++) {
- String string = contents[i];
+ for (String string : contents) {
File f = new File(location, string);
if (f.isDirectory()) {
collectUpFiles(f, base, collectionPoint);
if (contents == null) {
return;
}
- for (int i = 0; i < contents.length; i++) {
- String string = contents[i];
+ for (String string : contents) {
File f = new File(location, string);
if (f.isDirectory()) {
collectUpXmlFiles(f, base, collectionPoint);
public void checkForError(String projectName, String anError) {
AjCompiler compiler = CompilerFactory.getCompilerForProjectWithDir(sandboxDir + File.separator + projectName);
List<IMessage> messages = ((MultiProjTestMessageHandler) compiler.getMessageHandler()).getErrorMessages();
- for (Iterator<IMessage> iter = messages.iterator(); iter.hasNext();) {
- IMessage element = iter.next();
+ for (IMessage element : messages) {
if (element.getMessage().indexOf(anError) != -1) {
return;
}
System.out.println("Build took: " + getTimeTakenForBuild(projectName) + "ms");
List<String> compiled = getCompiledFiles(projectName);
System.out.println("Compiled: " + compiled.size() + " files");
- for (Iterator<String> iter = compiled.iterator(); iter.hasNext();) {
- System.out.println(" :" + iter.next());
+ for (String value : compiled) {
+ System.out.println(" :" + value);
}
List<String> woven = getWovenClasses(projectName);
System.out.println("Wove: " + woven.size() + " files");
- for (Iterator<String> iter = woven.iterator(); iter.hasNext();) {
- System.out.println(" :" + iter.next());
+ for (String s : woven) {
+ System.out.println(" :" + s);
}
if (wasFullBuild()) {
System.out.println("It was a batch (full) build");
Map<String,File> classNameToFileMap = state.getClassNameToFileMap();
assertFalse("expected there to be classes ", classNameToFileMap.isEmpty());
Set<Map.Entry<String,File>> entrySet = classNameToFileMap.entrySet();
- for (Iterator<Map.Entry<String,File>> iterator = entrySet.iterator(); iterator.hasNext();) {
- Map.Entry<String,File> entry = iterator.next();
+ for (Map.Entry<String, File> entry : entrySet) {
String className = entry.getKey();
String fullClassName = expectedOutputDir + File.separator + className.replace('.', File.separatorChar) + ".class";
File file = entry.getValue();
checkWasFullBuild();
List<IMessage> weaveMessages = getWeavingMessages(p);
if (weaveMessages.size() != 1) {
- for (Iterator<IMessage> iterator = weaveMessages.iterator(); iterator.hasNext();) {
- Object object = iterator.next();
+ for (Object object : weaveMessages) {
System.out.println(object);
}
fail("Expected just one weave message. The aop.xml should have limited the weaving");
assertNotNull(ps);
assertEquals(2, ps.size());
int count = 0;
- for (Iterator<String> iterator = ps.iterator(); iterator.hasNext();) {
- String type = iterator.next();
+ for (String type : ps) {
if (type.equals("java.io.Serializable")) {
count++;
}
IRelationshipMap asmRelMap = getModelFor("P4").getRelationshipMap();
assertEquals("There should be two relationships in the relationship map", 2, asmRelMap.getEntries().size());
- for (Iterator<String> iter = asmRelMap.getEntries().iterator(); iter.hasNext();) {
- String sourceOfRelationship = (String) iter.next();
+ for (String sourceOfRelationship : asmRelMap.getEntries()) {
IProgramElement ipe = getModelFor("P4").getHierarchy().findElementForHandle(sourceOfRelationship);
assertNotNull("expected to find IProgramElement with handle " + sourceOfRelationship + " but didn't", ipe);
- if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) {
+ if (ipe.getKind().equals(Kind.ADVICE)) {
assertEquals("expected source of relationship to be " + advice.toString() + " but found " + ipe.toString(),
advice, ipe);
- } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
+ } else if (ipe.getKind().equals(Kind.CODE)) {
assertEquals(
"expected source of relationship to be " + codeElement.toString() + " but found " + ipe.toString(),
codeElement, ipe);
}
List<IRelationship> relationships = asmRelMap.get(ipe);
assertNotNull("expected " + ipe.getName() + " to have some " + "relationships", relationships);
- for (Iterator<IRelationship> iterator = relationships.iterator(); iterator.hasNext();) {
- Relationship rel = (Relationship) iterator.next();
+ for (IRelationship relationship : relationships) {
+ Relationship rel = (Relationship) relationship;
List<String> targets = rel.getTargets();
- for (Iterator<String> iterator2 = targets.iterator(); iterator2.hasNext();) {
- String t = (String) iterator2.next();
+ for (String t : targets) {
IProgramElement link = getModelFor("P4").getHierarchy().findElementForHandle(t);
- if (ipe.getKind().equals(IProgramElement.Kind.ADVICE)) {
+ if (ipe.getKind().equals(Kind.ADVICE)) {
assertEquals(
"expected target of relationship to be " + codeElement.toString() + " but found "
+ link.toString(), codeElement, link);
- } else if (ipe.getKind().equals(IProgramElement.Kind.CODE)) {
+ } else if (ipe.getKind().equals(Kind.CODE)) {
assertEquals(
"expected target of relationship to be " + advice.toString() + " but found " + link.toString(),
advice, link);
IProgramElement root = model.getHierarchy().getRoot();
ProgramElement theITD = (ProgramElement) findElementAtLine(root, 7);
Map<String, Object> m = theITD.kvpairs;
- for (Iterator<String> iterator = m.keySet().iterator(); iterator.hasNext();) {
- String type = iterator.next();
+ for (String type : m.keySet()) {
System.out.println(type + " = " + m.get(type));
}
// return type of the ITD
assertEquals("a.b.c.B", theITD.getCorrespondingType(true));
List<char[]> ptypes = theITD.getParameterTypes();
- for (Iterator<char[]> iterator = ptypes.iterator(); iterator.hasNext();) {
- char[] object = iterator.next();
+ for (char[] object : ptypes) {
System.out.println("p = " + new String(object));
}
ProgramElement decp = (ProgramElement) findElementAtLine(root, 8);
m = decp.kvpairs;
- for (Iterator<String> iterator = m.keySet().iterator(); iterator.hasNext();) {
- String type = iterator.next();
+ for (String type : m.keySet()) {
System.out.println(type + " = " + m.get(type));
}
List<String> l = decp.getParentTypes();
}
List<IProgramElement> kids = start.getChildren();
if (kids != null) {
- for (int i = 0; i < kids.size(); i++) {
- IProgramElement found = getChild((IProgramElement) kids.get(i), name);
+ for (IProgramElement kid : kids) {
+ IProgramElement found = getChild((IProgramElement) kid, name);
if (found != null) {
return found;
}
if (rels == null) {
fail("Did not find any related elements!");
}
- for (Iterator<IRelationship> iter = rels.iterator(); iter.hasNext();) {
- IRelationship element = iter.next();
+ for (IRelationship element : rels) {
List<String> targets = element.getTargets();
if (output == null) {
output = new ArrayList<String>();
}
// iterate over what we found
- for (Iterator<String> iter = foundFileContents.iterator(); iter.hasNext();) {
- String line = (String) iter.next();
+ for (String line : foundFileContents) {
if (debugTest)
System.err.println("looking at model entry: " + line);
if (!fileContents.contains(line)) {
if (debugTest) {
System.err.println("couldn't find: " + line);
- for (Iterator<String> iterator = fileContents.iterator(); iterator.hasNext();) {
- String element = (String) iterator.next();
+ for (String element : fileContents) {
System.err.println("compared with: " + element);
}
}
}
if (debugTest && !fileContents.isEmpty()) {
- for (Iterator<String> iter = fileContents.iterator(); iter.hasNext();) {
- String element = (String) iter.next();
+ for (String element : fileContents) {
System.err.println("remaining: " + element);
}
}
return 0;
}
- for (Iterator<String> iter = SOURCE_SUFFIXES.iterator(); iter.hasNext();) {
- String suffix = iter.next();
- if (path.endsWith(suffix) || path.toLowerCase().endsWith(suffix)) {
- return suffix.length();
- }
- }
+ for (String suffix : SOURCE_SUFFIXES) {
+ if (path.endsWith(suffix) || path.toLowerCase().endsWith(suffix)) {
+ return suffix.length();
+ }
+ }
return 0;
}
}
StringBuffer result = new StringBuffer();
boolean first = true;
- for (int i = 0; i < paths.length; i++) {
- String path = paths[i];
- if (null == path) {
- continue;
- }
- if (first) {
- first = false;
- } else {
- result.append(infix);
- }
- result.append(path);
- }
+ for (String path : paths) {
+ if (null == path) {
+ continue;
+ }
+ if (first) {
+ first = false;
+ }
+ else {
+ result.append(infix);
+ }
+ result.append(path);
+ }
return result.toString();
}
return 0;
}
int result = 0;
- for (int i = 0; i < fromFiles.length; i++) {
- String string = fromFiles[i];
- File file = new File(dir, string);
- if ((null == filter) || filter.accept(file)) {
- if (file.isDirectory()) {
- result += deleteContents(file, filter, deleteEmptyDirs);
- String[] fileContent = file.list();
- if (deleteEmptyDirs && fileContent != null
- && 0 == fileContent.length) {
- file.delete();
- }
- } else {
- /* boolean ret = */
- file.delete();
- result++;
- }
- }
- }
+ for (String string : fromFiles) {
+ File file = new File(dir, string);
+ if ((null == filter) || filter.accept(file)) {
+ if (file.isDirectory()) {
+ result += deleteContents(file, filter, deleteEmptyDirs);
+ String[] fileContent = file.list();
+ if (deleteEmptyDirs && fileContent != null
+ && 0 == fileContent.length) {
+ file.delete();
+ }
+ }
+ else {
+ /* boolean ret = */
+ file.delete();
+ result++;
+ }
+ }
+ }
return result;
}
File[] result = null;
if (!LangUtil.isEmpty(suffixes)) {
ArrayList<File> list = new ArrayList<File>();
- for (int i = 0; i < paths.length; i++) {
- String path = paths[i];
- for (int j = 0; j < suffixes.length; j++) {
- if (path.endsWith(suffixes[j])) {
- list.add(new File(basedir, paths[i]));
- break;
- }
- }
- }
+ for (String path : paths) {
+ for (String suffix : suffixes) {
+ if (path.endsWith(suffix)) {
+ list.add(new File(basedir, path));
+ break;
+ }
+ }
+ }
result = list.toArray(new File[0]);
} else {
result = new File[paths.length];
public static void writeBooleanArray(boolean[] a, DataOutputStream s) throws IOException {
int len = a.length;
s.writeInt(len);
- for (int i = 0; i < len; i++) {
- s.writeBoolean(a[i]);
- }
+ for (boolean b : a) {
+ s.writeBoolean(b);
+ }
}
/**
public static void writeIntArray(int[] a, DataOutputStream s) throws IOException {
int len = a.length;
s.writeInt(len);
- for (int i = 0; i < len; i++) {
- s.writeInt(a[i]);
- }
+ for (int j : a) {
+ s.writeInt(j);
+ }
}
/**
}
int len = a.length;
s.writeInt(len);
- for (int i = 0; i < len; i++) {
- s.writeUTF(a[i]);
- }
+ for (String value : a) {
+ s.writeUTF(value);
+ }
}
/**
return Collections.emptyList();
}
ArrayList<String> result = new ArrayList<String>();
- for (Iterator<String> iter = sources.iterator(); iter.hasNext();) {
- String path = iter.next();
- String error = lineSeek(sought, path, listAll, result);
- if ((null != error) && (null != errorSink)) {
- errorSink.println(error);
- }
- }
+ for (String path : sources) {
+ String error = lineSeek(sought, path, listAll, result);
+ if ((null != error) && (null != errorSink)) {
+ errorSink.println(error);
+ }
+ }
return result;
}
return true;
}
long delayUntil = System.currentTimeMillis();
- for (int i = 0; i < files.length; i++) {
- File file = files[i];
- if ((null == file) || !file.exists()) {
- continue;
- }
- long nextModTime = file.lastModified();
- if (nextModTime > delayUntil) {
- delayUntil = nextModTime;
- }
- }
+ for (File file : files) {
+ if ((null == file) || !file.exists()) {
+ continue;
+ }
+ long nextModTime = file.lastModified();
+ if (nextModTime > delayUntil) {
+ delayUntil = nextModTime;
+ }
+ }
return LangUtil.sleepUntil(++delayUntil);
}
private static void listClassFiles(final File baseDir, ArrayList<File> result) {
File[] files = baseDir.listFiles();
- for (int i = 0; i < files.length; i++) {
- File f = files[i];
- if (f.isDirectory()) {
- listClassFiles(f, result);
- } else {
- if (f.getName().endsWith(".class")) {
- result.add(f);
- }
- }
- }
+ for (File f : files) {
+ if (f.isDirectory()) {
+ listClassFiles(f, result);
+ }
+ else {
+ if (f.getName().endsWith(".class")) {
+ result.add(f);
+ }
+ }
+ }
}
private static void listFiles(final File baseDir, ArrayList<File> result, FileFilter filter) {
File[] files = baseDir.listFiles();
// hack https://bugs.eclipse.org/bugs/show_bug.cgi?id=48650
final boolean skipCVS = (!PERMIT_CVS && (filter == aspectjSourceFileFilter));
- for (int i = 0; i < files.length; i++) {
- File f = files[i];
- if (f.isDirectory()) {
- if (skipCVS) {
- String name = f.getName().toLowerCase();
- if ("cvs".equals(name) || "sccs".equals(name)) {
- continue;
- }
- }
- listFiles(f, result, filter);
- } else {
- if (filter.accept(f)) {
- result.add(f);
- }
- }
- }
+ for (File f : files) {
+ if (f.isDirectory()) {
+ if (skipCVS) {
+ String name = f.getName().toLowerCase();
+ if ("cvs".equals(name) || "sccs".equals(name)) {
+ continue;
+ }
+ }
+ listFiles(f, result, filter);
+ }
+ else {
+ if (filter.accept(f)) {
+ result.add(f);
+ }
+ }
+ }
}
/** @return true if input is not null and contains no path separator */
final String dirPrefix = (null == dir ? "" : dir + "/");
final File dirFile = (null == dir ? baseDir : new File(baseDir.getPath() + "/" + dir));
final String[] files = dirFile.list();
- for (int i = 0; i < files.length; i++) {
- File f = new File(dirFile, files[i]);
- String path = dirPrefix + files[i];
- if (f.isDirectory()) {
- listFiles(baseDir, path, result);
- } else {
- result.add(path);
- }
- }
+ for (String file : files) {
+ File f = new File(dirFile, file);
+ String path = dirPrefix + file;
+ if (f.isDirectory()) {
+ listFiles(baseDir, path, result);
+ }
+ else {
+ result.add(path);
+ }
+ }
}
private FileUtil() {
public static List<String> makeClasspath(URL[] urls) {
List<String> ret = new LinkedList<String>();
if (urls != null) {
- for (int i = 0; i < urls.length; i++) {
- ret.add(toPathString(urls[i]));
- }
+ for (URL url : urls) {
+ ret.add(toPathString(url));
+ }
}
return ret;
}
StringBuffer ret = new StringBuffer();
ret.append(formalTypeParameters.toString());
ret.append(superclassSignature.toString());
- for (int i = 0; i < superInterfaceSignatures.length; i++) {
- ret.append(superInterfaceSignatures[i].toString());
+ for (ClassTypeSignature superInterfaceSignature : superInterfaceSignatures) {
+ ret.append(superInterfaceSignature.toString());
}
return ret.toString();
}
StringBuffer sb = new StringBuffer();
if (formalTypeParameters.length > 0) {
sb.append("<");
- for (int i = 0; i < formalTypeParameters.length; i++) {
- sb.append(formalTypeParameters[i].toString());
+ for (FormalTypeParameter formalTypeParameter : formalTypeParameters) {
+ sb.append(formalTypeParameter.toString());
}
sb.append(">");
}
sb.append("(");
- for (int i = 0; i < parameters.length; i++) {
- sb.append(parameters[i].toString());
+ for (TypeSignature parameter : parameters) {
+ sb.append(parameter.toString());
}
sb.append(")");
sb.append(returnType.toString());
- for (int i = 0; i < throwsSignatures.length; i++) {
+ for (FieldTypeSignature throwsSignature : throwsSignatures) {
sb.append("^");
- sb.append(throwsSignatures[i].toString());
+ sb.append(throwsSignature.toString());
}
return sb.toString();
}
ret.append(identifier);
ret.append(":");
ret.append(classBound.toString());
- for (int i = 0; i < interfaceBounds.length; i++) {
+ for (FieldTypeSignature interfaceBound : interfaceBounds) {
ret.append(":");
- ret.append(interfaceBounds[i].toString());
+ ret.append(interfaceBound.toString());
}
return ret.toString();
}
sb.append(identifier);
if (typeArguments.length > 0) {
sb.append("<");
- for (int i = 0; i < typeArguments.length; i++) {
- sb.append(typeArguments[i].toString());
+ for (TypeArgument typeArgument : typeArguments) {
+ sb.append(typeArgument.toString());
}
sb.append(">");
}
} else if (tokenStream[tokenIndex].equals("<")) {
ret.append("<");
TypeArgument[] tArgs = maybeParseTypeArguments();
- for (int i = 0; i < tArgs.length; i++) {
- ret.append(tArgs[i].toString());
+ for (TypeArgument tArg : tArgs) {
+ ret.append(tArg.toString());
}
ret.append(">");
outerType = new SimpleClassTypeSignature(identifier, tArgs);
private static <T extends PartialComparable> void addNewPartialComparable(List<SortObject<T>> graph, T o) {
SortObject<T> so = new SortObject<T>(o);
- for (Iterator<SortObject<T>> i = graph.iterator(); i.hasNext();) {
- SortObject<T> other = i.next();
+ for (SortObject<T> other : graph) {
so.addDirectedLinks(other);
}
graph.add(so);
// ??? I don't like creating this data structure, but it does give good
// ??? separation of concerns.
List<SortObject<T>> sortList = new LinkedList<SortObject<T>>();
- for (Iterator<T> i = objects.iterator(); i.hasNext();) {
- addNewPartialComparable(sortList, i.next());
+ for (T object : objects) {
+ addNewPartialComparable(sortList, object);
}
// System.out.println(sortList);
public static Method getMatchingMethod(Class<?> class_, String name, Object[] args) {
Method[] meths = class_.getMethods();
- for (int i=0; i < meths.length; i++) {
- Method meth = meths[i];
+ for (Method meth : meths) {
if (meth.getName().equals(name) && isCompatible(meth, args)) {
return meth;
}
ArrayList<File> libs = new ArrayList<File>();
ArrayList<URL> urls = new ArrayList<URL>();
String[] entries = LangUtil.splitClasspath(classpath);
- for (int i = 0; i < entries.length; i++) {
- String entry = entries[i];
- URL url = makeURL(entry);
- if (null != url) {
- urls.add(url);
- }
- File file = new File(entries[i]);
+ for (String entry : entries) {
+ URL url = makeURL(entry);
+ if (null != url) {
+ urls.add(url);
+ }
+ File file = new File(entry);
// tolerate bad entries b/c bootclasspath sometimes has them
// if (!file.canRead()) {
// throw new IllegalArgumentException("cannot read " + file);
// }
- if (FileUtil.isZipFile(file)) {
- libs.add(file);
- } else if (file.isDirectory()) {
- dirs.add(file);
- } else {
- // not URL, zip, or dir - unsure what to do
- }
- }
+ if (FileUtil.isZipFile(file)) {
+ libs.add(file);
+ } else if (file.isDirectory()) {
+ dirs.add(file);
+ } else {
+ // not URL, zip, or dir - unsure what to do
+ }
+ }
File[] dirRa = (File[]) dirs.toArray(new File[0]);
File[] libRa = (File[]) libs.toArray(new File[0]);
URL[] urlRa = (URL[]) urls.toArray(new URL[0]);
/** @return null if class not found or byte[] of class otherwise */
private byte[] readClass(String className) throws ClassNotFoundException {
final String fileName = className.replace('.', '/')+".class";
- for (Iterator<File> iter = dirs.iterator(); iter.hasNext();) {
- File file = new File(iter.next(), fileName);
- if (file.canRead()) {
- return getClassData(file);
- }
- }
+ for (File dir : dirs) {
+ File file = new File(dir, fileName);
+ if (file.canRead()) {
+ return getClassData(file);
+ }
+ }
return null;
}
return;
}
File[] files = dir.listFiles();
- for (int i = 0; i < files.length; i++) {
- String path = files[i].getPath();
- if (!files[i].getName().startsWith(".")) {
- if (files[i].isFile()) {
+ for (File file : files) {
+ String path = file.getPath();
+ if (!file.getName().startsWith(".")) {
+ if (file.isFile()) {
paths.add(path);
- } else if (files[i].isDirectory()) {
- doDirPaths(files[i], paths);
+ } else if (file.isDirectory()) {
+ doDirPaths(file, paths);
} else {
log("not file or dir: " + dir + "/" + path);
}
public void testGetURL() {
String[] args = new String[] { ".", "../util/testdata", "../lib/test/aspectjrt.jar" };
- for (int i = 0; i < args.length; i++) {
- checkGetURL(args[i]);
+ for (String arg : args) {
+ checkGetURL(arg);
}
}
sb.append(LangUtil.EOL);
}
final String contents = sb.toString();
- for (int i = 0; i < sources.length; i++) {
- File file = new File(sources[i]);
+ for (String source : sources) {
+ File file = new File(source);
FileUtil.writeAsString(file, contents);
tempFiles.add(file);
}
assertTrue(d.exists());
tempFiles.add(d);
assertTrue(d.canWrite());
- for (int i = 0; i < filenames.length; i++) {
- File f = new File(d, filenames[i]);
- assertTrue(filenames[i], f.createNewFile());
+ for (String filename : filenames) {
+ File f = new File(d, filename);
+ assertTrue(filename, f.createNewFile());
}
return d;
}
boolean containsPointcut = false;
boolean containsAnnotationClassReference = false;
Constant[] cpool = javaClass.getConstantPool().getConstantPool();
- for (int i = 0; i < cpool.length; i++) {
- Constant constant = cpool[i];
+ for (Constant constant : cpool) {
if (constant != null && constant.getTag() == Constants.CONSTANT_Utf8) {
String constantValue = ((ConstantUtf8) constant).getValue();
if (constantValue.length() > 28 && constantValue.charAt(1) == PACKAGE_INITIAL_CHAR) {
boolean hasAtPrecedenceAnnotation = false;
WeaverVersionInfo wvinfo = null;
- for (int i = 0; i < attributes.length; i++) {
- Attribute attribute = attributes[i];
+ for (Attribute attribute : attributes) {
if (acceptAttribute(attribute)) {
RuntimeAnnos rvs = (RuntimeAnnos) attribute;
// we don't need to look for several attribute occurrences since
AjAttributeMethodStruct mstruct = null;
boolean processedPointcut = false;
Attribute[] mattributes = method.getAttributes();
- for (int j = 0; j < mattributes.length; j++) {
- Attribute mattribute = mattributes[j];
+ for (Attribute mattribute : mattributes) {
if (acceptAttribute(mattribute)) {
// TODO speed all this nonsense up rather than looking
// through all the annotations every time
// code style declare error / warning / implements / parents are field
// attributes
Field[] fs = javaClass.getFields();
- for (int i = 0; i < fs.length; i++) {
- Field field = fs[i];
+ for (Field field : fs) {
if (field.getName().startsWith(NameMangler.PREFIX)) {
continue; // already dealt with by ajc...
}
AjAttributeFieldStruct fstruct = new AjAttributeFieldStruct(field, null, type, context, msgHandler);
Attribute[] fattributes = field.getAttributes();
- for (int j = 0; j < fattributes.length; j++) {
- Attribute fattribute = fattributes[j];
+ for (Attribute fattribute : fattributes) {
if (acceptAttribute(fattribute)) {
RuntimeAnnos frvs = (RuntimeAnnos) fattribute;
if (handleDeclareErrorOrWarningAnnotation(model, frvs, fstruct)
// be too silent.
boolean hasAtAspectJAnnotation = false;
boolean hasAtAspectJAnnotationMustReturnVoid = false;
- for (int i = 0; i < attributes.length; i++) {
- Attribute attribute = attributes[i];
+ for (Attribute attribute : attributes) {
try {
if (acceptAttribute(attribute)) {
RuntimeAnnos rvs = (RuntimeAnnos) attribute;
|| Modifier.isProtected(implModifiers) || Modifier.isPublic(implModifiers));
boolean hasNoCtorOrANoArgOne = true;
ResolvedMember foundOneOfIncorrectVisibility = null;
- for (int i = 0; i < mm.length; i++) {
- ResolvedMember resolvedMember = mm[i];
+ for (ResolvedMember resolvedMember : mm) {
if (resolvedMember.getName().equals("<init>")) {
hasNoCtorOrANoArgOne = false;
boolean hasAtLeastOneMethod = false;
- for (Iterator<ResolvedType> iterator = newInterfaceTypes.iterator(); iterator.hasNext();) {
- ResolvedType typeForDelegation = iterator.next();
+ for (ResolvedType typeForDelegation : newInterfaceTypes) {
// TODO check for overlapping interfaces. Eg. A implements I, I extends J - if they specify interfaces={I,J} we dont
// want to do any methods twice
ResolvedMember[] methods = typeForDelegation.getMethodsWithoutIterator(true, false, false).toArray(
new ResolvedMember[0]);
- for (int i = 0; i < methods.length; i++) {
- ResolvedMember method = methods[i];
+ for (ResolvedMember resolvedMember : methods) {
+ ResolvedMember method = resolvedMember;
if (method.isAbstract()) {
hasAtLeastOneMethod = true;
if (method.hasBackingGenericMember()) {
*/
public static int extractExtraArgument(String[] argumentSignatures) {
int extraArgument = 0;
- for (int i = 0; i < argumentSignatures.length; i++) {
- if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argumentSignatures[i])) {
+ for (String argumentSignature : argumentSignatures) {
+ if (AjcMemberMaker.TYPEX_JOINPOINT.getSignature().equals(argumentSignature)) {
extraArgument |= Advice.ThisJoinPoint;
- } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argumentSignatures[i])) {
+ } else if (AjcMemberMaker.TYPEX_PROCEEDINGJOINPOINT.getSignature().equals(argumentSignature)) {
extraArgument |= Advice.ThisJoinPoint;
- } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argumentSignatures[i])) {
+ } else if (AjcMemberMaker.TYPEX_STATICJOINPOINT.getSignature().equals(argumentSignature)) {
extraArgument |= Advice.ThisJoinPointStaticPart;
- } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argumentSignatures[i])) {
+ } else if (AjcMemberMaker.TYPEX_ENCLOSINGSTATICJOINPOINT.getSignature().equals(argumentSignature)) {
extraArgument |= Advice.ThisEnclosingJoinPointStaticPart;
}
}
LocalVariableTable lt = method.getLocalVariableTable();
if (lt != null) {
LocalVariable[] lvt = lt.getLocalVariableTable();
- for (int j = 0; j < lvt.length; j++) {
- LocalVariable localVariable = lvt[j];
+ for (LocalVariable localVariable : lvt) {
if (localVariable != null) { // pr348488
if (localVariable.getStartPC() == 0) {
if (localVariable.getIndex() >= startAtStackIndex) {
// register ImplicitBindings as to be ignored since unbound
// TODO is it likely to fail in a bad way if f.e. this(jp) etc ?
List<String> ignores = new ArrayList<String>();
- for (int i = 0; i < bindings.length; i++) {
- FormalBinding formalBinding = bindings[i];
+ for (FormalBinding formalBinding : bindings) {
if (formalBinding instanceof FormalBinding.ImplicitFormalBinding) {
ignores.add(formalBinding.getName());
}
public boolean bindsProceedingJoinPoint() {
UnresolvedType[] parameterTypes = signature.getParameterTypes();
- for (int i=0;i<parameterTypes.length;i++) {
- if (parameterTypes[i].equals(UnresolvedType.PROCEEDING_JOINPOINT)) {
+ for (UnresolvedType parameterType : parameterTypes) {
+ if (parameterType.equals(UnresolvedType.PROCEEDING_JOINPOINT)) {
return true;
}
}
ResolvedType runtimeException = world.getCoreType(UnresolvedType.RUNTIME_EXCEPTION);
ResolvedType error = world.getCoreType(UnresolvedType.ERROR);
- for (int i = 0, len = excs.length; i < len; i++) {
- ResolvedType t = world.resolve(excs[i], true);
+ for (UnresolvedType exc : excs) {
+ ResolvedType t = world.resolve(exc, true);
if (t.isMissing()) {
world.getLint().cantFindType
- .signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE, excs[i].getName()),
+ .signal(WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE, exc.getName()),
getSourceLocation());
// IMessage msg = new Message(
// WeaverMessages.format(WeaverMessages.CANT_FIND_TYPE_EXCEPTION_TYPE,excs[i].getName()),
LocalVariableTable lvt = shadow.getEnclosingMethod().getMemberView().getMethod().getLocalVariableTable();
if (lvt != null) {
LocalVariable[] lvTable = lvt.getLocalVariableTable();
- for (int i = 0; i < lvTable.length; i++) {
- LocalVariable lv = lvTable[i];
+ for (LocalVariable lv : lvTable) {
if (lv.getStartPC() == 0) {
start.addTargeter(new LocalVariableTag(lv.getSignature(), lv.getName(), lv.getIndex(), 0));
}
ArrayElementValue aev = (ArrayElementValue) envp.getValue();
ElementValue[] evs = aev.getElementValuesArray();
Set<String> targets = new HashSet<String>();
- for (int i = 0; i < evs.length; i++) {
- EnumElementValue ev = (EnumElementValue) evs[i];
+ for (ElementValue elementValue : evs) {
+ EnumElementValue ev = (EnumElementValue) elementValue;
targets.add(ev.getEnumValueString());
}
return targets;
private void initializeSuperInitializerMap(ResolvedType child) {
ResolvedType[] superInterfaces = child.getDeclaredInterfaces();
- for (int i = 0, len = superInterfaces.length; i < len; i++) {
- if (ty.getResolvedTypeX().isTopmostImplementor(superInterfaces[i])) {
- if (addSuperInitializer(superInterfaces[i])) {
- initializeSuperInitializerMap(superInterfaces[i]);
+ for (ResolvedType superInterface : superInterfaces) {
+ if (ty.getResolvedTypeX().isTopmostImplementor(superInterface)) {
+ if (addSuperInitializer(superInterface)) {
+ initializeSuperInitializerMap(superInterface);
}
}
}
// now proceed with late type mungers
if (lateTypeMungers != null) {
- for (Iterator<ConcreteTypeMunger> i = lateTypeMungers.iterator(); i.hasNext();) {
- BcelTypeMunger munger = (BcelTypeMunger) i.next();
+ for (ConcreteTypeMunger lateTypeMunger : lateTypeMungers) {
+ BcelTypeMunger munger = (BcelTypeMunger) lateTypeMunger;
if (munger.matches(clazz.getType())) {
boolean typeMungerAffectedType = munger.munge(this);
if (typeMungerAffectedType) {
boolean inSamePackage = packageName.equals(mpkg);
ResolvedMember[] methods = typeToCheck.getDeclaredMethods();
- for (int ii = 0; ii < methods.length; ii++) {
+ for (ResolvedMember methodThatMightBeGettingOverridden : methods) {
// the method we are going to check
- ResolvedMember methodThatMightBeGettingOverridden = methods[ii];
ResolvedMember isOverriding = isOverriding(typeToCheck, methodThatMightBeGettingOverridden, mname, mrettype, mmods,
inSamePackage, methodParamsArray);
if (isOverriding != null) {
// was: List l = typeToCheck.getInterTypeMungers();
List<ConcreteTypeMunger> l = (typeToCheck.isRawType() ? typeToCheck.getGenericType().getInterTypeMungers() : typeToCheck
.getInterTypeMungers());
- for (Iterator<ConcreteTypeMunger> iterator = l.iterator(); iterator.hasNext();) {
- ConcreteTypeMunger o = iterator.next();
+ for (ConcreteTypeMunger o : l) {
// FIXME asc if its not a BcelTypeMunger then its an
// EclipseTypeMunger ... do I need to worry about that?
if (o instanceof BcelTypeMunger) {
checkForOverride(superclass, mname, mparams, mrettype, mmods, mpkg, methodParamsArray,overriddenMethodsCollector);
ResolvedType[] interfaces = typeToCheck.getDeclaredInterfaces();
- for (int i = 0; i < interfaces.length; i++) {
- ResolvedType anInterface = interfaces[i];
- checkForOverride(anInterface, mname, mparams, mrettype, mmods, mpkg, methodParamsArray,overriddenMethodsCollector);
+ for (ResolvedType anInterface : interfaces) {
+ checkForOverride(anInterface, mname, mparams, mrettype, mmods, mpkg, methodParamsArray, overriddenMethodsCollector);
}
}
// Keep a set of all methods from this type - it'll help us to check if bridge methods
// have already been created, we don't want to do it twice!
Set<String> methodsSet = new HashSet<String>();
- for (int i = 0; i < methods.size(); i++) {
- LazyMethodGen aMethod = methods.get(i);
+ for (LazyMethodGen aMethod : methods) {
StringBuilder sb = new StringBuilder(aMethod.getName());
sb.append(aMethod.getSignature());
methodsSet.add(sb.toString()); // e.g. "foo(Ljava/lang/String;)V"
}
// Now go through all the methods in this type
- for (int i = 0; i < methods.size(); i++) {
+ for (LazyMethodGen bridgeToCandidate : methods) {
// This is the local method that we *might* have to bridge to
- LazyMethodGen bridgeToCandidate = methods.get(i);
if (bridgeToCandidate.isBridgeMethod()) {
continue; // Doh!
}
List<ResolvedMember> overriddenMethodsCollector = new ArrayList<ResolvedMember>();
checkForOverride(theSuperclass, name, psig, rsig, bridgeToCandidate.getAccessFlags(), pkgName, bm, overriddenMethodsCollector);
if (overriddenMethodsCollector.size() != 0) {
- for (ResolvedMember overriddenMethod: overriddenMethodsCollector) {
+ for (ResolvedMember overriddenMethod : overriddenMethodsCollector) {
String key = new StringBuilder(overriddenMethod.getName()).append(overriddenMethod.getSignatureErased()).toString(); // pr237419
boolean alreadyHaveABridgeMethod = methodsSet.contains(key);
if (!alreadyHaveABridgeMethod) {
// Check superinterfaces
String[] interfaces = clazz.getInterfaceNames();
- for (int j = 0; j < interfaces.length; j++) {
+ for (String anInterface : interfaces) {
if (world.forDEBUG_bridgingCode) {
- System.err.println("Bridging:checking superinterface " + interfaces[j]);
+ System.err.println("Bridging:checking superinterface " + anInterface);
}
- ResolvedType interfaceType = world.resolve(interfaces[j]);
+ ResolvedType interfaceType = world.resolve(anInterface);
overriddenMethodsCollector.clear();
checkForOverride(interfaceType, name, psig, rsig, bridgeToCandidate.getAccessFlags(),
clazz.getPackageName(), bm, overriddenMethodsCollector);
- for (ResolvedMember overriddenMethod: overriddenMethodsCollector) {
+ for (ResolvedMember overriddenMethod : overriddenMethodsCollector) {
String key = new StringBuffer().append(overriddenMethod.getName()).append(overriddenMethod.getSignatureErased()).toString(); // pr237419
boolean alreadyHaveABridgeMethod = methodsSet.contains(key);
if (!alreadyHaveABridgeMethod) {
private boolean weaveAtFieldRepeatedly(List<DeclareAnnotation> decaFs, List<ConcreteTypeMunger> itdFields,
List<Integer> reportedErrors) {
boolean isChanged = false;
- for (Iterator<ConcreteTypeMunger> iter = itdFields.iterator(); iter.hasNext();) {
- BcelTypeMunger fieldMunger = (BcelTypeMunger) iter.next();
+ for (ConcreteTypeMunger itdField : itdFields) {
+ BcelTypeMunger fieldMunger = (BcelTypeMunger) itdField;
ResolvedMember itdIsActually = fieldMunger.getSignature();
Set<DeclareAnnotation> worthRetrying = new LinkedHashSet<DeclareAnnotation>();
boolean modificationOccured = false;
- for (Iterator<DeclareAnnotation> iter2 = decaFs.iterator(); iter2.hasNext();) {
- DeclareAnnotation decaF = iter2.next();
+ for (DeclareAnnotation decaF : decaFs) {
if (decaF.matches(itdIsActually, world)) {
if (decaF.isRemover()) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger);
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
- for (Iterator<DeclareAnnotation> iter2 = worthRetrying.iterator(); iter2.hasNext();) {
- DeclareAnnotation decaF = iter2.next();
+ for (DeclareAnnotation decaF : worthRetrying) {
if (decaF.matches(itdIsActually, world)) {
if (decaF.isRemover()) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, fieldMunger);
List<DeclareAnnotation> worthRetrying = new ArrayList<DeclareAnnotation>();
boolean modificationOccured = false;
- for (Iterator<DeclareAnnotation> iter2 = decaMCs.iterator(); iter2.hasNext();) {
- DeclareAnnotation decaMC = iter2.next();
+ for (DeclareAnnotation decaMC : decaMCs) {
if (decaMC.matches(unMangledInterMethod, world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForMethodCtorMunger(clazz, methodctorMunger);
if (annotationHolder == null
while (!worthRetrying.isEmpty() && modificationOccured) {
modificationOccured = false;
List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
- for (Iterator<DeclareAnnotation> iter2 = worthRetrying.iterator(); iter2.hasNext();) {
- DeclareAnnotation decaMC = iter2.next();
+ for (DeclareAnnotation decaMC : worthRetrying) {
if (decaMC.matches(unMangledInterMethod, world)) {
LazyMethodGen annotationHolder = locateAnnotationHolderForFieldMunger(clazz, methodctorMunger);
if (doesAlreadyHaveAnnotation(annotationHolder, unMangledInterMethod, decaMC, reportedErrors)) {
modificationOccured = false;
// lets have another go with any remaining ones
List<DeclareAnnotation> forRemoval = new ArrayList<DeclareAnnotation>();
- for (Iterator<DeclareAnnotation> iter = worthRetrying.iterator(); iter.hasNext();) {
- DeclareAnnotation decaF = iter.next();
-
+ for (DeclareAnnotation decaF : worthRetrying) {
if (decaF.matches(field, world)) {
if (decaF.isRemover()) {
AnnotationAJ annotation = decaF.getAnnotation();
} else {
// below code is for recursive things
unusedDecafs.remove(decaF);
- if (doesAlreadyHaveAnnotation(field, decaF, reportedProblems,true)) {
+ if (doesAlreadyHaveAnnotation(field, decaF, reportedProblems, true)) {
continue;
}
field.addAnnotation(decaF.getAnnotation());
// the load instruction
// (so we never jump over the monitorexit logic)
- for (Iterator<InstructionHandle> iter = rets.iterator(); iter.hasNext();) {
- InstructionHandle element = iter.next();
+ for (InstructionHandle element : rets) {
InstructionList monitorExitBlock = new InstructionList();
monitorExitBlock.append(InstructionFactory.createLoad(enclosingClassType, slotForLockObject));
monitorExitBlock.append(InstructionConstants.MONITOREXIT);
// load instruction
// (so we never jump over the monitorexit logic)
- for (Iterator<InstructionHandle> iter = rets.iterator(); iter.hasNext();) {
- InstructionHandle element = iter.next();
+ for (InstructionHandle element : rets) {
// System.err.println("Adding monitor exit block at "+element
// );
InstructionList monitorExitBlock = new InstructionList();
donorFramePos += 1;
}
Type[] argTypes = donor.getArgumentTypes();
- for (int i = 0, len = argTypes.length; i < len; i++) {
- Type argType = argTypes[i];
+ for (Type argType : argTypes) {
int argSlot = recipient.allocateLocal(argType);
ret.insert(InstructionFactory.createStore(argType, argSlot));
frameEnv.put(donorFramePos, argSlot);
// now add interface inits
if (!isThisCall(superOrThisCall)) {
InstructionHandle curr = enclosingShadow.getRange().getStart();
- for (Iterator<IfaceInitList> i = addedSuperInitializersAsList.iterator(); i.hasNext();) {
- IfaceInitList l = i.next();
-
+ for (IfaceInitList l : addedSuperInitializersAsList) {
Member ifaceInitSig = AjcMemberMaker.interfaceConstructor(l.onType);
BcelShadow initShadow = BcelShadow.makeIfaceInitialization(world, mg, ifaceInitSig);
*/
private ResolvedMember findResolvedMemberNamed(ResolvedType type, String methodName) {
ResolvedMember[] allMethods = type.getDeclaredMethods();
- for (int i = 0; i < allMethods.length; i++) {
- ResolvedMember member = allMethods[i];
+ for (ResolvedMember member : allMethods) {
if (member.getName().equals(methodName)) {
return member;
}
private ResolvedMember findResolvedMemberNamed(ResolvedType type, String methodName, UnresolvedType[] params) {
ResolvedMember[] allMethods = type.getDeclaredMethods();
List<ResolvedMember> candidates = new ArrayList<ResolvedMember>();
- for (int i = 0; i < allMethods.length; i++) {
- ResolvedMember candidate = allMethods[i];
+ for (ResolvedMember candidate : allMethods) {
if (candidate.getName().equals(methodName)) {
if (candidate.getArity() == params.length) {
candidates.add(candidate);
Map<GenericSignature.FormalTypeParameter, ReferenceType> inProgressTypeVariableResolutions)
throws GenericSignatureFormatException {
GenericSignature.FormalTypeParameter typeVarBounds = null;
- for (int i = 0; i < typeParams.length; i++) {
- if (typeParams[i].identifier.equals(aTypeVarSig.typeVariableName)) {
- typeVarBounds = typeParams[i];
+ for (GenericSignature.FormalTypeParameter typeParam : typeParams) {
+ if (typeParam.identifier.equals(aTypeVarSig.typeVariableName)) {
+ typeVarBounds = typeParam;
break;
}
}
ReferenceType rt = (ReferenceType) aTypeX;
TypeVariable[] typeVars = rt.getTypeVariables();
if (typeVars != null) {
- for (int i = 0; i < typeVars.length; i++) {
- if (typeVars[i].getUpperBound() instanceof FTPHolder) {
- GenericSignature.FormalTypeParameter key = ((FTPHolder) typeVars[i].getUpperBound()).ftpToBeSubstituted;
- typeVars[i].setUpperBound(typeVariableResolutions.get(key));
+ for (TypeVariable typeVar : typeVars) {
+ if (typeVar.getUpperBound() instanceof FTPHolder) {
+ GenericSignature.FormalTypeParameter key = ((FTPHolder) typeVar.getUpperBound()).ftpToBeSubstituted;
+ typeVar.setUpperBound(typeVariableResolutions.get(key));
}
}
}
AnnotationAJ[] annos = getAnnotations();
if (annos != null && annos.length != 0) {
AnnotationAJ[] axs = getAnnotations();
- for (int i = 0; i < axs.length; i++) {
- AnnotationAJ annotationX = axs[i];
+ for (AnnotationAJ annotationX : axs) {
String typename = annotationX.getTypeName();
if (typename.charAt(0) == PACKAGE_INITIAL_CHAR) {
if (typename.equals("org.aspectj.lang.annotation.Pointcut")
while (argsList.size() < requiredCount) {
argsList.add("arg" + argsList.size());
}
- setParameterNames(argsList.toArray(new String[] {}));
+ setParameterNames(argsList.toArray(new String[]{}));
return;
}
}
@Override
public String getAnnotationDefaultValue() {
Attribute[] attrs = method.getAttributes();
- for (int i = 0; i < attrs.length; i++) {
- Attribute attribute = attrs[i];
+ for (Attribute attribute : attrs) {
if (attribute.getName().equals("AnnotationDefault")) {
AnnotationDefault def = (AnnotationDefault) attribute;
return def.getElementValue().stringifyValue();
Attribute[] as = method.getAttributes();
List<String> names = new ArrayList<String>();
// String[] strs = new String[as.length];
- for (int j = 0; j < as.length; j++) {
- if (!onlyIncludeAjOnes || as[j].getName().startsWith(AjAttribute.AttributePrefix)) {
- names.add(as[j].getName());
+ for (Attribute a : as) {
+ if (!onlyIncludeAjOnes || a.getName().startsWith(AjAttribute.AttributePrefix)) {
+ names.add(a.getName());
}
}
return names.toArray(new String[] {});
if ((bitflags & HAS_ANNOTATIONS) == 0) {
return null;
}
- for (int i = 0; i < annotations.length; i++) {
- if (annotations[i].getTypeName().equals(ofType.getName())) {
- return annotations[i];
+ for (AnnotationAJ annotation : annotations) {
+ if (annotation.getTypeName().equals(ofType.getName())) {
+ return annotation;
}
}
return null;
// synthetic is an attribute
String[] synthetics = getAttributeNames(false);
if (synthetics != null) {
- for (int i = 0; i < synthetics.length; i++) {
- if (synthetics[i].equals("Synthetic")) {
+ for (String synthetic : synthetics) {
+ if (synthetic.equals("Synthetic")) {
bitflags |= IS_SYNTHETIC;
break;
}
private void resolveAnnotationDeclares(List<AjAttribute> attributeList) {
FormalBinding[] bindings = new org.aspectj.weaver.patterns.FormalBinding[0];
IScope bindingScope = new BindingScope(getResolvedTypeX(), getResolvedTypeX().getSourceContext(), bindings);
- for (Iterator<AjAttribute> iter = attributeList.iterator(); iter.hasNext();) {
- AjAttribute a = iter.next();
+ for (AjAttribute a : attributeList) {
if (a instanceof AjAttribute.DeclareAttribute) {
Declare decl = (((AjAttribute.DeclareAttribute) a).getDeclare());
if (decl instanceof DeclareErrorOrWarning) {
return false;
} else {
String lookingForSignature = ofType.getSignature();
- for (int a = 0; a < annos.length; a++) {
- AnnotationGen annotation = annos[a];
+ for (AnnotationGen annotation : annos) {
if (lookingForSignature.equals(annotation.getTypeSignature())) {
return true;
}
AnnotationAJ ax = annotations[i];
if (ax.getTypeName().equals(UnresolvedType.AT_RETENTION.getName())) {
List<NameValuePair> values = ((BcelAnnotation) ax).getBcelAnnotation().getValues();
- for (Iterator<NameValuePair> it = values.iterator(); it.hasNext();) {
- NameValuePair element = it.next();
+ for (NameValuePair element : values) {
EnumElementValue v = (EnumElementValue) element.getValue();
retentionPolicy = v.getEnumValueString();
return retentionPolicy;
if (targetKinds == null) {
return true;
}
- for (int i = 0; i < targetKinds.length; i++) {
- if (targetKinds[i].equals(AnnotationTargetKind.TYPE)) {
+ for (AnnotationTargetKind targetKind : targetKinds) {
+ if (targetKind.equals(AnnotationTargetKind.TYPE)) {
return true;
}
}
List<AnnotationTargetKind> targetKinds = new ArrayList<AnnotationTargetKind>();
if (isAnnotation()) {
AnnotationAJ[] annotationsOnThisType = getAnnotations();
- for (int i = 0; i < annotationsOnThisType.length; i++) {
- AnnotationAJ a = annotationsOnThisType[i];
+ for (AnnotationAJ a : annotationsOnThisType) {
if (a.getTypeName().equals(UnresolvedType.AT_TARGET.getName())) {
Set<String> targets = a.getTargets();
if (targets != null) {
GenericSignature.FormalTypeParameter[] extraFormals = getFormalTypeParametersFromOuterClass();
if (extraFormals.length > 0) {
List<FormalTypeParameter> allFormals = new ArrayList<FormalTypeParameter>();
- for (int i = 0; i < formalsForResolution.length; i++) {
- allFormals.add(formalsForResolution[i]);
+ for (FormalTypeParameter formalTypeParameter : formalsForResolution) {
+ allFormals.add(formalTypeParameter);
}
- for (int i = 0; i < extraFormals.length; i++) {
- allFormals.add(extraFormals[i]);
+ for (FormalTypeParameter extraFormal : extraFormals) {
+ allFormals.add(extraFormal);
}
formalsForResolution = new GenericSignature.FormalTypeParameter[allFormals.size()];
allFormals.toArray(formalsForResolution);
s.mungers = new ArrayList<ShadowMunger>();
}
List<ShadowMunger> dest = s.mungers;
- for (Iterator<ShadowMunger> i = src.iterator(); i.hasNext();) {
- dest.add(i.next());
+ for (ShadowMunger shadowMunger : src) {
+ dest.add(shadowMunger);
}
}
return s;
// something stopped us making it a lazy tjp
// can't build tjp lazily, no suitable test...
int valid = 0;
- for (Iterator<BcelAdvice> iter = badAdvice.iterator(); iter.hasNext();) {
- BcelAdvice element = iter.next();
+ for (BcelAdvice element : badAdvice) {
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc != null && sLoc.getLine() > 0) {
valid++;
if (valid != 0) {
ISourceLocation[] badLocs = new ISourceLocation[valid];
int i = 0;
- for (Iterator<BcelAdvice> iter = badAdvice.iterator(); iter.hasNext();) {
- BcelAdvice element = iter.next();
+ for (BcelAdvice element : badAdvice) {
ISourceLocation sLoc = element.getSourceLocation();
if (sLoc != null) {
badLocs[i++] = sLoc;
private boolean checkLazyTjp() {
// check for around advice
- for (Iterator<ShadowMunger> i = mungers.iterator(); i.hasNext();) {
- ShadowMunger munger = i.next();
+ for (ShadowMunger munger : mungers) {
if (munger instanceof Advice) {
if (((Advice) munger).getKind() == AdviceKind.Around) {
if (munger.getSourceLocation() != null) { // do we know enough to bother reporting?
if (world.getLint().canNotImplementLazyTjp.isEnabled()) {
- world.getLint().canNotImplementLazyTjp.signal(new String[] { toString() }, getSourceLocation(),
- new ISourceLocation[] { munger.getSourceLocation() });
+ world.getLint().canNotImplementLazyTjp.signal(new String[]{toString()}, getSourceLocation(),
+ new ISourceLocation[]{munger.getSourceLocation()});
}
}
return false;
ResolvedType[] rtx = this.getTargetType().resolve(world).getAnnotationTypes(); // what about annotations we havent
// gotten yet but we will get in
// subclasses?
- for (int i = 0; i < rtx.length; i++) {
- ResolvedType typeX = rtx[i];
+ for (ResolvedType typeX : rtx) {
targetAnnotationVars.put(typeX, new TypeAnnotationAccessVar(typeX, (BcelVar) getTargetVar()));
}
// populate.
if (foundMember == null) {
// check the ITD'd dooberries
List<ConcreteTypeMunger> mungers = relevantType.resolve(world).getInterTypeMungers();
- for (Iterator<ConcreteTypeMunger> iter = mungers.iterator(); iter.hasNext();) {
- Object munger = iter.next();
+ for (Object munger : mungers) {
ConcreteTypeMunger typeMunger = (ConcreteTypeMunger) munger;
if (typeMunger.getMunger() instanceof NewMethodTypeMunger
|| typeMunger.getMunger() instanceof NewConstructorTypeMunger) {
private ResolvedMember findMethod(ResolvedType aspectType, ResolvedMember ajcMethod) {
ResolvedMember decMethods[] = aspectType.getDeclaredMethods();
- for (int i = 0; i < decMethods.length; i++) {
- ResolvedMember member = decMethods[i];
+ for (ResolvedMember member : decMethods) {
if (member.equals(ajcMethod)) {
return member;
}
}
private ResolvedMember findField(ResolvedMember[] members, Member lookingFor) {
- for (int i = 0; i < members.length; i++) {
- ResolvedMember member = members[i];
+ for (ResolvedMember member : members) {
if (member.getName().equals(getSignature().getName()) && member.getType().equals(getSignature().getType())) {
return member;
}
withinAnnotationVars = new HashMap<ResolvedType, AnnotationAccessVar>();
ResolvedType[] annotations = getEnclosingType().resolve(world).getAnnotationTypes();
- for (int i = 0; i < annotations.length; i++) {
- ResolvedType ann = annotations[i];
+ for (ResolvedType ann : annotations) {
Kind k = Shadow.StaticInitialization;
withinAnnotationVars.put(ann, new AnnotationAccessVar(this, k, ann, getEnclosingType(), null, true));
}
// For some shadow we are interested in annotations on the method containing that shadow.
ResolvedType[] annotations = getEnclosingMethod().getMemberView().getAnnotationTypes();
- for (int i = 0; i < annotations.length; i++) {
- ResolvedType ann = annotations[i];
+ for (ResolvedType ann : annotations) {
Kind k = (getEnclosingMethod().getMemberView().getKind() == Member.CONSTRUCTOR ? Shadow.ConstructorExecution
: Shadow.MethodExecution);
withincodeAnnotationVars.put(ann, new AnnotationAccessVar(this, k, ann, getEnclosingType(),
if (hasReturnInstructions) {
InstructionHandle gotoTarget = advice.getStart();
- for (Iterator<InstructionHandle> i = returns.iterator(); i.hasNext();) {
- InstructionHandle ih = i.next();
+ for (InstructionHandle ih : returns) {
retargetReturnInstruction(munger.hasExtraParameter(), returnValueVar, gotoTarget, ih);
}
}
InstructionList advice = new InstructionList();
// InstructionHandle adviceMethodInvocation;
{
- for (Iterator<BcelVar> i = argsToCallLocalAdviceMethodWith.iterator(); i.hasNext();) {
- BcelVar var = i.next();
+ for (BcelVar var : argsToCallLocalAdviceMethodWith) {
var.appendLoad(advice, fact);
}
// ??? we don't actually need to push NULL for the closure if we take care
if (targetVar != null && targetVar != thisVar) {
ret.put(targetVar.getSlot(), reti++);
}
- for (int i = 0, len = argVars.length; i < len; i++) {
- ret.put(argVars[i].getSlot(), reti);
- reti += argVars[i].getType().getSize();
+ for (BcelVar argVar : argVars) {
+ ret.put(argVar.getSlot(), reti);
+ reti += argVar.getType().getSize();
}
if (thisJoinPointVar != null) {
ret.put(thisJoinPointVar.getSlot(), reti++);
addMethodDispatch(gen, member, AjcMemberMaker.privilegedAccessMethodForMethod(aspectType, member));
return true;
} else if (member.getKind() == Member.CONSTRUCTOR) {
- for (Iterator<LazyMethodGen> i = gen.getMethodGens().iterator(); i.hasNext();) {
- LazyMethodGen m = i.next();
+ for (LazyMethodGen m : gen.getMethodGens()) {
if (m.getMemberView() != null && m.getMemberView().getKind() == Member.CONSTRUCTOR) {
// m.getMemberView().equals(member)) {
m.forcePublic();
il.append(InstructionConstants.ALOAD_0);
pos++;
}
- for (int i = 0, len = paramTypes.length; i < len; i++) {
- Type paramType = paramTypes[i];
+ for (Type paramType : paramTypes) {
il.append(InstructionFactory.createLoad(paramType, pos));
pos += paramType.getSize();
}
pos++;
}
Type[] paramTypes = BcelWorld.makeBcelTypes(mangledInterMethod.getParameterTypes());
- for (int i = 0, len = paramTypes.length; i < len; i++) {
- Type paramType = paramTypes[i];
+ for (Type paramType : paramTypes) {
body.append(InstructionFactory.createLoad(paramType, pos));
pos += paramType.getSize();
}
body.append(InstructionFactory.createThis());
pos++;
}
- for (int i = 0, len = paramTypes.length; i < len; i++) {
- Type paramType = paramTypes[i];
+ for (Type paramType : paramTypes) {
body.append(InstructionFactory.createLoad(paramType, pos));
pos += paramType.getSize();
}
// Step1
boolean alreadyDone = false; // Compiler might have done it
ResolvedMember[] localMethods = onType.getDeclaredMethods();
- for (int i = 0; i < localMethods.length; i++) {
- ResolvedMember member = localMethods[i];
+ for (ResolvedMember member : localMethods) {
if (member.getName().equals(localMethodName)) {
// Check the params
if (member.getParameterSignature().equals(localParameterSig)) {
body.append(InstructionFactory.createThis());
pos++;
}
- for (int i = 0, len = paramTypes.length; i < len; i++) {
- Type paramType = paramTypes[i];
+ for (Type paramType : paramTypes) {
body.append(InstructionFactory.createLoad(paramType, pos));
// if (!bridgingSetter.getParameterTypes()[i].getErasureSignature().
// equals
pos++;
}
Type[] paramTypes = BcelWorld.makeBcelTypes(introduced.getParameterTypes());
- for (int i = 0, len = paramTypes.length; i < len; i++) {
- Type paramType = paramTypes[i];
+ for (Type paramType : paramTypes) {
body.append(InstructionFactory.createLoad(paramType, pos));
pos += paramType.getSize();
}
annotationsOnRealMember = realMember.getAnnotations();
}
if (annotationsOnRealMember != null) {
- for (int i = 0; i < annotationsOnRealMember.length; i++) {
- AnnotationAJ annotationX = annotationsOnRealMember[i];
+ for (AnnotationAJ annotationX : annotationsOnRealMember) {
AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
mg.addAnnotation(new BcelAnnotation(ag, weaver.getWorld()));
// case where an aspect declares an annotation
// on an ITD it declared on itself.
List<DeclareAnnotation> allDecams = weaver.getWorld().getDeclareAnnotationOnMethods();
- for (Iterator<DeclareAnnotation> i = allDecams.iterator(); i.hasNext();) {
- DeclareAnnotation decaMC = i.next();
+ for (DeclareAnnotation decaMC : allDecams) {
if (decaMC.matches(explicitConstructor, weaver.getWorld()) && mg.getEnclosingClass().getType() == aspectType) {
mg.addAnnotation(decaMC.getAnnotation());
}
body.append(InstructionFactory.createThis());
pos++;
- for (int i = 0, len = paramTypes.length; i < len; i++) {
- Type paramType = paramTypes[i];
+ for (Type paramType : paramTypes) {
body.append(InstructionFactory.createLoad(paramType, pos));
pos += paramType.getSize();
}
FieldGen fg = makeFieldGen(gen, newField);
if (annotationsOnRealMember != null) {
- for (int i = 0; i < annotationsOnRealMember.length; i++) {
- AnnotationAJ annotationX = annotationsOnRealMember[i];
+ for (AnnotationAJ annotationX : annotationsOnRealMember) {
AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
fg.addAnnotation(ag);
weaver.addInitializer(this);
FieldGen fg = makeFieldGen(gen,newField);
if (annotationsOnRealMember != null) {
- for (int i = 0; i < annotationsOnRealMember.length; i++) {
- AnnotationAJ annotationX = annotationsOnRealMember[i];
+ for (AnnotationAJ annotationX : annotationsOnRealMember) {
AnnotationGen a = ((BcelAnnotation) annotationX).getBcelAnnotation();
AnnotationGen ag = new AnnotationGen(a, weaver.getLazyClassGen().getConstantPool(), true);
fg.addAnnotation(ag);
});
// For each file, add it either as a real .class file or as a resource
- for (int i = 0; i < files.length; i++) {
- addedClassFiles.add(addClassFile(files[i], inFile, outDir));
+ for (File file : files) {
+ addedClassFiles.add(addClassFile(file, inFile, outDir));
}
return addedClassFiles;
needToReweaveWorld = xcutSet.hasChangedSinceLastReset();
// update mungers
- for (Iterator<UnwovenClassFile> i = addedClasses.iterator(); i.hasNext();) {
- UnwovenClassFile jc = i.next();
+ for (UnwovenClassFile jc : addedClasses) {
String name = jc.getClassName();
ResolvedType type = world.resolve(name);
// No overweaving guard. If you have one then when overweaving is on the
}
}
- for (Iterator<String> i = deletedTypenames.iterator(); i.hasNext();) {
- String name = i.next();
+ for (String name : deletedTypenames) {
if (xcutSet.deleteAspect(UnresolvedType.forName(name))) {
needToReweaveWorld = true;
}
private void addCustomMungers() {
if (customMungerFactory != null) {
- for (Iterator<UnwovenClassFile> i = addedClasses.iterator(); i.hasNext();) {
- UnwovenClassFile jc = i.next();
+ for (UnwovenClassFile jc : addedClasses) {
String name = jc.getClassName();
ResolvedType type = world.resolve(name);
if (type.isAspect()) {
} else if (pc instanceof ConcreteCflowPointcut) {
ConcreteCflowPointcut cfp = (ConcreteCflowPointcut) pc;
int[] slots = cfp.getUsedFormalSlots();
- for (int i = 0; i < slots.length; i++) {
- bindings[slots[i]] = cfp;
- if (foundFormals[slots[i]]) {
- raiseAmbiguousBindingError(names[slots[i]], userPointcut);
+ for (int slot : slots) {
+ bindings[slot] = cfp;
+ if (foundFormals[slot]) {
+ raiseAmbiguousBindingError(names[slot], userPointcut);
} else {
- foundFormals[slots[i]] = true;
+ foundFormals[slot] = true;
}
}
}
selfMunger.forceMunge(clazz, true);
classType.finishedWith();
UnwovenClassFile[] newClasses = getClassFilesFor(clazz);
- for (int news = 0; news < newClasses.length; news++) {
- requestor.acceptResult(newClasses[news]);
+ for (UnwovenClassFile newClass : newClasses) {
+ requestor.acceptResult(newClass);
}
wovenClassNames.add(classFile.getClassName());
}
List l = world.getCrosscuttingMembersSet().getShadowMungers();
Set<AdviceLocation> alreadyWarnedLocations = new HashSet<AdviceLocation>();
- for (Iterator iter = l.iterator(); iter.hasNext();) {
- ShadowMunger element = (ShadowMunger) iter.next();
+ for (Object o : l) {
+ ShadowMunger element = (ShadowMunger) o;
// This will stop us incorrectly reporting deow checkers:
if (element instanceof BcelAdvice) {
BcelAdvice ba = (BcelAdvice) element;
if (newClasses[0].getClassName().equals(classFile.getClassName())) {
newClasses[0].setClassNameAsChars(classFile.getClassNameAsChars());
}
- for (int i = 0; i < newClasses.length; i++) {
- requestor.acceptResult(newClasses[i]);
+ for (UnwovenClassFile newClass : newClasses) {
+ requestor.acceptResult(newClass);
}
} else {
requestor.acceptResult(classFile);
UnwovenClassFile[] ret = new UnwovenClassFile[1 + childClasses.size()];
ret[0] = new UnwovenClassFile(clazz.getFileName(), clazz.getClassName(), clazz.getJavaClassBytesIncludingReweavable(world));
int index = 1;
- for (Iterator<UnwovenClassFile.ChildClass> iter = childClasses.iterator(); iter.hasNext();) {
- UnwovenClassFile.ChildClass element = iter.next();
+ for (UnwovenClassFile.ChildClass element : childClasses) {
UnwovenClassFile childClass = new UnwovenClassFile(clazz.getFileName() + "$" + element.name, element.bytes);
ret[index++] = childClass;
}
while ((aParentChangeOccurred || anAnnotationChangeOccurred) && !decpToRepeat.isEmpty()) {
anAnnotationChangeOccurred = aParentChangeOccurred = false;
List<DeclareParents> decpToRepeatNextTime = new ArrayList<DeclareParents>();
- for (Iterator<DeclareParents> iter = decpToRepeat.iterator(); iter.hasNext();) {
- DeclareParents decp = iter.next();
+ for (DeclareParents decp : decpToRepeat) {
boolean typeChanged = applyDeclareParents(decp, onType);
if (typeChanged) {
aParentChangeOccurred = true;
writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass(world).getBytes());
List<UnwovenClassFile.ChildClass> childClasses = clazz.getChildClasses(world);
if (!childClasses.isEmpty()) {
- for (Iterator<UnwovenClassFile.ChildClass> i = childClasses.iterator(); i.hasNext();) {
- UnwovenClassFile.ChildClass c = i.next();
+ for (UnwovenClassFile.ChildClass c : childClasses) {
writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes);
}
}
boolean aParentChangeOccurred = false;
boolean anAnnotationChangeOccurred = false;
// First pass - apply all decp mungers
- for (Iterator<DeclareParents> i = declareParentsList.iterator(); i.hasNext();) {
- DeclareParents decp = i.next();
+ for (DeclareParents decp : declareParentsList) {
boolean typeChanged = applyDeclareParents(decp, onType);
if (typeChanged) {
aParentChangeOccurred = true;
public String toString() {
StringBuffer buf = new StringBuffer();
boolean start = true;
- for (Iterator<Entry> i = entries.iterator(); i.hasNext();) {
+ for (Entry entry : entries) {
if (start) {
start = false;
} else {
buf.append(File.pathSeparator);
}
- buf.append(i.next());
+ buf.append(entry);
}
return buf.toString();
}
hasSerialVersionUIDField = hasSerialVersionUIDField(getType());
ResolvedMember[] methods = getType().getDeclaredMethods();
- for (int i = 0; i < methods.length; i++) {
- ResolvedMember method = methods[i];
- if (method.getName().equals("<clinit>")) {
- if (method.getKind() != Member.STATIC_INITIALIZATION) {
- throw new RuntimeException("qui?");
- }
- hasClinit = true;
- }
- }
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals("<clinit>")) {
+ if (method.getKind() != Member.STATIC_INITIALIZATION) {
+ throw new RuntimeException("qui?");
+ }
+ hasClinit = true;
+ }
+ }
// Do we need to calculate an SUID and add it?
if (!getType().isInterface() && !hasSerialVersionUIDField && world.isAddSerialVerUID()) {
}
ResolvedMember[] methods = myType.getDeclaredMethods();
- for (int i = 0; i < methods.length; i++) {
- addMethodGen(new LazyMethodGen((BcelMethod) methods[i], this));
- }
+ for (ResolvedMember method : methods) {
+ addMethodGen(new LazyMethodGen((BcelMethod) method, this));
+ }
// Method[] methods = myGen.getMethods();
// for (int i = 0; i < methods.length; i++) {
// }
ResolvedMember[] fields = myType.getDeclaredFields();
- for (int i = 0; i < fields.length; i++) {
- this.fields.add((BcelField) fields[i]);
- }
+ for (ResolvedMember field : fields) {
+ this.fields.add((BcelField) field);
+ }
}
public static boolean hasSerialVersionUIDField(ResolvedType type) {
ResolvedMember[] fields = type.getDeclaredFields();
- for (int i = 0; i < fields.length; i++) {
- ResolvedMember field = fields[i];
- if (field.getName().equals("serialVersionUID") && Modifier.isStatic(field.getModifiers())
- && field.getType().equals(UnresolvedType.LONG)) {
- return true;
- }
- }
+ for (ResolvedMember field : fields) {
+ if (field.getName().equals("serialVersionUID") && Modifier.isStatic(field.getModifiers())
+ && field.getType().equals(UnresolvedType.LONG)) {
+ return true;
+ }
+ }
return false;
}
if (!needAttribute) {
if (myType != null) {
ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces();
- for (int i = 0; i < interfaceRTXs.length; i++) {
- ResolvedType typeX = interfaceRTXs[i];
- if (typeX.isGenericType() || typeX.isParameterizedType()) {
- needAttribute = true;
- }
- }
+ for (ResolvedType typeX : interfaceRTXs) {
+ if (typeX.isGenericType() || typeX.isParameterizedType()) {
+ needAttribute = true;
+ }
+ }
if (extraSuperInterfaces != null) {
- for (int i = 0; i < extraSuperInterfaces.length; i++) {
- ResolvedType interfaceType = extraSuperInterfaces[i];
- if (interfaceType.isGenericType() || interfaceType.isParameterizedType()) {
- needAttribute = true;
- }
- }
+ for (ResolvedType interfaceType : extraSuperInterfaces) {
+ if (interfaceType.isGenericType() || interfaceType.isParameterizedType()) {
+ needAttribute = true;
+ }
+ }
}
}
TypeVariable[] tVars = myType.getTypeVariables();
if (tVars.length > 0) {
signature.append("<");
- for (int i = 0; i < tVars.length; i++) {
- TypeVariable variable = tVars[i];
- signature.append(variable.getSignatureForAttribute());
- }
+ for (TypeVariable variable : tVars) {
+ signature.append(variable.getSignatureForAttribute());
+ }
signature.append(">");
}
}
signature.append(supersig);
if (myType != null) {
ResolvedType[] interfaceRTXs = myType.getDeclaredInterfaces();
- for (int i = 0; i < interfaceRTXs.length; i++) {
- String s = interfaceRTXs[i].getSignatureForAttribute();
- signature.append(s);
- }
+ for (ResolvedType interfaceRTX : interfaceRTXs) {
+ String s = interfaceRTX.getSignatureForAttribute();
+ signature.append(s);
+ }
if (extraSuperInterfaces != null) {
- for (int i = 0; i < extraSuperInterfaces.length; i++) {
- String s = extraSuperInterfaces[i].getSignatureForAttribute();
- signature.append(s);
- }
+ for (ResolvedType extraSuperInterface : extraSuperInterfaces) {
+ String s = extraSuperInterface.getSignatureForAttribute();
+ signature.append(s);
+ }
}
}
if (sigAttr != null) {
myType.printWackyStuff(out);
}
Field[] fields = myGen.getFields();
- for (int i = 0, len = fields.length; i < len; i++) {
- out.print(" ");
- out.println(fields[i]);
- }
+ for (Field field : fields) {
+ out.print(" ");
+ out.println(field);
+ }
List<LazyMethodGen> methodGens = getMethodGens();
for (Iterator<LazyMethodGen> iter = methodGens.iterator(); iter.hasNext();) {
LazyMethodGen gen = iter.next();
});
long estimatedSize = 0;
- for (Iterator<Map.Entry<BcelShadow, Field>> i = entries.iterator(); i.hasNext();) {
- Map.Entry<BcelShadow, Field> entry = i.next();
- if (estimatedSize > Constants.MAX_CODE_SIZE) {
- estimatedSize = 0;
- list = initInstructionList();
- lists.add(list);
- }
- estimatedSize += entry.getValue().getSignature().getBytes().length;
- initializeTjp(fact, list, entry.getValue(), entry.getKey());
- }
+ for (Map.Entry<BcelShadow, Field> entry : entries) {
+ if (estimatedSize > Constants.MAX_CODE_SIZE) {
+ estimatedSize = 0;
+ list = initInstructionList();
+ lists.add(list);
+ }
+ estimatedSize += entry.getValue().getSignature().getBytes().length;
+ initializeTjp(fact, list, entry.getValue(), entry.getKey());
+ }
InstructionList listArrayModel[] = new InstructionList[1];
return lists.toArray(listArrayModel);
}
}
private boolean hasSyntheticAttribute(List<Attribute> attributes) {
- for (int i = 0; i < attributes.size(); i++) {
- if ((attributes.get(i)).getName().equals("Synthetic")) {
- return true;
- }
- }
+ for (Attribute attribute : attributes) {
+ if (attribute.getName().equals("Synthetic")) {
+ return true;
+ }
+ }
return false;
}
if (agens == null) {
return false;
}
- for (int i = 0; i < agens.length; i++) {
- AnnotationGen gen = agens[i];
- if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) {
- return true;
- }
- }
+ for (AnnotationGen gen : agens) {
+ if (t.equals(UnresolvedType.forSignature(gen.getTypeSignature()))) {
+ return true;
+ }
+ }
// annotations added during this weave
}
ResolvedType[] interfaces = aType.getDeclaredInterfaces();
- for (int i = 0; i < interfaces.length; i++) {
- if (interfaces[i].isMissing()) {
- continue;
- }
- if (implementsSerializable(interfaces[i])) {
- return true;
- }
- }
+ for (ResolvedType anInterface : interfaces) {
+ if (anInterface.isMissing()) {
+ continue;
+ }
+ if (implementsSerializable(anInterface)) {
+ return true;
+ }
+ }
ResolvedType superType = aType.getSuperclass();
if (superType != null && !superType.isMissing()) {
return implementsSerializable(superType);
}
MethodGen gen = new MethodGen(flags, getReturnType(), getArgumentTypes(), null, // getArgumentNames(),
getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPool());
- for (int i = 0, len = declaredExceptions.length; i < len; i++) {
- gen.addException(declaredExceptions[i]);
+ for (String declaredException : declaredExceptions) {
+ gen.addException(declaredException);
}
for (Attribute attr : attributes) {
if (newParameterAnnotations != null) {
for (int i = 0; i < newParameterAnnotations.length; i++) {
AnnotationAJ[] annos = newParameterAnnotations[i];
- for (int j = 0; j < annos.length; j++) {
+ for (AnnotationAJ anno : annos) {
gen.addParameterAnnotation(i,
- new AnnotationGen(((BcelAnnotation) annos[j]).getBcelAnnotation(), gen.getConstantPool(), true));
+ new AnnotationGen(((BcelAnnotation) anno).getBcelAnnotation(), gen.getConstantPool(), true));
}
}
}
if (memberView != null && memberView.getAnnotations() != null && memberView.getAnnotations().length != 0) {
AnnotationAJ[] ans = memberView.getAnnotations();
- for (int i = 0, len = ans.length; i < len; i++) {
- AnnotationGen a = ((BcelAnnotation) ans[i]).getBcelAnnotation();
+ for (AnnotationAJ an : ans) {
+ AnnotationGen a = ((BcelAnnotation) an).getBcelAnnotation();
gen.addAnnotation(new AnnotationGen(a, gen.getConstantPool(), true));
}
}
int paramSlots = gen.isStatic() ? 0 : 1;
Type[] argTypes = gen.getArgumentTypes();
if (argTypes != null) {
- for (int i = 0; i < argTypes.length; i++) {
- if (argTypes[i].getSize() == 2) {
+ for (Type argType : argTypes) {
+ if (argType.getSize() == 2) {
paramSlots += 2;
} else {
paramSlots += 1;
// We know the value is an array value
ArrayElementValue array = (ArrayElementValue) (vals.get(0)).getValue();
ElementValue[] values = array.getElementValuesArray();
- for (int j = 0; j < values.length; j++) {
+ for (ElementValue elementValue : values) {
// We know values in the array are strings
- SimpleElementValue value = (SimpleElementValue) values[j];
+ SimpleElementValue value = (SimpleElementValue) elementValue;
Lint.Kind lintKind = lint.getLintKind(value.getValueString());
if (lintKind != null) {
suppressedWarnings.add(lintKind);
throws Exception {
sap.startElement(xml.getName(), xml.getAttributes());
ArrayList childrens = xml.getChildrens();
- for (int i = 0; i < childrens.size(); i++) {
- LightXMLParser child = (LightXMLParser) childrens.get(i);
+ for (Object children : childrens) {
+ LightXMLParser child = (LightXMLParser) children;
traverse(sap, child);
}
sap.endElement(xml.getName());
String betterChoices[] = { "java.util.concurrent.ConcurrentHashMap",
"edu.emory.mathcs.backport.java.util.concurrent.ConcurrentHashMap",
"EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap" };
- for (int i = 0; i < betterChoices.length; i++) {
+ for (String betterChoice : betterChoices) {
try {
- return Class.forName(betterChoices[i]);
+ return Class.forName(betterChoice);
} catch (ClassNotFoundException cnfe) {
// try the next one
} catch (SecurityException se) {
private static void addPointcuts(AsmManager model, String sourcefilename, ResolvedType aspect,
IProgramElement containingAspect, ResolvedMember[] pointcuts) {
- for (int i = 0; i < pointcuts.length; i++) {
- ResolvedMember pointcut = pointcuts[i];
+ for (ResolvedMember pointcut : pointcuts) {
if (pointcut instanceof ResolvedPointcutDefinition) {
ResolvedPointcutDefinition rpcd = (ResolvedPointcutDefinition) pointcut;
Pointcut p = rpcd.getPointcut();
private static final String NO_COMMENT = null;
private static void addChildNodes(AsmManager asm, ResolvedType aspect, IProgramElement parent, ResolvedMember[] children) {
- for (int i = 0; i < children.length; i++) {
- ResolvedMember pcd = children[i];
+ for (ResolvedMember pcd : children) {
if (pcd instanceof ResolvedPointcutDefinition) {
ResolvedPointcutDefinition rpcd = (ResolvedPointcutDefinition) pcd;
Pointcut p = rpcd.getPointcut();
pe.setParameterSignatures(Collections.<char[]>emptyList(), Collections.<String>emptyList());
} else {
List<char[]> paramSigs = new ArrayList<char[]>();
- for (int i = 0; i < ts.length; i++) {
- paramSigs.add(ts[i].getSignature().toCharArray());
+ for (UnresolvedType t : ts) {
+ paramSigs.add(t.getSignature().toCharArray());
}
pe.setParameterSignatures(paramSigs, Collections.<String>emptyList());
}
*/
private static IProgramElement findOrCreateCodeNode(AsmManager asm, IProgramElement enclosingNode, Member shadowSig,
Shadow shadow) {
- for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext();) {
- IProgramElement node = (IProgramElement) it.next();
+ for (IProgramElement node : enclosingNode.getChildren()) {
int excl = node.getBytecodeName().lastIndexOf('!');
if (((excl != -1 && shadowSig.getName().equals(node.getBytecodeName().substring(0, excl))) || shadowSig.getName()
.equals(node.getBytecodeName()))
if (typeElement == null) {
return null;
}
- for (Iterator it = typeElement.getChildren().iterator(); it.hasNext();) {
- IProgramElement element = (IProgramElement) it.next();
+ for (IProgramElement element : typeElement.getChildren()) {
if (member.getName().equals(element.getBytecodeName()) && member.getSignature().equals(element.getBytecodeSignature())) {
return element;
}
if (anns == null)
anns = new org.aspectj.apache.bcel.classfile.annotation.AnnotationGen[0];
// convert to our Annotation type
- for (int i = 0; i < anns.length; i++) {
- if (anns[i].getTypeSignature().equals(ofType.getSignature())) {
- return new BcelAnnotation(anns[i], world);
+ for (org.aspectj.apache.bcel.classfile.annotation.AnnotationGen ann : anns) {
+ if (ann.getTypeSignature().equals(ofType.getSignature())) {
+ return new BcelAnnotation(ann, world);
}
}
return null;
// onMember.getName()+"' in class '"+jc.getClassName()+"'");
} else {
Attribute[] attrs = bcelMethod.getAttributes();
- for (int i = 0; i < attrs.length; i++) {
- Attribute attribute = attrs[i];
+ for (Attribute attribute : attrs) {
if (attribute.getName().equals("AnnotationDefault")) {
AnnotationDefault def = (AnnotationDefault) attribute;
return def.getElementValue().stringifyValue();
public boolean hasAnnotation(UnresolvedType ofType) {
ResolvedType[] myAnns = getAnnotationTypes();
ResolvedType toLookFor = ofType.resolve(getWorld());
- for (int i = 0; i < myAnns.length; i++) {
- if (myAnns[i] == toLookFor) {
+ for (ResolvedType myAnn : myAnns) {
+ if (myAnn == toLookFor) {
return true;
}
}
parser = new InternalUseOnlyPointcutParser(classLoaderReference.getClassLoader());
}
Set additionalPointcutHandlers = world.getRegisteredPointcutHandlers();
- for (Iterator handlerIterator = additionalPointcutHandlers.iterator(); handlerIterator.hasNext();) {
- PointcutDesignatorHandler handler = (PointcutDesignatorHandler) handlerIterator.next();
+ for (Object additionalPointcutHandler : additionalPointcutHandlers) {
+ PointcutDesignatorHandler handler = (PointcutDesignatorHandler) additionalPointcutHandler;
parser.registerPointcutDesignatorHandler(handler);
}
Logger parent = logger.getParent();
if (parent != null) handlers = parent.getHandlers();
}
- for (int i = 0; i < handlers.length; i++) {
- Handler handler = handlers[i];
+ for (Handler handler : handlers) {
handler.setLevel(Level.FINER);
}
}
private void registerAspectLibraries(List aspectPath) {
// System.err.println("? WeavingAdaptor.registerAspectLibraries(" + aspectPath + ")");
- for (Iterator i = aspectPath.iterator(); i.hasNext();) {
- String libName = (String) i.next();
+ for (Object o : aspectPath) {
+ String libName = (String) o;
addAspectLibrary(libName);
}
// Add the list of loader urls to the hash list
if (cl != null && cl instanceof URLClassLoader) {
URL[] urls = ((URLClassLoader) cl).getURLs();
- for (int i = 0; i < urls.length; i++) {
- hashableStrings.add(urls[i].toString());
+ for (URL url : urls) {
+ hashableStrings.add(url.toString());
}
}
hashableStrings.addAll(aspects);
Collections.sort(hashableStrings);
- for (Iterator<String> it = hashableStrings.iterator(); it.hasNext(); ) {
- String url = it.next();
+ for (String url : hashableStrings) {
hashable.append(url);
}
String hash = null;
"java.lang.InheritableThreadLocal", "java.lang.ThreadLocal", "java.util.Collection", "java.util.Comparator",
"java.util.Enumeration", "java.util.Iterator", "java.util.List", "java.util.ListIterator", "java.util.Map",
"java.util.Map$Entry", "java.util.Queue", "java.util.Set", "java.util.SortedMap", "java.util.SortedSet" };
- for (int i = 0; i < testClasses.length; i++) {
- JavaClass jc = repository.loadClass(testClasses[i]);
+ for (String testClass : testClasses) {
+ JavaClass jc = repository.loadClass(testClass);
String sig = jc.getGenericSignature();
parser.parseAsClassSignature(sig);
}
"java.lang.InheritableThreadLocal", "java.lang.ThreadLocal", "java.util.Collection", "java.util.Comparator",
"java.util.Enumeration", "java.util.Iterator", "java.util.List", "java.util.ListIterator", "java.util.Map",
"java.util.Map$Entry", "java.util.Queue", "java.util.Set", "java.util.SortedMap", "java.util.SortedSet" };
- for (int i = 0; i < testClasses.length; i++) {
- JavaClass jc = repository.loadClass(testClasses[i]);
+ for (String testClass : testClasses) {
+ JavaClass jc = repository.loadClass(testClass);
Method[] methods = jc.getMethods();
- for (int j = 0; j < methods.length; j++) {
- String sig = methods[j].getGenericSignature();
+ for (Method method : methods) {
+ String sig = method.getGenericSignature();
if (sig != null)
parser.parseAsMethodSignature(sig);
}
ResolvedType javaLangClass = world.resolve(UnresolvedType.forName("java/lang/Class"));
ResolvedMember[] methods = javaLangClass.getDeclaredMethods();
ResolvedMember getAnnotations = null;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals("getAnnotations")) {
- getAnnotations = methods[i];
- break;
- }
- }
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals("getAnnotations")) {
+ getAnnotations = method;
+ break;
+ }
+ }
if (getAnnotations != null) { // so can run on non-Java 5
// System.out.println("got it");
assertFalse(getAnnotations.canBeParameterized());
if (javaLangClass == null) return; // for < 1.5
ResolvedMember[] methods = javaLangClass.getDeclaredMethods();
ResolvedMember asSubclass = null;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals("asSubclass")) {
- asSubclass = methods[i];
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals("asSubclass")) {
+ asSubclass = method;
break;
}
}
if (javaUtilList == null) return; // for < 1.5
ResolvedMember[] methods = javaUtilList.getDeclaredMethods();
ResolvedMember add = null;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals("add")) {
- add = methods[i];
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals("add")) {
+ add = method;
break;
}
}
ResolvedType javaLangClass = world.resolve(UnresolvedType.forName("java/lang/Class"));
ResolvedMember[] methods = javaLangClass.getDeclaredMethods();
ResolvedMember getAnnotations = null;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals("getAnnotations")) {
- getAnnotations = methods[i];
- break;
- }
- }
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals("getAnnotations")) {
+ getAnnotations = method;
+ break;
+ }
+ }
if (getAnnotations != null) { // so can run on non-Java 5
// System.out.println("got it");
assertFalse(getAnnotations.canBeParameterized());
if (javaLangClass == null) return; // for < 1.5
ResolvedMember[] methods = javaLangClass.getDeclaredMethods();
ResolvedMember asSubclass = null;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals("asSubclass")) {
- asSubclass = methods[i];
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals("asSubclass")) {
+ asSubclass = method;
break;
}
}
if (javaUtilList == null) return; // for < 1.5
ResolvedMember[] methods = javaUtilList.getDeclaredMethods();
ResolvedMember add = null;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals("add")) {
- add = methods[i];
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals("add")) {
+ add = method;
break;
}
}
public void testDeclaredMethodWithParameter() {
ResolvedMember[] methods = listOfString.getDeclaredMethods();
ResolvedMember add = null;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals("add")) {
- if (methods[i].getParameterTypes().length == 1) {
- add = methods[i];
+ for (ResolvedMember resolvedMember : methods) {
+ if (resolvedMember.getName().equals("add")) {
+ if (resolvedMember.getParameterTypes().length == 1) {
+ add = resolvedMember;
System.out.println(add);
// j8: boolean java.util.List<java.lang.String>.add(java.lang.Object)
// break;
assertEquals("Ljava/lang/String;",parameterType.getSignature());
ResolvedMember get = null;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals("get")) {
- if (methods[i].getParameterTypes().length == 1) {
- get = methods[i];
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals("get")) {
+ if (method.getParameterTypes().length == 1) {
+ get = method;
break;
}
}
public void testDeclaredMethodWithParameterizedReturnType() {
ResolvedMember[] methods = listOfString.getDeclaredMethods();
ResolvedMember iterator = null;
- for (int i = 0; i < methods.length; i++) {
- if (methods[i].getName().equals("iterator")) {
- iterator = methods[i];
+ for (ResolvedMember method : methods) {
+ if (method.getName().equals("iterator")) {
+ iterator = method;
break;
}
}
Class<?> wmClass = WeaverMessages.class;
Field[] fields = wmClass.getDeclaredFields();
List<String> fieldList = new ArrayList<String>();
- for (int i = 0; i < fields.length; i++) {
- Field f = fields[i];
+ for (Field f : fields) {
if (f.getType() == String.class) {
try {
String key = (String) f.get(null);
// String value = WeaverMessages.format(key);
- assertFalse("Each key should be unique",fieldList.contains(key));
+ assertFalse("Each key should be unique", fieldList.contains(key));
fieldList.add(key);
// System.out.println(key + "," + value);
- } catch (IllegalAccessException ex) {
- } catch(MissingResourceException mrEx) {
+ } catch (IllegalAccessException ex) {
+ } catch (MissingResourceException mrEx) {
fail("Missing resource: " + mrEx);
}
}
threads[i] = new TestThread((i%3)*1000);
threads[i].start();
}
- for (int i=0; i<threads.length; i++) {
- threads[i].join();
- if (threads[i].getFailure() != null) {
- throw threads[i].getFailure();
+ for (TestThread thread : threads) {
+ thread.join();
+ if (thread.getFailure() != null) {
+ throw thread.getFailure();
}
}
}
// ----
protected void weaveTest(String[] inClassNames, String outKind, ShadowMunger patternMunger) throws IOException {
- for (int i = 0; i < inClassNames.length; i++) {
- String inFileName = inClassNames[i];
+ for (String inFileName : inClassNames) {
weaveTest(inFileName, outKind + inFileName, patternMunger);
}
}
protected void weaveTest(String[] inClassNames, String outKind, List<ShadowMunger> patternMungers) throws IOException {
- for (int i = 0; i < inClassNames.length; i++) {
- String inFileName = inClassNames[i];
+ for (String inFileName : inClassNames) {
weaveTest(inFileName, outKind + inFileName, patternMungers);
}
}
// XXX cut-and-paster from IdWeaveTestCase
public void checkShadowSet(List l, String[] ss) {
- outer: for (int i = 0, len = ss.length; i < len; i++) {
+ outer:
+ for (String s : ss) {
// inner:
- for (Iterator j = l.iterator(); j.hasNext();) {
+ for (Iterator j = l.iterator(); j.hasNext(); ) {
BcelShadow shadow = (BcelShadow) j.next();
String shadowString = shadow.toString();
- if (shadowString.equals(ss[i])) {
+ if (shadowString.equals(s)) {
j.remove();
continue outer;
}
}
- assertTrue("didn't find " + ss[i] + " in " + l, false);
+ assertTrue("didn't find " + s + " in " + l, false);
}
assertTrue("too many things in " + l, l.size() == 0);
}
}
public boolean hasAnnotation(UnresolvedType ofType) {
- for (int i = 0; i < annotationTypes.length; i++) {
- if (annotationTypes[i].equals(ofType.getName())) {
+ for (String annotationType : annotationTypes) {
+ if (annotationType.equals(ofType.getName())) {
return true;
}
}
ResolvedMember[] rms2 = rawReflectType.getDelegate().getDeclaredMethods();
StringBuffer errors = new StringBuffer();
Set one = new HashSet();
- for (int i = 0; i < rms1.length; i++) {
- one.add(rms1[i].toString());
+ for (ResolvedMember item : rms1) {
+ one.add(item.toString());
}
Set two = new HashSet();
- for (int i = 0; i < rms2.length; i++) {
- two.add(rms2[i].toString());
+ for (ResolvedMember value : rms2) {
+ two.add(value.toString());
}
- for (int i = 0; i < rms2.length; i++) {
- if (!one.contains(rms2[i].toString())) {
- errors.append("Couldn't find " + rms2[i].toString() + " in the bcel set\n");
+ for (ResolvedMember member : rms2) {
+ if (!one.contains(member.toString())) {
+ errors.append("Couldn't find " + member.toString() + " in the bcel set\n");
}
}
- for (int i = 0; i < rms1.length; i++) {
- if (!two.contains(rms1[i].toString())) {
- if (!barfIfClinitMissing && rms1[i].getName().equals("<clinit>"))
+ for (ResolvedMember resolvedMember : rms1) {
+ if (!two.contains(resolvedMember.toString())) {
+ if (!barfIfClinitMissing && resolvedMember.getName().equals("<clinit>"))
continue;
- errors.append("Couldn't find " + rms1[i].toString() + " in the reflection set\n");
+ errors.append("Couldn't find " + resolvedMember.toString() + " in the reflection set\n");
}
}
assertTrue("Errors:" + errors.toString(), errors.length() == 0);
}
if (expected.size()>0) { // we have excess ones!
StringBuffer excessTokens = new StringBuffer();
- for (Iterator iterator = expected.iterator(); iterator.hasNext();) {
- String string = (String) iterator.next();
- excessTokens.append(string).append(" ");
- }
+ for (String string : expected) {
+ excessTokens.append(string).append(" ");
+ }
fail("In pointcut expression "+pe.getPointcutExpression()+" parameter "+parameterNumber+". The annotation type pattern has these unexpected parameter type annotations "+excessTokens.toString());
}
}
if (expected.size()>0) { // we have excess ones!
StringBuffer excessTokens = new StringBuffer();
- for (Iterator iterator = expected.iterator(); iterator.hasNext();) {
- String string = (String) iterator.next();
- excessTokens.append(string).append(" ");
- }
+ for (String string : expected) {
+ excessTokens.append(string).append(" ");
+ }
fail("In pointcut expression "+pe.getPointcutExpression()+" parameter "+parameterNumber+". The annotation type pattern has these unexpected parameter annotations "+excessTokens.toString());
}
JavaClass jc = getClassFrom(new File("n:/temp"), "com.springsource.petclinic.domain.Visit");
assertNotNull(jc);
Attribute[] attrs = jc.getAttributes();
- for (int i = 0; i < attrs.length; i++) {
- System.out.println(attrs[i].getName());
- if (attrs[i].getName().endsWith("WeaverState")) {
- Unknown u = (Unknown) attrs[i];
+ for (Attribute attr : attrs) {
+ System.out.println(attr.getName());
+ if (attr.getName().endsWith("WeaverState")) {
+ Unknown u = (Unknown) attr;
VersionedDataInputStream vdis = new VersionedDataInputStream(new ByteArrayInputStream(u.getBytes()), null);
// WeaverStateInfo wsi =
WeaverStateInfo.read(vdis, null);