if (RESOURCE_INIT_PATTERN.matches(initializeResource, m) &&
CLEAR_SAVED_EXCEPTION_PATTERN.matches(clearCaughtException, m) &&
_tryPattern.matches(node, m)) {
final IdentifierExpression resource = first(m.<IdentifierExpression>get("resource"));
final ResolveResult resourceResult = _resolver.apply(resource);
if (resourceResult == null || resourceResult.getType() == null) {
return null;
}
final BlockStatement tryContent = first(m.<BlockStatement>get("tryContent"));
final Expression resourceInitializer = first(m.<Expression>get("resourceInitializer"));
final IdentifierExpression caughtException = first(m.<IdentifierExpression>get("caughtException"));
final IdentifierExpression caughtOnClose = first(m.<IdentifierExpression>get("caughtOnClose"));
final CatchClause caughtParent = first(caughtException.getAncestors(CatchClause.class));
final CatchClause caughtOnCloseParent = first(caughtOnClose.getAncestors(CatchClause.class));
if (caughtParent == null ||
caughtOnCloseParent == null ||
!Pattern.matchString(caughtException.getIdentifier(), caughtParent.getVariableName()) ||
!Pattern.matchString(caughtOnClose.getIdentifier(), caughtOnCloseParent.getVariableName())) {
return null;
}
//
// Find the declaration of the resource variable.
//
final VariableDeclarationStatement resourceDeclaration = findVariableDeclaration(
node,
resource.getIdentifier()
);
if (resourceDeclaration == null || !(resourceDeclaration.getParent() instanceof BlockStatement)) {
return null;
}
final BlockStatement outerTemp = new BlockStatement();
final BlockStatement temp = new BlockStatement();
initializeResource.remove();
clearCaughtException.remove();
node.replaceWith(outerTemp);
temp.add(initializeResource);
temp.add(clearCaughtException);
temp.add(node);
outerTemp.add(temp);
//
// Now verify that we can move the variable declaration into the 'try'.
//
final Statement declarationPoint = canMoveVariableDeclarationIntoStatement(
context,
resourceDeclaration,
node
);
node.remove();
outerTemp.replaceWith(node);
if (declarationPoint != outerTemp) {
//
// We cannot move the declaration into the 'try'; abort.
//
initializeResource.remove();
clearCaughtException.remove();
parent.insertChildBefore(node, initializeResource, BlockStatement.STATEMENT_ROLE);
parent.insertChildBefore(node, clearCaughtException, BlockStatement.STATEMENT_ROLE);
return null;
}
tryContent.remove();
resource.remove();
resourceInitializer.remove();
final VariableDeclarationStatement newResourceDeclaration = new VariableDeclarationStatement(
_astBuilder.convertType(resourceResult.getType()),
resource.getIdentifier(),
resourceInitializer
);
final Statement firstStatement = firstOrDefault(tryContent.getStatements());