Search in sources :

Example 81 with CoreException

use of org.eclipse.core.runtime.CoreException in project che by eclipse.

the class ConvertAnonymousToNestedRefactoring method createNewConstructor.

private MethodDeclaration createNewConstructor(CompilationUnitRewrite rewrite, IVariableBinding[] bindings, String[] fieldNames) throws JavaModelException {
    ClassInstanceCreation instanceCreation = (ClassInstanceCreation) fAnonymousInnerClassNode.getParent();
    if (instanceCreation.arguments().isEmpty() && bindings.length == 0)
        return null;
    IJavaProject project = fCu.getJavaProject();
    AST ast = rewrite.getAST();
    ImportRewrite importRewrite = rewrite.getImportRewrite();
    ASTRewrite astRewrite = rewrite.getASTRewrite();
    MethodDeclaration newConstructor = ast.newMethodDeclaration();
    newConstructor.setConstructor(true);
    newConstructor.setJavadoc(null);
    newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, fVisibility));
    newConstructor.setName(ast.newSimpleName(fClassName));
    addLinkedPosition(KEY_TYPE_NAME, newConstructor.getName(), astRewrite, false);
    newConstructor.setBody(ast.newBlock());
    List<Statement> newStatements = newConstructor.getBody().statements();
    List<SingleVariableDeclaration> newParameters = newConstructor.parameters();
    List<String> newParameterNames = new ArrayList<String>();
    // add parameters for elements passed with the instance creation
    if (!instanceCreation.arguments().isEmpty()) {
        IMethodBinding constructorBinding = getSuperConstructorBinding();
        if (constructorBinding != null) {
            SuperConstructorInvocation superConstructorInvocation = ast.newSuperConstructorInvocation();
            ITypeBinding[] parameterTypes = constructorBinding.getParameterTypes();
            String[][] parameterNames = StubUtility.suggestArgumentNamesWithProposals(project, constructorBinding);
            for (int i = 0; i < parameterNames.length; i++) {
                String[] nameProposals = parameterNames[i];
                String paramName = nameProposals[0];
                SingleVariableDeclaration param = newParameterDeclaration(ast, importRewrite, paramName, parameterTypes[i]);
                newParameters.add(param);
                newParameterNames.add(paramName);
                SimpleName newSIArgument = ast.newSimpleName(paramName);
                superConstructorInvocation.arguments().add(newSIArgument);
                if (fLinkedProposalModel != null) {
                    LinkedProposalPositionGroup positionGroup = fLinkedProposalModel.getPositionGroup(KEY_PARAM_NAME_CONST + String.valueOf(i), true);
                    positionGroup.addPosition(astRewrite.track(param.getName()), false);
                    positionGroup.addPosition(astRewrite.track(newSIArgument), false);
                    for (int k = 0; k < nameProposals.length; k++) {
                        positionGroup.addProposal(nameProposals[k], null, nameProposals.length - k);
                    }
                }
            }
            newStatements.add(superConstructorInvocation);
        }
    }
    // add parameters for all outer variables used
    boolean useThisAccess = useThisForFieldAccess();
    for (int i = 0; i < bindings.length; i++) {
        String baseName = StubUtility.getBaseName(bindings[i], project);
        String[] paramNameProposals = StubUtility.getVariableNameSuggestions(NamingConventions.VK_PARAMETER, project, baseName, 0, newParameterNames, true);
        String paramName = paramNameProposals[0];
        SingleVariableDeclaration param = newParameterDeclaration(ast, importRewrite, paramName, bindings[i].getType());
        newParameters.add(param);
        newParameterNames.add(paramName);
        String fieldName = fieldNames[i];
        SimpleName fieldNameNode = ast.newSimpleName(fieldName);
        SimpleName paramNameNode = ast.newSimpleName(paramName);
        newStatements.add(newFieldAssignment(ast, fieldNameNode, paramNameNode, useThisAccess || newParameterNames.contains(fieldName)));
        if (fLinkedProposalModel != null) {
            LinkedProposalPositionGroup positionGroup = fLinkedProposalModel.getPositionGroup(KEY_PARAM_NAME_EXT + String.valueOf(i), true);
            positionGroup.addPosition(astRewrite.track(param.getName()), false);
            positionGroup.addPosition(astRewrite.track(paramNameNode), false);
            for (int k = 0; k < paramNameProposals.length; k++) {
                positionGroup.addProposal(paramNameProposals[k], null, paramNameProposals.length - k);
            }
            fLinkedProposalModel.getPositionGroup(KEY_FIELD_NAME_EXT + i, true).addPosition(astRewrite.track(fieldNameNode), false);
        }
    }
    addExceptionsToNewConstructor(newConstructor, importRewrite);
    if (doAddComments()) {
        try {
            String[] allParamNames = newParameterNames.toArray(new String[newParameterNames.size()]);
            String string = CodeGeneration.getMethodComment(fCu, fClassName, fClassName, allParamNames, new String[0], null, new String[0], null, StubUtility.getLineDelimiterUsed(fCu));
            if (string != null) {
                Javadoc javadoc = (Javadoc) astRewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
                newConstructor.setJavadoc(javadoc);
            }
        } catch (CoreException exception) {
            throw new JavaModelException(exception);
        }
    }
    return newConstructor;
}
Also used : IMethodBinding(org.eclipse.jdt.core.dom.IMethodBinding) JavaModelException(org.eclipse.jdt.core.JavaModelException) ImportRewrite(org.eclipse.jdt.core.dom.rewrite.ImportRewrite) SimpleName(org.eclipse.jdt.core.dom.SimpleName) ArrayList(java.util.ArrayList) Javadoc(org.eclipse.jdt.core.dom.Javadoc) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) ASTRewrite(org.eclipse.jdt.core.dom.rewrite.ASTRewrite) ClassInstanceCreation(org.eclipse.jdt.core.dom.ClassInstanceCreation) AST(org.eclipse.jdt.core.dom.AST) MethodDeclaration(org.eclipse.jdt.core.dom.MethodDeclaration) Statement(org.eclipse.jdt.core.dom.Statement) SingleVariableDeclaration(org.eclipse.jdt.core.dom.SingleVariableDeclaration) IJavaProject(org.eclipse.jdt.core.IJavaProject) CoreException(org.eclipse.core.runtime.CoreException) SuperConstructorInvocation(org.eclipse.jdt.core.dom.SuperConstructorInvocation) LinkedProposalPositionGroup(org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup)

Example 82 with CoreException

use of org.eclipse.core.runtime.CoreException in project che by eclipse.

the class DeletePackageFragmentRootChange method getFileLength.

private static int getFileLength(IFile file) throws CoreException {
    // Cannot use file buffers here, since they are not yet in sync at this point.
    InputStream contents = file.getContents();
    InputStreamReader reader;
    try {
        reader = new InputStreamReader(contents, file.getCharset());
    } catch (UnsupportedEncodingException e) {
        JavaPlugin.log(e);
        reader = new InputStreamReader(contents);
    }
    try {
        return (int) reader.skip(Integer.MAX_VALUE);
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, Corext.getPluginId(), e.getMessage(), e));
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
        }
    }
}
Also used : IStatus(org.eclipse.core.runtime.IStatus) Status(org.eclipse.core.runtime.Status) InputStreamReader(java.io.InputStreamReader) CoreException(org.eclipse.core.runtime.CoreException) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException)

Example 83 with CoreException

use of org.eclipse.core.runtime.CoreException in project che by eclipse.

the class RefactoringSearchEngine method findAffectedCompilationUnits.

//TODO: throw CoreException
public static ICompilationUnit[] findAffectedCompilationUnits(SearchPattern pattern, IJavaSearchScope scope, final IProgressMonitor pm, RefactoringStatus status, final boolean tolerateInAccurateMatches) throws JavaModelException {
    boolean hasNonCuMatches = false;
    class ResourceSearchRequestor extends SearchRequestor {

        boolean hasPotentialMatches = false;

        Set<IResource> resources = new HashSet<IResource>(5);

        private IResource fLastResource;

        @Override
        public void acceptSearchMatch(SearchMatch match) {
            if (!tolerateInAccurateMatches && match.getAccuracy() == SearchMatch.A_INACCURATE) {
                hasPotentialMatches = true;
            }
            if (fLastResource != match.getResource()) {
                fLastResource = match.getResource();
                resources.add(fLastResource);
            }
        }
    }
    ResourceSearchRequestor requestor = new ResourceSearchRequestor();
    try {
        new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor, pm);
    } catch (CoreException e) {
        throw new JavaModelException(e);
    }
    List<IJavaElement> result = new ArrayList<IJavaElement>(requestor.resources.size());
    for (Iterator<IResource> iter = requestor.resources.iterator(); iter.hasNext(); ) {
        IResource resource = iter.next();
        IJavaElement element = JavaCore.create(resource);
        if (element instanceof ICompilationUnit) {
            result.add(element);
        } else {
            hasNonCuMatches = true;
        }
    }
    addStatusErrors(status, requestor.hasPotentialMatches, hasNonCuMatches);
    return result.toArray(new ICompilationUnit[result.size()]);
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) SearchMatch(org.eclipse.jdt.core.search.SearchMatch) JavaModelException(org.eclipse.jdt.core.JavaModelException) HashSet(java.util.HashSet) Set(java.util.Set) ArrayList(java.util.ArrayList) SearchRequestor(org.eclipse.jdt.core.search.SearchRequestor) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) CoreException(org.eclipse.core.runtime.CoreException) IResource(org.eclipse.core.resources.IResource)

Example 84 with CoreException

use of org.eclipse.core.runtime.CoreException in project che by eclipse.

the class RefactoringSearchEngine2 method searchReferencedMethods.

/**
	 * Performs the search of referenced methods.
	 *
	 * @param element the java element whose referenced methods have to be found
	 * @param monitor the progress monitor, or <code>null</code>
	 * @throws JavaModelException if an error occurs during search
	 */
public final void searchReferencedMethods(final IJavaElement element, IProgressMonitor monitor) throws JavaModelException {
    Assert.isNotNull(element);
    if (monitor == null)
        monitor = new NullProgressMonitor();
    try {
        //$NON-NLS-1$
        monitor.beginTask("", 1);
        monitor.setTaskName(RefactoringCoreMessages.RefactoringSearchEngine_searching_referenced_methods);
        try {
            SearchEngine engine = null;
            if (fOwner != null)
                engine = new SearchEngine(fOwner);
            else
                engine = new SearchEngine(fWorkingCopies);
            engine.searchDeclarationsOfSentMessages(element, getCollector(), new SubProgressMonitor(monitor, 1, SubProgressMonitor.SUPPRESS_SUBTASK_LABEL));
        } catch (CoreException exception) {
            throw new JavaModelException(exception);
        }
    } finally {
        monitor.done();
    }
}
Also used : NullProgressMonitor(org.eclipse.core.runtime.NullProgressMonitor) JavaModelException(org.eclipse.jdt.core.JavaModelException) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) CoreException(org.eclipse.core.runtime.CoreException) SubProgressMonitor(org.eclipse.core.runtime.SubProgressMonitor)

Example 85 with CoreException

use of org.eclipse.core.runtime.CoreException in project che by eclipse.

the class SelectionAwareSourceRangeComputer method initializeRanges.

private void initializeRanges() throws CoreException {
    fRanges = new HashMap<ASTNode, SourceRange>();
    if (fSelectedNodes.length == 0)
        return;
    fRanges.put(fSelectedNodes[0], super.computeSourceRange(fSelectedNodes[0]));
    int last = fSelectedNodes.length - 1;
    fRanges.put(fSelectedNodes[last], super.computeSourceRange(fSelectedNodes[last]));
    IScanner scanner = ToolFactory.createScanner(true, false, false, false);
    char[] source = fDocumentPortionToScan.toCharArray();
    scanner.setSource(source);
    // initializeRanges() is only called once
    fDocumentPortionToScan = null;
    TokenScanner tokenizer = new TokenScanner(scanner);
    int pos = tokenizer.getNextStartOffset(0, false);
    ASTNode currentNode = fSelectedNodes[0];
    int newStart = Math.min(fSelectionStart + pos, currentNode.getStartPosition());
    SourceRange range = fRanges.get(currentNode);
    fRanges.put(currentNode, new SourceRange(newStart, range.getLength() + range.getStartPosition() - newStart));
    currentNode = fSelectedNodes[last];
    int scannerStart = currentNode.getStartPosition() + currentNode.getLength() - fSelectionStart;
    tokenizer.setOffset(scannerStart);
    pos = scannerStart;
    int token = -1;
    try {
        while (true) {
            token = tokenizer.readNext(false);
            pos = tokenizer.getCurrentEndOffset();
        }
    } catch (CoreException e) {
    }
    if (token == ITerminalSymbols.TokenNameCOMMENT_LINE) {
        int index = pos - 1;
        while (index >= 0 && IndentManipulation.isLineDelimiterChar(source[index])) {
            pos--;
            index--;
        }
    }
    int newEnd = Math.max(fSelectionStart + pos, currentNode.getStartPosition() + currentNode.getLength());
    range = fRanges.get(currentNode);
    fRanges.put(currentNode, new SourceRange(range.getStartPosition(), newEnd - range.getStartPosition()));
}
Also used : IScanner(org.eclipse.jdt.core.compiler.IScanner) TokenScanner(org.eclipse.jdt.internal.corext.dom.TokenScanner) CoreException(org.eclipse.core.runtime.CoreException) ASTNode(org.eclipse.jdt.core.dom.ASTNode)

Aggregations

CoreException (org.eclipse.core.runtime.CoreException)987 IStatus (org.eclipse.core.runtime.IStatus)264 Status (org.eclipse.core.runtime.Status)240 IFile (org.eclipse.core.resources.IFile)176 IOException (java.io.IOException)174 IProject (org.eclipse.core.resources.IProject)133 IResource (org.eclipse.core.resources.IResource)132 IProgressMonitor (org.eclipse.core.runtime.IProgressMonitor)128 IPath (org.eclipse.core.runtime.IPath)126 ArrayList (java.util.ArrayList)125 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)100 File (java.io.File)95 InvocationTargetException (java.lang.reflect.InvocationTargetException)95 InputStream (java.io.InputStream)76 IConfigurationElement (org.eclipse.core.runtime.IConfigurationElement)67 Path (org.eclipse.core.runtime.Path)61 ByteArrayInputStream (java.io.ByteArrayInputStream)54 IWorkspace (org.eclipse.core.resources.IWorkspace)53 IWorkspaceRoot (org.eclipse.core.resources.IWorkspaceRoot)52 IFileStore (org.eclipse.core.filesystem.IFileStore)51