diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/AbstractDataTreeNode.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/AbstractDataTreeNode.java index ad9a37ef8a2..7e61460ca6c 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/AbstractDataTreeNode.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/AbstractDataTreeNode.java @@ -50,10 +50,11 @@ public abstract class AbstractDataTreeNode { */ AbstractDataTreeNode(String name, AbstractDataTreeNode[] children) { this.name = name; - if (children == null || children.length == 0) + if (children == null || children.length == 0) { this.children = AbstractDataTreeNode.NO_CHILDREN; - else + } else { this.children = children; + } } /** @@ -84,8 +85,9 @@ AbstractDataTreeNode asReverseComparisonNode(IComparator comparator) { static AbstractDataTreeNode[] assembleWith(AbstractDataTreeNode[] oldNodes, AbstractDataTreeNode[] newNodes, boolean keepDeleted) { // Optimize the common case where the new list is empty. - if (newNodes.length == 0) + if (newNodes.length == 0) { return oldNodes; + } // Can't just return newNodes if oldNodes has length 0 // because newNodes may contain deleted nodes. @@ -198,8 +200,9 @@ AbstractDataTreeNode assembleWith(AbstractDataTreeNode node) { } if (this.isDelta()) { AbstractDataTreeNode[] assembledChildren = assembleWith(children, node.children, true); - if (this.hasData()) + if (this.hasData()) { return new DataDeltaNode(name, this.getData(), assembledChildren); + } return new NoDataDeltaNode(name, assembledChildren); } AbstractDataTreeNode[] assembledChildren = assembleWith(children, node.children, false); @@ -271,10 +274,11 @@ AbstractDataTreeNode childAtIgnoreCase(String localName) { for (AbstractDataTreeNode element : children) { if (element.getName().equalsIgnoreCase(localName)) { //if we find a deleted child, keep looking for a real child - if (element.isDeleted()) + if (element.isDeleted()) { result = element; - else + } else { return element; + } } } return result; @@ -502,8 +506,9 @@ boolean isEmptyDelta() { String[] namesOfChildren() { String names[] = new String[children.length]; /* copy child names (Reverse loop optimized) */ - for (int i = children.length; --i >= 0;) + for (int i = children.length; --i >= 0;) { names[i] = children[i].getName(); + } return names; } @@ -538,8 +543,9 @@ void setName(String s) { */ protected static AbstractDataTreeNode[] simplifyWithParent(AbstractDataTreeNode[] nodes, IPath key, DeltaDataTree parent, IComparator comparer) { int nodeCount = nodes.length; - if (nodeCount == 0) + if (nodeCount == 0) { return NO_CHILDREN; + } AbstractDataTreeNode[] simplifiedNodes = new AbstractDataTreeNode[nodeCount]; int simplifiedCount = 0; for (int i = 0; i < nodeCount; ++i) { @@ -577,9 +583,11 @@ public void storeStrings(StringPool set) { name = set.add(name); //copy children pointer in case of concurrent modification AbstractDataTreeNode[] nodes = children; - if (nodes != null) - for (int i = nodes.length; --i >= 0;) + if (nodes != null) { + for (int i = nodes.length; --i >= 0;) { nodes[i].storeStrings(set); + } + } } /** diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DataDeltaNode.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DataDeltaNode.java index 4b57e1b9ef3..6c48b073540 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DataDeltaNode.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DataDeltaNode.java @@ -100,8 +100,9 @@ boolean isDelta() { AbstractDataTreeNode simplifyWithParent(IPath key, DeltaDataTree parent, IComparator comparer) { AbstractDataTreeNode[] simplifiedChildren = simplifyWithParent(children, key, parent, comparer); /* don't compare root nodes */ - if (!key.isRoot() && comparer.compare(parent.getData(key), data) == 0) + if (!key.isRoot() && comparer.compare(parent.getData(key), data) == 0) { return new NoDataDeltaNode(name, simplifiedChildren); + } return new DataDeltaNode(name, data, simplifiedChildren); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DataTreeNode.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DataTreeNode.java index c1603f136c7..ad163361a9f 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DataTreeNode.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DataTreeNode.java @@ -55,8 +55,9 @@ public DataTreeNode(String name, Object data, AbstractDataTreeNode[] children) { */ @Override AbstractDataTreeNode asBackwardDelta(DeltaDataTree myTree, DeltaDataTree parentTree, IPath key) { - if (parentTree.includes(key)) + if (parentTree.includes(key)) { return parentTree.copyCompleteSubtree(key); + } return new DeletedNode(name); } @@ -116,8 +117,9 @@ AbstractDataTreeNode compareWith(DataTreeNode other, IComparator comparator) { @Override AbstractDataTreeNode compareWithParent(IPath key, DeltaDataTree parent, IComparator comparator) { - if (!parent.includes(key)) + if (!parent.includes(key)) { return convertToAddedComparisonNode(this, NodeComparison.K_ADDED); + } DataTreeNode inParent = (DataTreeNode) parent.copyCompleteSubtree(key); return inParent.compareWith(this, comparator); } @@ -218,47 +220,52 @@ protected static AbstractDataTreeNode[] forwardDeltaWith(AbstractDataTreeNode[] AbstractDataTreeNode deltaNode = forwardDeltaWithOrNullIfEqual(oldNodes[oldIndex++], newNodes[newIndex++], comparer); if (deltaNode != null) { if (numChildDeltas >= childDeltaMax) { - if (childDeltas == null) + if (childDeltas == null) { childDeltas = new AbstractDataTreeNode[childDeltaMax = 5]; - else + } else { System.arraycopy(childDeltas, 0, childDeltas = new AbstractDataTreeNode[childDeltaMax = childDeltaMax * 2 + 1], 0, numChildDeltas); + } } childDeltas[numChildDeltas++] = deltaNode; } } else if (compare < 0) { if (numChildDeltas >= childDeltaMax) { - if (childDeltas == null) + if (childDeltas == null) { childDeltas = new AbstractDataTreeNode[childDeltaMax = 5]; - else + } else { System.arraycopy(childDeltas, 0, childDeltas = new AbstractDataTreeNode[childDeltaMax = childDeltaMax * 2 + 1], 0, numChildDeltas); + } } childDeltas[numChildDeltas++] = new DeletedNode(oldName); oldIndex++; } else { if (numChildDeltas >= childDeltaMax) { - if (childDeltas == null) + if (childDeltas == null) { childDeltas = new AbstractDataTreeNode[childDeltaMax = 5]; - else + } else { System.arraycopy(childDeltas, 0, childDeltas = new AbstractDataTreeNode[childDeltaMax = childDeltaMax * 2 + 1], 0, numChildDeltas); + } } childDeltas[numChildDeltas++] = newNodes[newIndex++]; } } while (oldIndex < oldNodes.length) { if (numChildDeltas >= childDeltaMax) { - if (childDeltas == null) + if (childDeltas == null) { childDeltas = new AbstractDataTreeNode[childDeltaMax = 5]; - else + } else { System.arraycopy(childDeltas, 0, childDeltas = new AbstractDataTreeNode[childDeltaMax = childDeltaMax * 2 + 1], 0, numChildDeltas); + } } childDeltas[numChildDeltas++] = new DeletedNode(oldNodes[oldIndex++].name); } while (newIndex < newNodes.length) { if (numChildDeltas >= childDeltaMax) { - if (childDeltas == null) + if (childDeltas == null) { childDeltas = new AbstractDataTreeNode[childDeltaMax = 5]; - else + } else { System.arraycopy(childDeltas, 0, childDeltas = new AbstractDataTreeNode[childDeltaMax = childDeltaMax * 2 + 1], 0, numChildDeltas); + } } childDeltas[numChildDeltas++] = newNodes[newIndex++]; } @@ -346,8 +353,9 @@ public void storeStrings(StringPool set) { super.storeStrings(set); //copy data for thread safety Object o = data; - if (o instanceof IStringPoolParticipant) + if (o instanceof IStringPoolParticipant) { ((IStringPoolParticipant) o).shareStrings(set); + } } @Override diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DeletedNode.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DeletedNode.java index 56470276e8b..55d26053132 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DeletedNode.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DeletedNode.java @@ -36,8 +36,9 @@ public class DeletedNode extends AbstractDataTreeNode { */ @Override AbstractDataTreeNode asBackwardDelta(DeltaDataTree myTree, DeltaDataTree parentTree, IPath key) { - if (parentTree.includes(key)) + if (parentTree.includes(key)) { return parentTree.copyCompleteSubtree(key); + } return this; } @@ -66,8 +67,9 @@ AbstractDataTreeNode compareWithParent(IPath key, DeltaDataTree parent, ICompara * be a corresponding node in the parent. Deleted nodes can live * in isolation. */ - if (parent.includes(key)) + if (parent.includes(key)) { return convertToRemovedComparisonNode(parent.copyCompleteSubtree(key), NodeComparison.K_REMOVED); + } // Node doesn't exist in either tree. Return an empty comparison. // Empty comparisons are omitted from the delta. return new DataTreeNode(key.lastSegment(), new NodeComparison(null, null, 0, 0)); @@ -95,8 +97,9 @@ boolean isDeleted() { */ @Override AbstractDataTreeNode simplifyWithParent(IPath key, DeltaDataTree parent, IComparator comparer) { - if (parent.includes(key)) + if (parent.includes(key)) { return this; + } return new NoDataDeltaNode(name); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DeltaDataTree.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DeltaDataTree.java index a667540f45b..dd14acd22e4 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DeltaDataTree.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/DeltaDataTree.java @@ -77,8 +77,9 @@ protected DeltaDataTree(AbstractDataTreeNode rootNode, DeltaDataTree parent) { * @param childNode child node. */ protected void addChild(IPath parentKey, String localName, AbstractDataTreeNode childNode) { - if (!includes(parentKey)) + if (!includes(parentKey)) { handleNotFound(parentKey); + } childNode.setName(localName); this.assembleNode(parentKey, new NoDataDeltaNode(parentKey.lastSegment(), childNode)); } @@ -91,8 +92,9 @@ protected void addChild(IPath parentKey, String localName, AbstractDataTreeNode * Returns the delta A<-B. The result is equivalent to A, but has B as its parent. */ DeltaDataTree asBackwardDelta() { - if (getParent() == null) + if (getParent() == null) { return newEmptyDeltaTree(); + } return new DeltaDataTree(getRootNode().asBackwardDelta(this, getParent(), rootKey()), this); } @@ -285,14 +287,16 @@ public DeltaDataTree compareWith(DeltaDataTree other, IComparator comparator) { public DeltaDataTree compareWith(DeltaDataTree other, IComparator comparator, IPath path) { /* need to figure out if trees really contain the given path */ if (this.includes(path)) { - if (other.includes(path)) + if (other.includes(path)) { return basicCompare(other, comparator, path); + } /* only exists in this tree */ return new DeltaDataTree(AbstractDataTreeNode.convertToRemovedComparisonNode(this.copyCompleteSubtree(path), comparator.compare(this.getData(path), null))); } - if (other.includes(path)) + if (other.includes(path)) { /* only exists in other tree */ return new DeltaDataTree(AbstractDataTreeNode.convertToAddedComparisonNode(other.copyCompleteSubtree(path), comparator.compare(null, other.getData(path)))); + } /* doesn't exist in either tree */ return DeltaDataTree.createEmptyDelta(); } @@ -317,8 +321,9 @@ public AbstractDataTreeNode copyCompleteSubtree(IPath key) { handleNotFound(key); return null; } - if (node.isDelta()) + if (node.isDelta()) { return naiveCopyCompleteSubtree(key); + } //copy the node in case the user wants to hammer the subtree name return node.copy(); } @@ -336,8 +341,9 @@ public void createChild(IPath parentKey, String localName) { */ @Override public void createChild(IPath parentKey, String localName, Object data) { - if (isImmutable()) + if (isImmutable()) { handleImmutableTree(); + } addChild(parentKey, localName, new DataTreeNode(localName, data)); } @@ -355,8 +361,9 @@ static DeltaDataTree createEmptyDelta() { */ @Override public void createSubtree(IPath key, AbstractDataTreeNode node) { - if (isImmutable()) + if (isImmutable()) { handleImmutableTree(); + } if (key.isRoot()) { setParent(null); setRootNode(node); @@ -370,12 +377,14 @@ public void createSubtree(IPath key, AbstractDataTreeNode node) { */ @Override public void deleteChild(IPath parentKey, String localName) { - if (isImmutable()) + if (isImmutable()) { handleImmutableTree(); + } /* If the child does not exist */ IPath childKey = parentKey.append(localName); - if (!includes(childKey)) + if (!includes(childKey)) { handleNotFound(childKey); + } assembleNode(parentKey, new NoDataDeltaNode(parentKey.lastSegment(), new DeletedNode(localName))); } @@ -390,8 +399,9 @@ public AbstractDataTreeNode findNodeAt(IPath key) { int segmentCount = key.segmentCount(); for (int i = 0; i < segmentCount; i++) { node = node.childAtOrNull(key.segment(i)); - if (node == null) + if (node == null) { return null; + } } return node; } @@ -519,11 +529,13 @@ protected AbstractDataTreeNode[] getChildNodes(IPath parentKey) { public IPath[] getChildren(IPath parentKey) { AbstractDataTreeNode[] childNodes = getChildNodes(parentKey); int len = childNodes.length; - if (len == 0) + if (len == 0) { return NO_CHILDREN; + } IPath[] answer = new IPath[len]; - for (int i = 0; i < len; ++i) + for (int i = 0; i < len; ++i) { answer[i] = parentKey.append(childNodes[i].name); + } return answer; } @@ -592,8 +604,9 @@ public String[] getNamesOfChildren(IPath parentKey) { AbstractDataTreeNode[] childNodes = getChildNodes(parentKey); int len = childNodes.length; String[] namesOfChildren = new String[len]; - for (int i = 0; i < len; ++i) + for (int i = 0; i < len; ++i) { namesOfChildren[i] = childNodes[i].name; + } return namesOfChildren; } @@ -764,8 +777,9 @@ protected AbstractDataTreeNode naiveCopyCompleteSubtree(IPath key) { * resulting delta. */ public DeltaDataTree newEmptyDeltaTree() { - if (!isImmutable()) + if (!isImmutable()) { throw new IllegalArgumentException(Messages.dtree_notImmutable); + } return new DeltaDataTree(new NoDataDeltaNode(null), this); } @@ -800,11 +814,13 @@ public DeltaDataTree reroot() { * sourceTree is not immutable */ protected void reroot(DeltaDataTree sourceTree) { - if (!sourceTree.isImmutable()) + if (!sourceTree.isImmutable()) { handleImmutableTree(); + } DeltaDataTree sourceParent = sourceTree.getParent(); - if (sourceParent == null) + if (sourceParent == null) { return; + } this.reroot(sourceParent); DeltaDataTree backwardDelta = sourceTree.asBackwardDelta(); DeltaDataTree complete = sourceParent.assembleWithForwardDelta(sourceTree); @@ -823,10 +839,12 @@ protected void reroot(DeltaDataTree sourceTree) { */ public AbstractDataTreeNode safeCopyCompleteSubtree(IPath key) { AbstractDataTreeNode node = searchNodeAt(key); - if (node == null) + if (node == null) { return null; - if (node.isDelta()) + } + if (node.isDelta()) { return safeNaiveCopyCompleteSubtree(key); + } //copy the node in case the user wants to hammer the subtree name return node.copy(); } @@ -852,15 +870,18 @@ protected AbstractDataTreeNode safeNaiveCopyCompleteSubtree(IPath key) { int actualChildCount = 0; for (int i = numChildren; --i >= 0;) { childNodes[i] = safeCopyCompleteSubtree(key.append(childNames[i])); - if (childNodes[i] != null) + if (childNodes[i] != null) { actualChildCount++; + } } //if there are less actual children due to concurrent deletion, shrink the child array if (actualChildCount < numChildren) { AbstractDataTreeNode[] actualChildNodes = new AbstractDataTreeNode[actualChildCount]; - for (int iOld = 0, iNew = 0; iOld < numChildren; iOld++) - if (childNodes[iOld] != null) + for (int iOld = 0, iNew = 0; iOld < numChildren; iOld++) { + if (childNodes[iOld] != null) { actualChildNodes[iNew++] = childNodes[iOld]; + } + } childNodes = actualChildNodes; } } @@ -889,8 +910,9 @@ protected AbstractDataTreeNode searchNodeAt(IPath key) { } } if (node != null) { - if (node.isDeleted()) + if (node.isDeleted()) { break; + } return node; } if (complete) { @@ -921,8 +943,9 @@ protected AbstractDataTreeNode searchLocalNodeAt(IPath key) { } } if (node != null) { - if (node.isDeleted()) + if (node.isDeleted()) { return null; + } return node; } if (complete) { @@ -936,10 +959,12 @@ protected AbstractDataTreeNode searchLocalNodeAt(IPath key) { */ @Override public void setData(IPath key, Object data) { - if (isImmutable()) + if (isImmutable()) { handleImmutableTree(); - if (!includes(key)) + } + if (!includes(key)) { handleNotFound(key); + } assembleNode(key, new DataDeltaNode(key.lastSegment(), data)); } @@ -973,8 +998,9 @@ void setRootNode(AbstractDataTreeNode aNode) { * - removes any empty (leaf NoDataDelta) nodes */ protected void simplify(IComparator comparer) { - if (parent == null) + if (parent == null) { return; + } setRootNode(rootNode.simplifyWithParent(rootKey(), parent, comparer)); } @@ -985,8 +1011,9 @@ public void storeStrings(StringPool set) { AbstractDataTreeNode root = null; for (DeltaDataTree dad = this; dad != null; dad = dad.getParent()) { root = dad.getRootNode(); - if (root != null) + if (root != null) { root.storeStrings(set); + } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/NoDataDeltaNode.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/NoDataDeltaNode.java index a4933cd5951..c299813e0bc 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/NoDataDeltaNode.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/dtree/NoDataDeltaNode.java @@ -56,8 +56,9 @@ public NoDataDeltaNode(String name, AbstractDataTreeNode[] children) { @Override AbstractDataTreeNode asBackwardDelta(DeltaDataTree myTree, DeltaDataTree parentTree, IPath key) { int numChildren = children.length; - if (numChildren == 0) + if (numChildren == 0) { return new NoDataDeltaNode(name, NO_CHILDREN); + } AbstractDataTreeNode[] newChildren = new AbstractDataTreeNode[numChildren]; for (int i = numChildren; --i >= 0;) { newChildren[i] = children[i].asBackwardDelta(myTree, parentTree, key.append(children[i].getName())); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/AutoBuildJob.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/AutoBuildJob.java index bdf4c7ba365..1978fa637bb 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/AutoBuildJob.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/AutoBuildJob.java @@ -104,8 +104,9 @@ synchronized void build(boolean needsBuild) { } //don't mess with the interrupt flag if the job is still running - if (state != Job.RUNNING) + if (state != Job.RUNNING) { setInterrupted(false); + } switch (state) { case Job.SLEEPING : @@ -203,8 +204,9 @@ private void doBuild(IProgressMonitor monitor) throws CoreException, OperationCa IStatus result = Status.OK_STATUS; try { // Note: shouldBuild() also resets the need/force/avoid build flags! - if (shouldBuild()) + if (shouldBuild()) { result = workspace.getBuildManager().build(workspace.getBuildOrder(), ICoreConstants.EMPTY_BUILD_CONFIG_ARRAY, trigger, subMonitor.split(Policy.opWork)); + } } finally { //always send POST_BUILD if there has been a PRE_BUILD workspace.broadcastBuildEvent(workspace, IResourceChangeEvent.POST_BUILD, trigger); @@ -236,8 +238,9 @@ public void forceBuild() { */ synchronized void interrupt() { //if already interrupted, do nothing - if (interrupted) + if (interrupted) { return; + } switch (getState()) { case NONE : return; @@ -247,29 +250,34 @@ synchronized void interrupt() { break; case RUNNING : //make sure autobuild doesn't interrupt itself - if (Job.getJobManager().currentJob() == this) + if (Job.getJobManager().currentJob() == this) { return; + } setInterrupted(true); break; } //clear the autobuild avoidance flag if we were interrupted - if (interrupted) + if (interrupted) { avoidBuild = false; + } } synchronized boolean isInterrupted() { - if (interrupted) + if (interrupted) { return true; + } //check if another job is blocked by the build job - if (isBlocking()) + if (isBlocking()) { setInterrupted(true); + } return interrupted; } @Override public void preferenceChange(PreferenceChangeEvent event) { - if (!ResourcesPlugin.PREF_AUTO_BUILDING.equals(event.getKey())) + if (!ResourcesPlugin.PREF_AUTO_BUILDING.equals(event.getKey())) { return; + } // get the new value of auto-build directly from the preferences boolean wasAutoBuilding = isAutoBuilding; isAutoBuilding = Platform.getPreferencesService().getBoolean(ResourcesPlugin.PI_RESOURCES, @@ -294,8 +302,9 @@ public IStatus run(IProgressMonitor monitor) { } } //if the system is shutting down, don't build - if (systemBundle.getState() == Bundle.STOPPING) + if (systemBundle.getState() == Bundle.STOPPING) { return Status.OK_STATUS; + } try { doBuild(subMonitor.split(1)); lastBuild = System.currentTimeMillis(); @@ -329,13 +338,16 @@ private synchronized void setInterrupted(boolean value) { private synchronized boolean shouldBuild() { try { //if auto-build is off then we never run - if (!workspace.isAutoBuilding()) + if (!workspace.isAutoBuilding()) { return false; + } //build if the workspace requires a build (description changes) - if (forceBuild) + if (forceBuild) { return true; - if (avoidBuild) + } + if (avoidBuild) { return false; + } //return whether there have been any changes to the workspace tree. return buildNeeded; } finally { @@ -366,8 +378,9 @@ public boolean belongsTo(Object family) { @Override protected IStatus run(IProgressMonitor monitor) { // if the system is shutting down, don't build - if (systemBundle.getState() == Bundle.STOPPING) + if (systemBundle.getState() == Bundle.STOPPING) { return Status.OK_STATUS; + } final ISchedulingRule rule = workspace.getRuleFactory().buildRule(); try { workspace.prepareOperation(rule, monitor); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildCommand.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildCommand.java index 879e60672e0..102224e8671 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildCommand.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildCommand.java @@ -104,8 +104,9 @@ public BuildCommand() { @Override public Object clone() { BuildCommand result = (BuildCommand) super.clone(); - if (result == null) + if (result == null) { return null; + } result.setArguments(getArguments()); //don't let references to builder instances leak out because they reference trees result.setBuilders(null); @@ -130,11 +131,12 @@ private void computeIsConfigurable() { @Override public boolean equals(Object object) { - if (this == object) + if (this == object) { return true; - if (!(object instanceof BuildCommand)) + } + if (!(object instanceof BuildCommand command)) { return false; - BuildCommand command = (BuildCommand) object; + } // equal if same builder name, arguments, and triggers return getBuilderName().equals(command.getBuilderName()) && getArguments(false).equals(command.getArguments(false)) && (triggers & ALL_TRIGGERS) == (command.triggers & ALL_TRIGGERS); } @@ -173,8 +175,9 @@ public Object getBuilders() { */ public IncrementalProjectBuilder getBuilder(IBuildConfiguration config) { synchronized (builderLock) { - if (builders != null && supportsConfigs()) + if (builders != null && supportsConfigs()) { return builders.get(config); + } return builder; } } @@ -197,8 +200,9 @@ public boolean isBuilding(int trigger) { @Override public boolean isConfigurable() { - if ((triggers & MASK_CONFIG_COMPUTED) == 0) + if ((triggers & MASK_CONFIG_COMPUTED) == 0) { computeIsConfigurable(); + } return (triggers & MASK_CONFIGURABLE) != 0; } @@ -237,10 +241,11 @@ public void setBuilders(Object value) { builder = null; builders = null; } else { - if (value instanceof IncrementalProjectBuilder) + if (value instanceof IncrementalProjectBuilder) { builder = (IncrementalProjectBuilder) value; - else + } else { builders = new HashMap<>((Map) value); + } } } } @@ -260,11 +265,13 @@ public void addBuilder(IBuildConfiguration config, IncrementalProjectBuilder new IncrementalProjectBuilder configBuilder = builders == null ? null : builders.get(config); if (configBuilder == null && builder == null) { if (supportsConfigs()) { - if (builders == null) + if (builders == null) { builders = new HashMap<>(1); + } builders.put(config, newBuilder); - } else + } else { builder = newBuilder; + } } } } @@ -277,12 +284,14 @@ public void setBuilderName(String value) { @Override public void setBuilding(int trigger, boolean value) { - if (!isConfigurable()) + if (!isConfigurable()) { return; - if (value) + } + if (value) { triggers |= maskForTrigger(trigger); - else + } else { triggers &= ~maskForTrigger(trigger); + } } /** @@ -293,10 +302,11 @@ public void setBuilding(int trigger, boolean value) { */ public void setConfigurable(boolean value) { triggers |= MASK_CONFIG_COMPUTED; - if (value) + if (value) { triggers |= MASK_CONFIGURABLE; - else + } else { triggers = ALL_TRIGGERS; + } } /** diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildContext.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildContext.java index 63731179b81..108ba8468ae 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildContext.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildContext.java @@ -96,12 +96,15 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } BuildContext other = (BuildContext) obj; return buildConfiguration.equals(other.buildConfiguration) && Arrays.equals(requestedBuilt, other.requestedBuilt) && Arrays.equals(buildOrder, other.buildOrder); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildManager.java index 70a3e01bc17..1bdc685ce6b 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/BuildManager.java @@ -242,8 +242,9 @@ private void basicBuild(int trigger, IncrementalProjectBuilder builder, Map createBuildersPersistentInfo(IProject pr ProjectDescription desc = ((Project) project).internalGetDescription(); ICommand[] commands = desc.getBuildSpec(false); - if (commands.length == 0) + if (commands.length == 0) { return null; + } IBuildConfiguration[] configs = project.getBuildConfigs(); /* build the new list */ @@ -729,8 +741,9 @@ public ArrayList createBuildersPersistentInfo(IProject pr IncrementalProjectBuilder builder = ((BuildCommand) commands[i]).getBuilder(config); if (builder == null) { // if the builder was not instantiated, use the old info if any. - if (oldInfos != null) + if (oldInfos != null) { info = getBuilderInfo(oldInfos, builderName, supportsConfigs ? config.getName() : null, i); + } } else if (!(builder instanceof MissingBuilder)) { ElementTree oldTree = ((InternalBuilder) builder).getLastBuiltTree(); //don't persist build state for builders that have no last built state @@ -741,8 +754,9 @@ public ArrayList createBuildersPersistentInfo(IProject pr info.setInterestingProjects(((InternalBuilder) builder).getInterestingProjects()); } } - if (info != null) + if (info != null) { newInfos.add(info); + } } } return newInfos; @@ -753,8 +767,9 @@ private String debugBuilder() { } private String debugProject() { - if (currentBuilders == null) + if (currentBuilders == null) { return ""; //$NON-NLS-1$ + } return "[" + currentBuilders.stream().map(builder -> builder.getProject().getFullPath().toString()).collect(Collectors.joining(",")) + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } @@ -805,10 +820,11 @@ private static void waitFor(Job job) { while (job.getState() != Job.NONE) { // Need to wake up thread to finish as soon as possible: while (job.getState() != Job.RUNNING && job.getState() != Job.NONE) { - if (jobManager.isSuspended()) + if (jobManager.isSuspended()) { throw new JobManagerSuspendedException("The JobManager is suspended, waiting for " //$NON-NLS-1$ + "a job to finish will just block this thread forever. Activate the JobManager again before waiting " //$NON-NLS-1$ + "for a job to finish"); //$NON-NLS-1$ + } jobManager.wakeUp(ResourcesPlugin.FAMILY_AUTO_BUILD); Thread.yield(); @@ -912,8 +928,9 @@ private IncrementalProjectBuilder getBuilder(IBuildConfiguration buildConfigurat */ private IncrementalProjectBuilder getBuilder(IBuildConfiguration buildConfiguration, ICommand command, int buildSpecIndex, MultiStatus status, IBuildContext context) throws CoreException { InternalBuilder builder = getBuilder(buildConfiguration, command, buildSpecIndex, status); - if (builder != null) + if (builder != null) { builder.setContext(context); + } return (IncrementalProjectBuilder) builder; } @@ -933,11 +950,13 @@ private BuilderPersistentInfo getBuilderInfo(ArrayList in // Note: the config name may be null for builders that don't support configurations, or old workspaces if (info.getBuilderName().equals(builderName) && (info.getConfigName() == null || info.getConfigName().equals(configName))) { //we have found a match on name alone - if (nameMatch == null) + if (nameMatch == null) { nameMatch = info; + } //see if the index matches - if (buildSpecIndex == -1 || info.getBuildSpecIndex() == -1 || buildSpecIndex == info.getBuildSpecIndex()) + if (buildSpecIndex == -1 || info.getBuildSpecIndex() == -1 || buildSpecIndex == info.getBuildSpecIndex()) { return info; + } } } //no exact index match, so return name match, if any @@ -963,9 +982,11 @@ public ArrayList getBuildersPersistentInfo(IProject proje */ private ICommand getCommand(IProject project, String builderName, Map args) { ICommand[] buildSpec = ((Project) project).internalGetDescription().getBuildSpec(false); - for (ICommand element : buildSpec) - if (element.getBuilderName().equals(builderName)) + for (ICommand element : buildSpec) { + if (element.getBuilderName().equals(builderName)) { return element; + } + } //none found, so create a new command BuildCommand result = new BuildCommand(); result.setBuilderName(builderName); @@ -993,15 +1014,17 @@ IResourceDelta getDelta(IProject project) { try { lock.acquire(); if (currentTree == null) { - if (Policy.DEBUG_BUILD_FAILURE) + if (Policy.DEBUG_BUILD_FAILURE) { Policy.debug("Build: no tree for delta " + debugBuilder() + " [" + debugProject() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } return null; } Set interestedBuilders = getInterestedBuilders(project); //check if this builder has indicated it cares about this project if (interestedBuilders.isEmpty()) { - if (Policy.DEBUG_BUILD_FAILURE) + if (Policy.DEBUG_BUILD_FAILURE) { Policy.debug("Build: project not interesting for current builders " + debugBuilder() + " [" + debugProject() + "] " + project.getFullPath()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } return null; } @@ -1026,12 +1049,14 @@ private IResourceDelta getDeltaCached(IProject project, ElementTree oldTree, Ele } else { result = ResourceDeltaFactory.computeDelta(workspace, oldTree, newTree, fullPath, -1); } - if (Policy.DEBUG_BUILD_FAILURE && result == null) + if (Policy.DEBUG_BUILD_FAILURE && result == null) { Policy.debug( "Build: no delta " + debugBuilder() + " [" + debugProject() + "] " + fullPath); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (Policy.DEBUG_BUILD_DELTA) + } + if (Policy.DEBUG_BUILD_DELTA) { Policy.debug("Finished computing delta, time: " + (System.currentTimeMillis() - startTime) + "ms" //$NON-NLS-1$ //$NON-NLS-2$ + ((ResourceDelta) result).toDeepDebugString()); + } return result; }); @@ -1046,8 +1071,9 @@ private ISafeRunnable getSafeRunnable(final InternalBuilder currentBuilder, fina @Override public void handleException(Throwable e) { if (e instanceof OperationCanceledException) { - if (Policy.DEBUG_BUILD_INVOKING) + if (Policy.DEBUG_BUILD_INVOKING) { Policy.debug("Build canceled"); //$NON-NLS-1$ + } //just discard built state when a builder cancels, to ensure //that it is called again on the very next build. currentBuilder.forgetLastBuiltState(); @@ -1058,32 +1084,35 @@ public void handleException(Throwable e) { //add a generic message to the MultiStatus String builderName = currentBuilder.getLabel(); - if (builderName == null || builderName.length() == 0) + if (builderName == null || builderName.length() == 0) { builderName = currentBuilder.getClass().getName(); + } String pluginId = currentBuilder.getPluginId(); String message = NLS.bind(Messages.events_builderError, builderName, currentBuilder.getProject().getName()); status.add(new Status(IStatus.ERROR, pluginId, IResourceStatus.BUILD_FAILED, message, e)); //add the exception status to the MultiStatus - if (e instanceof CoreException) + if (e instanceof CoreException) { status.add(((CoreException) e).getStatus()); + } } @Override public void run() throws Exception { IProject[] prereqs = null; //invoke the appropriate build method depending on the trigger - if (trigger != IncrementalProjectBuilder.CLEAN_BUILD) + if (trigger != IncrementalProjectBuilder.CLEAN_BUILD) { prereqs = currentBuilder.build(trigger, args, monitor); - else { + } else { if (currentBuilder instanceof IIncrementalProjectBuilder2) { ((IIncrementalProjectBuilder2) currentBuilder).clean(args, monitor); } else { currentBuilder.clean(monitor); } } - if (prereqs == null) + if (prereqs == null) { prereqs = new IProject[0]; + } currentBuilder.setInterestingProjects(prereqs.clone()); } }; @@ -1111,8 +1140,9 @@ public void handleEvent(LifecycleEvent event) { case LifecycleEvent.PRE_PROJECT_MOVE : project = (IProject) event.resource; //make sure the builder persistent info is deleted for the project move case - if (project.isAccessible()) + if (project.isAccessible()) { setBuildersPersistentInfo(project, null); + } } } @@ -1129,10 +1159,12 @@ boolean hasBeenBuilt(IProject project) { * This hook is called after each builder instance is called. */ private void hookEndBuild(IncrementalProjectBuilder builder) { - if (ResourceStats.TRACE_BUILDERS) + if (ResourceStats.TRACE_BUILDERS) { ResourceStats.endBuild(); - if (!Policy.DEBUG_BUILD_INVOKING || timeStamp == -1) + } + if (!Policy.DEBUG_BUILD_INVOKING || timeStamp == -1) { return; //builder wasn't called or we are not debugging + } Policy.debug("Builder finished: " + toString(builder) + " time: " + (System.currentTimeMillis() - timeStamp) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ timeStamp = -1; } @@ -1146,8 +1178,9 @@ private void hookEndBuild(int trigger) { builtProjects.clear(); deltaCache.flush(); //ensure autobuild runs after a clean - if (trigger == IncrementalProjectBuilder.CLEAN_BUILD) + if (trigger == IncrementalProjectBuilder.CLEAN_BUILD) { autoBuildJob.forceBuild(); + } if (Policy.DEBUG_BUILD_INVOKING) { Policy.debug("Top-level build-end time: " + (System.currentTimeMillis() - overallTimeStamp)); //$NON-NLS-1$ overallTimeStamp = -1; @@ -1159,8 +1192,9 @@ private void hookEndBuild(int trigger) { * This hook is called before each builder instance is called. */ private void hookStartBuild(IncrementalProjectBuilder builder, int trigger) { - if (ResourceStats.TRACE_BUILDERS) + if (ResourceStats.TRACE_BUILDERS) { ResourceStats.startBuild(builder); + } if (Policy.DEBUG_BUILD_INVOKING) { timeStamp = System.currentTimeMillis(); Policy.debug("Invoking (" + debugTrigger(trigger) + ") on builder: " + toString(builder)); //$NON-NLS-1$ //$NON-NLS-2$ @@ -1173,13 +1207,15 @@ private void hookStartBuild(IncrementalProjectBuilder builder, int trigger) { * start running. */ private void hookStartBuild(IBuildConfiguration[] configs, int trigger) { - if (Policy.DEBUG_BUILD_STACK) + if (Policy.DEBUG_BUILD_STACK) { Policy.debug(new RuntimeException("Starting build: " + debugTrigger(trigger))); //$NON-NLS-1$ + } if (Policy.DEBUG_BUILD_INVOKING) { overallTimeStamp = System.currentTimeMillis(); StringBuilder sb = new StringBuilder("Top-level build-start of: "); //$NON-NLS-1$ - for (IBuildConfiguration config : configs) + for (IBuildConfiguration config : configs) { sb.append(config).append(", "); //$NON-NLS-1$ + } sb.append(debugTrigger(trigger)); Policy.debug(sb.toString()); } @@ -1243,18 +1279,21 @@ private BuilderPersistentInfo removePersistentBuilderInfo(String builderName, IB */ private IncrementalProjectBuilder instantiateBuilder(String builderName) throws CoreException { IExtension extension = Platform.getExtensionRegistry().getExtension(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_BUILDERS, builderName); - if (extension == null) + if (extension == null) { return null; + } IConfigurationElement[] configs = extension.getConfigurationElements(); - if (configs.length == 0) + if (configs.length == 0) { return null; + } String natureId = null; if (getBooleanAttribute(configs[0], "hasNature")) { //$NON-NLS-1$ //find the nature that owns this builder String builderId = extension.getUniqueIdentifier(); natureId = workspace.getNatureManager().findNatureForBuilder(builderId); - if (natureId == null) + if (natureId == null) { return null; + } } //The nature exists, or this builder doesn't specify a nature InternalBuilder builder = (InternalBuilder) configs[0].createExecutableExtension("run"); //$NON-NLS-1$ @@ -1286,8 +1325,9 @@ public boolean isAutobuildBuildPending() { * to the given project, and false otherwise. */ private boolean isInterestingProject(InternalBuilder currentBuilder, IProject project) { - if (project.equals(currentBuilder.getProject())) + if (project.equals(currentBuilder.getProject())) { return true; + } IProject[] interestingProjects = currentBuilder.getInterestingProjects(); for (IProject interestingProject : interestingProjects) { if (interestingProject.equals(project)) { @@ -1387,23 +1427,27 @@ private void removeBuilders(IProject project, String builderId) throws CoreExcep IProjectDescription desc = project.getDescription(); ICommand[] oldSpec = desc.getBuildSpec(); int oldLength = oldSpec.length; - if (oldLength == 0) + if (oldLength == 0) { return; + } int remaining = 0; //null out all commands that match the builder to remove for (int i = 0; i < oldSpec.length; i++) { - if (oldSpec[i].getBuilderName().equals(builderId)) + if (oldSpec[i].getBuilderName().equals(builderId)) { oldSpec[i] = null; - else + } else { remaining++; + } } //check if any were actually removed - if (remaining == oldSpec.length) + if (remaining == oldSpec.length) { return; + } ICommand[] newSpec = new ICommand[remaining]; for (int i = 0, newIndex = 0; i < oldLength; i++) { - if (oldSpec[i] != null) + if (oldSpec[i] != null) { newSpec[newIndex++] = oldSpec[i]; + } } desc.setBuildSpec(newSpec); project.setDescription(desc, IResource.NONE, null); @@ -1533,8 +1577,9 @@ public void startup(IProgressMonitor monitor) { private String toString(InternalBuilder builder) { String name = builder.getClass().getName(); name = name.substring(name.lastIndexOf('.') + 1); - if (builder instanceof MissingBuilder) + if (builder instanceof MissingBuilder) { name = name + ": '" + ((MissingBuilder) builder).getName() + "'"; //$NON-NLS-1$ //$NON-NLS-2$ + } return name + "(" + builder.getBuildConfig() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } @@ -1556,8 +1601,9 @@ private String toString(InternalBuilder builder) { */ private boolean validateNature(InternalBuilder builder, String builderId) throws CoreException { String nature = builder.getNatureId(); - if (nature == null) + if (nature == null) { return true; + } IProject project = builder.getProject(); if (!project.hasNature(nature)) { //remove this builder from the build spec @@ -1592,21 +1638,24 @@ public ISchedulingRule getRule(IBuildConfiguration buildConfiguration, int trigg IncrementalProjectBuilder builder = getBuilder(buildConfiguration, command, i, status, context); if (builder != null) { ISchedulingRule builderRule = builder.getRule(trigger, allArgs); - if (builderRule != null) + if (builderRule != null) { rules.add(builderRule); - else + } else { hasNullBuildRule = true; + } } } catch (CoreException e) { status.add(e.getStatus()); } } - if (rules.isEmpty()) + if (rules.isEmpty()) { return null; + } // Bug 306824 - Builders returning a null rule can't work safely if other builders require a non-null rule // Be pessimistic and fall back to the default build rule (workspace root) in this case. - if (!hasNullBuildRule) + if (!hasNullBuildRule) { return new MultiRule(rules.toArray(new ISchedulingRule[rules.size()])); + } } } else { // Returns the derived resources for the specified builderName @@ -1620,16 +1669,18 @@ public ISchedulingRule getRule(IBuildConfiguration buildConfiguration, int trigg } try { IncrementalProjectBuilder builder = getBuilder(buildConfiguration, command, -1, status); - if (builder != null) + if (builder != null) { return builder.getRule(trigger, allArgs); + } } catch (CoreException e) { status.add(e.getStatus()); } } // Log any errors - if (!status.isOK()) + if (!status.isOK()) { Policy.log(status); + } return workspace.getRoot(); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/InternalBuilder.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/InternalBuilder.java index 0e9a9c640e5..f0bf5d56917 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/InternalBuilder.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/InternalBuilder.java @@ -231,8 +231,9 @@ final void setPluginId(String value) { final void setBuildConfig(IBuildConfiguration value) { Assert.isNotNull(value); buildConfiguration = value; - if (context == null) + if (context == null) { context = new BuildContext(buildConfiguration); + } } /** diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/NodeIDMap.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/NodeIDMap.java index dd5966f97ce..95e0172cf78 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/NodeIDMap.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/NodeIDMap.java @@ -64,8 +64,9 @@ protected void expand() { int hash = hashFor(id, newLength); while (grownIds[hash] != 0) { hash++; - if (hash > maxArrayIndex) + if (hash > maxArrayIndex) { hash = 0; + } } grownIds[hash] = id; grownOldPaths[hash] = oldPaths[i]; @@ -87,20 +88,24 @@ private int getIndex(long searchID) { // search the last half of the array for (int i = hash; i < len; i++) { - if (ids[i] == searchID) + if (ids[i] == searchID) { return i; + } // marker info not found so return -1 - if (ids[i] == 0) + if (ids[i] == 0) { return -1; + } } // search the beginning of the array for (int i = 0; i < hash - 1; i++) { - if (ids[i] == searchID) + if (ids[i] == searchID) { return i; + } // marker info not found so return -1 - if (ids[i] == 0) + if (ids[i] == 0) { return -1; + } } // marker info not found so return -1 return -1; @@ -112,8 +117,9 @@ private int getIndex(long searchID) { */ public IPath getNewPath(long nodeID) { int index = getIndex(nodeID); - if (index == -1) + if (index == -1) { return null; + } return newPaths[index]; } @@ -123,8 +129,9 @@ public IPath getNewPath(long nodeID) { */ public IPath getOldPath(long nodeID) { int index = getIndex(nodeID); - if (index == -1) + if (index == -1) { return null; + } return oldPaths[index]; } @@ -146,31 +153,37 @@ public boolean isEmpty() { * or newPath is null, they are ignored (old map values are not overwritten). */ private void put(long id, IPath oldPath, IPath newPath) { - if (oldPath == null && newPath == null) + if (oldPath == null && newPath == null) { return; + } int hash = hashFor(id, ids.length); // search for an empty slot at the end of the array for (int i = hash; i < ids.length; i++) { if (ids[i] == id) { //replace value for existing entry - if (oldPath != null) + if (oldPath != null) { oldPaths[i] = oldPath; - if (newPath != null) + } + if (newPath != null) { newPaths[i] = newPath; + } return; } if (ids[i] == 0) { //add a new entry to the map ids[i] = id; - if (oldPath != null) + if (oldPath != null) { oldPaths[i] = oldPath; - if (newPath != null) + } + if (newPath != null) { newPaths[i] = newPath; + } elementCount++; // grow if necessary - if (shouldGrow()) + if (shouldGrow()) { expand(); + } return; } } @@ -179,23 +192,28 @@ private void put(long id, IPath oldPath, IPath newPath) { for (int i = 0; i < hash - 1; i++) { if (ids[i] == id) { //replace value for existing entry - if (oldPath != null) + if (oldPath != null) { oldPaths[i] = oldPath; - if (newPath != null) + } + if (newPath != null) { newPaths[i] = newPath; + } return; } if (ids[i] == 0) { //add a new entry to the map ids[i] = id; - if (oldPath != null) + if (oldPath != null) { oldPaths[i] = oldPath; - if (newPath != null) + } + if (newPath != null) { newPaths[i] = newPath; + } elementCount++; // grow if necessary - if (shouldGrow()) + if (shouldGrow()) { expand(); + } return; } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/NotificationManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/NotificationManager.java index 87e1465a359..6a36bbde5da 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/NotificationManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/NotificationManager.java @@ -53,8 +53,9 @@ public NotifyJob() { @Override public IStatus run(IProgressMonitor monitor) { - if (monitor.isCanceled()) + if (monitor.isCanceled()) { return Status.CANCEL_STATUS; + } notificationRequested = true; try { workspace.run(noop, null, IResource.NONE, null); @@ -131,8 +132,9 @@ public NotificationManager(Workspace workspace) { public void addListener(IResourceChangeListener listener, int eventMask) { listeners.add(listener, eventMask); - if (ResourceStats.TRACE_LISTENERS) + if (ResourceStats.TRACE_LISTENERS) { ResourceStats.listenerAdded(listener); + } } /** @@ -159,15 +161,17 @@ public void broadcastChanges(ElementTree lastState, ResourceChangeEvent event, b final int type = event.getType(); try { // Do the notification if there are listeners for events of the given type. - if (!listeners.hasListenerFor(type)) + if (!listeners.hasListenerFor(type)) { return; + } isNotifying = true; ResourceDelta delta = getDelta(lastState, type); //don't broadcast POST_CHANGE or autobuild events if the delta is empty if (delta == null || delta.getKind() == 0) { int trigger = event.getBuildKind(); - if (trigger == IncrementalProjectBuilder.AUTO_BUILD || trigger == 0) + if (trigger == IncrementalProjectBuilder.AUTO_BUILD || trigger == 0) { return; + } } event.setDelta(delta); long start = System.currentTimeMillis(); @@ -223,12 +227,14 @@ public void endAvoidNotify() { */ public void requestNotify() { //don't do intermediate notifications if the current thread doesn't want them - if (isNotifying || avoidNotify.contains(Thread.currentThread())) + if (isNotifying || avoidNotify.contains(Thread.currentThread())) { return; + } //notifications must never take more than one tenth of operation time long delay = Math.max(NOTIFICATION_DELAY, lastNotifyDuration * 10); - if (notifyJob.getState() == Job.NONE) + if (notifyJob.getState() == Job.NONE) { notifyJob.schedule(delay); + } } /** @@ -269,30 +275,35 @@ protected ResourceChangeListenerList.ListenerEntry[] getListeners() { public void handleEvent(LifecycleEvent event) { switch (event.kind) { case LifecycleEvent.PRE_PROJECT_CLOSE : - if (!listeners.hasListenerFor(IResourceChangeEvent.PRE_CLOSE)) + if (!listeners.hasListenerFor(IResourceChangeEvent.PRE_CLOSE)) { return; + } IProject project = (IProject) event.resource; notify(getListeners(), new ResourceChangeEvent(workspace, IResourceChangeEvent.PRE_CLOSE, project), true); break; case LifecycleEvent.PRE_PROJECT_MOVE : //only notify deletion on move if old project handle is going // away - if (event.resource.equals(event.newResource)) + if (event.resource.equals(event.newResource)) { return; + } //fall through case LifecycleEvent.PRE_PROJECT_DELETE : - if (!listeners.hasListenerFor(IResourceChangeEvent.PRE_DELETE)) + if (!listeners.hasListenerFor(IResourceChangeEvent.PRE_DELETE)) { return; + } project = (IProject) event.resource; notify(getListeners(), new ResourceChangeEvent(workspace, IResourceChangeEvent.PRE_DELETE, project), true); break; case LifecycleEvent.PRE_REFRESH : - if (!listeners.hasListenerFor(IResourceChangeEvent.PRE_REFRESH)) + if (!listeners.hasListenerFor(IResourceChangeEvent.PRE_REFRESH)) { return; - if (event.resource.getType() == IResource.PROJECT) + } + if (event.resource.getType() == IResource.PROJECT) { notify(getListeners(), new ResourceChangeEvent(event.resource, IResourceChangeEvent.PRE_REFRESH, event.resource), true); - else if (event.resource.getType() == IResource.ROOT) + } else if (event.resource.getType() == IResource.ROOT) { notify(getListeners(), new ResourceChangeEvent(workspace, IResourceChangeEvent.PRE_REFRESH, null), true); + } break; } } @@ -300,14 +311,16 @@ else if (event.resource.getType() == IResource.ROOT) private void notify(ResourceChangeListenerList.ListenerEntry[] resourceListeners, final ResourceChangeEvent event, final boolean lockTree) { int type = event.getType(); boolean oldLock = workspace.isTreeLocked(); - if (lockTree) + if (lockTree) { workspace.setTreeLocked(true); + } try { for (ListenerEntry resourceListener : resourceListeners) { if ((type & resourceListener.eventMask) != 0) { final IResourceChangeListener listener = resourceListener.listener; - if (ResourceStats.TRACE_LISTENERS) + if (ResourceStats.TRACE_LISTENERS) { ResourceStats.startNotify(listener); + } SafeRunner.run(new ISafeRunnable() { @Override public void handleException(Throwable e) { @@ -316,25 +329,29 @@ public void handleException(Throwable e) { @Override public void run() throws Exception { - if (Policy.DEBUG_NOTIFICATIONS) + if (Policy.DEBUG_NOTIFICATIONS) { Policy.debug("Notifying " + listener.getClass().getName() + " about resource change event" + event.toDebugString()); //$NON-NLS-1$ //$NON-NLS-2$ + } listener.resourceChanged(event); } }); - if (ResourceStats.TRACE_LISTENERS) + if (ResourceStats.TRACE_LISTENERS) { ResourceStats.endNotify(); + } } } } finally { - if (lockTree) + if (lockTree) { workspace.setTreeLocked(oldLock); + } } } public void removeListener(IResourceChangeListener listener) { listeners.remove(listener); - if (ResourceStats.TRACE_LISTENERS) + if (ResourceStats.TRACE_LISTENERS) { ResourceStats.listenerRemoved(listener); + } } /** diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/PathVariableChangeEvent.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/PathVariableChangeEvent.java index bbf553df343..9ffcdc1adb1 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/PathVariableChangeEvent.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/PathVariableChangeEvent.java @@ -43,8 +43,9 @@ public class PathVariableChangeEvent extends EventObject implements IPathVariabl */ public PathVariableChangeEvent(IPathVariableManager source, String variableName, IPath value, int type) { super(source); - if (type < VARIABLE_CHANGED || type > VARIABLE_DELETED) + if (type < VARIABLE_CHANGED || type > VARIABLE_DELETED) { throw new IllegalArgumentException("Invalid event type: " + type); //$NON-NLS-1$ + } this.variableName = variableName; this.value = value; this.type = type; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceChangeEvent.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceChangeEvent.java index b13d62af244..43daf101a56 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceChangeEvent.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceChangeEvent.java @@ -50,15 +50,18 @@ public ResourceChangeEvent(Object source, int type, int buildKind, IResourceDelt */ @Override public IMarkerDelta[] findMarkerDeltas(String findType, boolean includeSubtypes) { - if (delta == null) + if (delta == null) { return NO_MARKER_DELTAS; + } ResourceDeltaInfo info = ((ResourceDelta) delta).getDeltaInfo(); - if (info == null) + if (info == null) { return NO_MARKER_DELTAS; + } //Map of IPath -> MarkerSet containing MarkerDelta objects Map markerDeltas = info.getMarkerDeltas(); - if (markerDeltas == null || markerDeltas.isEmpty()) + if (markerDeltas == null || markerDeltas.isEmpty()) { return NO_MARKER_DELTAS; + } ArrayList matching = new ArrayList<>(); Iterator deltaSets = markerDeltas.values().iterator(); while (deltaSets.hasNext()) { @@ -67,8 +70,9 @@ public IMarkerDelta[] findMarkerDeltas(String findType, boolean includeSubtypes) for (IMarkerSetElement element : elements) { MarkerDelta markerDelta = (MarkerDelta) element; //our inclusion test depends on whether we are considering subtypes - if (findType == null || (includeSubtypes ? markerDelta.isSubtypeOf(findType) : markerDelta.getType().equals(findType))) + if (findType == null || (includeSubtypes ? markerDelta.isSubtypeOf(findType) : markerDelta.getType().equals(findType))) { matching.add(markerDelta); + } } } return matching.toArray(new IMarkerDelta[matching.size()]); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceChangeListenerList.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceChangeListenerList.java index 825fdd8cea4..3fc2de8496e 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceChangeListenerList.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceChangeListenerList.java @@ -96,18 +96,24 @@ public synchronized void add(IResourceChangeListener listener, int mask) { } private void adding(int mask) { - if ((mask & 1) != 0) + if ((mask & 1) != 0) { count1++; - if ((mask & 2) != 0) + } + if ((mask & 2) != 0) { count2++; - if ((mask & 4) != 0) + } + if ((mask & 4) != 0) { count4++; - if ((mask & 8) != 0) + } + if ((mask & 8) != 0) { count8++; - if ((mask & 16) != 0) + } + if ((mask & 16) != 0) { count16++; - if ((mask & 32) != 0) + } + if ((mask & 32) != 0) { count32++; + } } /** @@ -167,18 +173,24 @@ public synchronized void clear() { } private void removing(int mask) { - if ((mask & 1) != 0) + if ((mask & 1) != 0) { count1--; - if ((mask & 2) != 0) + } + if ((mask & 2) != 0) { count2--; - if ((mask & 4) != 0) + } + if ((mask & 4) != 0) { count4--; - if ((mask & 8) != 0) + } + if ((mask & 8) != 0) { count8--; - if ((mask & 16) != 0) + } + if ((mask & 16) != 0) { count16--; - if ((mask & 32) != 0) + } + if ((mask & 32) != 0) { count32--; + } } @Override diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceComparator.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceComparator.java index a0a2a37368d..59f4b4e2a89 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceComparator.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceComparator.java @@ -85,49 +85,64 @@ private ResourceComparator(boolean notification, boolean save) { @Override public int compare(Object o1, Object o2) { // == handles null, null. - if (o1 == o2) + if (o1 == o2) { return IResourceDelta.NO_CHANGE; + } int result = 0; - if (o1 == null) + if (o1 == null) { return ((ResourceInfo) o2).isSet(M_PHANTOM) ? IResourceDelta.ADDED_PHANTOM : IResourceDelta.ADDED; - if (o2 == null) + } + if (o2 == null) { return ((ResourceInfo) o1).isSet(M_PHANTOM) ? IResourceDelta.REMOVED_PHANTOM : IResourceDelta.REMOVED; - if (!(o1 instanceof ResourceInfo && o2 instanceof ResourceInfo)) + } + if (!(o1 instanceof ResourceInfo oldElement && o2 instanceof ResourceInfo)) { return IResourceDelta.NO_CHANGE; - ResourceInfo oldElement = (ResourceInfo) o1; + } ResourceInfo newElement = (ResourceInfo) o2; - if (!oldElement.isSet(M_PHANTOM) && newElement.isSet(M_PHANTOM)) + if (!oldElement.isSet(M_PHANTOM) && newElement.isSet(M_PHANTOM)) { return IResourceDelta.REMOVED; - if (oldElement.isSet(M_PHANTOM) && !newElement.isSet(M_PHANTOM)) + } + if (oldElement.isSet(M_PHANTOM) && !newElement.isSet(M_PHANTOM)) { return IResourceDelta.ADDED; - if (!compareOpen(oldElement, newElement)) + } + if (!compareOpen(oldElement, newElement)) { result |= IResourceDelta.OPEN; + } if (!compareContents(oldElement, newElement)) { - if (oldElement.getType() == IResource.PROJECT) + if (oldElement.getType() == IResource.PROJECT) { result |= IResourceDelta.DESCRIPTION; - else if (newElement.getType() == IResource.FILE || oldElement.getType() == IResource.FILE) + } else if (newElement.getType() == IResource.FILE || oldElement.getType() == IResource.FILE) { result |= IResourceDelta.CONTENT; + } } - if (!compareType(oldElement, newElement)) + if (!compareType(oldElement, newElement)) { result |= IResourceDelta.TYPE; + } if (!compareNodeIDs(oldElement, newElement)) { result |= IResourceDelta.REPLACED; // if the node was replaced and the old and new were files, this is also a content change. - if (oldElement.getType() == IResource.FILE && newElement.getType() == IResource.FILE) + if (oldElement.getType() == IResource.FILE && newElement.getType() == IResource.FILE) { result |= IResourceDelta.CONTENT; + } } - if (compareLocal(oldElement, newElement)) + if (compareLocal(oldElement, newElement)) { result |= IResourceDelta.LOCAL_CHANGED; - if (!compareCharsets(oldElement, newElement)) + } + if (!compareCharsets(oldElement, newElement)) { result |= IResourceDelta.ENCODING; - if (!compareDerived(oldElement, newElement)) + } + if (!compareDerived(oldElement, newElement)) { result |= IResourceDelta.DERIVED_CHANGED; - if (notification && !compareSync(oldElement, newElement)) + } + if (notification && !compareSync(oldElement, newElement)) { result |= IResourceDelta.SYNC; - if (notification && !compareMarkers(oldElement, newElement)) + } + if (notification && !compareMarkers(oldElement, newElement)) { result |= IResourceDelta.MARKERS; - if (save && !compareUsed(oldElement, newElement)) + } + if (save && !compareUsed(oldElement, newElement)) { result |= IResourceDelta.CHANGED; + } return result == 0 ? 0 : result | IResourceDelta.CHANGED; } @@ -151,8 +166,9 @@ private boolean compareContents(ResourceInfo oldElement, ResourceInfo newElement */ private boolean compareLocal(ResourceInfo oldElement, ResourceInfo newElement) { //only applicable for linked resources - if (!oldElement.isSet(ICoreConstants.M_LINK) || !newElement.isSet(ICoreConstants.M_LINK)) + if (!oldElement.isSet(ICoreConstants.M_LINK) || !newElement.isSet(ICoreConstants.M_LINK)) { return false; + } long oldStamp = oldElement.getModificationStamp(); long newStamp = newElement.getModificationStamp(); return (oldStamp == -1 || newStamp == -1) && (oldStamp != newStamp); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceDelta.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceDelta.java index 03d7c918b22..279417156d4 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceDelta.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceDelta.java @@ -72,18 +72,23 @@ public void accept(IResourceDeltaVisitor visitor, int memberFlags) throws CoreEx final boolean includeTeamPrivate = (memberFlags & IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS) != 0; final boolean includeHidden = (memberFlags & IContainer.INCLUDE_HIDDEN) != 0; int mask = includePhantoms ? ALL_WITH_PHANTOMS : REMOVED | ADDED | CHANGED; - if ((getKind() & mask) == 0) + if ((getKind() & mask) == 0) { return; - if (!visitor.visit(this)) + } + if (!visitor.visit(this)) { return; + } for (ResourceDelta childDelta : children) { // quietly exclude team-private, hidden and phantom members unless explicitly included - if (!includeTeamPrivate && childDelta.isTeamPrivate()) + if (!includeTeamPrivate && childDelta.isTeamPrivate()) { continue; - if (!includePhantoms && childDelta.isPhantom()) + } + if (!includePhantoms && childDelta.isPhantom()) { continue; - if (!includeHidden && childDelta.isHidden()) + } + if (!includeHidden && childDelta.isHidden()) { continue; + } childDelta.accept(visitor, memberFlags); } } @@ -92,8 +97,9 @@ public void accept(IResourceDeltaVisitor visitor, int memberFlags) throws CoreEx * Check for marker deltas, and set the appropriate change flag if there are any. */ protected void checkForMarkerDeltas() { - if (deltaInfo.getMarkerDeltas() == null) + if (deltaInfo.getMarkerDeltas() == null) { return; + } int kind = getKind(); // Only need to check for added and removed, or for changes on the workspace. // For changed, the bit is set in the comparator. @@ -103,8 +109,9 @@ protected void checkForMarkerDeltas() { status |= MARKERS; // If there have been marker changes, then ensure kind is CHANGED (if not ADDED or REMOVED). // See 1FV9K20: ITPUI:WINNT - severe - task list - add or delete not working - if (kind == 0) + if (kind == 0) { status |= CHANGED; + } } } } @@ -112,8 +119,9 @@ protected void checkForMarkerDeltas() { @Override public IResourceDelta findMember(IPath memberPath) { int segmentCount = memberPath.segmentCount(); - if (segmentCount == 0) + if (segmentCount == 0) { return this; + } //iterate over the path and find matching child delta ResourceDelta current = this; @@ -153,11 +161,13 @@ protected void fixMovesAndMarkers(ElementTree oldTree) { status = (status & KIND_MASK) | (deltaInfo.getComparator().compare(actualOldInfo, newInfo) & ~KIND_MASK); status |= MOVED_FROM; //our API states that MOVED_FROM must be in conjunction with ADDED | (CHANGED + REPLACED) - if (kind == CHANGED) + if (kind == CHANGED) { status = status | REPLACED | CONTENT; + } //check for gender change - if (oldInfo != null && newInfo != null && oldInfo.getType() != newInfo.getType()) + if (oldInfo != null && newInfo != null && oldInfo.getType() != newInfo.getType()) { status |= TYPE; + } } } switch (kind) { @@ -167,8 +177,9 @@ protected void fixMovesAndMarkers(ElementTree oldTree) { if (newPath != null && !newPath.equals(path)) { status |= MOVED_TO; //our API states that MOVED_TO must be in conjunction with REMOVED | (CHANGED + REPLACED) - if (kind == CHANGED) + if (kind == CHANGED) { status = status | REPLACED | CONTENT; + } } } } @@ -178,8 +189,9 @@ protected void fixMovesAndMarkers(ElementTree oldTree) { checkForMarkerDeltas(); //recurse on children - for (ResourceDelta element : children) + for (ResourceDelta element : children) { element.fixMovesAndMarkers(oldTree); + } } @Override @@ -196,26 +208,32 @@ public IResourceDelta[] getAffectedChildren(int kindMask) { public IResourceDelta[] getAffectedChildren(int kindMask, int memberFlags) { int numChildren = children.length; //if there are no children, they all match - if (numChildren == 0) + if (numChildren == 0) { return children; + } boolean includePhantoms = (memberFlags & IContainer.INCLUDE_PHANTOMS) != 0; boolean includeTeamPrivate = (memberFlags & IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS) != 0; boolean includeHidden = (memberFlags & IContainer.INCLUDE_HIDDEN) != 0; // reduce INCLUDE_PHANTOMS member flag to kind mask - if (includePhantoms) + if (includePhantoms) { kindMask |= ADDED_PHANTOM | REMOVED_PHANTOM; + } //first count the number of matches so we can allocate the exact array size int matching = 0; for (int i = 0; i < numChildren; i++) { - if ((children[i].getKind() & kindMask) == 0) + if ((children[i].getKind() & kindMask) == 0) { continue;// child has wrong kind - if (!includePhantoms && children[i].isPhantom()) + } + if (!includePhantoms && children[i].isPhantom()) { continue; - if (!includeTeamPrivate && children[i].isTeamPrivate()) + } + if (!includeTeamPrivate && children[i].isTeamPrivate()) { continue; // child has is a team-private member which are not included - if (!includeHidden && children[i].isHidden()) + } + if (!includeHidden && children[i].isHidden()) { continue; + } matching++; } //use arraycopy if all match @@ -228,14 +246,18 @@ public IResourceDelta[] getAffectedChildren(int kindMask, int memberFlags) { IResourceDelta[] result = new IResourceDelta[matching]; int nextPosition = 0; for (int i = 0; i < numChildren; i++) { - if ((children[i].getKind() & kindMask) == 0) + if ((children[i].getKind() & kindMask) == 0) { continue; // child has wrong kind - if (!includePhantoms && children[i].isPhantom()) + } + if (!includePhantoms && children[i].isPhantom()) { continue; - if (!includeTeamPrivate && children[i].isTeamPrivate()) + } + if (!includeTeamPrivate && children[i].isTeamPrivate()) { continue; // child has is a team-private member which are not included - if (!includeHidden && children[i].isHidden()) + } + if (!includeHidden && children[i].isHidden()) { continue; + } result[nextPosition++] = children[i]; } return result; @@ -263,17 +285,21 @@ public int getKind() { @Override public IMarkerDelta[] getMarkerDeltas() { Map markerDeltas = deltaInfo.getMarkerDeltas(); - if (markerDeltas == null) + if (markerDeltas == null) { return EMPTY_MARKER_DELTAS; - if (path == null) + } + if (path == null) { path = IPath.ROOT; + } MarkerSet changes = markerDeltas.get(path); - if (changes == null) + if (changes == null) { return EMPTY_MARKER_DELTAS; + } IMarkerSetElement[] elements = changes.elements(); IMarkerDelta[] result = new IMarkerDelta[elements.length]; - for (int i = 0; i < elements.length; i++) + for (int i = 0; i < elements.length; i++) { result[i] = (IMarkerDelta) elements[i]; + } return result; } @@ -297,29 +323,34 @@ public IPath getMovedToPath() { public IPath getProjectRelativePath() { IPath full = getFullPath(); int count = full.segmentCount(); - if (count < 0) + if (count < 0) { return null; - if (count <= 1) // 0 or 1 + } + if (count <= 1) { // 0 or 1 return IPath.EMPTY; + } return full.removeFirstSegments(1); } @Override public IResource getResource() { // return a cached copy if we have one - if (cachedResource != null) + if (cachedResource != null) { return cachedResource; + } // if this is a delta for the root then return the root resource - if (path.segmentCount() == 0) + if (path.segmentCount() == 0) { return deltaInfo.getWorkspace().getRoot(); + } // if the delta is a remove then we have to look for the old info to find the type // of resource to create. ResourceInfo info = null; - if ((getKind() & (REMOVED | REMOVED_PHANTOM)) != 0) + if ((getKind() & (REMOVED | REMOVED_PHANTOM)) != 0) { info = oldInfo; - else + } else { info = newInfo; + } Assert.isNotNull(info, "Do not have resource info for resource in delta: " + path); //$NON-NLS-1$ cachedResource = deltaInfo.getWorkspace().newResource(path, info.getType()); return cachedResource; @@ -331,8 +362,9 @@ public IResource getResource() { */ protected boolean isPhantom() { //use old info for removals, and new info for added or changed - if ((status & (REMOVED | REMOVED_PHANTOM)) != 0) + if ((status & (REMOVED | REMOVED_PHANTOM)) != 0) { return ResourceInfo.isSet(oldInfo.getFlags(), ICoreConstants.M_PHANTOM); + } return ResourceInfo.isSet(newInfo.getFlags(), ICoreConstants.M_PHANTOM); } @@ -342,8 +374,9 @@ protected boolean isPhantom() { */ protected boolean isTeamPrivate() { //use old info for removals, and new info for added or changed - if ((status & (REMOVED | REMOVED_PHANTOM)) != 0) + if ((status & (REMOVED | REMOVED_PHANTOM)) != 0) { return ResourceInfo.isSet(oldInfo.getFlags(), ICoreConstants.M_TEAM_PRIVATE_MEMBER); + } return ResourceInfo.isSet(newInfo.getFlags(), ICoreConstants.M_TEAM_PRIVATE_MEMBER); } @@ -353,8 +386,9 @@ protected boolean isTeamPrivate() { */ protected boolean isHidden() { //use old info for removals, and new info for added or changed - if ((status & (REMOVED | REMOVED_PHANTOM)) != 0) + if ((status & (REMOVED | REMOVED_PHANTOM)) != 0) { return ResourceInfo.isSet(oldInfo.getFlags(), ICoreConstants.M_HIDDEN); + } return ResourceInfo.isSet(newInfo.getFlags(), ICoreConstants.M_HIDDEN); } @@ -391,8 +425,9 @@ public String toDebugString() { public String toDeepDebugString() { final StringBuilder buffer = new StringBuilder("\n"); //$NON-NLS-1$ writeDebugString(buffer); - for (ResourceDelta element : children) + for (ResourceDelta element : children) { buffer.append(element.toDeepDebugString()); + } return buffer.toString(); } @@ -447,89 +482,104 @@ public void writeDebugString(StringBuilder buffer) { int changeFlags = getFlags(); boolean prev = false; if ((changeFlags & CONTENT) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("CONTENT"); //$NON-NLS-1$ prev = true; } if ((changeFlags & LOCAL_CHANGED) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("LOCAL_CHANGED"); //$NON-NLS-1$ prev = true; } if ((changeFlags & MOVED_FROM) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("MOVED_FROM(" + getMovedFromPath() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ prev = true; } if ((changeFlags & MOVED_TO) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("MOVED_TO(" + getMovedToPath() + ")"); //$NON-NLS-1$ //$NON-NLS-2$ prev = true; } if ((changeFlags & OPEN) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("OPEN"); //$NON-NLS-1$ prev = true; } if ((changeFlags & TYPE) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("TYPE"); //$NON-NLS-1$ prev = true; } if ((changeFlags & SYNC) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("SYNC"); //$NON-NLS-1$ prev = true; } if ((changeFlags & MARKERS) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("MARKERS"); //$NON-NLS-1$ writeMarkerDebugString(buffer); prev = true; } if ((changeFlags & REPLACED) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("REPLACED"); //$NON-NLS-1$ prev = true; } if ((changeFlags & DESCRIPTION) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("DESCRIPTION"); //$NON-NLS-1$ prev = true; } if ((changeFlags & ENCODING) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("ENCODING"); //$NON-NLS-1$ prev = true; } if ((changeFlags & DERIVED_CHANGED) != 0) { - if (prev) + if (prev) { buffer.append(" | "); //$NON-NLS-1$ + } buffer.append("DERIVED_CHANGED"); //$NON-NLS-1$ prev = true; } buffer.append("}"); //$NON-NLS-1$ - if (isTeamPrivate()) + if (isTeamPrivate()) { buffer.append(" (team private)"); //$NON-NLS-1$ - if (isHidden()) + } + if (isHidden()) { buffer.append(" (hidden)"); //$NON-NLS-1$ + } } public void writeMarkerDebugString(StringBuilder buffer) { Map markerDeltas = deltaInfo.getMarkerDeltas(); - if (markerDeltas == null || markerDeltas.isEmpty()) + if (markerDeltas == null || markerDeltas.isEmpty()) { return; + } buffer.append('['); for (Entry entry : markerDeltas.entrySet()) { IPath key = entry.getKey(); @@ -539,8 +589,9 @@ public void writeMarkerDebugString(StringBuilder buffer) { boolean addComma = false; for (IMarkerSetElement delta2 : deltas) { IMarkerDelta delta = (IMarkerDelta) delta2; - if (addComma) + if (addComma) { buffer.append(','); + } switch (delta.getKind()) { case IResourceDelta.ADDED : buffer.append('+'); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceDeltaFactory.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceDeltaFactory.java index 73d96433c1f..ea05b018ae2 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceDeltaFactory.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceDeltaFactory.java @@ -48,10 +48,11 @@ public static ResourceDelta computeDelta(Workspace workspace, ElementTree oldTre ResourceComparator comparator = markerGeneration >= 0 ? ResourceComparator.getNotificationComparator() : ResourceComparator.getBuildComparator(); newTree.immutable(); DeltaDataTree delta = null; - if (IPath.ROOT.equals(root)) + if (IPath.ROOT.equals(root)) { delta = newTree.getDataTree().compareWith(oldTree.getDataTree(), comparator); - else + } else { delta = newTree.getDataTree().compareWith(oldTree.getDataTree(), comparator, root); + } delta = delta.asReverseComparisonTree(comparator); IPath pathInTree = root.isRoot() ? IPath.ROOT : root; @@ -59,8 +60,9 @@ public static ResourceDelta computeDelta(Workspace workspace, ElementTree oldTre // get the marker deltas for the delta info object....if needed Map allMarkerDeltas = null; - if (markerGeneration >= 0) + if (markerGeneration >= 0) { allMarkerDeltas = workspace.getMarkerManager().getMarkerDeltas(markerGeneration); + } //recursively walk the delta and create a tree of ResourceDelta objects. ResourceDeltaInfo deltaInfo = new ResourceDeltaInfo(workspace, allMarkerDeltas, comparator); @@ -73,8 +75,9 @@ public static ResourceDelta computeDelta(Workspace workspace, ElementTree oldTre // check all the projects and if they were added and opened then tweek the flags // so the delta reports both. int segmentCount = result.getFullPath().segmentCount(); - if (segmentCount <= 1) + if (segmentCount <= 1) { checkForOpen(result, segmentCount); + } return result; } @@ -84,16 +87,20 @@ public static ResourceDelta computeDelta(Workspace workspace, ElementTree oldTre * in since we've already calculated it before. */ protected static void checkForOpen(ResourceDelta delta, int segmentCount) { - if (delta.getKind() == IResourceDelta.ADDED) - if (delta.newInfo.isSet(ICoreConstants.M_OPEN)) + if (delta.getKind() == IResourceDelta.ADDED) { + if (delta.newInfo.isSet(ICoreConstants.M_OPEN)) { delta.status |= IResourceDelta.OPEN; + } + } // return for PROJECT - if (segmentCount == 1) + if (segmentCount == 1) { return; + } // recurse for ROOT IResourceDelta[] children = delta.children; - for (IResourceDelta element : children) + for (IResourceDelta element : children) { checkForOpen((ResourceDelta) element, 1); + } } /** @@ -165,8 +172,9 @@ protected static ResourceDelta createDelta(Workspace workspace, DeltaDataTree de // if this delta has children but no other changes, mark it as changed int status = result.status; - if ((status & IResourceDelta.ALL_WITH_PHANTOMS) == 0 && numChildren != 0) + if ((status & IResourceDelta.ALL_WITH_PHANTOMS) == 0 && numChildren != 0) { result.setStatus(status |= IResourceDelta.CHANGED); + } // return the delta return result; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceStats.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceStats.java index 8213c62cfba..6676f75e4b3 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceStats.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/events/ResourceStats.java @@ -38,26 +38,30 @@ public class ResourceStats { public static boolean TRACE_SNAPSHOT = PerformanceStats.isEnabled(ResourceStats.EVENT_SNAPSHOT); public static void endBuild() { - if (currentStats != null) + if (currentStats != null) { currentStats.endRun(); + } currentStats = null; } public static void endNotify() { - if (currentStats != null) + if (currentStats != null) { currentStats.endRun(); + } currentStats = null; } public static void endSave() { - if (currentStats != null) + if (currentStats != null) { currentStats.endRun(); + } currentStats = null; } public static void endSnapshot() { - if (currentStats != null) + if (currentStats != null) { currentStats.endRun(); + } currentStats = null; } @@ -65,16 +69,18 @@ public static void endSnapshot() { * Notifies the stats tool that a resource change listener has been added. */ public static void listenerAdded(IResourceChangeListener listener) { - if (listener != null) + if (listener != null) { PerformanceStats.getStats(EVENT_LISTENERS, listener.getClass().getName()); + } } /** * Notifies the stats tool that a resource change listener has been removed. */ public static void listenerRemoved(IResourceChangeListener listener) { - if (listener != null) + if (listener != null) { PerformanceStats.removeStats(EVENT_LISTENERS, listener.getClass().getName()); + } } public static void startBuild(IncrementalProjectBuilder builder) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/BlobStore.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/BlobStore.java index 3b23b1891e3..3587ef9d40e 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/BlobStore.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/BlobStore.java @@ -53,10 +53,11 @@ public UniversalUniqueIdentifier addBlob(IFileStore target, boolean moveContents UniversalUniqueIdentifier uuid = new UniversalUniqueIdentifier(); folderFor(uuid).mkdir(EFS.NONE, null); IFileStore destination = fileFor(uuid); - if (moveContents) + if (moveContents) { target.move(destination, EFS.NONE, null); - else + } else { target.copy(destination, EFS.NONE, null); + } return uuid; } @@ -66,12 +67,14 @@ public UniversalUniqueIdentifier addBlob(IFileStore target, boolean moveContents @SuppressWarnings("javadoc") private void appendByteString(StringBuilder buffer, byte value) { String hexString; - if (value < 0) + if (value < 0) { hexString = Integer.toHexString(256 + value); - else + } else { hexString = Integer.toHexString(value); - if (hexString.length() == 1) + } + if (hexString.length() == 1) { buffer.append("0"); //$NON-NLS-1$ + } buffer.append(hexString); } @@ -82,8 +85,9 @@ private void appendByteString(StringBuilder buffer, byte value) { */ private String bytesToHexString(byte[] b) { StringBuilder buffer = new StringBuilder(); - for (byte element : b) + for (byte element : b) { appendByteString(buffer, element); + } return buffer.toString(); } @@ -103,8 +107,9 @@ public void deleteBlob(UniversalUniqueIdentifier uuid) { * Delete all of the blobs in the given set. */ public void deleteBlobs(Set set) { - for (UniversalUniqueIdentifier id : set) + for (UniversalUniqueIdentifier id : set) { deleteBlob(id); + } } public IFileStore fileFor(UniversalUniqueIdentifier uuid) { @@ -134,8 +139,9 @@ public InputStream getBlob(UniversalUniqueIdentifier uuid) throws CoreException protected byte hashUUIDbytes(UniversalUniqueIdentifier uuid) { byte[] bytes = uuid.toBytes(); byte hash = 0; - for (byte b : bytes) + for (byte b : bytes) { hash ^= randomArray[b + 128]; // +128 makes sure the index is >0 + } return hash; } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/Bucket.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/Bucket.java index ef586ff5b58..bac711a893a 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/Bucket.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/Bucket.java @@ -209,16 +209,18 @@ public Bucket(boolean cacheEntries) { * @exception CoreException thrown by the visitor or from a failed save */ public final int accept(Visitor visitor, IPath filter, int depth) throws CoreException { - if (entries.isEmpty()) + if (entries.isEmpty()) { return Visitor.CONTINUE; + } try { for (Iterator> i = entries.entrySet().iterator(); i.hasNext();) { Map.Entry mapEntry = i.next(); IPath path = IPath.fromOSString(mapEntry.getKey()); // check whether the filter applies int matchingSegments = filter.matchingFirstSegments(path); - if (!filter.isPrefixOf(path) || path.segmentCount() - matchingSegments > depth) + if (!filter.isPrefixOf(path) || path.segmentCount() - matchingSegments > depth) { continue; + } // apply visitor Entry bucketEntry = createEntry(path, mapEntry.getValue()); // calls the visitor passing all uuids for the entry @@ -232,8 +234,9 @@ public final int accept(Visitor visitor, IPath filter, int depth) throws CoreExc needSaving = true; mapEntry.setValue(bucketEntry.getValue()); } - if (outcome != Visitor.CONTINUE) + if (outcome != Visitor.CONTINUE) { return outcome; + } } return Visitor.CONTINUE; } finally { @@ -247,12 +250,14 @@ public final int accept(Visitor visitor, IPath filter, int depth) throws CoreExc * Tries to delete as many empty levels as possible. */ private void cleanUp(File toDelete) { - if (!toDelete.delete()) + if (!toDelete.delete()) { // if deletion didn't go well, don't bother trying to delete the parent dir return; + } // don't try to delete beyond the root for bucket indexes - if (toDelete.getName().equals(INDEXES_DIR_NAME)) + if (toDelete.getName().equals(INDEXES_DIR_NAME)) { return; + } // recurse to parent directory cleanUp(toDelete.getParentFile()); } @@ -387,8 +392,9 @@ private Map loadEntries(File indexFile) throws CoreException, IO } private String readEntryKey(DataInputStream source) throws IOException { - if (projectName == null) + if (projectName == null) { return source.readUTF(); + } return IPath.SEPARATOR + projectName + source.readUTF(); } @@ -415,8 +421,9 @@ public void save() throws CoreException { cache.put(key, entriesSnapshot); // remember the entries in cache } } - if (!needSaving) + if (!needSaving) { return; + } try { if (entriesSnapshot.isEmpty()) { needSaving = false; @@ -425,8 +432,9 @@ public void save() throws CoreException { } // ensure the parent location exists File parent = location.getParentFile(); - if (parent == null) + if (parent == null) { throw new IOException();//caught and rethrown below + } parent.mkdirs(); try (DataOutputStream destination = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(location), 8192))) { destination.write(getVersion()); @@ -449,10 +457,11 @@ public void save() throws CoreException { * removes the entry. */ public final void setEntryValue(String path, Object value) { - if (value == null) + if (value == null) { entries.remove(path); - else + } else { entries.put(path, value); + } needSaving = true; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/BucketTree.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/BucketTree.java index edb7d6a344b..308bc89cd7e 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/BucketTree.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/BucketTree.java @@ -45,8 +45,9 @@ public class BucketTree { static { HEX_STRINGS = new char[SEGMENT_QUOTA][]; - for (int i = 0; i < HEX_STRINGS.length; i++) + for (int i = 0; i < HEX_STRINGS.length; i++) { HEX_STRINGS[i] = Integer.toHexString(i).toCharArray(); + } } protected Bucket current; @@ -71,10 +72,12 @@ public BucketTree(Workspace workspace, Bucket bucket) { public void accept(Bucket.Visitor visitor, IPath base, int depth) throws CoreException { if (IPath.ROOT.equals(base)) { current.load(null, locationFor(IPath.ROOT)); - if (current.accept(visitor, base, DEPTH_ZERO) != Visitor.CONTINUE) + if (current.accept(visitor, base, DEPTH_ZERO) != Visitor.CONTINUE) { return; - if (depth == DEPTH_ZERO) + } + if (depth == DEPTH_ZERO) { return; + } boolean keepVisiting = true; depth--; IProject[] projects = workspace.getRoot().getProjects(IContainer.INCLUDE_HIDDEN); @@ -82,8 +85,9 @@ public void accept(Bucket.Visitor visitor, IPath base, int depth) throws CoreExc IPath projectPath = projects[i].getFullPath(); keepVisiting = internalAccept(visitor, projectPath, locationFor(projectPath), depth, 1); } - } else + } else { internalAccept(visitor, base, locationFor(base), depth, 0); + } } public void close() throws CoreException { @@ -107,13 +111,16 @@ public File getVersionFile() { private boolean internalAccept(Bucket.Visitor visitor, IPath base, File bucketDir, int depthRequested, int currentDepth) throws CoreException { current.load(base.segment(0), bucketDir); int outcome = current.accept(visitor, base, depthRequested); - if (outcome != Visitor.CONTINUE) + if (outcome != Visitor.CONTINUE) { return outcome == Visitor.RETURN; - if (depthRequested <= currentDepth) + } + if (depthRequested <= currentDepth) { return true; + } File[] subDirs = bucketDir.listFiles(); - if (subDirs == null) + if (subDirs == null) { return true; + } for (File subDir : subDirs) { if (subDir.isDirectory()) { if (!internalAccept(visitor, base, subDir, depthRequested, currentDepth + 1)) { @@ -151,8 +158,9 @@ private File locationFor(IPath resourcePath) { */ private void saveVersion() throws CoreException { File versionFile = getVersionFile(); - if (!versionFile.getParentFile().exists()) + if (!versionFile.getParentFile().exists()) { versionFile.getParentFile().mkdirs(); + } try (FileOutputStream stream = new FileOutputStream(versionFile)) { stream.write(current.getVersion()); } catch (IOException e) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/CollectSyncStatusVisitor.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/CollectSyncStatusVisitor.java index 8600b36269b..8295379d932 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/CollectSyncStatusVisitor.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/CollectSyncStatusVisitor.java @@ -52,8 +52,9 @@ public CollectSyncStatusVisitor(String multiStatusTitle, IProgressMonitor monito protected void changed(Resource target) { String message = NLS.bind(Messages.localstore_resourceIsOutOfSync, target.getFullPath()); status.add(new ResourceStatus(IResourceStatus.OUT_OF_SYNC_LOCAL, target.getFullPath(), message)); - if (affectedResources == null) + if (affectedResources == null) { affectedResources = new ArrayList<>(20); + } affectedResources.add(target); resourceChanged = true; } @@ -65,8 +66,9 @@ protected void createResource(UnifiedTreeNode node, Resource target) { @Override protected void deleteResource(UnifiedTreeNode node, Resource target) { - if (!ignoreLocalDeletions) + if (!ignoreLocalDeletions) { changed(target); + } } @Override diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/CopyVisitor.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/CopyVisitor.java index 9687c8b95cc..464fc908a75 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/CopyVisitor.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/CopyVisitor.java @@ -86,8 +86,9 @@ protected boolean copy(UnifiedTreeNode node) { Resource source = (Resource) node.getResource(); IPath sufix = source.getFullPath().removeFirstSegments(segmentsToDrop); Resource destination = getDestinationResource(source, sufix); - if (!copyProperties(source, destination)) + if (!copyProperties(source, destination)) { return false; + } return copyContents(node, source, destination); } @@ -117,16 +118,18 @@ protected boolean copyContents(UnifiedTreeNode node, Resource source, Resource d SubMonitor subMonitor = SubMonitor.convert(monitor.newChild(work), 2); work = 0; //ensure the parent of the root destination exists (bug 126104) - if (destination == rootDestination) + if (destination == rootDestination) { destinationStore.getParent().mkdir(EFS.NONE, subMonitor.newChild(1)); + } sourceStore.copy(destinationStore, EFS.SHALLOW, subMonitor.newChild(1)); //create the destination in the workspace ResourceInfo info = localManager.getWorkspace().createResource(destination, updateFlags); localManager.updateLocalSync(info, destinationStore.fetchInfo().getLastModified()); //update timestamps on aliases getWorkspace().getAliasManager().updateAliases(destination, destinationStore, IResource.DEPTH_ZERO, monitor); - if (destination.getType() == IResource.FILE) + if (destination.getType() == IResource.FILE) { ((File) destination).updateMetadataFiles(); + } } catch (CoreException e) { status.add(e.getStatus()); } @@ -144,8 +147,9 @@ protected boolean copyProperties(Resource target, Resource destination) { } protected Resource getDestinationResource(Resource source, IPath suffix) { - if (suffix.segmentCount() == 0) + if (suffix.segmentCount() == 0) { return (Resource) rootDestination; + } IPath destinationPath = rootDestination.getFullPath().append(suffix); return getWorkspace().newResource(destinationPath, source.getType()); } @@ -154,8 +158,9 @@ protected Resource getDestinationResource(Resource source, IPath suffix) { * This is done in order to generate less garbage. */ protected RefreshLocalVisitor getRefreshLocalVisitor() { - if (refreshLocalVisitor == null) + if (refreshLocalVisitor == null) { refreshLocalVisitor = new RefreshLocalVisitor(null); + } return refreshLocalVisitor; } @@ -169,21 +174,26 @@ protected Workspace getWorkspace() { protected boolean isSynchronized(UnifiedTreeNode node) { /* virtual resources are always deemed as being synchronized */ - if (node.getResource().isVirtual()) + if (node.getResource().isVirtual()) { return true; - if (node.isErrorInFileSystem()) + } + if (node.isErrorInFileSystem()) { return true; // Assume synchronized unless proven otherwise + } /* does the resource exist in workspace and file system? */ - if (!node.existsInWorkspace() || !node.existsInFileSystem()) + if (!node.existsInWorkspace() || !node.existsInFileSystem()) { return false; + } /* we don't care about folder last modified */ - if (node.isFolder() && node.getResource().getType() == IResource.FOLDER) + if (node.isFolder() && node.getResource().getType() == IResource.FOLDER) { return true; + } /* is lastModified different? */ Resource target = (Resource) node.getResource(); long lastModifed = target.getResourceInfo(false, false).getLocalSyncInfo(); - if (lastModifed != node.getLastModified()) + if (lastModifed != node.getLastModified()) { return false; + } return true; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/DeleteVisitor.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/DeleteVisitor.java index 3ed0de10148..b19cc9768d0 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/DeleteVisitor.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/DeleteVisitor.java @@ -56,19 +56,22 @@ protected void delete(UnifiedTreeNode node, boolean shouldKeepHistory) { try { final boolean deleteLocalFile = !target.isLinked() && node.existsInFileSystem(); IFileStore localFile = deleteLocalFile ? node.getStore() : null; - if (deleteLocalFile && shouldKeepHistory) + if (deleteLocalFile && shouldKeepHistory) { recursiveKeepHistory(target.getLocalManager().getHistoryStore(), node); + } node.removeChildrenFromTree(); //delete from disk int work = ticks < 0 ? 0 : ticks; ticks -= work; - if (deleteLocalFile) + if (deleteLocalFile) { localFile.delete(EFS.NONE, monitor.split(work)); - else + } else { monitor.worked(work); + } //delete from tree - if (node.existsInWorkspace()) + if (node.existsInWorkspace()) { target.deleteResource(true, status); + } } catch (CoreException e) { status.add(e.getStatus()); // delete might have been partly successful, so refresh to ensure in sync @@ -96,11 +99,13 @@ protected boolean isAncestor(IResource one, IResource another) { } protected boolean isAncestorOfResourceToSkip(IResource resource) { - if (skipList == null) + if (skipList == null) { return false; + } for (IResource target : skipList) { - if (isAncestor(resource, target)) + if (isAncestor(resource, target)) { return true; + } } return false; } @@ -108,16 +113,19 @@ protected boolean isAncestorOfResourceToSkip(IResource resource) { private void recursiveKeepHistory(IHistoryStore store, UnifiedTreeNode node) { final IResource target = node.getResource(); //we don't delete linked content, so no need to keep history - if (target.isLinked() || target.isVirtual() || node.isSymbolicLink()) + if (target.isLinked() || target.isVirtual() || node.isSymbolicLink()) { return; + } if (node.isFolder()) { monitor.subTask(NLS.bind(Messages.localstore_deleting, target.getFullPath())); - for (Iterator children = node.getChildren(); children.hasNext();) + for (Iterator children = node.getChildren(); children.hasNext();) { recursiveKeepHistory(store, children.next()); + } } else { IFileInfo info = node.fileInfo; - if (info == null) + if (info == null) { info = new FileInfo(node.getLocalName()); + } if (FileSystemResourceManager.storeHistory(node.getResource())) { store.addState(target.getFullPath(), node.getStore(), info, true); } @@ -127,16 +135,20 @@ private void recursiveKeepHistory(IHistoryStore store, UnifiedTreeNode node) { } protected void removeFromSkipList(IResource resource) { - if (skipList != null) + if (skipList != null) { skipList.remove(resource); + } } protected boolean shouldSkip(IResource resource) { - if (skipList == null) + if (skipList == null) { return false; - for (Resource element : skipList) - if (equals(resource, element)) + } + for (Resource element : skipList) { + if (equals(resource, element)) { return true; + } + } return false; } @@ -151,8 +163,9 @@ public boolean visit(UnifiedTreeNode node) { ticks -= skipTicks; return false; } - if (isAncestorOfResourceToSkip(target)) + if (isAncestorOfResourceToSkip(target)) { return true; + } delete(node, keepHistory); return false; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileStoreRoot.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileStoreRoot.java index 4fbcb69c5a3..321f530e415 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileStoreRoot.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileStoreRoot.java @@ -77,8 +77,9 @@ public class FileStoreRoot { private IPathVariableManager getManager(IPath workspacePath) { IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = workspaceRoot.findMember(workspacePath); - if (resource != null) + if (resource != null) { return resource.getPathVariableManager(); + } // Bug 547691 - deal with requests for the path of a deleted project if (workspacePath.segmentCount() == 0) { return workspaceRoot.getPathVariableManager(); @@ -111,8 +112,9 @@ public URI computeURI(IPath workspacePath, boolean canonical) { IPath childPath = workspacePath.removeFirstSegments(chop); URI rootURI = canonical ? getCanonicalRoot() : root; rootURI = getManager(workspacePath).resolveURI(rootURI); - if (childPath.segmentCount() == 0) + if (childPath.segmentCount() == 0) { return rootURI; + } try { return EFS.getStore(rootURI).getFileStore(childPath).toURI(); } catch (CoreException e) { @@ -137,8 +139,9 @@ IFileStore createStore(IPath workspacePath, IResource resource) throws CoreExcep return EFS.getNullFileSystem().getStore(workspacePath); } IFileStore rootStore = EFS.getStore(uri); - if (childPath.segmentCount() == 0) + if (childPath.segmentCount() == 0) { return rootStore; + } return rootStore.getFileStore(childPath); } @@ -168,20 +171,23 @@ IPath localLocation(IPath workspacePath, IResource resource) { * to this root will be canonicalized */ IPath localLocation(IPath workspacePath, IResource resource, boolean canonical) { - if (localRoot == null) + if (localRoot == null) { return null; + } IPath rootPath = canonical ? getCanonicalLocalRoot() : localRoot; IPath location; - if (workspacePath.segmentCount() <= chop) + if (workspacePath.segmentCount() <= chop) { location = rootPath; - else + } else { location = rootPath.append(workspacePath.removeFirstSegments(chop)); + } location = resource.getPathVariableManager().resolvePath(location); // if path is still relative then path variable could not be resolved // if path is null, it means path variable refers to a non-local filesystem - if (location == null || !location.isAbsolute()) + if (location == null || !location.isAbsolute()) { return null; + } return location; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileSystemResourceManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileSystemResourceManager.java index 2b200644e34..f1b404cf443 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileSystemResourceManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/FileSystemResourceManager.java @@ -135,18 +135,22 @@ private ArrayList allPathsForLocationNonCanonical(URI inputLocation) { return results; } for (IProject project : root.getProjects(IContainer.INCLUDE_HIDDEN)) { - if (!project.exists()) + if (!project.exists()) { continue; + } //check the project location URI testLocation = locationURIFor(project, true); - if (testLocation == null) + if (testLocation == null) { continue; + } boolean usingAnotherScheme = !inputLocation.getScheme().equals(testLocation.getScheme()); // if we are looking for file: locations try to get a file: location for this project - if (isFileLocation && !EFS.SCHEME_FILE.equals(testLocation.getScheme())) + if (isFileLocation && !EFS.SCHEME_FILE.equals(testLocation.getScheme())) { testLocation = getFileURI(testLocation); - if (testLocation == null) + } + if (testLocation == null) { continue; + } URI relative = testLocation.relativize(location); if (!relative.isAbsolute() && !relative.equals(testLocation)) { IPath suffix = IPath.fromOSString(relative.getPath()); @@ -156,20 +160,24 @@ private ArrayList allPathsForLocationNonCanonical(URI inputLocation) { // if a different scheme is used, we can't use the AliasManager, since the manager // map is stored using the EFS scheme, and not necessarily the SCHEME_FILE ProjectDescription description = ((Project) project).internalGetDescription(); - if (description == null) + if (description == null) { continue; + } HashMap links = description.getLinks(); - if (links == null) + if (links == null) { continue; + } for (LinkDescription link : links.values()) { IResource resource = project.findMember(link.getProjectRelativePath()); IPathVariableManager pathMan = resource == null ? project.getPathVariableManager() : resource.getPathVariableManager(); testLocation = pathMan.resolveURI(link.getLocationURI()); // if we are looking for file: locations try to get a file: location for this link - if (isFileLocation && !EFS.SCHEME_FILE.equals(testLocation.getScheme())) + if (isFileLocation && !EFS.SCHEME_FILE.equals(testLocation.getScheme())) { testLocation = getFileURI(testLocation); - if (testLocation == null) + } + if (testLocation == null) { continue; + } relative = testLocation.relativize(location); if (!relative.isAbsolute() && !relative.equals(testLocation)) { IPath suffix = IPath.fromOSString(relative.getPath()); @@ -207,16 +215,19 @@ private void findLinkedResourcesPaths(URI inputLocation, final ArrayList for (IResource resource : resources) { if (resource.isLinked()) { IPath path = resource.getFullPath(); - if (suffix != null) + if (suffix != null) { path = path.append(suffix); - if (!results.contains(path)) + } + if (!results.contains(path)) { results.add(path); + } } } - if (suffix == null) + if (suffix == null) { suffix = IPath.fromPortableString(fileStore.getName()); - else + } else { suffix = IPath.fromPortableString(fileStore.getName()).append(suffix); + } fileStore = fileStore.getParent(); } } @@ -231,8 +242,9 @@ private URI getFileURI(URI locationURI) { try { IFileStore testLocationStore = EFS.getStore(locationURI); java.io.File storeAsFile = testLocationStore.toLocalFile(EFS.NONE, null); - if (storeAsFile != null) + if (storeAsFile != null) { return URIUtil.toURI(storeAsFile.getAbsolutePath()); + } } catch (CoreException e) { // we don't know such file system or some other failure, just return null } @@ -281,21 +293,24 @@ public IResource[] allResourcesFor(URI location, boolean files, int memberFlags) //replace the path in the list with the appropriate resource type IResource resource = resourceFor((IPath) result.get(i), files); - if (resource == null || ((Resource) resource).isFiltered() || (((memberFlags & IContainer.INCLUDE_HIDDEN) == 0) && resource.isHidden(IResource.CHECK_ANCESTORS)) || (((memberFlags & IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS) == 0) && resource.isTeamPrivateMember(IResource.CHECK_ANCESTORS))) + if (resource == null || ((Resource) resource).isFiltered() || (((memberFlags & IContainer.INCLUDE_HIDDEN) == 0) && resource.isHidden(IResource.CHECK_ANCESTORS)) || (((memberFlags & IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS) == 0) && resource.isTeamPrivateMember(IResource.CHECK_ANCESTORS))) { resource = null; + } result.set(i, resource); //count actual resources - some paths won't have a corresponding resource - if (resource != null) + if (resource != null) { count++; + } } //convert to array and remove null elements IResource[] toReturn = files ? (IResource[]) new IFile[count] : (IResource[]) new IContainer[count]; count = 0; for (Object element : result) { IResource resource = (IResource) element; - if (resource != null) + if (resource != null) { toReturn[count++] = resource; + } } return toReturn; } @@ -306,8 +321,9 @@ public IResource[] allResourcesFor(URI location, boolean files, int memberFlags) public ResourceAttributes attributes(IResource resource) { IFileStore store = getStore(resource); IFileInfo fileInfo = store.fetchInfo(); - if (!fileInfo.exists()) + if (!fileInfo.exists()) { return null; + } return FileUtil.fileInfoToAttributes(fileInfo); } @@ -344,8 +360,9 @@ public IContainer containerForLocation(IPath location) { */ private IResource resourceForLocation(IPath location, boolean files) { if (workspace.getRoot().getLocation().equals(location)) { - if (!files) + if (!files) { return resourceFor(IPath.ROOT, false); + } return null; } int resultProjectPathSegments = 0; @@ -439,18 +456,21 @@ private boolean descriptionChanged(IFile descriptionFile, byte[] newContents) { oldChar = oldStream.read(); } else if ((newChar == '\r' || newChar == '\n') && (oldChar == '\r' || oldChar == '\n')) { //got a difference, but both sides are newlines: read over newlines - while (newChar == '\r' || newChar == '\n') + while (newChar == '\r' || newChar == '\n') { newChar = newStream.read(); - while (oldChar == '\r' || oldChar == '\n') + } + while (oldChar == '\r' || oldChar == '\n') { oldChar = oldStream.read(); + } } else { //streams are different return true; } } //test for excess data in one stream - if (newChar >= 0 || oldChar >= 0) + if (newChar >= 0 || oldChar >= 0) { return true; + } return false; } catch (Exception e) { Policy.log(e); @@ -469,21 +489,26 @@ public int doGetEncoding(IFileStore store) throws CoreException { ) { int first = input.read(); int second = input.read(); - if (first == -1 || second == -1) + if (first == -1 || second == -1) { return IFile.ENCODING_UNKNOWN; + } first &= 0xFF;//converts unsigned byte to int second &= 0xFF; //look for the UTF-16 Byte Order Mark (BOM) - if (first == 0xFE && second == 0xFF) + if (first == 0xFE && second == 0xFF) { return IFile.ENCODING_UTF_16BE; - if (first == 0xFF && second == 0xFE) + } + if (first == 0xFF && second == 0xFE) { return IFile.ENCODING_UTF_16LE; + } int third = (input.read() & 0xFF); - if (third == -1) + if (third == -1) { return IFile.ENCODING_UNKNOWN; + } //look for the UTF-8 BOM - if (first == 0xEF && second == 0xBB && third == 0xBF) + if (first == 0xEF && second == 0xBB && third == 0xBF) { return IFile.ENCODING_UTF_8; + } return IFile.ENCODING_UNKNOWN; } catch (IOException e) { String message = NLS.bind(Messages.localstore_couldNotRead, store.toString()); @@ -500,8 +525,9 @@ public boolean fastIsSynchronized(File target) { ResourceInfo info = target.getResourceInfo(false, false); if (target.exists(target.getFlags(info), true)) { IFileInfo fileInfo = getStore(target).fetchInfo(); - if (!fileInfo.isDirectory() && info.getLocalSyncInfo() == fileInfo.getLastModified()) + if (!fileInfo.isDirectory() && info.getLocalSyncInfo() == fileInfo.getLastModified()) { return true; + } } return false; } @@ -510,8 +536,9 @@ public boolean fastIsSynchronized(Folder target) { ResourceInfo info = target.getResourceInfo(false, false); if (target.exists(target.getFlags(info), true)) { IFileInfo fileInfo = getStore(target).fetchInfo(); - if (!fileInfo.exists() && info.getLocalSyncInfo() == fileInfo.getLastModified()) + if (!fileInfo.exists() && info.getLocalSyncInfo() == fileInfo.getLastModified()) { return true; + } } return false; } @@ -594,8 +621,9 @@ private FileStoreRoot getStoreRoot(IResource target) { FileStoreRoot root; if (info != null) { root = info.getFileStoreRoot(); - if (root != null && root.isValid()) + if (root != null && root.isValid()) { return root; + } if (info.isSet(ICoreConstants.M_VIRTUAL)) { ProjectDescription description = ((Project) target.getProject()).internalGetDescription(); if (description != null) { @@ -626,8 +654,9 @@ private FileStoreRoot getStoreRoot(IResource target) { return info.getFileStoreRoot(); } root = getStoreRoot(parent); - if (info != null) + if (info != null) { info.setFileStoreRoot(root); + } return root; } @@ -680,11 +709,13 @@ private IFileStore initializeStore(IResource target, URI location, boolean locat */ public boolean internalWrite(IProject target, IProjectDescription description, int updateFlags, boolean hasPublicChanges, boolean hasPrivateChanges) throws CoreException { //write the project's private description to the metadata area - if (hasPrivateChanges) + if (hasPrivateChanges) { getWorkspace().getMetaArea().writePrivateDescription(target); + } //can't do anything if there's no description - if (!hasPublicChanges || (description == null)) + if (!hasPublicChanges || (description == null)) { return false; + } //write the model to a byte array ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -708,16 +739,18 @@ public boolean internalWrite(IProject target, IProjectDescription description, i workspace.createResource(descriptionFile, false); } else { //if the description has not changed, don't write anything - if (!descriptionChanged(descriptionFile, newContents)) + if (!descriptionChanged(descriptionFile, newContents)) { return false; + } } IFileStore descriptionFileStore = ((Resource) descriptionFile).getStore(); IFileInfo fileInfo = descriptionFileStore.fetchInfo(); if (fileInfo.getAttribute(EFS.ATTRIBUTE_READ_ONLY)) { IStatus result = getWorkspace().validateEdit(new IFile[] {descriptionFile}, null); - if (!result.isOK()) + if (!result.isOK()) { throw new ResourceException(result); + } // re-read the file info in case the file attributes were modified fileInfo = descriptionFileStore.fetchInfo(); } @@ -747,8 +780,9 @@ public boolean isDescriptionSynchronized(IProject target) { //stamp will be out of date IFile descriptionFile = target.getFile(IProjectDescription.DESCRIPTION_FILE_NAME); ResourceInfo projectInfo = ((Resource) target).getResourceInfo(false, false); - if (projectInfo == null) + if (projectInfo == null) { return false; + } return projectInfo.getLocalSyncInfo() == getStore(descriptionFile).fetchInfo().getLastModified(); } @@ -765,8 +799,9 @@ public boolean isDescriptionSynchronized(IProject target) { public boolean isSynchronized(IResource target, int depth) { switch (target.getType()) { case IResource.ROOT : - if (depth == IResource.DEPTH_ZERO) + if (depth == IResource.DEPTH_ZERO) { return true; + } //check sync on child projects. depth = depth == IResource.DEPTH_ONE ? IResource.DEPTH_ZERO : depth; IProject[] projects = ((IWorkspaceRoot) target).getProjects(IContainer.INCLUDE_HIDDEN); @@ -777,16 +812,19 @@ public boolean isSynchronized(IResource target, int depth) { } return true; case IResource.PROJECT : - if (!target.isAccessible()) + if (!target.isAccessible()) { return true; + } break; case IResource.FOLDER : - if (fastIsSynchronized((Folder) target)) + if (fastIsSynchronized((Folder) target)) { return true; + } break; case IResource.FILE : - if (fastIsSynchronized((File) target)) + if (fastIsSynchronized((File) target)) { return true; + } break; } IsSynchronizedVisitor visitor = new IsSynchronizedVisitor(null); @@ -820,8 +858,9 @@ public void link(Resource target, URI location, IFileInfo fileInfo) throws CoreE initializeStore(target, location, false); ResourceInfo info = target.getResourceInfo(false, true); long lastModified = fileInfo == null ? 0 : fileInfo.getLastModified(); - if (lastModified == 0) + if (lastModified == 0) { info.clearModificationStamp(); + } updateLocalSync(info, lastModified); } @@ -964,8 +1003,9 @@ public ProjectDescription read(IProject target, boolean creation) throws CoreExc } catch (CoreException e) { //try the legacy location in the meta area description = getWorkspace().getMetaArea().readOldDescription(target); - if (description != null) + if (description != null) { return description; + } if (!descriptionStore.fetchInfo().exists()) { String msg = NLS.bind(Messages.resources_missingProjectMeta, target.getName()); throw new ResourceException(IResourceStatus.FAILED_READ_METADATA, target.getFullPath(), msg, null); @@ -980,11 +1020,13 @@ public ProjectDescription read(IProject target, boolean creation) throws CoreExc error = new ResourceException(IResourceStatus.FAILED_READ_METADATA, target.getFullPath(), msg, null); } if (description != null) { - if (!isDefaultLocation) + if (!isDefaultLocation) { description.setLocationURI(projectLocation); - if (creation && privateDescription != null) + } + if (creation && privateDescription != null) { // Bring dynamic state back to life description.updateDynamicState(privateDescription); + } } long lastModified = descriptionStore.fetchInfo().getLastModified(); IFile descriptionFile = target.getFile(IProjectDescription.DESCRIPTION_FILE_NAME); @@ -998,16 +1040,18 @@ public ProjectDescription read(IProject target, boolean creation) throws CoreExc } //if the project description has changed between sessions, let it remain //out of sync -- that way link changes will be reconciled on next refresh - if (!creation) + if (!creation) { updateLocalSync(info, lastModified); + } //update the timestamp on the project as well so we know when it has //been changed from the outside info = ((Resource) target).getResourceInfo(false, true); updateLocalSync(info, lastModified); - if (error != null) + if (error != null) { throw error; + } return description; } @@ -1016,8 +1060,9 @@ public boolean refresh(IResource target, int depth, boolean updateAliases, IProg case IResource.ROOT : return refreshRoot((IWorkspaceRoot) target, depth, updateAliases, monitor); case IResource.PROJECT : - if (!target.isAccessible()) + if (!target.isAccessible()) { return false; + } //fall through case IResource.FOLDER : case IResource.FILE : @@ -1040,8 +1085,9 @@ protected boolean refreshResource(IResource target, int depth, boolean updateAli RefreshLocalVisitor visitor = updateAliases ? new RefreshLocalAliasVisitor(refreshMonitor) : new RefreshLocalVisitor(refreshMonitor); tree.accept(visitor, depth); IStatus result = visitor.getErrorStatus(); - if (!result.isOK()) + if (!result.isOK()) { throw new ResourceException(result); + } return visitor.resourcesChanged(); } @@ -1057,8 +1103,9 @@ protected boolean refreshRoot(IWorkspaceRoot target, int depth, boolean updateAl SubMonitor subMonitor = SubMonitor.convert(monitor, title, projects.length); // if doing depth zero, there is nothing to do (can't refresh the root). // Note that we still need to do the beginTask, done pair. - if (depth == IResource.DEPTH_ZERO) + if (depth == IResource.DEPTH_ZERO) { return false; + } boolean changed = false; // drop the depth by one level since processing the root counts as one level. depth = depth == IResource.DEPTH_ONE ? IResource.DEPTH_ZERO : depth; @@ -1076,13 +1123,16 @@ protected boolean refreshRoot(IWorkspaceRoot target, int depth, boolean updateAl */ protected IResource resourceFor(IPath path, boolean files) { int numSegments = path.segmentCount(); - if (files && numSegments < ICoreConstants.MINIMUM_FILE_SEGMENT_LENGTH) + if (files && numSegments < ICoreConstants.MINIMUM_FILE_SEGMENT_LENGTH) { return null; + } IWorkspaceRoot root = getWorkspace().getRoot(); - if (path.isRoot()) + if (path.isRoot()) { return root; - if (numSegments == 1) + } + if (numSegments == 1) { return root.getProject(path.segment(0)); + } return files ? (IResource) root.getFile(path) : (IResource) root.getFolder(path); } @@ -1121,8 +1171,9 @@ public void setNormalizedLocation(IResource target, ResourceInfo info, URI locat //project is in default location so clear the store root info.setFileStoreRoot(null); } - if (oldRoot != null) + if (oldRoot != null) { oldRoot.setValid(false); + } } /* (non-javadoc) @@ -1132,18 +1183,21 @@ public void setResourceAttributes(IResource resource, ResourceAttributes attribu IFileStore store = getStore(resource); //when the executable bit is changed on a folder a refresh is required boolean refresh = false; - if (resource instanceof IContainer && ((store.getFileSystem().attributes() & EFS.ATTRIBUTE_EXECUTABLE) != 0)) + if (resource instanceof IContainer && ((store.getFileSystem().attributes() & EFS.ATTRIBUTE_EXECUTABLE) != 0)) { refresh = store.fetchInfo().getAttribute(EFS.ATTRIBUTE_EXECUTABLE) != attributes.isExecutable(); + } store.putInfo(FileUtil.attributesToFileInfo(attributes), EFS.SET_ATTRIBUTES, null); //must refresh in the background because we are not inside an operation - if (refresh) + if (refresh) { workspace.getRefreshManager().refresh(resource); + } } @Override public void shutdown(IProgressMonitor monitor) throws CoreException { - if (_historyStore != null) + if (_historyStore != null) { _historyStore.shutdown(monitor); + } InstanceScope.INSTANCE.getNode(ResourcesPlugin.PI_RESOURCES) .removePreferenceChangeListener(lightweightAutoRefreshPrefListener); } @@ -1161,10 +1215,11 @@ public void startup(IProgressMonitor monitor) { */ public void updateLocalSync(ResourceInfo info, long localSyncInfo) { info.setLocalSyncInfo(localSyncInfo); - if (localSyncInfo == I_NULL_SYNC_INFO) + if (localSyncInfo == I_NULL_SYNC_INFO) { info.clear(M_LOCAL_EXISTS); - else + } else { info.set(M_LOCAL_EXISTS); + } } /** @@ -1298,10 +1353,11 @@ private void prepareWrite(IFile target, IFileInfo fileInfo, int updateFlags, boo } // add entry to History Store. if (BitMask.isSet(updateFlags, IResource.KEEP_HISTORY) && fileInfo.exists() - && FileSystemResourceManager.storeHistory(target)) + && FileSystemResourceManager.storeHistory(target)) { // never move to the history store, because then the file is missing if write // fails getHistoryStore().addState(target.getFullPath(), store, fileInfo, false); + } if (!assumeParentDirectoryExists && !fileInfo.exists()) { IFileStore parent = store.getParent(); IFileInfo parentInfo = parent.fetchInfo(); @@ -1407,14 +1463,16 @@ public void write(IFolder target, boolean force, IProgressMonitor monitor) throw public void writeSilently(IProject target) throws CoreException { IPath location = locationFor(target, false); //if the project location cannot be resolved, we don't know if a description file exists or not - if (location == null) + if (location == null) { return; + } IFileStore projectStore = getStore(target); projectStore.mkdir(EFS.NONE, null); //can't do anything if there's no description IProjectDescription desc = ((Project) target).internalGetDescription(); - if (desc == null) + if (desc == null) { return; + } //write the project's private description to the meta-data area getWorkspace().getMetaArea().writePrivateDescription(target); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/HistoryBucket.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/HistoryBucket.java index 25b2a9d140c..2ac10f55c6d 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/HistoryBucket.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/HistoryBucket.java @@ -58,8 +58,9 @@ public static final class HistoryEntry extends Bucket.Entry { static int compareStates(byte[] state1, byte[] state2) { long timestamp1 = getTimestamp(state1); long timestamp2 = getTimestamp(state2); - if (timestamp1 == timestamp2) + if (timestamp1 == timestamp2) { return -UniversalUniqueIdentifier.compareTime(state1, state2); + } return timestamp1 < timestamp2 ? +1 : -1; } @@ -79,8 +80,9 @@ static byte[] getState(UniversalUniqueIdentifier uuid, long timestamp) { private static long getTimestamp(byte[] state) { long timestamp = 0; - for (int j = 0; j < LONG_LENGTH; j++) + for (int j = 0; j < LONG_LENGTH; j++) { timestamp += (state[UUID_LENGTH + j] & 0xFFL) << j * 8; + } return timestamp; } @@ -91,17 +93,20 @@ private static long getTimestamp(byte[] state) { static byte[][] insert(byte[][] existing, byte[] toAdd) { // look for the right spot where to insert the new guy int index = search(existing, toAdd); - if (index >= 0) + if (index >= 0) { // already there - nothing else to be done return null; + } // not found - insert int insertPosition = -index - 1; byte[][] newValue = new byte[existing.length + 1][]; - if (insertPosition > 0) + if (insertPosition > 0) { System.arraycopy(existing, 0, newValue, 0, insertPosition); + } newValue[insertPosition] = toAdd; - if (insertPosition < existing.length) + if (insertPosition < existing.length) { System.arraycopy(existing, insertPosition, newValue, insertPosition + 1, existing.length - insertPosition); + } return newValue; } @@ -119,10 +124,11 @@ static byte[][] merge(byte[][] base, byte[][] additions) { result[added++] = base[basePointer++]; // duplicate, ignore additionPointer++; - } else if (comparison < 0) + } else if (comparison < 0) { result[added++] = base[basePointer++]; - else + } else { result[added++] = additions[additionPointer++]; + } } // copy the remaining states from either additions or base arrays byte[][] remaining = basePointer == base.length ? additions : base; @@ -130,9 +136,10 @@ static byte[][] merge(byte[][] base, byte[][] additions) { int remainingCount = remaining.length - remainingPointer; System.arraycopy(remaining, remainingPointer, result, added, remainingCount); added += remainingCount; - if (added == base.length + additions.length) + if (added == base.length + additions.length) { // no collisions return result; + } // there were collisions, need to compact byte[][] finalResult = new byte[added][]; System.arraycopy(result, 0, finalResult, 0, finalResult.length); @@ -159,17 +166,19 @@ public HistoryEntry(IPath path, HistoryEntry base) { * are found, the entry is marked for removal. */ private void compact() { - if (!isDirty()) + if (!isDirty()) { return; + } int occurrences = 0; for (byte[] d : data) { if (d != null) { data[occurrences++] = d; } } - if (occurrences == data.length) + if (occurrences == data.length) { // no states deleted return; + } if (occurrences == 0) { // no states remaining data = EMPTY_DATA; @@ -262,8 +271,9 @@ public void addBlob(IPath path, UniversalUniqueIdentifier uuid, long lastModifie return; } byte[][] newValue = HistoryEntry.insert(existing, state); - if (newValue == null) + if (newValue == null) { return; + } setEntryValue(pathAsString, newValue); } @@ -287,8 +297,9 @@ protected Bucket.Entry createEntry(IPath path, Object value) { public HistoryEntry getEntry(IPath path) { String pathAsString = path.toString(); byte[][] existing = (byte[][]) getEntryValue(pathAsString); - if (existing == null) + if (existing == null) { return null; + } return new HistoryEntry(path, existing); } @@ -311,8 +322,9 @@ protected String getVersionFileName() { protected Object readEntryValue(DataInputStream source) throws IOException { int length = source.readUnsignedShort(); byte[][] uuids = new byte[length][HistoryEntry.DATA_LENGTH]; - for (byte[] uuid : uuids) + for (byte[] uuid : uuids) { source.read(uuid); + } return uuids; } @@ -320,7 +332,8 @@ protected Object readEntryValue(DataInputStream source) throws IOException { protected void writeEntryValue(DataOutputStream destination, Object entryValue) throws IOException { byte[][] uuids = (byte[][]) entryValue; destination.writeShort(uuids.length); - for (byte[] uuid : uuids) + for (byte[] uuid : uuids) { destination.write(uuid); + } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/HistoryStore2.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/HistoryStore2.java index d1d51a04da5..b1858e8edde 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/HistoryStore2.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/HistoryStore2.java @@ -64,16 +64,18 @@ public void afterSaving(Bucket bucket) throws CoreException { } private void saveChanges() throws CoreException { - if (changes.isEmpty()) + if (changes.isEmpty()) { return; + } // make effective all changes collected Iterator i = changes.iterator(); HistoryEntry entry = i.next(); tree.loadBucketFor(entry.getPath()); HistoryBucket bucket = (HistoryBucket) tree.getCurrent(); bucket.addBlobs(entry); - while (i.hasNext()) + while (i.hasNext()) { bucket.addBlobs(i.next()); + } bucket.save(); } @@ -111,10 +113,12 @@ public HistoryStore2(Workspace workspace, IFileStore store, int limit) { @Override public synchronized IFileState addState(IPath key, IFileStore localFile, IFileInfo info, boolean moveContents) { long lastModified = info.getLastModified(); - if (Policy.DEBUG_HISTORY) + if (Policy.DEBUG_HISTORY) { Policy.debug("History: Adding state for key: " + key + ", file: " + localFile + ", timestamp: " + lastModified + ", size: " + localFile.fetchInfo().getLength()); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - if (!isValid(localFile, info)) + } + if (!isValid(localFile, info)) { return null; + } UniversalUniqueIdentifier uuid = null; try { uuid = blobStore.addBlob(localFile, moveContents); @@ -150,8 +154,9 @@ public int visit(Entry fileEntry) { */ protected void applyPolicy(HistoryEntry fileEntry, int maxStates, long minTimeStamp) { for (int i = 0; i < fileEntry.getOccurrences(); i++) { - if (i < maxStates && fileEntry.getTimestamp(i) >= minTimeStamp) + if (i < maxStates && fileEntry.getTimestamp(i) >= minTimeStamp) { continue; + } // "delete" the current uuid blobsToRemove.add(fileEntry.getUUID(i)); fileEntry.deleteOccurrence(i); @@ -189,8 +194,9 @@ public synchronized void clean(final IProgressMonitor monitor) { tree.accept(new Bucket.Visitor() { @Override public int visit(Entry fileEntry) { - if (monitor.isCanceled()) + if (monitor.isCanceled()) { return STOP; + } entryCount[0] += fileEntry.getOccurrences(); applyPolicy((HistoryEntry) fileEntry, maxStates, minimumTimestamp); // remove unreferenced blobs, when blobsToRemove size is greater than 100 @@ -224,8 +230,9 @@ void removeUnreferencedBlobs(int limit) { long start = System.currentTimeMillis(); // remove unreferenced blobs blobStore.deleteBlobs(blobsToRemove); - if (Policy.DEBUG_HISTORY) + if (Policy.DEBUG_HISTORY) { Policy.debug("Time to remove " + blobsToRemove.size() + " unreferenced blobs: " + (System.currentTimeMillis() - start) + "ms."); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ + } blobsToRemove = new HashSet<>(); } } @@ -302,11 +309,13 @@ public synchronized IFileState[] getStates(IPath filePath, IProgressMonitor moni tree.loadBucketFor(filePath); HistoryBucket currentBucket = (HistoryBucket) tree.getCurrent(); HistoryEntry fileEntry = currentBucket.getEntry(filePath); - if (fileEntry == null || fileEntry.isEmpty()) + if (fileEntry == null || fileEntry.isEmpty()) { return new IFileState[0]; + } IFileState[] states = new IFileState[fileEntry.getOccurrences()]; - for (int i = 0; i < states.length; i++) + for (int i = 0; i < states.length; i++) { states[i] = new FileState(this, fileEntry.getPath(), fileEntry.getTimestamp(i), fileEntry.getUUID(i)); + } return states; } catch (CoreException ce) { log(ce); @@ -329,14 +338,16 @@ public BucketTree getTree() { */ private boolean isValid(IFileStore localFile, IFileInfo info) { WorkspaceDescription description = workspace.internalGetDescription(); - if (!description.isApplyFileStatePolicy()) + if (!description.isApplyFileStatePolicy()) { return true; + } long length = info.getLength(); boolean result = length <= description.getMaxFileStateSize(); - if (Policy.DEBUG_HISTORY && !result) + if (Policy.DEBUG_HISTORY && !result) { Policy.debug("History: Ignoring file (too large). File: " + localFile.toString() + //$NON-NLS-1$ ", size: " + length + //$NON-NLS-1$ ", max: " + description.getMaxFileStateSize()); //$NON-NLS-1$ + } return result; } @@ -346,8 +357,9 @@ private boolean isValid(IFileStore localFile, IFileInfo info) { private void log(CoreException e) { //create a new status to wrap the exception if there is no exception in the status IStatus status = e.getStatus(); - if (status.getException() == null) + if (status.getException() == null) { status = new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_WRITE_METADATA, "Internal error in history store", e); //$NON-NLS-1$ + } Policy.log(status); } @@ -358,9 +370,10 @@ public synchronized void remove(IPath root, IProgressMonitor monitor) { tree.accept(new Bucket.Visitor() { @Override public int visit(Entry fileEntry) { - for (int i = 0; i < fileEntry.getOccurrences(); i++) + for (int i = 0; i < fileEntry.getOccurrences(); i++) { // remember we need to delete the files later tmpBlobsToRemove.add(((HistoryEntry) fileEntry).getUUID(i)); + } fileEntry.delete(); return CONTINUE; } @@ -380,9 +393,10 @@ public synchronized void removeGarbage() { tree.accept(new Bucket.Visitor() { @Override public int visit(Entry fileEntry) { - for (int i = 0; i < fileEntry.getOccurrences(); i++) + for (int i = 0; i < fileEntry.getOccurrences(); i++) { // remember we need to delete the files later tmpBlobsToRemove.remove(((HistoryEntry) fileEntry).getUUID(i)); + } return CONTINUE; } }, IPath.ROOT, BucketTree.DEPTH_INFINITE); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/PrefixPool.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/PrefixPool.java index 11cb5f1c0b3..1a8b88147c2 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/PrefixPool.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/PrefixPool.java @@ -59,8 +59,9 @@ public class PrefixPool { * be greater than 0. */ public PrefixPool(int initialCapacity) { - if (initialCapacity <= 0) + if (initialCapacity <= 0) { throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity); //$NON-NLS-1$ + } pool = new String[initialCapacity]; size = 0; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalAliasVisitor.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalAliasVisitor.java index 2797c617437..39088f39799 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalAliasVisitor.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalAliasVisitor.java @@ -33,35 +33,41 @@ public RefreshLocalAliasVisitor(IProgressMonitor monitor) { protected void createResource(UnifiedTreeNode node, Resource target) throws CoreException { super.createResource(node, target); IFileStore store = node.getStore(); - if (store == null) + if (store == null) { return; + } IResource[] aliases = workspace.getAliasManager().computeAliases(target, store); - if (aliases != null) + if (aliases != null) { for (IResource alias : aliases) { if (alias.getProject().isOpen() && !((Resource) alias).isFiltered()) { super.createResource(node, (Resource) alias); } } + } } @Override protected void deleteResource(UnifiedTreeNode node, Resource target) throws CoreException { super.deleteResource(node, target); IFileStore store = node.getStore(); - if (store == null) + if (store == null) { return; + } IResource[] aliases = workspace.getAliasManager().computeAliases(target, store); if (aliases != null) { boolean wasFilteredOut = false; - if (store.fetchInfo() != null && store.fetchInfo().exists()) + if (store.fetchInfo() != null && store.fetchInfo().exists()) { wasFilteredOut = target.isFiltered(); + } for (IResource aliase : aliases) { if (aliase.getProject().isOpen()) { if (wasFilteredOut) { - if (((Resource) aliase).isFiltered()) + if (((Resource) aliase).isFiltered()) { super.deleteResource(node, (Resource) aliase); - } else + } + } else { super.deleteResource(node, (Resource) aliase); + } } } } @@ -71,38 +77,47 @@ protected void deleteResource(UnifiedTreeNode node, Resource target) throws Core protected void resourceChanged(UnifiedTreeNode node, Resource target) { super.resourceChanged(node, target); IFileStore store = node.getStore(); - if (store == null) + if (store == null) { return; + } IResource[] aliases = workspace.getAliasManager().computeAliases(target, store); - if (aliases != null) + if (aliases != null) { for (IResource aliase : aliases) { - if (aliase.getProject().isOpen()) + if (aliase.getProject().isOpen()) { super.resourceChanged(node, (Resource) aliase); + } } + } } @Override protected void fileToFolder(UnifiedTreeNode node, Resource target) throws CoreException { super.fileToFolder(node, target); IFileStore store = node.getStore(); - if (store == null) + if (store == null) { return; + } IResource[] aliases = workspace.getAliasManager().computeAliases(target, store); - if (aliases != null) - for (IResource aliase : aliases) + if (aliases != null) { + for (IResource aliase : aliases) { super.fileToFolder(node, (Resource) aliase); + } + } } @Override protected void folderToFile(UnifiedTreeNode node, Resource target) throws CoreException { super.folderToFile(node, target); IFileStore store = node.getStore(); - if (store == null) + if (store == null) { return; + } IResource[] aliases = workspace.getAliasManager().computeAliases(target, store); - if (aliases != null) - for (IResource aliase : aliases) + if (aliases != null) { + for (IResource aliase : aliases) { super.folderToFile(node, (Resource) aliase); + } + } } @Override diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java index 0fb70969856..ee136683f1c 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/RefreshLocalVisitor.java @@ -76,12 +76,14 @@ protected void contentAdded(UnifiedTreeNode node, Resource target) { protected void createResource(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); - if (target.exists(flags, false)) + if (target.exists(flags, false)) { return; + } /* make sure target's parent exists */ IContainer parent = target.getParent(); - if (parent.getType() == IResource.FOLDER) + if (parent.getType() == IResource.FOLDER) { ((Folder) target.getParent()).ensureExists(monitor); + } /* Use the basic file creation protocol since we don't want to create any content on disk. */ info = workspace.createResource(target, false); /* Mark this resource as having unknown children */ @@ -103,8 +105,9 @@ protected void deleteResource(UnifiedTreeNode node, Resource target) throws Core } return; } - if (target.exists(flags, false)) + if (target.exists(flags, false)) { target.deleteResource(true, errors); + } node.setExistsWorkspace(false); } @@ -128,9 +131,9 @@ protected void fileToFolder(UnifiedTreeNode node, Resource target) throws CoreEx protected void folderToFile(UnifiedTreeNode node, Resource target) throws CoreException { ResourceInfo info = target.getResourceInfo(false, false); int flags = target.getFlags(info); - if (target.exists(flags, true)) + if (target.exists(flags, true)) { target = (File) ((Folder) target).changeToFile(); - else { + } else { if (!target.exists(flags, false)) { target = (Resource) workspace.getRoot().getFile(target.getFullPath()); // Use the basic file creation protocol since we don't want to @@ -154,8 +157,9 @@ public IStatus getErrorStatus() { protected void makeLocal(UnifiedTreeNode node, Resource target) { ResourceInfo info = target.getResourceInfo(false, true); - if (info != null) + if (info != null) { target.getLocalManager().updateLocalSync(info, node.getLastModified()); + } } /** @@ -167,8 +171,9 @@ protected void refresh(Container parent) throws CoreException { protected void resourceChanged(UnifiedTreeNode node, Resource target) { ResourceInfo info = target.getResourceInfo(false, true); - if (info == null) + if (info == null) { return; + } target.getLocalManager().updateLocalSync(info, node.getLastModified()); info.incrementContentId(); // forget content-related caching flags @@ -201,17 +206,20 @@ protected int synchronizeExistence(UnifiedTreeNode node, Resource target) throws } else { // do we have a gender variant in the workspace? IResource genderVariant = workspace.getRoot().findMember(target.getFullPath()); - if (genderVariant != null) + if (genderVariant != null) { return RL_UNKNOWN; + } if (node.existsInFileSystem()) { Container parent = (Container) target.getParent(); if (!parent.exists()) { refresh(parent); - if (!parent.exists()) + if (!parent.exists()) { return RL_NOT_IN_SYNC; + } } - if (!target.getName().equals(node.getLocalName())) + if (!target.getName().equals(node.getLocalName())) { return RL_IN_SYNC; + } if (!Workspace.caseSensitive && node.getLevel() == 0) { // do we have any alphabetic variants in the workspace? IResource variant = target.findExistingResourceVariant(target.getFullPath()); @@ -237,8 +245,9 @@ protected boolean synchronizeGender(UnifiedTreeNode node, Resource target) throw if (!node.existsInWorkspace()) { //may be an existing resource in the workspace of different gender IResource genderVariant = workspace.getRoot().findMember(target.getFullPath()); - if (genderVariant != null) + if (genderVariant != null) { target = (Resource) genderVariant; + } } if (target.getType() == IResource.FILE) { if (node.isFolder()) { @@ -260,10 +269,11 @@ protected boolean synchronizeGender(UnifiedTreeNode node, Resource target) throw * lastModified */ protected void synchronizeLastModified(UnifiedTreeNode node, Resource target) { - if (target.isLocal(IResource.DEPTH_ZERO)) + if (target.isLocal(IResource.DEPTH_ZERO)) { resourceChanged(node, target); - else + } else { contentAdded(node, target); + } resourceChanged = true; } @@ -271,27 +281,32 @@ protected void synchronizeLastModified(UnifiedTreeNode node, Resource target) { public boolean visit(UnifiedTreeNode node) throws CoreException { Policy.checkCanceled(monitor); try { - if (node.isErrorInFileSystem()) + if (node.isErrorInFileSystem()) { return false; // Don't visit children if we encountered an I/O error + } Resource target = (Resource) node.getResource(); int targetType = target.getType(); - if (targetType == IResource.PROJECT) + if (targetType == IResource.PROJECT) { return true; + } if (node.existsInWorkspace() && node.existsInFileSystem()) { /* for folders we only care about updating local status */ if (targetType == IResource.FOLDER && node.isFolder()) { // if not local, mark as local - if (!target.isLocal(IResource.DEPTH_ZERO)) + if (!target.isLocal(IResource.DEPTH_ZERO)) { makeLocal(node, target); + } ResourceInfo info = target.getResourceInfo(false, false); - if (info != null && info.getModificationStamp() != IResource.NULL_STAMP) + if (info != null && info.getModificationStamp() != IResource.NULL_STAMP) { return true; + } } /* compare file last modified */ if (targetType == IResource.FILE && !node.isFolder()) { ResourceInfo info = target.getResourceInfo(false, false); - if (info != null && info.getModificationStamp() != IResource.NULL_STAMP && info.getLocalSyncInfo() == node.getLastModified()) + if (info != null && info.getModificationStamp() != IResource.NULL_STAMP && info.getLocalSyncInfo() == node.getLastModified()) { return true; + } } } else { if (node.existsInFileSystem() && !IPath.EMPTY.isValidSegment(node.getLocalName())) { @@ -311,11 +326,13 @@ public boolean visit(UnifiedTreeNode node) throws CoreException { return true; } } - if (node.isSymbolicLink() && !node.existsInFileSystem()) + if (node.isSymbolicLink() && !node.existsInFileSystem()) { return true; // Dangling symbolic links are considered to be synchronized. + } - if (synchronizeGender(node, target)) + if (synchronizeGender(node, target)) { synchronizeLastModified(node, target); + } if (targetType == IResource.FILE) { try { ((File) target).updateMetadataFiles(); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeChunkyInputStream.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeChunkyInputStream.java index fc8e73198e5..f16efa8aa0a 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeChunkyInputStream.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeChunkyInputStream.java @@ -54,8 +54,9 @@ public int available() { protected void buildChunk() throws IOException { //read buffer loads of data until an entire chunk is accumulated while (true) { - if (nextByteInBuffer + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength) + if (nextByteInBuffer + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength) { shiftAndFillBuffer(); + } int end = find(ILocalStoreConstants.END_CHUNK, nextByteInBuffer, bufferLength, true); if (end != -1) { accumulate(buffer, nextByteInBuffer, end); @@ -79,8 +80,9 @@ public void close() throws IOException { protected boolean compare(byte[] source, byte[] target, int startIndex) { for (byte element : target) { - if (source[startIndex] != element) + if (source[startIndex] != element) { return false; + } startIndex++; } return true; @@ -88,32 +90,37 @@ protected boolean compare(byte[] source, byte[] target, int startIndex) { protected int find(byte[] pattern, int startIndex, int endIndex, boolean accumulate) throws IOException { int pos = findByte(pattern[0], startIndex, endIndex); - if (pos == -1) + if (pos == -1) { return -1; + } if (pos + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength) { - if (accumulate) + if (accumulate) { accumulate(buffer, nextByteInBuffer, pos); + } nextByteInBuffer = pos; pos = 0; shiftAndFillBuffer(); } - if (compare(buffer, pattern, pos)) + if (compare(buffer, pattern, pos)) { return pos; + } return find(pattern, pos + 1, endIndex, accumulate); } protected int findByte(byte target, int startIndex, int endIndex) { while (startIndex < endIndex) { - if (buffer[startIndex] == target) + if (buffer[startIndex] == target) { return startIndex; + } startIndex++; } return -1; } protected void findChunkStart() throws IOException { - if (nextByteInBuffer + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength) + if (nextByteInBuffer + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength) { shiftAndFillBuffer(); + } int begin = find(ILocalStoreConstants.BEGIN_CHUNK, nextByteInBuffer, bufferLength, false); if (begin != -1) { nextByteInBuffer = begin + ILocalStoreConstants.CHUNK_DELIMITER_SIZE; @@ -131,18 +138,21 @@ protected void findChunkStart() throws IOException { @Override public int read() throws IOException { - if (endOfFile) + if (endOfFile) { return -1; + } // if there are bytes left in the chunk, return the first available - if (nextByteInChunk < chunkLength) + if (nextByteInChunk < chunkLength) { return chunk[nextByteInChunk++] & 0xFF; + } // Otherwise the chunk is empty so clear the current one, get the next // one and recursively call read. Need to recur as the chunk may be // real but empty. resetChunk(); findChunkStart(); - if (endOfFile) + if (endOfFile) { return -1; + } buildChunk(); refineChunk(); return read(); @@ -154,8 +164,9 @@ public int read() throws IOException { */ protected void refineChunk() { int start = chunkLength - ILocalStoreConstants.CHUNK_DELIMITER_SIZE; - if (start < 0) + if (start < 0) { return; + } for (int i = start; i >= 0; i--) { if (compare(chunk, ILocalStoreConstants.BEGIN_CHUNK, i)) { nextByteInChunk = i + ILocalStoreConstants.CHUNK_DELIMITER_SIZE; @@ -176,9 +187,9 @@ protected void shiftAndFillBuffer() throws IOException { nextByteInBuffer = 0; bufferLength = length; int read = input.read(buffer, bufferLength, buffer.length - bufferLength); - if (read != -1) + if (read != -1) { bufferLength += read; - else { + } else { resetChunk(); endOfFile = true; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeChunkyOutputStream.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeChunkyOutputStream.java index f4d9f754664..deaf34b7553 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeChunkyOutputStream.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeChunkyOutputStream.java @@ -92,15 +92,17 @@ public void close() throws IOException { @Override public void write(int b) throws IOException { - if (!isOpen) + if (!isOpen) { open(); + } super.write(b); } @Override public void write(byte b[], int off, int len) throws IOException { - if (!isOpen) + if (!isOpen) { open(); + } out.write(b, off, len); } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeFileInputStream.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeFileInputStream.java index 931b8e4b175..dcc8a5978f7 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeFileInputStream.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeFileInputStream.java @@ -47,8 +47,9 @@ public SafeFileInputStream(String targetPath, String tempPath, int bufferSize) t private static InputStream getInputStream(String targetPath, String tempPath, int bufferSize) throws IOException { File target = new File(targetPath); if (!target.exists()) { - if (tempPath == null) + if (tempPath == null) { tempPath = target.getAbsolutePath() + EXTENSION; + } target = new File(tempPath); } return new BufferedInputStream(new FileInputStream(target), bufferSize); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeFileOutputStream.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeFileOutputStream.java index 9b39f052573..b27771e3d03 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeFileOutputStream.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/SafeFileOutputStream.java @@ -71,22 +71,25 @@ public void close() throws IOException { failed = true; throw e; // rethrow } - if (failed) + if (failed) { temp.delete(); - else + } else { commit(); + } } protected void commit() throws IOException { - if (!temp.exists()) + if (!temp.exists()) { return; + } Files.copy(temp.toPath(), target.toPath(), StandardCopyOption.REPLACE_EXISTING); temp.delete(); } protected void createTempFile(String tempPath) { - if (tempPath == null) + if (tempPath == null) { tempPath = target.getAbsolutePath() + EXTENSION; + } temp = new File(tempPath); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTree.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTree.java index 5dd1d64940e..c610492bd69 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTree.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTree.java @@ -116,17 +116,20 @@ public void accept(IUnifiedTreeVisitor visitor, int depth) throws CoreException setLevel(0, depth); while (!queue.isEmpty()) { UnifiedTreeNode node = queue.remove(); - if (isChildrenMarker(node)) + if (isChildrenMarker(node)) { continue; + } if (isLevelMarker(node)) { - if (!setLevel(getLevel() + 1, depth)) + if (!setLevel(getLevel() + 1, depth)) { break; + } continue; } - if (visitor.visit(node)) + if (visitor.visit(node)) { addNodeChildrenToQueue(node); - else + } else { removeNodeChildrenFromQueue(node); + } //allow reuse of the node, but don't let the freeNodes list grow infinitely if (freeNodes.size() < 32767) { //free memory-consuming elements of the node for garbage collection @@ -143,12 +146,14 @@ protected void addChildren(UnifiedTreeNode node) { // is there a possibility to have children? int parentType = parent.getType(); - if (parentType == IResource.FILE && !node.isFolder()) + if (parentType == IResource.FILE && !node.isFolder()) { return; + } //don't refresh resources in closed or non-existent projects - if (!parent.getProject().isAccessible()) + if (!parent.getProject().isAccessible()) { return; + } // get the list of resources in the file system // don't ask for local children if we know it doesn't exist locally @@ -183,32 +188,36 @@ protected void addChildren(UnifiedTreeNode node) { child = createChildForLinkedResource(target); workspaceIndex++; //if there is a matching local file, skip it - it will be blocked by the linked resource - if (comp == 0) + if (comp == 0) { localIndex++; + } } else if (comp == 0) { // resource exists in workspace and file system --> localInfo is non-null //create workspace-only node for symbolic link that creates a cycle - if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo)) + if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo)) { child = createNode(target, null, null, true); - else + } else { child = createNode(target, null, localInfo, true); + } localIndex++; workspaceIndex++; } else if (comp > 0) { // resource exists only in file system //don't create a node for symbolic links that create a cycle - if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo)) + if (localInfo.getAttribute(EFS.ATTRIBUTE_SYMLINK) && localInfo.isDirectory() && isRecursiveLink(node.getStore(), localInfo)) { child = null; - else + } else { child = createChildNodeFromFileSystem(node, localInfo); + } localIndex++; } else { // resource exists only in the workspace child = createNode(target, null, null, true); workspaceIndex++; } - if (child != null) + if (child != null) { addChildToTree(node, child); + } } } @@ -219,13 +228,15 @@ protected void addChildren(UnifiedTreeNode node) { if (unknown) { // Don't open the info - we might not be inside a workspace-modifying operation resourceInfo = parent.getResourceInfo(false, false); - if (resourceInfo != null) + if (resourceInfo != null) { resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN); + } } /* if we added children, add the childMarker separator */ - if (node.getFirstChild() != null) + if (node.getFirstChild() != null) { addChildrenMarker(); + } } protected void addChildrenFromFileSystem(UnifiedTreeNode node, List childInfos, int index) { @@ -234,8 +245,9 @@ protected void addChildrenFromFileSystem(UnifiedTreeNode node, List c } for (IFileInfo info : childInfos.subList(index, childInfos.size())) { //don't create a node for symbolic links that create a cycle - if (!info.getAttribute(EFS.ATTRIBUTE_SYMLINK) || !info.isDirectory() || !isRecursiveLink(node.getStore(), info)) + if (!info.getAttribute(EFS.ATTRIBUTE_SYMLINK) || !info.isDirectory() || !isRecursiveLink(node.getStore(), info)) { addChildToTree(node, createChildNodeFromFileSystem(node, info)); + } } } @@ -244,8 +256,9 @@ protected void addChildrenMarker() { } protected void addChildToTree(UnifiedTreeNode node, UnifiedTreeNode child) { - if (node.getFirstChild() == null) + if (node.getFirstChild() == null) { node.setFirstChild(child); + } addElementToQueue(child); } @@ -256,30 +269,36 @@ protected void addElementToQueue(UnifiedTreeNode target) { protected void addNodeChildrenToQueue(UnifiedTreeNode node) { /* if the first child is not null we already added the children */ /* If the children won't be at a valid level for the refresh depth, don't bother adding them */ - if (!childLevelValid || node.getFirstChild() != null) + if (!childLevelValid || node.getFirstChild() != null) { return; + } addChildren(node); - if (queue.isEmpty()) + if (queue.isEmpty()) { return; + } //if we're about to change levels, then the children just added //are the last nodes for their level, so add a level marker to the queue UnifiedTreeNode nextNode = queue.peek(); - if (isChildrenMarker(nextNode)) + if (isChildrenMarker(nextNode)) { queue.remove(); + } nextNode = queue.peek(); - if (isLevelMarker(nextNode)) + if (isLevelMarker(nextNode)) { addElementToQueue(levelMarker); + } } protected void addRootToQueue() { //don't refresh in closed projects - if (!root.getProject().isAccessible()) + if (!root.getProject().isAccessible()) { return; + } IFileStore store = ((Resource) root).getStore(); IFileInfo fileInfo = fileTree != null ? fileTree.getFileInfo(store) : store.fetchInfo(); UnifiedTreeNode node = createNode(root, store, fileInfo, root.exists()); - if (node.existsInFileSystem() || node.existsInWorkspace()) + if (node.existsInFileSystem() || node.existsInWorkspace()) { addElementToQueue(node); + } } /** @@ -323,26 +342,30 @@ protected UnifiedTreeNode createNode(IResource resource, IFileStore store, IFile protected Iterator getChildren(UnifiedTreeNode node) { /* if first child is null we need to add node's children to queue */ - if (node.getFirstChild() == null) + if (node.getFirstChild() == null) { addNodeChildrenToQueue(node); + } /* if the first child is still null, the node does not have any children */ - if (node.getFirstChild() == null) + if (node.getFirstChild() == null) { return Collections.emptyIterator(); + } /* get the index of the first child */ int index = queue.indexOf(node.getFirstChild()); /* if we do not have children, just return an empty enumeration */ - if (index == -1) + if (index == -1) { return Collections.emptyIterator(); + } /* create an enumeration with node's children */ List result = new ArrayList<>(10); while (true) { UnifiedTreeNode child = queue.get(index); - if (isChildrenMarker(child)) + if (isChildrenMarker(child)) { break; + } result.add(child); if (index == queue.size() - 1) { index = 0; @@ -361,13 +384,15 @@ protected List getLocalList(UnifiedTreeNode node) { try { final IFileStore store = node.getStore(); IFileInfo[] list; - if (fileTree != null && (fileTree.getTreeRoot().equals(store) || fileTree.getTreeRoot().isParentOf(store))) + if (fileTree != null && (fileTree.getTreeRoot().equals(store) || fileTree.getTreeRoot().isParentOf(store))) { list = fileTree.getChildInfos(store); - else + } else { list = store.childInfos(EFS.NONE, null); + } - if (list == null || list.length == 0) + if (list == null || list.length == 0) { return List.of(); + } list = ((Resource) node.getResource()).filterChildren(list, false); if (list.length > 1) { Arrays.sort(list); @@ -385,15 +410,17 @@ protected Workspace getWorkspace() { protected void initializeQueue() { //initialize the queue - if (queue == null) + if (queue == null) { queue = new LinkedList<>(); - else + } else { queue.clear(); + } //initialize the free nodes list - if (freeNodes == null) + if (freeNodes == null) { freeNodes = new ArrayList<>(100); - else + } else { freeNodes.clear(); + } addRootToQueue(); addElementToQueue(levelMarker); } @@ -424,9 +451,8 @@ protected void initLinkHistoriesIfNeeded() { if (pathPrefixHistory == null) { //Bug 232426: Check what life cycle we need for the histories Job job = Job.getJobManager().currentJob(); - if (job instanceof RefreshJob) { + if (job instanceof RefreshJob refreshJob) { //we are running from the RefreshJob: use the path history of the job - RefreshJob refreshJob = (RefreshJob) job; pathPrefixHistory = refreshJob.getPathPrefixHistory(); rootPathHistory = refreshJob.getRootPathHistory(); } else { @@ -562,11 +588,13 @@ protected boolean isValidLevel(int currentLevel, int depth) { */ protected void removeNodeChildrenFromQueue(UnifiedTreeNode node) { UnifiedTreeNode first = node.getFirstChild(); - if (first == null) + if (first == null) { return; + } while (true) { - if (first.equals(queue.pollLast())) + if (first.equals(queue.pollLast())) { break; + } } node.setFirstChild(null); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTreeNode.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTreeNode.java index 3e45ecd5ce5..5c6de678e21 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTreeNode.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/localstore/UnifiedTreeNode.java @@ -92,8 +92,9 @@ public IResource getResource() { */ public IFileStore getStore() { //initialize store lazily, because it is not always needed - if (store == null) + if (store == null) { store = ((Resource) resource).getStore(); + } return store; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/properties/PropertyBucket.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/properties/PropertyBucket.java index 9958c654adf..187417b80ab 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/properties/PropertyBucket.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/properties/PropertyBucket.java @@ -52,20 +52,24 @@ public static class PropertyEntry extends Entry { */ static String[][] delete(String[][] existing, QualifiedName propertyName) { // a size-1 array is a special case - if (existing.length == 1) + if (existing.length == 1) { return (existing[0][0].equals(propertyName.getQualifier()) && existing[0][1].equals(propertyName.getLocalName())) ? null : existing; + } // find the guy to delete int deletePosition = search(existing, propertyName); - if (deletePosition < 0) + if (deletePosition < 0) { // not found, nothing to delete return existing; + } String[][] newValue = new String[existing.length - 1][]; - if (deletePosition > 0) + if (deletePosition > 0) { // copy elements preceding the one to be removed System.arraycopy(existing, 0, newValue, 0, deletePosition); - if (deletePosition < existing.length - 1) + } + if (deletePosition < existing.length - 1) { // copy elements succeeding the one to be removed System.arraycopy(existing, deletePosition + 1, newValue, deletePosition, newValue.length - deletePosition); + } return newValue; } @@ -80,11 +84,13 @@ static String[][] insert(String[][] existing, QualifiedName propertyName, String // not found - insert int insertPosition = -index - 1; String[][] newValue = new String[existing.length + 1][]; - if (insertPosition > 0) + if (insertPosition > 0) { System.arraycopy(existing, 0, newValue, 0, insertPosition); + } newValue[insertPosition] = new String[] {propertyName.getQualifier(), propertyName.getLocalName(), propertyValue}; - if (insertPosition < existing.length) + if (insertPosition < existing.length) { System.arraycopy(existing, insertPosition, newValue, insertPosition + 1, existing.length - insertPosition); + } return newValue; } @@ -102,10 +108,11 @@ static Object merge(String[][] base, String[][] additions) { result[added++] = additions[additionPointer++]; // duplicate, override basePointer++; - } else if (comparison < 0) + } else if (comparison < 0) { result[added++] = base[basePointer++]; - else + } else { result[added++] = additions[additionPointer++]; + } } // copy the remaining states from either additions or base arrays String[][] remaining = basePointer == base.length ? additions : base; @@ -113,9 +120,10 @@ static Object merge(String[][] base, String[][] additions) { int remainingCount = remaining.length - remainingPointer; System.arraycopy(remaining, remainingPointer, result, added, remainingCount); added += remainingCount; - if (added == base.length + additions.length) + if (added == base.length + additions.length) { // no collisions return result; + } // there were collisions, need to compact String[][] finalResult = new String[added][]; System.arraycopy(result, 0, finalResult, 0, finalResult.length); @@ -153,17 +161,19 @@ protected PropertyEntry(IPath path, String[][] value) { * are found, the entry is marked for removal. */ private void compact() { - if (!isDirty()) + if (!isDirty()) { return; + } int occurrences = 0; for (String[] s : value) { if (s != null) { value[occurrences++] = s; } } - if (occurrences == value.length) + if (occurrences == value.length) { // no states deleted return; + } if (occurrences == 0) { // no states remaining value = EMPTY_DATA; @@ -241,8 +251,9 @@ protected Entry createEntry(IPath path, Object value) { private PropertyEntry getEntry(IPath path) { String pathAsString = path.toString(); String[][] existing = (String[][]) getEntryValue(pathAsString); - if (existing == null) + if (existing == null) { return null; + } return new PropertyEntry(path, existing); } @@ -253,8 +264,9 @@ protected String getIndexFileName() { public String getProperty(IPath path, QualifiedName name) { PropertyEntry entry = getEntry(path); - if (entry == null) + if (entry == null) { return null; + } return entry.getProperty(name); } @@ -325,15 +337,17 @@ public void setProperty(IPath path, QualifiedName name, String value) { String pathAsString = path.toString(); String[][] existing = (String[][]) getEntryValue(pathAsString); if (existing == null) { - if (value != null) + if (value != null) { setEntryValue(pathAsString, new String[][] {{name.getQualifier(), name.getLocalName(), value}}); + } return; } String[][] newValue; - if (value != null) + if (value != null) { newValue = PropertyEntry.insert(existing, name, value); - else + } else { newValue = PropertyEntry.delete(existing, name); + } // even if newValue == existing we should mark as dirty (insert may just change the existing array) setEntryValue(pathAsString, newValue); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/properties/PropertyManager2.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/properties/PropertyManager2.java index a97a6f9dce9..161564cb813 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/properties/PropertyManager2.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/properties/PropertyManager2.java @@ -53,15 +53,17 @@ public void afterSaving(Bucket bucket) throws CoreException { } private void saveChanges(PropertyBucket bucket) throws CoreException { - if (changes.isEmpty()) + if (changes.isEmpty()) { return; + } // make effective all changes collected Iterator i = changes.iterator(); PropertyEntry entry = i.next(); tree.loadBucketFor(entry.getPath()); bucket.setProperties(entry); - while (i.hasNext()) + while (i.hasNext()) { bucket.setProperties(i.next()); + } bucket.save(); } @@ -133,8 +135,9 @@ public synchronized Map getProperties(IResource target) t public int visit(Entry entry) { PropertyEntry propertyEntry = (PropertyEntry) entry; int propertyCount = propertyEntry.getOccurrences(); - for (int i = 0; i < propertyCount; i++) + for (int i = 0; i < propertyCount; i++) { result.put(propertyEntry.getPropertyName(i), propertyEntry.getPropertyValue(i)); + } return CONTINUE; } }, target.getFullPath(), BucketTree.DEPTH_ZERO); @@ -171,7 +174,7 @@ public synchronized void setProperty(IResource target, QualifiedName name, Strin resource.checkAccessible(flags); // enforce the limit stated by the spec if (value != null && value.length() > MAX_VALUE_SIZE) { - String message = NLS.bind(Messages.properties_valueTooLong, new Object[] {name.getQualifier(), name.getLocalName(), Integer.toString(MAX_VALUE_SIZE)}); + String message = NLS.bind(Messages.properties_valueTooLong, name.getQualifier(), name.getLocalName(), Integer.toString(MAX_VALUE_SIZE)); throw new ResourceException(IResourceStatus.FAILED_WRITE_METADATA, target.getFullPath(), message, null); } if (name.getQualifier() == null) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/FilePropertyTester.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/FilePropertyTester.java index 03d500684c9..66eaac664fc 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/FilePropertyTester.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/FilePropertyTester.java @@ -52,15 +52,18 @@ public class FilePropertyTester extends ResourcePropertyTester { @Override public boolean test(Object receiver, String method, Object[] args, Object expectedValue) { - if ((receiver instanceof IFile) && method.equals(CONTENT_TYPE_ID)) + if ((receiver instanceof IFile) && method.equals(CONTENT_TYPE_ID)) { return testContentType((IFile) receiver, toString(expectedValue), isArgumentUsed(args, IS_KIND_OF), isArgumentUsed(args, USE_FILENAME_ONLY)); + } return false; } private boolean isArgumentUsed(Object[] args, String value) { - for (Object arg : args) - if (value.equals(arg)) + for (Object arg : args) { + if (value.equals(arg)) { return true; + } + } return false; } @@ -97,22 +100,25 @@ private boolean testContentType(final IFile file, String contentTypeId, boolean final String expectedValue = contentTypeId.trim(); IContentType actualContentType = null; if (!useFilenameOnly) { - if (!file.exists()) + if (!file.exists()) { return false; + } IContentDescription contentDescription = null; try { contentDescription = file.getContentDescription(); } catch (CoreException e) { Policy.log(IStatus.ERROR, "Core exception while retrieving the content description", e);//$NON-NLS-1$ } - if (contentDescription != null) + if (contentDescription != null) { actualContentType = contentDescription.getContentType(); + } } else { actualContentType = Platform.getContentTypeManager().findContentTypeFor(file.getName()); } if (actualContentType != null) { - if (isKindOfUsed) + if (isKindOfUsed) { return actualContentType.isKindOf(Platform.getContentTypeManager().getContentType(expectedValue)); + } return expectedValue.equals(actualContentType.getId()); } return false; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ProjectPropertyTester.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ProjectPropertyTester.java index 20858b871c1..6f61fd9f724 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ProjectPropertyTester.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ProjectPropertyTester.java @@ -30,8 +30,9 @@ public class ProjectPropertyTester extends ResourcePropertyTester { @Override public boolean test(Object receiver, String method, Object[] args, Object expectedValue) { - if ((receiver instanceof IProject) && method.equals(OPEN)) + if ((receiver instanceof IProject) && method.equals(OPEN)) { return ((IProject) receiver).isOpen() == toBoolean(expectedValue); + } return false; } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ResourceMappingPropertyTester.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ResourceMappingPropertyTester.java index 7e58b34c507..616b9603090 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ResourceMappingPropertyTester.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ResourceMappingPropertyTester.java @@ -26,15 +26,18 @@ public class ResourceMappingPropertyTester extends ResourcePropertyTester { @Override public boolean test(Object receiver, String method, Object[] args, Object expectedValue) { - if (!(receiver instanceof ResourceMapping)) + if (!(receiver instanceof ResourceMapping)) { return false; - if (!method.equals(PROJECT_PERSISTENT_PROPERTY)) + } + if (!method.equals(PROJECT_PERSISTENT_PROPERTY)) { return false; + } //Note: we currently say the test is satisfied if any project associated //with the mapping satisfies the test. IProject[] projects = ((ResourceMapping) receiver).getProjects(); - if (projects.length == 0) + if (projects.length == 0) { return false; + } String propertyName; String expectedVal; switch (args.length) { @@ -57,16 +60,19 @@ public boolean test(Object receiver, String method, Object[] args, Object expect try { Object actualVal = project.getPersistentProperty(key); //the value is not set, so keep looking on other projects - if (actualVal == null) + if (actualVal == null) { continue; + } //record that we have found at least one value found = true; //expected value of null means we expect *any* value, rather than expecting no value - if (expectedVal == null) + if (expectedVal == null) { continue; + } //if the value we find does not match, then the property is not satisfied - if (!expectedVal.equals(actualVal.toString())) + if (!expectedVal.equals(actualVal.toString())) { return false; + } } catch (CoreException e) { // ignore } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ResourcePropertyTester.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ResourcePropertyTester.java index f52850315c4..d821cf85919 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ResourcePropertyTester.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/ResourcePropertyTester.java @@ -96,9 +96,9 @@ public class ResourcePropertyTester extends PropertyTester { @Override public boolean test(Object receiver, String method, Object[] args, Object expectedValue) { - if (!(receiver instanceof IResource)) + if (!(receiver instanceof IResource res)) { return false; - IResource res = (IResource) receiver; + } if (method.equals(NAME)) { return new StringMatcher(toString(expectedValue)).match(res.getName()); } else if (method.equals(PATH)) { @@ -151,8 +151,9 @@ public boolean test(Object receiver, String method, Object[] args, Object expect */ protected boolean testProperty(IResource resource, boolean persistentFlag, Object[] args, Object expectedValue) { //the project of IWorkspaceRoot is null - if (resource == null) + if (resource == null) { return false; + } String propertyName; String expectedVal; switch (args.length) { @@ -172,8 +173,9 @@ protected boolean testProperty(IResource resource, boolean persistentFlag, Objec try { QualifiedName key = toQualifedName(propertyName); Object actualVal = persistentFlag ? resource.getPersistentProperty(key) : resource.getSessionProperty(key); - if (actualVal == null) + if (actualVal == null) { return false; + } return expectedVal == null || expectedVal.equals(actualVal.toString()); } catch (CoreException e) { //if the resource is not accessible, fall through and return false below diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/StringMatcher.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/StringMatcher.java index 1f0717bec0c..67b372a6103 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/StringMatcher.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/propertytester/StringMatcher.java @@ -60,8 +60,9 @@ public class StringMatcher { * @param pattern the pattern to match text against */ public StringMatcher(String pattern) { - if (pattern == null) + if (pattern == null) { throw new IllegalArgumentException(); + } this.pattern = pattern; patternLength = pattern.length(); parseWildCards(); @@ -79,11 +80,13 @@ private int findPosition(String text, int start, int end, String p) { int plen = p.length(); for (int i = start, max = end - plen; i <= max; ++i) { if (hasWildCard) { - if (regExpRegionMatches(text, i, p, 0, plen)) + if (regExpRegionMatches(text, i, p, 0, plen)) { return i; + } } else { - if (text.regionMatches(true, i, p, 0, plen)) + if (text.regionMatches(true, i, p, 0, plen)) { return i; + } } } return -1; @@ -96,27 +99,33 @@ private int findPosition(String text, int start, int end, String p) { * @param text a String object that contains the substring to match */ public boolean match(String text) { - if (text == null) + if (text == null) { return false; + } final int end = text.length(); final int segmentCount = segments.length; - if (segmentCount == 0 && (hasLeadingStar || hasTrailingStar)) // pattern contains only '*'(s) + if (segmentCount == 0 && (hasLeadingStar || hasTrailingStar)) { // pattern contains only '*'(s) return true; - if (end == 0) + } + if (end == 0) { return patternLength == 0; - if (patternLength == 0) + } + if (patternLength == 0) { return false; + } int currentTextPosition = 0; - if ((end - bound) < 0) + if ((end - bound) < 0) { return false; + } int segmentIndex = 0; String current = segments[segmentIndex]; /* process first segment */ if (!hasLeadingStar) { int currentLength = current.length(); - if (!regExpRegionMatches(text, 0, current, 0, currentLength)) + if (!regExpRegionMatches(text, 0, current, 0, currentLength)) { return false; + } segmentIndex++; currentTextPosition = currentTextPosition + currentLength; } @@ -128,8 +137,9 @@ public boolean match(String text) { while (segmentIndex < segmentCount) { current = segments[segmentIndex]; int currentMatch = findPosition(text, currentTextPosition, end, current); - if (currentMatch < 0) + if (currentMatch < 0) { return false; + } currentTextPosition = currentMatch + current.length(); segmentIndex++; } @@ -146,8 +156,9 @@ public boolean match(String text) { * Parses the pattern into segments separated by wildcard '*' characters. */ private void parseWildCards() { - if (pattern.startsWith("*")) //$NON-NLS-1$ + if (pattern.startsWith("*")) { //$NON-NLS-1$ hasLeadingStar = true; + } if (pattern.endsWith("*")) {//$NON-NLS-1$ /* make sure it's not an escaped wildcard */ if (patternLength > 1 && pattern.charAt(patternLength - 2) != '\\') { @@ -217,16 +228,20 @@ private boolean regExpRegionMatches(String text, int tStart, String p, int pStar char pchar = p.charAt(pStart++); // process wild cards, skipping single wild cards - if (pchar == SINGLE_WILD_CARD) + if (pchar == SINGLE_WILD_CARD) { continue; - if (pchar == tchar) + } + if (pchar == tchar) { continue; - if (Character.toUpperCase(tchar) == Character.toUpperCase(pchar)) + } + if (Character.toUpperCase(tchar) == Character.toUpperCase(pchar)) { continue; + } // comparing after converting to upper case doesn't handle all cases; // also compare after converting to lower case - if (Character.toLowerCase(tchar) == Character.toLowerCase(pchar)) + if (Character.toLowerCase(tchar) == Character.toLowerCase(pchar)) { continue; + } return false; } return true; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/MonitorManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/MonitorManager.java index 01fb19f7ff7..d0887aea693 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/MonitorManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/MonitorManager.java @@ -99,8 +99,9 @@ public MonitorManager(IWorkspace workspace, RefreshManager refreshManager) { */ private RefreshProvider[] getRefreshProviders() { synchronized (this) { - if (providers != null) + if (providers != null) { return providers; + } } IExtensionPoint extensionPoint = Platform.getExtensionRegistry().getExtensionPoint(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_REFRESH_PROVIDERS); IConfigurationElement[] infos = extensionPoint.getConfigurationElements(); @@ -115,8 +116,9 @@ private RefreshProvider[] getRefreshProviders() { } catch (CoreException e) { Policy.log(IStatus.WARNING, Messages.refresh_installError, e); } - if (provider != null) + if (provider != null) { providerList.add(provider); + } } synchronized (this) { providers = providerList.toArray(new RefreshProvider[providerList.size()]); @@ -139,8 +141,9 @@ private List getResourcesToMonitor() { try { IResource[] members = project.members(); for (IResource member : members) { - if (member.isLinked()) + if (member.isLinked()) { resourcesToMonitor.add(member); + } } }catch (CoreException e) { Policy.log(IStatus.WARNING, Messages.refresh_refreshErr, e); @@ -163,8 +166,9 @@ public void handleEvent(LifecycleEvent event) { private boolean isMonitoring(IResource resource) { synchronized (registeredMonitors) { for (List resources : registeredMonitors.values()) { - if ((resources != null) && (resources.contains(resource))) + if ((resources != null) && (resources.contains(resource))) { return true; + } } } return false; @@ -175,8 +179,9 @@ private boolean isMonitoring(IResource resource) { * monitor was installed, and false if a refresh provider was installed. */ boolean monitor(IResource resource, IProgressMonitor progressMonitor) { - if (isMonitoring(resource)) + if (isMonitoring(resource)) { return false; + } boolean pollingMonitorNeeded = true; RefreshProvider[] refreshProviders = getRefreshProviders(); SubMonitor subMonitor = SubMonitor.convert(progressMonitor, refreshProviders.length); @@ -198,10 +203,12 @@ boolean monitor(IResource resource, IProgressMonitor progressMonitor) { * @see IRefreshResult#monitorFailed */ public void monitorFailed(IRefreshMonitor monitor, IResource resource) { - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + " monitor (" + monitor + ") failed to monitor resource: " + resource); //$NON-NLS-1$ //$NON-NLS-2$ - if (registeredMonitors == null || monitor == null) + } + if (registeredMonitors == null || monitor == null) { return; + } if (resource == null) { List resources = registeredMonitors.get(monitor); if (resources == null || resources.isEmpty()) { @@ -228,8 +235,9 @@ public void monitorFailed(IRefreshMonitor monitor, IResource resource) { */ @Override public void pathVariableChanged(IPathVariableChangeEvent event) { - if (registeredMonitors.isEmpty()) + if (registeredMonitors.isEmpty()) { return; + } String variableName = event.getVariableName(); final Set invalidResources = new HashSet<>(); for (List resources : registeredMonitors.values()) { @@ -264,11 +272,13 @@ private void registerMonitor(IRefreshMonitor monitor, IResource resource) { resources = new ArrayList<>(1); registeredMonitors.put(monitor, resources); } - if (!resources.contains(resource)) + if (!resources.contains(resource)) { resources.add(resource); + } } - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + " added monitor (" + monitor + ") on resource: " + resource); //$NON-NLS-1$ //$NON-NLS-2$ + } } private void removeMonitor(IRefreshMonitor monitor, IResource resource) { @@ -281,8 +291,9 @@ private void removeMonitor(IRefreshMonitor monitor, IResource resource) { registeredMonitors.remove(monitor); } } - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + " removing monitor (" + monitor + ") on resource: " + resource); //$NON-NLS-1$ //$NON-NLS-2$ + } } private IRefreshMonitor safeInstallMonitor(RefreshProvider provider, IResource resource, IProgressMonitor progressMonitor) { @@ -311,8 +322,9 @@ public void start(IProgressMonitor progressMonitor) { workspace.addResourceChangeListener(this, IResourceChangeEvent.POST_CHANGE); //adding the lifecycle listener twice does no harm ((Workspace) workspace).addLifecycleListener(this); - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + " starting monitor manager."); //$NON-NLS-1$ + } //If not exclusively using polling, create a polling monitor and run it once, to catch //changes that occurred while the native monitor was turned off. subMonitor.split(1); @@ -334,14 +346,16 @@ public void stop() { } } registeredMonitors.clear(); - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + " stopping monitor manager."); //$NON-NLS-1$ + } pollMonitor.cancel(); } void unmonitor(IResource resource, IProgressMonitor progressMonitor) { - if (resource == null || !isMonitoring(resource)) + if (resource == null || !isMonitoring(resource)) { return; + } SubMonitor subMonitor = SubMonitor.convert(progressMonitor, 100); synchronized (registeredMonitors) { SubMonitor loopMonitor = subMonitor.split(90).setWorkRemaining(registeredMonitors.entrySet().size()); @@ -354,13 +368,15 @@ void unmonitor(IResource resource, IProgressMonitor progressMonitor) { } } } - if (resource.getType() == IResource.PROJECT) + if (resource.getType() == IResource.PROJECT) { unmonitorLinkedContents((IProject) resource, subMonitor.split(10)); + } } private void unmonitorLinkedContents(IProject project, IProgressMonitor progressMonitor) { - if (!project.isAccessible()) + if (!project.isAccessible()) { return; + } IResource[] children = null; try { children = project.members(); @@ -380,8 +396,9 @@ private void unmonitorLinkedContents(IProject project, IProgressMonitor progress @Override public void resourceChanged(IResourceChangeEvent event) { IResourceDelta delta = event.getDelta(); - if (delta == null) + if (delta == null) { return; + } try { delta.accept(this); } catch (CoreException e) { @@ -393,13 +410,15 @@ public void resourceChanged(IResourceChangeEvent event) { public boolean visit(IResourceDelta delta) { if (delta.getKind() == IResourceDelta.ADDED) { IResource resource = delta.getResource(); - if (resource.isLinked()) + if (resource.isLinked()) { monitor(resource, new NullProgressMonitor()); + } } if ((delta.getFlags() & IResourceDelta.OPEN) != 0) { IProject project = (IProject) delta.getResource(); - if (project.isAccessible()) + if (project.isAccessible()) { monitor(project, new NullProgressMonitor()); + } } return true; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/PollingMonitor.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/PollingMonitor.java index 988a6032c5b..f35cffa2b8c 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/PollingMonitor.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/PollingMonitor.java @@ -113,50 +113,60 @@ protected IStatus run(IProgressMonitor monitor) { //ignore } //don't wait forever - if ((System.currentTimeMillis() - waitStart) > 90000) + if ((System.currentTimeMillis() - waitStart) > 90000) { break; + } } } long time = System.currentTimeMillis(); //check to see if we need to start an iteration if (toRefresh.isEmpty()) { beginIteration(); - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + "New polling iteration on " + toRefresh.size() + " roots"); //$NON-NLS-1$ //$NON-NLS-2$ + } } final int oldSize = toRefresh.size(); - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + "started polling"); //$NON-NLS-1$ + } //refresh the hot root if applicable - if (time - hotRootTime > HOT_ROOT_DECAY) + if (time - hotRootTime > HOT_ROOT_DECAY) { hotRoot = null; - else if (hotRoot != null && !monitor.isCanceled()) + } else if (hotRoot != null && !monitor.isCanceled()) { poll(hotRoot); + } //process roots that have not yet been refreshed this iteration final long loopStart = System.currentTimeMillis(); while (!toRefresh.isEmpty()) { - if (monitor.isCanceled()) + if (monitor.isCanceled()) { break; + } poll(toRefresh.remove(toRefresh.size() - 1)); //stop the iteration if we have exceed maximum duration - if (System.currentTimeMillis() - loopStart > MAX_DURATION) + if (System.currentTimeMillis() - loopStart > MAX_DURATION) { break; + } } time = System.currentTimeMillis() - time; - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + "polled " + (oldSize - toRefresh.size()) + " roots in " + time + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } //reschedule automatically - shouldRun will cancel if not needed //make sure it doesn't run more than 5% of the time long delay = Math.max(MIN_FREQUENCY, time * 20); //back off even more if there are other jobs running - if (!getJobManager().isIdle()) + if (!getJobManager().isIdle()) { delay *= 2; - if (Policy.DEBUG_AUTO_REFRESH) + } + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + "rescheduling polling job in: " + delay / 1000 + " seconds"); //$NON-NLS-1$ //$NON-NLS-2$ + } //don't reschedule the job if the resources plugin has been shut down Bundle bundle = Platform.getBundle(ResourcesPlugin.PI_RESOURCES); - if (bundle != null && bundle.getState() == Bundle.ACTIVE) + if (bundle != null && bundle.getState() == Bundle.ACTIVE) { schedule(delay); + } return Status.OK_STATUS; } @@ -178,17 +188,20 @@ void runOnce() { } private void poll(IResource resource) { - if (resource.isSynchronized(IResource.DEPTH_INFINITE)) + if (resource.isSynchronized(IResource.DEPTH_INFINITE)) { return; + } //don't refresh links with no local content - if (resource.isLinked() && !((Resource) resource).getStore().fetchInfo().exists()) + if (resource.isLinked() && !((Resource) resource).getStore().fetchInfo().exists()) { return; + } //submit refresh request refreshManager.refresh(resource); hotRoot = resource; hotRootTime = System.currentTimeMillis(); - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + "new hot root: " + resource); //$NON-NLS-1$ + } } @Override @@ -204,8 +217,9 @@ public boolean shouldRun() { */ private synchronized void beginIteration() { toRefresh.addAll(resourceRoots); - if (hotRoot != null) + if (hotRoot != null) { toRefresh.remove(hotRoot); + } } /* @@ -213,11 +227,13 @@ private synchronized void beginIteration() { */ @Override public synchronized void unmonitor(IResource resource) { - if (resource == null) + if (resource == null) { resourceRoots.clear(); - else + } else { resourceRoots.remove(resource); - if (resourceRoots.isEmpty()) + } + if (resourceRoots.isEmpty()) { cancel(); + } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/RefreshJob.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/RefreshJob.java index a2bf5e28c2c..f44181e608b 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/RefreshJob.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/refresh/RefreshJob.java @@ -115,11 +115,11 @@ private synchronized void addRequest(IResource resource) { for (Iterator it = fRequests.iterator(); it.hasNext();) { IPath request = it.next().getFullPath(); //discard any existing requests the same or below the resource to be added - if (toAdd.isPrefixOf(request)) + if (toAdd.isPrefixOf(request)) { it.remove(); - //nothing to do if the resource to be added is a child of an existing request - else if (request.isPrefixOf(toAdd)) + } else if (request.isPrefixOf(toAdd)) { return; + } } //finally add the new request to the front of the queue fRequests.add(resource); @@ -142,8 +142,9 @@ public boolean belongsTo(Object family) { * to the provided list. */ protected List collectChildrenToDepth(IResource resource, ArrayList children, int depth) { - if (resource.getType() == IResource.FILE) + if (resource.getType() == IResource.FILE) { return children; + } IResource[] members; try { members = ((IContainer) resource).members(); @@ -152,12 +153,14 @@ protected List collectChildrenToDepth(IResource resource, ArrayList collectChildrenToDepth(IResource resource, ArrayList longestRefresh) + if (refreshTime > longestRefresh) { longestRefresh = refreshTime; + } //show occasional progress if (refreshCount % depthIncreaseStep == 0) { //be polite to other threads (no effect on some platforms) @@ -261,11 +269,13 @@ public IStatus runInWorkspace(IProgressMonitor monitor) { } finally { pathPrefixHistory = null; rootPathHistory = null; - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(RefreshManager.DEBUG_PREFIX + " finished refresh job in: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } } - if (!errors.isOK()) + if (!errors.isOK()) { return errors; + } return Status.OK_STATUS; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/AliasManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/AliasManager.java index a871c521961..0112726a74e 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/AliasManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/AliasManager.java @@ -86,16 +86,18 @@ public FindAliasesDoit(IResource aliasResource) { @Override public void accept(IResource match) { //don't record the resource we're computing aliases against as a match - if (match.getFullPath().isPrefixOf(searchPath)) + if (match.getFullPath().isPrefixOf(searchPath)) { return; + } IPath aliasPath = null; switch (match.getType()) { case IResource.PROJECT : //first check if there is a linked resource that blocks the project location if (suffix.segmentCount() > 0) { IResource testResource = ((IProject) match).findMember(suffix.segment(0)); - if (testResource != null && testResource.isLinked()) + if (testResource != null && testResource.isLinked()) { return; + } } //there is an alias under this project aliasPath = match.getFullPath().append(suffix); @@ -104,19 +106,22 @@ public void accept(IResource match) { aliasPath = match.getFullPath().append(suffix); break; case IResource.FILE : - if (suffix.segmentCount() == 0) + if (suffix.segmentCount() == 0) { aliasPath = match.getFullPath(); + } break; } - if (aliasPath != null) + if (aliasPath != null) { if (aliasType == IResource.FILE) { aliases.add(workspace.getRoot().getFile(aliasPath)); } else { - if (aliasPath.segmentCount() == 1) + if (aliasPath.segmentCount() == 1) { aliases.add(workspace.getRoot().getProject(aliasPath.lastSegment())); - else + } else { aliases.add(workspace.getRoot().getFolder(aliasPath)); + } } + } } } @@ -142,8 +147,9 @@ public boolean add(IFileStore location, IResource resource) { return true; } if (oldValue instanceof IResource) { - if (resource.equals(oldValue)) + if (resource.equals(oldValue)) { return false;//duplicate + } ArrayList newValue = new ArrayList<>(2); newValue.add(oldValue); newValue.add(resource); @@ -152,8 +158,9 @@ public boolean add(IFileStore location, IResource resource) { } @SuppressWarnings("unchecked") ArrayList list = (ArrayList) oldValue; - if (list.contains(resource)) + if (list.contains(resource)) { return false;//duplicate + } list.add(resource); return true; } @@ -181,8 +188,9 @@ public void matchingPrefixDo(IFileStore prefix, Consumer doit) { matching = map; } for (Object value : matching.values()) { - if (value == null) + if (value == null) { return; + } if (value instanceof List) { for (Object element : ((List) value)) { if (element instanceof IResource) { @@ -201,8 +209,9 @@ public void matchingPrefixDo(IFileStore prefix, Consumer doit) { */ public void matchingResourcesDo(IFileStore location, Consumer doit) { Object value = map.get(location); - if (value == null) + if (value == null) { return; + } if (value instanceof List) { for (Object element : ((List) value)) { if (element instanceof IResource) { @@ -247,8 +256,9 @@ public void overLappingResourcesDo(Consumer doit) { //null out previous resource so we don't call doit twice with same resource previousResource = null; } - if (currentResource != null) + if (currentResource != null) { doit.accept(currentResource.getProject()); + } //keep iterating with the same previous store because there may be more overlaps continue; } @@ -264,8 +274,9 @@ public void overLappingResourcesDo(Consumer doit) { */ public boolean remove(IFileStore location, IResource resource) { Object oldValue = map.get(location); - if (oldValue == null) + if (oldValue == null) { return false; + } if (oldValue instanceof IResource) { if (resource.equals(oldValue)) { map.remove(location); @@ -276,8 +287,9 @@ public boolean remove(IFileStore location, IResource resource) { @SuppressWarnings("unchecked") ArrayList list = (ArrayList) oldValue; boolean wasRemoved = list.remove(resource); - if (list.isEmpty()) + if (list.isEmpty()) { map.remove(location); + } return wasRemoved; } } @@ -338,16 +350,20 @@ public AliasManager(Workspace workspace) { private void addToLocationsMap(IProject project) { IFileStore location = ((Resource) project).getStore(); - if (location != null) + if (location != null) { locationsMap.add(location, project); + } ProjectDescription description = ((Project) project).internalGetDescription(); - if (description == null) + if (description == null) { return; - if (description.getLocationURI() != null) + } + if (description.getLocationURI() != null) { nonDefaultResourceCount++; + } HashMap links = description.getLinks(); - if (links == null) + if (links == null) { return; + } for (LinkDescription linkDesc : links.values()) { IResource link = project.findMember(linkDesc.getProjectRelativePath()); if (link != null) { @@ -364,9 +380,11 @@ private void addToLocationsMap(IProject project) { } private void addToLocationsMap(IResource link, IFileStore location) { - if (location != null && !link.isVirtual()) - if (locationsMap.add(location, link)) + if (location != null && !link.isVirtual()) { + if (locationsMap.add(location, link)) { nonDefaultResourceCount++; + } + } } /** @@ -375,8 +393,9 @@ private void addToLocationsMap(IResource link, IFileStore location) { private void buildAliasedProjectsSet() { aliasedProjects.clear(); //if there are no resources in non-default locations then there can't be any aliased projects - if (nonDefaultResourceCount <= 0) + if (nonDefaultResourceCount <= 0) { return; + } //for every resource that overlaps another, marked its project as aliased locationsMap.overLappingResourcesDo(aliasedProjects::add); } @@ -390,9 +409,11 @@ private void buildLocationsMap() { nonDefaultResourceCount = 0; //build table of IPath (file system location) -> IResource (project or linked resource) IProject[] projects = workspace.getRoot().getProjects(IContainer.INCLUDE_HIDDEN); - for (IProject project : projects) - if (project.isAccessible()) + for (IProject project : projects) { + if (project.isAccessible()) { addToLocationsMap(project); + } + } } /** @@ -423,14 +444,16 @@ private boolean checkDeletion(Project project, IFileStore location) throws CoreE */ public IResource[] computeAliases(final IResource resource, IFileStore location) { //nothing to do if we are or were in an alias-free workspace or project - if (hasNoAliases(resource)) + if (hasNoAliases(resource)) { return null; + } aliases.clear(); internalComputeAliases(resource, location); int size = aliases.size(); - if (size == 0) + if (size == 0) { return null; + } return aliases.toArray(new IResource[size]); } @@ -449,8 +472,9 @@ public IResource[] findResources(IFileStore location) { */ private void computeDeepAliases(IResource resource, IFileStore location) { //if the location is invalid then there won't be any aliases to update - if (location == null) + if (location == null) { return; + } //get the normal aliases (resources rooted in parent locations) internalComputeAliases(resource, location); //get all resources rooted below this resource's location @@ -463,8 +487,9 @@ private void computeDeepAliases(IResource resource, IFileStore location) { for (IResource member : members) { if (member.isLinked()) { IFileStore linkLocation = localManager.getStore(member); - if (linkLocation != null) + if (linkLocation != null) { locationsMap.matchingPrefixDo(linkLocation, aliases::add); + } } } } catch (CoreException e) { @@ -485,8 +510,9 @@ public void handleEvent(LifecycleEvent event) { case LifecycleEvent.PRE_LINK_CHANGE : case LifecycleEvent.PRE_LINK_DELETE : Resource link = (Resource) event.resource; - if (link.isLinked()) + if (link.isLinked()) { removeFromLocationsMap(link, link.getStore()); + } //fall through case LifecycleEvent.PRE_FILTER_ADD : case LifecycleEvent.PRE_FILTER_REMOVE : @@ -498,8 +524,9 @@ public void handleEvent(LifecycleEvent event) { break; case LifecycleEvent.PRE_LINK_MOVE : link = (Resource) event.resource; - if (link.isLinked()) + if (link.isLinked()) { removeFromLocationsMap(link, link.getStore()); + } changedLinks.add(event.newResource); break; } @@ -528,11 +555,13 @@ private boolean hasNoAliases(final IResource resource) { */ private void internalComputeAliases(IResource resource, IFileStore location) { IFileStore searchLocation = location; - if (searchLocation == null) + if (searchLocation == null) { searchLocation = ((Resource) resource).getStore(); + } //if the location is invalid then there won't be any aliases to update - if (searchLocation == null) + if (searchLocation == null) { return; + } suffix = IPath.EMPTY; FindAliasesDoit findAliases = new FindAliasesDoit(resource); @@ -549,9 +578,11 @@ private void internalComputeAliases(IResource resource, IFileStore location) { } private void removeFromLocationsMap(IResource link, IFileStore location) { - if (location != null) - if (locationsMap.remove(location, link)) + if (location != null) { + if (locationsMap.remove(location, link)) { nonDefaultResourceCount--; + } + } } @Override @@ -562,8 +593,9 @@ public void resourceChanged(IResourceChangeEvent event) { return; } final IResourceDelta delta = event.getDelta(); - if (delta == null) + if (delta == null) { return; + } //invalidate location map if there are added or removed projects. if (delta.getAffectedChildren(IResourceDelta.ADDED | IResourceDelta.REMOVED, IContainer.INCLUDE_HIDDEN).length > 0) { @@ -610,25 +642,30 @@ public void startup(IProgressMonitor monitor) { */ public void updateAliases(IResource resource, IFileStore location, int depth, IProgressMonitor monitor) throws CoreException { monitor = IProgressMonitor.nullSafe(monitor); - if (hasNoAliases(resource)) + if (hasNoAliases(resource)) { return; + } aliases.clear(); - if (depth == IResource.DEPTH_ZERO) + if (depth == IResource.DEPTH_ZERO) { internalComputeAliases(resource, location); - else + } else { computeDeepAliases(resource, location); - if (aliases.isEmpty()) + } + if (aliases.isEmpty()) { return; + } FileSystemResourceManager localManager = workspace.getFileSystemManager(); for (IResource alias : new ArrayList<>(aliases)) { monitor.subTask(NLS.bind(Messages.links_updatingDuplicate, alias.getFullPath())); if (alias.getType() == IResource.PROJECT) { - if (checkDeletion((Project) alias, location)) + if (checkDeletion((Project) alias, location)) { continue; //project did not require deletion, so fall through below and refresh it + } } - if (!((Resource) alias).isFiltered()) + if (!((Resource) alias).isFiltered()) { localManager.refresh(alias, IResource.DEPTH_INFINITE, false, null); + } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/BuildConfiguration.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/BuildConfiguration.java index 57ba43a74da..46399f468b6 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/BuildConfiguration.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/BuildConfiguration.java @@ -67,12 +67,15 @@ public IProject getProject() { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } BuildConfiguration other = (BuildConfiguration) obj; return Objects.equals(this.name, other.name) && Objects.equals(this.project, other.project); } @@ -89,23 +92,26 @@ public int hashCode() { @Override public String toString() { StringBuilder result = new StringBuilder(); - if (project != null) + if (project != null) { result.append(project.getName()); - else + } else { result.append("?"); //$NON-NLS-1$ + } result.append(";"); //$NON-NLS-1$ - if (name != null) + if (name != null) { result.append(" [").append(name).append(']'); //$NON-NLS-1$ - else + } else { result.append(" [active]"); //$NON-NLS-1$ + } return result.toString(); } @Override @SuppressWarnings("unchecked") public T getAdapter(Class adapter) { - if (adapter.isInstance(project)) + if (adapter.isInstance(project)) { return (T) project; + } return super.getAdapter(adapter); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/CharsetDeltaJob.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/CharsetDeltaJob.java index 73e99b65380..b9279515ed0 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/CharsetDeltaJob.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/CharsetDeltaJob.java @@ -93,12 +93,14 @@ public boolean belongsTo(Object family) { public void charsetPreferencesChanged(final IProject project) { // avoid reacting to changes made by ourselves - if (isDisabled()) + if (isDisabled()) { return; + } ResourceInfo projectInfo = ((Project) project).getResourceInfo(false, false); //nothing to do if project has already been deleted - if (projectInfo == null) + if (projectInfo == null) { return; + } final long projectId = projectInfo.getNodeId(); // ensure all resources under the affected project are // reported as having encoding changes @@ -107,11 +109,13 @@ public void charsetPreferencesChanged(final IProject project) { public IPath getRoot() { //make sure it is still the same project - it could have been deleted and recreated ResourceInfo currentInfo = ((Project) project).getResourceInfo(false, false); - if (currentInfo == null) + if (currentInfo == null) { return null; + } long currentId = currentInfo.getNodeId(); - if (currentId != projectId) + if (currentId != projectId) { return null; + } // visit the project subtree return project.getFullPath(); } @@ -146,8 +150,9 @@ public IPath getRoot() { @Override public boolean isAffected(ResourceInfo info, IPathRequestor requestor) { - if (info.getType() != IResource.FILE) + if (info.getType() != IResource.FILE) { return false; + } return event.getContentType().isAssociatedWith(requestor.requestName()); } @@ -166,11 +171,13 @@ private boolean isDisabled() { private void processNextEvent(final ICharsetListenerFilter filter, IProgressMonitor monitor) throws CoreException { IElementContentVisitor visitor = (tree, requestor, elementContents) -> { ResourceInfo info = (ResourceInfo) elementContents; - if (!filter.isAffected(info, requestor)) + if (!filter.isAffected(info, requestor)) { return true; + } info = workspace.getResourceInfo(requestor.requestPath(), false, true); - if (info == null) + if (info == null) { return false; + } info.incrementCharsetGenerationCount(); return true; }; @@ -186,8 +193,9 @@ private void processNextEvent(final ICharsetListenerFilter filter, IProgressMoni } catch (WrappedRuntimeException e) { throw (CoreException) e.getTargetException(); } - if (monitor.isCanceled()) + if (monitor.isCanceled()) { throw new OperationCanceledException(); + } } private ICharsetListenerFilter removeFromQueue() { @@ -207,8 +215,9 @@ public IStatus run(IProgressMonitor monitor) { workspace.beginOperation(true); ICharsetListenerFilter next; //if the system is shutting down, don't broadcast - while (systemBundle.getState() != Bundle.STOPPING && (next = removeFromQueue()) != null) + while (systemBundle.getState() != Bundle.STOPPING && (next = removeFromQueue()) != null) { processNextEvent(next, monitor); + } } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); return Status.CANCEL_STATUS; @@ -248,8 +257,9 @@ public void shutdown() { } IContentTypeManager contentTypeManager = Platform.getContentTypeManager(); //if the service is already gone there is nothing to do - if (contentTypeManager != null) + if (contentTypeManager != null) { contentTypeManager.removeContentTypeChangeListener(this); + } } public void startup() { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/CharsetManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/CharsetManager.java index 66a3fc9827c..6970c9eb720 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/CharsetManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/CharsetManager.java @@ -77,8 +77,9 @@ public boolean belongsTo(Object family) { } public void addChanges(Map newChanges) { - if (newChanges.isEmpty()) + if (newChanges.isEmpty()) { return; + } synchronized (asyncChanges) { asyncChanges.addAll(newChanges.entrySet()); asyncChanges.notify(); @@ -106,8 +107,9 @@ protected IStatus run(IProgressMonitor monitor) { while (!monitor.isCanceled() && ((next = getNextChange()) != null)) { //just exit if the system is shutting down or has been shut down //it is too late to change the workspace at this point anyway - if (systemBundle.getState() != Bundle.ACTIVE) + if (systemBundle.getState() != Bundle.ACTIVE) { return Status.OK_STATUS; + } IProject project = next.getKey(); try { if (project.isAccessible()) { @@ -201,15 +203,17 @@ private void processEntryChanges(IResourceDelta projectDelta, Map affectedResourcesMap = new HashMap<>(); try { // no regular preferences for this project - if (projectRegularPrefs == null) + if (projectRegularPrefs == null) { affectedResourcesMap.put(Boolean.FALSE, new String[0]); - else + } else { affectedResourcesMap.put(Boolean.FALSE, projectRegularPrefs.keys()); + } // no derived preferences for this project - if (projectDerivedPrefs == null) + if (projectDerivedPrefs == null) { affectedResourcesMap.put(Boolean.TRUE, new String[0]); - else + } else { affectedResourcesMap.put(Boolean.TRUE, projectDerivedPrefs.keys()); + } } catch (BackingStoreException e) { // problems with the project scope... we will miss the changes (but will log) String message = Messages.resources_readingEncoding; @@ -223,8 +227,9 @@ private void processEntryChanges(IResourceDelta projectDelta, Map projectsToSave = new HashMap<>(); - for (IResourceDelta projectDelta : projectDeltas) + for (IResourceDelta projectDelta : projectDeltas) { //nothing to do if a project has been added/removed/moved - if (projectDelta.getKind() == IResourceDelta.CHANGED && (projectDelta.getFlags() & IResourceDelta.OPEN) == 0) + if (projectDelta.getKind() == IResourceDelta.CHANGED && (projectDelta.getFlags() & IResourceDelta.OPEN) == 0) { processEntryChanges(projectDelta, projectsToSave); + } + } job.addChanges(projectsToSave); } } @@ -292,12 +302,14 @@ public CharsetManager(Workspace workspace) { void flushPreferences(Preferences projectPrefs, boolean shouldDisableCharsetDeltaJob) throws BackingStoreException { if (projectPrefs != null) { try { - if (shouldDisableCharsetDeltaJob) + if (shouldDisableCharsetDeltaJob) { charsetListener.setDisabled(true); + } projectPrefs.flush(); } finally { - if (shouldDisableCharsetDeltaJob) + if (shouldDisableCharsetDeltaJob) { charsetListener.setDisabled(false); + } } } } @@ -339,9 +351,10 @@ Preferences getPreferences(IProject project, boolean create, boolean isDerived) Preferences getPreferences(IProject project, boolean create, boolean isDerived, boolean isDerivedEncodingStoredSeparately) { boolean localIsDerived = isDerivedEncodingStoredSeparately ? isDerived : false; String qualifier = localIsDerived ? ProjectPreferences.PREFS_DERIVED_QUALIFIER : ProjectPreferences.PREFS_REGULAR_QUALIFIER; - if (create) + if (create) { // create all nodes down to the one we are interested in return new ProjectScope(project).getNode(qualifier).node(ResourcesPlugin.PREF_ENCODING); + } // be careful looking up for our node so not to create any nodes as side effect Preferences node = Platform.getPreferencesService().getRootNode().node(ProjectScope.SCOPE); try { @@ -349,14 +362,17 @@ Preferences getPreferences(IProject project, boolean create, boolean isDerived, // String path = project.getName() + IPath.SEPARATOR + ResourcesPlugin.PI_RESOURCES + IPath.SEPARATOR + ENCODING_PREF_NODE; // return node.nodeExists(path) ? node.node(path) : null; // for now, take the long way - if (!node.nodeExists(project.getName())) + if (!node.nodeExists(project.getName())) { return null; + } node = node.node(project.getName()); - if (!node.nodeExists(qualifier)) + if (!node.nodeExists(qualifier)) { return null; + } node = node.node(qualifier); - if (!node.nodeExists(ResourcesPlugin.PREF_ENCODING)) + if (!node.nodeExists(ResourcesPlugin.PREF_ENCODING)) { return null; + } return node.node(ResourcesPlugin.PREF_ENCODING); } catch (BackingStoreException e) { // nodeExists failed @@ -405,11 +421,13 @@ private boolean isDerivedEncodingStoredSeparately(IProject project) { // String path = project.getName() + IPath.SEPARATOR + ResourcesPlugin.PI_RESOURCES; // return node.nodeExists(path) ? node.node(path).getBoolean(ResourcesPlugin.PREF_SEPARATE_DERIVED_ENCODINGS, false) : false; // for now, take the long way - if (!node.nodeExists(project.getName())) + if (!node.nodeExists(project.getName())) { return ResourcesPlugin.DEFAULT_PREF_SEPARATE_DERIVED_ENCODINGS; + } node = node.node(project.getName()); - if (!node.nodeExists(ResourcesPlugin.PI_RESOURCES)) + if (!node.nodeExists(ResourcesPlugin.PI_RESOURCES)) { return ResourcesPlugin.DEFAULT_PREF_SEPARATE_DERIVED_ENCODINGS; + } node = node.node(ResourcesPlugin.PI_RESOURCES); return node.getBoolean(ResourcesPlugin.PREF_SEPARATE_DERIVED_ENCODINGS, ResourcesPlugin.DEFAULT_PREF_SEPARATE_DERIVED_ENCODINGS); } catch (BackingStoreException e) { @@ -423,8 +441,9 @@ private boolean isDerivedEncodingStoredSeparately(IProject project) { protected void mergeEncodingPreferences(IProject project) { Preferences projectRegularPrefs = null; Preferences projectDerivedPrefs = getPreferences(project, false, true, true); - if (projectDerivedPrefs == null) + if (projectDerivedPrefs == null) { return; + } try { boolean prefsChanged = false; String[] affectedResources; @@ -433,8 +452,9 @@ protected void mergeEncodingPreferences(IProject project) { String value = projectDerivedPrefs.get(path, null); projectDerivedPrefs.remove(path); // lazy creation of non-derived preferences - if (projectRegularPrefs == null) + if (projectRegularPrefs == null) { projectRegularPrefs = getPreferences(project, true, false, false); + } projectRegularPrefs.put(path, value); prefsChanged = true; } @@ -518,15 +538,17 @@ public void shutdown(IProgressMonitor monitor) { .removePreferenceChangeListener(preferenceChangeListener); workspace.removeResourceChangeListener(resourceChangeListener); - if (charsetListener != null) + if (charsetListener != null) { charsetListener.shutdown(); + } } protected void splitEncodingPreferences(IProject project) { Preferences projectRegularPrefs = getPreferences(project, false, false, false); Preferences projectDerivedPrefs = null; - if (projectRegularPrefs == null) + if (projectRegularPrefs == null) { return; + } try { boolean prefsChanged = false; String[] affectedResources; @@ -538,8 +560,9 @@ protected void splitEncodingPreferences(IProject project) { String value = projectRegularPrefs.get(path, null); projectRegularPrefs.remove(path); // lazy creation of derived preferences - if (projectDerivedPrefs == null) + if (projectDerivedPrefs == null) { projectDerivedPrefs = getPreferences(project, true, true, true); + } projectDerivedPrefs.put(path, value); prefsChanged = true; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ComputeProjectOrder.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ComputeProjectOrder.java index b4b55764ddd..c4bd424434e 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ComputeProjectOrder.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ComputeProjectOrder.java @@ -611,8 +611,9 @@ static VertexOrder filterVertexOrder(VertexOrder order, Predicate f boolean[] filterMatches = new boolean[order.vertexes.length]; for (int i = 0; i < order.vertexes.length; i++) { filterMatches[i] = filter.test(order.vertexes[i]); - if (filterMatches[i]) + if (filterMatches[i]) { filteredCount++; + } } // No vertexes match the filter, so return the order unmodified diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Container.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Container.java index c2e8ccf6267..1fd35e9f8ff 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Container.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Container.java @@ -36,12 +36,14 @@ protected Container(IPath path, Workspace container) { */ @Override public void convertToPhantom() throws CoreException { - if (isPhantom()) + if (isPhantom()) { return; + } super.convertToPhantom(); IResource[] members = members(IContainer.INCLUDE_PHANTOMS | IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS | IContainer.INCLUDE_HIDDEN); - for (IResource member : members) + for (IResource member : members) { ((Resource) member).convertToPhantom(); + } } @Override @@ -78,8 +80,9 @@ public IResourceFilterDescription createFilter(int type, FileInfoMatcherDescript } else { refreshLocal(DEPTH_INFINITE, Policy.subMonitorFor(monitor, Policy.opWork * 90 / 100)); } - } else + } else { monitor.worked(Policy.opWork * 90 / 100); + } } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; @@ -124,11 +127,13 @@ public IResource findMember(IPath childPath, boolean phantom) { @Override protected void fixupAfterMoveSource() throws CoreException { super.fixupAfterMoveSource(); - if (!synchronizing(getResourceInfo(true, false))) + if (!synchronizing(getResourceInfo(true, false))) { return; + } IResource[] members = members(IContainer.INCLUDE_PHANTOMS | IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS | IContainer.INCLUDE_HIDDEN); - for (IResource member : members) + for (IResource member : members) { ((Resource) member).fixupAfterMoveSource(); + } } protected IResource[] getChildren(int memberFlags) { @@ -139,17 +144,20 @@ protected IResource[] getChildren(int memberFlags) { //concurrency problem: the container has been deleted by another //thread during this call. Just return empty children set } - if (children == null || children.length == 0) + if (children == null || children.length == 0) { return ICoreConstants.EMPTY_RESOURCE_ARRAY; + } Resource[] result = new Resource[children.length]; int found = 0; for (IPath child : children) { ResourceInfo info = workspace.getResourceInfo(child, true, false); - if (info != null && isMember(info.getFlags(), memberFlags)) + if (info != null && isMember(info.getFlags(), memberFlags)) { result[found++] = workspace.newResource(child, info.getType()); + } } - if (found == result.length) + if (found == result.length) { return result; + } Resource[] trimmedResult = new Resource[found]; System.arraycopy(result, 0, trimmedResult, 0, found); return trimmedResult; @@ -180,14 +188,17 @@ public IResourceFilterDescription[] getFilters() throws CoreException { public boolean hasFilters() { IProject project = getProject(); - if (project == null) + if (project == null) { return false; + } ProjectDescription desc = ((Project) project).internalGetDescription(); - if (desc == null) + if (desc == null) { return false; + } LinkedList filters = desc.getFilter(getProjectRelativePath()); - if ((filters != null) && (filters.size() > 0)) + if ((filters != null) && (filters.size() > 0)) { return true; + } return false; } @@ -208,12 +219,15 @@ public IFolder getFolder(IPath childPath) { @Deprecated @Override public boolean isLocal(int flags, int depth) { - if (!super.isLocal(flags, depth)) + if (!super.isLocal(flags, depth)) { return false; - if (depth == DEPTH_ZERO) + } + if (depth == DEPTH_ZERO) { return true; - if (depth == DEPTH_ONE) + } + if (depth == DEPTH_ONE) { depth = DEPTH_ZERO; + } // get the children via the workspace since we know that this // resource exists (it is local). IResource[] children = getChildren(IResource.NONE); @@ -243,8 +257,9 @@ public IResource[] members(int memberFlags) throws CoreException { ResourceInfo info = getResourceInfo(phantom, false); checkAccessible(getFlags(info)); //if children are currently unknown, ask for immediate refresh - if (info.isSet(ICoreConstants.M_CHILDREN_UNKNOWN)) + if (info.isSet(ICoreConstants.M_CHILDREN_UNKNOWN)) { workspace.refreshManager.refresh(this); + } return getChildren(memberFlags); } @@ -276,8 +291,9 @@ public void removeFilter(IResourceFilterDescription filterDescription, int updat } else { refreshLocal(DEPTH_INFINITE, Policy.subMonitorFor(monitor, Policy.opWork * 90 / 100)); } - } else + } else { monitor.worked(Policy.opWork * 90 / 100); + } } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; @@ -349,8 +365,9 @@ public void setDefaultCharset(String newCharset, IProgressMonitor monitor) throw @Override public boolean visitElement(ElementTree tree, IPathRequestor requestor, Object elementContents) { - if (elementContents == null) + if (elementContents == null) { return false; + } IPath nodePath = requestor.requestPath(); // we will always generate an event at least for the root of the sub tree // (skip visiting the root because we already have set the charset above and @@ -358,17 +375,20 @@ public boolean visitElement(ElementTree tree, IPathRequestor requestor, Object e if (!visitedRoot) { visitedRoot = true; ResourceInfo info = workspace.getResourceInfo(nodePath, false, true); - if (info == null) + if (info == null) { return false; + } info.incrementCharsetGenerationCount(); return true; } // does it already have an encoding explicitly set? - if (workspace.getCharsetManager().getCharsetFor(nodePath, false) != null) + if (workspace.getCharsetManager().getCharsetFor(nodePath, false) != null) { return false; + } ResourceInfo info = workspace.getResourceInfo(nodePath, false, true); - if (info == null) + if (info == null) { return false; + } info.incrementCharsetGenerationCount(); return true; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ContentDescriptionManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ContentDescriptionManager.java index 9e4a155df5e..97a1111d227 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ContentDescriptionManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ContentDescriptionManager.java @@ -99,8 +99,9 @@ public boolean belongsTo(Object family) { @Override public IStatus runInWorkspace(final IProgressMonitor monitor) { - if (monitor.isCanceled()) + if (monitor.isCanceled()) { return Status.CANCEL_STATUS; + } try { monitor.beginTask("", Policy.opWork); //$NON-NLS-1$ //note that even though we are running in a workspace job, we @@ -111,8 +112,9 @@ public IStatus runInWorkspace(final IProgressMonitor monitor) { workspace.beginOperation(true); //don't do anything if the system is shutting down or has been shut down //it is too late to change the workspace at this point anyway - if (systemBundle.getState() != Bundle.STOPPING) + if (systemBundle.getState() != Bundle.STOPPING) { doFlushCache(monitor, getPathsToFlush()); + } } finally { workspace.endOperation(rule, false); } @@ -144,15 +146,18 @@ private Set getPathsToFlush() { * @param project project to flush, or null for a full flush */ void flush(IProject project) { - if (Policy.DEBUG_CONTENT_TYPE_CACHE) + if (Policy.DEBUG_CONTENT_TYPE_CACHE) { Policy.debug("Scheduling flushing of content type cache for " //$NON-NLS-1$ + (project == null ? IPath.ROOT : project.getFullPath())); + } synchronized (toFlush) { - if (!fullFlush) - if (project == null) + if (!fullFlush) { + if (project == null) { fullFlush = true; - else + } else { toFlush.add(project.getFullPath()); + } + } } schedule(1000); } @@ -173,23 +178,27 @@ static class LazyFileInputStream extends InputStream { @Override public int available() throws IOException { - if (actual == null) + if (actual == null) { return 0; + } return actual.available(); } @Override public void close() throws IOException { - if (actual == null) + if (actual == null) { return; + } actual.close(); } private void ensureOpened() throws IOException { - if (actual != null) + if (actual != null) { return; - if (target == null) + } + if (target == null) { throw new FileNotFoundException(); + } try { actual = target.openInputStream(EFS.NONE, null); } catch (CoreException e) { @@ -255,16 +264,18 @@ public ContentDescriptionManager(Workspace workspace) { */ @Override public void contentTypeChanged(ContentTypeChangeEvent event) { - if (Policy.DEBUG_CONTENT_TYPE) + if (Policy.DEBUG_CONTENT_TYPE) { Policy.debug("Content type settings changed for " + event.getContentType()); //$NON-NLS-1$ + } invalidateCache(true, null); } synchronized void doFlushCache(final IProgressMonitor monitor, Set toClean) throws CoreException { // nothing to be done if no information cached if (getCacheState() != INVALID_CACHE && getCacheState() != ABOUT_TO_FLUSH) { - if (Policy.DEBUG_CONTENT_TYPE_CACHE) + if (Policy.DEBUG_CONTENT_TYPE_CACHE) { Policy.debug("Content type cache flush not performed"); //$NON-NLS-1$ + } return; } try { @@ -296,26 +307,32 @@ synchronized void doFlushCache(final IProgressMonitor monitor, Set toClea */ private void clearContentFlags(IPath root, final IProgressMonitor monitor) { long flushStart = System.currentTimeMillis(); - if (Policy.DEBUG_CONTENT_TYPE_CACHE) + if (Policy.DEBUG_CONTENT_TYPE_CACHE) { Policy.debug("Flushing content type cache for " + root); //$NON-NLS-1$ + } // discard content type related flags for all files in the tree IElementContentVisitor visitor = (tree, requestor, elementContents) -> { - if (monitor.isCanceled()) + if (monitor.isCanceled()) { throw new OperationCanceledException(); - if (elementContents == null) + } + if (elementContents == null) { return false; + } ResourceInfo info = (ResourceInfo) elementContents; - if (info.getType() != IResource.FILE) + if (info.getType() != IResource.FILE) { return true; + } info = workspace.getResourceInfo(requestor.requestPath(), false, true); - if (info == null) + if (info == null) { return false; + } info.clear(ICoreConstants.M_CONTENT_CACHE); return true; }; new ElementTreeIterator(workspace.getElementTree(), root).iterate(visitor); - if (Policy.DEBUG_CONTENT_TYPE_CACHE) + if (Policy.DEBUG_CONTENT_TYPE_CACHE) { Policy.debug("Content type cache for " + root + " flushed in " + (System.currentTimeMillis() - flushStart) + " ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } } /** Public so tests can examine it. */ @@ -355,9 +372,10 @@ public IContentTypeMatcher getContentTypeMatcher(Project project) throws CoreExc * @return IContentDescription for the file */ public IContentDescription getDescriptionFor(File file, ResourceInfo info, boolean inSync) throws CoreException { - if (ProjectContentTypes.usesContentTypePreferences(file.getFullPath().segment(0))) + if (ProjectContentTypes.usesContentTypePreferences(file.getFullPath().segment(0))) { // caching for project containing project specific settings is not supported return readDescription(file); + } if (getCacheState() == INVALID_CACHE) { // discard the cache, so it can be used before the flush job starts setCacheState(ABOUT_TO_FLUSH); @@ -368,17 +386,19 @@ public IContentDescription getDescriptionFor(File file, ResourceInfo info, boole if (inSync && getCacheState() != ABOUT_TO_FLUSH) { // first look for the flags in the resource info to avoid looking in the cache // don't need to copy the info because the modified bits are not in the deltas - if ((info == null) || info.isSet(ICoreConstants.M_NO_CONTENT_DESCRIPTION)) + if ((info == null) || info.isSet(ICoreConstants.M_NO_CONTENT_DESCRIPTION)) { // presumably, this file has no known content type return null; + } if (info.isSet(ICoreConstants.M_DEFAULT_CONTENT_DESCRIPTION)) { // this file supposedly has a default content description for an "obvious" content type IContentTypeManager contentTypeManager = Platform.getContentTypeManager(); // try to find the obvious content type matching its name IContentType type = contentTypeManager.findContentTypeFor(file.getName()); - if (type != null) + if (type != null) { // we found it, we are done return type.getDefaultDescription(); + } // for some reason, there was no content type for this file name // fix this and keep going info.clear(ICoreConstants.M_CONTENT_CACHE); @@ -388,9 +408,10 @@ public IContentDescription getDescriptionFor(File file, ResourceInfo info, boole // tries to get a description from the cache synchronized (this) { Entry entry = cache.getEntry(file.getFullPath()); - if (entry != null && entry.getTimestamp() == getTimestamp(info)) + if (entry != null && entry.getTimestamp() == getTimestamp(info)) { // there was a description in the cache, and it was up to date return entry.getCached(); + } } } @@ -401,9 +422,10 @@ public IContentDescription getDescriptionFor(File file, ResourceInfo info, boole synchronized (this) { // tries to get a description from the cache Entry entry = cache.getEntry(file.getFullPath()); - if (entry != null && inSync && entry.getTimestamp() == getTimestamp(info)) + if (entry != null && inSync && entry.getTimestamp() == getTimestamp(info)) { // there was a description in the cache, and it was up to date return entry.getCached(); + } if (getCacheState() != ABOUT_TO_FLUSH) { // we are going to add an entry to the cache or update the resource info - remember that @@ -445,17 +467,19 @@ private long getTimestamp(ResourceInfo info) { * @see #doFlushCache(IProgressMonitor, Set) */ public synchronized void invalidateCache(boolean flush, IProject project) { - if (getCacheState() == EMPTY_CACHE) + if (getCacheState() == EMPTY_CACHE) { // cache has not been touched, nothing to do return; + } // mark the cache as invalid try { setCacheState(INVALID_CACHE); } catch (CoreException e) { Policy.log(e.getStatus()); } - if (Policy.DEBUG_CONTENT_TYPE_CACHE) + if (Policy.DEBUG_CONTENT_TYPE_CACHE) { Policy.debug("Invalidated cache for " + (project == null ? IPath.ROOT : project.getFullPath())); //$NON-NLS-1$ + } if (flush) { try { // discard the cache, so it can be used before the flush job starts @@ -505,8 +529,9 @@ private String getCachedPlatformState() { * Tries to obtain a content description for the given file. */ private IContentDescription readDescription(File file) throws CoreException { - if (Policy.DEBUG_CONTENT_TYPE) + if (Policy.DEBUG_CONTENT_TYPE) { Policy.debug("reading contents of " + file); //$NON-NLS-1$ + } // tries to obtain a description for this file contents try ( InputStream contents = new LazyFileInputStream(file.getStore()); @@ -528,8 +553,9 @@ private IContentDescription readDescription(File file) throws CoreException { @Override public void registryChanged(IRegistryChangeEvent event) { // no changes related to the content type registry - if (event.getExtensionDeltas(Platform.PI_RUNTIME, PT_CONTENTTYPES).length == 0) + if (event.getExtensionDeltas(Platform.PI_RUNTIME, PT_CONTENTTYPES).length == 0) { return; + } invalidateCache(true, null); } @@ -551,8 +577,9 @@ public void handleEvent(LifecycleEvent event) { } synchronized void setCacheState(byte newCacheState) throws CoreException { - if (cacheState == newCacheState) + if (cacheState == newCacheState) { return; + } workspace.getRoot().setPersistentProperty(CACHE_STATE, Byte.toString(newCacheState)); cacheState = newCacheState; } @@ -564,11 +591,13 @@ public void shutdown(IProgressMonitor monitor) throws CoreException { } IContentTypeManager contentTypeManager = Platform.getContentTypeManager(); //tolerate missing services during shutdown because they might be already gone - if (contentTypeManager != null) + if (contentTypeManager != null) { contentTypeManager.removeContentTypeChangeListener(this); + } IExtensionRegistry registry = Platform.getExtensionRegistry(); - if (registry != null) + if (registry != null) { registry.removeRegistryChangeListener(this); + } cache.clear(); flushJob.cancel(); flushJob = null; @@ -579,9 +608,10 @@ public void shutdown(IProgressMonitor monitor) throws CoreException { public void startup(IProgressMonitor monitor) throws CoreException { projectContentTypes = new ProjectContentTypes(workspace); getCacheState(); - if (cacheState == FLUSHING_CACHE || cacheState == ABOUT_TO_FLUSH) + if (cacheState == FLUSHING_CACHE || cacheState == ABOUT_TO_FLUSH) { // in case we died before completing the last flushing setCacheState(INVALID_CACHE); + } flushJob = new FlushJob(workspace); // the cache is stale (plug-ins that might be contributing content types were added/removed) if (!Objects.equals(getCachedPlatformState(), getCurrentPlatformState())) { @@ -596,8 +626,9 @@ public void startup(IProgressMonitor monitor) throws CoreException { } public void projectPreferencesChanged(IProject project) { - if (Policy.DEBUG_CONTENT_TYPE) + if (Policy.DEBUG_CONTENT_TYPE) { Policy.debug("Project preferences changed for " + project); //$NON-NLS-1$ + } projectContentTypes.contentTypePreferencesChanged(project); } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/DelayedSnapshotJob.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/DelayedSnapshotJob.java index 80f06f21005..dae314356ab 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/DelayedSnapshotJob.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/DelayedSnapshotJob.java @@ -43,8 +43,9 @@ public DelayedSnapshotJob(SaveManager manager, Workspace workspace) { @Override public IStatus run(IProgressMonitor monitor) { - if (monitor.isCanceled()) + if (monitor.isCanceled()) { return Status.CANCEL_STATUS; + } if (!workspace.isOpen()) { return Status.OK_STATUS; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/File.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/File.java index 6ca0f25e598..54a72e30207 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/File.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/File.java @@ -71,8 +71,9 @@ public void appendContents(InputStream content, int updateFlags, IProgressMonito SubMonitor subMonitor = SubMonitor.convert(monitor, message, 100); try (content) { Assert.isNotNull(content, "Content cannot be null."); //$NON-NLS-1$ - if (workspace.shouldValidate) + if (workspace.shouldValidate) { workspace.validateSave(this); + } final ISchedulingRule rule = workspace.getRuleFactory().modifyRule(this); SubMonitor newChild = subMonitor.newChild(1); try { @@ -251,8 +252,9 @@ IFileInfo create(int updateFlags, IProgressMonitor subMonitor, IFileStore store) private void setLocal(boolean local) throws CoreException { internalSetLocal(local, DEPTH_ZERO); - if (!local) + if (!local) { getResourceInfo(true, true).clearModificationStamp(); + } } @Override @@ -265,8 +267,9 @@ public String getCharset(boolean checkImplicit) throws CoreException { // non-existing resources default to parent's charset ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); - if (!exists(flags, false)) + if (!exists(flags, false)) { return checkImplicit ? workspace.getCharsetManager().getCharsetFor(getFullPath().removeLastSegments(1), true) : null; + } checkLocal(flags, DEPTH_ZERO); try { return internalGetCharset(checkImplicit, info); @@ -283,11 +286,13 @@ public String getCharsetFor(Reader contents) throws CoreException { String charset; ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); - if (exists(flags, true)) + if (exists(flags, true)) { // the file exists, look for user setting - if ((charset = workspace.getCharsetManager().getCharsetFor(getFullPath(), false)) != null) + if ((charset = workspace.getCharsetManager().getCharsetFor(getFullPath(), false)) != null) { // if there is a file-specific user setting, use it return charset; + } + } // tries to obtain a description from the contents provided IContentDescription description; try { @@ -298,10 +303,12 @@ public String getCharsetFor(Reader contents) throws CoreException { String message = NLS.bind(Messages.resources_errorContentDescription, getFullPath()); throw new ResourceException(IResourceStatus.FAILED_DESCRIBING_CONTENTS, getFullPath(), message, e); } - if (description != null) - if ((charset = description.getCharset()) != null) + if (description != null) { + if ((charset = description.getCharset()) != null) { // the description contained charset info, we are done return charset; + } + } // could not find out the encoding based on the contents... default to parent's return workspace.getCharsetManager().getCharsetFor(getFullPath().removeLastSegments(1), true); } @@ -309,14 +316,16 @@ public String getCharsetFor(Reader contents) throws CoreException { private String internalGetCharset(boolean checkImplicit, ResourceInfo info) throws CoreException { // if there is a file-specific user setting, use it String charset = workspace.getCharsetManager().getCharsetFor(getFullPath(), false); - if (charset != null || !checkImplicit) + if (charset != null || !checkImplicit) { return charset; + } // tries to obtain a description for the file contents IContentDescription description = workspace.getContentDescriptionManager().getDescriptionFor(this, info, true); if (description != null) { String contentCharset = description.getCharset(); - if (contentCharset != null) + if (contentCharset != null) { return contentCharset; + } } // could not find out the encoding based on the contents... default to parent's return workspace.getCharsetManager().getCharsetFor(getFullPath().removeLastSegments(1), true); @@ -384,8 +393,9 @@ public int getType() { } protected void internalSetContents(InputStream content, IFileInfo fileInfo, int updateFlags, boolean append, IProgressMonitor monitor) throws CoreException { - if (content == null) + if (content == null) { content = new ByteArrayInputStream(new byte[0]); + } getLocalManager().write(this, content, fileInfo, updateFlags, append, monitor); updateMetadataFiles(); workspace.getAliasManager().updateAliases(this, getStore(), IResource.DEPTH_ZERO, monitor); @@ -393,8 +403,9 @@ protected void internalSetContents(InputStream content, IFileInfo fileInfo, int protected void internalSetContents(byte[] content, IFileInfo fileInfo, int updateFlags, boolean append, IProgressMonitor monitor) throws CoreException { - if (content == null) + if (content == null) { content = new byte[0]; + } getLocalManager().write(this, content, fileInfo, updateFlags, append, monitor); updateMetadataFiles(); workspace.getAliasManager().updateAliases(this, getStore(), IResource.DEPTH_ZERO, monitor); @@ -460,8 +471,9 @@ private static void writeSingle(int updateFlags, boolean append, IProgressMonito */ @Override public void refreshLocal(int depth, IProgressMonitor monitor) throws CoreException { - if (!getLocalManager().fastIsSynchronized(this)) + if (!getLocalManager().fastIsSynchronized(this)) { super.refreshLocal(IResource.DEPTH_ZERO, monitor); + } } @Override @@ -474,8 +486,9 @@ public void setContents(InputStream content, int updateFlags, IProgressMonitor m String message = NLS.bind(Messages.resources_settingContents, getFullPath()); SubMonitor subMonitor = SubMonitor.convert(monitor, message, 100); try (content) { - if (workspace.shouldValidate) + if (workspace.shouldValidate) { workspace.validateSave(this); + } final ISchedulingRule rule = workspace.getRuleFactory().modifyRule(this); SubMonitor newChild = subMonitor.newChild(1); try { @@ -506,8 +519,9 @@ public void setContents(byte[] content, int updateFlags, IProgressMonitor monito String message = NLS.bind(Messages.resources_settingContents, getFullPath()); SubMonitor subMonitor = SubMonitor.convert(monitor, message, 100); try { - if (workspace.shouldValidate) + if (workspace.shouldValidate) { workspace.validateSave(this); + } final ISchedulingRule rule = workspace.getRuleFactory().modifyRule(this); SubMonitor newChild = subMonitor.newChild(1); try { @@ -539,8 +553,9 @@ public long setLocalTimeStamp(long value) throws CoreException { if (path.segmentCount() == 2 && path.segment(1).equals(IProjectDescription.DESCRIPTION_FILE_NAME)) { //handle concurrent project deletion ResourceInfo projectInfo = ((Project) getProject()).getResourceInfo(false, false); - if (projectInfo != null) + if (projectInfo != null) { getLocalManager().updateLocalSync(projectInfo, result); + } } return result; } @@ -630,13 +645,16 @@ public String getLineSeparator(boolean checkParent) throws CoreException { // reflect the average length of the first Line: InputStream input = new BufferedInputStream(getContents(), 128);) { int c = input.read(); - while (c != -1 && c != '\r' && c != '\n') + while (c != -1 && c != '\r' && c != '\n') { c = input.read(); - if (c == '\n') + } + if (c == '\n') { return "\n"; //$NON-NLS-1$ + } if (c == '\r') { - if (input.read() == '\n') + if (input.read() == '\n') { return "\r\n"; //$NON-NLS-1$ + } return "\r"; //$NON-NLS-1$ } } catch (CoreException core) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FileState.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FileState.java index eab65678706..385d1811665 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FileState.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FileState.java @@ -47,8 +47,9 @@ public boolean exists() { public String getCharset() throws CoreException { // if there is an existing file at this state's path, use the encoding of that file IResource file = workspace.getRoot().findMember(fullPath); - if (file != null && file.getType() == IResource.FILE) + if (file != null && file.getType() == IResource.FILE) { return ((IFile) file).getCharset(); + } // tries to obtain a description for the file contents IContentTypeManager contentTypeManager = Platform.getContentTypeManager(); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Filter.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Filter.java index 837afce5bbb..594af236afd 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Filter.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Filter.java @@ -60,8 +60,9 @@ public Filter(IProject project, FilterDescription description) { public boolean match(IContainer parent, IFileInfo fileInfo) throws CoreException { if (provider == null) { IFilterMatcherDescriptor filterDescriptor = project.getWorkspace().getFilterMatcherDescriptor(getId()); - if (filterDescriptor != null) + if (filterDescriptor != null) { provider = ((FilterDescriptor) filterDescriptor).createFilter(); + } if (provider == null) { String message = NLS.bind(Messages.filters_missingFilterType, getId()); Policy.log(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, Platform.PLUGIN_ERROR, message, new Error())); @@ -76,15 +77,17 @@ public boolean match(IContainer parent, IFileInfo fileInfo) throws CoreException provider = null; } } - if (provider != null) + if (provider != null) { return provider.matches(parent, fileInfo); + } return false; } public boolean isFirst() { IFilterMatcherDescriptor descriptor = project.getWorkspace().getFilterMatcherDescriptor(getId()); - if (descriptor != null) + if (descriptor != null) { return descriptor.isFirstOrdering(); + } return false; } @@ -105,8 +108,9 @@ public boolean isIncludeOnly() { } public boolean appliesTo(IFileInfo info) { - if (info.isDirectory()) + if (info.isDirectory()) { return (getType() & IResourceFilterDescription.FOLDERS) != 0; + } return (getType() & IResourceFilterDescription.FILES) != 0; } @@ -133,8 +137,9 @@ public static IFileInfo[] filterIncludes(IProject project, LinkedList fi } } } - if (!filtersWereApplicable) + if (!filtersWereApplicable) { result[outputIndex++] = info; + } } if (outputIndex != result.length) { IFileInfo[] tmp = new IFileInfo[outputIndex]; @@ -163,8 +168,9 @@ public static IFileInfo[] filterExcludes(IProject project, LinkedList fi } } } - if (!shouldBeExcluded) + if (!shouldBeExcluded) { result[outputIndex++] = info; + } } if (outputIndex != result.length) { IFileInfo[] tmp = new IFileInfo[outputIndex]; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterDescription.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterDescription.java index 84015a252a5..3ed32856ea1 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterDescription.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterDescription.java @@ -106,15 +106,19 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } FilterDescription other = (FilterDescription) obj; - if (id != other.id) + if (id != other.id) { return false; + } return true; } @@ -127,12 +131,14 @@ public int compareTo(FilterDescription that) { IPath path2 = that.getResource().getProjectRelativePath(); int count1 = path1.segmentCount(); int compare = count1 - path2.segmentCount(); - if (compare != 0) + if (compare != 0) { return compare; + } for (int i = 0; i < count1; i++) { compare = path1.segment(i).compareTo(path2.segment(i)); - if (compare != 0) + if (compare != 0) { return compare; + } } return 0; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterDescriptor.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterDescriptor.java index 558a8dd5b68..5b29e847fe4 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterDescriptor.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterDescriptor.java @@ -36,12 +36,14 @@ public FilterDescriptor(IConfigurationElement element, boolean instantiateFactor name = element.getAttribute("name"); //$NON-NLS-1$ description = element.getAttribute("description"); //$NON-NLS-1$ argumentType = element.getAttribute("argumentType"); //$NON-NLS-1$ - if (argumentType == null) + if (argumentType == null) { argumentType = IFilterMatcherDescriptor.ARGUMENT_TYPE_NONE; + } this.element = element; String ordering = element.getAttribute("ordering"); //$NON-NLS-1$ - if (ordering != null) + if (ordering != null) { isFirst = ordering.equals("first"); //$NON-NLS-1$ + } } @Override diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterTypeManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterTypeManager.java index 5df6ce7c706..ddeec260be6 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterTypeManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/FilterTypeManager.java @@ -42,8 +42,9 @@ public FilterTypeManager() { RegistryFactory.getRegistry().addListener(new IRegistryEventListener() { @Override public void added(IExtension[] extensions) { - for (IExtension extension : extensions) + for (IExtension extension : extensions) { processExtension(extension); + } } @Override @@ -53,8 +54,9 @@ public void added(IExtensionPoint[] extensionPoints) { @Override public void removed(IExtension[] extensions) { - for (IExtension extension : extensions) + for (IExtension extension : extensions) { processRemovedExtension(extension); + } } @Override diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java index 27c2ed1b28e..d6fb7271f75 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Folder.java @@ -137,8 +137,9 @@ public void create(boolean force, boolean local, IProgressMonitor monitor) throw public void ensureExists(IProgressMonitor monitor) throws CoreException { ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); - if (exists(flags, true)) + if (exists(flags, true)) { return; + } if (exists(flags, false)) { String message = NLS.bind(Messages.resources_folderOverFile, getFullPath()); throw new ResourceException(IResourceStatus.RESOURCE_WRONG_TYPE, getFullPath(), message, null); @@ -147,19 +148,22 @@ public void ensureExists(IProgressMonitor monitor) throws CoreException { if (parent.getType() == PROJECT) { info = parent.getResourceInfo(false, false); parent.checkExists(getFlags(info), true); - } else + } else { ((Folder) parent).ensureExists(monitor); - if (getType() == FOLDER && isUnderVirtual()) + } + if (getType() == FOLDER && isUnderVirtual()) { create(IResource.VIRTUAL | IResource.FORCE, true, monitor); - else + } else { internalCreate(IResource.FORCE, true, monitor); + } } @Override public String getDefaultCharset(boolean checkImplicit) { // non-existing resources default to parent's charset - if (!exists()) + if (!exists()) { return checkImplicit ? workspace.getCharsetManager().getCharsetFor(getFullPath().removeLastSegments(1), true) : null; + } return workspace.getCharsetManager().getCharsetFor(getFullPath(), checkImplicit); } @@ -185,8 +189,9 @@ public void internalCreate(int updateFlags, boolean local, IProgressMonitor moni } } internalSetLocal(local, DEPTH_ZERO); - if (!local) + if (!local) { getResourceInfo(true, true).clearModificationStamp(); + } } finally { monitor.done(); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/InternalWorkspaceJob.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/InternalWorkspaceJob.java index 53a12e84eea..3bb4e75c076 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/InternalWorkspaceJob.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/InternalWorkspaceJob.java @@ -45,8 +45,9 @@ public final IStatus run(IProgressMonitor monitor) { workManager.operationCanceled(); return Status.CANCEL_STATUS; } finally { - if (depth >= 0) + if (depth >= 0) { workManager.endUnprotected(depth); + } workspace.endOperation(null, false); } } catch (CoreException e) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LinkDescription.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LinkDescription.java index 428b280231b..9f68d5e61ae 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LinkDescription.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LinkDescription.java @@ -67,8 +67,9 @@ public boolean equals(Object o) { if (o == null) { return false; } - if (o.getClass() != this.getClass()) + if (o.getClass() != this.getClass()) { return false; + } LinkDescription other = (LinkDescription) o; return localLocation.equals(other.localLocation) && path.equals(other.path) && type == other.type; } @@ -121,12 +122,14 @@ public int compareTo(LinkDescription that) { IPath path2 = that.getProjectRelativePath(); int count1 = path1.segmentCount(); int compare = count1 - path2.segmentCount(); - if (compare != 0) + if (compare != 0) { return compare; + } for (int i = 0; i < count1; i++) { compare = path1.segment(i).compareTo(path2.segment(i)); - if (compare != 0) + if (compare != 0) { return compare; + } } return 0; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LocalMetaArea.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LocalMetaArea.java index 7ea32c18c11..ba4175e2f88 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LocalMetaArea.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LocalMetaArea.java @@ -185,8 +185,9 @@ public IPath getSafeTableLocationFor(String pluginId) { IPath prefix = metaAreaLocation.append(F_SAFE_TABLE); // if the plugin is the resources plugin, we return the master table // location - if (pluginId.equals(ResourcesPlugin.PI_RESOURCES)) + if (pluginId.equals(ResourcesPlugin.PI_RESOURCES)) { return prefix.append(pluginId); // master table + } int saveNumber = getWorkspace().getSaveManager().getSaveNumber(pluginId); return prefix.append(pluginId + "." + saveNumber); //$NON-NLS-1$ } @@ -201,8 +202,9 @@ public IPath getSnapshotLocationFor(IResource resource) { Assert.isLegal(resource.getType() == IResource.ROOT); IPath key = resource.getFullPath().append(F_TREE); String sequenceNumber = getWorkspace().getSaveManager().getMasterTable().getProperty(key.toString()); - if (sequenceNumber == null) + if (sequenceNumber == null) { sequenceNumber = "0"; //$NON-NLS-1$ + } return metaAreaLocation.append(sequenceNumber + F_SNAP); } @@ -245,8 +247,9 @@ public IPath getSyncInfoSnapshotLocationFor(IResource resource) { public IPath getTreeLocationFor(IResource target, boolean updateSequenceNumber) { IPath key = target.getFullPath().append(F_TREE); String sequenceNumber = getWorkspace().getSaveManager().getMasterTable().getProperty(key.toString()); - if (sequenceNumber == null) + if (sequenceNumber == null) { sequenceNumber = "0"; //$NON-NLS-1$ + } if (updateSequenceNumber) { int n = Integer.parseInt(sequenceNumber) + 1; n = n < 0 ? 1 : n; @@ -282,8 +285,9 @@ public boolean hasSavedProjects() { * resource with the given path is stored. */ public IPath locationFor(IPath resourcePath) { - if (IPath.ROOT.equals(resourcePath)) + if (IPath.ROOT.equals(resourcePath)) { return metaAreaLocation.append(F_ROOT); + } return projectMetaLocation.append(resourcePath.segment(0)); } @@ -292,8 +296,9 @@ public IPath locationFor(IPath resourcePath) { * given resource is stored. */ public IPath locationFor(IResource resource) { - if (resource.getType() == IResource.ROOT) + if (resource.getType() == IResource.ROOT) { return metaAreaLocation.append(F_ROOT); + } return projectMetaLocation.append(resource.getProject().getName()); } @@ -304,8 +309,9 @@ public IPath locationFor(IResource resource) { */ public ProjectDescription readOldDescription(IProject project) throws CoreException { IPath path = getOldDescriptionLocationFor(project); - if (!path.toFile().exists()) + if (!path.toFile().exists()) { return null; + } IPath tempPath = getBackupLocationFor(path); ProjectDescription description = null; try { @@ -354,8 +360,9 @@ public void readPrivateDescription(IProject target, ProjectDescription descripti if (!file.exists()) { locationFile = getBackupLocationFor(locationFile); file = locationFile.toFile(); - if (!file.exists()) + if (!file.exists()) { return; + } } try (DataInputStream dataIn = new DataInputStream(new SafeChunkyInputStream(file, 500))) { try { @@ -363,10 +370,11 @@ public void readPrivateDescription(IProject target, ProjectDescription descripti if (location.length() > 0) { //location format < 3.2 was a local file system OS path //location format >= 3.2 is: URI_PREFIX + uri.toString() - if (location.startsWith(URI_PREFIX)) + if (location.startsWith(URI_PREFIX)) { description.setLocationURI(URI.create(location.substring(URI_PREFIX.length()))); - else + } else { description.setLocationURI(URIUtil.toURI(IPath.fromOSString(location))); + } } } catch (Exception e) { //don't allow failure to read the location to propagate @@ -377,18 +385,21 @@ public void readPrivateDescription(IProject target, ProjectDescription descripti int numRefs = dataIn.readInt(); IProject[] references = new IProject[numRefs]; IWorkspaceRoot root = getWorkspace().getRoot(); - for (int i = 0; i < numRefs; i++) + for (int i = 0; i < numRefs; i++) { references[i] = root.getProject(dataIn.readUTF()); + } description.setDynamicReferences(references); // Since 3.7 - Build Configurations String[] configs = new String[dataIn.readInt()]; - for (int i = 0; i < configs.length; i++) + for (int i = 0; i < configs.length; i++) { configs[i] = dataIn.readUTF(); - if (configs.length > 0) + } + if (configs.length > 0) { // In the future we may decide this is better stored in the // .project, so only set if configs.length > 0 description.setBuildConfigs(configs); + } // Active configuration name description.setActiveBuildConfig(dataIn.readUTF()); // Build configuration references? @@ -400,10 +411,11 @@ public void readPrivateDescription(IProject target, ProjectDescription descripti IBuildConfiguration[] refs = new IBuildConfiguration[numRefs]; for (int j = 0; j < numRefs; j++) { String projName = dataIn.readUTF(); - if (dataIn.readBoolean()) + if (dataIn.readBoolean()) { refs[j] = new BuildConfiguration(root.getProject(projName), dataIn.readUTF()); - else + } else { refs[j] = new BuildConfiguration(root.getProject(projName), null); + } } m.put(configName, refs); } @@ -426,23 +438,27 @@ public void writePrivateDescription(IProject target) throws CoreException { Workspace.clear(file); //don't write anything if there is no interesting private metadata ProjectDescription desc = ((Project) target).internalGetDescription(); - if (desc == null) + if (desc == null) { return; + } final URI projectLocation = desc.getLocationURI(); final IProject[] prjRefs = desc.getDynamicReferences(false); final String[] buildConfigs = desc.configNames; final Map configRefs = desc.getBuildConfigReferences(false); - if (projectLocation == null && prjRefs.length == 0 && buildConfigs.length == 0 && configRefs.isEmpty()) + if (projectLocation == null && prjRefs.length == 0 && buildConfigs.length == 0 && configRefs.isEmpty()) { return; + } //write the private metadata file try (SafeChunkyOutputStream output = new SafeChunkyOutputStream(file); DataOutputStream dataOut = new DataOutputStream(output);) { - if (projectLocation == null) + if (projectLocation == null) { dataOut.writeUTF(""); //$NON-NLS-1$ - else + } else { dataOut.writeUTF(URI_PREFIX + projectLocation); + } dataOut.writeInt(prjRefs.length); - for (IProject prjRef : prjRefs) + for (IProject prjRef : prjRefs) { dataOut.writeUTF(prjRef.getName()); + } // Since 3.7 - build configurations + references // Write out the build configurations diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LocationValidator.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LocationValidator.java index e4f2e7fcaa4..729f33c466a 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LocationValidator.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/LocationValidator.java @@ -68,10 +68,11 @@ private IStatus validateAbsolute(URI location, boolean error) { message = Messages.links_noPath; } else { IPath pathPart = IPath.fromOSString(schemeSpecificPart); - if (pathPart.segmentCount() > 0) + if (pathPart.segmentCount() > 0) { message = NLS.bind(Messages.pathvar_undefined, location.toString(), pathPart.segment(0)); - else + } else { message = Messages.links_noPath; + } } int code = error ? IResourceStatus.VARIABLE_NOT_DEFINED : IResourceStatus.VARIABLE_NOT_DEFINED_WARNING; return new ResourceStatus(code, null, message); @@ -84,8 +85,9 @@ private IStatus validateAbsolute(URI location, boolean error) { */ public IStatus validateLinkLocation(IResource resource, IPath unresolvedLocation) { IPath location = resource.getPathVariableManager().resolvePath(unresolvedLocation); - if (location.isEmpty()) + if (location.isEmpty()) { return new ResourceStatus(IResourceStatus.INVALID_VALUE, resource.getFullPath(), Messages.links_noPath); + } //check that the location is absolute if (!location.isAbsolute()) { //we know there is at least one segment, because of previous isEmpty check @@ -93,8 +95,9 @@ public IStatus validateLinkLocation(IResource resource, IPath unresolvedLocation return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED_WARNING, resource.getFullPath(), message); } //if the location doesn't have a device, see if the OS will assign one - if (location.getDevice() == null) + if (location.getDevice() == null) { location = IPath.fromOSString(location.toFile().getAbsolutePath()); + } return validateLinkLocationURI(resource, URIUtil.toURI(location)); } @@ -125,23 +128,28 @@ public IStatus validateLinkLocationURI(IResource resource, URI unresolvedLocatio String[] natureIds = ((Project) resource.getProject()).internalGetDescription().getNatureIds(); IStatus result = workspace.getNatureManager().validateLinkCreation(natureIds); - if (!result.isOK()) + if (!result.isOK()) { return result; + } //check team provider veto - if (resource.getType() == IResource.FILE) + if (resource.getType() == IResource.FILE) { result = workspace.getTeamHook().validateCreateLink((IFile) resource, IResource.NONE, location); - else + } else { result = workspace.getTeamHook().validateCreateLink((IFolder) resource, IResource.NONE, location); - if (!result.isOK()) + } + if (!result.isOK()) { return result; + } //check the standard path name restrictions result = validateSegments(location); - if (!result.isOK()) + if (!result.isOK()) { return result; + } //check if the location is based on an undefined variable result = validateAbsolute(location, false); - if (!result.isOK()) + if (!result.isOK()) { return result; + } // test if the given location overlaps the platform metadata location URI testLocation = workspace.getMetaArea().getLocation().toFile().toURI(); if (FileUtil.isOverlapping(location, testLocation)) { @@ -168,16 +176,18 @@ public IStatus validateLinkLocationURI(IResource resource, URI unresolvedLocatio return new ResourceStatus(IResourceStatus.OVERLAPPING_LOCATION, resource.getFullPath(), message); } //iterate over linked resources and check for overlap - if (!project.isOpen()) + if (!project.isOpen()) { continue; + } IResource[] children = null; try { children = project.members(); } catch (CoreException e) { //ignore projects that cannot be accessed } - if (children == null) + if (children == null) { continue; + } for (IResource child : children) { if (child.isLinked()) { testLocation = child.getLocationURI(); @@ -211,11 +221,12 @@ public IStatus validateName(String segment, int type) { /* test invalid characters */ char[] chars = OS.INVALID_RESOURCE_CHARACTERS; - for (char c : chars) + for (char c : chars) { if (segment.indexOf(c) != -1) { message = NLS.bind(Messages.resources_invalidCharInName, String.valueOf(c), segment); return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); } + } /* test invalid OS names */ if (!OS.isNameValid(segment)) { @@ -276,16 +287,19 @@ public IStatus validatePath(IPath path, int type, boolean lastSegmentOnly) { } int fileFolderType = type &= ~IResource.PROJECT; int segmentCount = path.segmentCount(); - if (lastSegmentOnly) + if (lastSegmentOnly) { return validateName(path.segment(segmentCount - 1), fileFolderType); + } IStatus status = validateName(path.segment(0), IResource.PROJECT); - if (!status.isOK()) + if (!status.isOK()) { return status; + } // ignore first segment (the project) for (int i = 1; i < segmentCount; i++) { status = validateName(path.segment(i), fileFolderType); - if (!status.isOK()) + if (!status.isOK()) { return status; + } } return Status.OK_STATUS; } @@ -306,20 +320,23 @@ public IStatus validatePath(String path, int type) { } public IStatus validateProjectLocation(IProject context, IPath unresolvedLocation) { - if (unresolvedLocation == null) + if (unresolvedLocation == null) { return validateProjectLocationURI(context, null); + } IPath location; - if (context != null) + if (context != null) { location = context.getPathVariableManager().resolvePath(unresolvedLocation); - else + } else { location = workspace.getPathVariableManager().resolvePath(unresolvedLocation); + } //check that the location is absolute if (!location.isAbsolute()) { String message; - if (location.segmentCount() > 0) + if (location.segmentCount() > 0) { message = NLS.bind(Messages.pathvar_undefined, location.toString(), location.segment(0)); - else + } else { message = Messages.links_noPath; + } return new ResourceStatus(IResourceStatus.VARIABLE_NOT_DEFINED, null, message); } return validateProjectLocationURI(context, URIUtil.toURI(location)); @@ -329,8 +346,9 @@ public IStatus validateProjectLocation(IProject context, IPath unresolvedLocatio * @see IWorkspace#validateProjectLocationURI(IProject, URI) */ public IStatus validateProjectLocationURI(IProject context, URI unresolvedLocation) { - if (context == null && unresolvedLocation == null) + if (context == null && unresolvedLocation == null) { throw new IllegalArgumentException("Either a project or a location must be provided"); //$NON-NLS-1$ + } // Checks if the new location overlaps the workspace metadata location boolean isMetadataLocation = false; @@ -350,20 +368,24 @@ public IStatus validateProjectLocationURI(IProject context, URI unresolvedLocati } // the default is ok for all other projects - if (unresolvedLocation == null) + if (unresolvedLocation == null) { return Status.OK_STATUS; + } URI location; - if (context != null) + if (context != null) { location = context.getPathVariableManager().resolveURI(unresolvedLocation); - else + } else { location = workspace.getPathVariableManager().resolveURI(unresolvedLocation); + } //check the standard path name restrictions IStatus result = validateSegments(location); - if (!result.isOK()) + if (!result.isOK()) { return result; + } result = validateAbsolute(location, true); - if (!result.isOK()) + if (!result.isOK()) { return result; + } //check that the URI has a legal scheme try { EFS.getFileSystem(location.getScheme()); @@ -395,11 +417,13 @@ public IStatus validateProjectLocationURI(IProject context, URI unresolvedLocati URI testLocation = project.getLocationURI(); if (context != null && project.equals(context)) { //tolerate locations being the same if this is the project being tested - if (URIUtil.equals(testLocation, location)) + if (URIUtil.equals(testLocation, location)) { continue; + } //a project cannot be moved inside of its current location - if (!FileUtil.isPrefixOf(testLocation, location)) + if (!FileUtil.isPrefixOf(testLocation, location)) { continue; + } } else if (!URIUtil.equals(testLocation, location)) { // a project cannot have the same location as another existing project continue; @@ -443,8 +467,9 @@ private IStatus validateSegments(URI location) { int segmentCount = pathPart.segmentCount(); for (int i = 0; i < segmentCount; i++) { IStatus result = validateName(pathPart.segment(i), IResource.PROJECT); - if (!result.isOK()) + if (!result.isOK()) { return result; + } } } return Status.OK_STATUS; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Marker.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Marker.java index 15b07b6403e..c42426bb1c3 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Marker.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Marker.java @@ -92,9 +92,9 @@ public void delete() throws CoreException { */ @Override public boolean equals(Object object) { - if (!(object instanceof IMarker)) + if (!(object instanceof IMarker other)) { return false; - IMarker other = (IMarker) object; + } return (id == other.getId() && resource.equals(other.getResource())); } @@ -124,11 +124,13 @@ public Object getAttribute(String attributeName) throws CoreException { public int getAttribute(String attributeName, int defaultValue) { Assert.isNotNull(attributeName); MarkerInfo info = getInfo(); - if (info == null) + if (info == null) { return defaultValue; + } Object value = info.getAttribute(attributeName); - if (value instanceof Integer) + if (value instanceof Integer) { return ((Integer) value).intValue(); + } return defaultValue; } @@ -139,11 +141,13 @@ public int getAttribute(String attributeName, int defaultValue) { public String getAttribute(String attributeName, String defaultValue) { Assert.isNotNull(attributeName); MarkerInfo info = getInfo(); - if (info == null) + if (info == null) { return defaultValue; + } Object value = info.getAttribute(attributeName); - if (value instanceof String) + if (value instanceof String) { return (String) value; + } return defaultValue; } @@ -154,11 +158,13 @@ public String getAttribute(String attributeName, String defaultValue) { public boolean getAttribute(String attributeName, boolean defaultValue) { Assert.isNotNull(attributeName); MarkerInfo info = getInfo(); - if (info == null) + if (info == null) { return defaultValue; + } Object value = info.getAttribute(attributeName); - if (value instanceof Boolean) + if (value instanceof Boolean) { return ((Boolean) value).booleanValue(); + } return defaultValue; } @@ -272,8 +278,9 @@ public void setAttribute(String attributeName, Object value) throws CoreExceptio MarkerInfo oldInfo = needDelta ? (MarkerInfo) markerInfo.clone() : null; boolean validate = manager.isPersistentType(markerInfo.getType()); markerInfo.setAttribute(attributeName, value, validate); - if (manager.isPersistent(markerInfo)) + if (manager.isPersistent(markerInfo)) { ((Resource) resource).getResourceInfo(false, true).set(ICoreConstants.M_MARKERS_SNAP_DIRTY); + } if (needDelta) { MarkerDelta delta = new MarkerDelta(IResourceDelta.CHANGED, resource, oldInfo); manager.changedMarkers(resource, new MarkerDelta[] {delta}); @@ -312,8 +319,9 @@ public void setAttributes(String[] attributeNames, Object[] values) throws CoreE MarkerInfo oldInfo = needDelta ? (MarkerInfo) markerInfo.clone() : null; boolean validate = manager.isPersistentType(markerInfo.getType()); markerInfo.addAttributes(attributeNames, values, validate); - if (manager.isPersistent(markerInfo)) + if (manager.isPersistent(markerInfo)) { ((Resource) resource).getResourceInfo(false, true).set(ICoreConstants.M_MARKERS_SNAP_DIRTY); + } if (needDelta) { MarkerDelta delta = new MarkerDelta(IResourceDelta.CHANGED, resource, oldInfo); manager.changedMarkers(resource, new MarkerDelta[] {delta}); @@ -342,8 +350,9 @@ public void setAttributes(Map values) throws CoreExcep MarkerInfo oldInfo = needDelta ? (MarkerInfo) markerInfo.clone() : null; boolean validate = manager.isPersistentType(markerInfo.getType()); markerInfo.setAttributes(values, validate); - if (manager.isPersistent(markerInfo)) + if (manager.isPersistent(markerInfo)) { ((Resource) resource).getResourceInfo(false, true).set(ICoreConstants.M_MARKERS_SNAP_DIRTY); + } if (needDelta) { MarkerDelta delta = new MarkerDelta(IResourceDelta.CHANGED, resource, oldInfo); manager.changedMarkers(resource, new MarkerDelta[] {delta}); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerDelta.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerDelta.java index eb83dc9b089..95ae96423b8 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerDelta.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerDelta.java @@ -44,24 +44,27 @@ public Object getAttribute(String attributeName) { @Override public int getAttribute(String attributeName, int defaultValue) { Object value = info.getAttribute(attributeName); - if (value instanceof Integer) + if (value instanceof Integer) { return ((Integer) value).intValue(); + } return defaultValue; } @Override public String getAttribute(String attributeName, String defaultValue) { Object value = info.getAttribute(attributeName); - if (value instanceof String) + if (value instanceof String) { return (String) value; + } return defaultValue; } @Override public boolean getAttribute(String attributeName, boolean defaultValue) { Object value = info.getAttribute(attributeName); - if (value instanceof Boolean) + if (value instanceof Boolean) { return ((Boolean) value).booleanValue(); + } return defaultValue; } @@ -110,19 +113,22 @@ public boolean isSubtypeOf(String superType) { * to store the result so we don't have to build a new map to return. */ public static Map merge(Map oldChanges, Map newChanges) { - if (oldChanges == null) + if (oldChanges == null) { //don't worry about copying since the new changes are no longer used return newChanges; - if (newChanges == null) + } + if (newChanges == null) { return oldChanges; + } for (Map.Entry newEntry : newChanges.entrySet()) { IPath key = newEntry.getKey(); MarkerSet oldSet = oldChanges.get(key); MarkerSet newSet = newEntry.getValue(); - if (oldSet == null) + if (oldSet == null) { oldChanges.put(key, newSet); - else + } else { merge(oldSet, newSet.elements()); + } } return oldChanges; } @@ -146,12 +152,14 @@ public static Map merge(Map oldChanges, Map< protected static MarkerSet merge(MarkerSet oldChanges, IMarkerSetElement[] newChanges) { if (oldChanges == null) { MarkerSet result = new MarkerSet(newChanges.length); - for (IMarkerSetElement newChange : newChanges) + for (IMarkerSetElement newChange : newChanges) { result.add(newChange); + } return result; } - if (newChanges == null) + if (newChanges == null) { return oldChanges; + } for (IMarkerSetElement newChange : newChanges) { MarkerDelta newDelta = (MarkerDelta) newChange; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerDeltaManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerDeltaManager.java index a9da748c6db..63e3894b4a8 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerDeltaManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerDeltaManager.java @@ -40,9 +40,11 @@ class MarkerDeltaManager { */ protected Map assembleDeltas(long start) { Map result = null; - for (int i = 0; i < nextFree; i++) - if (startIds[i] >= start) + for (int i = 0; i < nextFree; i++) { + if (startIds[i] >= start) { result = MarkerDelta.merge(result, batches[i]); + } + } return result; } @@ -53,11 +55,14 @@ protected Map assembleDeltas(long start) { protected void resetDeltas(long startId) { //find offset of first batch to keep int startOffset = 0; - for (; startOffset < nextFree; startOffset++) - if (startIds[startOffset] >= startId) + for (; startOffset < nextFree; startOffset++) { + if (startIds[startOffset] >= startId) { break; - if (startOffset == 0) + } + } + if (startOffset == 0) { return; + } long[] newIds = startIds; Map[] newBatches = batches; //shrink the arrays if it has grown too large diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerInfo.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerInfo.java index 793b7a9cf66..d968aea008a 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerInfo.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerInfo.java @@ -45,14 +45,15 @@ public class MarkerInfo implements IMarkerSetElement, Cloneable, IStringPoolPart * either the attribute or an equal canonical substitute. */ protected static Object checkValidAttribute(Object value) { - if (value == null) + if (value == null) { return null; - if (value instanceof String) { + } + if (value instanceof String valueString) { //we cannot write attributes whose UTF encoding exceeds 65535 bytes. - String valueString = (String) value; //optimized test based on maximum 3 bytes per character - if (valueString.length() < 21000) + if (valueString.length() < 21000) { return value; + } byte[] bytes = valueString.getBytes(StandardCharsets.UTF_8); if (bytes.length > 65535) { String msg = "Marker property value is too long: " + valueString.substring(0, 10000); //$NON-NLS-1$ @@ -113,21 +114,24 @@ public Object getAttribute(String attributeName) { } public Map getAttributes() { - if (attributes.isEmpty()) + if (attributes.isEmpty()) { return null; + } return attributes.toMap(); } public MarkerAttributeMap getAttributes(boolean makeCopy) { - if (attributes.isEmpty()) + if (attributes.isEmpty()) { return null; + } return makeCopy ? new MarkerAttributeMap(attributes) : attributes; } public Object[] getAttributes(String[] attributeNames) { Object[] result = new Object[attributeNames.length]; - for (int i = 0; i < attributeNames.length; i++) + for (int i = 0; i < attributeNames.length; i++) { result[i] = getAttribute(attributeNames[i]); + } return result; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerManager.java index cec89d44c58..f7eeb8ef44c 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerManager.java @@ -61,19 +61,23 @@ public void add(IResource resource, MarkerInfo newMarker) throws CoreException { target.checkExists(target.getFlags(info), false); info = workspace.getResourceInfo(resource.getFullPath(), false, true); // resource may have been deleted concurrently -- just bail out if this happens - if (info == null) + if (info == null) { return; + } // set the M_MARKERS_SNAP_DIRTY flag to indicate that this // resource's markers have changed since the last snapshot - if (isPersistent(newMarker)) + if (isPersistent(newMarker)) { info.set(ICoreConstants.M_MARKERS_SNAP_DIRTY); + } // Concurrency: copy the marker set on modify MarkerSet markers = info.getMarkers(true); - if (markers == null) + if (markers == null) { markers = new MarkerSet(1); + } basicAdd(resource, markers, newMarker); - if (!markers.isEmpty()) + if (!markers.isEmpty()) { info.setMarkers(markers); + } } /** @@ -93,49 +97,56 @@ private void basicAdd(IResource resource, MarkerSet markers, MarkerInfo newMarke */ protected MarkerInfo[] basicFindMatching(MarkerSet markers, String type, boolean includeSubtypes) { int size = markers.size(); - if (size <= 0) + if (size <= 0) { return NO_MARKER_INFO; + } List result = new ArrayList<>(size); IMarkerSetElement[] elements = markers.elements(); for (IMarkerSetElement element : elements) { MarkerInfo marker = (MarkerInfo) element; // if the type is null then we are looking for all types of markers - if (type == null) + if (type == null) { result.add(marker); - else { + } else { if (includeSubtypes) { - if (cache.isSubtype(marker.getType(), type)) + if (cache.isSubtype(marker.getType(), type)) { result.add(marker); + } } else { - if (marker.getType().equals(type)) + if (marker.getType().equals(type)) { result.add(marker); + } } } } size = result.size(); - if (size <= 0) + if (size <= 0) { return NO_MARKER_INFO; + } return result.toArray(new MarkerInfo[size]); } protected int basicFindMaxSeverity(MarkerSet markers, String type, boolean includeSubtypes) { int max = -1; int size = markers.size(); - if (size <= 0) + if (size <= 0) { return max; + } IMarkerSetElement[] elements = markers.elements(); for (IMarkerSetElement element : elements) { MarkerInfo marker = (MarkerInfo) element; // if the type is null then we are looking for all types of markers - if (type == null) + if (type == null) { max = Math.max(max, getSeverity(marker)); - else { + } else { if (includeSubtypes) { - if (cache.isSubtype(marker.getType(), type)) + if (cache.isSubtype(marker.getType(), type)) { max = Math.max(max, getSeverity(marker)); + } } else { - if (marker.getType().equals(type)) + if (marker.getType().equals(type)) { max = Math.max(max, getSeverity(marker)); + } } } if (max >= IMarker.SEVERITY_ERROR) { @@ -147,8 +158,7 @@ protected int basicFindMaxSeverity(MarkerSet markers, String type, boolean inclu private int getSeverity(MarkerInfo marker) { Object o = marker.getAttribute(IMarker.SEVERITY); - if (o instanceof Integer) { - Integer i = (Integer) o; + if (o instanceof Integer i) { return i.intValue(); } return -1; @@ -162,8 +172,9 @@ private int getSeverity(MarkerInfo marker) { protected void basicRemoveMarkers(ResourceInfo info, IPathRequestor requestor, String type, boolean includeSubtypes) { MarkerSet markers = info.getMarkers(false); - if (markers == null) + if (markers == null) { return; + } IMarkerSetElement[] matching; IPath path; if (type == null) { @@ -176,8 +187,9 @@ protected void basicRemoveMarkers(ResourceInfo info, IPathRequestor requestor, S } else { matching = basicFindMatching(markers, type, includeSubtypes); // if none match, there is nothing to remove - if (matching.length == 0) + if (matching.length == 0) { return; + } // now we need to crack open the tree path = requestor.requestPath(); info = workspace.getResourceInfo(path, false, true); @@ -195,8 +207,9 @@ protected void basicRemoveMarkers(ResourceInfo info, IPathRequestor requestor, S info.set(ICoreConstants.M_MARKERS_SNAP_DIRTY); IMarkerSetElement[] changes = new IMarkerSetElement[matching.length]; IResource resource = workspace.getRoot().findMember(path); - for (int i = 0; i < matching.length; i++) + for (int i = 0; i < matching.length; i++) { changes[i] = new MarkerDelta(IResourceDelta.REMOVED, resource, (MarkerInfo) matching[i]); + } changedMarkers(resource, changes); return; } @@ -206,8 +219,9 @@ protected void basicRemoveMarkers(ResourceInfo info, IPathRequestor requestor, S * list. */ protected void buildMarkers(IMarkerSetElement[] markers, IPath path, int type, ArrayList list) { - if (markers.length == 0) + if (markers.length == 0) { return; + } IResource resource = workspace.newResource(path, type); list.ensureCapacity(list.size() + markers.length); for (IMarkerSetElement marker : markers) { @@ -220,21 +234,25 @@ protected void buildMarkers(IMarkerSetElement[] markers, IPath path, int type, A * subsequent notification. */ protected void changedMarkers(IResource resource, IMarkerSetElement[] changes) { - if (changes == null || changes.length == 0) + if (changes == null || changes.length == 0) { return; + } long change = changeId.incrementAndGet(); - if (currentDeltas == null) + if (currentDeltas == null) { currentDeltas = deltaManager.newGeneration(change); + } IPath path = resource.getFullPath(); MarkerSet previousChanges = currentDeltas.get(path); MarkerSet result = MarkerDelta.merge(previousChanges, changes); - if (result.size() == 0) + if (result.size() == 0) { currentDeltas.remove(path); - else + } else { currentDeltas.put(path, result); + } ResourceInfo info = workspace.getResourceInfo(path, false, true); - if (info != null) + if (info != null) { info.incrementMarkerGenerationCount(); + } } /** @@ -250,11 +268,13 @@ public IMarker findMarker(IResource resource, long id) { */ public MarkerInfo findMarkerInfo(IResource resource, long id) { ResourceInfo info = workspace.getResourceInfo(resource.getFullPath(), false, false); - if (info == null) + if (info == null) { return null; + } MarkerSet markers = info.getMarkers(false); - if (markers == null) + if (markers == null) { return null; + } return (MarkerInfo) markers.get(id); } @@ -266,8 +286,9 @@ public MarkerInfo findMarkerInfo(IResource resource, long id) { public IMarker[] findMarkers(IResource target, final String type, final boolean includeSubtypes, int depth) { ArrayList result = new ArrayList<>(); doFindMarkers(target, result, type, includeSubtypes, depth); - if (result.isEmpty()) + if (result.isEmpty()) { return NO_MARKERS; + } return result.toArray(new IMarker[result.size()]); } @@ -280,10 +301,11 @@ public IMarker[] findMarkers(IResource target, final String type, final boolean public void doFindMarkers(IResource target, ArrayList result, final String type, final boolean includeSubtypes, int depth) { // optimize the deep searches with an element tree visitor - if (depth == IResource.DEPTH_INFINITE && target.getType() != IResource.FILE) + if (depth == IResource.DEPTH_INFINITE && target.getType() != IResource.FILE) { visitorFindMarkers(target.getFullPath(), result, type, includeSubtypes); - else + } else { recursiveFindMarkers(target.getFullPath(), result, type, includeSubtypes, depth); + } } /** @@ -292,8 +314,9 @@ public void doFindMarkers(IResource target, ArrayList result, final Str */ public int findMaxProblemSeverity(IResource target, String type, boolean includeSubtypes, int depth) { // optimize the deep searches with an element tree visitor - if (depth == IResource.DEPTH_INFINITE && target.getType() != IResource.FILE) + if (depth == IResource.DEPTH_INFINITE && target.getType() != IResource.FILE) { return visitorFindMaxSeverity(target.getFullPath(), type, includeSubtypes); + } return recursiveFindMaxSeverity(target.getFullPath(), type, includeSubtypes, depth); } @@ -313,11 +336,13 @@ public Map getMarkerDeltas(long startChangeId) { * id, and false otherwise. */ boolean hasDelta(IPath path, long id) { - if (currentDeltas == null) + if (currentDeltas == null) { return false; + } MarkerSet set = currentDeltas.get(path); - if (set == null) + if (set == null) { return false; + } return set.get(id) != null; } @@ -325,8 +350,9 @@ boolean hasDelta(IPath path, long id) { * Returns true if the given marker is persistent, and false otherwise. */ public boolean isPersistent(MarkerInfo info) { - if (!cache.isPersistent(info.getType())) + if (!cache.isPersistent(info.getType())) { return false; + } Object isTransient = info.getAttribute(IMarker.TRANSIENT); return isTransient == null || !(isTransient instanceof Boolean) || !((Boolean) isTransient).booleanValue(); } @@ -353,8 +379,9 @@ public void moved(final IResource source, final IResource destination, int depth Resource r = (Resource) resource; ResourceInfo info = r.getResourceInfo(false, true); MarkerSet markers = info.getMarkers(false); - if (markers == null) + if (markers == null) { return true; + } info.set(ICoreConstants.M_MARKERS_SNAP_DIRTY); IMarkerSetElement[] removed = new IMarkerSetElement[markers.size()]; IMarkerSetElement[] added = new IMarkerSetElement[markers.size()]; @@ -384,25 +411,29 @@ public void moved(final IResource source, final IResource destination, int depth private void recursiveFindMarkers(IPath path, ArrayList list, String type, boolean includeSubtypes, int depth) { ResourceInfo info = workspace.getResourceInfo(path, false, false); - if (info == null) + if (info == null) { return; + } MarkerSet markers = info.getMarkers(false); // add the matching markers for this resource if (markers != null) { IMarkerSetElement[] matching; - if (type == null) + if (type == null) { matching = markers.elements(); - else + } else { matching = basicFindMatching(markers, type, includeSubtypes); + } buildMarkers(matching, path, info.getType(), list); } // recurse - if (depth == IResource.DEPTH_ZERO || info.getType() == IResource.FILE) + if (depth == IResource.DEPTH_ZERO || info.getType() == IResource.FILE) { return; - if (depth == IResource.DEPTH_ONE) + } + if (depth == IResource.DEPTH_ONE) { depth = IResource.DEPTH_ZERO; + } for (IPath child : workspace.getElementTree().getChildren(path)) { recursiveFindMarkers(child, list, type, includeSubtypes, depth); } @@ -413,8 +444,9 @@ private void recursiveFindMarkers(IPath path, ArrayList list, String ty */ private int recursiveFindMaxSeverity(IPath path, String type, boolean includeSubtypes, int depth) { ResourceInfo info = workspace.getResourceInfo(path, false, false); - if (info == null) + if (info == null) { return -1; + } MarkerSet markers = info.getMarkers(false); // add the matching markers for this resource @@ -427,10 +459,12 @@ private int recursiveFindMaxSeverity(IPath path, String type, boolean includeSub } // recurse - if (depth == IResource.DEPTH_ZERO || info.getType() == IResource.FILE) + if (depth == IResource.DEPTH_ZERO || info.getType() == IResource.FILE) { return max; - if (depth == IResource.DEPTH_ONE) + } + if (depth == IResource.DEPTH_ONE) { depth = IResource.DEPTH_ZERO; + } for (IPath child : workspace.getElementTree().getChildren(path)) { max = Math.max(max, recursiveFindMaxSeverity(child, type, includeSubtypes, depth)); if (max >= IMarker.SEVERITY_ERROR) { @@ -445,8 +479,9 @@ private int recursiveFindMaxSeverity(IPath path, String type, boolean includeSub */ private void recursiveRemoveMarkers(final IPath path, String type, boolean includeSubtypes, int depth) { ResourceInfo info = workspace.getResourceInfo(path, false, false); - if (info == null) // phantoms don't have markers + if (info == null) { // phantoms don't have markers return; + } IPathRequestor requestor = new IPathRequestor() { @Override public String requestName() { @@ -460,10 +495,12 @@ public IPath requestPath() { }; basicRemoveMarkers(info, requestor, type, includeSubtypes); // recurse - if (depth == IResource.DEPTH_ZERO || info.getType() == IResource.FILE) + if (depth == IResource.DEPTH_ZERO || info.getType() == IResource.FILE) { return; - if (depth == IResource.DEPTH_ONE) + } + if (depth == IResource.DEPTH_ONE) { depth = IResource.DEPTH_ZERO; + } for (IPath child : workspace.getElementTree().getChildren(path)) { recursiveRemoveMarkers(child, type, includeSubtypes, depth); } @@ -474,8 +511,9 @@ public IPath requestPath() { */ public void removeMarker(IResource resource, long id) { MarkerInfo markerInfo = findMarkerInfo(resource, id); - if (markerInfo == null) + if (markerInfo == null) { return; + } ResourceInfo info = ((Workspace) resource.getWorkspace()).getResourceInfo(resource.getFullPath(), false, true); // Concurrency: copy the marker set on modify MarkerSet markers = info.getMarkers(true); @@ -485,8 +523,9 @@ public void removeMarker(IResource resource, long id) { info.setMarkers(markers.size() == 0 ? null : markers); // if we actually did remove a marker, post a delta for the change. if (markers.size() != size) { - if (isPersistent(markerInfo)) + if (isPersistent(markerInfo)) { info.set(ICoreConstants.M_MARKERS_SNAP_DIRTY); + } IMarkerSetElement[] change = new IMarkerSetElement[] { new MarkerDelta(IResourceDelta.REMOVED, resource, markerInfo) }; changedMarkers(resource, change); @@ -506,10 +545,11 @@ public void removeMarkers(IResource resource, int depth) { * null is a wildcard. */ public void removeMarkers(IResource target, final String type, final boolean includeSubtypes, int depth) { - if (depth == IResource.DEPTH_INFINITE && target.getType() != IResource.FILE) + if (depth == IResource.DEPTH_INFINITE && target.getType() != IResource.FILE) { visitorRemoveMarkers(target.getFullPath(), type, includeSubtypes); - else + } else { recursiveRemoveMarkers(target.getFullPath(), type, includeSubtypes, depth); + } } /** @@ -531,8 +571,9 @@ protected void restoreFromSave(IResource resource, boolean generateDeltas) throw IPath tempLocation = workspace.getMetaArea().getBackupLocationFor(sourceLocation); java.io.File sourceFile = new java.io.File(sourceLocation.toOSString()); java.io.File tempFile = new java.io.File(tempLocation.toOSString()); - if (!sourceFile.exists() && !tempFile.exists()) + if (!sourceFile.exists() && !tempFile.exists()) { return; + } try (DataInputStream input = new DataInputStream( new SafeFileInputStream(sourceLocation.toOSString(), tempLocation.toOSString()))) { MarkerReader reader = new MarkerReader(workspace); @@ -546,12 +587,14 @@ protected void restoreFromSave(IResource resource, boolean generateDeltas) throw protected void restoreFromSnap(IResource resource) { IPath sourceLocation = workspace.getMetaArea().getMarkersSnapshotLocationFor(resource); - if (!sourceLocation.toFile().exists()) + if (!sourceLocation.toFile().exists()) { return; + } try (DataInputStream input = new DataInputStream(new SafeChunkyInputStream(sourceLocation.toFile()))) { MarkerSnapshotReader reader = new MarkerSnapshotReader(workspace); - while (true) + while (true) { reader.read(input); + } } catch (EOFException eof) { // ignore end of file } catch (Exception e) { @@ -587,17 +630,19 @@ private void visitorFindMarkers(IPath path, final ArrayList list, final final boolean includeSubtypes) { IElementContentVisitor visitor = (tree, requestor, elementContents) -> { ResourceInfo info = (ResourceInfo) elementContents; - if (info == null) + if (info == null) { return false; + } MarkerSet markers = info.getMarkers(false); // add the matching markers for this resource if (markers != null) { IMarkerSetElement[] matching; - if (type == null) + if (type == null) { matching = markers.elements(); - else + } else { matching = basicFindMatching(markers, type, includeSubtypes); + } buildMarkers(matching, requestor.requestPath(), info.getType(), list); } return true; @@ -619,8 +664,9 @@ public boolean visitElement(ElementTree tree, IPathRequestor requestor, Object e return false; } ResourceInfo info = (ResourceInfo) elementContents; - if (info == null) + if (info == null) { return false; + } MarkerSet markers = info.getMarkers(false); // add the matching markers for this resource @@ -641,8 +687,9 @@ public boolean visitElement(ElementTree tree, IPathRequestor requestor, Object e private void visitorRemoveMarkers(IPath path, final String type, final boolean includeSubtypes) { IElementContentVisitor visitor = (tree, requestor, elementContents) -> { ResourceInfo info = (ResourceInfo) elementContents; - if (info == null) + if (info == null) { return false; + } basicRemoveMarkers(info, requestor, type, includeSubtypes); return true; }; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_1.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_1.java index 71d1b410146..03da72e20c6 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_1.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_1.java @@ -78,14 +78,16 @@ public void read(DataInputStream input, boolean generateDeltas) throws IOExcepti IPath path = IPath.fromOSString(input.readUTF()); int markersSize = input.readInt(); MarkerSet markers = new MarkerSet(markersSize); - for (int i = 0; i < markersSize; i++) + for (int i = 0; i < markersSize; i++) { markers.add(readMarkerInfo(input, readTypes)); + } // if the resource doesn't exist then return. ensure we do this after // reading the markers from the file so we don't get into an // inconsistent state. ResourceInfo info = workspace.getResourceInfo(path, false, false); - if (info == null) + if (info == null) { continue; + } info.setMarkers(markers); if (generateDeltas) { Resource resource = workspace.newResource(path, info.getType()); @@ -93,9 +95,11 @@ public void read(DataInputStream input, boolean generateDeltas) throws IOExcepti // and shrinking the array. IMarkerSetElement[] infos = markers.elements; ArrayList deltas = new ArrayList<>(infos.length); - for (IMarkerSetElement info2 : infos) - if (info2 != null) + for (IMarkerSetElement info2 : infos) { + if (info2 != null) { deltas.add(new MarkerDelta(IResourceDelta.ADDED, resource, (MarkerInfo) info2)); + } + } workspace.getMarkerManager().changedMarkers(resource, deltas.toArray(new IMarkerSetElement[deltas.size()])); } } @@ -106,8 +110,9 @@ public void read(DataInputStream input, boolean generateDeltas) throws IOExcepti private Map readAttributes(DataInputStream input) throws IOException { int attributesSize = input.readInt(); - if (attributesSize == 0) + if (attributesSize == 0) { return null; + } Map result = new HashMap<>(attributesSize); for (int j = 0; j < attributesSize; j++) { String key = input.readUTF(); @@ -127,8 +132,9 @@ private Map readAttributes(DataInputStream input) throws IOExcep // do nothing break; } - if (value != null) + if (value != null) { result.put(key, value); + } } return result.isEmpty() ? null : result; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_2.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_2.java index 9df09e18fed..dd659e31686 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_2.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_2.java @@ -79,14 +79,16 @@ public void read(DataInputStream input, boolean generateDeltas) throws IOExcepti IPath path = IPath.fromOSString(input.readUTF()); int markersSize = input.readInt(); MarkerSet markers = new MarkerSet(markersSize); - for (int i = 0; i < markersSize; i++) + for (int i = 0; i < markersSize; i++) { markers.add(readMarkerInfo(input, readTypes)); + } // if the resource doesn't exist then return. ensure we do this after // reading the markers from the file so we don't get into an // inconsistent state. ResourceInfo info = workspace.getResourceInfo(path, false, false); - if (info == null) + if (info == null) { continue; + } info.setMarkers(markers); if (generateDeltas) { // Iterate over all elements and add not null ones. This saves us from copying @@ -94,9 +96,11 @@ public void read(DataInputStream input, boolean generateDeltas) throws IOExcepti Resource resource = workspace.newResource(path, info.getType()); IMarkerSetElement[] infos = markers.elements; ArrayList deltas = new ArrayList<>(infos.length); - for (IMarkerSetElement info2 : infos) - if (info2 != null) + for (IMarkerSetElement info2 : infos) { + if (info2 != null) { deltas.add(new MarkerDelta(IResourceDelta.ADDED, resource, (MarkerInfo) info2)); + } + } workspace.getMarkerManager().changedMarkers(resource, deltas.toArray(new IMarkerSetElement[deltas.size()])); } } @@ -107,8 +111,9 @@ public void read(DataInputStream input, boolean generateDeltas) throws IOExcepti private Map readAttributes(DataInputStream input) throws IOException { int attributesSize = input.readShort(); - if (attributesSize == 0) + if (attributesSize == 0) { return null; + } Map result = new HashMap<>(attributesSize); for (int j = 0; j < attributesSize; j++) { String key = input.readUTF(); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_3.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_3.java index f31266cb983..570eb78948a 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_3.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerReader_3.java @@ -80,14 +80,16 @@ public void read(DataInputStream input, boolean generateDeltas) throws IOExcepti IPath path = IPath.fromOSString(input.readUTF()); int markersSize = input.readInt(); MarkerSet markers = new MarkerSet(markersSize); - for (int i = 0; i < markersSize; i++) + for (int i = 0; i < markersSize; i++) { markers.add(readMarkerInfo(input, readTypes)); + } // if the resource doesn't exist then return. ensure we do this after // reading the markers from the file so we don't get into an // inconsistent state. ResourceInfo info = workspace.getResourceInfo(path, false, false); - if (info == null) + if (info == null) { continue; + } info.setMarkers(markers); if (generateDeltas) { // Iterate over all elements and add not null ones. This saves us from copying @@ -95,9 +97,11 @@ public void read(DataInputStream input, boolean generateDeltas) throws IOExcepti Resource resource = workspace.newResource(path, info.getType()); IMarkerSetElement[] infos = markers.elements; ArrayList deltas = new ArrayList<>(infos.length); - for (IMarkerSetElement info2 : infos) - if (info2 != null) + for (IMarkerSetElement info2 : infos) { + if (info2 != null) { deltas.add(new MarkerDelta(IResourceDelta.ADDED, resource, (MarkerInfo) info2)); + } + } workspace.getMarkerManager().changedMarkers(resource, deltas.toArray(new IMarkerSetElement[deltas.size()])); } } @@ -108,8 +112,9 @@ public void read(DataInputStream input, boolean generateDeltas) throws IOExcepti private Map readAttributes(DataInputStream input) throws IOException { int attributesSize = input.readShort(); - if (attributesSize == 0) + if (attributesSize == 0) { return null; + } Map result = new HashMap<>(attributesSize); for (int j = 0; j < attributesSize; j++) { String key = input.readUTF(); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSet.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSet.java index 249cd691924..a88e54e78d0 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSet.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSet.java @@ -33,8 +33,9 @@ public MarkerSet(int capacity) { } public void add(IMarkerSetElement element) { - if (element == null) + if (element == null) { return; + } int hash = hashFor(element.getId()) % elements.length; // search for an empty slot at the end of the array @@ -43,8 +44,9 @@ public void add(IMarkerSetElement element) { elements[i] = element; elementCount++; // grow if necessary - if (shouldGrow()) + if (shouldGrow()) { expand(); + } return; } } @@ -55,8 +57,9 @@ public void add(IMarkerSetElement element) { elements[i] = element; elementCount++; // grow if necessary - if (shouldGrow()) + if (shouldGrow()) { expand(); + } return; } } @@ -67,8 +70,9 @@ public void add(IMarkerSetElement element) { } public void addAll(IMarkerSetElement[] toAdd) { - for (IMarkerSetElement element : toAdd) + for (IMarkerSetElement element : toAdd) { add(element); + } } @Override @@ -92,8 +96,9 @@ public IMarkerSetElement[] elements() { IMarkerSetElement[] result = new IMarkerSetElement[elementCount]; int j = 0; for (IMarkerSetElement element : elements) { - if (element != null) + if (element != null) { result[j++] = element; + } } return result; } @@ -110,8 +115,9 @@ protected void expand() { int hash = hashFor(element.getId()) % array.length; while (array[hash] != null) { hash++; - if (hash > maxArrayIndex) + if (hash > maxArrayIndex) { hash = 0; + } } array[hash] = element; } @@ -124,26 +130,31 @@ protected void expand() { * if not found. */ public IMarkerSetElement get(long id) { - if (elementCount == 0) + if (elementCount == 0) { return null; + } int hash = hashFor(id) % elements.length; // search the last half of the array for (int i = hash; i < elements.length; i++) { IMarkerSetElement element = elements[i]; - if (element == null) + if (element == null) { return null; - if (element.getId() == id) + } + if (element.getId() == id) { return element; + } } // search the beginning of the array for (int i = 0; i < hash - 1; i++) { IMarkerSetElement element = elements[i]; - if (element == null) + if (element == null) { return null; - if (element.getId() == id) + } + if (element.getId() == id) { return element; + } } // marker info not found so return null @@ -166,23 +177,26 @@ protected void rehashTo(int anIndex) { int target = anIndex; int index = anIndex + 1; - if (index >= elements.length) + if (index >= elements.length) { index = 0; + } IMarkerSetElement element = elements[index]; while (element != null) { int hashIndex = hashFor(element.getId()) % elements.length; boolean match; - if (index < target) + if (index < target) { match = !(hashIndex > target || hashIndex <= index); - else + } else { match = !(hashIndex > target && hashIndex <= index); + } if (match) { elements[target] = element; target = index; } index++; - if (index >= elements.length) + if (index >= elements.length) { index = 0; + } element = elements[index]; } elements[target] = null; @@ -193,8 +207,9 @@ public void remove(long id) { for (int i = hash; i < elements.length; i++) { IMarkerSetElement element = elements[i]; - if (element == null) + if (element == null) { return; + } if (element.getId() == id) { rehashTo(i); elementCount--; @@ -203,8 +218,9 @@ public void remove(long id) { for (int i = 0; i < hash - 1; i++) { IMarkerSetElement element = elements[i]; - if (element == null) + if (element == null) { return; + } if (element.getId() == id) { rehashTo(i); elementCount--; @@ -217,8 +233,9 @@ public void remove(IMarkerSetElement element) { } public void removeAll(IMarkerSetElement[] toRemove) { - for (IMarkerSetElement element : toRemove) + for (IMarkerSetElement element : toRemove) { remove(element); + } } private boolean shouldGrow() { @@ -236,11 +253,13 @@ public int size() { public void shareStrings(StringPool set) { //copy elements for thread safety IMarkerSetElement[] array = elements; - if (array == null) + if (array == null) { return; + } for (IMarkerSetElement o : array) { - if (o instanceof IStringPoolParticipant) + if (o instanceof IStringPoolParticipant) { ((IStringPoolParticipant) o).shareStrings(set); + } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSnapshotReader_1.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSnapshotReader_1.java index d47c3dc1167..87635ae1189 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSnapshotReader_1.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSnapshotReader_1.java @@ -75,21 +75,24 @@ public void read(DataInputStream input) throws IOException, CoreException { int markersSize = input.readInt(); MarkerSet markers = new MarkerSet(markersSize); ArrayList readTypes = new ArrayList<>(); - for (int i = 0; i < markersSize; i++) + for (int i = 0; i < markersSize; i++) { markers.add(readMarkerInfo(input, readTypes)); + } // we've read all the markers from the file for this snap. if the resource // doesn't exist in the workspace then consider this a delete and return ResourceInfo info = workspace.getResourceInfo(path, false, false); - if (info == null) + if (info == null) { return; + } info.setMarkers(markers); info.clear(ICoreConstants.M_MARKERS_SNAP_DIRTY); } private Map readAttributes(DataInputStream input) throws IOException { short attributesSize = input.readShort(); - if (attributesSize == 0) + if (attributesSize == 0) { return null; + } Map result = new HashMap<>(attributesSize); for (int j = 0; j < attributesSize; j++) { String key = input.readUTF(); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSnapshotReader_2.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSnapshotReader_2.java index dcf6f41fe1e..86ae3a01e7f 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSnapshotReader_2.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerSnapshotReader_2.java @@ -76,21 +76,24 @@ public void read(DataInputStream input) throws IOException, CoreException { int markersSize = input.readInt(); MarkerSet markers = new MarkerSet(markersSize); ArrayList readTypes = new ArrayList<>(); - for (int i = 0; i < markersSize; i++) + for (int i = 0; i < markersSize; i++) { markers.add(readMarkerInfo(input, readTypes)); + } // we've read all the markers from the file for this snap. if the resource // doesn't exist in the workspace then consider this a delete and return ResourceInfo info = workspace.getResourceInfo(path, false, false); - if (info == null) + if (info == null) { return; + } info.setMarkers(markers); info.clear(ICoreConstants.M_MARKERS_SNAP_DIRTY); } private Map readAttributes(DataInputStream input) throws IOException { short attributesSize = input.readShort(); - if (attributesSize == 0) + if (attributesSize == 0) { return null; + } Map result = new HashMap<>(attributesSize); for (int j = 0; j < attributesSize; j++) { String key = input.readUTF(); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerTypeDefinitionCache.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerTypeDefinitionCache.java index 489d4efd1d7..2abedc383e6 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerTypeDefinitionCache.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerTypeDefinitionCache.java @@ -33,8 +33,9 @@ static class MarkerTypeDefinition { if (elementName.equalsIgnoreCase("super")) { //$NON-NLS-1$ String aType = element.getAttribute("type"); //$NON-NLS-1$ if (aType != null) { - if (superTypes == null) + if (superTypes == null) { superTypes = new HashSet<>(8); + } //note that all marker type names will be in the intern table //already because there is invariably a constant to describe //the type name @@ -44,14 +45,16 @@ static class MarkerTypeDefinition { // persistent if (elementName.equalsIgnoreCase("persistent")) { //$NON-NLS-1$ String bool = element.getAttribute("value"); //$NON-NLS-1$ - if (bool != null) + if (bool != null) { this.isPersistent = Boolean.parseBoolean(bool); + } } // XXX: legacy code for support of tag. remove later. if (elementName.equalsIgnoreCase("transient")) { //$NON-NLS-1$ String bool = element.getAttribute("value"); //$NON-NLS-1$ - if (bool != null) + if (bool != null) { this.isPersistent = !Boolean.parseBoolean(bool); + } } } } @@ -68,8 +71,9 @@ public MarkerTypeDefinitionCache() { loadDefinitions(); HashSet toCompute = new HashSet<>(definitions.keySet()); for (String markerId : definitions.keySet()) { - if (toCompute.contains(markerId)) + if (toCompute.contains(markerId)) { computeSuperTypes(markerId, toCompute); + } } } @@ -97,11 +101,13 @@ private Set computeSuperTypes(String markerId, Set toCompute) { } else { // we have already computed this super type's super types (or it doesn't exist) MarkerTypeDefinition parentDef = definitions.get(superId); - if (parentDef != null) + if (parentDef != null) { toAdd = parentDef.superTypes; + } } - if (toAdd != null) + if (toAdd != null) { transitiveSuperTypes.addAll(toAdd); + } } def.superTypes = transitiveSuperTypes; toCompute.remove(markerId); @@ -121,8 +127,9 @@ public boolean isPersistent(String type) { */ public boolean isSubtype(String type, String superType) { //types are considered super types of themselves - if (type.equals(superType)) + if (type.equals(superType)) { return true; + } MarkerTypeDefinition def = definitions.get(type); return def != null && def.superTypes != null && def.superTypes.contains(superType); } @@ -133,10 +140,11 @@ private void loadDefinitions() { definitions = new HashMap<>(types.length); for (IExtension type : types) { String markerId = type.getUniqueIdentifier(); - if (markerId != null) + if (markerId != null) { definitions.put(markerId.intern(), new MarkerTypeDefinition(type)); - else + } else { Policy.log(IStatus.WARNING, "Missing marker id from plugin: " + type.getContributor().getName(), null); //$NON-NLS-1$ + } } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerWriter.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerWriter.java index 4a10fe74a17..60153f407da 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerWriter.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/MarkerWriter.java @@ -91,27 +91,33 @@ private Object[] filterMarkers(IMarkerSetElement[] markers) { */ public void save(ResourceInfo info, IPathRequestor requestor, DataOutputStream output, List writtenTypes) throws IOException { // phantom resources don't have markers - if (info.isSet(ICoreConstants.M_PHANTOM)) + if (info.isSet(ICoreConstants.M_PHANTOM)) { return; + } MarkerSet markers = info.getMarkers(false); - if (markers == null) + if (markers == null) { return; + } IMarkerSetElement[] elements = markers.elements(); // filter out the markers...determine if there are any persistent ones Object[] result = filterMarkers(elements); int count = ((Integer) result[0]).intValue(); - if (count == 0) + if (count == 0) { return; + } // if this is the first set of markers that we have written, then // write the version id for the file. - if (output.size() == 0) + if (output.size() == 0) { output.writeInt(MARKERS_SAVE_VERSION); + } boolean[] isPersistent = (boolean[]) result[1]; output.writeUTF(requestor.requestPath().toString()); output.writeInt(count); - for (int i = 0; i < elements.length; i++) - if (isPersistent[i]) + for (int i = 0; i < elements.length; i++) { + if (isPersistent[i]) { write((MarkerInfo) elements[i], output, writtenTypes); + } + } } /** @@ -141,13 +147,16 @@ public void save(ResourceInfo info, IPathRequestor requestor, DataOutputStream o */ public void snap(ResourceInfo info, IPathRequestor requestor, DataOutputStream output) throws IOException { // phantom resources don't have markers - if (info.isSet(ICoreConstants.M_PHANTOM)) + if (info.isSet(ICoreConstants.M_PHANTOM)) { return; - if (!info.isSet(ICoreConstants.M_MARKERS_SNAP_DIRTY)) + } + if (!info.isSet(ICoreConstants.M_MARKERS_SNAP_DIRTY)) { return; + } MarkerSet markers = info.getMarkers(false); - if (markers == null) + if (markers == null) { return; + } IMarkerSetElement[] elements = markers.elements(); // filter out the markers...determine if there are any persistent ones Object[] result = filterMarkers(elements); @@ -160,9 +169,11 @@ public void snap(ResourceInfo info, IPathRequestor requestor, DataOutputStream o // use pick up marker deletions from our snapshot. output.writeInt(count); List writtenTypes = new ArrayList<>(); - for (int i = 0; i < elements.length; i++) - if (isPersistent[i]) + for (int i = 0; i < elements.length; i++) { + if (isPersistent[i]) { write((MarkerInfo) elements[i], output, writtenTypes); + } + } info.clear(ICoreConstants.M_MARKERS_SNAP_DIRTY); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ModelObjectWriter.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ModelObjectWriter.java index 697e64a2f4a..9a441eddd98 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ModelObjectWriter.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ModelObjectWriter.java @@ -46,14 +46,18 @@ public class ModelObjectWriter implements IModelObjectConstants { */ private static String triggerString(BuildCommand command) { StringBuilder buf = new StringBuilder(); - if (command.isBuilding(IncrementalProjectBuilder.AUTO_BUILD)) + if (command.isBuilding(IncrementalProjectBuilder.AUTO_BUILD)) { buf.append(TRIGGER_AUTO).append(','); - if (command.isBuilding(IncrementalProjectBuilder.CLEAN_BUILD)) + } + if (command.isBuilding(IncrementalProjectBuilder.CLEAN_BUILD)) { buf.append(TRIGGER_CLEAN).append(','); - if (command.isBuilding(IncrementalProjectBuilder.FULL_BUILD)) + } + if (command.isBuilding(IncrementalProjectBuilder.FULL_BUILD)) { buf.append(TRIGGER_FULL).append(','); - if (command.isBuilding(IncrementalProjectBuilder.INCREMENTAL_BUILD)) + } + if (command.isBuilding(IncrementalProjectBuilder.INCREMENTAL_BUILD)) { buf.append(TRIGGER_INCREMENTAL).append(','); + } return buf.toString(); } @@ -64,8 +68,9 @@ public ModelObjectWriter() { protected String[] getReferencedProjects(ProjectDescription description) { IProject[] projects = description.getReferencedProjects(); String[] result = new String[projects.length]; - for (int i = 0; i < projects.length; i++) + for (int i = 0; i < projects.length; i++) { result[i] = projects[i].getName(); + } return result; } @@ -73,8 +78,9 @@ protected void write(BuildCommand command, XMLWriter writer) { writer.startTag(BUILD_COMMAND, null); if (command != null) { writer.printSimpleTag(NAME, command.getName()); - if (shouldWriteTriggers(command)) + if (shouldWriteTriggers(command)) { writer.printSimpleTag(BUILD_TRIGGERS, triggerString(command)); + } write(ARGUMENTS, command.getArguments(false), writer); } writer.endTag(BUILD_COMMAND); @@ -87,8 +93,9 @@ private boolean shouldWriteTriggers(BuildCommand command) { //only write triggers if command is configurable and there exists a trigger //that the builder does NOT respond to. I.e., don't write out on the default //cases to avoid dirtying .project files unnecessarily. - if (!command.isConfigurable()) + if (!command.isConfigurable()) { return false; + } return !command.isBuilding(IncrementalProjectBuilder.AUTO_BUILD) || !command.isBuilding(IncrementalProjectBuilder.CLEAN_BUILD) || !command.isBuilding(IncrementalProjectBuilder.FULL_BUILD) || !command.isBuilding(IncrementalProjectBuilder.INCREMENTAL_BUILD); } @@ -129,8 +136,9 @@ protected void write(FileInfoMatcherDescription description, XMLWriter writer) { write(element, writer); } writer.endTag(ARGUMENTS); - } else + } else { writer.printSimpleTag(ARGUMENTS, ""); //$NON-NLS-1$ + } } writer.endTag(MATCHER); } @@ -166,8 +174,9 @@ public void write(Object object, OutputStream output, String lineSeparator) thro ) { write(object, writer); writer.flush(); - if (writer.checkError()) + if (writer.checkError()) { throw new IOException(); + } } } @@ -241,8 +250,9 @@ protected void write(ProjectDescription description, XMLWriter writer) throws IO protected void write(String name, Collection collection, XMLWriter writer) throws IOException { writer.startTag(name, null); - for (Object o : collection) + for (Object o : collection) { write(o, writer); + } writer.endTag(name); } @@ -269,8 +279,9 @@ protected void write(String name, Map table, XMLWriter writer) { protected void write(String name, String elementTagName, String[] array, XMLWriter writer) { writer.startTag(name, null); - for (String element : array) + for (String element : array) { writer.printSimpleTag(elementTagName, element); + } writer.endTag(name); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/NatureManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/NatureManager.java index 116be4f7bdc..4d9b61f23d7 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/NatureManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/NatureManager.java @@ -56,12 +56,14 @@ protected NatureManager(Workspace workspace) { */ protected String[] computeNatureEnablements(Project project) { final ProjectDescription description = project.internalGetDescription(); - if (description == null) + if (description == null) { return new String[0];//project deleted concurrently + } String[] natureIds = description.getNatureIds(); int count = natureIds.length; - if (count == 0) + if (count == 0) { return natureIds; + } //set of the nature ids being validated (String (id)) HashSet candidates = new HashSet<>(count * 2); @@ -70,10 +72,12 @@ protected String[] computeNatureEnablements(Project project) { for (int i = 0; i < count; i++) { String id = natureIds[i]; ProjectNatureDescriptor desc = (ProjectNatureDescriptor) getNatureDescriptor(id); - if (desc == null) + if (desc == null) { continue; - if (!desc.hasCycle) + } + if (!desc.hasCycle) { candidates.add(id); + } //build set to nature map String[] setIds = desc.getNatureSetIds(); for (String set : setIds) { @@ -154,10 +158,11 @@ public void run() throws Exception { @Override public void handleException(Throwable exception) { - if (exception instanceof CoreException) + if (exception instanceof CoreException) { errors.add(((CoreException) exception).getStatus()); - else + } else { errors.add(new ResourceStatus(IResourceStatus.INTERNAL_ERROR, project.getFullPath(), NLS.bind(Messages.resources_errorNature, natureID), exception)); + } } }; if (Policy.DEBUG_NATURES) { @@ -178,8 +183,9 @@ public void configureNatures(Project project, ProjectDescription oldDescription, // may well result in recursive calls to this method. HashSet oldNatures = new HashSet<>(Arrays.asList(oldDescription.getNatureIds(false))); HashSet newNatures = new HashSet<>(Arrays.asList(newDescription.getNatureIds(false))); - if (oldNatures.equals(newNatures)) + if (oldNatures.equals(newNatures)) { return; + } HashSet deletions = (HashSet) oldNatures.clone(); HashSet additions = (HashSet) newNatures.clone(); additions.removeAll(oldNatures); @@ -203,13 +209,15 @@ public void configureNatures(Project project, ProjectDescription oldDescription, String[] ordered = null; if (deletions.size() > 0) { ordered = sortNatureSet(deletions.toArray(new String[deletions.size()])); - for (int i = ordered.length; --i >= 0;) + for (int i = ordered.length; --i >= 0;) { deconfigureNature(project, ordered[i], status); + } } if (additions.size() > 0) { ordered = sortNatureSet(additions.toArray(new String[additions.size()])); - for (String element : ordered) + for (String element : ordered) { configureNature(project, element, status); + } } } @@ -229,9 +237,11 @@ protected IProjectNature createNature(Project project, String natureID) throws C } //find the runtime configuration element IConfigurationElement config = null; - for (int i = 0; config == null && i < configs.length; i++) - if ("runtime".equalsIgnoreCase(configs[i].getName())) //$NON-NLS-1$ + for (int i = 0; config == null && i < configs.length; i++) { + if ("runtime".equalsIgnoreCase(configs[i].getName())) { //$NON-NLS-1$ config = configs[i]; + } + } if (config == null) { String message = NLS.bind(Messages.resources_natureFormat, natureID); throw new ResourceException(Platform.PLUGIN_ERROR, project.getFullPath(), message, null); @@ -271,10 +281,11 @@ public void run() throws Exception { @Override public void handleException(Throwable exception) { - if (exception instanceof CoreException) + if (exception instanceof CoreException) { status.add(((CoreException) exception).getStatus()); - else + } else { status.add(new ResourceStatus(IResourceStatus.INTERNAL_ERROR, project.getFullPath(), NLS.bind(Messages.resources_natureDeconfig, natureID), exception)); + } } }; if (Policy.DEBUG_NATURES) { @@ -289,9 +300,11 @@ public void handleException(Throwable exception) { private void detectCycles() { Collection values = descriptors.values(); ProjectNatureDescriptor[] natures = values.toArray(new ProjectNatureDescriptor[values.size()]); - for (ProjectNatureDescriptor nature : natures) - if (nature.colour == WHITE) + for (ProjectNatureDescriptor nature : natures) { + if (nature.colour == WHITE) { hasCycles(nature); + } + } } /** @@ -331,8 +344,9 @@ private synchronized void flushEnablements(IProject project) { */ protected synchronized String[] getEnabledNatures(Project project) { String[] enabled = natureEnablements.get(project); - if (enabled != null) + if (enabled != null) { return enabled; + } enabled = computeNatureEnablements(project); natureEnablements.put(project, enabled); return enabled; @@ -379,9 +393,11 @@ protected boolean hasCycles(ProjectNatureDescriptor desc) { protected boolean hasLinks(IProject project) { try { IResource[] children = project.members(); - for (IResource element : children) - if (element.isLinked()) + for (IResource element : children) { + if (element.isLinked()) { return true; + } + } } catch (CoreException e) { //not possible for project to be inaccessible Policy.log(e.getStatus()); @@ -415,15 +431,17 @@ protected String hasSetOverlap(IProjectNatureDescriptor one, IProjectNatureDescr * Perform depth-first insertion of the given nature ID into the result list. */ protected void insert(ArrayList list, Set seen, String id) { - if (seen.contains(id)) + if (seen.contains(id)) { return; + } seen.add(id); //insert prerequisite natures IProjectNatureDescriptor desc = getNatureDescriptor(id); if (desc != null) { String[] prereqs = desc.getRequiredNatureIds(); - for (String prereq : prereqs) + for (String prereq : prereqs) { insert(list, seen, prereq); + } } list.add(id); } @@ -436,8 +454,9 @@ protected void insert(ArrayList list, Set seen, String id) { public boolean isNatureEnabled(Project project, String id) { String[] enabled = getEnabledNatures(project); for (String element : enabled) { - if (element.equals(id)) + if (element.equals(id)) { return true; + } } return false; } @@ -447,8 +466,9 @@ public boolean isNatureEnabled(Project project, String id) { * Running programs may never need to refer to this cache. */ private void lazyInitialize() { - if (descriptors != null) + if (descriptors != null) { return; + } IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_NATURES); IExtension[] extensions = point.getExtensions(); descriptors = new HashMap<>(extensions.length * 2 + 1); @@ -459,8 +479,9 @@ private void lazyInitialize() { } catch (CoreException e) { Policy.log(e.getStatus()); } - if (desc != null) + if (desc != null) { descriptors.put(desc.getNatureId(), desc); + } } //do cycle detection now so it only has to be done once //cycle detection on a graph subset is a pain @@ -477,19 +498,22 @@ public void shutdown(IProgressMonitor monitor) { */ public String[] sortNatureSet(String[] natureIds) { int count = natureIds.length; - if (count == 0) + if (count == 0) { return natureIds; + } ArrayList result = new ArrayList<>(count); HashSet seen = new HashSet<>(count);//for cycle and duplicate detection - for (int i = 0; i < count; i++) + for (int i = 0; i < count; i++) { insert(result, seen, natureIds[i]); + } //remove added prerequisites that didn't exist in original list seen.clear(); seen.addAll(Arrays.asList(natureIds)); for (Iterator it = result.iterator(); it.hasNext();) { Object id = it.next(); - if (!seen.contains(id)) + if (!seen.contains(id)) { it.remove(); + } } return result.toArray(new String[result.size()]); } @@ -543,8 +567,9 @@ protected IStatus validateAdditions(HashSet newNatures, HashSet if (hasLinks == null) { hasLinks = hasLinks(project) ? Boolean.TRUE : Boolean.FALSE; } - if (hasLinks.booleanValue()) + if (hasLinks.booleanValue()) { return failure(NLS.bind(Messages.links_vetoNature, project.getName(), id)); + } } } return Status.OK_STATUS; @@ -600,8 +625,9 @@ protected IStatus validateRemovals(HashSet newNatures, HashSet d */ public IStatus validateNatureSet(String[] natureIds) { int count = natureIds.length; - if (count == 0) + if (count == 0) { return Status.OK_STATUS; + } String msg = Messages.natures_invalidSet; MultiStatus result = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INVALID_NATURE_SET, msg, null); @@ -616,10 +642,12 @@ public IStatus validateNatureSet(String[] natureIds) { result.add(failure(NLS.bind(Messages.natures_missingNature, id))); continue; } - if (desc.hasCycle) + if (desc.hasCycle) { result.add(failure(NLS.bind(Messages.natures_hasCycle, id))); - if (!natures.add(id)) + } + if (!natures.add(id)) { result.add(failure(NLS.bind(Messages.natures_duplicateNature, id))); + } //validate nature set one-of constraint String[] setIds = desc.getNatureSetIds(); for (String setId : setIds) { @@ -631,8 +659,9 @@ public IStatus validateNatureSet(String[] natureIds) { //now walk over the set and ensure all pre-requisite natures are present for (int i = 0; i < count; i++) { IProjectNatureDescriptor desc = getNatureDescriptor(natureIds[i]); - if (desc == null) + if (desc == null) { continue; + } String[] required = desc.getRequiredNatureIds(); for (String r : required) { if (!natures.contains(r)) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/OS.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/OS.java index 49be9167bc2..3b1e5ca99d8 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/OS.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/OS.java @@ -61,25 +61,30 @@ public abstract class OS { */ public static boolean isNameValid(String name) { //. and .. have special meaning on all platforms - if (name.equals(".") || name.equals("..")) //$NON-NLS-1$ //$NON-NLS-2$ + if (name.equals(".") || name.equals("..")) { //$NON-NLS-1$ //$NON-NLS-2$ return false; + } if (INSTALLED_PLATFORM.equals(Platform.OS_WIN32)) { //empty names are not valid final int length = name.length(); - if (length == 0) + if (length == 0) { return false; + } final char lastChar = name.charAt(length - 1); // filenames ending in dot are not valid - if (lastChar == '.') + if (lastChar == '.') { return false; + } // file names ending with whitespace are truncated (bug 118997) - if (Character.isWhitespace(lastChar)) + if (Character.isWhitespace(lastChar)) { return false; + } int dot = name.indexOf('.'); //on windows, filename suffixes are not relevant to name validity String basename = dot == -1 ? name : name.substring(0, dot); - if (Arrays.binarySearch(INVALID_RESOURCE_BASENAMES, basename.toLowerCase()) >= 0) + if (Arrays.binarySearch(INVALID_RESOURCE_BASENAMES, basename.toLowerCase()) >= 0) { return false; + } return Arrays.binarySearch(INVALID_RESOURCE_FULLNAMES, name.toLowerCase()) < 0; } return true; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PathVariableManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PathVariableManager.java index 2db2d105407..e1f3bb32c74 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PathVariableManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PathVariableManager.java @@ -88,8 +88,9 @@ synchronized public void addChangeListener(IPathVariableChangeListener listener, */ private void checkIsValidName(String name) throws CoreException { IStatus status = validateName(name); - if (!status.isOK()) + if (!status.isOK()) { throw new CoreException(status); + } } /** @@ -98,8 +99,9 @@ private void checkIsValidName(String name) throws CoreException { */ private void checkIsValidValue(IPath newValue) throws CoreException { IStatus status = validateValue(newValue); - if (!status.isOK()) + if (!status.isOK()) { throw new CoreException(status); + } } /** @@ -123,8 +125,9 @@ private void fireVariableChangeEvent(String name, IPath value, int type) { } private void fireVariableChangeEvent(Collection list, String name, IPath value, int type) { - if (list.isEmpty()) + if (list.isEmpty()) { return; + } // use a separate collection to avoid interference of simultaneous additions/removals IPathVariableChangeListener[] listenerArray = list.toArray(new IPathVariableChangeListener[list.size()]); final PathVariableChangeEvent pve = new PathVariableChangeEvent(this, name, value, type); @@ -146,8 +149,9 @@ public void run() throws Exception { public void fireVariableChangeEvent(IProject project, String name, IPath value, int type) { Collection list = projectListeners.get(project); - if (list != null) + if (list != null) { fireVariableChangeEvent(list, name, value, type); + } } /** @@ -174,8 +178,9 @@ public String[] getPathVariableNames() { // reserved to path variables (#VARIABLE_PREFIX). // TODO: we may want to look at removing these keys from the // preference store as a garbage collection means - if (validateName(key).isOK() && validateValue(getValue(key)).isOK()) + if (validateName(key).isOK() && validateValue(getValue(key)).isOK()) { result.add(key); + } } } return result.toArray(new String[result.size()]); @@ -217,8 +222,9 @@ synchronized public void removeChangeListener(IPathVariableChangeListener listen Collection list = projectListeners.get(project); if (list != null) { list.remove(listener); - if (list.isEmpty()) + if (list.isEmpty()) { projectListeners.remove(project); + } } } @@ -228,16 +234,18 @@ synchronized public void removeChangeListener(IPathVariableChangeListener listen @Deprecated @Override public IPath resolvePath(IPath path) { - if (path == null || path.segmentCount() == 0 || path.isAbsolute() || path.getDevice() != null) + if (path == null || path.segmentCount() == 0 || path.isAbsolute() || path.getDevice() != null) { return path; + } IPath value = getValue(path.segment(0)); return value == null ? path : value.append(path.removeFirstSegments(1)); } @Override public URI resolveURI(URI uri) { - if (uri == null || uri.isAbsolute()) + if (uri == null || uri.isAbsolute()) { return uri; + } String schemeSpecificPart = uri.getSchemeSpecificPart(); if (schemeSpecificPart == null || schemeSpecificPart.isEmpty()) { return uri; @@ -254,18 +262,21 @@ public URI resolveURI(URI uri) { public void setValue(String varName, IPath newValue) throws CoreException { checkIsValidName(varName); //convert path value to canonical form - if (newValue != null && newValue.isAbsolute()) + if (newValue != null && newValue.isAbsolute()) { newValue = FileUtil.canonicalPath(newValue); + } checkIsValidValue(newValue); int eventType; // read previous value and set new value atomically in order to generate the right event synchronized (this) { IPath currentValue = getValue(varName); boolean variableExists = currentValue != null; - if (!variableExists && newValue == null) + if (!variableExists && newValue == null) { return; - if (variableExists && currentValue.equals(newValue)) + } + if (variableExists && currentValue.equals(newValue)) { return; + } if (newValue == null) { preferences.setToDefault(getKeyForName(varName)); eventType = IPathVariableChangeEvent.VARIABLE_DELETED; @@ -315,8 +326,9 @@ public IStatus validateName(String name) { for (int i = 1; i < name.length(); i++) { char following = name.charAt(i); - if (Character.isWhitespace(following)) + if (Character.isWhitespace(following)) { return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, Messages.pathvar_whitespace); + } if (!Character.isLetter(following) && !Character.isDigit(following) && following != '_') { message = NLS.bind(Messages.pathvar_invalidChar, String.valueOf(following)); return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); @@ -351,8 +363,9 @@ public URI convertToRelative(URI path, boolean force, String variableHint) throw @Override public URI getURIValue(String name) { IPath path = getValue(name); - if (path != null) + if (path != null) { return URIUtil.toURI(path); + } return null; } @@ -384,8 +397,9 @@ public String[] getPathVariableNames(IResource resource) { public URI getVariableRelativePathLocation(URI location) { try { URI result = convertToRelative(location, false, null); - if (!result.equals(location)) + if (!result.equals(location)) { return result; + } } catch (CoreException e) { // handled by returning null } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PathVariableUtil.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PathVariableUtil.java index 2d0789b9734..e11ebfab2fa 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PathVariableUtil.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PathVariableUtil.java @@ -38,8 +38,9 @@ static public String getUniqueVariableName(String variable, IResource resource) StringBuilder destVariable = new StringBuilder(variable); IPathVariableManager pathVariableManager = resource.getPathVariableManager(); - if (variable.startsWith(ParentVariableResolver.NAME) || variable.startsWith(ProjectLocationVariableResolver.NAME)) + if (variable.startsWith(ParentVariableResolver.NAME) || variable.startsWith(ProjectLocationVariableResolver.NAME)) { destVariable.insert(0, "copy_"); //$NON-NLS-1$ + } while (pathVariableManager.isDefined(destVariable.toString())) { destVariable.append(index); @@ -51,8 +52,9 @@ static public String getUniqueVariableName(String variable, IResource resource) public static String getValidVariableName(String variable) { // remove the argument part if the variable is of the form ${VAR-ARG} int argumentIndex = variable.indexOf('-'); - if (argumentIndex != -1) + if (argumentIndex != -1) { variable = variable.substring(0, argumentIndex); + } variable = variable.trim(); char first = variable.charAt(0); @@ -63,8 +65,9 @@ public static String getValidVariableName(String variable) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < variable.length(); i++) { char c = variable.charAt(i); - if ((Character.isLetter(c) || Character.isDigit(c) || c == '_') && !Character.isWhitespace(c)) + if ((Character.isLetter(c) || Character.isDigit(c) || c == '_') && !Character.isWhitespace(c)) { builder.append(c); + } } variable = builder.toString(); return variable; @@ -89,8 +92,9 @@ static public URI convertToRelative(IPathVariableManager pathVariableManager, UR static private IPath convertToRelative(IPathVariableManager pathVariableManager, IPath originalPath, IResource resource, boolean force, String variableHint, boolean skipWorkspace, boolean generateMacro) throws CoreException { if (variableHint != null && pathVariableManager.isDefined(variableHint)) { IPath value = URIUtil.toPath(pathVariableManager.getURIValue(variableHint)); - if (value != null) + if (value != null) { return wrapInProperFormat(makeRelativeToVariable(pathVariableManager, originalPath, force, variableHint), generateMacro); + } } IPath path = convertToProperCase(originalPath); IPath newPath = null; @@ -100,13 +104,16 @@ static private IPath convertToRelative(IPathVariableManager pathVariableManager, if (skipWorkspace) { // Variables relative to the workspace are not portable, and defeat the purpose of having linked resource locations, // so they should not automatically be created relative to the workspace. - if (variable.equals(WorkspaceLocationVariableResolver.NAME)) + if (variable.equals(WorkspaceLocationVariableResolver.NAME)) { continue; + } } - if (variable.equals(WorkspaceParentLocationVariableResolver.NAME)) + if (variable.equals(WorkspaceParentLocationVariableResolver.NAME)) { continue; - if (variable.equals(ParentVariableResolver.NAME)) + } + if (variable.equals(ParentVariableResolver.NAME)) { continue; + } // find closest path to the original path IPath value = URIUtil.toPath(pathVariableManager.getURIValue(variable)); if (value != null) { @@ -120,8 +127,9 @@ static private IPath convertToRelative(IPathVariableManager pathVariableManager, } } } - if (newPath != null) + if (newPath != null) { return wrapInProperFormat(newPath, generateMacro); + } if (force) { int originalSegmentCount = originalPath.segmentCount(); @@ -130,13 +138,16 @@ static private IPath convertToRelative(IPathVariableManager pathVariableManager, int minDifference = Integer.MAX_VALUE; for (String variable : existingVariables) { if (skipWorkspace) { - if (variable.equals(WorkspaceLocationVariableResolver.NAME)) + if (variable.equals(WorkspaceLocationVariableResolver.NAME)) { continue; + } } - if (variable.equals(WorkspaceParentLocationVariableResolver.NAME)) + if (variable.equals(WorkspaceParentLocationVariableResolver.NAME)) { continue; - if (variable.equals(ParentVariableResolver.NAME)) + } + if (variable.equals(ParentVariableResolver.NAME)) { continue; + } IPath value = URIUtil.toPath(pathVariableManager.getURIValue(variable)); if (value != null) { value = convertToProperCase(URIUtil.toPath(pathVariableManager.resolveURI(URIUtil.toURI(value)))); @@ -149,28 +160,33 @@ static private IPath convertToRelative(IPathVariableManager pathVariableManager, } } } - if (newPath != null) + if (newPath != null) { return wrapInProperFormat(newPath, generateMacro); + } } if (originalSegmentCount == 0) { String variable = ProjectLocationVariableResolver.NAME; IPath value = URIUtil.toPath(pathVariableManager.getURIValue(variable)); value = convertToProperCase(URIUtil.toPath(pathVariableManager.resolveURI(URIUtil.toURI(value)))); - if (originalPath.isPrefixOf(value)) + if (originalPath.isPrefixOf(value)) { newPath = makeRelativeToVariable(pathVariableManager, originalPath, force, variable); - if (newPath != null) + } + if (newPath != null) { return wrapInProperFormat(newPath, generateMacro); + } } } - if (skipWorkspace) + if (skipWorkspace) { return convertToRelative(pathVariableManager, originalPath, resource, force, variableHint, false, generateMacro); + } return originalPath; } private static IPath wrapInProperFormat(IPath newPath, boolean generateMacro) { - if (generateMacro) + if (generateMacro) { newPath = PathVariableUtil.buildVariableMacro(newPath); + } return newPath; } @@ -210,8 +226,9 @@ private static boolean devicesAreCompatible(IPath path, IPath value) { } static private IPath convertToProperCase(IPath path) { - if (Platform.getOS().equals(Platform.OS_WIN32)) + if (Platform.getOS().equals(Platform.OS_WIN32)) { return IPath.fromPortableString(path.toPortableString().toLowerCase()); + } return path; } @@ -236,16 +253,18 @@ static public int getParentVariableCount(String variableString) { // the format is PARENT-COUNT-ARGUMENT static public String getParentVariableArgument(String variableString) { String items[] = variableString.split("-"); //$NON-NLS-1$ - if (items.length == 3) + if (items.length == 3) { return items[2]; + } return null; } static public String buildParentPathVariable(String variable, int difference, boolean generateMacro) { String newString = ParentVariableResolver.NAME + "-" + difference + "-" + variable; //$NON-NLS-1$//$NON-NLS-2$ - if (!generateMacro) + if (!generateMacro) { newString = "${" + newString + "}"; //$NON-NLS-1$//$NON-NLS-2$ + } return newString; } @@ -257,12 +276,14 @@ public static IPath buildVariableMacro(IPath relativeSrcValue) { public static String convertFromUserEditableFormatInternal(IPathVariableManager manager, String userFormat, boolean locationFormat) { char pathPrefix = 0; - if ((userFormat.length() > 0) && (userFormat.charAt(0) == '/' || userFormat.charAt(0) == '\\')) + if ((userFormat.length() > 0) && (userFormat.charAt(0) == '/' || userFormat.charAt(0) == '\\')) { pathPrefix = userFormat.charAt(0); + } String components[] = splitPathComponents(userFormat); for (int i = 0; i < components.length; i++) { - if (components[i] == null) + if (components[i] == null) { continue; + } if (isDotDot(components[i])) { int parentCount = 1; components[i] = null; @@ -271,18 +292,21 @@ public static String convertFromUserEditableFormatInternal(IPathVariableManager if (isDotDot(components[j])) { parentCount++; components[j] = null; - } else + } else { break; + } } } - if (i == 0) // this means the value is implicitly relative to the project location + if (i == 0) { // this means the value is implicitly relative to the project location components[0] = PathVariableUtil.buildParentPathVariable(ProjectLocationVariableResolver.NAME, parentCount, false); - else { + } else { for (int j = i - 1; j >= 0; j--) { - if (parentCount == 0) + if (parentCount == 0) { break; - if (components[j] == null) + } + if (components[j] == null) { continue; + } String variable = extractVariable(components[j]); boolean hasVariableWithMacroSyntax = true; @@ -309,12 +333,14 @@ public static String convertFromUserEditableFormatInternal(IPathVariableManager String originalIntermediateVariableName = intermediateVariable; while (manager.isDefined(intermediateVariable)) { IPath tmpValue = URIUtil.toPath(manager.getURIValue(intermediateVariable)); - if (tmpValue.equals(intermediateValue)) + if (tmpValue.equals(intermediateValue)) { break; + } intermediateVariable = originalIntermediateVariableName + intermediateVariableIndex; } - if (!manager.isDefined(intermediateVariable)) + if (!manager.isDefined(intermediateVariable)) { manager.setURIValue(intermediateVariable, URIUtil.toURI(intermediateValue)); + } variable = intermediateVariable; prefix = ""; //$NON-NLS-1$ } @@ -323,12 +349,14 @@ public static String convertFromUserEditableFormatInternal(IPathVariableManager if (PathVariableUtil.isParentVariable(variable)) { String argument = PathVariableUtil.getParentVariableArgument(variable); int count = PathVariableUtil.getParentVariableCount(variable); - if (argument != null && count != -1) + if (argument != null && count != -1) { newVariable = PathVariableUtil.buildParentPathVariable(argument, count + parentCount, locationFormat); - else + } else { newVariable = PathVariableUtil.buildParentPathVariable(variable, parentCount, locationFormat); - } else + } + } else { newVariable = PathVariableUtil.buildParentPathVariable(variable, parentCount, locationFormat); + } components[j] = prefix + newVariable; break; } @@ -343,12 +371,14 @@ public static String convertFromUserEditableFormatInternal(IPathVariableManager } } StringBuilder buffer = new StringBuilder(); - if (pathPrefix != 0) + if (pathPrefix != 0) { buffer.append(pathPrefix); + } for (int i = 0; i < components.length; i++) { if (components[i] != null) { - if (i > 0) + if (i > 0) { buffer.append(java.io.File.separator); + } buffer.append(components[i]); } } @@ -365,14 +395,17 @@ private static String[] splitPathComponents(String userFormat) { for (int i = 0; i < userFormat.length(); i++) { char c = userFormat.charAt(i); if (c == '/' || c == '\\') { - if (buffer.length() > 0) + if (buffer.length() > 0) { list.add(buffer.toString()); + } buffer = new StringBuilder(); - } else + } else { buffer.append(c); + } } - if (buffer.length() > 0) + if (buffer.length() > 0) { list.add(buffer.toString()); + } return list.toArray(new String[0]); } @@ -380,13 +413,15 @@ public static String convertToUserEditableFormatInternal(String value, boolean l StringBuilder buffer = new StringBuilder(); if (locationFormat) { IPath path = IPath.fromOSString(value); - if (path.isAbsolute()) + if (path.isAbsolute()) { return path.toOSString(); + } int index = value.indexOf(java.io.File.separator); String variable = index != -1 ? value.substring(0, index) : value; convertVariableToUserFormat(buffer, variable, variable, false); - if (index != -1) + if (index != -1) { buffer.append(value.substring(index)); + } } else { String components[] = splitVariablesAndContent(value); for (String component : components) { @@ -407,10 +442,12 @@ private static void convertVariableToUserFormat(StringBuilder buffer, String com for (int j = 0; j < count; j++) { buffer.append(java.io.File.separator + ".."); //$NON-NLS-1$ } - } else + } else { buffer.append(component); - } else + } + } else { buffer.append(component); + } } /* @@ -428,15 +465,18 @@ static String[] splitVariablesAndContent(String value) { int index = value.indexOf("${"); //$NON-NLS-1$ if (index != -1) { int endIndex = getMatchingBrace(value, index); - if (index > 0) + if (index > 0) { result.add(value.substring(0, index)); + } result.add(value.substring(index, endIndex + 1)); value = value.substring(endIndex + 1); - } else + } else { break; + } } - if (value.length() > 0) + if (value.length() > 0) { result.add(value); + } return result.toArray(new String[0]); } @@ -457,8 +497,9 @@ static String[] splitVariableNames(String value) { int endIndex = getMatchingBrace(value, index); result.add(value.substring(index + 2, endIndex)); value = value.substring(endIndex + 1); - } else + } else { break; + } } return result.toArray(new String[0]); } @@ -487,13 +528,15 @@ static int getMatchingBrace(String value, int index) { for (int i = index + 1; i < value.length(); i++) { char c = value.charAt(i); if (c == '}') { - if (scope == 0) + if (scope == 0) { return i; + } scope--; } if (c == '$') { - if ((i + 1 < value.length()) && (value.charAt(i + 1) == '{')) + if ((i + 1 < value.length()) && (value.charAt(i + 1) == '{')) { scope++; + } } } return value.length(); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PlatformURLResourceConnection.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PlatformURLResourceConnection.java index f54bac54b02..f9ce9ee1f38 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PlatformURLResourceConnection.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/PlatformURLResourceConnection.java @@ -53,12 +53,14 @@ protected URL resolve() throws IOException { String filePath = url.getFile().trim(); filePath = URLDecoder.decode(filePath, StandardCharsets.UTF_8); IPath spec = IPath.fromOSString(filePath).makeRelative(); - if (!spec.segment(0).equals(RESOURCE)) + if (!spec.segment(0).equals(RESOURCE)) { throw new IOException(NLS.bind(Messages.url_badVariant, url)); + } int count = spec.segmentCount(); // if there is only one segment then we are talking about the workspace root. - if (count == 1) + if (count == 1) { return rootURL; + } // if there are two segments then the second is a project name. IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(spec.segment(1)); if (!project.exists()) { @@ -81,8 +83,9 @@ protected URL resolve() throws IOException { if (uri != null) { try { URL url2 = uri.toURL(); - if (url2.getProtocol().equals("file")) //$NON-NLS-1$ + if (url2.getProtocol().equals("file")) { //$NON-NLS-1$ return url2; + } } catch (MalformedURLException e) { String message = NLS.bind(Messages.url_couldNotResolve_URLProtocolHandlerCanNotResolveURL, uri.toString(), url.toExternalForm()); throw new IOException(message); @@ -101,8 +104,9 @@ protected URL resolve() throws IOException { */ public static void startup(IPath root) { // register connection type for platform:/resource/ handling - if (rootURL != null) + if (rootURL != null) { return; + } try { rootURL = root.toFile().toURL(); } catch (MalformedURLException e) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Project.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Project.java index 99600609b46..3df936f2214 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Project.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Project.java @@ -94,8 +94,9 @@ protected void assertCreateRequirements(IProjectDescription description) throws checkDoesNotExist(); checkDescription(this, description, false); URI location = description.getLocationURI(); - if (location != null) + if (location != null) { return; + } //if the project is in the default location, need to check for collision with existing folder of different case if (!Workspace.caseSensitive) { IFileStore store = getStore(); @@ -136,29 +137,33 @@ protected MultiStatus basicSetDescription(ProjectDescription description, int up // Update the dynamic state flushOrder |= current.updateDynamicState(description); - if (flushOrder) + if (flushOrder) { workspace.flushBuildOrder(); + } // the natures last as this may cause recursive calls to setDescription. - if ((updateFlags & IResource.AVOID_NATURE_CONFIG) == 0) + if ((updateFlags & IResource.AVOID_NATURE_CONFIG) == 0) { workspace.getNatureManager().configureNatures(this, current, description, result); - else + } else { current.setNatureIds(description.getNatureIds(false)); + } return result; } @Override public void build(int trigger, IProgressMonitor monitor) throws CoreException { - if (!isAccessible()) + if (!isAccessible()) { return; + } internalBuild(getActiveBuildConfig(), trigger, null, null, monitor); } @Override public void build(int trigger, String builderName, Map args, IProgressMonitor monitor) throws CoreException { Assert.isNotNull(builderName); - if (!isAccessible()) + if (!isAccessible()) { return; + } internalBuild(getActiveBuildConfig(), trigger, builderName, args, monitor); } @@ -166,8 +171,9 @@ public void build(int trigger, String builderName, Map args, IPr public void build(IBuildConfiguration config, int trigger, IProgressMonitor monitor) throws CoreException { Assert.isNotNull(config); // If project isn't accessible, or doesn't contain the build configuration, nothing to do. - if (!isAccessible() || !hasBuildConfig(config.getName())) + if (!isAccessible() || !hasBuildConfig(config.getName())) { return; + } internalBuild(config, trigger, null, null, monitor); } @@ -202,13 +208,16 @@ protected void checkDescription(IProject project, IProjectDescription desc, bool // is null (we are using the default) or if the locations aren't equal, then validate the location // of the new description. Otherwise both locations aren't null and they are equal so ignore validation. URI sourceLocation = internalGetDescription().getLocationURI(); - if (sourceLocation == null || !sourceLocation.equals(location)) + if (sourceLocation == null || !sourceLocation.equals(location)) { status.merge(workspace.validateProjectLocationURI(project, location)); - } else + } + } else { // otherwise continue on like before status.merge(workspace.validateProjectLocationURI(project, location)); - if (!status.isOK()) + } + if (!status.isOK()) { throw new ResourceException(status); + } } @Override @@ -223,8 +232,9 @@ public void close(IProgressMonitor monitor) throws CoreException { int flags = getFlags(info); checkExists(flags, true); subMonitor.subTask(msg); - if (!isOpen(flags)) + if (!isOpen(flags)) { return; + } // Signal that this resource is about to be closed. Do this at the very // beginning so that infrastructure pieces have a chance to do clean up // while the resources still exist. @@ -235,8 +245,9 @@ public void close(IProgressMonitor monitor) throws CoreException { IProgressMonitor sub = subMonitor.newChild(49, SubMonitor.SUPPRESS_SUBTASK); IStatus saveStatus = workspace.getSaveManager().save(ISaveContext.PROJECT_SAVE, this, sub); internalClose(subMonitor.newChild(49)); - if (saveStatus != null && !saveStatus.isOK()) + if (saveStatus != null && !saveStatus.isOK()) { throw new ResourceException(saveStatus); + } } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; @@ -318,8 +329,9 @@ public void create(IProjectDescription description, int updateFlags, IProgressMo final boolean hasSavedDescription = getLocalManager().hasSavedDescription(this); boolean hasContent = hasSavedDescription; // if there is no project description, there might still be content on disk - if (!hasSavedDescription) + if (!hasSavedDescription) { hasContent = getLocalManager().hasSavedContent(this); + } try { // look for a description on disk if (hasSavedDescription) { @@ -340,8 +352,9 @@ public void create(IProjectDescription description, int updateFlags, IProgressMo info.clearModificationStamp(); // if a project already had content on disk, mark the project as having unknown // children - if (hasContent) + if (hasContent) { info.set(ICoreConstants.M_CHILDREN_UNKNOWN); + } workspace.getSaveManager().requestSnapshot(); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); @@ -391,8 +404,9 @@ public IBuildConfiguration getActiveBuildConfig() throws CoreException { @Override public IBuildConfiguration getBuildConfig(String configName) throws CoreException { - if (configName == null) + if (configName == null) { return getActiveBuildConfig(); + } ProjectInfo info = (ProjectInfo) getResourceInfo(false, false); checkAccessible(getFlags(info)); IBuildConfiguration[] configs = internalGetBuildConfigs(false); @@ -419,8 +433,9 @@ public IContentTypeMatcher getContentTypeMatcher() throws CoreException { @Override public String getDefaultCharset(boolean checkImplicit) { // non-existing resources default to parent's charset - if (!exists()) + if (!exists()) { return checkImplicit ? ResourcesPlugin.getEncoding() : null; + } return workspace.getCharsetManager().getCharsetFor(getFullPath(), checkImplicit); } @@ -430,8 +445,9 @@ public IProjectDescription getDescription() throws CoreException { checkAccessible(getFlags(info)); ProjectDescription description = ((ProjectInfo) info).getDescription(); //if the project is currently in the middle of being created, the description might not be available yet - if (description == null) + if (description == null) { checkAccessible(NULL_FLAG); + } return (IProjectDescription) description.clone(); } @@ -443,8 +459,9 @@ public IProjectNature getNature(String natureID) throws CoreException { IProjectNature nature = info.getNature(natureID); if (nature == null) { // Not initialized yet. Does this project have the nature? - if (!hasNature(natureID)) + if (!hasNature(natureID)) { return null; + } nature = workspace.getNatureManager().createNature(this, natureID); info.setNature(natureID, nature); } @@ -484,10 +501,12 @@ public IBuildConfiguration[] getReferencedBuildConfigs(String configName, boolea checkAccessible(getFlags(info)); ProjectDescription description = ((ProjectInfo) info).getDescription(); //if the project is currently in the middle of being created, the description might not be available yet - if (description == null) + if (description == null) { checkAccessible(NULL_FLAG); - if (!hasBuildConfig(configName)) + } + if (!hasBuildConfig(configName)) { throw new ResourceException(IResourceStatus.BUILD_CONFIGURATION_NOT_FOUND, getFullPath(), null, null); + } return internalGetReferencedBuildConfigs(configName, includeMissing); } @@ -497,8 +516,9 @@ public IProject[] getReferencedProjects() throws CoreException { checkAccessible(getFlags(info)); ProjectDescription description = ((ProjectInfo) info).getDescription(); //if the project is currently in the middle of being created, the description might not be available yet - if (description == null) + if (description == null) { checkAccessible(NULL_FLAG); + } return description.getAllReferences(this, true); } @@ -523,17 +543,20 @@ public IProject[] getReferencingProjects() { List result = new ArrayList<>(projects.length); for (IProject p : projects) { Project project = (Project) p; - if (!project.isAccessible()) + if (!project.isAccessible()) { continue; + } ProjectDescription description = project.internalGetDescription(); - if (description == null) + if (description == null) { continue; + } IProject[] references = description.getAllReferences(project, false); - for (IProject reference : references) + for (IProject reference : references) { if (reference.equals(this)) { result.add(project); break; } + } } return result.toArray(new IProject[result.size()]); } @@ -545,8 +568,9 @@ public int getType() { @Override public IPath getWorkingLocation(String id) { - if (id == null || !exists()) + if (id == null || !exists()) { return null; + } IPath result = workspace.getMetaArea().getWorkingLocation(this, id); result.toFile().mkdirs(); return result; @@ -565,8 +589,9 @@ public boolean hasNature(String natureID) throws CoreException { // use #internal method to avoid copy but still throw an // exception if the resource doesn't exist. IProjectDescription desc = internalGetDescription(); - if (desc == null) + if (desc == null) { checkAccessible(NULL_FLAG); + } return desc.hasNature(natureID); } @@ -589,8 +614,9 @@ public void run(IProgressMonitor innerMonitor) throws CoreException { try { try { workspace.prepareOperation(notificationsRule, innerMonitor); - if (!shouldBuild()) + if (!shouldBuild()) { return; + } workspace.beginOperation(true); workspace.aboutToBuild(Project.this, trigger); } finally { @@ -603,8 +629,9 @@ public void run(IProgressMonitor innerMonitor) throws CoreException { workspace.beginOperation(false); result = workspace.getBuildManager().build(config, trigger, builderName, args, subMonitor.split(100)); - if (!result.isOK()) + if (!result.isOK()) { throw new ResourceException(result); + } } finally { workspace.endOperation(projectBuildRule, false); try { @@ -613,8 +640,9 @@ public void run(IProgressMonitor innerMonitor) throws CoreException { workspace.beginOperation(false); workspace.broadcastBuildEvent(Project.this, IResourceChangeEvent.POST_BUILD, trigger); // building may close the tree, so open it - if (workspace.getElementTree().isImmutable()) + if (workspace.getElementTree().isImmutable()) { workspace.newWorkingTree(); + } } finally { workspace.endOperation(notificationsRule, false); } @@ -741,8 +769,9 @@ protected void internalCopy(IProjectDescription destDesc, int updateFlags, IProg // refresh local monitor.subTask(Messages.resources_updating); getLocalManager().refresh(destination, DEPTH_INFINITE, true, Policy.subMonitorFor(monitor, Policy.opWork * 10 / 100)); - if (!problems.isOK()) + if (!problems.isOK()) { throw new ResourceException(problems); + } } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; @@ -789,8 +818,9 @@ protected void internalCopyProjectOnly(IResource destination, IProjectDescriptio IBuildConfiguration internalGetActiveBuildConfig() { String configName = internalGetDescription().activeConfiguration; try { - if (configName != null) + if (configName != null) { return getBuildConfig(configName); + } } catch (CoreException e) { // Build configuration doesn't exist; treat the first as active. } @@ -802,8 +832,9 @@ IBuildConfiguration internalGetActiveBuildConfig() { */ public IBuildConfiguration[] internalGetBuildConfigs(boolean makeCopy) { ProjectDescription desc = internalGetDescription(); - if (desc == null) + if (desc == null) { return new IBuildConfiguration[] {new BuildConfiguration(this, IBuildConfiguration.DEFAULT_CONFIG_NAME)}; + } return desc.getBuildConfigs(this, makeCopy); } @@ -815,8 +846,9 @@ public IBuildConfiguration[] internalGetBuildConfigs(boolean makeCopy) { */ public ProjectDescription internalGetDescription() { ProjectInfo info = (ProjectInfo) getResourceInfo(false, false); - if (info == null) + if (info == null) { return null; + } return info.getDescription(); } @@ -836,8 +868,9 @@ public IBuildConfiguration[] internalGetReferencedBuildConfigs(String configName // The project isn't accessible, or the build configuration doesn't exist // on the project. If requested return the full set of build references which may // be useful to API consumers - if (includeMissing) + if (includeMissing) { configs.add(ref); + } } } return configs.toArray(new IBuildConfiguration[configs.size()]); @@ -871,23 +904,27 @@ void internalSetDescription(IProjectDescription value, boolean incrementContentI if (incrementContentId) { info.incrementContentId(); //if the project is not accessible, stamp will be null and should remain null - if (info.getModificationStamp() != NULL_STAMP) + if (info.getModificationStamp() != NULL_STAMP) { workspace.updateModificationStamp(info); + } } } @Override public void internalSetLocal(boolean flag, int depth) throws CoreException { // do nothing for projects, but call for its children - if (depth == IResource.DEPTH_ZERO) + if (depth == IResource.DEPTH_ZERO) { return; - if (depth == IResource.DEPTH_ONE) + } + if (depth == IResource.DEPTH_ONE) { depth = IResource.DEPTH_ZERO; + } // get the children via the workspace since we know that this // resource exists (it is local). IResource[] children = getChildren(IResource.NONE); - for (IResource element : children) + for (IResource element : children) { ((Resource) element).internalSetLocal(flag, depth); + } } @Override @@ -927,16 +964,20 @@ public boolean isLocal(int depth) { @Override public boolean isLocal(int flags, int depth) { // don't check the flags....projects are always local - if (depth == DEPTH_ZERO) + if (depth == DEPTH_ZERO) { return true; - if (depth == DEPTH_ONE) + } + if (depth == DEPTH_ONE) { depth = DEPTH_ZERO; + } // get the children via the workspace since we know that this // resource exists (it is local). IResource[] children = getChildren(IResource.NONE); - for (IResource element : children) - if (!element.isLocal(depth)) + for (IResource element : children) { + if (!element.isLocal(depth)) { return false; + } + } return true; } @@ -1031,15 +1072,17 @@ public void move(IProjectDescription description, int updateFlags, IProgressMoni int depth = 0; try { depth = workManager.beginUnprotected(); - if (!hook.moveProject(tree, this, description, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork / 2))) + if (!hook.moveProject(tree, this, description, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork / 2))) { tree.standardMoveProject(this, description, updateFlags, Policy.subMonitorFor(monitor, Policy.opWork / 2)); + } } finally { workManager.endUnprotected(depth); } // Invalidate the tree for further use by clients. tree.makeInvalid(); - if (!tree.getStatus().isOK()) + if (!tree.getStatus().isOK()) { throw new ResourceException(tree.getStatus()); + } // make sure the move operation is remembered workspace.getSaveManager().requestSnapshot(); } catch (OperationCanceledException e) { @@ -1067,8 +1110,9 @@ public void open(int updateFlags, IProgressMonitor monitor) throws CoreException ProjectInfo info = (ProjectInfo) getResourceInfo(false, false); int flags = getFlags(info); checkExists(flags, true); - if (isOpen(flags)) + if (isOpen(flags)) { return; + } workspace.beginOperation(true); // flush the build order early in case there is a problem @@ -1077,8 +1121,9 @@ public void open(int updateFlags, IProgressMonitor monitor) throws CoreException info.set(M_OPEN); //clear the unknown children immediately to avoid background refresh boolean unknownChildren = info.isSet(M_CHILDREN_UNKNOWN); - if (unknownChildren) + if (unknownChildren) { info.clear(M_CHILDREN_UNKNOWN); + } // the M_USED flag is used to indicate the difference between opening a project // for the first time and opening it from a previous close (restoring it from disk) boolean used = info.isSet(M_USED); @@ -1111,8 +1156,9 @@ public void open(int updateFlags, IProgressMonitor monitor) throws CoreException info.set(M_USED); //reconcile any links and groups in the project description IStatus result = reconcileLinksAndGroups(info.getDescription()); - if (!result.isOK()) + if (!result.isOK()) { throw new CoreException(result); + } workspace.updateModificationStamp(info); monitor.worked(Policy.opWork * (snapshotLoaded ? 15 : 20) / 100); } @@ -1212,11 +1258,13 @@ public IStatus reconcileLinksAndGroups(ProjectDescription newDescription) { if (oldLinks != null) { for (LinkDescription oldLink : oldLinks.values()) { Resource oldLinkResource = (Resource) findMember(oldLink.getProjectRelativePath()); - if (oldLinkResource == null || !oldLinkResource.isLinked()) + if (oldLinkResource == null || !oldLinkResource.isLinked()) { continue; + } LinkDescription newLink = null; - if (newLinks != null) + if (newLinks != null) { newLink = newLinks.get(oldLink.getProjectRelativePath()); + } //if the new link is missing, or has different (raw) location or gender, then remove old link if (newLink == null || !newLink.getLocationURI().equals(oldLinkResource.getRawLocationURI()) || newLink.getType() != oldLinkResource.getType()) { try { @@ -1235,33 +1283,38 @@ public IStatus reconcileLinksAndGroups(ProjectDescription newDescription) { // so we don't have to create intermediate directories that would turn // out // to be groups or link folders. - if (newLinks == null) + if (newLinks == null) { return status; + } //sort links to avoid creating nested links before their parents TreeSet newLinksAndGroups = new TreeSet<>((arg0, arg1) -> { int numberOfSegments0 = arg0.getProjectRelativePath().segmentCount(); int numberOfSegments1 = arg1.getProjectRelativePath().segmentCount(); - if (numberOfSegments0 != numberOfSegments1) + if (numberOfSegments0 != numberOfSegments1) { return numberOfSegments0 - numberOfSegments1; - else if (arg0.equals(arg1)) + } else if (arg0.equals(arg1)) { return 0; + } return -1; }); - if (newLinks != null) + if (newLinks != null) { newLinksAndGroups.addAll(newLinks.values()); + } for (LinkDescription newLink : newLinksAndGroups) { try { Resource toLink = workspace.newResource(getFullPath().append(newLink.getProjectRelativePath()), newLink.getType()); IContainer parent = toLink.getParent(); - if (parent != null && !parent.exists() && parent.getType() == FOLDER) + if (parent != null && !parent.exists() && parent.getType() == FOLDER) { ((Folder) parent).ensureExists(Policy.monitorFor(null)); + } if (!toLink.exists() || !toLink.isLinked()) { - if (newLink.isGroup()) + if (newLink.isGroup()) { ((Folder) toLink).create(IResource.REPLACE | IResource.VIRTUAL, true, null); - else + } else { toLink.createLink(newLink.getLocationURI(), IResource.REPLACE | IResource.ALLOW_MISSING_LOCAL, null); + } } } catch (CoreException e) { status.merge(e.getStatus()); @@ -1317,10 +1370,11 @@ public void setDescription(IProjectDescription description, int updateFlags, IPr try { monitor.beginTask(Messages.resources_setDesc, Policy.totalWork); ISchedulingRule rule = null; - if ((updateFlags & IResource.AVOID_NATURE_CONFIG) != 0) + if ((updateFlags & IResource.AVOID_NATURE_CONFIG) != 0) { rule = workspace.getRuleFactory().modifyRule(this); - else + } else { rule = workspace.getRoot(); + } try { //need to use root rule because nature configuration calls third party code workspace.prepareOperation(rule, monitor); @@ -1331,8 +1385,9 @@ public void setDescription(IProjectDescription description, int updateFlags, IPr ProjectDescription newDescription = (ProjectDescription) description; boolean hasPublicChanges = oldDescription.hasPublicChanges(newDescription); boolean hasPrivateChanges = oldDescription.hasPrivateChanges(newDescription); - if (!hasPublicChanges && !hasPrivateChanges) + if (!hasPublicChanges && !hasPrivateChanges) { return; + } checkDescription(this, newDescription, false); //If we're out of sync and !FORCE, then fail. //If the file is missing, we want to write the new description then throw an exception. @@ -1345,12 +1400,14 @@ public void setDescription(IProjectDescription description, int updateFlags, IPr } } //see if we have an old .prj file - if (!hadSavedDescription) + if (!hadSavedDescription) { hadSavedDescription = workspace.getMetaArea().hasSavedProject(this); + } workspace.beginOperation(true); MultiStatus status = basicSetDescription(newDescription, updateFlags); - if (hadSavedDescription && !status.isOK()) + if (hadSavedDescription && !status.isOK()) { throw new CoreException(status); + } //write the new description to the .project file writeDescription(oldDescription, updateFlags, hasPublicChanges, hasPrivateChanges); //increment the content id even for private changes @@ -1361,8 +1418,9 @@ public void setDescription(IProjectDescription description, int updateFlags, IPr String msg = NLS.bind(Messages.resources_missingProjectMetaRepaired, getName()); status.merge(new ResourceStatus(IResourceStatus.MISSING_DESCRIPTION_REPAIRED, getFullPath(), msg)); } - if (!status.isOK()) + if (!status.isOK()) { throw new CoreException(status); + } } finally { workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.POST_PROJECT_CHANGE, this)); workspace.endOperation(rule, true); @@ -1385,8 +1443,9 @@ public void setDescription(IProjectDescription description, IProgressMonitor mon * the behaviour of open(). */ protected void startup() throws CoreException { - if (!isOpen()) + if (!isOpen()) { return; + } workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_PROJECT_OPEN, this)); } @@ -1422,18 +1481,21 @@ public void touch(IProgressMonitor monitor) throws CoreException { * description file contents. */ protected void updateDescription() throws CoreException { - if (ProjectDescription.isWriting) + if (ProjectDescription.isWriting) { return; + } ProjectDescription.isReading = true; try { ProjectDescription description = getLocalManager().read(this, false); //links can only be created if the project is open IStatus result = null; - if (isOpen()) + if (isOpen()) { result = reconcileLinksAndGroups(description); + } internalSetDescription(description, true); - if (result != null && !result.isOK()) + if (result != null && !result.isOK()) { throw new CoreException(result); + } } finally { workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.POST_PROJECT_CHANGE, this)); ProjectDescription.isReading = false; @@ -1459,8 +1521,9 @@ public void writeDescription(int updateFlags) throws CoreException { * @exception CoreException On failure to write the description */ public void writeDescription(IProjectDescription description, int updateFlags, boolean hasPublicChanges, boolean hasPrivateChanges) throws CoreException { - if (ProjectDescription.isReading) + if (ProjectDescription.isReading) { return; + } ProjectDescription.isWriting = true; try { getLocalManager().internalWrite(this, description, updateFlags, hasPublicChanges, hasPrivateChanges); @@ -1474,16 +1537,19 @@ public String getDefaultLineSeparator() { Preferences rootNode = Platform.getPreferencesService().getRootNode(); // if the file does not exist or has no content yet, try with project preference String value = getLineSeparatorFromPreferences(rootNode.node(ProjectScope.SCOPE).node(getProject().getName())); - if (value != null) + if (value != null) { return value; + } // try with instance preferences value = getLineSeparatorFromPreferences(rootNode.node(InstanceScope.SCOPE)); - if (value != null) + if (value != null) { return value; + } // try with default preferences value = getLineSeparatorFromPreferences(rootNode.node(DefaultScope.SCOPE)); - if (value != null) + if (value != null) { return value; + } // if there is no preference set, fall back to OS default value return System.lineSeparator(); } @@ -1491,8 +1557,9 @@ public String getDefaultLineSeparator() { private static String getLineSeparatorFromPreferences(Preferences node) { try { // be careful looking up for our node so not to create any nodes as side effect - if (node.nodeExists(Platform.PI_RUNTIME)) + if (node.nodeExists(Platform.PI_RUNTIME)) { return node.node(Platform.PI_RUNTIME).get(Platform.PREF_LINE_SEPARATOR, null); + } } catch (org.osgi.service.prefs.BackingStoreException e) { // ignore } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectContentTypes.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectContentTypes.java index f0cc75c2a82..f32e0297adc 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectContentTypes.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectContentTypes.java @@ -63,20 +63,23 @@ public ProjectContentTypeSelectionPolicy(Project project) { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (!(obj instanceof IScopeContext)) + } + if (!(obj instanceof IScopeContext other)) { return false; - IScopeContext other = (IScopeContext) obj; - if (!getName().equals(other.getName())) + } + if (!getName().equals(other.getName())) { return false; + } IPath location = getLocation(); return location == null ? other.getLocation() == null : location.equals(other.getLocation()); } private IScopeContext getDelegate() { - if (!usesContentTypePreferences(project.getName())) + if (!usesContentTypePreferences(project.getName())) { return InstanceScope.INSTANCE; + } return projectScope; } @@ -119,14 +122,17 @@ static boolean usesContentTypePreferences(String projectName) { Preferences node = PROJECT_SCOPE; //TODO once bug 90500 is fixed, should be simpler // for now, take the long way - if (!node.nodeExists(projectName)) + if (!node.nodeExists(projectName)) { return false; + } node = node.node(projectName); - if (!node.nodeExists(Platform.PI_RUNTIME)) + if (!node.nodeExists(Platform.PI_RUNTIME)) { return false; + } node = node.node(Platform.PI_RUNTIME); - if (!node.nodeExists(CONTENT_TYPE_PREF_NODE)) + if (!node.nodeExists(CONTENT_TYPE_PREF_NODE)) { return false; + } node = node.node(CONTENT_TYPE_PREF_NODE); return node.getBoolean(PREF_LOCAL_CONTENT_TYPE_SETTINGS, false); } catch (BackingStoreException | IllegalStateException | IllegalArgumentException e) { @@ -144,14 +150,16 @@ public ProjectContentTypes(Workspace workspace) { */ private Set collectAssociatedContentTypes(Project project) { String[] enabledNatures = workspace.getNatureManager().getEnabledNatures(project); - if (enabledNatures.length == 0) + if (enabledNatures.length == 0) { return Collections.EMPTY_SET; + } Set related = new HashSet<>(enabledNatures.length); for (String enabledNature : enabledNatures) { ProjectNatureDescriptor descriptor = (ProjectNatureDescriptor) workspace.getNatureDescriptor(enabledNature); - if (descriptor == null) + if (descriptor == null) { // no descriptor found for the nature, skip it continue; + } String[] natureContentTypes = descriptor.getContentTypeIds(); related.addAll(Arrays.asList(natureContentTypes)); // collect associate content types } @@ -160,8 +168,9 @@ private Set collectAssociatedContentTypes(Project project) { public void contentTypePreferencesChanged(IProject project) { final ProjectInfo info = (ProjectInfo) ((Project) project).getResourceInfo(false, false); - if (info != null) + if (info != null) { info.setMatcher(null); + } } /** @@ -174,9 +183,10 @@ private IContentTypeMatcher createMatcher(Project project) { private Set getAssociatedContentTypes(Project project) { final ResourceInfo info = project.getResourceInfo(false, false); - if (info == null) + if (info == null) { // the project has been deleted return null; + } final String projectName = project.getName(); synchronized (contentTypesPerProject) { Entry> entry = contentTypesPerProject.getEntry(projectName); @@ -195,11 +205,13 @@ private Set getAssociatedContentTypes(Project project) { public IContentTypeMatcher getMatcherFor(Project project) throws CoreException { ProjectInfo info = (ProjectInfo) project.getResourceInfo(false, false); //fail if project has been deleted concurrently - if (info == null) + if (info == null) { project.checkAccessible(project.getFlags(null)); + } IContentTypeMatcher matcher = info.getMatcher(); - if (matcher != null) + if (matcher != null) { return matcher; + } matcher = createMatcher(project); info.setMatcher(matcher); return matcher; @@ -218,27 +230,31 @@ public IContentTypeMatcher getMatcherFor(Project project) throws CoreException { */ final IContentType[] select(Project project, IContentType[] candidates, boolean fileName, boolean content) { // since no vetoing is done here, don't go further if there is nothing to sort - if (candidates.length < 2) + if (candidates.length < 2) { return candidates; + } final Set associated = getAssociatedContentTypes(project); - if (associated == null || associated.isEmpty()) + if (associated == null || associated.isEmpty()) { // project has no content types associated return candidates; + } int associatedCount = 0; - for (int i = 0; i < candidates.length; i++) + for (int i = 0; i < candidates.length; i++) { // is it an associated content type? if (associated.contains(candidates[i].getId())) { // need to move it to the right spot (unless all types visited so far are associated as well) if (associatedCount < i) { final IContentType promoted = candidates[i]; // move all non-associated content types before it one one position up... - for (int j = i; j > associatedCount; j--) + for (int j = i; j > associatedCount; j--) { candidates[j] = candidates[j - 1]; + } // ...so there is an empty spot for the content type we are promoting candidates[associatedCount] = promoted; } associatedCount++; } + } return candidates; } } \ No newline at end of file diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectDescription.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectDescription.java index 3502ac2f9a7..9c7894f9f4b 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectDescription.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectDescription.java @@ -136,8 +136,9 @@ public Object clone() { //don't want the clone to have access to our internal link locations table or builders clone.linkDescriptions = null; clone.filterDescriptions = null; - if (variableDescriptions != null) + if (variableDescriptions != null) { clone.variableDescriptions = (HashMap) variableDescriptions.clone(); + } clone.buildSpec = getBuildSpec(true); clone.dynamicConfigRefs = (HashMap) dynamicConfigRefs.clone(); clone.cachedConfigRefs = Collections.synchronizedMap(new HashMap<>(1)); @@ -151,10 +152,11 @@ public Object clone() { */ public void clearCachedDynamicReferences(String configName) { synchronized (cachedRefsMutex) { - if (configName == null) + if (configName == null) { cachedConfigRefs.clear(); - else + } else { cachedConfigRefs.remove(configName); + } cachedRefs = null; cachedRefsDirtyCount++; } @@ -176,9 +178,11 @@ private IProject[] copyAndRemoveDuplicates(IProject[] projects) { int count = 0; next: for (IProject project : projects) { // scan to see if there are any other projects by the same name - for (int j = 0; j < count; j++) - if (project.equals(result[j])) + for (int j = 0; j < count; j++) { + if (project.equals(result[j])) { continue next; + } + } // not found result[count++] = project; } @@ -201,8 +205,9 @@ private IProject[] copyAndRemoveDuplicates(IProject[] projects) { */ private Collection getBuildConfigReferencesFromProjects(IProject[] projects) { List refs = new ArrayList<>(projects.length); - for (IProject project : projects) + for (IProject project : projects) { refs.add(new BuildConfiguration(project, null)); + } return refs; } @@ -212,8 +217,9 @@ private Collection getBuildConfigReferencesFromProjects(IPro */ private Collection getProjectsFromBuildConfigRefs(IBuildConfiguration[] refs) { LinkedHashSet projects = new LinkedHashSet<>(refs.length); - for (IBuildConfiguration ref : refs) + for (IBuildConfiguration ref : refs) { projects.add(ref.getProject()); + } return projects; } @@ -240,13 +246,14 @@ public IProject[] getAllReferences(IProject project, boolean makeCopy) { // the time we invoke getAllBuildConfigReferences and the time we can write to cachedRefs. while (projRefs == null) { IBuildConfiguration[] refs; - if (hasBuildConfig(activeConfiguration)) + if (hasBuildConfig(activeConfiguration)) { refs = getAllBuildConfigReferences(project, activeConfiguration, false); - else if (configNames.length > 0) + } else if (configNames.length > 0) { refs = getAllBuildConfigReferences(project, configNames[0], false); - else + } else { // No build configuration => fall-back to default refs = getAllBuildConfigReferences(project, IBuildConfiguration.DEFAULT_CONFIG_NAME, false); + } Collection l = getProjectsFromBuildConfigRefs(refs); synchronized (cachedRefsMutex) { @@ -275,8 +282,9 @@ else if (configNames.length > 0) * Returns an empty array if the given configName does not exist in the description. */ public IBuildConfiguration[] getAllBuildConfigReferences(IProject project, String configName, boolean makeCopy) { - if (!hasBuildConfig(configName)) + if (!hasBuildConfig(configName)) { return EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; + } IBuildConfiguration[] refs = cachedConfigRefs.get(configName); if (refs == null) { Set references = new LinkedHashSet<>(); @@ -311,15 +319,17 @@ public IBuildConfiguration[] getAllBuildConfigReferences(IProject project, Strin public IBuildConfiguration[] getBuildConfigs(IProject project, boolean makeCopy) { IBuildConfiguration[] configs = cachedBuildConfigs; // Ensure project is up to date in the cache - if (configs != null && !project.equals(configs[0].getProject())) + if (configs != null && !project.equals(configs[0].getProject())) { configs = null; + } if (configs == null) { - if (configNames.length == 0) + if (configNames.length == 0) { configs = new IBuildConfiguration[] {new BuildConfiguration(project)}; - else { + } else { configs = new IBuildConfiguration[configNames.length]; - for (int i = 0; i < configs.length; i++) + for (int i = 0; i < configs.length; i++) { configs[i] = new BuildConfiguration(project, configNames[i]); + } } cachedBuildConfigs = configs; } @@ -332,8 +342,9 @@ public IBuildConfiguration[] getBuildConfigReferences(String configName) { } public IBuildConfiguration[] getBuildConfigRefs(String configName, boolean makeCopy) { - if (!hasBuildConfig(configName) || !dynamicConfigRefs.containsKey(configName)) + if (!hasBuildConfig(configName) || !dynamicConfigRefs.containsKey(configName)) { return EMPTY_BUILD_CONFIG_REFERENCE_ARRAY; + } return makeCopy ? (IBuildConfiguration[]) dynamicConfigRefs.get(configName).clone() : dynamicConfigRefs.get(configName); } @@ -354,13 +365,16 @@ public ICommand[] getBuildSpec() { public ICommand[] getBuildSpec(boolean makeCopy) { //thread safety: copy reference in case of concurrent write ICommand[] oldCommands = this.buildSpec; - if (oldCommands == null) + if (oldCommands == null) { return EMPTY_COMMAND_ARRAY; - if (!makeCopy) + } + if (!makeCopy) { return oldCommands; + } ICommand[] result = new ICommand[oldCommands.length]; - for (int i = 0; i < result.length; i++) + for (int i = 0; i < result.length; i++) { result[i] = (ICommand) ((BuildCommand) oldCommands[i]).clone(); + } return result; } @@ -383,8 +397,9 @@ public IProject[] getDynamicReferences(boolean makeCopy) { * no such link exists. */ public URI getLinkLocationURI(IPath aPath) { - if (linkDescriptions == null) + if (linkDescriptions == null) { return null; + } LinkDescription desc = linkDescriptions.get(aPath); return desc == null ? null : desc.getLocationURI(); } @@ -394,8 +409,9 @@ public URI getLinkLocationURI(IPath aPath) { * no such filter exists. */ synchronized public LinkedList getFilter(IPath aPath) { - if (filterDescriptions == null) + if (filterDescriptions == null) { return null; + } return filterDescriptions.get(aPath); } @@ -434,8 +450,9 @@ public HashMap getVariables() { @Override @Deprecated public IPath getLocation() { - if (location == null) + if (location == null) { return null; + } return FileUtil.toPath(location); } @@ -450,8 +467,9 @@ public String[] getNatureIds() { } public String[] getNatureIds(boolean makeCopy) { - if (natures == null) + if (natures == null) { return EMPTY_STRING_ARRAY; + } return makeCopy ? (String[]) natures.clone() : natures; } @@ -461,8 +479,9 @@ public IProject[] getReferencedProjects() { } public IProject[] getReferencedProjects(boolean makeCopy) { - if (staticRefs == null) + if (staticRefs == null) { return EMPTY_PROJECT_ARRAY; + } return makeCopy ? (IProject[]) staticRefs.clone() : staticRefs; } @@ -488,9 +507,11 @@ public URI getSnapshotLocationURI() { @Override public boolean hasNature(String natureID) { String[] natureIDs = getNatureIds(false); - for (String natureID2 : natureIDs) - if (natureID2.equals(natureID)) + for (String natureID2 : natureIDs) { + if (natureID2.equals(natureID)) { return true; + } + } return false; } @@ -499,13 +520,16 @@ public boolean hasNature(String natureID) { * @return boolean indicating if there are differences between the two maps */ private static boolean configRefsHaveChanges(Map m1, Map m2) { - if (m1.size() != m2.size()) + if (m1.size() != m2.size()) { return true; + } for (Entry e : m1.entrySet()) { - if (!m2.containsKey(e.getKey())) + if (!m2.containsKey(e.getKey())) { return true; - if (!Arrays.equals(e.getValue(), m2.get(e.getKey()))) + } + if (!Arrays.equals(e.getValue(), m2.get(e.getKey()))) { return true; + } } return false; } @@ -515,11 +539,14 @@ private static boolean configRefsHaveChanges(Map */ boolean hasBuildConfig(String buildConfigName) { Assert.isNotNull(buildConfigName); - if (configNames.length == 0) + if (configNames.length == 0) { return IBuildConfiguration.DEFAULT_CONFIG_NAME.equals(buildConfigName); - for (String configName : configNames) - if (configName.equals(buildConfigName)) + } + for (String configName : configNames) { + if (configName.equals(buildConfigName)) { return true; + } + } return false; } @@ -530,22 +557,28 @@ boolean hasBuildConfig(String buildConfigName) { */ public boolean hasPrivateChanges(ProjectDescription description) { if (location == null) { - if (description.location != null) + if (description.location != null) { return true; - } else if (!location.equals(description.location)) + } + } else if (!location.equals(description.location)) { return true; + } - if (!Arrays.equals(dynamicRefs, description.dynamicRefs)) + if (!Arrays.equals(dynamicRefs, description.dynamicRefs)) { return true; + } // Build Configuration state - if (!activeConfiguration.equals(description.activeConfiguration)) + if (!activeConfiguration.equals(description.activeConfiguration)) { return true; - if (!Arrays.equals(configNames, description.configNames)) + } + if (!Arrays.equals(configNames, description.configNames)) { return true; + } // Configuration level references - if (configRefsHaveChanges(dynamicConfigRefs, description.dynamicConfigRefs)) + if (configRefsHaveChanges(dynamicConfigRefs, description.dynamicConfigRefs)) { return true; + } return false; } @@ -556,40 +589,51 @@ public boolean hasPrivateChanges(ProjectDescription description) { * file (.project). */ public boolean hasPublicChanges(ProjectDescription description) { - if (!getName().equals(description.getName())) + if (!getName().equals(description.getName())) { return true; - if (!comment.equals(description.getComment())) + } + if (!comment.equals(description.getComment())) { return true; + } //don't bother optimizing if the order has changed - if (!Arrays.equals(buildSpec, description.getBuildSpec(false))) + if (!Arrays.equals(buildSpec, description.getBuildSpec(false))) { return true; - if (!Arrays.equals(staticRefs, description.getReferencedProjects(false))) + } + if (!Arrays.equals(staticRefs, description.getReferencedProjects(false))) { return true; - if (!Arrays.equals(natures, description.getNatureIds(false))) + } + if (!Arrays.equals(natures, description.getNatureIds(false))) { return true; + } HashMap> otherFilters = description.getFilters(); - if ((filterDescriptions == null) && (otherFilters != null)) + if ((filterDescriptions == null) && (otherFilters != null)) { return otherFilters != null; - if ((filterDescriptions != null) && !filterDescriptions.equals(otherFilters)) + } + if ((filterDescriptions != null) && !filterDescriptions.equals(otherFilters)) { return true; + } HashMap otherVariables = description.getVariables(); - if ((variableDescriptions == null) && (otherVariables != null)) + if ((variableDescriptions == null) && (otherVariables != null)) { return true; - if ((variableDescriptions != null) && !variableDescriptions.equals(otherVariables)) + } + if ((variableDescriptions != null) && !variableDescriptions.equals(otherVariables)) { return true; + } final HashMap otherLinks = description.getLinks(); if (linkDescriptions != otherLinks) { - if (linkDescriptions == null || !linkDescriptions.equals(otherLinks)) + if (linkDescriptions == null || !linkDescriptions.equals(otherLinks)) { return true; + } } final URI otherSnapshotLoc = description.getSnapshotLocationURI(); if (snapshotLocation != otherSnapshotLoc) { - if (snapshotLocation == null || !snapshotLocation.equals(otherSnapshotLoc)) + if (snapshotLocation == null || !snapshotLocation.equals(otherSnapshotLoc)) { return true; + } } return false; } @@ -602,8 +646,9 @@ public ICommand newCommand() { @Override public void setActiveBuildConfig(String configName) { Assert.isNotNull(configName); - if (!configName.equals(activeConfiguration)) + if (!configName.equals(activeConfiguration)) { clearCachedDynamicReferences(null); + } activeConfiguration = configName; } @@ -648,8 +693,9 @@ public void setBuildConfigReferences(HashMap refs public void setBuildConfigReferences(String configName, IBuildConfiguration[] references) { Assert.isLegal(configName != null); Assert.isLegal(references != null); - if (!hasBuildConfig(configName)) + if (!hasBuildConfig(configName)) { return; + } dynamicConfigRefs.put(configName, copyAndRemoveDuplicates(references)); clearCachedDynamicReferences(configName); } @@ -669,16 +715,18 @@ public void setBuildConfigs(String[] names) { buildConfigNames.add(n); } - if (buildConfigNames.size() == 1 && ((buildConfigNames.iterator().next())).equals(IBuildConfiguration.DEFAULT_CONFIG_NAME)) + if (buildConfigNames.size() == 1 && ((buildConfigNames.iterator().next())).equals(IBuildConfiguration.DEFAULT_CONFIG_NAME)) { configNames = EMPTY_STRING_ARRAY; - else + } else { configNames = buildConfigNames.toArray(new String[buildConfigNames.size()]); + } } // Remove references for deleted buildConfigs boolean modified = dynamicConfigRefs.keySet().retainAll(buildConfigNames); - if (modified) + if (modified) { clearCachedDynamicReferences(null); + } // Clear the cached IBuildConfiguration[] cachedBuildConfigs = null; } @@ -722,11 +770,12 @@ public boolean setLinkLocation(IPath path, LinkDescription description) { HashMap tempMap = linkDescriptions; if (description != null) { //addition or modification - if (tempMap == null) + if (tempMap == null) { tempMap = new HashMap<>(10); - else + } else { //copy on write to protect against concurrent read tempMap = (HashMap) tempMap.clone(); + } Object oldValue = tempMap.put(path, description); if (oldValue != null && description.equals(oldValue)) { //not actually changed anything @@ -735,8 +784,9 @@ public boolean setLinkLocation(IPath path, LinkDescription description) { linkDescriptions = tempMap; } else { //removal - if (tempMap == null) + if (tempMap == null) { return false; + } //copy on write to protect against concurrent access HashMap newMap = (HashMap) tempMap.clone(); Object oldValue = newMap.remove(path); @@ -755,8 +805,9 @@ public boolean setLinkLocation(IPath path, LinkDescription description) { */ synchronized public void addFilter(IPath path, FilterDescription description) { Assert.isNotNull(description); - if (filterDescriptions == null) + if (filterDescriptions == null) { filterDescriptions = new HashMap<>(10); + } LinkedList descList = filterDescriptions.get(path); if (descList == null) { descList = new LinkedList<>(); @@ -776,8 +827,9 @@ synchronized public void removeFilter(IPath path, FilterDescription description) descList.remove(description); if (descList.isEmpty()) { filterDescriptions.remove(path); - if (filterDescriptions.isEmpty()) + if (filterDescriptions.isEmpty()) { filterDescriptions = null; + } } } } @@ -795,11 +847,12 @@ public boolean setVariableDescription(String name, VariableDescription descripti HashMap tempMap = variableDescriptions; if (description != null) { // addition or modification - if (tempMap == null) + if (tempMap == null) { tempMap = new HashMap<>(10); - else + } else { // copy on write to protect against concurrent read tempMap = (HashMap) tempMap.clone(); + } Object oldValue = tempMap.put(name, description); if (oldValue != null && description.equals(oldValue)) { //not actually changed anything @@ -808,8 +861,9 @@ public boolean setVariableDescription(String name, VariableDescription descripti variableDescriptions = tempMap; } else { // removal - if (tempMap == null) + if (tempMap == null) { return false; + } // copy on write to protect against concurrent access HashMap newMap = (HashMap) tempMap.clone(); Object oldValue = newMap.remove(name); @@ -831,8 +885,9 @@ public boolean setVariableDescription(String name, VariableDescription descripti synchronized public boolean setFilters(IPath path, LinkedList descriptions) { if (descriptions != null) { // addition - if (filterDescriptions == null) + if (filterDescriptions == null) { filterDescriptions = new HashMap<>(10); + } Object oldValue = filterDescriptions.put(path, descriptions); if (oldValue != null && descriptions.equals(oldValue)) { //not actually changed anything @@ -840,16 +895,18 @@ synchronized public boolean setFilters(IPath path, LinkedList } } else { // removal - if (filterDescriptions == null) + if (filterDescriptions == null) { return false; + } Object oldValue = filterDescriptions.remove(path); if (oldValue == null) { //not actually changed anything return false; } - if (filterDescriptions.isEmpty()) + if (filterDescriptions.isEmpty()) { filterDescriptions = null; + } } return true; } @@ -935,8 +992,9 @@ public boolean updateDynamicState(ProjectDescription description) { changed = true; dynamicConfigRefs = new HashMap<>(description.dynamicConfigRefs); } - if (changed) + if (changed) { clearCachedDynamicReferences(null); + } return changed; } @@ -965,9 +1023,7 @@ private static IProject[] computeDynamicReferencesForProject(IBuildConfiguration IConfigurationElement[] children = element.getChildren("dynamicReference"); //$NON-NLS-1$ if (children.length != 0) { executableExtension = children[0].createExecutableExtension("class"); //$NON-NLS-1$ - if (executableExtension instanceof IDynamicReferenceProvider) { - IDynamicReferenceProvider provider = (IDynamicReferenceProvider) executableExtension; - + if (executableExtension instanceof IDynamicReferenceProvider provider) { result.addAll(provider.getDependentProjects(buildConfig)); } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectDescriptionReader.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectDescriptionReader.java index 1a3f9222f42..408db0ce277 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectDescriptionReader.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectDescriptionReader.java @@ -141,8 +141,9 @@ public class ProjectDescriptionReader extends DefaultHandler implements IModelOb private static synchronized SAXParser createParser(Workspace workspace) throws ParserConfigurationException, SAXException { //the parser can't be used concurrently, so only use singleton when workspace is locked - if (workspace == null || !isWorkspaceLocked(workspace)) + if (workspace == null || !isWorkspaceLocked(workspace)) { return createParserFactory().newSAXParser(); + } if (singletonParser == null) { singletonParser = createParserFactory().newSAXParser(); } @@ -217,8 +218,9 @@ private void endBuildSpecElement(String elementName) { // ProjectDescription which is the next thing on the stack. ArrayList commands = (ArrayList) objectStack.pop(); state = S_PROJECT_DESC; - if (commands.isEmpty()) + if (commands.isEmpty()) { return; + } ICommand[] commandArray = commands.toArray(new ICommand[commands.size()]); projectDescription.setBuildSpec(commandArray); } @@ -339,8 +341,9 @@ public void endElement(String uri, String elementName, String qname) { // arguments (if any). HashMap dictionaryArgs = (HashMap) objectStack.pop(); state = S_BUILD_COMMAND; - if (dictionaryArgs.isEmpty()) + if (dictionaryArgs.isEmpty()) { break; + } // Below the hashMap on the stack, there is a BuildCommand. ((BuildCommand) objectStack.peek()).setArguments(dictionaryArgs); } @@ -465,8 +468,9 @@ private void endLinkedResourcesElement(String elementName) { if (elementName.equals(LINKED_RESOURCES)) { HashMap linkedResources = (HashMap) objectStack.pop(); state = S_PROJECT_DESC; - if (linkedResources.isEmpty()) + if (linkedResources.isEmpty()) { return; + } projectDescription.setLinkDescriptions(linkedResources); } } @@ -478,8 +482,9 @@ private void endFilteredResourcesElement(String elementName) { if (elementName.equals(FILTERED_RESOURCES)) { HashMap> filteredResources = (HashMap>) objectStack.pop(); state = S_PROJECT_DESC; - if (filteredResources.isEmpty()) + if (filteredResources.isEmpty()) { return; + } projectDescription.setFilterDescriptions(filteredResources); } } @@ -492,8 +497,9 @@ private void endVariableListElement(String elementName) { if (elementName.equals(VARIABLE_LIST)) { HashMap variableList = (HashMap) objectStack.pop(); state = S_PROJECT_DESC; - if (variableList.isEmpty()) + if (variableList.isEmpty()) { return; + } projectDescription.setVariableDescriptions(variableList); } } @@ -698,15 +704,17 @@ private void endMatcherArguments(String elementName) { ArrayList matchers = (ArrayList) objectStack.pop(); Object newArguments = charBuffer.toString(); - if (matchers.size() > 0) + if (matchers.size() > 0) { newArguments = matchers.toArray(new FileInfoMatcherDescription[matchers.size()]); + } // objectStack has an array (Object[2]) on it for the matcher id and arguments. String oldArguments = (String) ((Object[]) objectStack.peek())[1]; if (oldArguments != null) { parseProblem(NLS.bind(Messages.projRead_badArguments, oldArguments, newArguments)); - } else + } else { ((Object[]) objectStack.peek())[1] = newArguments; + } state = S_MATCHER; } } @@ -823,8 +831,9 @@ private void endNaturesElement(String elementName) { // Pop the array list of natures off the stack ArrayList natures = (ArrayList) objectStack.pop(); state = S_PROJECT_DESC; - if (natures.isEmpty()) + if (natures.isEmpty()) { return; + } String[] natureNames = natures.toArray(new String[natures.size()]); projectDescription.setNatureIds(natureNames); } @@ -836,10 +845,11 @@ private void endNaturesElement(String elementName) { private void endProjectsElement() { // Pop the array list that contains all the referenced project names ArrayList referencedProjects = (ArrayList) objectStack.pop(); - if (referencedProjects.isEmpty()) + if (referencedProjects.isEmpty()) { // Don't bother adding an empty group of referenced projects to the // project descriptor. return; + } IWorkspaceRoot root = workspace.getRoot(); IProject[] projects = new IProject[referencedProjects.size()]; for (int i = 0; i < projects.length; i++) { @@ -876,16 +886,18 @@ public void error(SAXParseException error) { public void fatalError(SAXParseException error) throws SAXException { // ensure a null value is not passed as message to Status constructor (bug 42782) String message = error.getMessage(); - if (project != null) + if (project != null) { message = NLS.bind(Messages.resources_readMeta, project.getName()); + } problems.add(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, message == null ? "" : message, error)); //$NON-NLS-1$ throw error; } protected void log(Exception ex) { String message = ex.getMessage(); - if (project != null) + if (project != null) { message = NLS.bind(Messages.resources_readMeta, project.getName()); + } problems.add(new Status(IStatus.WARNING, ResourcesPlugin.PI_RESOURCES, IResourceStatus.FAILED_READ_METADATA, message == null ? "" : message, ex)); //$NON-NLS-1$ } @@ -961,8 +973,9 @@ public ProjectDescription read(InputSource input) { log(e); } - if (projectDescription != null && projectDescription.getName() == null) + if (projectDescription != null && projectDescription.getName() == null) { parseProblem(Messages.projRead_missingProjectName); + } switch (problems.getSeverity()) { case IStatus.ERROR : diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectInfo.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectInfo.java index 9ce97c50f6d..6abff76c940 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectInfo.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectInfo.java @@ -60,8 +60,9 @@ public synchronized void fixupAfterMove() { propertyStore = null; if (description != null) { ICommand[] buildSpec = description.getBuildSpec(false); - for (ICommand element : buildSpec) + for (ICommand element : buildSpec) { ((BuildCommand) element).setBuilders(null); + } } } @@ -82,8 +83,9 @@ public IContentTypeMatcher getMatcher() { public IProjectNature getNature(String natureId) { // thread safety: (Concurrency001) HashMap temp = natures; - if (temp == null) + if (temp == null) { return null; + } return temp.get(natureId); } @@ -122,20 +124,23 @@ public void setMatcher(IContentTypeMatcher matcher) { public synchronized void setNature(String natureId, IProjectNature value) { // thread safety: (Concurrency001) if (value == null) { - if (natures == null) + if (natures == null) { return; + } HashMap temp = (HashMap) natures.clone(); temp.remove(natureId); - if (temp.isEmpty()) + if (temp.isEmpty()) { natures = null; - else + } else { natures = temp; + } } else { HashMap temp = natures; - if (temp == null) + if (temp == null) { temp = new HashMap<>(5); - else + } else { temp = (HashMap) natures.clone(); + } temp.put(natureId, value); natures = temp; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectNatureDescriptor.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectNatureDescriptor.java index a1e49b4767c..6c8b89ae235 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectNatureDescriptor.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectNatureDescriptor.java @@ -129,23 +129,27 @@ protected void readExtension(IExtension natureExtension) throws CoreException { String name = element.getName(); if (name.equalsIgnoreCase("requires-nature")) { //$NON-NLS-1$ String attribute = element.getAttribute("id"); //$NON-NLS-1$ - if (attribute == null) + if (attribute == null) { fail(); + } requiredList.add(attribute); } else if (name.equalsIgnoreCase("one-of-nature")) { //$NON-NLS-1$ String attribute = element.getAttribute("id"); //$NON-NLS-1$ - if (attribute == null) + if (attribute == null) { fail(); + } setList.add(attribute); } else if (name.equalsIgnoreCase("builder")) { //$NON-NLS-1$ String attribute = element.getAttribute("id"); //$NON-NLS-1$ - if (attribute == null) + if (attribute == null) { fail(); + } builderList.add(attribute); } else if (name.equalsIgnoreCase("content-type")) { //$NON-NLS-1$ String attribute = element.getAttribute("id"); //$NON-NLS-1$ - if (attribute == null) + if (attribute == null) { fail(); + } contentTypeList.add(attribute); } else if (name.equalsIgnoreCase("options")) { //$NON-NLS-1$ String attribute = element.getAttribute("allowLinking"); //$NON-NLS-1$ diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectPathVariableManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectPathVariableManager.java index 2c09e7877b7..d99721e628f 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectPathVariableManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectPathVariableManager.java @@ -67,8 +67,9 @@ PathVariableManager getWorkspaceManager() { */ private void checkIsValidName(String name) throws CoreException { IStatus status = validateName(name); - if (!status.isOK()) + if (!status.isOK()) { throw new CoreException(status); + } } /** @@ -77,8 +78,9 @@ private void checkIsValidName(String name) throws CoreException { */ private void checkIsValidValue(URI newValue) throws CoreException { IStatus status = validateValue(newValue); - if (!status.isOK()) + if (!status.isOK()) { throw new CoreException(status); + } } /** @@ -95,12 +97,15 @@ public String[] getPathVariableNames() { } for (Descriptor variableProvider : variableProviders) { String[] variableHints = variableProvider.getVariableNames(variableProvider.getName(), resource); - if (variableHints != null && variableHints.length > 0) - for (int k = 0; k < variableHints.length; k++) + if (variableHints != null && variableHints.length > 0) { + for (int k = 0; k < variableHints.length; k++) { result.add(variableProvider.getVariableNames(variableProvider.getName(), resource)[k]); + } + } } - if (map != null) + if (map != null) { result.addAll(map.keySet()); + } result.addAll(Arrays.asList(getWorkspaceManager().getPathVariableNames())); return result.toArray(new String[0]); } @@ -112,8 +117,9 @@ public String[] getPathVariableNames() { @Override public IPath getValue(String varName) { URI uri = getURIValue(varName); - if (uri != null) + if (uri != null) { return URIUtil.toPath(uri); + } return null; } @@ -134,8 +140,9 @@ public URI getURIValue(String varName) { // absolute path on unix, so we don't // resolve it URI resolved = resolveVariable(value); - if (resolved != null) + if (resolved != null) { return resolved; + } } } try { @@ -155,22 +162,26 @@ public String internalGetValue(String varName) { } catch (CoreException e) { return null; } - if (map != null && map.containsKey(varName)) + if (map != null && map.containsKey(varName)) { return map.get(varName).getValue(); + } String name; int index = varName.indexOf('-'); - if (index != -1) + if (index != -1) { name = varName.substring(0, index); - else + } else { name = varName; + } for (Descriptor variableProvider : variableProviders) { - if (variableProvider.getName().equals(name)) + if (variableProvider.getName().equals(name)) { return variableProvider.getValue(varName, resource); + } } for (Descriptor variableProvider : variableProviders) { - if (name.startsWith(variableProvider.getName())) + if (name.startsWith(variableProvider.getName())) { return variableProvider.getValue(varName, resource); + } } return null; } @@ -181,16 +192,18 @@ public String internalGetValue(String varName) { @Override public boolean isDefined(String varName) { for (Descriptor variableProvider : variableProviders) { - if (varName.startsWith(variableProvider.getName())) + if (varName.startsWith(variableProvider.getName())) { return true; + } } try { HashMap map = ((ProjectDescription) resource.getProject().getDescription()).getVariables(); if (map != null) { for (String name : map.keySet()) { - if (name.equals(varName)) + if (name.equals(varName)) { return true; + } } } } catch (CoreException e) { @@ -214,8 +227,9 @@ public boolean isDefined(String varName) { @Override @Deprecated public IPath resolvePath(IPath path) { - if (path == null || path.segmentCount() == 0 || path.isAbsolute() || path.getDevice() != null) + if (path == null || path.segmentCount() == 0 || path.isAbsolute() || path.getDevice() != null) { return path; + } URI value = resolveURI(URIUtil.toURI(path)); return value == null ? path : URIUtil.toPath(value); } @@ -235,16 +249,19 @@ public URI resolveVariable(String variable) { } public String resolveVariable(String value, LinkedList variableStack) { - if (variableStack == null) + if (variableStack == null) { variableStack = new LinkedList<>(); + } String tmp = internalGetValue(value); if (tmp == null) { URI result = getWorkspaceManager().getURIValue(value); - if (result != null) + if (result != null) { return result.toASCIIString(); - } else + } + } else { value = tmp; + } while (true) { String stringValue; @@ -252,12 +269,14 @@ public String resolveVariable(String value, LinkedList variableStack) { URI uri = URI.create(value); if (uri != null) { IPath path = URIUtil.toPath(uri); - if (path != null) + if (path != null) { stringValue = path.toPortableString(); - else + } else { stringValue = value; - } else + } + } else { stringValue = value; + } } catch (IllegalArgumentException e) { stringValue = value; } @@ -270,16 +289,19 @@ public String resolveVariable(String value, LinkedList variableStack) { if (!variableStack.contains(macro)) { variableStack.add(macro); resolvedMacro = resolveVariable(macro, variableStack); - if (resolvedMacro == null) + if (resolvedMacro == null) { resolvedMacro = ""; //$NON-NLS-1$ + } } - if (stringValue.length() > endIndex) + if (stringValue.length() > endIndex) { stringValue = stringValue.substring(0, index) + resolvedMacro + stringValue.substring(endIndex + 1); - else + } else { stringValue = resolvedMacro; + } value = stringValue; - } else + } else { break; + } } return value; } @@ -294,11 +316,13 @@ public URI resolveURI(URI uri) { return uri; } IPath raw = IPath.fromOSString(schemeSpecificPart); - if (raw == null || raw.segmentCount() == 0 || raw.isAbsolute() || raw.getDevice() != null) + if (raw == null || raw.segmentCount() == 0 || raw.isAbsolute() || raw.getDevice() != null) { return URIUtil.toURI(raw); + } URI value = resolveVariable(raw.segment(0)); - if (value == null) + if (value == null) { return uri; + } String path = value.getPath(); if (path != null) { @@ -320,10 +344,11 @@ public URI resolveURI(URI uri) { @Deprecated @Override public void setValue(String varName, IPath newValue) throws CoreException { - if (newValue == null) + if (newValue == null) { setURIValue(varName, (URI) null); - else + } else { setURIValue(varName, URIUtil.toURI(newValue)); + } } /** @@ -342,9 +367,9 @@ public void setURIValue(String varName, URI newValue) throws CoreException { synchronized (this) { String value = internalGetValue(varName); URI currentValue = null; - if (value == null) + if (value == null) { currentValue = getWorkspaceManager().getURIValue(varName); - else { + } else { try { currentValue = URI.create(value); } catch (IllegalArgumentException e) { @@ -352,20 +377,22 @@ public void setURIValue(String varName, URI newValue) throws CoreException { } } boolean variableExists = currentValue != null; - if ((!variableExists && newValue == null) || (variableExists && currentValue.equals(newValue))) + if ((!variableExists && newValue == null) || (variableExists && currentValue.equals(newValue))) { return; + } for (Descriptor variableProvider : variableProviders) { // if (variableProviders[i].getName().equals(varName)) // return; - if (varName.startsWith(variableProvider.getName())) + if (varName.startsWith(variableProvider.getName())) { return; + } } - if (value == null && variableExists) + if (value == null && variableExists) { changeWorkspaceValue = true; - else { + } else { IProgressMonitor monitor = new NullProgressMonitor(); final ISchedulingRule rule = resource.getProject(); // project.workspace.getRuleFactory().modifyRule(project); try { @@ -386,9 +413,9 @@ public void setURIValue(String varName, URI newValue) throws CoreException { } } } - if (changeWorkspaceValue) + if (changeWorkspaceValue) { getWorkspaceManager().setURIValue(varName, newValue); - else { + } else { // notify listeners from outside the synchronized block to avoid deadlocks getWorkspaceManager().fireVariableChangeEvent(project, varName, newValue != null ? URIUtil.toPath(newValue) : null, eventType); } @@ -429,8 +456,9 @@ public IStatus validateName(String name) { for (int i = 1; i < name.length(); i++) { char following = name.charAt(i); - if (Character.isWhitespace(following)) + if (Character.isWhitespace(following)) { return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, Messages.pathvar_whitespace); + } if (!Character.isLetter(following) && !Character.isDigit(following) && following != '_') { message = NLS.bind(Messages.pathvar_invalidChar, String.valueOf(following)); return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); @@ -494,8 +522,9 @@ public void removeChangeListener(IPathVariableChangeListener listener) { public URI getVariableRelativePathLocation(URI location) { try { URI result = convertToRelative(location, false, null); - if (!result.equals(location)) + if (!result.equals(location)) { return result; + } } catch (CoreException e) { // handled by returning null } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectPreferences.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectPreferences.java index 918cf8b6c1c..c1365585498 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectPreferences.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectPreferences.java @@ -97,19 +97,22 @@ public class ProjectPreferences extends EclipsePreferences { static void deleted(IFile file) throws CoreException { IPath path = file.getFullPath(); int count = path.segmentCount(); - if (count != 3) + if (count != 3) { return; + } // check if we are in the .settings directory - if (!EclipsePreferences.DEFAULT_PREFERENCES_DIRNAME.equals(path.segment(1))) + if (!EclipsePreferences.DEFAULT_PREFERENCES_DIRNAME.equals(path.segment(1))) { return; + } Preferences root = Platform.getPreferencesService().getRootNode(); String project = path.segment(0); String qualifier = path.removeFileExtension().lastSegment(); ProjectPreferences projectNode = (ProjectPreferences) root.node(ProjectScope.SCOPE).node(project); // if the node isn't known then just return try { - if (!projectNode.nodeExists(qualifier)) + if (!projectNode.nodeExists(qualifier)) { return; + } } catch (BackingStoreException e) { // ignore } @@ -118,18 +121,21 @@ static void deleted(IFile file) throws CoreException { clearNode(projectNode.node(qualifier)); // notifies the CharsetManager if needed - if (qualifier.equals(PREFS_REGULAR_QUALIFIER) || qualifier.equals(PREFS_DERIVED_QUALIFIER)) + if (qualifier.equals(PREFS_REGULAR_QUALIFIER) || qualifier.equals(PREFS_DERIVED_QUALIFIER)) { preferencesChanged(file.getProject()); + } } static void deleted(IFolder folder) throws CoreException { IPath path = folder.getFullPath(); int count = path.segmentCount(); - if (count != 2) + if (count != 2) { return; + } // check if we are the .settings directory - if (!EclipsePreferences.DEFAULT_PREFERENCES_DIRNAME.equals(path.segment(1))) + if (!EclipsePreferences.DEFAULT_PREFERENCES_DIRNAME.equals(path.segment(1))) { return; + } Preferences root = Platform.getPreferencesService().getRootNode(); // The settings dir has been removed/moved so remove all project prefs // for the resource. @@ -140,8 +146,9 @@ static void deleted(IFolder folder) throws CoreException { // remove the preferences removeNode(projectNode); // notifies the CharsetManager - if (hasResourcesSettings) + if (hasResourcesSettings) { preferencesChanged(folder.getProject()); + } } /* @@ -159,8 +166,9 @@ static void deleted(IProject project) throws CoreException { // remove the preferences removeNode(projectNode); // notifies the CharsetManager - if (hasResourcesSettings) + if (hasResourcesSettings) { preferencesChanged(project); + } } static void deleted(IResource resource) throws CoreException { @@ -193,8 +201,9 @@ static IFile getFile(IProject project, String qualifier) { } private static Properties loadProperties(IFile file) throws BackingStoreException { - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug("Loading preferences from file: " + file.getFullPath()); //$NON-NLS-1$ + } Properties result = new Properties(); try ( InputStream input = new BufferedInputStream(file.getContents(true)); @@ -202,8 +211,9 @@ private static Properties loadProperties(IFile file) throws BackingStoreExceptio result.load(input); } catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.RESOURCE_NOT_FOUND) { - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug(MessageFormat.format("Preference file {0} does not exist.", file.getFullPath())); //$NON-NLS-1$ + } } else { String message = NLS.bind(Messages.preferences_loadException, file.getFullPath()); log(new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e)); @@ -225,8 +235,9 @@ private static void preferencesChanged(IProject project) { private static void read(ProjectPreferences node, IFile file) throws BackingStoreException, CoreException { if (file == null || !file.exists()) { - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug("Unable to determine preference file or file does not exist for node: " + node.absolutePath()); //$NON-NLS-1$ + } return; } @@ -343,8 +354,9 @@ public static void updatePreferences(IFile file) throws CoreException { IPath path = file.getFullPath(); // if we made it this far we are inside /project/.settings and might // have a change to a preference file - if (!PREFS_FILE_EXTENSION.equals(path.getFileExtension())) + if (!PREFS_FILE_EXTENSION.equals(path.getFileExtension())) { return; + } String project = path.segment(0); String qualifier = path.removeFileExtension().lastSegment(); @@ -353,11 +365,12 @@ public static void updatePreferences(IFile file) throws CoreException { String message = null; try { message = NLS.bind(Messages.preferences_syncException, node.absolutePath()); - if (!(node instanceof ProjectPreferences)) + if (!(node instanceof ProjectPreferences projectPrefs)) { return; - ProjectPreferences projectPrefs = (ProjectPreferences) node; - if (projectPrefs.isWriting) + } + if (projectPrefs.isWriting) { return; + } read(projectPrefs, file); // Bug 108066: In case the node had existed before it was updated from // file, the read() operation marks it dirty. Override the dirty flag @@ -366,8 +379,9 @@ public static void updatePreferences(IFile file) throws CoreException { // make sure that we generate the appropriate resource change events // if encoding settings have changed - if (PREFS_REGULAR_QUALIFIER.equals(qualifier) || PREFS_DERIVED_QUALIFIER.equals(qualifier)) + if (PREFS_REGULAR_QUALIFIER.equals(qualifier) || PREFS_DERIVED_QUALIFIER.equals(qualifier)) { preferencesChanged(file.getProject()); + } } catch (BackingStoreException e) { IStatus status = new Status(IStatus.ERROR, ResourcesPlugin.PI_RESOURCES, IStatus.ERROR, message, e); throw new CoreException(status); @@ -443,23 +457,26 @@ private List computeChildren() { } List result = new ArrayList<>(); for (IResource resource : members) { - if (resource.getType() == IResource.FILE && PREFS_FILE_EXTENSION.equals(resource.getFullPath().getFileExtension())) + if (resource.getType() == IResource.FILE && PREFS_FILE_EXTENSION.equals(resource.getFullPath().getFileExtension())) { result.add(resource.getFullPath().removeFileExtension().lastSegment()); + } } return result; } @Override public void flush() throws BackingStoreException { - if (isReading) + if (isReading) { return; + } isWriting = true; try { // call the internal method because we don't want to be synchronized, we will do that ourselves later. IEclipsePreferences toFlush = super.internalFlush(); //if we aren't at the right level, then flush the appropriate node - if (toFlush != null) + if (toFlush != null) { toFlush.flush(); + } } finally { isWriting = false; } @@ -467,8 +484,9 @@ public void flush() throws BackingStoreException { private IFile getFile() { if (file == null) { - if (project == null || qualifier == null) + if (project == null || qualifier == null) { return null; + } file = getFile(project, qualifier); } return file; @@ -480,14 +498,16 @@ private IFile getFile() { @Override protected IEclipsePreferences getLoadLevel() { if (loadLevel == null) { - if (project == null || qualifier == null) + if (project == null || qualifier == null) { return null; + } // Make it relative to this node rather than navigating to it from the root. // Walk backwards up the tree starting at this node. // This is important to avoid a chicken/egg thing on startup. EclipsePreferences node = this; - for (int i = 3; i < segmentCount; i++) + for (int i = 3; i < segmentCount; i++) { node = (EclipsePreferences) node.parent(); + } loadLevel = node; } return loadLevel; @@ -503,8 +523,9 @@ protected IEclipsePreferences getLoadLevel() { */ @Override protected IPath getLocation() { - if (project == null || qualifier == null) + if (project == null || qualifier == null) { return null; + } IPath path = project.getLocation(); return computeLocation(path, qualifier); } @@ -517,8 +538,9 @@ protected EclipsePreferences internalCreate(EclipsePreferences nodeParent, Strin @Override protected String internalGet(String key) { // throw NPE if key is null - if (key == null) + if (key == null) { throw new NullPointerException(); + } // illegal state if this node has been removed checkRemoved(); silentLoad(); @@ -533,22 +555,25 @@ protected String internalPut(String key, String newValue) { if ((segmentCount == 3) && PREFS_REGULAR_QUALIFIER.equals(qualifier) && (project != null)) { if (ResourcesPlugin.PREF_SEPARATE_DERIVED_ENCODINGS.equals(key)) { CharsetManager charsetManager = getWorkspace().getCharsetManager(); - if (Boolean.parseBoolean(newValue)) + if (Boolean.parseBoolean(newValue)) { charsetManager.splitEncodingPreferences(project); - else + } else { charsetManager.mergeEncodingPreferences(project); + } } } return super.internalPut(key, newValue); } private void initialize() { - if (segmentCount != 2) + if (segmentCount != 2) { return; + } // if already initialized, then skip this initialization - if (initialized) + if (initialized) { return; + } // initialize the children only if project is opened if (project.isOpen()) { @@ -590,12 +615,14 @@ protected void load() throws BackingStoreException { private void load(boolean reportProblems) throws BackingStoreException { IFile localFile = getFile(); if (localFile == null || !localFile.exists()) { - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug("Unable to determine preference file or file does not exist for node: " + absolutePath()); //$NON-NLS-1$ + } return; } - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug("Loading preferences from file: " + localFile.getFullPath()); //$NON-NLS-1$ + } Properties fromDisk = new Properties(); try (InputStream input = localFile.getContents(true)) { fromDisk.load(input); @@ -603,8 +630,9 @@ private void load(boolean reportProblems) throws BackingStoreException { loadedNodes.add(absolutePath()); } catch (CoreException e) { if (e.getStatus().getCode() == IResourceStatus.RESOURCE_NOT_FOUND) { - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug("Preference file does not exist for node: " + absolutePath()); //$NON-NLS-1$ + } return; } if (reportProblems) { @@ -629,21 +657,26 @@ private void load(boolean reportProblems) throws BackingStoreException { @Override public boolean nodeExists(String path) throws BackingStoreException { // short circuit for checking this node - if (path.length() == 0) + if (path.length() == 0) { return !removed; + } // illegal state if this node has been removed. // do this AFTER checking for the empty string. checkRemoved(); initialize(); silentLoad(); - if (segmentCount != 1) + if (segmentCount != 1) { return super.nodeExists(path); - if (path.length() == 0) + } + if (path.length() == 0) { return super.nodeExists(path); - if (path.charAt(0) == IPath.SEPARATOR) + } + if (path.charAt(0) == IPath.SEPARATOR) { return super.nodeExists(path); - if (path.indexOf(IPath.SEPARATOR) != -1) + } + if (path.indexOf(IPath.SEPARATOR) != -1) { return super.nodeExists(path); + } // if we are checking existance of a single segment child of /project, base the answer on // whether or not it exists in the workspace. return getWorkspace().getRoot().getProject(path).exists() || super.nodeExists(path); @@ -658,10 +691,11 @@ public void remove(String key) { if ((segmentCount == 3) && PREFS_REGULAR_QUALIFIER.equals(qualifier) && (project != null)) { if (ResourcesPlugin.PREF_SEPARATE_DERIVED_ENCODINGS.equals(key)) { CharsetManager charsetManager = getWorkspace().getCharsetManager(); - if (ResourcesPlugin.DEFAULT_PREF_SEPARATE_DERIVED_ENCODINGS) + if (ResourcesPlugin.DEFAULT_PREF_SEPARATE_DERIVED_ENCODINGS) { charsetManager.splitEncodingPreferences(project); - else + } else { charsetManager.mergeEncodingPreferences(project); + } } } } @@ -670,8 +704,9 @@ public void remove(String key) { protected void save() throws BackingStoreException { final IFile fileInWorkspace = getFile(); if (fileInWorkspace == null) { - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug("Not saving preferences since there is no file for node: " + absolutePath()); //$NON-NLS-1$ + } return; } final String finalQualifier = qualifier; @@ -683,12 +718,14 @@ protected void save() throws BackingStoreException { // nothing to save. delete existing file if one exists. if (table.isEmpty()) { if (fileInWorkspace.exists()) { - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug("Deleting preference file: " + fileInWorkspace.getFullPath()); //$NON-NLS-1$ + } if (fileInWorkspace.isReadOnly()) { IStatus status1 = fileInWorkspace.getWorkspace().validateEdit(new IFile[] {fileInWorkspace}, IWorkspace.VALIDATE_PROMPT); - if (!status1.isOK()) + if (!status1.isOK()) { throw new CoreException(status1); + } } try { fileInWorkspace.delete(true, null); @@ -704,15 +741,17 @@ protected void save() throws BackingStoreException { String s = removeTimestampFromTable(table); String systemLineSeparator = System.lineSeparator(); String fileLineSeparator = fileInWorkspace.getLineSeparator(true); - if (!systemLineSeparator.equals(fileLineSeparator)) + if (!systemLineSeparator.equals(fileLineSeparator)) { s = s.replaceAll(systemLineSeparator, fileLineSeparator); + } byte[] input = s.getBytes(StandardCharsets.UTF_8); // make sure that preference folder and file are in sync fileInWorkspace.getParent().refreshLocal(IResource.DEPTH_ZERO, null); fileInWorkspace.refreshLocal(IResource.DEPTH_ZERO, null); if (fileInWorkspace.exists()) { - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug("Setting preference file contents for: " + fileInWorkspace.getFullPath()); //$NON-NLS-1$ + } if (fileInWorkspace.isReadOnly()) { IStatus status2 = fileInWorkspace.getWorkspace().validateEdit(new IFile[] {fileInWorkspace}, IWorkspace.VALIDATE_PROMPT); if (!status2.isOK()) { @@ -725,16 +764,19 @@ protected void save() throws BackingStoreException { // create the file IFolder folder = (IFolder) fileInWorkspace.getParent(); if (!folder.exists()) { - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug("Creating parent preference directory: " + folder.getFullPath()); //$NON-NLS-1$ + } folder.create(IResource.NONE, true, null); } - if (Policy.DEBUG_PREFERENCES) + if (Policy.DEBUG_PREFERENCES) { Policy.debug("Creating preference file: " + fileInWorkspace.getLocation()); //$NON-NLS-1$ + } fileInWorkspace.create(input, IResource.NONE, null); } - if (PREFS_DERIVED_QUALIFIER.equals(finalQualifier)) + if (PREFS_DERIVED_QUALIFIER.equals(finalQualifier)) { fileInWorkspace.setDerived(true, null); + } } catch (BackingStoreException e2) { bse[0] = e2; } catch (IOException e3) { @@ -753,8 +795,9 @@ protected void save() throws BackingStoreException { // we might: delete the file, create the .settings folder, create the file, modify the file, or set derived flag for the file. ISchedulingRule rule = MultiRule.combine(new ISchedulingRule[] {factory.deleteRule(fileInWorkspace), factory.createRule(fileInWorkspace.getParent()), factory.modifyRule(fileInWorkspace), factory.derivedRule(fileInWorkspace)}); ws.run(operation, rule, IResource.NONE, null); - if (bse[0] != null) + if (bse[0] != null) { throw bse[0]; + } } } catch (OperationCanceledException e) { throw new BackingStoreException(Messages.preferences_operationCanceled); @@ -768,10 +811,12 @@ protected void save() throws BackingStoreException { private void silentLoad() { ProjectPreferences node = (ProjectPreferences) getLoadLevel(); - if (node == null) + if (node == null) { return; - if (isAlreadyLoaded(node) || node.isLoading()) + } + if (isAlreadyLoaded(node) || node.isLoading()) { return; + } try { node.setLoading(true); node.load(false); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectVariableProviderManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectVariableProviderManager.java index 6496188593e..6dbbc85d7b1 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectVariableProviderManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ProjectVariableProviderManager.java @@ -49,14 +49,16 @@ public Descriptor(IExtension extension, IConfigurationElement element) throws Ru PathVariableResolver p = null; try { String classAttribute = "class"; //$NON-NLS-1$ - if (element.getAttribute(classAttribute) != null) + if (element.getAttribute(classAttribute) != null) { p = (PathVariableResolver) element.createExecutableExtension(classAttribute); + } } catch (CoreException e) { Policy.log(e); } provider = p; - if (name == null) + if (name == null) { fail(NLS.bind(Messages.mapping_invalidDef, extension.getUniqueIdentifier())); + } } protected void fail(String reason) throws CoreException { @@ -68,16 +70,19 @@ public String getName() { } public String getValue(String variable, IResource resource) { - if (value != null) + if (value != null) { return value; + } return provider.getValue(variable, resource); } public String[] getVariableNames(String variable, IResource resource) { - if (provider != null) + if (provider != null) { return provider.getVariableNames(variable, resource); - if (name.equals(variable)) + } + if (name.equals(variable)) { return new String[] {variable}; + } return null; } } @@ -109,8 +114,9 @@ private static Map getDescriptorMap() { } catch (CoreException e) { Policy.log(e); } - if (desc != null) + if (desc != null) { d.put(desc.getName(), desc); + } } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Resource.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Resource.java index 9736ae77c70..044727c145f 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Resource.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Resource.java @@ -96,14 +96,16 @@ public void accept(IResourceProxyVisitor visitor, int memberFlags) throws CoreEx public void accept(final IResourceProxyVisitor visitor, final int depth, final int memberFlags) throws CoreException { // It is invalid to call accept on a phantom when INCLUDE_PHANTOMS is not specified. final boolean includePhantoms = (memberFlags & IContainer.INCLUDE_PHANTOMS) != 0; - if ((memberFlags & IContainer.DO_NOT_CHECK_EXISTENCE) == 0) + if ((memberFlags & IContainer.DO_NOT_CHECK_EXISTENCE) == 0) { checkAccessible(getFlags(getResourceInfo(includePhantoms, false))); + } final ResourceProxy proxy = new ResourceProxy(); IElementContentVisitor elementVisitor = (tree, requestor, contents) -> { ResourceInfo info = (ResourceInfo) contents; - if (!isMember(getFlags(info), memberFlags)) + if (!isMember(getFlags(info), memberFlags)) { return false; + } proxy.requestor = requestor; proxy.info = info; try { @@ -158,26 +160,31 @@ public void accept(final IResourceVisitor visitor, int depth, int memberFlags) t final boolean includePhantoms = (memberFlags & IContainer.INCLUDE_PHANTOMS) != 0; ResourceInfo info = getResourceInfo(includePhantoms, false); int flags = getFlags(info); - if ((memberFlags & IContainer.DO_NOT_CHECK_EXISTENCE) == 0) + if ((memberFlags & IContainer.DO_NOT_CHECK_EXISTENCE) == 0) { checkAccessible(flags); + } // Check that this resource matches the member flags // Visit this resource. - if (!isMember(flags, memberFlags) || !visitor.visit(this) || depth == DEPTH_ZERO) + if (!isMember(flags, memberFlags) || !visitor.visit(this) || depth == DEPTH_ZERO) { return; + } // Get the info again because it might have been changed by the visitor. info = getResourceInfo(includePhantoms, false); - if (info == null) + if (info == null) { return; + } // Thread safety: (cache the type to avoid changes -- we might not be inside an operation). int type = info.getType(); - if (type == FILE) + if (type == FILE) { return; + } // If we had a gender change we need to fix up the resource before asking for its members. IContainer resource = getType() != type ? (IContainer) workspace.newResource(getFullPath(), type) : (IContainer) this; IResource[] members = resource.members(memberFlags); - for (IResource member : members) + for (IResource member : members) { member.accept(visitor, DEPTH_ZERO, memberFlags | IContainer.DO_NOT_CHECK_EXISTENCE); + } } protected void assertCopyRequirements(IPath destination, int destinationType, int updateFlags) throws CoreException { @@ -195,19 +202,22 @@ protected void assertCopyRequirements(IPath destination, int destinationType, in */ protected IFileInfo assertLinkRequirements(URI localLocation, int updateFlags) throws CoreException { boolean allowMissingLocal = (updateFlags & IResource.ALLOW_MISSING_LOCAL) != 0; - if ((updateFlags & IResource.REPLACE) == 0) + if ((updateFlags & IResource.REPLACE) == 0) { checkDoesNotExist(getFlags(getResourceInfo(false, false)), true); + } IStatus locationStatus = workspace.validateLinkLocationURI(this, localLocation); // We only tolerate an undefined path variable in the allow missing local case. final boolean variableUndefined = locationStatus.getCode() == IResourceStatus.VARIABLE_NOT_DEFINED_WARNING; - if (locationStatus.getSeverity() == IStatus.ERROR || (variableUndefined && !allowMissingLocal)) + if (locationStatus.getSeverity() == IStatus.ERROR || (variableUndefined && !allowMissingLocal)) { throw new ResourceException(locationStatus); + } // Check that the parent exists and is open. Container parent = (Container) getParent(); parent.checkAccessible(getFlags(parent.getResourceInfo(false, false))); // If the variable is undefined we can't do any further checks. - if (variableUndefined) + if (variableUndefined) { return null; + } // Check if the file exists. URI resolved = getPathVariableManager().resolveURI(localLocation); IFileStore store = EFS.getStore(resolved); @@ -342,12 +352,14 @@ public void checkDoesNotExist(int flags, boolean checkType) throws CoreException String message = NLS.bind(Messages.resources_mustNotExist, getFullPath()); throw new ResourceException(checkType ? IResourceStatus.RESOURCE_EXISTS : IResourceStatus.PATH_OCCUPIED, getFullPath(), message, null); } - if (Workspace.caseSensitive) + if (Workspace.caseSensitive) { return; + } // Now look for a matching case variant in the tree. IResource variant = findExistingResourceVariant(getFullPath()); - if (variant == null) + if (variant == null) { return; + } String msg = NLS.bind(Messages.resources_existsDifferentCase, variant.getFullPath()); throw new ResourceException(IResourceStatus.CASE_VARIANT_EXISTS, variant.getFullPath(), msg, null); } @@ -415,8 +427,9 @@ protected IStatus checkMoveRequirements(IPath destination, int destinationType, // Check if we are only changing case. IResource variant = Workspace.caseSensitive ? null : findExistingResourceVariant(destination); - if (variant == null || !this.equals(variant)) + if (variant == null || !this.equals(variant)) { dest.checkDoesNotExist(); + } // Ensure we aren't trying to move a file to a project. if (getType() == IResource.FILE && dest.getType() == IResource.PROJECT) { @@ -466,8 +479,9 @@ protected IStatus checkMoveRequirements(IPath destination, int destinationType, */ public void checkValidPath(IPath toValidate, int type, boolean lastSegmentOnly) throws CoreException { IStatus result = workspace.locationValidator.validatePath(toValidate, type, lastSegmentOnly); - if (!result.isOK()) + if (!result.isOK()) { throw new ResourceException(result); + } } /** @@ -477,8 +491,9 @@ public void checkValidPath(IPath toValidate, int type, boolean lastSegmentOnly) */ public void checkValidGroupContainer(IPath destination, boolean isLink, boolean isGroup) throws CoreException { IStatus status = getValidGroupContainer(destination, isLink, isGroup); - if (!status.isOK()) + if (!status.isOK()) { throw new ResourceException(status); + } } /** @@ -489,8 +504,9 @@ public void checkValidGroupContainer(IPath destination, boolean isLink, boolean public void checkValidGroupContainer(Container destination, boolean isLink, boolean isGroup) throws CoreException { if (!isLink && !isGroup) { String message = Messages.group_invalidParent; - if (destination.isVirtual()) + if (destination.isVirtual()) { throw new ResourceException(new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message)); + } } } @@ -498,8 +514,9 @@ public IStatus getValidGroupContainer(IPath destination, boolean isLink, boolean if (!isLink && !isGroup) { String message = Messages.group_invalidParent; ResourceInfo info = workspace.getResourceInfo(destination, false, false); - if (info != null && info.isSet(M_VIRTUAL)) + if (info != null && info.isSet(M_VIRTUAL)) { return new ResourceStatus(IResourceStatus.INVALID_VALUE, null, message); + } } return Status.OK_STATUS; } @@ -512,10 +529,10 @@ public void clearHistory(IProgressMonitor monitor) { @Override public boolean contains(ISchedulingRule rule) { // Must allow notifications to nest in all resource rules. - if ((this == rule) || rule.getClass().equals(WorkManager.NotifyRule.class)) + if ((this == rule) || rule.getClass().equals(WorkManager.NotifyRule.class)) { return true; - if (rule instanceof MultiRule) { - MultiRule multi = (MultiRule) rule; + } + if (rule instanceof MultiRule multi) { ISchedulingRule[] children = multi.getChildren(); for (ISchedulingRule c : children) { if (!contains(c)) { @@ -524,11 +541,12 @@ public boolean contains(ISchedulingRule rule) { } return true; } - if (!(rule instanceof IResource)) + if (!(rule instanceof IResource resource)) { return false; - IResource resource = (IResource) rule; - if (!workspace.equals(resource.getWorkspace())) + } + if (!workspace.equals(resource.getWorkspace())) { return false; + } return path.isPrefixOf(resource.getFullPath()); } @@ -537,8 +555,9 @@ public boolean contains(ISchedulingRule rule) { */ public void convertToPhantom() throws CoreException { ResourceInfo info = getResourceInfo(false, true); - if (info == null || isPhantom(getFlags(info))) + if (info == null || isPhantom(getFlags(info))) { return; + } info.clearSessionProperties(); info.set(M_PHANTOM); getLocalManager().updateLocalSync(info, I_NULL_SYNC_INFO); @@ -676,12 +695,14 @@ public void createLink(URI localLocation, int updateFlags, IProgressMonitor moni workspace.deleteResource(existing); } ResourceInfo info = workspace.createResource(this, false); - if ((updateFlags & IResource.HIDDEN) != 0) + if ((updateFlags & IResource.HIDDEN) != 0) { info.set(M_HIDDEN); + } info.set(M_LINK); LinkDescription linkDescription = new LinkDescription(this, localLocation); - if (linkDescription.isGroup()) + if (linkDescription.isGroup()) { info.set(M_VIRTUAL); + } getLocalManager().link(this, localLocation, fileInfo); progress.split(5); // Save the location in the project description. @@ -782,14 +803,16 @@ public void delete(int updateFlags, IProgressMonitor monitor) throws CoreExcepti try { workspace.prepareOperation(rule, split); // If there is no resource then there is nothing to delete so just return. - if (!exists()) + if (!exists()) { return; + } workspace.beginOperation(true); broadcastPreDeleteEvent(); // When a project is being deleted, flush the build order in case there is a problem. - if (this.getType() == IResource.PROJECT) + if (this.getType() == IResource.PROJECT) { workspace.flushBuildOrder(); + } final IFileStore originalStore = getStore(); boolean wasLinked = isLinked(); @@ -812,12 +835,14 @@ public void delete(int updateFlags, IProgressMonitor monitor) throws CoreExcepti } // Invalidate the tree for further use by clients. tree.makeInvalid(); - if (!tree.getStatus().isOK()) + if (!tree.getStatus().isOK()) { throw new ResourceException(tree.getStatus()); + } // Update any aliases of this resource. // Note that deletion of a linked resource cannot affect other resources. - if (!wasLinked) + if (!wasLinked) { workspace.getAliasManager().updateAliases(this, originalStore, IResource.DEPTH_INFINITE, progress.split(48)); + } if (getType() == PROJECT) { // Make sure the rule factory is cleared on project deletion. ((Rules) workspace.getRuleFactory()).setRuleFactory((IProject) this, null); @@ -855,15 +880,18 @@ public void deleteMarkers(String type, boolean includeSubtypes, int depth) throw */ public void deleteResource(boolean convertToPhantom, MultiStatus status) throws CoreException { // Remove markers on this resource and its descendants. - if (exists()) + if (exists()) { getMarkerManager().removeMarkers(this, IResource.DEPTH_INFINITE); + } // If this is a linked resource or contains linked resources, // remove their entries from the project description. List links = findLinks(); // Pre-delete notification to internal infrastructure - if (links != null) - for (Resource resource : links) + if (links != null) { + for (Resource resource : links) { workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_LINK_DELETE, resource)); + } + } // Check if we deleted a preferences file. ProjectPreferences.deleted(this); @@ -874,8 +902,9 @@ public void deleteResource(boolean convertToPhantom, MultiStatus status) throws ProjectDescription description = project.internalGetDescription(); if (description != null) { boolean wasChanged = false; - for (Resource resource : links) + for (Resource resource : links) { wasChanged |= description.setLinkLocation(resource.getProjectRelativePath(), null); + } if (wasChanged) { project.internalSetDescription(description, true); try { @@ -903,8 +932,9 @@ public void deleteResource(boolean convertToPhantom, MultiStatus status) throws Project project = (Project) getProject(); ProjectDescription description = project.internalGetDescription(); if (description != null) { - for (Resource resource : filters) + for (Resource resource : filters) { description.setFilters(resource.getProjectRelativePath(), null); + } project.internalSetDescription(description, true); project.writeDescription(IResource.FORCE); } @@ -921,8 +951,9 @@ public void deleteResource(boolean convertToPhantom, MultiStatus status) throws err = e; } } - if (err != null) + if (err != null) { throw err; + } } /** @@ -932,15 +963,17 @@ private List findLinks() { Project project = (Project) getProject(); ProjectDescription description = project.internalGetDescription(); HashMap linkMap = description.getLinks(); - if (linkMap == null) + if (linkMap == null) { return null; + } List links = null; IPath myPath = getProjectRelativePath(); for (LinkDescription link : linkMap.values()) { IPath linkPath = link.getProjectRelativePath(); if (myPath.isPrefixOf(linkPath)) { - if (links == null) + if (links == null) { links = new ArrayList<>(); + } links.add(workspace.newResource(project.getFullPath().append(linkPath), link.getType())); } } @@ -960,8 +993,9 @@ private List findFilters() { IPath myPath = getProjectRelativePath(); for (IPath filterPath : filterMap.keySet()) { if (myPath.isPrefixOf(filterPath)) { - if (filters == null) + if (filters == null) { filters = new ArrayList<>(); + } filters.add(workspace.newResource(project.getFullPath().append(filterPath), IResource.FOLDER)); } } @@ -972,11 +1006,12 @@ private List findFilters() { @Override public boolean equals(Object target) { - if (this == target) + if (this == target) { return true; - if (!(target instanceof Resource)) + } + if (!(target instanceof Resource resource)) { return false; - Resource resource = (Resource) target; + } return getType() == resource.getType() && path.equals(resource.path) && workspace.equals(resource.workspace); } @@ -996,20 +1031,23 @@ public boolean exists(int flags, boolean checkType) { * the given path, or null if no such resource exists. */ public IResource findExistingResourceVariant(IPath target) { - if (!workspace.tree.includesIgnoreCase(target)) + if (!workspace.tree.includesIgnoreCase(target)) { return null; + } // Ignore phantoms. ResourceInfo info = (ResourceInfo) workspace.tree.getElementDataIgnoreCase(target); - if (info != null && info.isSet(M_PHANTOM)) + if (info != null && info.isSet(M_PHANTOM)) { return null; + } // Resort to slow lookup to find exact case variant. IPath result = IPath.ROOT; int segmentCount = target.segmentCount(); for (int i = 0; i < segmentCount; i++) { String[] childNames = workspace.tree.getNamesOfChildren(result); String name = findVariant(target.segment(i), childNames); - if (name == null) + if (name == null) { return null; + } result = result.append(name); } return workspace.getRoot().findMember(result); @@ -1045,8 +1083,9 @@ public int findMaxProblemSeverity(String type, boolean includeSubtypes, int dept */ private String findVariant(String target, String[] list) { for (String element : list) { - if (target.equalsIgnoreCase(element)) + if (target.equalsIgnoreCase(element)) { return element; + } } return null; } @@ -1056,8 +1095,9 @@ protected void fixupAfterMoveSource() throws CoreException { // If a linked resource is moved, we need to remove the location info from the ".project" file. if (isLinked() || isVirtual()) { Project project = (Project) getProject(); - if (project.internalGetDescription().setLinkLocation(getProjectRelativePath(), null)) + if (project.internalGetDescription().setLinkLocation(getProjectRelativePath(), null)) { project.writeDescription(IResource.NONE); + } } List filters = findFilters(); @@ -1065,8 +1105,9 @@ protected void fixupAfterMoveSource() throws CoreException { // Delete resource filters. Project project = (Project) getProject(); ProjectDescription description = project.internalGetDescription(); - for (Resource resource : filters) + for (Resource resource : filters) { description.setFilters(resource.getProjectRelativePath(), null); + } project.writeDescription(IResource.NONE); } @@ -1089,10 +1130,12 @@ protected void fixupAfterMoveSource() throws CoreException { public String getFileExtension() { String name = getName(); int index = name.lastIndexOf('.'); - if (index == -1) + if (index == -1) { return null; - if (index == (name.length() - 1)) + } + if (index == (name.length() - 1)) { return ""; //$NON-NLS-1$ + } return name.substring(index + 1); } @@ -1118,16 +1161,18 @@ public long getLocalTimeStamp() { @Override public IPath getLocation() { IProject project = getProject(); - if (project != null && !project.exists()) + if (project != null && !project.exists()) { return null; + } return getLocalManager().locationFor(this, false); } @Override public URI getLocationURI() { IProject project = getProject(); - if (project != null && !project.exists()) + if (project != null && !project.exists()) { return null; + } return getLocalManager().locationURIFor(this, false); } @@ -1155,10 +1200,12 @@ public String getName() { public IContainer getParent() { int segments = path.segmentCount(); // Zero and one segments handled by subclasses. - if (segments < 2) + if (segments < 2) { Assert.isLegal(false, path.toString()); - if (segments == 2) + } + if (segments == 2) { return workspace.getRoot().getProject(path.segment(0)); + } return (IFolder) workspace.newResource(path.removeLastSegments(1), IResource.FOLDER); } @@ -1190,22 +1237,25 @@ public IPropertyManager getPropertyManager() { @Override public IPath getRawLocation() { - if (isLinked()) + if (isLinked()) { return FileUtil.toPath(((Project) getProject()).internalGetDescription().getLinkLocationURI(getProjectRelativePath())); + } return getLocation(); } @Override public URI getRawLocationURI() { - if (isLinked()) + if (isLinked()) { return ((Project) getProject()).internalGetDescription().getLinkLocationURI(getProjectRelativePath()); + } return getLocationURI(); } @Override public ResourceAttributes getResourceAttributes() { - if (!isAccessible() || isVirtual()) + if (!isAccessible() || isVirtual()) { return null; + } return getLocalManager().attributes(this); } @@ -1279,13 +1329,16 @@ protected void internalSetLocal(boolean flag, int depth) throws CoreException { info.clearModificationStamp(); } } - if (getType() == IResource.FILE || depth == IResource.DEPTH_ZERO) + if (getType() == IResource.FILE || depth == IResource.DEPTH_ZERO) { return; - if (depth == IResource.DEPTH_ONE) + } + if (depth == IResource.DEPTH_ONE) { depth = IResource.DEPTH_ZERO; + } IResource[] children = ((IContainer) this).members(); - for (IResource element : children) + for (IResource element : children) { ((Resource) element).internalSetLocal(flag, depth); + } } @Override @@ -1296,21 +1349,24 @@ public boolean isAccessible() { @Override public boolean isConflicting(ISchedulingRule rule) { // Must not schedule at same time as notification. - if ((this == rule) || rule.getClass().equals(WorkManager.NotifyRule.class)) + if ((this == rule) || rule.getClass().equals(WorkManager.NotifyRule.class)) { return true; - if (rule instanceof MultiRule) { - MultiRule multi = (MultiRule) rule; + } + if (rule instanceof MultiRule multi) { ISchedulingRule[] children = multi.getChildren(); - for (ISchedulingRule element : children) - if (isConflicting(element)) + for (ISchedulingRule element : children) { + if (isConflicting(element)) { return true; + } + } return false; } - if (!(rule instanceof IResource)) + if (!(rule instanceof IResource resource)) { return false; - IResource resource = (IResource) rule; - if (!workspace.equals(resource.getWorkspace())) + } + if (!workspace.equals(resource.getWorkspace())) { return false; + } IPath otherPath = resource.getFullPath(); return path.isPrefixOf(otherPath) || otherPath.isPrefixOf(path); } @@ -1324,11 +1380,13 @@ public boolean isDerived() { public boolean isDerived(int options) { ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); - if (flags != NULL_FLAG && ResourceInfo.isSet(flags, ICoreConstants.M_DERIVED)) + if (flags != NULL_FLAG && ResourceInfo.isSet(flags, ICoreConstants.M_DERIVED)) { return true; + } // Check ancestors if the appropriate option is set. - if ((options & CHECK_ANCESTORS) != 0) + if ((options & CHECK_ANCESTORS) != 0) { return getParent().isDerived(options); + } return false; } @@ -1343,11 +1401,13 @@ public boolean isHidden() { public boolean isHidden(int options) { ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); - if (flags != NULL_FLAG && ResourceInfo.isSet(flags, ICoreConstants.M_HIDDEN)) + if (flags != NULL_FLAG && ResourceInfo.isSet(flags, ICoreConstants.M_HIDDEN)) { return true; + } // Check ancestors if the appropriate option is set. - if ((options & CHECK_ANCESTORS) != 0) + if ((options & CHECK_ANCESTORS) != 0) { return getParent().isHidden(options); + } return false; } @@ -1360,18 +1420,22 @@ public boolean isLinked() { public boolean isLinked(int options) { if ((options & CHECK_ANCESTORS) != 0) { IProject project = getProject(); - if (project == null) + if (project == null) { return false; + } ProjectDescription desc = ((Project) project).internalGetDescription(); - if (desc == null) + if (desc == null) { return false; + } HashMap links = desc.getLinks(); - if (links == null) + if (links == null) { return false; + } IPath myPath = getProjectRelativePath(); for (LinkDescription linkDescription : links.values()) { - if (linkDescription.getProjectRelativePath().isPrefixOf(myPath)) + if (linkDescription.getProjectRelativePath().isPrefixOf(myPath)) { return true; + } } return false; } @@ -1392,8 +1456,9 @@ public boolean isVirtual() { public boolean isUnderVirtual() { IContainer parent = getParent(); while (parent != null) { - if (parent.isVirtual()) + if (parent.isVirtual()) { return true; + } parent = parent.getParent(); } return false; @@ -1426,14 +1491,18 @@ public boolean isLocal(int flags, int depth) { */ protected boolean isMember(int flags, int memberFlags) { int excludeMask = 0; - if ((memberFlags & IContainer.INCLUDE_PHANTOMS) == 0) + if ((memberFlags & IContainer.INCLUDE_PHANTOMS) == 0) { excludeMask |= M_PHANTOM; - if ((memberFlags & IContainer.INCLUDE_HIDDEN) == 0) + } + if ((memberFlags & IContainer.INCLUDE_HIDDEN) == 0) { excludeMask |= M_HIDDEN; - if ((memberFlags & IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS) == 0) + } + if ((memberFlags & IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS) == 0) { excludeMask |= M_TEAM_PRIVATE_MEMBER; - if ((memberFlags & IContainer.EXCLUDE_DERIVED) != 0) + } + if ((memberFlags & IContainer.EXCLUDE_DERIVED) != 0) { excludeMask |= M_DERIVED; + } // The resource is a matching member if it matches none of the exclude flags. return flags != NULL_FLAG && (flags & excludeMask) == 0; } @@ -1471,11 +1540,13 @@ public boolean isTeamPrivateMember() { public boolean isTeamPrivateMember(int options) { ResourceInfo info = getResourceInfo(false, false); int flags = getFlags(info); - if (flags != NULL_FLAG && ResourceInfo.isSet(flags, ICoreConstants.M_TEAM_PRIVATE_MEMBER)) + if (flags != NULL_FLAG && ResourceInfo.isSet(flags, ICoreConstants.M_TEAM_PRIVATE_MEMBER)) { return true; + } // Check ancestors if the appropriate option is set. - if ((options & CHECK_ANCESTORS) != 0) + if ((options & CHECK_ANCESTORS) != 0) { return getParent().isTeamPrivateMember(options); + } return false; } @@ -1485,18 +1556,21 @@ public boolean isTeamPrivateMember(int options) { */ public boolean isUnderLink() { int depth = path.segmentCount(); - if (depth < 2) + if (depth < 2) { return false; - if (depth == 2) + } + if (depth == 2) { return isLinked(); + } // Check if parent at depth two is a link. IPath linkParent = path.removeLastSegments(depth - 2); return workspace.getResourceInfo(linkParent, false, false).isSet(ICoreConstants.M_LINK); } protected IPath makePathAbsolute(IPath target) { - if (target.isAbsolute()) + if (target.isAbsolute()) { return target; + } return getParent().getFullPath().append(target); } @@ -1551,11 +1625,13 @@ public void move(IPath destination, int updateFlags, IProgressMonitor monitor) t workspace.getAliasManager().updateAliases(this, originalStore, IResource.DEPTH_INFINITE, progress.split(24)); workspace.getAliasManager().updateAliases(destResource, destResource.getStore(), IResource.DEPTH_INFINITE, progress.split(24)); } - if (!tree.getStatus().isOK()) + if (!tree.getStatus().isOK()) { throw new ResourceException(tree.getStatus()); + } // If this is a project, make sure the move operation is remembered. - if (getType() == PROJECT) + if (getType() == PROJECT) { workspace.getSaveManager().requestSnapshot(); + } } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); throw e; @@ -1593,11 +1669,13 @@ public void refreshLocal(int depth, IProgressMonitor monitor) throws CoreExcepti SubMonitor split = progress.split(1); try { workspace.prepareOperation(rule, split); - if ((!isRoot && !getProject().isAccessible()) || (!exists() && isFiltered())) + if ((!isRoot && !getProject().isAccessible()) || (!exists() && isFiltered())) { return; + } workspace.beginOperation(true); - if (getType() == IResource.PROJECT || getType() == IResource.ROOT) + if (getType() == IResource.PROJECT || getType() == IResource.ROOT) { workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_REFRESH, this)); + } build = getLocalManager().refresh(this, depth, true, progress.split(98)); } catch (OperationCanceledException e) { workspace.getWorkManager().operationCanceled(); @@ -1620,8 +1698,9 @@ public IPath requestPath() { @Override public void revertModificationStamp(long value) throws CoreException { - if (value < 0) + if (value < 0) { throw new IllegalArgumentException("Illegal value: " + value); //$NON-NLS-1$ + } // Fetch the info but don't bother making it mutable even though we are going to modify it. // It really doesn't matter as the change we are making does not show up in deltas. ResourceInfo info = checkAccessibleAndLocal(DEPTH_ZERO); @@ -1658,8 +1737,9 @@ public void setDerived(boolean isDerived, IProgressMonitor monitor) throws CoreE ResourceInfo info = getResourceInfo(false, false); checkAccessible(getFlags(info)); // Ignore attempts to set derived flag on anything except files and folders. - if (info.getType() != FILE && info.getType() != FOLDER) + if (info.getType() != FILE && info.getType() != FOLDER) { return; + } workspace.beginOperation(true); info = getResourceInfo(false, true); if (isDerived) { @@ -1711,8 +1791,9 @@ public void setLocal(boolean flag, int depth, IProgressMonitor monitor) throws C @Override public long setLocalTimeStamp(long value) throws CoreException { - if (value < 0) + if (value < 0) { throw new IllegalArgumentException("Illegal value: " + value); //$NON-NLS-1$ + } // Fetch the info but don't bother making it mutable even though we are going to modify it. // It really doesn't matter as the change we are making does not show up in deltas. ResourceInfo info = checkAccessibleAndLocal(DEPTH_ZERO); @@ -1729,8 +1810,9 @@ public void setPersistentProperty(QualifiedName key, String value) throws CoreEx @Override public void setReadOnly(boolean readonly) { ResourceAttributes attributes = getResourceAttributes(); - if (attributes == null) + if (attributes == null) { return; + } attributes.setReadOnly(readonly); try { setResourceAttributes(attributes); @@ -1822,16 +1904,19 @@ private void unprotectedDelete(ResourceTree tree, int updateFlags, IProgressMoni try { switch (getType()) { case IResource.FILE: - if (!hook.deleteFile(tree, (IFile) this, updateFlags, progress.split(1))) + if (!hook.deleteFile(tree, (IFile) this, updateFlags, progress.split(1))) { tree.standardDeleteFile((IFile) this, updateFlags, progress.split(1)); + } break; case IResource.FOLDER: - if (!hook.deleteFolder(tree, (IFolder) this, updateFlags, progress.split(1))) + if (!hook.deleteFolder(tree, (IFolder) this, updateFlags, progress.split(1))) { tree.standardDeleteFolder((IFolder) this, updateFlags, progress.split(1)); + } break; case IResource.PROJECT: - if (!hook.deleteProject(tree, (IProject) this, updateFlags, progress.split(1))) + if (!hook.deleteProject(tree, (IProject) this, updateFlags, progress.split(1))) { tree.standardDeleteProject((IProject) this, updateFlags, progress.split(1)); + } break; case IResource.ROOT: // When the root is deleted, all its children including hidden projects have to @@ -1839,8 +1924,9 @@ private void unprotectedDelete(ResourceTree tree, int updateFlags, IProgressMoni IProject[] projects = ((IWorkspaceRoot) this).getProjects(IContainer.INCLUDE_HIDDEN); progress.setWorkRemaining(projects.length * 2); for (IProject project : projects) { - if (!hook.deleteProject(tree, project, updateFlags, progress.split(1))) + if (!hook.deleteProject(tree, project, updateFlags, progress.split(1))) { tree.standardDeleteProject(project, updateFlags, progress.split(1)); + } } break; } @@ -1860,22 +1946,26 @@ private boolean unprotectedMove(ResourceTree tree, final IResource destination, try { switch (getType()) { case IResource.FILE: - if (!hook.moveFile(tree, (IFile) this, (IFile) destination, updateFlags, progress.split(1))) + if (!hook.moveFile(tree, (IFile) this, (IFile) destination, updateFlags, progress.split(1))) { tree.standardMoveFile((IFile) this, (IFile) destination, updateFlags, progress.split(1)); + } break; case IResource.FOLDER: - if (!hook.moveFolder(tree, (IFolder) this, (IFolder) destination, updateFlags, progress.split(1))) + if (!hook.moveFolder(tree, (IFolder) this, (IFolder) destination, updateFlags, progress.split(1))) { tree.standardMoveFolder((IFolder) this, (IFolder) destination, updateFlags, progress.split(1)); + } break; case IResource.PROJECT: IProject project = (IProject) this; // If there is no change in name, there is nothing to do so return. - if (getName().equals(destination.getName())) + if (getName().equals(destination.getName())) { return false; + } IProjectDescription description = project.getDescription(); description.setName(destination.getName()); - if (!hook.moveProject(tree, project, description, updateFlags, progress.split(1))) + if (!hook.moveProject(tree, project, description, updateFlags, progress.split(1))) { tree.standardMoveProject(project, description, updateFlags, progress.split(1)); + } break; case IResource.ROOT: String msg = Messages.resources_moveRoot; @@ -1905,14 +1995,17 @@ private void broadcastPreDeleteEvent() throws CoreException { private void broadcastPreMoveEvent(final IResource destination, int updateFlags) throws CoreException { switch (getType()) { case IResource.FILE : - if (isLinked()) + if (isLinked()) { workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_LINK_MOVE, this, destination, updateFlags)); + } break; case IResource.FOLDER : - if (isLinked()) + if (isLinked()) { workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_LINK_MOVE, this, destination, updateFlags)); - if (isVirtual()) + } + if (isVirtual()) { workspace.broadcastEvent(LifecycleEvent.newEvent(LifecycleEvent.PRE_GROUP_MOVE, this, destination, updateFlags)); + } break; case IResource.PROJECT : if (!getName().equals(destination.getName())) { @@ -1925,8 +2018,9 @@ private void broadcastPreMoveEvent(final IResource destination, int updateFlags) @Override public IPathVariableManager getPathVariableManager() { - if (getProject() == null) + if (getProject() == null) { return workspace.getPathVariableManager(); + } return new ProjectPathVariableManager(this); } @@ -1950,15 +2044,18 @@ public boolean isFiltered() { } public boolean isFilteredWithException(boolean throwExeception) throws CoreException { - if (isLinked() || isVirtual()) + if (isLinked() || isVirtual()) { return false; + } Project project = (Project) getProject(); - if (project == null) + if (project == null) { return false; + } final ProjectDescription description = project.internalGetDescription(); - if ((description == null) || (description.getFilters() == null)) + if ((description == null) || (description.getFilters() == null)) { return false; + } Resource currentResource = this; while (currentResource != null && currentResource.getParent() != null) { @@ -1969,8 +2066,9 @@ public boolean isFilteredWithException(boolean throwExeception) throws CoreExcep fileInfo.setDirectory(currentResource.getType() == IResource.FOLDER); if (fileInfo != null) { IFileInfo[] filtered = parent.filterChildren(project, description, new IFileInfo[] {fileInfo}, throwExeception); - if (filtered.length == 0) + if (filtered.length == 0) { return true; + } } } currentResource = parent; @@ -1980,11 +2078,13 @@ public boolean isFilteredWithException(boolean throwExeception) throws CoreExcep public IFileInfo[] filterChildren(IFileInfo[] list, boolean throwException) throws CoreException { Project project = (Project) getProject(); - if (project == null) + if (project == null) { return list; + } final ProjectDescription description = project.internalGetDescription(); - if (description == null) + if (description == null) { return list; + } return filterChildren(project, description, list, throwException); } @@ -1996,23 +2096,26 @@ private IFileInfo[] filterChildren(Project project, ProjectDescription descripti boolean firstSegment = true; do { - if (!firstSegment) + if (!firstSegment) { relativePath = relativePath.removeLastSegments(1); + } filters = description.getFilter(relativePath); if (filters != null) { for (FilterDescription desc : filters) { if (firstSegment || desc.isInheritable()) { Filter filter = new Filter(project, desc); if (filter.isIncludeOnly()) { - if (filter.isFirst()) + if (filter.isFirst()) { currentIncludeFilters.addFirst(filter); - else + } else { currentIncludeFilters.addLast(filter); + } } else { - if (filter.isFirst()) + if (filter.isFirst()) { currentExcludeFilters.addFirst(filter); - else + } else { currentExcludeFilters.addLast(filter); + } } } } @@ -2024,8 +2127,9 @@ private IFileInfo[] filterChildren(Project project, ProjectDescription descripti try { list = Filter.filter(project, currentIncludeFilters, currentExcludeFilters, (IContainer) this, list); } catch (CoreException e) { - if (throwException) + if (throwException) { throw e; + } } } return list; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceException.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceException.java index 76dcd64ced4..651d08c823d 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceException.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceException.java @@ -73,12 +73,14 @@ public void printStackTrace(PrintStream output) { IStatus status = getStatus(); if (status.getException() != null) { String path = "()"; //$NON-NLS-1$ - if (status instanceof IResourceStatus) + if (status instanceof IResourceStatus) { path = "(" + ((IResourceStatus) status).getPath() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } output.print(getClass().getName() + path + "[" + status.getCode() + "]: "); //$NON-NLS-1$ //$NON-NLS-2$ status.getException().printStackTrace(output); - } else + } else { super.printStackTrace(output); + } } } @@ -93,12 +95,14 @@ public void printStackTrace(PrintWriter output) { IStatus status = getStatus(); if (status.getException() != null) { String path = "()"; //$NON-NLS-1$ - if (status instanceof IResourceStatus) + if (status instanceof IResourceStatus) { path = "(" + ((IResourceStatus) status).getPath() + ")"; //$NON-NLS-1$ //$NON-NLS-2$ + } output.print(getClass().getName() + path + "[" + status.getCode() + "]: "); //$NON-NLS-1$ //$NON-NLS-2$ status.getException().printStackTrace(output); - } else + } else { super.printStackTrace(output); + } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceInfo.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceInfo.java index ee275163425..f5df7552d1b 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceInfo.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceInfo.java @@ -193,8 +193,9 @@ public MarkerSet getMarkers() { * null is returned if there are none. */ public MarkerSet getMarkers(boolean makeCopy) { - if (markers == null) + if (markers == null) { return null; + } return makeCopy ? (MarkerSet) markers.clone() : markers; } @@ -221,10 +222,11 @@ public Object getPropertyStore() { public Map getSessionProperties() { // thread safety: (Concurrency001) ObjectMap temp = sessionProperties; - if (temp == null) + if (temp == null) { temp = new ObjectMap<>(5); - else + } else { temp = (ObjectMap) sessionProperties.clone(); + } return temp; } @@ -234,8 +236,9 @@ public Map getSessionProperties() { public Object getSessionProperty(QualifiedName name) { // thread safety: (Concurrency001) Map temp = sessionProperties; - if (temp == null) + if (temp == null) { return null; + } return temp.get(name); } @@ -246,16 +249,18 @@ public Object getSessionProperty(QualifiedName name) { */ @SuppressWarnings({"unchecked"}) public synchronized ObjectMap getSyncInfo(boolean makeCopy) { - if (syncInfo == null) + if (syncInfo == null) { return null; + } return makeCopy ? (ObjectMap) syncInfo.clone() : syncInfo; } public synchronized byte[] getSyncInfo(QualifiedName id, boolean makeCopy) { // thread safety: (Concurrency001) byte[] b; - if (syncInfo == null) + if (syncInfo == null) { return null; + } b = (byte[]) syncInfo.get(id); return b == null ? null : (makeCopy ? (byte[]) b.clone() : b); } @@ -395,8 +400,9 @@ public void setNodeId(long id) { nodeId = id; // Resource modification stamp starts from current nodeId // so future generations are distinguishable (bug 160728) - if (modStamp == 0) + if (modStamp == 0) { modStamp = nodeId; + } } /** @@ -414,20 +420,23 @@ public void setPropertyStore(Object value) { public synchronized void setSessionProperty(QualifiedName name, Object value) { // thread safety: (Concurrency001) if (value == null) { - if (sessionProperties == null) + if (sessionProperties == null) { return; + } ObjectMap temp = (ObjectMap) sessionProperties.clone(); temp.remove(name); - if (temp.isEmpty()) + if (temp.isEmpty()) { sessionProperties = null; - else + } else { sessionProperties = temp; + } } else { ObjectMap temp = sessionProperties; - if (temp == null) + if (temp == null) { temp = new ObjectMap<>(5); - else + } else { temp = (ObjectMap) sessionProperties.clone(); + } temp.put(name, value); sessionProperties = temp; } @@ -445,15 +454,18 @@ protected void setSyncInfo(ObjectMap syncInfo) { public synchronized void setSyncInfo(QualifiedName id, byte[] value) { if (value == null) { //delete sync info - if (syncInfo == null) + if (syncInfo == null) { return; + } syncInfo.remove(id); - if (syncInfo.isEmpty()) + if (syncInfo.isEmpty()) { syncInfo = null; + } } else { //add sync info - if (syncInfo == null) + if (syncInfo == null) { syncInfo = new ObjectMap<>(5); + } syncInfo.put(id, value.clone()); } } @@ -472,14 +484,17 @@ public void setType(int value) { @Override public void shareStrings(StringPool set) { ObjectMap map = syncInfo; - if (map != null) + if (map != null) { map.shareStrings(set); + } map = sessionProperties; - if (map != null) + if (map != null) { map.shareStrings(set); + } MarkerSet markerSet = markers; - if (markerSet != null) + if (markerSet != null) { markerSet.shareStrings(set); + } } public void writeTo(DataOutput output) throws IOException { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceProxy.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceProxy.java index 1d6e4f858d0..596861ea45c 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceProxy.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceProxy.java @@ -60,8 +60,9 @@ public int getType() { @Override public boolean isAccessible() { int flags = info.getFlags(); - if (info.getType() == IResource.PROJECT) + if (info.getType() == IResource.PROJECT) { return flags != NULL_FLAG && ResourceInfo.isSet(flags, M_OPEN); + } return flags != NULL_FLAG; } @@ -115,8 +116,9 @@ public boolean isHidden() { */ @Override public IPath requestFullPath() { - if (fullPath == null) + if (fullPath == null) { fullPath = requestor.requestPath(); + } return fullPath; } @@ -125,8 +127,9 @@ public IPath requestFullPath() { */ @Override public IResource requestResource() { - if (resource == null) + if (resource == null) { resource = workspace.newResource(requestFullPath(), info.getType()); + } return resource; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceTree.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceTree.java index 370ada4b88c..4d78eab6595 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceTree.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/ResourceTree.java @@ -67,12 +67,14 @@ public void addToLocalHistory(IFile file) { Assert.isLegal(isValid); try { lock.acquire(); - if (!file.exists()) + if (!file.exists()) { return; + } IFileStore store = localManager.getStore(file); final IFileInfo fileInfo = store.fetchInfo(); - if (!fileInfo.exists()) + if (!fileInfo.exists()) { return; + } localManager.getHistoryStore().addState(file.getFullPath(), store, fileInfo, false); } finally { lock.release(); @@ -97,8 +99,9 @@ public long computeTimestamp(IFile file) { Assert.isLegal(isValid); try { lock.acquire(); - if (!file.getProject().exists()) + if (!file.getProject().exists()) { return NULL_TIMESTAMP; + } return internalComputeTimestamp(file); } finally { lock.release(); @@ -124,8 +127,9 @@ public void deletedFile(IFile file) { try { lock.acquire(); // Do nothing if the resource doesn't exist. - if (!file.exists()) + if (!file.exists()) { return; + } try { // Delete properties, generate marker deltas, and remove the node from the workspace tree. ((Resource) file).deleteResource(true, null); @@ -148,8 +152,9 @@ public void deletedFolder(IFolder folder) { try { lock.acquire(); // Do nothing if the resource doesn't exist. - if (!folder.exists()) + if (!folder.exists()) { return; + } try { // Delete properties, generate marker deltas, and remove the node from the workspace tree. ((Resource) folder).deleteResource(true, null); @@ -172,8 +177,9 @@ public void deletedProject(IProject target) { try { lock.acquire(); // Do nothing if the resource doesn't exist. - if (!target.exists()) + if (!target.exists()) { return; + } // Delete properties, generate marker deltas, and remove the node from the workspace tree. try { ((Project) target).deleteResource(false, null); @@ -195,13 +201,15 @@ public void deletedProject(IProject target) { private boolean ensureDestinationEmpty(IProject source, IFileStore destinationStore, IProgressMonitor monitor) throws CoreException { String message; //Make sure the destination location is unoccupied - if (!destinationStore.fetchInfo().exists()) + if (!destinationStore.fetchInfo().exists()) { return true; + } //check for existing children if (destinationStore.childNames(EFS.NONE, Policy.subMonitorFor(monitor, 0)).length > 0) { //allow case rename to proceed - if (((Resource) source).getStore().equals(destinationStore)) + if (((Resource) source).getStore().equals(destinationStore)) { return true; + } //fail because the destination is occupied message = NLS.bind(Messages.localstore_resourceExists, destinationStore); IStatus status = new ResourceStatus(IStatus.ERROR, source.getFullPath(), message, null); @@ -238,8 +246,9 @@ public long getTimestamp(IFile file) { Assert.isLegal(isValid); try { lock.acquire(); - if (!file.exists()) + if (!file.exists()) { return NULL_TIMESTAMP; + } ResourceInfo info = ((File) file).getResourceInfo(false, false); return info == null ? NULL_TIMESTAMP : info.getLocalSyncInfo(); } finally { @@ -291,8 +300,9 @@ private boolean internalDeleteFile(IFile file, int flags, IProgressMonitor monit boolean force = (flags & IResource.FORCE) != 0; // Add the file to the local history if requested by the user. - if (keepHistory) + if (keepHistory) { addToLocalHistory(file); + } monitor.worked(Policy.totalWork / 4); // We want to fail if force is false and the file is not synchronized with the @@ -341,8 +351,9 @@ private boolean internalDeleteFolder(IFolder folder, int flags, IProgressMonitor subMonitor.subTask(message); // Do nothing if the folder doesn't exist in the workspace. - if (!folder.exists()) + if (!folder.exists()) { return true; + } // Don't delete contents if this is a linked resource if (folder.isLinked()) { @@ -390,8 +401,9 @@ private boolean internalDeleteProject(IProject project, int flags, IProgressMoni switch (child.getType()) { case IResource.FILE : // ignore the .project file for now and delete it last - if (!IProjectDescription.DESCRIPTION_FILE_NAME.equals(child.getName())) + if (!IProjectDescription.DESCRIPTION_FILE_NAME.equals(child.getName())) { deletedChildren &= internalDeleteFile((IFile) child, flags, Policy.subMonitorFor(monitor, Policy.totalWork / members.length)); + } break; case IResource.FOLDER : deletedChildren &= internalDeleteFolder((IFolder) child, flags, Policy.subMonitorFor(monitor, Policy.totalWork / members.length)); @@ -402,9 +414,10 @@ private boolean internalDeleteProject(IProject project, int flags, IProgressMoni // Check to see if the children were deleted ok. If there was a problem // just return as the problem should have been logged by the recursive // call to the child. - if (!deletedChildren) + if (!deletedChildren) { // Indicate that the delete was unsuccessful. return false; + } //Check if there are any undiscovered children of the project on disk other than description file String[] children; @@ -464,8 +477,9 @@ private boolean isContentChange(IProject project, IProjectDescription destDescri IProjectDescription srcDescription = ((Project) project).internalGetDescription(); URI srcLocation = srcDescription.getLocationURI(); URI destLocation = destDescription.getLocationURI(); - if (srcLocation == null || destLocation == null) + if (srcLocation == null || destLocation == null) { return true; + } //don't use URIUtil because we want to treat case rename as a content change return !srcLocation.equals(destLocation); } @@ -521,8 +535,9 @@ public void movedFile(IFile source, IFile destination) { try { lock.acquire(); // Do nothing if the resource doesn't exist. - if (!source.exists()) + if (!source.exists()) { return; + } // If the destination already exists then we have a problem. if (destination.exists()) { String message = NLS.bind(Messages.resources_mustNotExist, destination.getFullPath()); @@ -579,8 +594,9 @@ public void movedFolderSubtree(IFolder source, IFolder destination) { try { lock.acquire(); // Do nothing if the source resource doesn't exist. - if (!source.exists()) + if (!source.exists()) { return; + } // If the destination already exists then we have an error. if (destination.exists()) { String message = NLS.bind(Messages.resources_mustNotExist, destination.getFullPath()); @@ -638,8 +654,9 @@ public boolean movedProjectSubtree(IProject project, IProjectDescription destDes try { lock.acquire(); // Do nothing if the source resource doesn't exist. - if (!project.exists()) + if (!project.exists()) { return true; + } Project source = (Project) project; Project destination = (Project) source.getWorkspace().getRoot().getProject(destDescription.getName()); @@ -753,8 +770,9 @@ private void moveProjectContent(IProject source, IFileStore destStore, int flags IProjectDescription srcDescription = source.getDescription(); URI srcLocation = srcDescription.getLocationURI(); // If the locations are the same (and non-default) then there is nothing to do. - if (srcLocation != null && URIUtil.equals(srcLocation, destStore.toURI())) + if (srcLocation != null && URIUtil.equals(srcLocation, destStore.toURI())) { return; + } //If this is a replace, just make sure the destination location exists, and return boolean replace = (flags & IResource.REPLACE) != 0; @@ -832,8 +850,9 @@ public void standardDeleteProject(IProject project, int flags, IProgressMonitor String message = NLS.bind(Messages.resources_deleting, project.getFullPath()); monitor.beginTask(message, Policy.totalWork); // Do nothing if the project doesn't exist in the workspace tree. - if (!project.exists()) + if (!project.exists()) { return; + } boolean alwaysDeleteContent = (flags & IResource.ALWAYS_DELETE_PROJECT_CONTENT) != 0; boolean neverDeleteContent = (flags & IResource.NEVER_DELETE_PROJECT_CONTENT) != 0; @@ -884,9 +903,9 @@ public void standardDeleteProject(IProject project, int flags, IProgressMonitor } // Signal that the workspace tree should be updated that the project has been deleted. - if (success) + if (success) { deletedProject(project); - else { + } else { message = NLS.bind(Messages.localstore_couldnotDelete, project.getFullPath()); IStatus status = new ResourceStatus(IResourceStatus.FAILED_DELETE_LOCAL, project.getFullPath(), message); failed(status); @@ -909,8 +928,9 @@ public void standardMoveFile(IFile source, IFile destination, int flags, IProgre monitor.beginTask(message, Policy.totalWork); // These pre-conditions should all be ok but just in case... - if (!source.exists() || destination.exists() || !destination.getParent().isAccessible()) + if (!source.exists() || destination.exists() || !destination.getParent().isAccessible()) { throw new IllegalArgumentException(); + } boolean force = (flags & IResource.FORCE) != 0; boolean keepHistory = (flags & IResource.KEEP_HISTORY) != 0; @@ -927,8 +947,9 @@ public void standardMoveFile(IFile source, IFile destination, int flags, IProgre monitor.worked(Policy.totalWork / 4); // Add the file contents to the local history if requested by the user. - if (keepHistory) + if (keepHistory) { addToLocalHistory(source); + } monitor.worked(Policy.totalWork / 4); //for shallow move of linked resources, nothing needs to be moved in the file system @@ -951,8 +972,9 @@ public void standardMoveFile(IFile source, IFile destination, int flags, IProgre // did the fail occur after copying to the destination? failedDeletingSource = destStore != null && destStore.fetchInfo().exists(); // if so, we should proceed - if (!failedDeletingSource) + if (!failedDeletingSource) { return; + } } movedFile(source, destination); updateMovedFileTimestamp(destination, internalComputeTimestamp(destination)); @@ -984,8 +1006,9 @@ public void standardMoveFolder(IFolder source, IFolder destination, int flags, I monitor.beginTask(message, 100); // These pre-conditions should all be ok but just in case... - if (!source.exists() || destination.exists() || !destination.getParent().isAccessible()) + if (!source.exists() || destination.exists() || !destination.getParent().isAccessible()) { throw new IllegalArgumentException(); + } // Check to see if we are synchronized with the local file system. If we are in sync then we can // short circuit this method and do a file system only move. Otherwise we have to recursively @@ -1018,8 +1041,9 @@ public void standardMoveFolder(IFolder source, IFolder destination, int flags, I // did the fail occur after copying to the destination? failedDeletingSource = destStore != null && destStore.fetchInfo().exists(); // if so, we should proceed - if (!failedDeletingSource) + if (!failedDeletingSource) { return; + } } movedFolderSubtree(source, destination); monitor.worked(20); @@ -1051,8 +1075,9 @@ public void standardMoveProject(IProject source, IProjectDescription description monitor.beginTask(message, Policy.totalWork); // Double-check this pre-condition. - if (!source.isAccessible()) + if (!source.isAccessible()) { throw new IllegalArgumentException(); + } // If there is nothing to do on disk then signal to make the workspace tree // changes. @@ -1075,9 +1100,11 @@ public void standardMoveProject(IProject source, IProjectDescription description try { destinationStore = computeDestinationStore(description); //destination can be non-empty on replace - if ((flags & IResource.REPLACE) == 0) - if (!ensureDestinationEmpty(source, destinationStore, monitor)) + if ((flags & IResource.REPLACE) == 0) { + if (!ensureDestinationEmpty(source, destinationStore, monitor)) { return; + } + } } catch (CoreException e) { //must fail if the destination location cannot be accessd (undefined file system) message = NLS.bind(Messages.localstore_couldNotMove, source.getFullPath()); @@ -1124,8 +1151,9 @@ public void updateMovedFileTimestamp(IFile file, long timestamp) { try { lock.acquire(); // Do nothing if the file doesn't exist in the workspace tree. - if (!file.exists()) + if (!file.exists()) { return; + } // Update the timestamp in the tree. ResourceInfo info = ((Resource) file).getResourceInfo(false, true); // The info should never be null since we just checked that the resource exists in the tree. diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Rules.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Rules.java index a65c35e44b0..3a3af68539d 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Rules.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Rules.java @@ -64,8 +64,9 @@ public ISchedulingRule buildRule() { */ @Override public ISchedulingRule copyRule(IResource source, IResource destination) { - if (source.getType() == IResource.ROOT || destination.getType() == IResource.ROOT) + if (source.getType() == IResource.ROOT || destination.getType() == IResource.ROOT) { return root; + } //source is not modified, destination is created return factoryFor(destination).copyRule(source, destination); } @@ -75,8 +76,9 @@ public ISchedulingRule copyRule(IResource source, IResource destination) { */ @Override public ISchedulingRule createRule(IResource resource) { - if (resource.getType() == IResource.ROOT) + if (resource.getType() == IResource.ROOT) { return root; + } return factoryFor(resource).createRule(resource); } @@ -85,8 +87,9 @@ public ISchedulingRule createRule(IResource resource) { */ @Override public ISchedulingRule deleteRule(IResource resource) { - if (resource.getType() == IResource.ROOT) + if (resource.getType() == IResource.ROOT) { return root; + } return factoryFor(resource).deleteRule(resource); } @@ -97,8 +100,9 @@ private IResourceRuleFactory factoryFor(IResource destination) { IResourceRuleFactory fac = projectsToRules.get(destination.getFullPath().segment(0)); if (fac == null) { //use the default factory if the project is not yet accessible - if (!destination.getProject().isAccessible()) + if (!destination.getProject().isAccessible()) { return defaultFactory; + } //ask the team hook to supply one fac = teamHook.getRuleFactory(destination.getProject()); projectsToRules.put(destination.getFullPath().segment(0), fac); @@ -124,8 +128,9 @@ public void handleEvent(LifecycleEvent event) { */ @Override public ISchedulingRule charsetRule(IResource resource) { - if (resource.getType() == IResource.ROOT) + if (resource.getType() == IResource.ROOT) { return null; + } return factoryFor(resource).charsetRule(resource); } @@ -152,8 +157,9 @@ public ISchedulingRule markerRule(IResource resource) { */ @Override public ISchedulingRule modifyRule(IResource resource) { - if (resource.getType() == IResource.ROOT) + if (resource.getType() == IResource.ROOT) { return root; + } return factoryFor(resource).modifyRule(resource); } @@ -162,11 +168,13 @@ public ISchedulingRule modifyRule(IResource resource) { */ @Override public ISchedulingRule moveRule(IResource source, IResource destination) { - if (source.getType() == IResource.ROOT || destination.getType() == IResource.ROOT) + if (source.getType() == IResource.ROOT || destination.getType() == IResource.ROOT) { return root; + } //treat a move across projects as a create on the destination and a delete on the source - if (!source.getFullPath().segment(0).equals(destination.getFullPath().segment(0))) + if (!source.getFullPath().segment(0).equals(destination.getFullPath().segment(0))) { return MultiRule.combine(modifyRule(source.getProject()), modifyRule(destination.getProject())); + } return factoryFor(source).moveRule(source, destination); } @@ -175,8 +183,9 @@ public ISchedulingRule moveRule(IResource source, IResource destination) { */ @Override public ISchedulingRule refreshRule(IResource resource) { - if (resource.getType() == IResource.ROOT) + if (resource.getType() == IResource.ROOT) { return root; + } return factoryFor(resource).refreshRule(resource); } @@ -184,10 +193,11 @@ public ISchedulingRule refreshRule(IResource resource) { * Implements TeamHook#setRuleFactory */ void setRuleFactory(IProject project, IResourceRuleFactory factory) { - if (factory == null) + if (factory == null) { projectsToRules.remove(project.getName()); - else + } else { projectsToRules.put(project.getName(), factory); + } } /** @@ -196,29 +206,35 @@ void setRuleFactory(IProject project, IResourceRuleFactory factory) { */ @Override public ISchedulingRule validateEditRule(IResource[] resources) { - if (resources.length == 0) + if (resources.length == 0) { return null; + } //optimize rule for single file if (resources.length == 1) { - if (resources[0].getType() == IResource.ROOT) + if (resources[0].getType() == IResource.ROOT) { return root; + } return factoryFor(resources[0]).validateEditRule(resources); } //gather rules for each resource from appropriate factory HashSet rules = new HashSet<>(); IResource[] oneResource = new IResource[1]; for (IResource resource : resources) { - if (resource.getType() == IResource.ROOT) + if (resource.getType() == IResource.ROOT) { return root; + } oneResource[0] = resource; ISchedulingRule rule = factoryFor(resource).validateEditRule(oneResource); - if (rule != null) + if (rule != null) { rules.add(rule); + } } - if (rules.isEmpty()) + if (rules.isEmpty()) { return null; - if (rules.size() == 1) + } + if (rules.size() == 1) { return rules.iterator().next(); + } ISchedulingRule[] ruleArray = rules.toArray(new ISchedulingRule[rules.size()]); return new MultiRule(ruleArray); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SafeFileTable.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SafeFileTable.java index 0a15f739e3a..6a74074f33f 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SafeFileTable.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SafeFileTable.java @@ -44,8 +44,9 @@ public IPath[] getFiles() { Set set = table.keySet(); String[] keys = set.toArray(new String[set.size()]); IPath[] files = new IPath[keys.length]; - for (int i = 0; i < keys.length; i++) + for (int i = 0; i < keys.length; i++) { files[i] = IPath.fromOSString(keys[i]); + } return files; } @@ -59,17 +60,19 @@ public IPath lookup(IPath file) { } public void map(IPath file, IPath aLocation) { - if (aLocation == null) + if (aLocation == null) { table.remove(file); - else + } else { table.setProperty(file.toOSString(), aLocation.toOSString()); + } } public void restore() throws CoreException { java.io.File target = location.toFile(); table = new Properties(); - if (!target.exists()) + if (!target.exists()) { return; + } try (FileInputStream input = new FileInputStream(target)) { table.load(input); } catch (IOException e) { @@ -89,7 +92,8 @@ public void save() throws CoreException { } public void setLocation(IPath location) { - if (location != null) + if (location != null) { this.location = location; + } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SaveManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SaveManager.java index 25493cf919c..b666609579b 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SaveManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SaveManager.java @@ -210,8 +210,9 @@ public SaveManager(Workspace workspace) { public ISavedState addParticipant(String pluginId, ISaveParticipant participant) throws CoreException { // If the plugin was already registered as a save participant we return null - if (saveParticipants.put(pluginId, participant) != null) + if (saveParticipants.put(pluginId, participant) != null) { return null; + } SavedState state = savedStates.get(pluginId); if (state != null) { if (isDeltaCleared(pluginId)) { @@ -232,8 +233,9 @@ public ISavedState addParticipant(String pluginId, ISaveParticipant participant) } } // if the plug-in has a previous save number, we return a state, otherwise we return null - if (getSaveNumber(pluginId) > 0) + if (getSaveNumber(pluginId) > 0) { return new SavedState(workspace, pluginId, null, null); + } return null; } @@ -289,15 +291,18 @@ protected void cleanMasterTable() { //remove tree file entries for everything except closed projects for (Iterator it = masterTable.keySet().iterator(); it.hasNext();) { String key = (String) it.next(); - if (!key.endsWith(LocalMetaArea.F_TREE)) + if (!key.endsWith(LocalMetaArea.F_TREE)) { continue; + } String prefix = key.substring(0, key.length() - LocalMetaArea.F_TREE.length()); //always save the root tree entry - if (prefix.equals(IPath.ROOT.toString())) + if (prefix.equals(IPath.ROOT.toString())) { continue; + } IProject project = workspace.getRoot().getProject(prefix); - if (!project.exists() || project.isOpen()) + if (!project.exists() || project.isOpen()) { it.remove(); + } } savedState = null; IPath location = workspace.getMetaArea().getSafeTableLocationFor(ResourcesPlugin.PI_RESOURCES); @@ -309,8 +314,9 @@ protected void cleanMasterTable() { backup.toFile().delete(); return; } - if (location.toFile().exists() && !location.toFile().delete()) + if (location.toFile().exists() && !location.toFile().delete()) { return; + } try { saveMasterTable(ISaveContext.FULL_SAVE, location); } catch (CoreException e) { @@ -372,8 +378,9 @@ protected void collapseTrees(Map contexts) throws CoreExcep } //no need to collapse if there are no trees at this point - if (trees.isEmpty()) + if (trees.isEmpty()) { return; + } //the complete tree trees.add(workspace.getElementTree()); @@ -386,15 +393,18 @@ protected void collapseTrees(Map contexts) throws CoreExcep ElementTree[] sorted = sortTrees(treeArray); // if there was a problem sorting the tree, bail on trying to collapse. // We will be able to GC the layers at a later time. - if (sorted == null) + if (sorted == null) { return; - for (int i = 1; i < sorted.length; i++) + } + for (int i = 1; i < sorted.length; i++) { sorted[i].collapseTo(sorted[i - 1]); + } } protected void commit(Map contexts) throws CoreException { - for (SaveContext saveContext : contexts.values()) + for (SaveContext saveContext : contexts.values()) { saveContext.commit(); + } } /** @@ -428,13 +438,15 @@ protected Map computeStatesToSave(Map HashMap result = new HashMap<>(savedStates.size() * 2); synchronized (savedStates) { for (SavedState state : savedStates.values()) { - if (state.oldTree != null) + if (state.oldTree != null) { result.put(state.pluginId, state.oldTree); + } } } for (SaveContext context : contexts.values()) { - if (!context.isDeltaNeeded()) + if (!context.isDeltaNeeded()) { continue; + } String pluginId = context.getPluginId(); result.put(pluginId, current); } @@ -448,12 +460,14 @@ protected void executeLifecycle(int lifecycle, ISaveParticipant participant, Sav break; case SAVING : try { - if (ResourceStats.TRACE_SAVE_PARTICIPANTS) + if (ResourceStats.TRACE_SAVE_PARTICIPANTS) { ResourceStats.startSave(participant); + } participant.saving(context); } finally { - if (ResourceStats.TRACE_SAVE_PARTICIPANTS) + if (ResourceStats.TRACE_SAVE_PARTICIPANTS) { ResourceStats.endSave(); + } } break; case DONE_SAVING : @@ -470,13 +484,15 @@ protected void executeLifecycle(int lifecycle, ISaveParticipant participant, Sav public void forgetSavedTree(String pluginId) { if (pluginId == null) { synchronized (savedStates) { - for (SavedState state : savedStates.values()) + for (SavedState state : savedStates.values()) { state.forgetTrees(); + } } } else { SavedState state = savedStates.get(pluginId); - if (state != null) + if (state != null) { state.forgetTrees(); + } } } @@ -508,8 +524,9 @@ protected String[] getSaveParticipantPluginIds() { * monitoring purposes. */ private void hookEndSave(int kind, IProject project, long start) { - if (ResourceStats.TRACE_SNAPSHOT && kind == ISaveContext.SNAPSHOT) + if (ResourceStats.TRACE_SNAPSHOT && kind == ISaveContext.SNAPSHOT) { ResourceStats.endSnapshot(); + } if (Policy.DEBUG_SAVE) { String endMessage = null; switch (kind) { @@ -523,8 +540,9 @@ private void hookEndSave(int kind, IProject project, long start) { endMessage = DEBUG_PROJECT_SAVE + project.getFullPath() + ": "; //$NON-NLS-1$ break; } - if (endMessage != null) + if (endMessage != null) { Policy.debug(endMessage + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ + } } } @@ -533,8 +551,9 @@ private void hookEndSave(int kind, IProject project, long start) { * monitoring purposes. */ private void hookStartSave(int kind, Project project) { - if (ResourceStats.TRACE_SNAPSHOT && kind == ISaveContext.SNAPSHOT) + if (ResourceStats.TRACE_SNAPSHOT && kind == ISaveContext.SNAPSHOT) { ResourceStats.startSnapshot(); + } if (Policy.DEBUG_SAVE) { switch (kind) { case ISaveContext.FULL_SAVE : @@ -566,18 +585,21 @@ protected void initSnap(IProgressMonitor monitor) { IPath location = workspace.getMetaArea().getSnapshotLocationFor(workspace.getRoot()); java.io.File target = location.toFile().getParentFile(); FilenameFilter filter = (dir, name) -> { - if (!name.endsWith(LocalMetaArea.F_SNAP)) + if (!name.endsWith(LocalMetaArea.F_SNAP)) { return false; + } for (int i = 0; i < name.length() - LocalMetaArea.F_SNAP.length(); i++) { char c = name.charAt(i); - if (c < '0' || c > '9') + if (c < '0' || c > '9') { return false; + } } return true; }; String[] candidates = target.list(filter); - if (candidates != null) + if (candidates != null) { removeFiles(target, candidates, Collections. emptyList()); + } } protected boolean isDeltaCleared(String pluginId) { @@ -587,11 +609,13 @@ protected boolean isDeltaCleared(String pluginId) { protected boolean isOldPluginTree(String pluginId) { // first, check if this plug-ins was marked not to receive a delta - if (isDeltaCleared(pluginId)) + if (isDeltaCleared(pluginId)) { return false; + } //see if the plugin is still installed - if (Platform.getBundle(pluginId) == null) + if (Platform.getBundle(pluginId) == null) { return true; + } //finally see if the delta has past its expiry date long deltaAge = System.currentTimeMillis() - getDeltaExpiration(pluginId); @@ -614,8 +638,9 @@ public Object readElement(IPath path, DataInput input) throws IOException { } private void rememberSnapshotRequestor() { - if (Policy.DEBUG_SAVE) + if (Policy.DEBUG_SAVE) { Policy.debug(new RuntimeException("Scheduling workspace snapshot")); //$NON-NLS-1$ + } if (snapshotRequestor == null) { String msg = "The workspace will exit with unsaved changes in this session."; //$NON-NLS-1$ snapshotRequestor = new ResourceStatus(ICoreConstants.CRASH_DETECTED, msg); @@ -649,8 +674,9 @@ protected void removeFiles(java.io.File root, String[] candidates, List break; } } - if (delete) + if (delete) { new java.io.File(root, candidate).delete(); + } } } @@ -679,8 +705,9 @@ protected void removeUnusedSafeTables() { } java.io.File target = location.toFile().getParentFile(); String[] candidates = target.list(); - if (candidates == null) + if (candidates == null) { return; + } removeFiles(target, candidates, valuables); } @@ -692,8 +719,9 @@ protected void removeUnusedTreeFiles() { java.io.File target = location.toFile().getParentFile(); FilenameFilter filter = (dir, name) -> name.endsWith(LocalMetaArea.F_TREE); String[] candidates = target.list(filter); - if (candidates != null) + if (candidates != null) { removeFiles(target, candidates, valuables); + } // projects IProject[] projects = workspace.getRoot().getProjects(IContainer.INCLUDE_HIDDEN); @@ -702,14 +730,16 @@ protected void removeUnusedTreeFiles() { valuables.add(location.lastSegment()); target = location.toFile().getParentFile(); candidates = target.list(filter); - if (candidates != null) + if (candidates != null) { removeFiles(target, candidates, valuables); + } } } protected void reportSnapshotRequestor() { - if (snapshotRequestor != null) + if (snapshotRequestor != null) { Policy.log(snapshotRequestor); + } } public void requestSnapshot() { @@ -726,8 +756,9 @@ protected void resetSnapshots(IResource resource) throws CoreException { // delete the snapshot file, if any java.io.File file = workspace.getMetaArea().getMarkersSnapshotLocationFor(resource).toFile(); - if (file.exists()) + if (file.exists()) { file.delete(); + } if (file.exists()) { message = Messages.resources_resetMarkers; throw new ResourceException(IResourceStatus.FAILED_DELETE_METADATA, resource.getFullPath(), message, null); @@ -735,8 +766,9 @@ protected void resetSnapshots(IResource resource) throws CoreException { // delete the snapshot file, if any file = workspace.getMetaArea().getSyncInfoSnapshotLocationFor(resource).toFile(); - if (file.exists()) + if (file.exists()) { file.delete(); + } if (file.exists()) { message = Messages.resources_resetSync; throw new ResourceException(IResourceStatus.FAILED_DELETE_METADATA, resource.getFullPath(), message, null); @@ -744,11 +776,13 @@ protected void resetSnapshots(IResource resource) throws CoreException { // if we have the workspace root then recursive over the projects. // only do open projects since closed ones are saved elsewhere - if (resource.getType() == IResource.PROJECT) + if (resource.getType() == IResource.PROJECT) { return; + } IProject[] projects = ((IWorkspaceRoot) resource).getProjects(IContainer.INCLUDE_HIDDEN); - for (IProject project : projects) + for (IProject project : projects) { resetSnapshots(project); + } } /** @@ -756,8 +790,9 @@ protected void resetSnapshots(IResource resource) throws CoreException { * which were open when it was last saved. */ protected void restore(IProgressMonitor monitor) throws CoreException { - if (Policy.DEBUG_RESTORE) + if (Policy.DEBUG_RESTORE) { Policy.debug("Restore workspace: starting..."); //$NON-NLS-1$ + } long start = System.currentTimeMillis(); monitor = Policy.monitorFor(monitor); try { @@ -789,18 +824,21 @@ protected void restore(IProgressMonitor monitor) throws CoreException { // restore meta info last because it might close a project if its description is not readable restoreMetaInfo(problems, Policy.subMonitorFor(monitor, 10)); IProject[] roots = workspace.getRoot().getProjects(IContainer.INCLUDE_HIDDEN); - for (IProject root : roots) + for (IProject root : roots) { ((Project) root).startup(); - if (!problems.isOK()) + } + if (!problems.isOK()) { Policy.log(problems); + } } finally { workspace.getElementTree().immutable(); } } finally { monitor.done(); } - if (Policy.DEBUG_RESTORE) + if (Policy.DEBUG_RESTORE) { Policy.debug("Restore workspace: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } } /** @@ -812,8 +850,9 @@ protected void restore(IProgressMonitor monitor) throws CoreException { */ protected boolean restore(Project project, IProgressMonitor monitor) throws CoreException { boolean status = true; - if (Policy.DEBUG_RESTORE) + if (Policy.DEBUG_RESTORE) { Policy.debug("Restore project " + project.getFullPath() + ": starting..."); //$NON-NLS-1$ //$NON-NLS-2$ + } long start = System.currentTimeMillis(); monitor = Policy.monitorFor(monitor); try { @@ -830,8 +869,9 @@ protected boolean restore(Project project, IProgressMonitor monitor) throws Core } finally { monitor.done(); } - if (Policy.DEBUG_RESTORE) + if (Policy.DEBUG_RESTORE) { Policy.debug("Restore project " + project.getFullPath() + ": " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } return status; } @@ -847,10 +887,12 @@ protected boolean restoreFromRefreshSnapshot(Project project, IProgressMonitor m boolean status = true; IPath snapshotPath = workspace.getMetaArea().getRefreshLocationFor(project); java.io.File snapshotFile = snapshotPath.toFile(); - if (!snapshotFile.exists()) + if (!snapshotFile.exists()) { return false; - if (Policy.DEBUG_RESTORE) + } + if (Policy.DEBUG_RESTORE) { Policy.debug("Restore project " + project.getFullPath() + ": starting..."); //$NON-NLS-1$ //$NON-NLS-2$ + } long start = System.currentTimeMillis(); monitor = Policy.monitorFor(monitor); try { @@ -865,8 +907,9 @@ protected boolean restoreFromRefreshSnapshot(Project project, IProgressMonitor m } finally { monitor.done(); } - if (Policy.DEBUG_RESTORE) + if (Policy.DEBUG_RESTORE) { Policy.debug("Restore project " + project.getFullPath() + ": " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } return status; } @@ -879,8 +922,9 @@ protected void restoreMarkers(IResource resource, boolean generateDeltas, IProgr long start = System.currentTimeMillis(); MarkerManager markerManager = workspace.getMarkerManager(); // when restoring a project, only load markers if it is open - if (resource.isAccessible()) + if (resource.isAccessible()) { markerManager.restore(resource, generateDeltas, monitor); + } // if we have the workspace root then restore markers for its projects if (resource.getType() == IResource.PROJECT) { @@ -890,9 +934,11 @@ protected void restoreMarkers(IResource resource, boolean generateDeltas, IProgr return; } IProject[] projects = ((IWorkspaceRoot) resource).getProjects(IContainer.INCLUDE_HIDDEN); - for (IProject project : projects) - if (project.isAccessible()) + for (IProject project : projects) { + if (project.isAccessible()) { markerManager.restore(project, generateDeltas, monitor); + } + } if (Policy.DEBUG_RESTORE_MARKERS) { Policy.debug("Restore Markers for workspace: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ } @@ -906,8 +952,9 @@ protected void restoreMasterTable() throws CoreException { if (!target.exists()) { location = workspace.getMetaArea().getBackupLocationFor(location); target = location.toFile(); - if (!target.exists()) + if (!target.exists()) { return; + } } try (SafeChunkyInputStream input = new SafeChunkyInputStream(target)) { masterTable.load(input); @@ -915,8 +962,9 @@ protected void restoreMasterTable() throws CoreException { String message = Messages.resources_exMasterTable; throw new ResourceException(IResourceStatus.INTERNAL_ERROR, null, message, e); } - if (Policy.DEBUG_RESTORE_MASTERTABLE) + if (Policy.DEBUG_RESTORE_MASTERTABLE) { Policy.debug("Restore master table for " + location + ": " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } } /** @@ -924,8 +972,9 @@ protected void restoreMasterTable() throws CoreException { * which were open when it was last saved. */ protected void restoreMetaInfo(MultiStatus problems, IProgressMonitor monitor) { - if (Policy.DEBUG_RESTORE_METAINFO) + if (Policy.DEBUG_RESTORE_METAINFO) { Policy.debug("Restore workspace metainfo: starting..."); //$NON-NLS-1$ + } long start = System.currentTimeMillis(); IProject[] roots = workspace.getRoot().getProjects(IContainer.INCLUDE_HIDDEN); for (IProject root : roots) { @@ -937,8 +986,9 @@ protected void restoreMetaInfo(MultiStatus problems, IProgressMonitor monitor) { problems.merge(new ResourceStatus(IResourceStatus.FAILED_READ_METADATA, root.getFullPath(), message, e)); } } - if (Policy.DEBUG_RESTORE_METAINFO) + if (Policy.DEBUG_RESTORE_METAINFO) { Policy.debug("Restore workspace metainfo: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } } /** @@ -950,12 +1000,13 @@ protected void restoreMetaInfo(Project project, IProgressMonitor monitor) throws ProjectDescription description = null; CoreException failure = null; try { - if (project.isOpen()) + if (project.isOpen()) { description = workspace.getFileSystemManager().read(project, true); - else + } else { //for closed projects, just try to read the legacy .prj file, //because the project location is stored there. description = workspace.getMetaArea().readOldDescription(project); + } } catch (CoreException e) { failure = e; } @@ -979,8 +1030,9 @@ protected void restoreMetaInfo(Project project, IProgressMonitor monitor) throws } throw failure; } - if (Policy.DEBUG_RESTORE_METAINFO) + if (Policy.DEBUG_RESTORE_METAINFO) { Policy.debug("Restore metainfo for " + project.getFullPath() + ": " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } } /** @@ -1038,8 +1090,9 @@ protected void restoreSnapshots(IProgressMonitor monitor) { } finally { monitor.done(); } - if (Policy.DEBUG_RESTORE_SNAPSHOTS) + if (Policy.DEBUG_RESTORE_SNAPSHOTS) { Policy.debug("Restore snapshots for workspace: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } } /** @@ -1055,8 +1108,9 @@ private boolean isSnapshotOlderThanTree(File snapshot) { if (!tree.exists()) { treeLocation = workspace.getMetaArea().getBackupLocationFor(treeLocation); tree = treeLocation.toFile(); - if (!tree.exists()) + if (!tree.exists()) { return false; + } } return snapshot.lastModified() < tree.lastModified(); } @@ -1070,8 +1124,9 @@ protected void restoreSyncInfo(IResource resource, IProgressMonitor monitor) thr long start = System.currentTimeMillis(); Synchronizer synchronizer = (Synchronizer) workspace.getSynchronizer(); // when restoring a project, only load sync info if it is open - if (resource.isAccessible()) + if (resource.isAccessible()) { synchronizer.restore(resource, monitor); + } // restore sync info for all projects if we were given the workspace root. if (resource.getType() == IResource.PROJECT) { @@ -1081,9 +1136,11 @@ protected void restoreSyncInfo(IResource resource, IProgressMonitor monitor) thr return; } IProject[] projects = ((IWorkspaceRoot) resource).getProjects(IContainer.INCLUDE_HIDDEN); - for (IProject project : projects) - if (project.isAccessible()) + for (IProject project : projects) { + if (project.isAccessible()) { synchronizer.restore(project, monitor); + } + } if (Policy.DEBUG_RESTORE_SYNCINFO) { Policy.debug("Restore SyncInfo for workspace: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ } @@ -1131,8 +1188,9 @@ protected boolean restoreTree(Project project, IProgressMonitor monitor) throws monitor.beginTask("", Policy.totalWork); //$NON-NLS-1$ IPath treeLocation = workspace.getMetaArea().getTreeLocationFor(project, false); IPath tempLocation = workspace.getMetaArea().getBackupLocationFor(treeLocation); - if (!treeLocation.toFile().exists() && !tempLocation.toFile().exists()) + if (!treeLocation.toFile().exists() && !tempLocation.toFile().exists()) { return false; + } try ( DataInputStream input = new DataInputStream(new SafeFileInputStream(treeLocation.toOSString(), tempLocation.toOSString())); ) { @@ -1281,15 +1339,17 @@ public IStatus save(int kind, boolean keepConsistencyWhenCanceled, Project proje // reset the snapshot file resetSnapshots(project); IStatus result = saveMetaInfo(project, null); - if (!result.isOK()) + if (!result.isOK()) { warnings.merge(result); + } monitor.worked(1); break; } // save contexts commit(contexts); - if (kind == ISaveContext.FULL_SAVE) + if (kind == ISaveContext.FULL_SAVE) { removeClearDeltaMarks(); + } //this must be done after committing save contexts to update participant save numbers saveMasterTable(kind); broadcastLifecycle(DONE_SAVING, contexts, warnings, Policy.subMonitorFor(monitor, 1)); @@ -1326,8 +1386,9 @@ protected void saveMasterTable(int kind, IPath location) throws CoreException { long start = System.currentTimeMillis(); java.io.File target = location.toFile(); try { - if (kind == ISaveContext.FULL_SAVE || kind == ISaveContext.SNAPSHOT) + if (kind == ISaveContext.FULL_SAVE || kind == ISaveContext.SNAPSHOT) { validateMasterTableBeforeSave(target); + } try ( SafeChunkyOutputStream output = new SafeChunkyOutputStream(target); ) { @@ -1337,8 +1398,9 @@ protected void saveMasterTable(int kind, IPath location) throws CoreException { } catch (IOException e) { throw new ResourceException(IResourceStatus.INTERNAL_ERROR, null, NLS.bind(Messages.resources_exSaveMaster, location.toOSString()), e); } - if (Policy.DEBUG_SAVE_MASTERTABLE) + if (Policy.DEBUG_SAVE_MASTERTABLE) { Policy.debug("Save master table for " + location + ": " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } } /** @@ -1346,21 +1408,25 @@ protected void saveMasterTable(int kind, IPath location) throws CoreException { * all projects to the local disk. */ protected void saveMetaInfo(MultiStatus problems, IProgressMonitor monitor) throws CoreException { - if (Policy.DEBUG_SAVE_METAINFO) + if (Policy.DEBUG_SAVE_METAINFO) { Policy.debug("Save workspace metainfo: starting..."); //$NON-NLS-1$ + } long start = System.currentTimeMillis(); // save preferences (workspace description, path variables, etc) ResourcesPlugin.getPlugin().savePluginPreferences(); // save projects' meta info IProject[] roots = workspace.getRoot().getProjects(IContainer.INCLUDE_HIDDEN); - for (IProject root : roots) + for (IProject root : roots) { if (root.isAccessible()) { IStatus result = saveMetaInfo((Project) root, null); - if (!result.isOK()) + if (!result.isOK()) { problems.merge(result); + } } - if (Policy.DEBUG_SAVE_METAINFO) + } + if (Policy.DEBUG_SAVE_METAINFO) { Policy.debug("Save workspace metainfo: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } } /** @@ -1378,8 +1444,9 @@ protected IStatus saveMetaInfo(Project project, IProgressMonitor monitor) throws String msg = NLS.bind(Messages.resources_missingProjectMetaRepaired, project.getName()); return new ResourceStatus(IResourceStatus.MISSING_DESCRIPTION_REPAIRED, project.getFullPath(), msg); } - if (Policy.DEBUG_SAVE_METAINFO) + if (Policy.DEBUG_SAVE_METAINFO) { Policy.debug("Save metainfo for " + project.getFullPath() + ": " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } return Status.OK_STATUS; } @@ -1430,8 +1497,9 @@ protected void saveTree(Map contexts, IProgressMonitor moni String msg = NLS.bind(Messages.resources_writeWorkspaceMeta, treeLocation); throw new ResourceException(IResourceStatus.FAILED_WRITE_METADATA, IPath.ROOT, msg, e); } - if (Policy.DEBUG_SAVE_TREE) + if (Policy.DEBUG_SAVE_TREE) { Policy.debug("Save Workspace Tree: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } } /** @@ -1456,9 +1524,10 @@ public void shutdown(final IProgressMonitor monitor) { // we force it in the same thread because it would not // help if the job runs after we close the workspace int state = snapshotJob.getState(); - if (state == Job.WAITING || state == Job.SLEEPING) + if (state == Job.WAITING || state == Job.SLEEPING) { // we cannot pass null to Job#run snapshotJob.run(SubMonitor.convert(monitor)); + } // cancel the snapshot job snapshotJob.cancel(); } @@ -1470,14 +1539,16 @@ public void shutdown(final IProgressMonitor monitor) { */ public void snapshotIfNeeded(boolean hasTreeChanges) { // never schedule a snapshot while save is occurring. - if (isSaving) + if (isSaving) { return; + } if (snapshotRequested || operationCount >= workspace.internalGetDescription().getOperationsPerSnapshot()) { rememberSnapshotRequestor(); - if (snapshotJob.getState() == Job.NONE) + if (snapshotJob.getState() == Job.NONE) { snapshotJob.schedule(); - else + } else { snapshotJob.wakeUp(); + } } else { if (hasTreeChanges) { operationCount++; @@ -1507,8 +1578,9 @@ protected void snapTree(ElementTree tree, IProgressMonitor monitor) throws CoreE // the tree must be immutable tree.immutable(); // don't need to snapshot if there are no changes - if (tree == lastSnap) + if (tree == lastSnap) { return; + } operationCount = 0; IPath snapPath = workspace.getMetaArea().getSnapshotLocationFor(workspace.getRoot()); ElementTreeWriter writer = new ElementTreeWriter(this); @@ -1528,8 +1600,9 @@ protected void snapTree(ElementTree tree, IProgressMonitor monitor) throws CoreE throw new ResourceException(IResourceStatus.FAILED_WRITE_METADATA, IPath.ROOT, message, e); } lastSnap = tree; - if (Policy.DEBUG_SAVE_TREE) + if (Policy.DEBUG_SAVE_TREE) { Policy.debug("Snapshot Workspace Tree: " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } } finally { subMonitor.done(); } @@ -1615,8 +1688,9 @@ static String parentChain(ElementTree e) { public void startup(IProgressMonitor monitor) throws CoreException { restore(monitor); java.io.File table = workspace.getMetaArea().getSafeTableLocationFor(ResourcesPlugin.PI_RESOURCES).toFile(); - if (!table.exists()) + if (!table.exists()) { table.getParentFile().mkdirs(); + } } /** @@ -1629,8 +1703,9 @@ public void startup(IProgressMonitor monitor) throws CoreException { */ protected void updateDeltaExpiration(String pluginId) { String key = DELTA_EXPIRATION_PREFIX + pluginId; - if (!masterTable.containsKey(key)) + if (!masterTable.containsKey(key)) { masterTable.setProperty(key, Long.toString(System.currentTimeMillis())); + } } private void validateMasterTableBeforeSave(java.io.File target) throws IOException { @@ -1697,8 +1772,9 @@ public void visitAndSave(final IResource root) throws CoreException { // Ensure we have either a project or the workspace root Assert.isLegal(root.getType() == IResource.ROOT || root.getType() == IResource.PROJECT); // only write out info for accessible resources - if (!root.isAccessible()) + if (!root.isAccessible()) { return; + } // Setup variables final Synchronizer synchronizer = (Synchronizer) workspace.getSynchronizer(); @@ -1759,10 +1835,12 @@ public void visitAndSave(final IResource root) throws CoreException { } catch (WrappedRuntimeException e) { throw (IOException) e.getTargetException(); } - if (Policy.DEBUG_SAVE_MARKERS) + if (Policy.DEBUG_SAVE_MARKERS) { Policy.debug("Save Markers for " + root.getFullPath() + ": " + saveTimes[0] + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (Policy.DEBUG_SAVE_SYNCINFO) + } + if (Policy.DEBUG_SAVE_SYNCINFO) { Policy.debug("Save SyncInfo for " + root.getFullPath() + ": " + saveTimes[1] + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } removeGarbage(markersOutput, markersLocation, markersTempLocation); // if we have the workspace root the output stream will be null and we // don't have to perform cleanup code @@ -1777,8 +1855,9 @@ public void visitAndSave(final IResource root) throws CoreException { } // recurse over the projects in the workspace if we were given the workspace root - if (root.getType() == IResource.PROJECT) + if (root.getType() == IResource.PROJECT) { return; + } forEachProjectInParallel(null, this::visitAndSave); } @@ -1842,8 +1921,9 @@ public void visitAndSnap(final IResource root) throws CoreException { // Ensure we have either a project or the workspace root Assert.isLegal(root.getType() == IResource.ROOT || root.getType() == IResource.PROJECT); // only write out info for accessible resources - if (!root.isAccessible()) + if (!root.isAccessible()) { return; + } // Setup variables final Synchronizer synchronizer = (Synchronizer) workspace.getSynchronizer(); @@ -1903,12 +1983,15 @@ public void visitAndSnap(final IResource root) throws CoreException { } catch (WrappedRuntimeException e) { throw (IOException) e.getTargetException(); } - if (Policy.DEBUG_SAVE_MARKERS) + if (Policy.DEBUG_SAVE_MARKERS) { Policy.debug("Snap Markers for " + root.getFullPath() + ": " + snapTimes[0] + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (Policy.DEBUG_SAVE_SYNCINFO) + } + if (Policy.DEBUG_SAVE_SYNCINFO) { Policy.debug("Snap SyncInfo for " + root.getFullPath() + ": " + snapTimes[1] + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - if (markerFileSize != markersOutput.size()) + } + if (markerFileSize != markersOutput.size()) { safeMarkerStream.succeed(); + } if (safeSyncInfoStream != null && syncInfoFileSize != syncInfoOutput.size()) { safeSyncInfoStream.succeed(); syncInfoOutput.close(); @@ -1921,11 +2004,13 @@ public void visitAndSnap(final IResource root) throws CoreException { } // recurse over the projects in the workspace if we were given the workspace root - if (root.getType() == IResource.PROJECT) + if (root.getType() == IResource.PROJECT) { return; + } IProject[] projects = ((IWorkspaceRoot) root).getProjects(IContainer.INCLUDE_HIDDEN); - for (IProject project : projects) + for (IProject project : projects) { visitAndSnap(project); + } } /** @@ -1950,8 +2035,9 @@ private void writeBuilderPersistentInfo(DataOutputStream output, List trees, List statesToSave, DataOutputStream List additionalTrees = new ArrayList<>(projects.length * 2); List additionalBuilderInfos = new ArrayList<>(projects.length * 2); List additionalConfigNames = new ArrayList<>(projects.length); - for (IProject project : projects) + for (IProject project : projects) { getTreesToSave(project, trees, builderInfos, configNames, additionalTrees, additionalBuilderInfos, additionalConfigNames); + } // Save the version 2 builders info writeBuilderPersistentInfo(output, builderInfos); @@ -2086,14 +2174,17 @@ protected void writeTree(Map statesToSave, DataOutputStream writeBuilderPersistentInfo(output, additionalBuilderInfos); // Save the configuration names for the builders in the order they were saved - for (String string : configNames) + for (String string : configNames) { output.writeUTF(string); - for (String string : additionalConfigNames) + } + for (String string : additionalConfigNames) { output.writeUTF(string); + } } finally { subMonitor.done(); - if (!wasImmutable) + if (!wasImmutable) { workspace.newWorkingTree(); + } } } @@ -2159,14 +2250,17 @@ protected void writeTree(Project project, DataOutputStream output, IProgressMoni writeBuilderPersistentInfo(output, additionalBuilderInfos); // Save configuration names for the builders in the order they were saved - for (String string : configNames) + for (String string : configNames) { output.writeUTF(string); - for (String string : additionalConfigNames) + } + for (String string : additionalConfigNames) { output.writeUTF(string); + } } finally { subMonitor.done(); - if (!wasImmutable) + if (!wasImmutable) { workspace.newWorkingTree(); + } } } @@ -2186,8 +2280,9 @@ protected void writeTree(Project project, int depth) throws CoreException { String msg = NLS.bind(Messages.resources_writeMeta, project.getFullPath()); throw new ResourceException(IResourceStatus.FAILED_WRITE_METADATA, treeLocation, msg, e); } - if (Policy.DEBUG_SAVE_TREE) + if (Policy.DEBUG_SAVE_TREE) { Policy.debug("Save tree for " + project.getFullPath() + ": " + (System.currentTimeMillis() - start) + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + } } protected void writeWorkspaceFields(DataOutputStream output, IProgressMonitor monitor) throws IOException { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SavedState.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SavedState.java index 5e9df612743..61e387aaf24 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SavedState.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SavedState.java @@ -59,8 +59,9 @@ protected SafeFileTable getFileTable() { } protected SafeFileTable restoreFileTable() throws CoreException { - if (fileTable == null) + if (fileTable == null) { fileTable = new SafeFileTable(pluginId, workspace); + } return fileTable; } @@ -80,8 +81,9 @@ public void processResourceChangeEvents(IResourceChangeListener listener) { final ISchedulingRule rule = workspace.getRoot(); try { workspace.prepareOperation(rule, null); - if (oldTree == null || newTree == null) + if (oldTree == null || newTree == null) { return; + } workspace.beginOperation(true); ResourceDelta delta = ResourceDeltaFactory.computeDelta(workspace, oldTree, newTree, IPath.ROOT, -1); forgetTrees(); // free trees to prevent memory leak diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoReader_2.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoReader_2.java index 3222affe544..7039850b737 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoReader_2.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoReader_2.java @@ -99,8 +99,9 @@ private void readSyncInfo(IPath path, DataInputStream input, List } // set the table on the resource info ResourceInfo info = workspace.getResourceInfo(path, true, false); - if (info == null) + if (info == null) { return; + } info.setSyncInfo(table); info.clear(ICoreConstants.M_SYNCINFO_SNAP_DIRTY); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoReader_3.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoReader_3.java index ba71b2b1a78..6cfa154d5f9 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoReader_3.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoReader_3.java @@ -99,8 +99,9 @@ private void readSyncInfo(IPath path, DataInputStream input, List } // set the table on the resource info ResourceInfo info = workspace.getResourceInfo(path, true, false); - if (info == null) + if (info == null) { return; + } info.setSyncInfo(table); info.clear(ICoreConstants.M_SYNCINFO_SNAP_DIRTY); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoSnapReader_3.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoSnapReader_3.java index e3a9c84b3d9..453bb9b9793 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoSnapReader_3.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoSnapReader_3.java @@ -63,8 +63,9 @@ public void readSyncInfo(DataInputStream input) throws IOException { ObjectMap map = internalReadSyncInfo(input); // set the table on the resource info ResourceInfo info = workspace.getResourceInfo(path, true, false); - if (info == null) + if (info == null) { return; + } info.setSyncInfo(map); info.clear(ICoreConstants.M_SYNCINFO_SNAP_DIRTY); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoWriter.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoWriter.java index a1cdc13f5a5..90dfee3439d 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoWriter.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/SyncInfoWriter.java @@ -63,12 +63,14 @@ public void savePartners(DataOutputStream output) throws IOException { */ public void saveSyncInfo(ResourceInfo info, IPathRequestor requestor, DataOutputStream output, List writtenPartners) throws IOException { Map table = info.getSyncInfo(false); - if (table == null) + if (table == null) { return; + } // if this is the first sync info that we have written, then // write the version id for the file. - if (output.size() == 0) + if (output.size() == 0) { output.writeInt(SYNCINFO_SAVE_VERSION); + } output.writeUTF(requestor.requestPath().toString()); output.writeInt(table.size()); for (Map.Entry entry : table.entrySet()) { @@ -105,11 +107,13 @@ public void saveSyncInfo(ResourceInfo info, IPathRequestor requestor, DataOutput * } */ public void snapSyncInfo(ResourceInfo info, IPathRequestor requestor, DataOutputStream output) throws IOException { - if (!info.isSet(ICoreConstants.M_SYNCINFO_SNAP_DIRTY)) + if (!info.isSet(ICoreConstants.M_SYNCINFO_SNAP_DIRTY)) { return; + } Map table = info.getSyncInfo(false); - if (table == null) + if (table == null) { return; + } // write the version id for the snapshot. output.writeInt(SYNCINFO_SNAP_VERSION); output.writeUTF(requestor.requestPath().toString()); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Synchronizer.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Synchronizer.java index 82ba1d49494..e02fa151602 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Synchronizer.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Synchronizer.java @@ -53,20 +53,24 @@ public void accept(QualifiedName partner, IResource resource, IResourceVisitor v // if we don't have sync info for the given identifier, then skip it if (getSyncInfo(partner, resource) != null) { // visit the resource and if the visitor says to stop the recursion then return - if (!visitor.visit(resource)) + if (!visitor.visit(resource)) { return; + } } // adjust depth if necessary - if (depth == IResource.DEPTH_ZERO || resource.getType() == IResource.FILE) + if (depth == IResource.DEPTH_ZERO || resource.getType() == IResource.FILE) { return; - if (depth == IResource.DEPTH_ONE) + } + if (depth == IResource.DEPTH_ONE) { depth = IResource.DEPTH_ZERO; + } // otherwise recurse over the children IResource[] children = ((IContainer) resource).members(); - for (IResource element : children) + for (IResource element : children) { accept(partner, element, visitor, depth); + } } /** @@ -89,8 +93,9 @@ public void flushSyncInfo(final QualifiedName partner, final IResource root, fin ICoreRunnable body = monitor -> { IResourceVisitor visitor = resource -> { // only need to flush sync info if there is sync info - if (getSyncInfo(partner, resource) != null) + if (getSyncInfo(partner, resource) != null) { setSyncInfo(partner, resource, null); + } return true; }; root.accept(visitor, depth, true); @@ -153,8 +158,9 @@ public void restore(IResource resource, IProgressMonitor monitor) throws CoreExc protected void restoreFromSave(IResource resource) throws CoreException { IPath sourceLocation = workspace.getMetaArea().getSyncInfoLocationFor(resource); IPath tempLocation = workspace.getMetaArea().getBackupLocationFor(sourceLocation); - if (!sourceLocation.toFile().exists() && !tempLocation.toFile().exists()) + if (!sourceLocation.toFile().exists() && !tempLocation.toFile().exists()) { return; + } try (DataInputStream input = new DataInputStream( new SafeFileInputStream(sourceLocation.toOSString(), tempLocation.toOSString()))) { SyncInfoReader reader = new SyncInfoReader(workspace, this); @@ -168,12 +174,14 @@ protected void restoreFromSave(IResource resource) throws CoreException { protected void restoreFromSnap(IResource resource) { IPath sourceLocation = workspace.getMetaArea().getSyncInfoSnapshotLocationFor(resource); - if (!sourceLocation.toFile().exists()) + if (!sourceLocation.toFile().exists()) { return; + } try (DataInputStream input = new DataInputStream(new SafeChunkyInputStream(sourceLocation.toFile()))) { SyncInfoSnapReader reader = new SyncInfoSnapReader(workspace, this); - while (true) + while (true) { reader.readSyncInfo(input); + } } catch (EOFException eof) { // ignore end of file -- proceed with what we successfully read } catch (Exception e) { @@ -229,16 +237,18 @@ public void setSyncInfo(QualifiedName partner, IResource resource, byte[] info) throw new ResourceException(new ResourceStatus(IResourceStatus.PARTNER_NOT_REGISTERED, message)); } // we do not store sync info on the workspace root - if (resource.getType() == IResource.ROOT) + if (resource.getType() == IResource.ROOT) { return; + } // if the resource doesn't yet exist then create a phantom so we can set the // sync info on it Resource target = (Resource) resource; ResourceInfo resourceInfo = workspace.getResourceInfo(target.getFullPath(), true, false); int flags = target.getFlags(resourceInfo); if (!target.exists(flags, false)) { - if (info == null) + if (info == null) { return; + } // ensure it is possible to create this resource target.checkValidPath(target.getFullPath(), target.getType(), false); Container parent = (Container) target.getParent(); @@ -254,8 +264,9 @@ public void setSyncInfo(QualifiedName partner, IResource resource, byte[] info) MultiStatus status = new MultiStatus(ResourcesPlugin.PI_RESOURCES, IResourceStatus.INTERNAL_ERROR, Messages.resources_deleteProblem, null); ((Resource) resource).deleteResource(false, status); - if (!status.isOK()) + if (!status.isOK()) { throw new ResourceException(status); + } } } finally { workspace.endOperation(resource, false); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/VariableDescription.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/VariableDescription.java index f5911eb6e61..ecc24009efb 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/VariableDescription.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/VariableDescription.java @@ -38,8 +38,9 @@ public boolean equals(Object o) { if (o == null) { return false; } - if (o.getClass() != this.getClass()) + if (o.getClass() != this.getClass()) { return false; + } VariableDescription other = (VariableDescription) o; return name.equals(other.name) && value == other.value; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java index 2ff8a1280fd..b687851f062 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkManager.java @@ -105,8 +105,9 @@ public boolean isConflicting(ISchedulingRule rule) { */ public int beginUnprotected() { int depth = lock.getDepth(); - for (int i = 0; i < depth; i++) + for (int i = 0; i < depth; i++) { lock.release(); + } return depth; } @@ -149,8 +150,9 @@ boolean checkInFailed(ISchedulingRule rule) { //clear the failure flag for this thread checkInFailed.remove(); //must still end the rule even in the case of failure - if (!workspace.isTreeLocked()) + if (!workspace.isTreeLocked()) { jobManager.endRule(rule); + } return true; } return false; @@ -163,8 +165,9 @@ synchronized void checkOut(ISchedulingRule rule) { decrementPreparedOperations(); rebalanceNestedOperations(); //reset state if this is the end of a top level operation - if (preparedOperations == 0) + if (preparedOperations == 0) { hasBuildChanges = false; + } //don't let cancelation of this operation affect other operations operationCanceled = false; try { @@ -190,8 +193,9 @@ private void decrementPreparedOperations() { * @see #beginUnprotected() */ public void endUnprotected(int depth) { - for (int i = 0; i < depth; i++) + for (int i = 0; i < depth; i++) { lock.acquire(); + } } /** @@ -305,8 +309,9 @@ synchronized void setBuild(boolean hasChanges) { */ boolean shouldBuild() { if (hasBuildChanges) { - if (operationCanceled) + if (operationCanceled) { return Policy.buildOnCancel; + } return true; } return false; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java index f75350b41a3..a731959256a 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/Workspace.java @@ -333,8 +333,9 @@ public BuildConfigurationComparator() { @Override public int compare(IBuildConfiguration px, IBuildConfiguration py) { int cmp = py.getProject().getName().compareTo(px.getProject().getName()); - if (cmp == 0) + if (cmp == 0) { cmp = py.getName().compareTo(px.getName()); + } return cmp; } } @@ -364,11 +365,14 @@ public static WorkspaceDescription defaultWorkspaceDescription() { * other copy in the given array. */ private static boolean isDuplicate(Object[] array, int position) { - if (array == null || position >= array.length) + if (array == null || position >= array.length) { return false; - for (int j = position - 1; j >= 0; j--) - if (array[j].equals(array[position])) + } + for (int j = position - 1; j >= 0; j--) { + if (array[j].equals(array[position])) { return true; + } + } return false; } @@ -433,17 +437,20 @@ public ISavedState addSaveParticipant(String pluginId, ISaveParticipant particip public void beginOperation(boolean createNewTree) throws CoreException { WorkManager workManager = getWorkManager(); workManager.incrementNestedOperations(); - if (!workManager.isBalanced()) + if (!workManager.isBalanced()) { Assert.isTrue(false, "Operation was not prepared."); //$NON-NLS-1$ + } if (workManager.getPreparedOperationDepth() > 1) { - if (createNewTree && tree.isImmutable()) + if (createNewTree && tree.isImmutable()) { newWorkingTree(); + } return; } // stash the current tree as the basis for this operation. operationTree = tree; - if (createNewTree && tree.isImmutable()) + if (createNewTree && tree.isImmutable()) { newWorkingTree(); + } } public void broadcastBuildEvent(Object source, int type, int buildTrigger) { @@ -456,8 +463,9 @@ public void broadcastBuildEvent(Object source, int type, int buildTrigger) { * internal listeners. */ protected void broadcastEvent(LifecycleEvent event) throws CoreException { - for (ILifecycleListener listener : lifecycleListeners) + for (ILifecycleListener listener : lifecycleListeners) { listener.handleEvent(event); + } } public void broadcastPostChange() { @@ -474,8 +482,9 @@ private void recursivelyAddBuildConfigs(Collection/**/ configArr = new ArrayList<>(); IProject[] prjs = getRoot().getProjects(); - for (IProject prj : prjs) - if (prj.isAccessible()) + for (IProject prj : prjs) { + if (prj.isAccessible()) { configArr.addAll(Arrays.asList(prj.getBuildConfigs())); + } + } allConfigs = configArr.toArray(new IBuildConfiguration[configArr.size()]); } } else { @@ -565,12 +577,14 @@ private void buildInternal(IBuildConfiguration[] requestedConfigs, int trigger, for (IBuildConfiguration config : allConfigs) { // Check project + build configuration are accessible. if (!config.getProject().isAccessible() - || !config.getProject().hasBuildConfig(config.getName())) + || !config.getProject().hasBuildConfig(config.getName())) { continue; + } refsList.add(config); // Find transitive closure of referenced project buildConfigs - if (buildReferences) + if (buildReferences) { recursivelyAddBuildConfigs(refsList, config); + } } // Order the referenced project buildConfigs @@ -614,13 +628,15 @@ private void buildInternal(IBuildConfiguration[] requestedConfigs, int trigger, // must fire POST_BUILD if PRE_BUILD has occurred broadcastBuildEvent(this, IResourceChangeEvent.POST_BUILD, trigger); } - if (!result.isOK()) + if (!result.isOK()) { throw new ResourceException(result); + } } finally { subMonitor.done(); // building may close the tree, but we are still inside an operation so open it - if (tree.isImmutable()) + if (tree.isImmutable()) { newWorkingTree(); + } // Rule will be the build-rule from the POST_BUILD refresh endOperation(currentRule, false); } @@ -692,8 +708,9 @@ public void checkpoint(boolean build) { */ public void close(IProgressMonitor monitor) throws CoreException { //nothing to do if the workspace failed to open - if (!isOpen()) + if (!isOpen()) { return; + } String msg = Messages.resources_closing_0; SubMonitor subMonitor = SubMonitor.convert(monitor, msg, 20); subMonitor.subTask(msg); @@ -769,18 +786,21 @@ private VertexOrder computeFullProjectOrder() { for (IProject p : allProjects) { Project project = (Project) p; // ignore projects that are not accessible - if (!project.isAccessible()) + if (!project.isAccessible()) { continue; + } ProjectDescription desc = project.internalGetDescription(); - if (desc == null) + if (desc == null) { continue; + } //obtain both static and dynamic project references IProject[] refs = desc.getAllReferences(project, false); allAccessibleProjects.add(project); for (IProject ref : refs) { // ignore self references and references to projects that are not accessible - if (ref.isAccessible() && !ref.equals(project)) + if (ref.isAccessible() && !ref.equals(project)) { edges.add(new IProject[] {project, ref}); + } } } return ComputeProjectOrder.computeVertexOrder(allAccessibleProjects, edges, IProject.class); @@ -835,8 +855,9 @@ private Digraph computeActiveBuildConfigGraph() { for (IProject allProject : allProjects) { Project project = (Project) allProject; // Ignore projects that are not accessible - if (!project.isAccessible()) + if (!project.isAccessible()) { continue; + } // If the active build configuration hasn't already been explored // perform a depth first search rooted at it @@ -854,15 +875,17 @@ private Digraph computeActiveBuildConfigGraph() { IBuildConfiguration[] refs = subProject.internalGetReferencedBuildConfigs(buildConfiguration.getName(), false); for (IBuildConfiguration ref : refs) { // Ignore self references and references to projects that are not accessible - if (ref.equals(buildConfiguration)) + if (ref.equals(buildConfiguration)) { continue; + } // Add the referenced accessible configuration edges.add(new IBuildConfiguration[] {buildConfiguration, ref}); // If we have already explored the referenced configuration, don't explore it again - if (allAccessibleBuildConfigs.contains(ref)) + if (allAccessibleBuildConfigs.contains(ref)) { continue; + } allAccessibleBuildConfigs.add(ref); @@ -916,8 +939,9 @@ private Digraph computeFullBuildConfigGraph() { for (IProject p : allProjects) { Project project = (Project) p; // Ignore projects that are not accessible - if (!project.isAccessible()) + if (!project.isAccessible()) { continue; + } IBuildConfiguration[] configs = project.internalGetBuildConfigs(false); for (IBuildConfiguration config : configs) { @@ -925,8 +949,9 @@ private Digraph computeFullBuildConfigGraph() { IBuildConfiguration[] refs = project.internalGetReferencedBuildConfigs(config.getName(), false); for (IBuildConfiguration ref : refs) { // Ignore self references - if (ref.equals(config)) + if (ref.equals(config)) { continue; + } // Add the reference to the set of reachable configs + add an edge allAccessibleBuildConfigurations.add(ref); @@ -1058,7 +1083,8 @@ public ProjectOrder computeProjectOrder(IProject[] projects) { */ public ProjectBuildConfigOrder computeProjectBuildConfigOrder(IBuildConfiguration[] buildConfigs) { // Compute the full project order for all accessible projects - VertexOrder fullBuildConfigOrder = computeFullBuildConfigOrder(); + Digraph graph = computeFullBuildConfigGraph(); + VertexOrder fullBuildConfigOrder = ComputeProjectOrder.computeVertexOrder(graph, IBuildConfiguration.class); // Create a filter to remove all project buildConfigs that are not in the list asked for final Set projectConfigSet = new HashSet<>(buildConfigs.length); @@ -1110,8 +1136,9 @@ public IStatus copy(IResource[] resources, IPath destination, int updateFlags, I continue; } // test siblings - if (parentPath == null) + if (parentPath == null) { parentPath = resource.getFullPath().removeLastSegments(1); + } if (parentPath.equals(resource.getFullPath().removeLastSegments(1))) { // test copy requirements try { @@ -1142,8 +1169,9 @@ public IStatus copy(IResource[] resources, IPath destination, int updateFlags, I subMonitor.done(); endOperation(getRoot(), true); } - if (status.matches(IStatus.ERROR)) + if (status.matches(IStatus.ERROR)) { throw new ResourceException(status); + } return status.isOK() ? Status.OK_STATUS : (IStatus) status; } @@ -1159,15 +1187,17 @@ private void copyTree(IResource source, IPath destination, int depth, int update IResource destinationResource = getRoot().findMember(destination, true); int destinationType; if (destinationResource == null) { - if (source.getType() == IResource.FILE) + if (source.getType() == IResource.FILE) { destinationType = IResource.FILE; - else if (destination.segmentCount() == 1) + } else if (destination.segmentCount() == 1) { destinationType = IResource.PROJECT; - else + } else { destinationType = IResource.FOLDER; + } destinationResource = newResource(destination, destinationType); - } else + } else { destinationType = destinationResource.getType(); + } // create the resource at the destination ResourceInfo sourceInfo = ((Resource) source).getResourceInfo(true, false); @@ -1202,8 +1232,9 @@ else if (destination.segmentCount() == 1) linkDescription = null; } if (moveResources && !movingProject) { - if (((Project) source.getProject()).internalGetDescription().setLinkLocation(source.getProjectRelativePath(), null)) + if (((Project) source.getProject()).internalGetDescription().setLinkLocation(source.getProjectRelativePath(), null)) { ((Project) source.getProject()).writeDescription(updateFlags); + } } Project project = (Project) destinationResource.getProject(); project.internalGetDescription().setLinkLocation(destinationResource.getProjectRelativePath(), linkDescription); @@ -1219,8 +1250,9 @@ else if (destination.segmentCount() == 1) LinkedList originalDescriptions = sourceProject.internalGetDescription().getFilter(source.getProjectRelativePath()); LinkedList filterDescriptions = FilterDescription.copy(originalDescriptions, destinationResource); if (moveResources) { - if (((Project) source.getProject()).internalGetDescription().setFilters(source.getProjectRelativePath(), null)) + if (((Project) source.getProject()).internalGetDescription().setFilters(source.getProjectRelativePath(), null)) { ((Project) source.getProject()).writeDescription(updateFlags); + } } Project project = (Project) destinationResource.getProject(); project.internalGetDescription().setFilters(destinationResource.getProjectRelativePath(), filterDescriptions); @@ -1229,16 +1261,19 @@ else if (destination.segmentCount() == 1) // do the recursion. if we have a file then it has no members so return. otherwise // recursively call this method on the container's members if the depth tells us to - if (depth == IResource.DEPTH_ZERO || source.getType() == IResource.FILE) + if (depth == IResource.DEPTH_ZERO || source.getType() == IResource.FILE) { return; - if (depth == IResource.DEPTH_ONE) + } + if (depth == IResource.DEPTH_ONE) { depth = IResource.DEPTH_ZERO; + } //copy .project file first if project is being copied, otherwise links won't be able to update description boolean projectCopy = source.getType() == IResource.PROJECT && destinationType == IResource.PROJECT; if (projectCopy) { IResource dotProject = ((Project) source).findMember(IProjectDescription.DESCRIPTION_FILE_NAME); - if (dotProject != null) + if (dotProject != null) { copyTree(dotProject, destination.append(dotProject.getName()), depth, updateFlags, keepSyncInfo, moveResources, movingProject); + } } IResource[] children = ((IContainer) source).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS | IContainer.INCLUDE_HIDDEN); for (IResource element : children) { @@ -1268,8 +1303,9 @@ public URI transferVariableDefinition(IResource source, IResource dest, URI sour } URI toURI(IPath path) { - if (path.isAbsolute()) + if (path.isAbsolute()) { return org.eclipse.core.filesystem.URIUtil.toURI(path); + } try { return new URI(null, null, path.toPortableString(), null); } catch (URISyntaxException e) { @@ -1282,9 +1318,10 @@ String copyVariable(IResource source, IResource dest, String variable) throws Co IPathVariableManager srcPathVariableManager = source.getPathVariableManager(); IPath srcValue = URIUtil.toPath(srcPathVariableManager.getURIValue(variable)); - if (srcValue == null) // if the variable doesn't exist, return another - // variable that doesn't exist either + if (srcValue == null) { // if the variable doesn't exist, return another + // variable that doesn't exist either return PathVariableUtil.getUniqueVariableName(variable, dest); + } IPath resolvedSrcValue = URIUtil.toPath(srcPathVariableManager.resolveURI(URIUtil.toURI(srcValue))); boolean variableExisted = false; @@ -1292,14 +1329,16 @@ String copyVariable(IResource source, IResource dest, String variable) throws Co if (destPathVariableManager.isDefined(variable)) { variableExisted = true; IPath destValue = URIUtil.toPath(destPathVariableManager.getURIValue(variable)); - if (destValue != null && URIUtil.toPath(destPathVariableManager.resolveURI(URIUtil.toURI(destValue))).equals(resolvedSrcValue)) + if (destValue != null && URIUtil.toPath(destPathVariableManager.resolveURI(URIUtil.toURI(destValue))).equals(resolvedSrcValue)) { return variable; + } } // look if one variable in the destination project matches String[] variables = destPathVariableManager.getPathVariableNames(); for (String other : variables) { - if (!PathVariableUtil.isPreferred(other)) + if (!PathVariableUtil.isPreferred(other)) { continue; + } IPath resolveDestVariable = URIUtil.toPath(destPathVariableManager.resolveURI(destPathVariableManager.getURIValue(other))); if (resolveDestVariable != null && resolveDestVariable.equals(resolvedSrcValue)) { return other; @@ -1319,8 +1358,9 @@ String copyVariable(IResource source, IResource dest, String variable) throws Co // If the variable value is of type ${PARENT-COUNT-VAR}, // we can avoid generating an intermediate variable and convert it directly. if (referencedVariables.length == 1) { - if (PathVariableUtil.isParentVariable(referencedVariables[0])) + if (PathVariableUtil.isParentVariable(referencedVariables[0])) { shouldConvertToRelative = true; + } } if (!shouldConvertToRelative) { @@ -1338,16 +1378,18 @@ String copyVariable(IResource source, IResource dest, String variable) throws Co int end = segment.length(); result.append(segment.substring(start, end)); } - } else + } else { result.append(segment); + } } srcValue = IPath.fromPortableString(result.toString()); } } if (shouldConvertToRelative) { IPath relativeSrcValue = PathVariableUtil.convertToPathRelativeMacro(destPathVariableManager, resolvedSrcValue, dest, true, null); - if (relativeSrcValue != null) + if (relativeSrcValue != null) { srcValue = relativeSrcValue; + } } destPathVariableManager.setURIValue(destVariable, URIUtil.toURI(srcValue)); return destVariable; @@ -1361,8 +1403,9 @@ String copyVariable(IResource source, IResource dest, String variable) throws Co * @param phantom If true, phantoms are included, otherwise they are ignored. */ public int countResources(IPath root, int depth, final boolean phantom) { - if (!tree.includes(root)) + if (!tree.includes(root)) { return 0; + } switch (depth) { case IResource.DEPTH_ZERO : return 1; @@ -1371,8 +1414,9 @@ public int countResources(IPath root, int depth, final boolean phantom) { case IResource.DEPTH_INFINITE : final int[] count = new int[1]; IElementContentVisitor visitor = (aTree, requestor, elementContents) -> { - if (phantom || !((ResourceInfo) elementContents).isSet(M_PHANTOM)) + if (phantom || !((ResourceInfo) elementContents).isSet(M_PHANTOM)) { count[0]++; + } return true; }; new ElementTreeIterator(tree, root).iterate(visitor); @@ -1400,12 +1444,15 @@ public ResourceInfo createResource(IResource resource, boolean phantom) throws C */ public ResourceInfo createResource(IResource resource, int updateFlags) throws CoreException { ResourceInfo info = createResource(resource, null, false, BitMask.isSet(updateFlags, IResource.REPLACE), false); - if ((updateFlags & IResource.DERIVED) != 0) + if ((updateFlags & IResource.DERIVED) != 0) { info.set(M_DERIVED); - if ((updateFlags & IResource.TEAM_PRIVATE) != 0) + } + if ((updateFlags & IResource.TEAM_PRIVATE) != 0) { info.set(M_TEAM_PRIVATE_MEMBER); - if ((updateFlags & IResource.HIDDEN) != 0) + } + if ((updateFlags & IResource.HIDDEN) != 0) { info.set(M_HIDDEN); + } // if ((updateFlags & IResource.VIRTUAL) != 0) // info.set(M_VIRTUAL); return info; @@ -1436,8 +1483,9 @@ public ResourceInfo createResource(IResource resource, ResourceInfo info, boolea if (original == null) { // we got here from a copy/move. we don't want to copy over any sync info // from the source so clear it. - if (!keepSyncInfo) + if (!keepSyncInfo) { info.setSyncInfo(null); + } tree.createElement(resource.getFullPath(), info); } else { // if overwrite==true then slam the new info into the tree even if one existed before @@ -1448,8 +1496,9 @@ public ResourceInfo createResource(IResource resource, ResourceInfo info, boolea // preserve the old sync info so its not dirty // XXX: must copy over the generic sync info from the old info to the new // XXX: do we really need to clone the sync info here? - if (!keepSyncInfo) + if (!keepSyncInfo) { info.setSyncInfo(original.getSyncInfo(true)); + } // mark the markers bit as dirty so we snapshot an empty marker set for // the new resource info.set(ICoreConstants.M_MARKERS_SNAP_DIRTY); @@ -1503,8 +1552,9 @@ public IStatus delete(IResource[] resources, int updateFlags, IProgressMonitor m } subMonitor.worked(1); } - if (result.matches(IStatus.ERROR)) + if (result.matches(IStatus.ERROR)) { throw new ResourceException(result); + } return result; } catch (OperationCanceledException e) { getWorkManager().operationCanceled(); @@ -1518,16 +1568,19 @@ public IStatus delete(IResource[] resources, int updateFlags, IProgressMonitor m @Override public void deleteMarkers(IMarker[] markers) throws CoreException { Assert.isNotNull(markers); - if (markers.length == 0) + if (markers.length == 0) { return; + } // clone to avoid outside changes markers = markers.clone(); try { prepareOperation(null, null); beginOperation(true); - for (IMarker marker : markers) - if (marker != null && marker.getResource() != null) + for (IMarker marker : markers) { + if (marker != null && marker.getResource() != null) { markerManager.removeMarker(marker.getResource(), marker.getId()); + } + } } finally { endOperation(null, false); } @@ -1544,10 +1597,12 @@ void deleteResource(IResource resource) { IPath path = resource.getFullPath(); if (path.equals(IPath.ROOT)) { IProject[] children = getRoot().getProjects(IContainer.INCLUDE_HIDDEN); - for (IProject element : children) + for (IProject element : children) { tree.deleteElement(element.getFullPath()); - } else + } + } else { tree.deleteElement(path); + } } /** @@ -1559,8 +1614,9 @@ void deleteResource(IResource resource) { public void endOperation(ISchedulingRule rule, boolean build) throws CoreException { WorkManager workManager = getWorkManager(); //don't do any end operation work if we failed to check in - if (workManager.checkInFailed(rule)) + if (workManager.checkInFailed(rule)) { return; + } // This is done in a try finally to ensure that we always decrement the operation count // and release the workspace lock. This must be done at the end because snapshot // and "hasChanges" comparison have to happen without interference from other threads. @@ -1588,8 +1644,9 @@ public void endOperation(ISchedulingRule rule, boolean build) throws CoreExcepti //find out if any operation has potentially modified the tree hasTreeChanges = workManager.shouldBuild(); //double check if the tree has actually changed - if (hasTreeChanges) + if (hasTreeChanges) { hasTreeChanges = operationTree != null && ElementTree.hasChanges(tree, operationTree, ResourceComparator.getBuildComparator(), true); + } broadcastPostChange(); // Request a snapshot if we are sufficiently out of date. saveManager.snapshotIfNeeded(hasTreeChanges); @@ -1598,14 +1655,16 @@ public void endOperation(ISchedulingRule rule, boolean build) throws CoreExcepti if (depthOne) { tree.immutable(); operationTree = null; - } else + } else { newWorkingTree(); + } } } finally { workManager.checkOut(rule); } - if (depthOne) + if (depthOne) { buildManager.endTopLevel(hasTreeChanges); + } } /** @@ -1663,8 +1722,9 @@ public BuildManager getBuildManager() { */ public IBuildConfiguration[] getBuildOrder() { // Return the build order cache. - if (buildOrder != null) + if (buildOrder != null) { return buildOrder; + } // see if a particular build order is specified String[] order = description.getBuildOrder(false); @@ -1675,8 +1735,9 @@ public IBuildConfiguration[] getBuildOrder() { // and eliminate non-existent and closed projects for (String element : order) { IProject project = getRoot().getProject(element); - if (project.isAccessible()) + if (project.isAccessible()) { configs.add(((Project) project).internalGetActiveBuildConfig()); + } } // Add projects not mentioned in the build order to the end, in a sensible reference order @@ -1772,8 +1833,9 @@ public LocalMetaArea getMetaArea() { } protected IMoveDeleteHook getMoveDeleteHook() { - if (moveDeleteHook == null) + if (moveDeleteHook == null) { initializeMoveDeleteHook(); + } return moveDeleteHook; } @@ -1840,14 +1902,17 @@ public ResourceInfo getResourceInfo(IPath path, boolean phantom, boolean mutable return info; } ResourceInfo result = null; - if (!tree.includes(path)) + if (!tree.includes(path)) { return null; - if (mutable) + } + if (mutable) { result = (ResourceInfo) tree.openElementData(path); - else + } else { result = (ResourceInfo) tree.getElementData(path); - if (result != null && (!phantom && result.isSet(M_PHANTOM))) + } + if (result != null && (!phantom && result.isSet(M_PHANTOM))) { return null; + } return result; } catch (IllegalArgumentException e) { return null; @@ -1863,8 +1928,9 @@ public IWorkspaceRoot getRoot() { public IResourceRuleFactory getRuleFactory() { //note that the rule factory is created lazily because it //requires loading the teamHook extension - if (ruleFactory == null) + if (ruleFactory == null) { ruleFactory = new Rules(this); + } return ruleFactory; } @@ -1881,8 +1947,9 @@ public ISynchronizer getSynchronizer() { * Returns the installed team hook. Never returns null. */ protected TeamHook getTeamHook() { - if (teamHook == null) + if (teamHook == null) { initializeTeamHook(); + } return teamHook; } @@ -1905,8 +1972,9 @@ public WorkManager getWorkManager() throws CoreException { */ protected void initializeMoveDeleteHook() { try { - if (!canCreateExtensions()) + if (!canCreateExtensions()) { return; + } IConfigurationElement[] configs = Platform.getExtensionRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_MOVE_DELETE_HOOK); // no-one is plugged into the extension point so disable validation if (configs == null || configs.length == 0) { @@ -1934,8 +2002,9 @@ protected void initializeMoveDeleteHook() { } } finally { // for now just use Core's implementation - if (moveDeleteHook == null) + if (moveDeleteHook == null) { moveDeleteHook = new MoveDeleteHook(); + } } } @@ -1964,8 +2033,9 @@ private void initializePreferenceLookupOrder() throws CoreException { */ protected void initializeTeamHook() { try { - if (!canCreateExtensions()) + if (!canCreateExtensions()) { return; + } IConfigurationElement[] configs = Platform.getExtensionRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_TEAM_HOOK); // no-one is plugged into the extension point so disable validation if (configs == null || configs.length == 0) { @@ -1994,10 +2064,11 @@ protected void initializeTeamHook() { } finally { // default to use Core's implementation //create anonymous subclass because TeamHook is abstract - if (teamHook == null) + if (teamHook == null) { teamHook = new TeamHook(this) { // empty }; + } } } @@ -2007,8 +2078,9 @@ protected void initializeTeamHook() { */ protected void initializeValidator() { shouldValidate = false; - if (!canCreateExtensions()) + if (!canCreateExtensions()) { return; + } IConfigurationElement[] configs = Platform.getExtensionRegistry().getConfigurationElementsFor(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_FILE_MODIFICATION_VALIDATOR); // no-one is plugged into the extension point so disable validation if (configs == null || configs.length == 0) { @@ -2085,8 +2157,9 @@ public IProjectDescription loadProjectDescription(IPath path) throws CoreExcepti // testing equality because it knows better w.r.t. drives and case sensitivity IPath user = path.removeLastSegments(1); IPath platform = getRoot().getLocation().append(result.getName()); - if (!user.toFile().equals(platform.toFile())) + if (!user.toFile().equals(platform.toFile())) { result.setLocation(user); + } } } catch (IOException ex) { e = ex; @@ -2131,8 +2204,9 @@ public IStatus move(IResource[] resources, IPath destination, int updateFlags, I continue; } // test siblings - if (parentPath == null) + if (parentPath == null) { parentPath = resource.getFullPath().removeLastSegments(1); + } if (parentPath.equals(resource.getFullPath().removeLastSegments(1))) { // test move requirements try { @@ -2166,8 +2240,9 @@ public IStatus move(IResource[] resources, IPath destination, int updateFlags, I subMonitor.done(); endOperation(getRoot(), true); } - if (status.matches(IStatus.ERROR)) + if (status.matches(IStatus.ERROR)) { throw new ResourceException(status); + } return status.isOK() ? (IStatus) Status.OK_STATUS : (IStatus) status; } @@ -2401,8 +2476,9 @@ public void prepareOperation(ISchedulingRule rule, IProgressMonitor monitor) thr try { //make sure autobuild is not running if it conflicts with this operation ISchedulingRule buildRule = getRuleFactory().buildRule(); - if (rule != null && buildRule != null && (rule.isConflicting(buildRule) || buildRule.isConflicting(rule))) + if (rule != null && buildRule != null && (rule.isConflicting(buildRule) || buildRule.isConflicting(rule))) { buildManager.interrupt(); + } } finally { getWorkManager().checkIn(rule, monitor); } @@ -2414,9 +2490,11 @@ public void prepareOperation(ISchedulingRule rule, IProgressMonitor monitor) thr protected boolean refreshRequested() { String[] args = Platform.getCommandLineArgs(); - for (String arg : args) - if (arg.equalsIgnoreCase(REFRESH_ON_STARTUP)) + for (String arg : args) { + if (arg.equalsIgnoreCase(REFRESH_ON_STARTUP)) { return true; + } + } return false; } @@ -2451,23 +2529,27 @@ public void run(ICoreRunnable action, ISchedulingRule rule, int options, IProgre try { prepareOperation(rule, subMonitor); beginOperation(true); - if (avoidNotification) + if (avoidNotification) { avoidNotification = notificationManager.beginAvoidNotify(); + } depth = getWorkManager().beginUnprotected(); action.run(subMonitor.newChild(Policy.opWork)); } catch (OperationCanceledException e) { getWorkManager().operationCanceled(); throw e; } catch (CoreException e) { - if (e.getStatus().getSeverity() == IStatus.CANCEL) + if (e.getStatus().getSeverity() == IStatus.CANCEL) { getWorkManager().operationCanceled(); + } throw e; } finally { subMonitor.done(); - if (avoidNotification) + if (avoidNotification) { notificationManager.endAvoidNotify(); - if (depth >= 0) + } + if (depth >= 0) { getWorkManager().endUnprotected(depth); + } endOperation(rule, false); } } @@ -2515,8 +2597,9 @@ public void setCrashed(boolean value) { if (crashed) { String msg = "The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes."; //$NON-NLS-1$ Policy.log(new ResourceStatus(ICoreConstants.CRASH_DETECTED, msg)); - if (Policy.DEBUG) + if (Policy.DEBUG) { Policy.debug(msg); + } } } @@ -2560,9 +2643,9 @@ protected void shutdown(IProgressMonitor monitor) throws CoreException { null); // best effort to shutdown every object and free resources for (IManager manager : managers) { - if (manager == null) + if (manager == null) { subMonitor.worked(1); - else { + } else { try { manager.shutdown(subMonitor.newChild(1)); } catch (Exception e) { @@ -2585,8 +2668,9 @@ protected void shutdown(IProgressMonitor monitor) throws CoreException { refreshManager = null; charsetManager = null; contentDescriptionManager = null; - if (!status.isOK()) + if (!status.isOK()) { throw new CoreException(status); + } } finally { subMonitor.done(); } @@ -2684,12 +2768,14 @@ public IStatus validateEdit(final IFile[] files, final Object context) { return result.getChildren().length == 0 ? Status.OK_STATUS : (IStatus) result; } // first time through the validator hasn't been initialized so try and create it - if (validator == null) + if (validator == null) { initializeValidator(); + } // we were unable to initialize the validator. Validation has been turned off and // a warning has already been logged so just return. - if (validator == null) + if (validator == null) { return Status.OK_STATUS; + } // otherwise call the API and throw an exception if appropriate final IStatus[] status = new IStatus[1]; ISafeRunnable body = new ISafeRunnable() { @@ -2702,9 +2788,11 @@ public void handleException(Throwable exception) { public void run() throws Exception { Object c = context; //must null any reference to FileModificationValidationContext for backwards compatibility - if (!(validator instanceof FileModificationValidator)) - if (c instanceof FileModificationValidationContext) + if (!(validator instanceof FileModificationValidator)) { + if (c instanceof FileModificationValidationContext) { c = null; + } + } status[0] = validator.validateEdit(files, c); } }; @@ -2759,15 +2847,18 @@ public IStatus validateProjectLocationURI(IProject project, URI location) { */ protected void validateSave(final IFile file) throws CoreException { // if validation is turned off then just return - if (!shouldValidate) + if (!shouldValidate) { return; + } // first time through the validator hasn't been initialized so try and create it - if (validator == null) + if (validator == null) { initializeValidator(); + } // we were unable to initialize the validator. Validation has been turned off and // a warning has already been logged so just return. - if (validator == null) + if (validator == null) { return; + } // otherwise call the API and throw an exception if appropriate final IStatus[] status = new IStatus[1]; ISafeRunnable body = new ISafeRunnable() { @@ -2782,15 +2873,17 @@ public void run() throws Exception { } }; SafeRunner.run(body); - if (!status[0].isOK()) + if (!status[0].isOK()) { throw new ResourceException(status[0]); + } } @Override public IStatus validateFiltered(IResource resource) { try { - if (((Resource) resource).isFilteredWithException(true)) + if (((Resource) resource).isFilteredWithException(true)) { return new ResourceStatus(IStatus.ERROR, Messages.resources_errorResourceIsFiltered); + } } catch (CoreException e) { // if we can't validate it, we return OK } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceDescription.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceDescription.java index 0859d7892c8..b55ff9eaf18 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceDescription.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceDescription.java @@ -62,8 +62,9 @@ public String[] getBuildOrder() { } public String[] getBuildOrder(boolean makeCopy) { - if (buildOrder == null) + if (buildOrder == null) { return null; + } return makeCopy ? (String[]) buildOrder.clone() : buildOrder; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspacePreferences.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspacePreferences.java index 1c27292c812..6e52f70dbde 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspacePreferences.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspacePreferences.java @@ -41,8 +41,9 @@ public class WorkspacePreferences extends WorkspaceDescription { * stringN". */ public static String convertStringArraytoString(String[] array) { - if (array == null || array.length == 0) + if (array == null || array.length == 0) { return ""; //$NON-NLS-1$ + } StringBuilder sb = new StringBuilder(); for (String element : array) { sb.append(element); @@ -58,8 +59,9 @@ public static String convertStringArraytoString(String[] array) { */ public static String[] convertStringToStringArray(String string, String separator) { List list = new ArrayList<>(); - for (StringTokenizer tokenizer = new StringTokenizer(string, separator); tokenizer.hasMoreTokens();) + for (StringTokenizer tokenizer = new StringTokenizer(string, separator); tokenizer.hasMoreTokens();) { list.add(tokenizer.nextToken()); + } return list.toArray(new String[list.size()]); } @@ -87,8 +89,9 @@ public WorkspacePreferences() { this.preferences = ResourcesPlugin.getPlugin().getPluginPreferences(); final String version = preferences.getString(ICoreConstants.PREF_VERSION_KEY); - if (!ICoreConstants.PREF_VERSION.equals(version)) + if (!ICoreConstants.PREF_VERSION.equals(version)) { upgradeVersion(version); + } // initialize cached preferences (for better performance) super.setAutoBuilding(preferences.getBoolean(ResourcesPlugin.PREF_AUTO_BUILDING)); @@ -130,8 +133,9 @@ public void copyTo(WorkspaceDescription target) { @Override public String[] getBuildOrder() { boolean defaultBuildOrder = preferences.getBoolean(ResourcesPlugin.PREF_DEFAULT_BUILD_ORDER); - if (defaultBuildOrder) + if (defaultBuildOrder) { return null; + } return convertStringToStringArray(preferences.getString(ResourcesPlugin.PREF_BUILD_ORDER), PROJECT_SEPARATOR); } @@ -234,27 +238,27 @@ protected void synchronizeWithPreferences(String property) { // do not use the value in the event - may be a string instead // of the expected type. Retrieve it from the preferences store // using the type-specific method - if (property.equals(ResourcesPlugin.PREF_AUTO_BUILDING)) + if (property.equals(ResourcesPlugin.PREF_AUTO_BUILDING)) { super.setAutoBuilding(preferences.getBoolean(ResourcesPlugin.PREF_AUTO_BUILDING)); - else if (property.equals(ResourcesPlugin.PREF_SNAPSHOT_INTERVAL)) + } else if (property.equals(ResourcesPlugin.PREF_SNAPSHOT_INTERVAL)) { super.setSnapshotInterval(preferences.getLong(ResourcesPlugin.PREF_SNAPSHOT_INTERVAL)); - else if (property.equals(ResourcesPlugin.PREF_MAX_BUILD_ITERATIONS)) + } else if (property.equals(ResourcesPlugin.PREF_MAX_BUILD_ITERATIONS)) { super.setMaxBuildIterations(preferences.getInt(ResourcesPlugin.PREF_MAX_BUILD_ITERATIONS)); - else if (property.equals(ResourcesPlugin.PREF_APPLY_FILE_STATE_POLICY)) + } else if (property.equals(ResourcesPlugin.PREF_APPLY_FILE_STATE_POLICY)) { super.setApplyFileStatePolicy(preferences.getBoolean(ResourcesPlugin.PREF_APPLY_FILE_STATE_POLICY)); - else if (property.equals(ResourcesPlugin.PREF_MAX_FILE_STATES)) + } else if (property.equals(ResourcesPlugin.PREF_MAX_FILE_STATES)) { super.setMaxFileStates(preferences.getInt(ResourcesPlugin.PREF_MAX_FILE_STATES)); - else if (property.equals(ResourcesPlugin.PREF_MAX_FILE_STATE_SIZE)) + } else if (property.equals(ResourcesPlugin.PREF_MAX_FILE_STATE_SIZE)) { super.setMaxFileStateSize(preferences.getLong(ResourcesPlugin.PREF_MAX_FILE_STATE_SIZE)); - else if (property.equals(ResourcesPlugin.PREF_FILE_STATE_LONGEVITY)) + } else if (property.equals(ResourcesPlugin.PREF_FILE_STATE_LONGEVITY)) { super.setFileStateLongevity(preferences.getLong(ResourcesPlugin.PREF_FILE_STATE_LONGEVITY)); - else if (property.equals(PreferenceInitializer.PREF_OPERATIONS_PER_SNAPSHOT)) + } else if (property.equals(PreferenceInitializer.PREF_OPERATIONS_PER_SNAPSHOT)) { super.setOperationsPerSnapshot(preferences.getInt(PreferenceInitializer.PREF_OPERATIONS_PER_SNAPSHOT)); - else if (property.equals(PreferenceInitializer.PREF_DELTA_EXPIRATION)) + } else if (property.equals(PreferenceInitializer.PREF_DELTA_EXPIRATION)) { super.setDeltaExpiration(preferences.getLong(PreferenceInitializer.PREF_DELTA_EXPIRATION)); - else if (property.equals(ResourcesPlugin.PREF_MAX_CONCURRENT_BUILDS)) + } else if (property.equals(ResourcesPlugin.PREF_MAX_CONCURRENT_BUILDS)) { super.setMaxConcurrentBuilds(preferences.getInt(ResourcesPlugin.PREF_MAX_CONCURRENT_BUILDS)); - else if (property.equals(ResourcesPlugin.PREF_KEEP_DERIVED_STATE)) { + } else if (property.equals(ResourcesPlugin.PREF_KEEP_DERIVED_STATE)) { super.setKeepDerivedState(preferences.getBoolean(ResourcesPlugin.PREF_KEEP_DERIVED_STATE)); } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceRoot.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceRoot.java index e4519d045aa..441d329483c 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceRoot.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceRoot.java @@ -88,8 +88,9 @@ public IContainer[] findContainersForLocationURI(URI location) { @Override public IContainer[] findContainersForLocationURI(URI location, int memberFlags) { - if (!location.isAbsolute()) + if (!location.isAbsolute()) { throw new IllegalArgumentException(); + } return (IContainer[]) getLocalManager().allResourcesFor(location, false, memberFlags); } @@ -106,8 +107,9 @@ public IFile[] findFilesForLocationURI(URI location) { @Override public IFile[] findFilesForLocationURI(URI location, int memberFlags) { - if (!location.isAbsolute()) + if (!location.isAbsolute()) { throw new IllegalArgumentException(); + } return (IFile[]) getLocalManager().allResourcesFor(location, true, memberFlags); } @@ -118,8 +120,9 @@ public IContainer getContainerForLocation(IPath location) { @Override public String getDefaultCharset(boolean checkImplicit) { - if (checkImplicit) + if (checkImplicit) { return ResourcesPlugin.getEncoding(); + } String enc = ResourcesPlugin.getPlugin().getPluginPreferences().getString(ResourcesPlugin.PREF_ENCODING); return enc == null || enc.length() == 0 ? null : enc; } @@ -190,9 +193,10 @@ public IProject[] getProjects(int memberFlags) { } catch (ArrayStoreException ex) { // Shouldn't happen since only projects should be children of the workspace root for (IResource root2 : roots) { - if (root2.getType() != IResource.PROJECT) + if (root2.getType() != IResource.PROJECT) { Policy.log(IStatus.ERROR, NLS.bind("{0} is an invalid child of the workspace root.", //$NON-NLS-1$ root2), null); + } } throw ex; @@ -208,15 +212,18 @@ public int getType() { @Override public void internalSetLocal(boolean flag, int depth) throws CoreException { // do nothing for the root, but call for its children - if (depth == IResource.DEPTH_ZERO) + if (depth == IResource.DEPTH_ZERO) { return; - if (depth == IResource.DEPTH_ONE) + } + if (depth == IResource.DEPTH_ONE) { depth = IResource.DEPTH_ZERO; + } // get the children via the workspace since we know that this // resource exists (it is local). IResource[] children = getChildren(IResource.NONE); - for (IResource element : children) + for (IResource element : children) { ((Resource) element).internalSetLocal(flag, depth); + } } @Override @@ -255,10 +262,12 @@ public boolean isLocal(int depth) { @Override public boolean isLocal(int flags, int depth) { // don't check the flags....workspace root is always local - if (depth == DEPTH_ZERO) + if (depth == DEPTH_ZERO) { return true; - if (depth == DEPTH_ONE) + } + if (depth == DEPTH_ONE) { depth = DEPTH_ZERO; + } // get the children via the workspace since we know that this // resource exists (it is local). IResource[] children = getChildren(IResource.NONE); @@ -280,10 +289,11 @@ public boolean isPhantom() { public void setDefaultCharset(String charset) { // directly change the Resource plugin's preference for encoding Preferences resourcesPreferences = ResourcesPlugin.getPlugin().getPluginPreferences(); - if (charset != null) + if (charset != null) { resourcesPreferences.setValue(ResourcesPlugin.PREF_ENCODING, charset); - else + } else { resourcesPreferences.setToDefault(ResourcesPlugin.PREF_ENCODING); + } } @Override @@ -293,8 +303,9 @@ public void setHidden(boolean isHidden) { @Override public long setLocalTimeStamp(long value) { - if (value < 0) + if (value < 0) { throw new IllegalArgumentException("Illegal time stamp: " + value); //$NON-NLS-1$ + } //can't set local time for root return value; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceTreeReader_1.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceTreeReader_1.java index b9050d21ff2..01006c82292 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceTreeReader_1.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceTreeReader_1.java @@ -97,8 +97,9 @@ protected BuilderPersistentInfo readBuilderInfo(IProject project, DataInputStrea //read the project name String projectName = input.readUTF(); //use the name of the project handle if available - if (project != null) + if (project != null) { projectName = project.getName(); + } String builderName = input.readUTF(); return new BuilderPersistentInfo(projectName, builderName, index); } @@ -107,8 +108,9 @@ protected void readBuildersPersistentInfo(IProject project, DataInputStream inpu monitor = Policy.monitorFor(monitor); try { int builderCount = input.readInt(); - for (int i = 0; i < builderCount; i++) + for (int i = 0; i < builderCount; i++) { builders.add(readBuilderInfo(project, input, i)); + } } finally { monitor.done(); } @@ -143,8 +145,9 @@ public ElementTree readSnapshotTree(DataInputStream input, ElementTree complete, try { // make sure each snapshot is read by the correct reader int version = input.readInt(); - if (version != getVersion()) + if (version != getVersion()) { return WorkspaceTreeReader.getReader(workspace, version).readSnapshotTree(input, complete, monitor); + } } catch (EOFException e) { break; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceTreeReader_2.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceTreeReader_2.java index aaefa603e81..da59f3eaa72 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceTreeReader_2.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/WorkspaceTreeReader_2.java @@ -75,8 +75,9 @@ protected void readBuildersPersistentInfo(IProject project, DataInputStream inpu // read interesting projects int n = input.readInt(); IProject[] projects = new IProject[n]; - for (int j = 0; j < n; j++) + for (int j = 0; j < n; j++) { projects[j] = workspace.getRoot().getProject(input.readUTF()); + } info.setInterestingProjects(projects); builders.add(info); } @@ -126,8 +127,9 @@ public void readTree(DataInputStream input, IProgressMonitor monitor) throws Cor readBuildersPersistentInfo(null, input, buildersToBeLinked, Policy.subMonitorFor(monitor, Policy.opWork * 10 / 100)); linkBuildersToTrees(buildersToBeLinked, trees, treeIndex, Policy.subMonitorFor(monitor, Policy.opWork * 10 / 100)); - for (BuilderPersistentInfo builderPersistentInfo : builderInfos) + for (BuilderPersistentInfo builderPersistentInfo : builderInfos) { builderPersistentInfo.setConfigName(input.readUTF()); + } } // Set the builder infos on the projects @@ -174,8 +176,9 @@ public void readTree(IProject project, DataInputStream input, IProgressMonitor m readBuildersPersistentInfo(project, input, infos, Policy.subMonitorFor(monitor, 1)); linkBuildersToTrees(infos, trees, treeIndex, Policy.subMonitorFor(monitor, 1)); - for (BuilderPersistentInfo builderPersistentInfo : builderInfos) + for (BuilderPersistentInfo builderPersistentInfo : builderInfos) { builderPersistentInfo.setConfigName(input.readUTF()); + } } // Set the builder info on the projects @@ -214,8 +217,9 @@ protected void linkBuildersToTrees(List buildersToBeLinke private void setBuilderInfos(List infos) { Map> groupedInfos = new HashMap<>(); for (BuilderPersistentInfo info : infos) { - if (!groupedInfos.containsKey(info.getProjectName())) + if (!groupedInfos.containsKey(info.getProjectName())) { groupedInfos.put(info.getProjectName(), new ArrayList<>()); + } groupedInfos.get(info.getProjectName()).add(info); } for (Map.Entry> entry : groupedInfos.entrySet()) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/XMLWriter.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/XMLWriter.java index e876c84078d..8d83fdfcc19 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/XMLWriter.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/XMLWriter.java @@ -56,8 +56,9 @@ public void printSimpleTag(String name, Object value) { } public void printTabulation() { - for (int i = 0; i < tab; i++) + for (int i = 0; i < tab; i++) { super.print('\t'); + } } public void printTag(String name, HashMap parameters) { @@ -68,7 +69,7 @@ public void printTag(String name, HashMap parameters, boolean sh StringBuilder sb = new StringBuilder(); sb.append("<"); //$NON-NLS-1$ sb.append(name); - if (parameters != null) + if (parameters != null) { for (Map.Entry entry : parameters.entrySet()) { sb.append(" "); //$NON-NLS-1$ String key = entry.getKey(); @@ -77,13 +78,16 @@ public void printTag(String name, HashMap parameters, boolean sh sb.append(getEscaped(String.valueOf(entry.getValue()))); sb.append("\""); //$NON-NLS-1$ } + } sb.append(">"); //$NON-NLS-1$ - if (shouldTab) + if (shouldTab) { printTabulation(); - if (newLine) + } + if (newLine) { println(sb.toString()); - else + } else { print(sb.toString()); + } } public void startTag(String name, HashMap parameters) { @@ -108,8 +112,9 @@ private static void appendEscapedChar(StringBuilder buffer, char c) { public static String getEscaped(String s) { StringBuilder result = new StringBuilder(s.length() + 10); - for (int i = 0; i < s.length(); ++i) + for (int i = 0; i < s.length(); ++i) { appendEscapedChar(result, s.charAt(i)); + } return result.toString(); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ModelProviderDescriptor.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ModelProviderDescriptor.java index b82bbedfa14..3186ea5c0d4 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ModelProviderDescriptor.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ModelProviderDescriptor.java @@ -43,8 +43,9 @@ public ModelProviderDescriptor(IExtension extension) throws CoreException { } private boolean convert(EvaluationResult eval) { - if (eval == EvaluationResult.FALSE) + if (eval == EvaluationResult.FALSE) { return false; + } return true; } @@ -100,8 +101,9 @@ public synchronized ModelProvider getModelProvider() throws CoreException { } public boolean matches(IEvaluationContext context) throws CoreException { - if (enablementRule == null) + if (enablementRule == null) { return false; + } return convert(enablementRule.evaluate(context)); } @@ -111,8 +113,9 @@ public boolean matches(IEvaluationContext context) throws CoreException { protected void readExtension(IExtension extension) throws CoreException { //read the extension id = extension.getUniqueIdentifier(); - if (id == null) + if (id == null) { fail(Messages.mapping_noIdentifier); + } label = extension.getLabel(); IConfigurationElement[] elements = extension.getConfigurationElements(); int count = elements.length; @@ -122,8 +125,9 @@ protected void readExtension(IExtension extension) throws CoreException { String name = element.getName(); if (name.equalsIgnoreCase("extends-model")) { //$NON-NLS-1$ String attribute = element.getAttribute("id"); //$NON-NLS-1$ - if (attribute == null) + if (attribute == null) { fail(NLS.bind(Messages.mapping_invalidDef, id)); + } extendsList.add(attribute); } else if (name.equalsIgnoreCase(ExpressionTagNames.ENABLEMENT)) { enablementRule = ExpressionConverter.getDefault().perform(element); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ModelProviderManager.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ModelProviderManager.java index c3b01f6d2fd..da954367699 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ModelProviderManager.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ModelProviderManager.java @@ -52,14 +52,16 @@ public IModelProviderDescriptor[] getDescriptors() { public ModelProvider getModelProvider(String modelProviderId) throws CoreException { IModelProviderDescriptor desc = getDescriptor(modelProviderId); - if (desc == null) + if (desc == null) { return null; + } return desc.getModelProvider(); } protected void lazyInitialize() { - if (descriptors != null) + if (descriptors != null) { return; + } IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(ResourcesPlugin.PI_RESOURCES, ResourcesPlugin.PT_MODEL_PROVIDERS); IExtension[] extensions = point.getExtensions(); descriptors = new HashMap<>(extensions.length * 2 + 1); @@ -70,8 +72,9 @@ protected void lazyInitialize() { } catch (CoreException e) { Policy.log(e); } - if (desc != null) + if (desc != null) { descriptors.put(desc.getId(), desc); + } } //do cycle detection now so it only has to be done once //cycle detection on a graph subset is a pain diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ProposedResourceDelta.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ProposedResourceDelta.java index dc0757e0fd5..7937d7e246f 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ProposedResourceDelta.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ProposedResourceDelta.java @@ -47,8 +47,9 @@ public void accept(IResourceDeltaVisitor visitor, boolean includePhantoms) throw @Override public void accept(IResourceDeltaVisitor visitor, int memberFlags) throws CoreException { - if (!visitor.visit(this)) + if (!visitor.visit(this)) { return; + } for (ProposedResourceDelta childDelta : children.values()) { childDelta.accept(visitor, memberFlags); } @@ -58,8 +59,9 @@ public void accept(IResourceDeltaVisitor visitor, int memberFlags) throws CoreEx * Adds a child delta to the list of children for this delta node. */ protected void add(ProposedResourceDelta delta) { - if (children.isEmpty() && status == 0) + if (children.isEmpty() && status == 0) { setKind(IResourceDelta.CHANGED); + } children.put(delta.getResource().getName(), delta); } @@ -75,15 +77,17 @@ protected void addFlags(int flags) { @Override public IResourceDelta findMember(IPath path) { int segmentCount = path.segmentCount(); - if (segmentCount == 0) + if (segmentCount == 0) { return this; + } //iterate over the path and find matching child delta ProposedResourceDelta current = this; for (int i = 0; i < segmentCount; i++) { current = current.children.get(path.segment(i)); - if (current == null) + if (current == null) { return null; + } } return current; } @@ -102,8 +106,9 @@ public IResourceDelta[] getAffectedChildren(int kindMask) { public IResourceDelta[] getAffectedChildren(int kindMask, int memberFlags) { List result = new ArrayList<>(); for (ProposedResourceDelta child : children.values()) { - if ((child.getKind() & kindMask) != 0) + if ((child.getKind() & kindMask) != 0) { result.add(child); + } } return result.toArray(new IResourceDelta[result.size()]); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ResourceChangeDescriptionFactory.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ResourceChangeDescriptionFactory.java index 5b2430d18ea..6318fa95ac1 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ResourceChangeDescriptionFactory.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ResourceChangeDescriptionFactory.java @@ -43,18 +43,21 @@ private ProposedResourceDelta buildDeleteDelta(ProposedResourceDelta parentDelta parentDelta.add(delta); } delta.setKind(IResourceDelta.REMOVED); - if (deleteContent) + if (deleteContent) { delta.addFlags(IResourceDelta.DELETE_CONTENT_PROPOSED); - if (resource.getType() == IResource.FILE) + } + if (resource.getType() == IResource.FILE) { return delta; + } //recurse to build deletion deltas for children try { IResource[] members = ((IContainer) resource).members(); int childCount = members.length; if (childCount > 0) { ProposedResourceDelta[] childDeltas = new ProposedResourceDelta[childCount]; - for (int i = 0; i < childCount; i++) + for (int i = 0; i < childCount; i++) { childDeltas[i] = buildDeleteDelta(delta, members[i], deleteContent); + } } } catch (CoreException e) { //don't need to create deletion deltas for children of inaccessible resources @@ -65,11 +68,13 @@ private ProposedResourceDelta buildDeleteDelta(ProposedResourceDelta parentDelta @Override public void change(IFile file) { ProposedResourceDelta delta = getDelta(file); - if (delta.getKind() == 0) + if (delta.getKind() == 0) { delta.setKind(IResourceDelta.CHANGED); + } //the CONTENT flag only applies to the changed and moved from cases - if (delta.getKind() == IResourceDelta.CHANGED || (delta.getFlags() & IResourceDelta.MOVED_FROM) != 0 || (delta.getFlags() & IResourceDelta.COPIED_FROM) != 0) + if (delta.getKind() == IResourceDelta.CHANGED || (delta.getFlags() & IResourceDelta.MOVED_FROM) != 0 || (delta.getFlags() & IResourceDelta.COPIED_FROM) != 0) { delta.addFlags(IResourceDelta.CONTENT); + } } @Override @@ -224,8 +229,9 @@ boolean moveOrCopy(IResource resource, final IPath sourcePrefix, final IPath des destinationDelta.addFlags(move ? IResourceDelta.MOVED_FROM : IResourceDelta.COPIED_FROM); destinationDelta.setMovedFromPath(fromPath); // Apply the source flags - if (move) + if (move) { destinationDelta.addFlags(sourceFlags); + } } return true; diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ResourceModelProvider.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ResourceModelProvider.java index dc87dd4acd4..9532740299e 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ResourceModelProvider.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ResourceModelProvider.java @@ -54,8 +54,9 @@ public ResourceMapping[] getMappings(ResourceTraversal[] traversals, ResourceMap } break; case IResource.DEPTH_ZERO : - if (resource.getType() == IResource.FILE) + if (resource.getType() == IResource.FILE) { result.add(resource); + } break; } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ShallowContainer.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ShallowContainer.java index 86f6dd4a8da..0585bc34412 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ShallowContainer.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ShallowContainer.java @@ -34,10 +34,10 @@ public IContainer getResource() { @Override public boolean equals(Object obj) { - if (obj == this) + if (obj == this) { return true; - if (obj instanceof ShallowContainer) { - ShallowContainer other = (ShallowContainer) obj; + } + if (obj instanceof ShallowContainer other) { return other.getResource().equals(getResource()); } return false; @@ -51,8 +51,9 @@ public int hashCode() { @Override @SuppressWarnings("unchecked") public T getAdapter(Class adapter) { - if (adapter == IResource.class || adapter == IContainer.class) + if (adapter == IResource.class || adapter == IContainer.class) { return (T) container; + } return super.getAdapter(adapter); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ShallowResourceMapping.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ShallowResourceMapping.java index 9f70538bf12..145b7c32c34 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ShallowResourceMapping.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/ShallowResourceMapping.java @@ -55,12 +55,10 @@ public boolean contains(ResourceMapping mapping) { Object object = mapping.getModelObject(); IResource resource = container.getResource(); // A shallow mapping only contains direct file children or equal shallow containers - if (object instanceof ShallowContainer) { - ShallowContainer sc = (ShallowContainer) object; + if (object instanceof ShallowContainer sc) { return sc.getResource().equals(resource); } - if (object instanceof IResource) { - IResource other = (IResource) object; + if (object instanceof IResource other) { return other.getType() == IResource.FILE && resource.getFullPath().equals(other.getFullPath().removeLastSegments(1)); } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/SimpleResourceMapping.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/SimpleResourceMapping.java index 188d780febc..13f62a8194c 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/SimpleResourceMapping.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/mapping/SimpleResourceMapping.java @@ -34,12 +34,10 @@ public SimpleResourceMapping(IResource resource) { public boolean contains(ResourceMapping mapping) { if (mapping.getModelProviderId().equals(this.getModelProviderId())) { Object object = mapping.getModelObject(); - if (object instanceof IResource) { - IResource other = (IResource) object; + if (object instanceof IResource other) { return resource.getFullPath().isPrefixOf(other.getFullPath()); } - if (object instanceof ShallowContainer) { - ShallowContainer sc = (ShallowContainer) object; + if (object instanceof ShallowContainer sc) { IResource other = sc.getResource(); return resource.getFullPath().isPrefixOf(other.getFullPath()); } @@ -59,8 +57,9 @@ public String getModelProviderId() { @Override public IProject[] getProjects() { - if (resource.getType() == IResource.ROOT) + if (resource.getType() == IResource.ROOT) { return ((IWorkspaceRoot) resource).getProjects(); + } return new IProject[] {resource.getProject()}; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/ParentVariableResolver.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/ParentVariableResolver.java index 97c700551d0..f908bcaa53d 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/ParentVariableResolver.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/ParentVariableResolver.java @@ -36,28 +36,32 @@ public ParentVariableResolver() { @Override public String getValue(String variable, IResource resource) { int index = variable.indexOf('-'); - if (index == -1 || index == (variable.length() - 1)) + if (index == -1 || index == (variable.length() - 1)) { return null; + } String countRemaining = variable.substring(index + 1); index = countRemaining.indexOf('-'); - if (index == -1 || index == (variable.length() - 1)) + if (index == -1 || index == (variable.length() - 1)) { return null; + } String countString = countRemaining.substring(0, index); int count = 0; try { count = Integer.parseInt(countString); - if (count < 0) + if (count < 0) { return null; + } } catch (NumberFormatException e) { return null; } String argument = countRemaining.substring(index + 1); URI value = resource.getPathVariableManager().getURIValue(argument); - if (value == null) + if (value == null) { return null; + } value = resource.getPathVariableManager().resolveURI(value); value = URIUtil.toURI(URIUtil.toPath(value).removeLastSegments(count)); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/ProjectLocationVariableResolver.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/ProjectLocationVariableResolver.java index 3837da1fd87..db922962efd 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/ProjectLocationVariableResolver.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/ProjectLocationVariableResolver.java @@ -32,8 +32,9 @@ public String[] getVariableNames(String variable, IResource resource) { @Override public String getValue(String variable, IResource resource) { - if (resource.getProject().getLocationURI() != null) + if (resource.getProject().getLocationURI() != null) { return resource.getProject().getLocationURI().toASCIIString(); + } return null; } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/WorkspaceParentLocationVariableResolver.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/WorkspaceParentLocationVariableResolver.java index 04e03c6fc68..666ceeb3e52 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/WorkspaceParentLocationVariableResolver.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/projectvariables/WorkspaceParentLocationVariableResolver.java @@ -40,8 +40,9 @@ public String getValue(String variable, IResource resource) { IContainer parent = resource.getParent(); if (parent != null) { URI locationURI = parent.getLocationURI(); - if (locationURI != null) + if (locationURI != null) { return locationURI.toASCIIString(); + } } return null; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Convert.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Convert.java index 64901a3c558..4773341e96e 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Convert.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Convert.java @@ -38,8 +38,9 @@ public class Convert { * This can be avoided by calling String.getBytes(String encoding) instead. */ public static byte[] toPlatformBytes(String target) { - if (defaultEncoding == null) + if (defaultEncoding == null) { return target.getBytes(); + } // try to use the default encoding try { return target.getBytes(defaultEncoding); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Win32Monitor.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Win32Monitor.java index ab856309bd1..8ffeafff327 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Win32Monitor.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Win32Monitor.java @@ -97,28 +97,30 @@ public boolean exists() { @Override public void handleNotification() { - if (!isOpen()) + if (!isOpen()) { return; + } ChainedHandle next = getNext(); if (next != null) { if (next.isOpen()) { if (!next.exists()) { next.close(); - if (next instanceof LinkedResourceHandle) { - LinkedResourceHandle linkedResourceHandle = (LinkedResourceHandle) next; + if (next instanceof LinkedResourceHandle linkedResourceHandle) { linkedResourceHandle.postRefreshRequest(); } ChainedHandle previous = getPrevious(); - if (previous != null) + if (previous != null) { previous.open(); + } } } else { next.open(); if (next.isOpen()) { Handle previous = getPrevious(); previous.close(); - if (next instanceof LinkedResourceHandle) + if (next instanceof LinkedResourceHandle) { ((LinkedResourceHandle) next).postRefreshRequest(); + } } } } @@ -161,11 +163,13 @@ public void close() { if (isOpen()) { if (!Win32Natives.FindCloseChangeNotification(handleValue)) { int error = Win32Natives.GetLastError(); - if (error != Win32Natives.ERROR_INVALID_HANDLE) + if (error != Win32Natives.ERROR_INVALID_HANDLE) { addException(NLS.bind(Messages.WM_errCloseHandle, Integer.toString(error))); + } } - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(DEBUG_PREFIX + "removed handle: " + handleValue); //$NON-NLS-1$ + } handleValue = Win32Natives.INVALID_HANDLE_VALUE; } } @@ -229,8 +233,9 @@ private void openHandleOn(String path, boolean subtree) { protected void postRefreshRequest(IResource resource) { //native callback occurs even if resource was changed within workspace - if (!resource.isSynchronized(IResource.DEPTH_INFINITE)) + if (!resource.isSynchronized(IResource.DEPTH_INFINITE)) { refreshResult.refresh(resource); + } } public void setHandleValue(long handleValue) { @@ -411,8 +416,9 @@ private long[][] balancedSplit(final long[] array, final int max) { } private Handle createHandle(IResource resource) { - if (resource.isLinked()) + if (resource.isLinked()) { return new LinkedResourceHandle(resource); + } return new ResourceHandle(resource); } @@ -449,8 +455,7 @@ private Handle getHandle(IResource resource) { // synchronized: in order to protect the map during iteration synchronized (fHandleValueToHandle) { for (Handle handle : fHandleValueToHandle.values()) { - if (handle instanceof ResourceHandle) { - ResourceHandle resourceHandle = (ResourceHandle) handle; + if (handle instanceof ResourceHandle resourceHandle) { if (resourceHandle.getResource().equals(resource)) { return handle; } @@ -491,8 +496,9 @@ public boolean monitor(IResource resource) { } //make sure the job is running schedule(RESCHEDULE_DELAY); - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(DEBUG_PREFIX + " added monitor for: " + resource); //$NON-NLS-1$ + } return true; } @@ -534,41 +540,48 @@ private void removeHandles(Collection handles) { @Override protected IStatus run(IProgressMonitor monitor) { long start = -System.currentTimeMillis(); - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(DEBUG_PREFIX + "job started."); //$NON-NLS-1$ + } try { long[][] handleArrays = getHandleValueArrays(); monitor.beginTask(Messages.WM_beginTask, handleArrays.length); // If changes occur to the list of handles, // ignore them until the next time through the loop. for (long[] handleArray : handleArrays) { - if (monitor.isCanceled()) + if (monitor.isCanceled()) { return Status.CANCEL_STATUS; + } waitForNotification(handleArray); monitor.worked(1); } } finally { monitor.done(); start += System.currentTimeMillis(); - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(DEBUG_PREFIX + "job finished in: " + start + "ms"); //$NON-NLS-1$ //$NON-NLS-2$ + } } //always reschedule the job - so it will come back after errors or cancelation long delay = Math.max(RESCHEDULE_DELAY, start); - if (Policy.DEBUG_AUTO_REFRESH) + if (Policy.DEBUG_AUTO_REFRESH) { Policy.debug(DEBUG_PREFIX + "rescheduling in: " + delay / 1000 + " seconds"); //$NON-NLS-1$ //$NON-NLS-2$ + } final Bundle bundle = Platform.getBundle(ResourcesPlugin.PI_RESOURCES); //if the bundle is null then the framework has shutdown - just bail out completely (bug 98219) - if (bundle == null) + if (bundle == null) { return Status.OK_STATUS; + } //don't reschedule the job if the resources plugin has been shut down - if (bundle.getState() == Bundle.ACTIVE) + if (bundle.getState() == Bundle.ACTIVE) { schedule(delay); + } MultiStatus result = errors; errors = null; //just log native refresh failures - if (result != null && !result.isOK()) + if (result != null && !result.isOK()) { ResourcesPlugin.getPlugin().getLog().log(result); + } return Status.OK_STATUS; } @@ -590,12 +603,14 @@ public void unmonitor(IResource resource) { } } else { Handle handle = getHandle(resource); - if (handle != null) + if (handle != null) { removeHandle(handle); + } } //stop the job if there are no more handles - if (fHandleValueToHandle.isEmpty()) + if (fHandleValueToHandle.isEmpty()) { cancel(); + } } /** @@ -636,7 +651,8 @@ private void waitForNotification(long[] handleValues) { // WaitForMultipleObjects returns WAIT_OBJECT_0 + index index -= Win32Natives.WAIT_OBJECT_0; Handle handle = fHandleValueToHandle.get(handleValues[index]); - if (handle != null) + if (handle != null) { handle.handleNotification(); + } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Win32RefreshProvider.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Win32RefreshProvider.java index e1b43efe207..7847c36c4a6 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Win32RefreshProvider.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/refresh/win32/Win32RefreshProvider.java @@ -33,12 +33,15 @@ public class Win32RefreshProvider extends RefreshProvider { */ @Override public IRefreshMonitor installMonitor(IResource resource, IRefreshResult result, IProgressMonitor progressMonitor) { - if (resource.getLocation() == null || !resource.exists() || resource.getType() == IResource.FILE) + if (resource.getLocation() == null || !resource.exists() || resource.getType() == IResource.FILE) { return null; - if (monitor == null) + } + if (monitor == null) { monitor = new Win32Monitor(result); - if (monitor.monitor(resource)) + } + if (monitor.monitor(resource)) { return monitor; + } return null; } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/undo/snapshot/AbstractResourceSnapshot.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/undo/snapshot/AbstractResourceSnapshot.java index 018f04b0c97..91563b8a993 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/undo/snapshot/AbstractResourceSnapshot.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/undo/snapshot/AbstractResourceSnapshot.java @@ -113,8 +113,9 @@ protected void restoreResourceAttributes(IResource resource) } if (markerDescriptions != null) { for (MarkerSnapshot markerDescription : markerDescriptions) { - if (markerDescription.resource.exists()) + if (markerDescription.resource.exists()) { markerDescription.createMarker(); + } } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/undo/snapshot/ContainerSnapshot.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/undo/snapshot/ContainerSnapshot.java index d8805ef5481..f516fa1c388 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/undo/snapshot/ContainerSnapshot.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/resources/undo/snapshot/ContainerSnapshot.java @@ -173,8 +173,9 @@ protected final void createChildResources(IContainer parentHandle, // restore any children SubMonitor subMonitor = SubMonitor.convert(monitor, members.size()); for (IResourceSnapshot member : members) { - if (member instanceof AbstractResourceSnapshot) + if (member instanceof AbstractResourceSnapshot) { ((AbstractResourceSnapshot) member).parent = parentHandle; + } member.createResource(subMonitor.split(1)); } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/FileUtil.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/FileUtil.java index 4037735f449..446355aab00 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/FileUtil.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/FileUtil.java @@ -67,14 +67,16 @@ public static IFileInfo attributesToFileInfo(ResourceAttributes attributes) { * Converts an IPath into its canonical form for the local file system. */ public static IPath canonicalPath(IPath path) { - if (path == null) + if (path == null) { return null; + } try { final String pathString = path.toOSString(); final String canonicalPath = new java.io.File(pathString).getCanonicalPath(); //only create a new path if necessary - if (canonicalPath.equals(pathString)) + if (canonicalPath.equals(pathString)) { return path; + } return IPath.fromOSString(canonicalPath); } catch (IOException e) { return path; @@ -92,11 +94,13 @@ public static IPath canonicalPath(IPath path) { * in Java 1.7. */ public static IPath realPath(IPath path) { - if (path == null) + if (path == null) { return null; + } IFileSystem fileSystem = EFS.getLocalFileSystem(); - if (fileSystem.isCaseSensitive()) + if (fileSystem.isCaseSensitive()) { return path; + } IPath realPath = path.isAbsolute() ? IPath.ROOT : IPath.EMPTY; String device = path.getDevice(); if (device != null) { @@ -128,8 +132,9 @@ public static IPath realPath(IPath path) { } realPath = realPath.append(realName); } else { - if (fileStore == null) + if (fileStore == null) { fileStore = fileSystem.getStore(realPath); + } fileStore = fileStore.getChild(segment); IFileInfo info = fileStore.fetchInfo(); if (!info.exists()) { @@ -153,14 +158,16 @@ public static IPath realPath(IPath path) { * Converts a URI into its canonical form. */ public static URI canonicalURI(URI uri) { - if (uri == null) + if (uri == null) { return null; + } if (EFS.SCHEME_FILE.equals(uri.getScheme())) { //only create a new URI if it is different final IPath inputPath = URIUtil.toPath(uri); final IPath canonicalPath = canonicalPath(inputPath); - if (inputPath == canonicalPath) + if (inputPath == canonicalPath) { return uri; + } return URIUtil.toURI(canonicalPath); } return uri; @@ -173,14 +180,16 @@ public static URI canonicalURI(URI uri) { * @see #realPath(IPath) */ public static URI realURI(URI uri) { - if (uri == null) + if (uri == null) { return null; + } if (EFS.SCHEME_FILE.equals(uri.getScheme())) { // Only create a new URI if it is different. final IPath inputPath = URIUtil.toPath(uri); final IPath realPath = realPath(inputPath); - if (inputPath == realPath) + if (inputPath == realPath) { return uri; + } return URIUtil.toURI(realPath); } return uri; @@ -211,14 +220,17 @@ private static boolean computeOverlap(IPath location1, IPath location2, boolean * is a prefix of the second. Returns false if the locations do not overlap */ private static boolean computeOverlap(URI location1, URI location2, boolean bothDirections) { - if (location1.equals(location2)) + if (location1.equals(location2)) { return true; + } String scheme1 = location1.getScheme(); String scheme2 = location2.getScheme(); - if (scheme1 == null ? scheme2 != null : !scheme1.equals(scheme2)) + if (scheme1 == null ? scheme2 != null : !scheme1.equals(scheme2)) { return false; - if (EFS.SCHEME_FILE.equals(scheme1) && EFS.SCHEME_FILE.equals(scheme2)) + } + if (EFS.SCHEME_FILE.equals(scheme1) && EFS.SCHEME_FILE.equals(scheme2)) { return computeOverlap(URIUtil.toPath(location1), URIUtil.toPath(location2), bothDirections); + } IFileSystem system = null; try { system = EFS.getFileSystem(scheme1); @@ -289,12 +301,14 @@ public static boolean isPrefixOf(URI location1, URI location2) { * as being relative to path variables. */ public static IPath toPath(URI uri) { - if (uri == null) + if (uri == null) { return null; + } final String scheme = uri.getScheme(); // null scheme represents path variable - if (scheme == null || EFS.SCHEME_FILE.equals(scheme)) + if (scheme == null || EFS.SCHEME_FILE.equals(scheme)) { return IPath.fromOSString(uri.getSchemeSpecificPart()); + } return null; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/ObjectMap.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/ObjectMap.java index 2c2ab2766da..751dde65b71 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/ObjectMap.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/ObjectMap.java @@ -44,8 +44,9 @@ public ObjectMap() { * @param initialCapacity The initial number of elements that will fit in the map. */ public ObjectMap(int initialCapacity) { - if (initialCapacity > 0) + if (initialCapacity > 0) { elements = new Object[Math.max(initialCapacity * 2, 0)]; + } } /** @@ -80,11 +81,14 @@ public Object clone() { */ @Override public boolean containsKey(Object key) { - if (elements == null || count == 0) + if (elements == null || count == 0) { return false; - for (int i = 0; i < elements.length; i = i + 2) - if (elements[i] != null && elements[i].equals(key)) + } + for (int i = 0; i < elements.length; i = i + 2) { + if (elements[i] != null && elements[i].equals(key)) { return true; + } + } return false; } @@ -93,11 +97,14 @@ public boolean containsKey(Object key) { */ @Override public boolean containsValue(Object value) { - if (elements == null || count == 0) + if (elements == null || count == 0) { return false; - for (int i = 1; i < elements.length; i = i + 2) - if (elements[i] != null && elements[i].equals(value)) + } + for (int i = 1; i < elements.length; i = i + 2) { + if (elements[i] != null && elements[i].equals(value)) { return true; + } + } return false; } @@ -117,21 +124,25 @@ public Set> entrySet() { */ @Override public boolean equals(Object o) { - if (!(o instanceof Map)) + if (!(o instanceof Map)) { return false; + } Map other = (Map) o; //must be same size - if (count != other.size()) + if (count != other.size()) { return false; + } //keysets must be equal - if (!keySet().equals(other.keySet())) + if (!keySet().equals(other.keySet())) { return false; + } //values for each key must be equal for (int i = 0; i < elements.length; i = i + 2) { - if (elements[i] != null && (!elements[i + 1].equals(other.get(elements[i])))) + if (elements[i] != null && (!elements[i + 1].equals(other.get(elements[i])))) { return false; + } } return true; } @@ -141,11 +152,14 @@ public boolean equals(Object o) { */ @Override public V get(Object key) { - if (elements == null || count == 0) + if (elements == null || count == 0) { return null; - for (int i = 0; i < elements.length; i = i + 2) - if (elements[i] != null && elements[i].equals(key)) + } + for (int i = 0; i < elements.length; i = i + 2) { + if (elements[i] != null && elements[i].equals(key)) { return (V) elements[i + 1]; + } + } return null; } @@ -203,14 +217,17 @@ public Set keySet() { */ @Override public V put(K key, V value) { - if (key == null) + if (key == null) { throw new NullPointerException(); - if (value == null) + } + if (value == null) { return remove(key); + } // handle the case where we don't have any attributes yet - if (elements == null) + if (elements == null) { elements = new Object[DEFAULT_SIZE]; + } if (count == 0) { elements[0] = key; elements[1] = value; @@ -234,13 +251,15 @@ public V put(K key, V value) { } // this will put the emptyIndex greater than the size but // that's ok because we will grow first. - if (emptyIndex == -1) + if (emptyIndex == -1) { emptyIndex = count * 2; + } // otherwise add it to the list of elements. // grow if necessary - if (elements.length <= (count * 2)) + if (elements.length <= (count * 2)) { grow(); + } elements[emptyIndex] = key; elements[emptyIndex + 1] = value; count++; @@ -252,8 +271,9 @@ public V put(K key, V value) { */ @Override public void putAll(Map map) { - for (Map.Entry e : map.entrySet()) + for (Map.Entry e : map.entrySet()) { put(e.getKey(), e.getValue()); + } } /** @@ -261,8 +281,9 @@ public void putAll(Map map) { */ @Override public V remove(Object key) { - if (elements == null || count == 0) + if (elements == null || count == 0) { return null; + } for (int i = 0; i < elements.length; i = i + 2) { if (elements[i] != null && elements[i].equals(key)) { elements[i] = null; @@ -290,14 +311,17 @@ public int size() { public void shareStrings(StringPool set) { //copy elements for thread safety Object[] array = elements; - if (array == null) + if (array == null) { return; + } for (int i = 0; i < array.length; i++) { Object o = array[i]; - if (o instanceof String) + if (o instanceof String) { array[i] = set.add((String) o); - if (o instanceof IStringPoolParticipant) + } + if (o instanceof IStringPoolParticipant) { ((IStringPoolParticipant) o).shareStrings(set); + } } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/Policy.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/Policy.java index 48eefd48cd2..97a3c093cff 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/Policy.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/Policy.java @@ -121,8 +121,9 @@ public void optionsChanged(DebugOptions options) { public static final int totalWork = 100; public static void checkCanceled(IProgressMonitor monitor) { - if (monitor.isCanceled()) + if (monitor.isCanceled()) { throw new OperationCanceledException(); + } } /** @@ -149,21 +150,24 @@ public static void debug(Throwable t) { StringWriter writer = new StringWriter(); t.printStackTrace(new PrintWriter(writer)); String str = writer.toString(); - if (str.endsWith("\n")) //$NON-NLS-1$ + if (str.endsWith("\n")) { //$NON-NLS-1$ str = str.substring(0, str.length() - 2); + } debug(str); } public static void log(int severity, String message, Throwable t) { - if (message == null) + if (message == null) { message = ""; //$NON-NLS-1$ + } log(new Status(severity, ResourcesPlugin.PI_RESOURCES, 1, message, t)); } public static void log(IStatus status) { final Bundle bundle = Platform.getBundle(ResourcesPlugin.PI_RESOURCES); - if (bundle == null) + if (bundle == null) { return; + } ILog.of(bundle).log(status); } @@ -179,10 +183,12 @@ public static IProgressMonitor monitorFor(IProgressMonitor monitor) { } public static IProgressMonitor subMonitorFor(IProgressMonitor monitor, int ticks) { - if (monitor == null) + if (monitor == null) { return new NullProgressMonitor(); - if (monitor instanceof NullProgressMonitor) + } + if (monitor instanceof NullProgressMonitor) { return monitor; + } return new SubProgressMonitor(monitor, ticks); } } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPool.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPool.java index 5d0c951ac3a..28a37b760f4 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPool.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPool.java @@ -47,8 +47,9 @@ public StringPool() { * @return A string that is equal to the argument. */ public String add(String string) { - if (string == null) + if (string == null) { return string; + } String result = map.putIfAbsent(string, string); if (result != null) { if (result != string) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPoolJob.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPoolJob.java index 50bb5ef2f36..9a4df532c87 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPoolJob.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/StringPoolJob.java @@ -61,10 +61,11 @@ public StringPoolJob() { */ public void addStringPoolParticipant(IStringPoolParticipant participant, ISchedulingRule rule) { participants.put(participant, rule); - if (getState() == Job.SLEEPING) + if (getState() == Job.SLEEPING) { wakeUp(INITIAL_DELAY); - else + } else { schedule(INITIAL_DELAY); + } } /** @@ -82,8 +83,9 @@ public void removeStringPoolParticipant(IStringPoolParticipant participant) { @Override protected IStatus run(IProgressMonitor monitor) { //if the system is shutting down, don't build - if (systemBundle.getState() == Bundle.STOPPING) + if (systemBundle.getState() == Bundle.STOPPING) { return Status.OK_STATUS; + } //copy current participants to handle concurrent additions and removals to map Map.Entry[] entries = participants.entrySet().toArray(new Map.Entry[participants.size()]); @@ -106,13 +108,15 @@ protected IStatus run(IProgressMonitor monitor) { } if (start > 0) { lastDuration = System.currentTimeMillis() - start; - if (Policy.DEBUG_STRINGS) + if (Policy.DEBUG_STRINGS) { Policy.debug("String sharing saved " + savings + " bytes in: " + lastDuration); //$NON-NLS-1$ //$NON-NLS-2$ + } } //throttle frequency if it takes too long long scheduleDelay = Math.max(RESCHEDULE_DELAY, lastDuration * 100); - if (Policy.DEBUG_STRINGS) + if (Policy.DEBUG_STRINGS) { Policy.debug("Rescheduling string sharing job in: " + scheduleDelay); //$NON-NLS-1$ + } schedule(scheduleDelay); return Status.OK_STATUS; } @@ -120,8 +124,9 @@ protected IStatus run(IProgressMonitor monitor) { private int shareStrings(IStringPoolParticipant[] toRun, IProgressMonitor monitor) { final StringPool pool = new StringPool(); for (final IStringPoolParticipant current : toRun) { - if (monitor.isCanceled()) + if (monitor.isCanceled()) { break; + } SafeRunner.run(new ISafeRunnable() { @Override public void handleException(Throwable exception) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/UniversalUniqueIdentifier.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/UniversalUniqueIdentifier.java index 8677f13e090..0521979116a 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/UniversalUniqueIdentifier.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/utils/UniversalUniqueIdentifier.java @@ -91,19 +91,22 @@ public UniversalUniqueIdentifier() { */ public UniversalUniqueIdentifier(byte[] byteValue) { fBits = new byte[BYTES_SIZE]; - if (byteValue.length >= BYTES_SIZE) + if (byteValue.length >= BYTES_SIZE) { System.arraycopy(byteValue, 0, fBits, 0, BYTES_SIZE); + } } private void appendByteString(StringBuilder buffer, byte value) { String hexString; - if (value < 0) + if (value < 0) { hexString = Integer.toHexString(256 + value); - else + } else { hexString = Integer.toHexString(value); - if (hexString.length() == 1) + } + if (hexString.length() == 1) { buffer.append("0"); //$NON-NLS-1$ + } buffer.append(hexString); } @@ -116,9 +119,11 @@ private static BigInteger clockValueNow() { } public static int compareTime(byte[] fBits1, byte[] fBits2) { - for (int i = TIME_FIELD_STOP; i >= 0; i--) - if (fBits1[i] != fBits2[i]) + for (int i = TIME_FIELD_STOP; i >= 0; i--) { + if (fBits1[i] != fBits2[i]) { return (0xFF & fBits1[i]) - (0xFF & fBits2[i]); + } + } return 0; } @@ -142,19 +147,24 @@ private static byte[] computeNodeAddress() { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (!(obj instanceof UniversalUniqueIdentifier)) + } + if (!(obj instanceof UniversalUniqueIdentifier)) { return false; + } byte[] other = ((UniversalUniqueIdentifier) obj).fBits; - if (fBits == other) + if (fBits == other) { return true; - if (fBits.length != other.length) + } + if (fBits.length != other.length) { return false; + } for (int i = 0; i < fBits.length; i++) { - if (fBits[i] != other[i]) + if (fBits[i] != other[i]) { return false; + } } return true; } @@ -170,8 +180,9 @@ public int hashCode() { private static int nextClockSequence() { - if (fgClockSequence == -1) + if (fgClockSequence == -1) { fgClockSequence = (int) (fgRandomNumberGenerator.nextDouble() * MAX_CLOCK_SEQUENCE); + } fgClockSequence = (fgClockSequence + 1) % MAX_CLOCK_SEQUENCE; @@ -187,16 +198,19 @@ private static BigInteger nextTimestamp() { if (timestampComparison == 0) { if (fgClockAdjustment == MAX_CLOCK_ADJUSTMENT) { - while (timestamp.compareTo(fgPreviousClockValue) == 0) + while (timestamp.compareTo(fgPreviousClockValue) == 0) { timestamp = clockValueNow(); + } timestamp = nextTimestamp(); - } else + } else { fgClockAdjustment++; + } } else { fgClockAdjustment = 0; - if (timestampComparison < 0) + if (timestampComparison < 0) { nextClockSequence(); + } } return timestamp; @@ -259,8 +273,9 @@ private static BigInteger timestamp() { fgClockAdjustment = 0; nextClockSequence(); timestamp = clockValueNow(); - } else + } else { timestamp = nextTimestamp(); + } fgPreviousClockValue = timestamp; return fgClockAdjustment == 0 ? timestamp : timestamp.add(BigInteger.valueOf(fgClockAdjustment)); @@ -281,8 +296,9 @@ public byte[] toBytes() { @Override public String toString() { StringBuilder buffer = new StringBuilder(); - for (byte bit : fBits) + for (byte bit : fBits) { appendByteString(buffer, bit); + } return buffer.toString(); } @@ -291,8 +307,9 @@ public String toStringAsBytes() { for (int i = 0; i < fBits.length; i++) { result.append(fBits[i]); - if (i < fBits.length + 1) + if (i < fBits.length + 1) { result.append(','); + } } result.append('}'); return result.toString(); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/DefaultElementComparator.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/DefaultElementComparator.java index 27a02f6b58c..9faa6f0711f 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/DefaultElementComparator.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/DefaultElementComparator.java @@ -36,10 +36,12 @@ protected DefaultElementComparator() { */ @Override public int compare(Object oldInfo, Object newInfo) { - if (oldInfo == null && newInfo == null) + if (oldInfo == null && newInfo == null) { return 0; - if (oldInfo == null || newInfo == null) + } + if (oldInfo == null || newInfo == null) { return 1; + } return testEquality(oldInfo, newInfo) ? 0 : 1; } @@ -57,10 +59,12 @@ public static IElementComparator getComparator() { * Makes a comparison based on equality */ protected boolean testEquality(Object oldInfo, Object newInfo) { - if (oldInfo == null && newInfo == null) + if (oldInfo == null && newInfo == null) { return true; - if (oldInfo == null || newInfo == null) + } + if (oldInfo == null || newInfo == null) { return false; + } return oldInfo.equals(newInfo); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTree.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTree.java index a4fa9b7c3fd..a0820ade654 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTree.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTree.java @@ -203,8 +203,9 @@ public synchronized ElementTree collapseTo(ElementTree parent) { */ public synchronized void createElement(IPath key, Object data) { /* don't allow modification of the implicit root */ - if (key.isRoot()) + if (key.isRoot()) { return; + } // Clear the child IDs cache in case it's referring to this parent. This is conservative. childIDsCache = null; @@ -265,8 +266,9 @@ public synchronized void createSubtree(IPath key, ElementTree subtree) { */ public synchronized void deleteElement(IPath key) { /* don't allow modification of the implicit root */ - if (key.isRoot()) + if (key.isRoot()) { return; + } // Clear the child IDs cache in case it's referring to this parent. // This is conservative. @@ -353,8 +355,9 @@ protected IPath[] getChildIDs(IPath key) { if (cache != null && cache.path == key) { return cache.childPaths; } - if (key == null) + if (key == null) { return tree.rootPaths(); + } try { IPath[] children = tree.getChildren(key); childIDsCache = new ChildIDsCache(key, children); // Cache the result @@ -408,13 +411,16 @@ public Object getElementData(IPath key) { */ public synchronized Object getElementDataIgnoreCase(IPath key) { /* don't allow modification of the implicit root */ - if (key.isRoot()) + if (key.isRoot()) { return null; + } DataTreeLookup lookup = lookupCacheIgnoreCase; // Grab it in case it's replaced concurrently. - if (lookup == null || lookup.key != key) + if (lookup == null || lookup.key != key) { lookupCacheIgnoreCase = lookup = tree.lookupIgnoreCase(key); - if (lookup.isPresent) + } + if (lookup.isPresent) { return lookup.data; + } throw createElementNotFoundException(key); } @@ -425,8 +431,9 @@ public synchronized Object getElementDataIgnoreCase(IPath key) { */ public synchronized String[] getNamesOfChildren(IPath key) { try { - if (key == null) + if (key == null) { return new String[] {""}; //$NON-NLS-1$ + } return tree.getNamesOfChildren(key); } catch (ObjectNotFoundException e) { throw createElementNotFoundException(key); @@ -489,13 +496,16 @@ public IElementTreeData getTreeData() { */ public static boolean hasChanges(ElementTree newLayer, ElementTree oldLayer, IElementComparator comparator, boolean inclusive) { // if any of the layers are null, assume that things have changed - if (newLayer == null || oldLayer == null) + if (newLayer == null || oldLayer == null) { return true; - if (newLayer == oldLayer) + } + if (newLayer == oldLayer) { return false; + } //if the tree data has changed, then the tree has changed - if (comparator.compare(newLayer.getTreeData(), oldLayer.getTreeData()) != IElementComparator.K_NO_CHANGE) + if (comparator.compare(newLayer.getTreeData(), oldLayer.getTreeData()) != IElementComparator.K_NO_CHANGE) { return true; + } // The tree structure has the top layer(s) (i.e., tree) parentage pointing down to a complete // layer whose parent is null. The bottom layers (i.e., operationTree) point up to the @@ -506,15 +516,16 @@ public static boolean hasChanges(ElementTree newLayer, ElementTree oldLayer, IEl // look down from the current layer (always inclusive) if the top layer is mutable ElementTree stopLayer = null; - if (newLayer.isImmutable()) + if (newLayer.isImmutable()) { // if the newLayer is immutable, the tree structure all points up so ensure that // when searching up, we stop at newLayer (inclusive) stopLayer = newLayer.getParent(); - else { + } else { ElementTree layer = newLayer; while (layer != null && layer.getParent() != null) { - if (!layer.getDataTree().isEmptyDelta()) + if (!layer.getDataTree().isEmptyDelta()) { return true; + } layer = layer.getParent(); } } @@ -523,8 +534,9 @@ public static boolean hasChanges(ElementTree newLayer, ElementTree oldLayer, IEl // depending on whether newLayer is mutable. ElementTree layer = inclusive ? oldLayer : oldLayer.getParent(); while (layer != null && layer.getParent() != stopLayer) { - if (!layer.getDataTree().isEmptyDelta()) + if (!layer.getDataTree().isEmptyDelta()) { return true; + } layer = layer.getParent(); } // didn't find anything that changed @@ -661,15 +673,17 @@ public synchronized Object openElementData(IPath key) { Assert.isTrue(!isImmutable()); /* don't allow modification of the implicit root */ - if (key.isRoot()) + if (key.isRoot()) { return null; + } DataTreeLookup lookup = lookupCache; // Grab it in case it's replaced concurrently. if (lookup == null || lookup.key != key) { lookupCache = lookup = tree.lookup(key); } if (lookup.isPresent) { - if (lookup.foundInFirstDelta) + if (lookup.foundInFirstDelta) { return lookup.data; + } /** * The node has no data in the most recent delta. * Pull it up to the present delta by setting its data with a clone. @@ -699,8 +713,9 @@ public synchronized Object openElementData(IPath key) { */ public synchronized void setElementData(IPath key, Object data) { /* don't allow modification of the implicit root */ - if (key.isRoot()) + if (key.isRoot()) { return; + } Assert.isNotNull(key); // Clear the lookup cache, in case the element being modified is the same diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeIterator.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeIterator.java index f8dc15087fd..1645b5040f8 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeIterator.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeIterator.java @@ -93,8 +93,9 @@ private void doIteration(DataTreeNode node, IElementContentVisitor visitor) { //pop the segment from the requestor stack nextFreeSegment--; - if (nextFreeSegment < 0) + if (nextFreeSegment < 0) { nextFreeSegment = 0; + } } /** @@ -117,8 +118,9 @@ public void iterate(IElementContentVisitor visitor) { if (path.isRoot()) { //special visit for root element to use special treeData if (visitor.visitElement(tree, this, tree.getTreeData())) { - if (treeRoot == null) + if (treeRoot == null) { return; + } AbstractDataTreeNode[] children = treeRoot.getChildren(); int len = children.length; for (int i = 0; i < len; i++) { @@ -129,8 +131,9 @@ public void iterate(IElementContentVisitor visitor) { } } } else { - if (treeRoot == null) + if (treeRoot == null) { return; + } push(path, path.segmentCount() - 1); doIteration(treeRoot, visitor); } @@ -140,8 +143,9 @@ public void iterate(IElementContentVisitor visitor) { * Push the first "toPush" segments of this path. */ private void push(IPath pathToPush, int toPush) { - if (toPush <= 0) + if (toPush <= 0) { return; + } for (int i = 0; i < toPush; i++) { if (nextFreeSegment >= segments.length) { grow(); @@ -152,8 +156,9 @@ private void push(IPath pathToPush, int toPush) { @Override public String requestName() { - if (nextFreeSegment == 0) + if (nextFreeSegment == 0) { return ""; //$NON-NLS-1$ + } return segments[nextFreeSegment - 1]; } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeReader.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeReader.java index ec130e43335..48647c204d0 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeReader.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeReader.java @@ -67,8 +67,9 @@ public void writeData(IPath path, Object data, DataOutput output) { public Object readData(IPath path, DataInput input) throws IOException { //never read the root node of an ElementTree //this node is reserved for the parent backpointer - if (!IPath.ROOT.equals(path)) + if (!IPath.ROOT.equals(path)) { return factory.readElement(path, input); + } return null; } }; @@ -79,8 +80,9 @@ public Object readData(IPath path, DataInput input) throws IOException { * Returns the appropriate reader for the given version. */ public ElementTreeReader getReader(int formatVersion) throws IOException { - if (formatVersion == 1) + if (formatVersion == 1) { return new ElementTreeReaderImpl_1(elementInfoFlattener); + } throw new IOException(Messages.watson_unknown); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeReaderImpl_1.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeReaderImpl_1.java index 08b81ed7543..cd93833c468 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeReaderImpl_1.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/internal/watson/ElementTreeReaderImpl_1.java @@ -47,8 +47,9 @@ public ElementTree readDelta(ElementTree parentTree, DataInput input) throws IOE DeltaDataTree delta = dataTreeReader.readTree(complete, input, ""); //$NON-NLS-1$ //if the delta is empty, just return the parent - if (delta.isEmptyDelta()) + if (delta.isEmptyDelta()) { return parentTree; + } ElementTree tree = new ElementTree(delta); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/FileInfoMatcherDescription.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/FileInfoMatcherDescription.java index e1e28cb0d29..e56e86c230e 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/FileInfoMatcherDescription.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/FileInfoMatcherDescription.java @@ -50,12 +50,15 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + if (getClass() != obj.getClass()) { return false; + } FileInfoMatcherDescription other = (FileInfoMatcherDescription) obj; return Objects.equals(this.arguments, other.arguments) && Objects.equals(this.id, other.id); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ProjectScope.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ProjectScope.java index 771956eb738..eef6f66771a 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ProjectScope.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ProjectScope.java @@ -57,15 +57,17 @@ public final class ProjectScope extends AbstractScope { */ public ProjectScope(IProject context) { super(); - if (context == null) + if (context == null) { throw new IllegalArgumentException(); + } this.project = context; } @Override public IEclipsePreferences getNode(String qualifier) { - if (qualifier == null) + if (qualifier == null) { throw new IllegalArgumentException(); + } IPreferencesService preferencesService = Platform.getPreferencesService(); Preferences scopeNode = preferencesService.getRootNode().node(SCOPE); Preferences projectNode = scopeNode.node(project.getName()); @@ -85,13 +87,15 @@ public String getName() { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (!super.equals(obj)) + } + if (!super.equals(obj)) { return false; - if (!(obj instanceof ProjectScope)) + } + if (!(obj instanceof ProjectScope other)) { return false; - ProjectScope other = (ProjectScope) obj; + } return project.equals(other.project); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ResourceAttributes.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ResourceAttributes.java index 160a1f5eee3..c307a4ec4d0 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ResourceAttributes.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ResourceAttributes.java @@ -151,10 +151,11 @@ public void setArchive(boolean archive) { * @noreference This method is not intended to be referenced by clients. */ public void set(int mask, boolean value) { - if (value) + if (value) { attributes |= mask; - else + } else { attributes &= ~mask; + } } /** diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ResourcesPlugin.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ResourcesPlugin.java index fb1bc20107f..efc710e73d2 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ResourcesPlugin.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/ResourcesPlugin.java @@ -589,8 +589,9 @@ public Workspace addingService(ServiceReference reference) { IStatus result; try { result = workspace.open(null); - if (!result.isOK()) + if (!result.isOK()) { getLog().log(result); + } workspaceRegistration = context.registerService(IWorkspace.class, workspace, null); return workspace; } catch (CoreException e) { diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/filtermatchers/CompoundFileInfoMatcher.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/filtermatchers/CompoundFileInfoMatcher.java index 866017b0616..e23cbb8543e 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/filtermatchers/CompoundFileInfoMatcher.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/filtermatchers/CompoundFileInfoMatcher.java @@ -40,7 +40,8 @@ private AbstractFileInfoMatcher instantiate(IProject project, FileInfoMatcherDes public final void initialize(IProject project, Object arguments) throws CoreException { FileInfoMatcherDescription[] filters = (FileInfoMatcherDescription[]) arguments; matchers = new AbstractFileInfoMatcher[filters != null ? filters.length : 0]; - for (int i = 0; i < matchers.length; i++) + for (int i = 0; i < matchers.length; i++) { matchers[i] = instantiate(project, filters[i]); + } } } \ No newline at end of file diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ModelProvider.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ModelProvider.java index b7c5f8d2803..623381f1a9b 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ModelProvider.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ModelProvider.java @@ -67,8 +67,7 @@ public static IModelProviderDescriptor[] getModelProviderDescriptors() { @Override public boolean equals(Object obj) { - if (obj instanceof ModelProvider) { - ModelProvider other = (ModelProvider) obj; + if (obj instanceof ModelProvider other) { return other.getDescriptor().getId().equals(getDescriptor().getId()); } return super.equals(obj); @@ -139,8 +138,9 @@ public ResourceMapping[] getMappings(IResource[] resources, ResourceMappingConte Set mappings = new HashSet<>(); for (IResource resource : resources) { ResourceMapping[] resourceMappings = getMappings(resource, context, monitor); - if (resourceMappings.length > 0) + if (resourceMappings.length > 0) { mappings.addAll(Arrays.asList(resourceMappings)); + } } return mappings.toArray(new ResourceMapping[mappings.size()]); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceChangeValidator.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceChangeValidator.java index b91d6c1faca..de9ca1ef01c 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceChangeValidator.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceChangeValidator.java @@ -57,8 +57,9 @@ public final class ResourceChangeValidator { * @return the singleton change validator */ public static ResourceChangeValidator getValidator() { - if (instance == null) + if (instance == null) { instance = new ResourceChangeValidator(); + } return instance; } @@ -151,12 +152,14 @@ public IStatus validateChange(IResourceDelta delta, IProgressMonitor monitor) { try { IResource[] resources = getRootResources(delta); ModelProvider[] providers = getProviders(resources); - if (providers.length == 0) + if (providers.length == 0) { return Status.OK_STATUS; + } monitor.beginTask(Messages.mapping_validate, providers.length); IStatus[] result = new IStatus[providers.length]; - for (int i = 0; i < providers.length; i++) + for (int i = 0; i < providers.length; i++) { result[i] = providers[i].validateChange(delta, Policy.subMonitorFor(monitor, 1)); + } return combineResults(result); } finally { monitor.done(); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceMapping.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceMapping.java index fb059811eec..0814f578e4b 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceMapping.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceMapping.java @@ -61,8 +61,9 @@ public abstract class ResourceMapping extends PlatformObject { */ public void accept(ResourceMappingContext context, IResourceVisitor visitor, IProgressMonitor monitor) throws CoreException { ResourceTraversal[] traversals = getTraversals(context, monitor); - for (ResourceTraversal traversal : traversals) + for (ResourceTraversal traversal : traversals) { traversal.accept(visitor); + } } /** @@ -90,10 +91,10 @@ public boolean contains(ResourceMapping mapping) { */ @Override public boolean equals(Object obj) { - if (obj == this) + if (obj == this) { return true; - if (obj instanceof ResourceMapping) { - ResourceMapping other = (ResourceMapping) obj; + } + if (obj instanceof ResourceMapping other) { return other.getModelObject().equals(getModelObject()); } return false; @@ -115,8 +116,9 @@ public boolean equals(Object obj) { public IMarker[] findMarkers(String type, boolean includeSubtypes, IProgressMonitor monitor) throws CoreException { final ResourceTraversal[] traversals = getTraversals(ResourceMappingContext.LOCAL_CONTEXT, monitor); ArrayList result = new ArrayList<>(); - for (ResourceTraversal traversal : traversals) + for (ResourceTraversal traversal : traversals) { traversal.doFindMarkers(result, type, includeSubtypes); + } return result.toArray(new IMarker[result.size()]); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceTraversal.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceTraversal.java index 682c386ad26..89a07d762d1 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceTraversal.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/mapping/ResourceTraversal.java @@ -51,8 +51,9 @@ public class ResourceTraversal { * that are passed to the IResource#accept method. */ public ResourceTraversal(IResource[] resources, int depth, int flags) { - if (resources == null) + if (resources == null) { throw new NullPointerException(); + } this.resources = resources; this.depth = depth; this.flags = flags; @@ -68,15 +69,18 @@ public ResourceTraversal(IResource[] resources, int depth, int flags) { * */ public void accept(IResourceVisitor visitor) throws CoreException { - for (IResource resource : resources) + for (IResource resource : resources) { try { - if (resource.exists()) + if (resource.exists()) { resource.accept(visitor, depth, flags); + } } catch (CoreException e) { //ignore failure in the case of concurrent deletion - if (e.getStatus().getCode() != IResourceStatus.RESOURCE_NOT_FOUND) + if (e.getStatus().getCode() != IResourceStatus.RESOURCE_NOT_FOUND) { throw e; + } } + } } /** @@ -98,14 +102,18 @@ public boolean contains(IResource resource) { } private boolean contains(IResource resource, IResource child) { - if (resource.equals(child)) + if (resource.equals(child)) { return true; - if (depth == IResource.DEPTH_ZERO) + } + if (depth == IResource.DEPTH_ZERO) { return false; - if (child.getParent().equals(resource)) + } + if (child.getParent().equals(resource)) { return true; - if (depth == IResource.DEPTH_INFINITE) + } + if (depth == IResource.DEPTH_INFINITE) { return resource.getFullPath().isPrefixOf(child.getFullPath()); + } return false; } @@ -116,8 +124,9 @@ private boolean contains(IResource resource, IResource child) { */ void doFindMarkers(ArrayList result, String type, boolean includeSubtypes) { MarkerManager markerMan = ((Workspace) ResourcesPlugin.getWorkspace()).getMarkerManager(); - for (IResource resource : resources) + for (IResource resource : resources) { markerMan.doFindMarkers(resource, result, type, includeSubtypes, depth); + } } /** @@ -133,8 +142,9 @@ void doFindMarkers(ArrayList result, String type, boolean includeSubtyp * @see IResource#findMarkers(String, boolean, int) */ public IMarker[] findMarkers(String type, boolean includeSubtypes) throws CoreException { - if (resources.length == 0) + if (resources.length == 0) { return new IMarker[0]; + } ArrayList result = new ArrayList<>(); doFindMarkers(result, type, includeSubtypes); return result.toArray(new IMarker[result.size()]); diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/FileModificationValidator.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/FileModificationValidator.java index 5dccc046901..e61c12e9e88 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/FileModificationValidator.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/FileModificationValidator.java @@ -55,12 +55,13 @@ public abstract class FileModificationValidator implements IFileModificationVali @Override public final IStatus validateEdit(IFile[] files, Object context) { FileModificationValidationContext validationContext; - if (context == null) + if (context == null) { validationContext = null; - else if (context instanceof FileModificationValidationContext) + } else if (context instanceof FileModificationValidationContext) { validationContext = (FileModificationValidationContext) context; - else + } else { validationContext = new FileModificationValidationContext(context); + } return validateEdit(files, validationContext); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/ResourceRuleFactory.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/ResourceRuleFactory.java index b1750230c16..bcf86ddf8d9 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/ResourceRuleFactory.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/ResourceRuleFactory.java @@ -83,8 +83,9 @@ public final ISchedulingRule buildRule() { */ @Override public ISchedulingRule charsetRule(IResource resource) { - if (resource.getType() == IResource.ROOT) + if (resource.getType() == IResource.ROOT) { return null; + } return resource.getProject(); } @@ -188,8 +189,9 @@ public final ISchedulingRule markerRule(IResource resource) { public ISchedulingRule modifyRule(IResource resource) { IPath path = resource.getFullPath(); //modifying the project description may cause linked resources to be created or deleted - if (path.segmentCount() == 2 && path.segment(1).equals(IProjectDescription.DESCRIPTION_FILE_NAME)) + if (path.segmentCount() == 2 && path.segment(1).equals(IProjectDescription.DESCRIPTION_FILE_NAME)) { return parent(resource); + } return resource; } @@ -257,20 +259,26 @@ public ISchedulingRule refreshRule(IResource resource) { */ @Override public ISchedulingRule validateEditRule(IResource[] resources) { - if (resources.length == 0) + if (resources.length == 0) { return null; + } //optimize rule for single file - if (resources.length == 1) + if (resources.length == 1) { return isReadOnly(resources[0]) ? parent(resources[0]) : null; + } //need a lock on the parents of all read-only files HashSet rules = new HashSet<>(); - for (IResource resource : resources) - if (isReadOnly(resource)) + for (IResource resource : resources) { + if (isReadOnly(resource)) { rules.add(parent(resource)); - if (rules.isEmpty()) + } + } + if (rules.isEmpty()) { return null; - if (rules.size() == 1) + } + if (rules.size() == 1) { return rules.iterator().next(); + } ISchedulingRule[] ruleArray = rules.toArray(new ISchedulingRule[rules.size()]); return new MultiRule(ruleArray); } diff --git a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/TeamHook.java b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/TeamHook.java index 454efb8969a..7f3bed86609 100644 --- a/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/TeamHook.java +++ b/resources/bundles/org.eclipse.core.resources/src/org/eclipse/core/resources/team/TeamHook.java @@ -177,8 +177,9 @@ public IStatus validateCreateLink(IFile file, int updateFlags, IPath location) { */ public IStatus validateCreateLink(IFile file, int updateFlags, URI location) { //forward to old method to ensure old hooks get a chance to validate in the local case - if (EFS.SCHEME_FILE.equals(location.getScheme())) + if (EFS.SCHEME_FILE.equals(location.getScheme())) { return validateCreateLink(file, updateFlags, URIUtil.toPath(location)); + } return Status.OK_STATUS; } @@ -241,8 +242,9 @@ public IStatus validateCreateLink(IFolder folder, int updateFlags, IPath locatio */ public IStatus validateCreateLink(IFolder folder, int updateFlags, URI location) { //forward to old method to ensure old hooks get a chance to validate in the local case - if (EFS.SCHEME_FILE.equals(location.getScheme())) + if (EFS.SCHEME_FILE.equals(location.getScheme())) { return validateCreateLink(folder, updateFlags, URIUtil.toPath(location)); + } return Status.OK_STATUS; } } diff --git a/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/ConvertPath.java b/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/ConvertPath.java index 67fb67dd7bd..b536377f52a 100644 --- a/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/ConvertPath.java +++ b/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/ConvertPath.java @@ -75,11 +75,12 @@ public ConvertPath() { @Override public void execute() throws BuildException { validateAttributes(); - if (fileSystemPath == null) + if (fileSystemPath == null) { // here, resourcePath is not null convertResourcePathToFileSystemPath(resourcePath); - else + } else { convertFileSystemPathToResourcePath(fileSystemPath); + } } protected void convertFileSystemPathToResourcePath(IPath path) { @@ -90,14 +91,16 @@ protected void convertFileSystemPathToResourcePath(IPath path) { resource = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(path); if (resource == null) { String message = Policy.bind("exception.noProjectMatchThePath", fileSystemPath.toOSString()); //$NON-NLS-1$ - if (failOnError) + if (failOnError) { throw new BuildException(message); + } log(message, Project.MSG_ERR); return; } } - if (property != null) + if (property != null) { getProject().setUserProperty(property, resource.getFullPath().toString()); + } if (pathID != null) { Path newPath = new Path(getProject(), resource.getFullPath().toString()); getProject().addReference(pathID, newPath); @@ -120,13 +123,15 @@ protected void convertResourcePathToFileSystemPath(IPath path) { if (resource.getLocation() == null) { // can occur if the first segment is not a project String message = Policy.bind("exception.pathNotValid", path.toString()); //$NON-NLS-1$ - if (failOnError) + if (failOnError) { throw new BuildException(message); + } log(message, Project.MSG_ERR); return; } - if (property != null) + if (property != null) { getProject().setUserProperty(property, resource.getLocation().toOSString()); + } if (pathID != null) { Path newPath = new Path(getProject(), resource.getLocation().toOSString()); getProject().addReference(pathID, newPath); @@ -139,8 +144,9 @@ protected void convertResourcePathToFileSystemPath(IPath path) { * @param value the file corresponding to the path supplied by the user */ public void setFileSystemPath(File value) { - if (resourcePath != null) + if (resourcePath != null) { throw new BuildException(Policy.bind("exception.cantUseBoth")); //$NON-NLS-1$ + } fileSystemPath = IPath.fromOSString(value.toString()); } @@ -150,8 +156,9 @@ public void setFileSystemPath(File value) { * @param value the path */ public void setResourcePath(String value) { - if (fileSystemPath != null) + if (fileSystemPath != null) { throw new BuildException(Policy.bind("exception.cantUseBoth")); //$NON-NLS-1$ + } resourcePath = IPath.fromOSString(value); } @@ -196,15 +203,18 @@ public void setFailOnError(boolean value) { * @exception BuildException thrown if a problem occurs during validation. */ protected void validateAttributes() throws BuildException { - if (property == null && pathID == null) + if (property == null && pathID == null) { throw new BuildException(Policy.bind("exception.propertyAndPathIdNotSpecified")); //$NON-NLS-1$ + } - if (resourcePath != null && (!resourcePath.isValidPath(resourcePath.toString()) || resourcePath.isEmpty())) + if (resourcePath != null && (!resourcePath.isValidPath(resourcePath.toString()) || resourcePath.isEmpty())) { throw new BuildException(Policy.bind("exception.invalidPath", resourcePath.toOSString())); //$NON-NLS-1$ - else if (fileSystemPath != null && !fileSystemPath.isValidPath(fileSystemPath.toOSString())) + } else if (fileSystemPath != null && !fileSystemPath.isValidPath(fileSystemPath.toOSString())) { throw new BuildException(Policy.bind("exception.invalidPath", fileSystemPath.toOSString())); //$NON-NLS-1$ + } - if (resourcePath == null && fileSystemPath == null) + if (resourcePath == null && fileSystemPath == null) { throw new BuildException(Policy.bind("exception.mustHaveOneAttribute")); //$NON-NLS-1$ + } } } diff --git a/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/IncrementalBuild.java b/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/IncrementalBuild.java index 3950e430b98..2d3fc23dde6 100644 --- a/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/IncrementalBuild.java +++ b/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/IncrementalBuild.java @@ -73,16 +73,18 @@ public void execute() throws BuildException { try { IProgressMonitor monitor = null; Hashtable references = getProject().getReferences(); - if (references != null) + if (references != null) { monitor = (IProgressMonitor) references.get(AntCorePlugin.ECLIPSE_PROGRESS_MONITOR); + } if (projectToBuild == null) { ResourcesPlugin.getWorkspace().build(kind, monitor); } else { IProject targetProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectToBuild); - if (builder == null) + if (builder == null) { targetProject.build(kind, monitor); - else + } else { targetProject.build(kind, builder, null, monitor); + } } } catch (CoreException e) { throw new BuildException(e); @@ -108,14 +110,15 @@ public void setBuilder(String value) { * @param value the receiver's kind attribute */ public void setKind(String value) { - if (IncrementalBuild.KIND_FULL.equalsIgnoreCase(value)) + if (IncrementalBuild.KIND_FULL.equalsIgnoreCase(value)) { kind = IncrementalProjectBuilder.FULL_BUILD; - else if (IncrementalBuild.KIND_AUTO.equalsIgnoreCase(value)) + } else if (IncrementalBuild.KIND_AUTO.equalsIgnoreCase(value)) { kind = IncrementalProjectBuilder.AUTO_BUILD; - else if (IncrementalBuild.KIND_CLEAN.equalsIgnoreCase(value)) + } else if (IncrementalBuild.KIND_CLEAN.equalsIgnoreCase(value)) { kind = IncrementalProjectBuilder.CLEAN_BUILD; - else if (IncrementalBuild.KIND_INCREMENTAL.equalsIgnoreCase(value)) + } else if (IncrementalBuild.KIND_INCREMENTAL.equalsIgnoreCase(value)) { kind = IncrementalProjectBuilder.INCREMENTAL_BUILD; + } } /** diff --git a/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/Policy.java b/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/Policy.java index 5b7acdb62b1..711df2a77fa 100644 --- a/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/Policy.java +++ b/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/Policy.java @@ -31,8 +31,9 @@ public static String bind(String id) { } public static IProgressMonitor monitorFor(IProgressMonitor monitor) { - if (monitor == null) + if (monitor == null) { return new NullProgressMonitor(); + } return monitor; } @@ -57,8 +58,9 @@ public static String bind(String id, String binding1, String binding2) { * substitution locations with the given string values. */ public static String bind(String id, String[] bindings) { - if (id == null) + if (id == null) { return "No message available";//$NON-NLS-1$ + } String message = null; try { message = bundle.getString(id); @@ -67,8 +69,9 @@ public static String bind(String id, String[] bindings) { // the id we were looking for. In most cases this is semi-informative so is not too bad. return "Missing message: " + id + " in: " + bundleName;//$NON-NLS-1$ //$NON-NLS-2$ } - if (bindings == null) + if (bindings == null) { return message; + } return MessageFormat.format(message, (Object[]) bindings); } } diff --git a/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/RefreshLocalTask.java b/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/RefreshLocalTask.java index 165ee124748..3dbc5b112ab 100644 --- a/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/RefreshLocalTask.java +++ b/resources/bundles/org.eclipse.core.resources/src_ant/org/eclipse/core/resources/ant/RefreshLocalTask.java @@ -75,13 +75,15 @@ public RefreshLocalTask() { */ @Override public void execute() throws BuildException { - if (resource == null) + if (resource == null) { throw new BuildException(Policy.bind("exception.resourceNotSpecified")); //$NON-NLS-1$ + } try { IProgressMonitor monitor = null; Hashtable references = getProject().getReferences(); - if (references != null) + if (references != null) { monitor = (IProgressMonitor) references.get(AntCorePlugin.ECLIPSE_PROGRESS_MONITOR); + } resource.refreshLocal(depth, monitor); } catch (CoreException e) { throw new BuildException(e); @@ -96,12 +98,13 @@ public void execute() throws BuildException { * @param value the depth to refresh to */ public void setDepth(String value) { - if (DEPTH_ZERO.equalsIgnoreCase(value)) + if (DEPTH_ZERO.equalsIgnoreCase(value)) { depth = IResource.DEPTH_ZERO; - else if (DEPTH_ONE.equalsIgnoreCase(value)) + } else if (DEPTH_ONE.equalsIgnoreCase(value)) { depth = IResource.DEPTH_ONE; - else if (DEPTH_INFINITE.equalsIgnoreCase(value)) + } else if (DEPTH_INFINITE.equalsIgnoreCase(value)) { depth = IResource.DEPTH_INFINITE; + } } /** @@ -114,12 +117,13 @@ public void setResource(String value) { resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path); if (resource == null) { // if it does not exist we guess it is a folder or a project - if (path.segmentCount() > 1) + if (path.segmentCount() > 1) { resource = ResourcesPlugin.getWorkspace().getRoot().getFolder(path); - else { + } else { resource = ResourcesPlugin.getWorkspace().getRoot().getProject(value); - if (!resource.exists()) + if (!resource.exists()) { log(Policy.bind("warning.projectDoesNotExist", value), Project.MSG_WARN); //$NON-NLS-1$ + } } } }