View | Details | Raw Unified | Return to bug 349390 | Differences between
and this patch

Collapse All | Expand All

(-)ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.java (+2 lines)
Lines 257-265 Link Here
257
	public static String QuickAssistProcessor_unwrap_methodinvocation;
257
	public static String QuickAssistProcessor_unwrap_methodinvocation;
258
	public static String QuickAssistProcessor_unwrap_synchronizedstatement;
258
	public static String QuickAssistProcessor_unwrap_synchronizedstatement;
259
	public static String QuickAssistProcessor_splitdeclaration_description;
259
	public static String QuickAssistProcessor_splitdeclaration_description;
260
	public static String QuickAssistProcessor_surroundresourcewithtry_description;
260
	public static String QuickAssistProcessor_joindeclaration_description;
261
	public static String QuickAssistProcessor_joindeclaration_description;
261
	public static String QuickAssistProcessor_addfinallyblock_description;
262
	public static String QuickAssistProcessor_addfinallyblock_description;
262
	public static String QuickAssistProcessor_addelseblock_description;
263
	public static String QuickAssistProcessor_addelseblock_description;
264
	public static String QuickAssistProcessor_addresourcetotry_description;
263
	public static String QuickAssistProcessor_replacethenwithblock_description;
265
	public static String QuickAssistProcessor_replacethenwithblock_description;
264
	public static String QuickAssistProcessor_replaceelsewithblock_description;
266
	public static String QuickAssistProcessor_replaceelsewithblock_description;
265
	public static String QuickAssistProcessor_replacethenelsewithblock_description;
267
	public static String QuickAssistProcessor_replacethenelsewithblock_description;
(-)ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.properties (+2 lines)
Lines 311-316 Link Here
311
QuickAssistProcessor_unwrap_synchronizedstatement=Remove surrounding 'synchronized' statement
311
QuickAssistProcessor_unwrap_synchronizedstatement=Remove surrounding 'synchronized' statement
312
312
313
QuickAssistProcessor_splitdeclaration_description=Split variable declaration
313
QuickAssistProcessor_splitdeclaration_description=Split variable declaration
314
QuickAssistProcessor_surroundresourcewithtry_description=Surround resource ''{0}'' with try-with-resources
314
QuickAssistProcessor_exceptiontothrows_description=Replace exception with throws
315
QuickAssistProcessor_exceptiontothrows_description=Replace exception with throws
315
QuickAssistProcessor_extract_to_local_all_description=Extract to local variable (replace all occurrences)
316
QuickAssistProcessor_extract_to_local_all_description=Extract to local variable (replace all occurrences)
316
QuickAssistProcessor_extract_to_local_description=Extract to local variable
317
QuickAssistProcessor_extract_to_local_description=Extract to local variable
Lines 319-324 Link Here
319
QuickAssistProcessor_joindeclaration_description=Join variable declaration
320
QuickAssistProcessor_joindeclaration_description=Join variable declaration
320
QuickAssistProcessor_addfinallyblock_description=Add finally block
321
QuickAssistProcessor_addfinallyblock_description=Add finally block
321
QuickAssistProcessor_addelseblock_description=Add else block
322
QuickAssistProcessor_addelseblock_description=Add else block
323
QuickAssistProcessor_addresourcetotry_description=Add resource ''{0}'' to following try
322
324
323
QuickAssistProcessor_replacethenwithblock_description=Change 'if' statement to block
325
QuickAssistProcessor_replacethenwithblock_description=Change 'if' statement to block
324
QuickAssistProcessor_replaceelsewithblock_description=Change 'else' statement to block
326
QuickAssistProcessor_replaceelsewithblock_description=Change 'else' statement to block
(-)ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java (+256 lines)
Lines 55-60 Link Here
55
import org.eclipse.jdt.core.compiler.IProblem;
55
import org.eclipse.jdt.core.compiler.IProblem;
56
import org.eclipse.jdt.core.dom.AST;
56
import org.eclipse.jdt.core.dom.AST;
57
import org.eclipse.jdt.core.dom.ASTNode;
57
import org.eclipse.jdt.core.dom.ASTNode;
58
import org.eclipse.jdt.core.dom.ASTVisitor;
58
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
59
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
59
import org.eclipse.jdt.core.dom.ArrayCreation;
60
import org.eclipse.jdt.core.dom.ArrayCreation;
60
import org.eclipse.jdt.core.dom.ArrayInitializer;
61
import org.eclipse.jdt.core.dom.ArrayInitializer;
Lines 87-92 Link Here
87
import org.eclipse.jdt.core.dom.Name;
88
import org.eclipse.jdt.core.dom.Name;
88
import org.eclipse.jdt.core.dom.ParenthesizedExpression;
89
import org.eclipse.jdt.core.dom.ParenthesizedExpression;
89
import org.eclipse.jdt.core.dom.PrimitiveType;
90
import org.eclipse.jdt.core.dom.PrimitiveType;
91
import org.eclipse.jdt.core.dom.ReturnStatement;
90
import org.eclipse.jdt.core.dom.SimpleName;
92
import org.eclipse.jdt.core.dom.SimpleName;
91
import org.eclipse.jdt.core.dom.SimpleType;
93
import org.eclipse.jdt.core.dom.SimpleType;
92
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
94
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
Lines 116-121 Link Here
116
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
118
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
117
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
119
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
118
import org.eclipse.jdt.internal.corext.dom.Bindings;
120
import org.eclipse.jdt.internal.corext.dom.Bindings;
121
import org.eclipse.jdt.internal.corext.dom.GenericVisitor;
119
import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder;
122
import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder;
120
import org.eclipse.jdt.internal.corext.dom.Selection;
123
import org.eclipse.jdt.internal.corext.dom.Selection;
121
import org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer;
124
import org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer;
Lines 193-198 Link Here
193
				|| getPickoutTypeFromMulticatchProposals(context, coveringNode, coveredNodes, null)
196
				|| getPickoutTypeFromMulticatchProposals(context, coveringNode, coveredNodes, null)
194
				|| getConvertToMultiCatchProposals(context, coveringNode, null)
197
				|| getConvertToMultiCatchProposals(context, coveringNode, null)
195
				|| getUnrollMultiCatchProposals(context, coveringNode, null)
198
				|| getUnrollMultiCatchProposals(context, coveringNode, null)
199
				|| getTryWithResourcesProposals(context, coveringNode, null)
196
				|| getRenameLocalProposals(context, coveringNode, null, null)
200
				|| getRenameLocalProposals(context, coveringNode, null, null)
197
				|| getRenameRefactoringProposal(context, coveringNode, null, null)
201
				|| getRenameRefactoringProposal(context, coveringNode, null, null)
198
				|| getAssignToVariableProposals(context, coveringNode, null, null)
202
				|| getAssignToVariableProposals(context, coveringNode, null, null)
Lines 240-245 Link Here
240
				getPickoutTypeFromMulticatchProposals(context, coveringNode, coveredNodes, resultingCollections);
244
				getPickoutTypeFromMulticatchProposals(context, coveringNode, coveredNodes, resultingCollections);
241
				getConvertToMultiCatchProposals(context, coveringNode, resultingCollections);
245
				getConvertToMultiCatchProposals(context, coveringNode, resultingCollections);
242
				getUnrollMultiCatchProposals(context, coveringNode, resultingCollections);
246
				getUnrollMultiCatchProposals(context, coveringNode, resultingCollections);
247
				getTryWithResourcesProposals(context, coveringNode, resultingCollections);
243
				getUnWrapProposals(context, coveringNode, resultingCollections);
248
				getUnWrapProposals(context, coveringNode, resultingCollections);
244
				getJoinVariableProposals(context, coveringNode, resultingCollections);
249
				getJoinVariableProposals(context, coveringNode, resultingCollections);
245
				getSplitVariableProposals(context, coveringNode, resultingCollections);
250
				getSplitVariableProposals(context, coveringNode, resultingCollections);
Lines 1554-1559 Link Here
1554
		}
1559
		}
1555
	}
1560
	}
1556
1561
1562
	private static boolean getTryWithResourcesProposals(IInvocationContext context, ASTNode covering, Collection<ICommandAccess> resultingCollections) {
1563
		if (!JavaModelUtil.is17OrHigher(context.getCompilationUnit().getJavaProject()))
1564
			return false;
1565
1566
		//TODO: should the user be able to select more than one resource and enclose in one twr ? This should be doable
1567
		ASTNode node= covering;
1568
		while (!(node instanceof Statement) && node != null) {
1569
			node= node.getParent();
1570
		}
1571
1572
		if (!(node instanceof VariableDeclarationStatement))
1573
			return false;
1574
1575
		VariableDeclarationStatement variableDeclarationStatement= (VariableDeclarationStatement) node;
1576
		Type type= variableDeclarationStatement.getType();
1577
		ITypeBinding typeBinding= type.resolveBinding();
1578
		if (typeBinding == null) {
1579
			return false;
1580
		}
1581
		String autocloseable= "java.lang.AutoCloseable"; //$NON-NLS-1$
1582
		ITypeBinding typeInHierarchy= Bindings.findTypeInHierarchy(typeBinding, autocloseable);
1583
		if (typeInHierarchy == null)
1584
			return false;
1585
1586
		MethodDeclaration methodDeclaration= ASTResolving.findParentMethodDeclaration(variableDeclarationStatement);
1587
		List<VariableDeclarationFragment> fragments= variableDeclarationStatement.fragments();
1588
		VariableDeclarationFragment variableDeclarationFragment= fragments.get(0); //TODO: More than one fragment ?
1589
1590
		VariableReferenceAnalyzer analyzer= new VariableReferenceAnalyzer(variableDeclarationFragment.resolveBinding(), covering);
1591
		methodDeclaration.accept(analyzer);
1592
		if (!analyzer.canProduceQuickAssist())
1593
			return false;
1594
1595
		if (resultingCollections == null) {
1596
			return true;
1597
		}
1598
1599
		TryStatement tryStatement= analyzer.getTryStatement();
1600
		List<MethodInvocation> closeInvocations= analyzer.getCloseInvocations();
1601
		if (tryStatement != null) {
1602
			AST ast= node.getAST();
1603
			ASTRewrite rewrite= ASTRewrite.create(ast);
1604
			ListRewrite listRewrite= rewrite.getListRewrite(tryStatement, TryStatement.RESOURCES_PROPERTY);
1605
1606
			VariableDeclarationExpression newVariableDeclarationExpression= ast.newVariableDeclarationExpression((VariableDeclarationFragment) rewrite.createCopyTarget(variableDeclarationFragment));
1607
			newVariableDeclarationExpression.setType((Type) rewrite.createCopyTarget(variableDeclarationStatement.getType()));
1608
1609
			listRewrite.insertLast(newVariableDeclarationExpression, null);
1610
			rewrite.remove(variableDeclarationStatement, null);
1611
1612
			if (closeInvocations != null)
1613
				removeCloseInvocations(closeInvocations, rewrite);
1614
1615
			Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
1616
			String label= Messages.format(CorrectionMessages.QuickAssistProcessor_addresourcetotry_description, variableDeclarationFragment.getName().getIdentifier());
1617
			ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 6, image);
1618
			resultingCollections.add(proposal);
1619
		} else {
1620
			AST ast= node.getAST();
1621
			ASTRewrite rewrite= ASTRewrite.create(ast);
1622
1623
			TryStatement newTryStatement= ast.newTryStatement();
1624
			List<ASTNode> nodes= analyzer.getReferences();
1625
1626
			ASTNode start= ASTResolving.findParentStatement(nodes.get(0));
1627
			ASTNode end= ASTResolving.findParentStatement(nodes.get(nodes.size() - 1));
1628
1629
			ListRewrite tryResourcesListRewrite= rewrite.getListRewrite(newTryStatement, TryStatement.RESOURCES_PROPERTY);
1630
			VariableDeclarationExpression newVariableDeclarationExpression= ast.newVariableDeclarationExpression((VariableDeclarationFragment) rewrite.createCopyTarget(variableDeclarationFragment));
1631
			newVariableDeclarationExpression.setType((Type) rewrite.createCopyTarget(variableDeclarationStatement.getType()));
1632
			tryResourcesListRewrite.insertLast(newVariableDeclarationExpression, null);
1633
1634
			ListRewrite tryStatementsListRewrite= rewrite.getListRewrite(newTryStatement.getBody(), Block.STATEMENTS_PROPERTY);
1635
			MethodDeclaration parentMethodDeclaration= ASTResolving.findParentMethodDeclaration(node);
1636
			ArrayList<ASTNode> coveredNodes= getCoveredNodes(start.getStartPosition(), end.getStartPosition() + end.getLength(), parentMethodDeclaration);
1637
1638
			if (closeInvocations != null)
1639
				removeCloseInvocations(closeInvocations, rewrite);
1640
1641
			if (coveredNodes.size() >= 1) {
1642
				ListRewrite bodyStatementsListRewrite= rewrite.getListRewrite(coveredNodes.get(1).getParent(), (ChildListPropertyDescriptor) coveredNodes.get(1).getLocationInParent());
1643
				ASTNode toMove= bodyStatementsListRewrite.createMoveTarget(coveredNodes.get(1), coveredNodes.get(coveredNodes.size() - 1), newTryStatement, null);
1644
				tryStatementsListRewrite.insertLast(toMove, null);
1645
			}
1646
1647
			rewrite.remove(variableDeclarationStatement, null);
1648
1649
			Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
1650
			String label= Messages.format(CorrectionMessages.QuickAssistProcessor_surroundresourcewithtry_description, variableDeclarationFragment.getName().getIdentifier());
1651
			ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 6, image);
1652
			resultingCollections.add(proposal);
1653
		}
1654
		return true;
1655
	}
1656
1657
	private static void removeCloseInvocations(List<MethodInvocation> closeInvocations, ASTRewrite rewrite) {
1658
		for (Iterator<MethodInvocation> iterator= closeInvocations.iterator(); iterator.hasNext();) {
1659
			MethodInvocation closeInvocation= iterator.next();
1660
			IfStatement parentif= null;
1661
			Statement parentStatement= ASTResolving.findParentStatement(closeInvocation);
1662
1663
			ASTNode parent= parentStatement.getParent();
1664
			if (parent instanceof Block) {
1665
				parent= parent.getParent();
1666
			}
1667
			if (parent instanceof IfStatement) {
1668
				parentif= (IfStatement) parent;
1669
			}
1670
1671
			if (parentif != null) {
1672
				Statement thenStatement= parentif.getThenStatement();
1673
				Statement toRemove= parentif;
1674
				if (thenStatement instanceof Block) {
1675
					Block block= (Block) thenStatement;
1676
					if (block.statements().size() > 1) {
1677
						toRemove= parentStatement;
1678
					}
1679
				}
1680
				Statement elseStatement= parentif.getElseStatement();
1681
				if (elseStatement != null && toRemove == parentif) {
1682
					ASTNode parentBlock= ASTResolving.findAncestor(parentif, ASTNode.BLOCK);
1683
					if (parentBlock instanceof Block) {
1684
						Block block2= (Block) parentBlock;
1685
						ASTNode copyTarget;
1686
						if (elseStatement instanceof Block) {
1687
							Block elseBlock= (Block) elseStatement;
1688
							List<Statement> statements= elseBlock.statements();
1689
							ASTNode[] array= statements.toArray(new ASTNode[statements.size()]);
1690
							copyTarget= rewrite.createGroupNode(array);
1691
						} else {
1692
							copyTarget= rewrite.createCopyTarget(elseStatement);
1693
						}
1694
						ListRewrite listRewrite= rewrite.getListRewrite(block2, Block.STATEMENTS_PROPERTY);
1695
						listRewrite.insertAfter(copyTarget, parentif, null);
1696
					}
1697
				}
1698
				rewrite.remove(toRemove, null);
1699
			} else {
1700
				rewrite.remove(parentStatement, null);
1701
			}
1702
		}
1703
	}
1704
1705
	private static ArrayList<ASTNode> getCoveredNodes(final int selectionBegin, final int selectionEnd, ASTNode coveringNode) {
1706
		final ArrayList<ASTNode> coveredNodes= new ArrayList<ASTNode>();
1707
		coveringNode.accept(new GenericVisitor() {
1708
			@Override
1709
			protected boolean visitNode(ASTNode node) {
1710
				int nodeStart= node.getStartPosition();
1711
				int nodeEnd= nodeStart + node.getLength();
1712
				// if node does not intersects with selection, don't visit children
1713
				if (nodeEnd < selectionBegin || selectionEnd < nodeStart) {
1714
					return false;
1715
				}
1716
				// if node is covered, we don't need to visit children
1717
				if (isCovered(node)) {
1718
					ASTNode parent= node.getParent();
1719
					if (parent == null || !isCovered(parent)) {
1720
						coveredNodes.add(node);
1721
						return false;
1722
					}
1723
				}
1724
				// if node only partly intersects with selection, we try to find fully covered children
1725
				return true;
1726
			}
1727
1728
			private boolean isCovered(ASTNode node) {
1729
				int begin= node.getStartPosition();
1730
				int end= begin + node.getLength();
1731
				return (begin >= selectionBegin && end <= selectionEnd) || (begin <= selectionBegin && end <= selectionEnd) || (begin >= selectionBegin && end >= selectionEnd);
1732
			}
1733
		});
1734
		return coveredNodes;
1735
	}
1736
1737
	static class VariableReferenceAnalyzer extends ASTVisitor {
1738
		private List<ASTNode> fReferences= null;
1739
		private List<MethodInvocation> fCloseInvocations= null;
1740
		private TryStatement fTryStatement= null;
1741
		private boolean fIsEnclosedInOneTryStatement= true;
1742
		private IVariableBinding fBinding;
1743
		private boolean fCanProduceQuickAssist= true;
1744
1745
		private final ASTNode fCoveringNode;
1746
1747
		public VariableReferenceAnalyzer(IVariableBinding binding, ASTNode coveringNode) {
1748
			fBinding= binding;
1749
			fCoveringNode= coveringNode;
1750
		}
1751
1752
		public List<ASTNode> getReferences() {
1753
			return fReferences;
1754
		}
1755
1756
		public List<MethodInvocation> getCloseInvocations() {
1757
			return fCloseInvocations;
1758
		}
1759
1760
		public TryStatement getTryStatement() {
1761
			return fTryStatement;
1762
		}
1763
		
1764
		public boolean canProduceQuickAssist() {
1765
			return fCanProduceQuickAssist;
1766
		}
1767
1768
		@Override
1769
		public boolean visit(SimpleName node) {
1770
			if (fReferences == null) {
1771
				fReferences= new ArrayList<ASTNode>();
1772
			}
1773
			if (Bindings.equals(fBinding, node.resolveBinding())) {
1774
				fReferences.add(node);
1775
1776
				StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
1777
				if (locationInParent instanceof ChildListPropertyDescriptor && locationInParent != InfixExpression.EXTENDED_OPERANDS_PROPERTY) {
1778
					// e.g. argument lists of MethodInvocation, ClassInstanceCreation ...
1779
					fCanProduceQuickAssist= false;
1780
				}
1781
1782
				if (locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == Assignment.LEFT_HAND_SIDE_PROPERTY) {
1783
					fCanProduceQuickAssist= false;
1784
				}
1785
				
1786
				ASTNode tryStatement= ASTResolving.findAncestor(node, ASTNode.TRY_STATEMENT);
1787
				if (node != fCoveringNode && tryStatement != null) {
1788
					if (fTryStatement == null && fIsEnclosedInOneTryStatement) {
1789
						fTryStatement= (TryStatement) tryStatement;
1790
					} else if (fTryStatement != tryStatement) {
1791
						fIsEnclosedInOneTryStatement= false;
1792
						fTryStatement= null;
1793
					}
1794
				}
1795
1796
				ASTNode parent= node.getParent();
1797
				if (parent instanceof MethodInvocation && node.getLocationInParent() == MethodInvocation.EXPRESSION_PROPERTY) {
1798
					MethodInvocation methodInvocation= (MethodInvocation) parent;
1799
					IMethodBinding methodBinding= methodInvocation.resolveMethodBinding();
1800
					if (methodBinding != null) {
1801
						if ("close".equals(methodBinding.getName())) { //$NON-NLS-1$
1802
							if (fCloseInvocations == null)
1803
								fCloseInvocations= new ArrayList<MethodInvocation>();
1804
							fCloseInvocations.add(methodInvocation);
1805
						}
1806
					}
1807
				}
1808
			}
1809
			return false;
1810
		}
1811
	}
1812
1557
	private static boolean getRenameLocalProposals(IInvocationContext context, ASTNode node, IProblemLocation[] locations, Collection<ICommandAccess> resultingCollections) {
1813
	private static boolean getRenameLocalProposals(IInvocationContext context, ASTNode node, IProblemLocation[] locations, Collection<ICommandAccess> resultingCollections) {
1558
		if (!(node instanceof SimpleName)) {
1814
		if (!(node instanceof SimpleName)) {
1559
			return false;
1815
			return false;
(-)ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest17.java (+89 lines)
Lines 928-931 Link Here
928
		assertProposalDoesNotExist(proposals, REMOVE_SURROUNDING_TRY_BLOCK);
928
		assertProposalDoesNotExist(proposals, REMOVE_SURROUNDING_TRY_BLOCK);
929
	}
929
	}
930
930
931
	public void testUseTryWithResources1() throws Exception {
932
		IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
933
		StringBuffer buf= new StringBuffer();
934
		buf.append("package test1;\n");
935
		buf.append("import java.io.FileReader;\n");
936
		buf.append("public class E {\n");
937
		buf.append("    void foo() throws Exception {\n");
938
		buf.append("        FileReader reader = new FileReader(\"file\");\n");
939
		buf.append("        try {\n");
940
		buf.append("            int ch;\n");
941
		buf.append("            while ((ch = reader.read()) != -1) {\n");
942
		buf.append("                System.out.println(ch);\n");
943
		buf.append("            }\n");
944
		buf.append("        } finally {\n");
945
		buf.append("            reader.close();\n");
946
		buf.append("        }\n");
947
		buf.append("    }\n");
948
		buf.append("}\n");
949
950
		ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
951
952
		int offset= buf.toString().indexOf("reader = ");
953
		AssistContext context= getCorrectionContext(cu, offset, 0);
954
		assertNoErrors(context);
955
		List proposals= collectAssists(context, false);
956
957
		assertCorrectLabels(proposals);
958
959
		buf= new StringBuffer();
960
		buf.append("package test1;\n");
961
		buf.append("import java.io.FileReader;\n");
962
		buf.append("public class E {\n");
963
		buf.append("    void foo() throws Exception {\n");
964
		buf.append("        try (FileReader reader = new FileReader(\"file\")) {\n");
965
		buf.append("            int ch;\n");
966
		buf.append("            while ((ch = reader.read()) != -1) {\n");
967
		buf.append("                System.out.println(ch);\n");
968
		buf.append("            }\n");
969
		buf.append("        } finally {\n");
970
		buf.append("        }\n");
971
		buf.append("    }\n");
972
		buf.append("}\n");
973
		String expected1= buf.toString();
974
975
		assertExpectedExistInProposals(proposals, new String[] { expected1 });
976
	}
977
978
	public void testUseTryWithResources2() throws Exception {
979
		IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
980
		StringBuffer buf= new StringBuffer();
981
		buf.append("package test1;\n");
982
		buf.append("import java.io.FileReader;\n");
983
		buf.append("public class E {\n");
984
		buf.append("    void foo() throws Exception {\n");
985
		buf.append("        FileReader reader = new FileReader(\"file\");\n");
986
		buf.append("        int ch;\n");
987
		buf.append("        while ((ch = reader.read()) != -1) {\n");
988
		buf.append("            System.out.println(ch);\n");
989
		buf.append("        }\n");
990
		buf.append("        if (reader != null) {\n");
991
		buf.append("            reader.close();\n");
992
		buf.append("        }\n");
993
		buf.append("    }\n");
994
		buf.append("}\n");
995
996
		ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
997
998
		int offset= buf.toString().indexOf("reader = ");
999
		AssistContext context= getCorrectionContext(cu, offset, 0);
1000
		assertNoErrors(context);
1001
		List proposals= collectAssists(context, false);
1002
1003
		assertCorrectLabels(proposals);
1004
1005
		buf= new StringBuffer();
1006
		buf.append("package test1;\n");
1007
		buf.append("import java.io.FileReader;\n");
1008
		buf.append("public class E {\n");
1009
		buf.append("    void foo() throws Exception {\n");
1010
		buf.append("        try (FileReader reader = new FileReader(\"file\")){int ch;\n");
1011
		buf.append("        while ((ch = reader.read()) != -1) {\n");
1012
		buf.append("            System.out.println(ch);\n");
1013
		buf.append("        }} \n");
1014
		buf.append("    }\n");
1015
		buf.append("}\n");
1016
		String expected1= buf.toString();
1017
1018
		assertExpectedExistInProposals(proposals, new String[] { expected1 });
1019
	}
931
}
1020
}

Return to bug 349390