Java Code Examples for org.eclipse.jdt.internal.corext.util.JavaModelUtil#reconcile()

The following examples show how to use org.eclipse.jdt.internal.corext.util.JavaModelUtil#reconcile() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the new extracted supertype.
 *
 * @param superType
 *            the super type, or <code>null</code> if no super type (ie.
 *            <code>java.lang.Object</code>) is available
 * @param monitor
 *            the progress monitor
 * @return a status describing the outcome of the operation
 * @throws CoreException
 *             if an error occurs
 */
protected final RefactoringStatus createExtractedSuperType(final IType superType, final IProgressMonitor monitor) throws CoreException {
	Assert.isNotNull(monitor);
	fSuperSource= null;
	final RefactoringStatus status= new RefactoringStatus();
	try {
		monitor.beginTask(RefactoringCoreMessages.ExtractSupertypeProcessor_preparing, 20);
		final IType declaring= getDeclaringType();
		final CompilationUnitRewrite declaringRewrite= new CompilationUnitRewrite(fOwner, declaring.getCompilationUnit());
		final AbstractTypeDeclaration declaringDeclaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(declaring, declaringRewrite.getRoot());
		if (declaringDeclaration != null) {
			final String name= JavaModelUtil.getRenamedCUName(declaring.getCompilationUnit(), fTypeName);
			final ICompilationUnit original= declaring.getPackageFragment().getCompilationUnit(name);
			final ICompilationUnit copy= getSharedWorkingCopy(original.getPrimary(), new SubProgressMonitor(monitor, 10));
			fSuperSource= createSuperTypeSource(copy, superType, declaringDeclaration, status, new SubProgressMonitor(monitor, 10));
			if (fSuperSource != null) {
				copy.getBuffer().setContents(fSuperSource);
				JavaModelUtil.reconcile(copy);
			}
		}
	} finally {
		monitor.done();
	}
	return status;
}
 
Example 2
Source File: AddJavaDocStubAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run(IStructuredSelection selection) {
	IMember[] members= getSelectedMembers(selection);
	if (members == null || members.length == 0) {
		return;
	}

	try {
		ICompilationUnit cu= members[0].getCompilationUnit();
		if (!ActionUtil.isEditable(getShell(), cu)) {
			return;
		}

		// open the editor, forces the creation of a working copy
		IEditorPart editor= JavaUI.openInEditor(cu);

		if (ElementValidator.check(members, getShell(), getDialogTitle(), false))
			run(members);
		JavaModelUtil.reconcile(cu);
		EditorUtility.revealInEditor(editor, members[0]);

	} catch (CoreException e) {
		ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.AddJavaDocStubsAction_error_actionFailed);
	}
}
 
Example 3
Source File: CompilationUnitEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the updated java element for the old java element.
 *
 * @param element Old Java element
 * @return Updated Java element
 */
private IJavaElement findElement(IJavaElement element) {

	if (element == null)
		return null;

	IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
	ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());

	if (unit != null) {
		try {
			JavaModelUtil.reconcile(unit);
			IJavaElement[] findings= unit.findElements(element);
			if (findings != null && findings.length > 0)
				return findings[0];

		} catch (JavaModelException x) {
			JavaPlugin.log(x.getStatus());
			// nothing found, be tolerant and go on
		}
	}

	return null;
}
 
Example 4
Source File: CompilationUnitEditor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Returns the most narrow element including the given offset.  If <code>reconcile</code>
 * is <code>true</code> the editor's input element is reconciled in advance. If it is
 * <code>false</code> this method only returns a result if the editor's input element
 * does not need to be reconciled.
 *
 * @param offset the offset included by the retrieved element
 * @param reconcile <code>true</code> if working copy should be reconciled
 * @return the most narrow element which includes the given offset
 */
@Override
protected IJavaElement getElementAt(int offset, boolean reconcile) {
	ICompilationUnit unit= (ICompilationUnit)getInputJavaElement();

	if (unit != null) {
		try {
			if (reconcile) {
				JavaModelUtil.reconcile(unit);
				return unit.getElementAt(offset);
			} else if (unit.isConsistent())
				return unit.getElementAt(offset);

		} catch (JavaModelException x) {
			if (!x.isDoesNotExist())
			JavaPlugin.log(x.getStatus());
			// nothing found, be tolerant and go on
		}
	}

	return null;
}
 
Example 5
Source File: ExtractInterfaceProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates the text change manager for this processor.
 *
 * @param monitor
 *            the progress monitor to display progress
 * @param status
 *            the refactoring status
 * @return the created text change manager
 * @throws JavaModelException
 *             if the method declaration could not be found
 * @throws CoreException
 *             if the changes could not be generated
 */
protected final TextEditBasedChangeManager createChangeManager(final IProgressMonitor monitor, final RefactoringStatus status) throws JavaModelException, CoreException {
	Assert.isNotNull(status);
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask("", 300); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
		resetEnvironment();
		final TextEditBasedChangeManager manager= new TextEditBasedChangeManager();
		final CompilationUnitRewrite sourceRewrite= new CompilationUnitRewrite(fSubType.getCompilationUnit());
		final AbstractTypeDeclaration declaration= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(fSubType, sourceRewrite.getRoot());
		if (declaration != null) {
			createTypeSignature(sourceRewrite, declaration, status, new SubProgressMonitor(monitor, 20));
			final IField[] fields= getExtractedFields(fSubType.getCompilationUnit());
			if (fields.length > 0)
				ASTNodeDeleteUtil.markAsDeleted(fields, sourceRewrite, sourceRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractInterfaceProcessor_remove_field_label, SET_EXTRACT_INTERFACE));
			if (fSubType.isInterface()) {
				final IMethod[] methods= getExtractedMethods(fSubType.getCompilationUnit());
				if (methods.length > 0)
					ASTNodeDeleteUtil.markAsDeleted(methods, sourceRewrite, sourceRewrite.createCategorizedGroupDescription(RefactoringCoreMessages.ExtractInterfaceProcessor_remove_method_label, SET_EXTRACT_INTERFACE));
			}
			final String name= JavaModelUtil.getRenamedCUName(fSubType.getCompilationUnit(), fSuperName);
			final ICompilationUnit original= fSubType.getPackageFragment().getCompilationUnit(name);
			final ICompilationUnit copy= getSharedWorkingCopy(original.getPrimary(), new SubProgressMonitor(monitor, 20));
			fSuperSource= createTypeSource(copy, fSubType, fSuperName, sourceRewrite, declaration, status, new SubProgressMonitor(monitor, 40));
			if (fSuperSource != null) {
				copy.getBuffer().setContents(fSuperSource);
				JavaModelUtil.reconcile(copy);
			}
			final Set<String> replacements= new HashSet<String>();
			if (fReplace)
				rewriteTypeOccurrences(manager, sourceRewrite, copy, replacements, status, new SubProgressMonitor(monitor, 220));
			rewriteSourceMethods(sourceRewrite, replacements);
			manager.manage(fSubType.getCompilationUnit(), sourceRewrite.createChange(true));
		}
		return manager;
	} finally {
		monitor.done();
	}
}
 
Example 6
Source File: TextSelectionConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IJavaElement[] codeResolve(IJavaElement input, ITextSelection selection) throws JavaModelException {
		if (input instanceof ICodeAssist) {
			if (input instanceof ICompilationUnit) {
				ICompilationUnit cunit= (ICompilationUnit)input;
				if (cunit.isWorkingCopy())
					JavaModelUtil.reconcile(cunit);
			}
			IJavaElement[] elements= ((ICodeAssist)input).codeSelect(selection.getOffset(), selection.getLength());
			if (elements != null && elements.length > 0)
				return elements;
		}
		return EMPTY_RESULT;
}
 
Example 7
Source File: CompilationUnitDocumentProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a fake compilation unit.
 *
 * @param editorInput the URI editor input
 * @return the fake compilation unit
 * @since 3.3
 */
private ICompilationUnit createFakeCompiltationUnit(IURIEditorInput editorInput) {
	try {
		final URI uri= editorInput.getURI();
		final IFileStore fileStore= EFS.getStore(uri);
		final IPath path= URIUtil.toPath(uri);
		String fileStoreName= fileStore.getName();
		if (fileStoreName == null || path == null)
			return null;

		WorkingCopyOwner woc= new WorkingCopyOwner() {
			/*
			 * @see org.eclipse.jdt.core.WorkingCopyOwner#createBuffer(org.eclipse.jdt.core.ICompilationUnit)
			 * @since 3.2
			 */
			@Override
			public IBuffer createBuffer(ICompilationUnit workingCopy) {
				return new DocumentAdapter(workingCopy, fileStore, path);
			}
		};

		IClasspathEntry[] cpEntries= null;
		IJavaProject jp= findJavaProject(path);
		if (jp != null)
			cpEntries= jp.getResolvedClasspath(true);

		if (cpEntries == null || cpEntries.length == 0)
			cpEntries= new IClasspathEntry[] { JavaRuntime.getDefaultJREContainerEntry() };

		final ICompilationUnit cu= woc.newWorkingCopy(fileStoreName, cpEntries, getProgressMonitor());

		if (!isModifiable(editorInput))
			JavaModelUtil.reconcile(cu);

		return cu;
	} catch (CoreException ex) {
		return null;
	}
}
 
Example 8
Source File: SelectionConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IJavaElement[] codeResolve(IJavaElement input, ITextSelection selection) throws JavaModelException {
		if (input instanceof ICodeAssist) {
			if (input instanceof ICompilationUnit) {
				JavaModelUtil.reconcile((ICompilationUnit) input);
			}
			IJavaElement[] elements= ((ICodeAssist)input).codeSelect(selection.getOffset() + selection.getLength(), 0);
			if (elements.length > 0) {
				return elements;
			}
		}
		return EMPTY_RESULT;
}
 
Example 9
Source File: SelectionConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IJavaElement getElementAtOffset(ITypeRoot input, ITextSelection selection) throws JavaModelException {
	if (input instanceof ICompilationUnit) {
		JavaModelUtil.reconcile((ICompilationUnit) input);
	}
	IJavaElement ref= input.getElementAt(selection.getOffset());
	if (ref == null)
		return input;
	return ref;
}
 
Example 10
Source File: SelectionConverter.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IJavaElement resolveEnclosingElement(IJavaElement input, ITextSelection selection) throws JavaModelException {
	IJavaElement atOffset= null;
	if (input instanceof ICompilationUnit) {
		ICompilationUnit cunit= (ICompilationUnit)input;
		JavaModelUtil.reconcile(cunit);
		atOffset= cunit.getElementAt(selection.getOffset());
	} else if (input instanceof IClassFile) {
		IClassFile cfile= (IClassFile)input;
		atOffset= cfile.getElementAt(selection.getOffset());
	} else {
		return null;
	}
	if (atOffset == null) {
		return input;
	} else {
		int selectionEnd= selection.getOffset() + selection.getLength();
		IJavaElement result= atOffset;
		if (atOffset instanceof ISourceReference) {
			ISourceRange range= ((ISourceReference)atOffset).getSourceRange();
			while (range.getOffset() + range.getLength() < selectionEnd) {
				result= result.getParent();
				if (! (result instanceof ISourceReference)) {
					result= input;
					break;
				}
				range= ((ISourceReference)result).getSourceRange();
			}
		}
		return result;
	}
}
 
Example 11
Source File: TypeCreator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates the new type.
 *
 * NOTE: If this method throws a {@link JavaModelException}, its {@link JavaModelException#getJavaModelStatus()}
 * method can provide more detailed information about the problem.
 */
public IType createType() throws CoreException {
  IProgressMonitor monitor = new NullProgressMonitor();

  ICompilationUnit cu = null;
  try {
    String cuName = simpleTypeName + ".java";

    // Create empty compilation unit
    cu = pckg.createCompilationUnit(cuName, "", false, monitor);
    cu.becomeWorkingCopy(monitor);
    IBuffer buffer = cu.getBuffer();

    // Need to create a minimal type stub here so we can create an import
    // rewriter a few lines down. The rewriter has to be in place when we
    // create the real type stub, so we can use it to transform the names of
    // any interfaces this type extends/implements.
    String dummyTypeStub = createDummyTypeStub();

    // Generate the content (file comment, package declaration, type stub)
    String cuContent = createCuContent(cu, dummyTypeStub);
    buffer.setContents(cuContent);

    ImportRewrite imports = StubUtility.createImportRewrite(cu, true);

    // Create the real type stub and replace the dummy one
    int typeDeclOffset = cuContent.lastIndexOf(dummyTypeStub);
    if (typeDeclOffset != -1) {
      String typeStub = createTypeStub(cu, imports);
      buffer.replace(typeDeclOffset, dummyTypeStub.length(), typeStub);
    }

    // Let our subclasses add members
    IType type = cu.getType(simpleTypeName);
    createTypeMembers(type, imports);

    // Rewrite the imports and apply the edit
    TextEdit edit = imports.rewriteImports(monitor);
    applyEdit(cu, edit, false, null);

    // Format the Java code
    String formattedSource = formatJava(type);
    buffer.setContents(formattedSource);

    // Save the new type
    JavaModelUtil.reconcile(cu);
    cu.commitWorkingCopy(true, monitor);

    return type;
  } finally {
    if (cu != null) {
      cu.discardWorkingCopy();
    }
  }
}
 
Example 12
Source File: NewPackageWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void createPackageInfoJava(IProgressMonitor monitor) throws CoreException {
	String lineDelimiter= StubUtility.getLineDelimiterUsed(fCreatedPackageFragment.getJavaProject());
	StringBuilder content = new StringBuilder();
	String fileComment= getFileComment(lineDelimiter);
	String typeComment= getTypeComment(lineDelimiter);
	
	if (fileComment != null) {
		content.append(fileComment);
		content.append(lineDelimiter);
	}

	if (typeComment != null) {
		content.append(typeComment);
		content.append(lineDelimiter);
	} else if (fileComment != null) {
		// insert an empty file comment to avoid that the file comment becomes the type comment
		content.append("/**");  //$NON-NLS-1$
		content.append(lineDelimiter);
		content.append(" *"); //$NON-NLS-1$
		content.append(lineDelimiter);
		content.append(" */"); //$NON-NLS-1$
		content.append(lineDelimiter);
	}

	content.append("package "); //$NON-NLS-1$
	content.append(fCreatedPackageFragment.getElementName());
	content.append(";"); //$NON-NLS-1$

	ICompilationUnit compilationUnit= fCreatedPackageFragment.createCompilationUnit(PACKAGE_INFO_JAVA_FILENAME, content.toString(), true, monitor);

	JavaModelUtil.reconcile(compilationUnit);

	compilationUnit.becomeWorkingCopy(monitor);
	try {
		IBuffer buffer= compilationUnit.getBuffer();
		ISourceRange sourceRange= compilationUnit.getSourceRange();
		String originalContent= buffer.getText(sourceRange.getOffset(), sourceRange.getLength());

		String formattedContent= CodeFormatterUtil.format(CodeFormatter.K_COMPILATION_UNIT, originalContent, 0, lineDelimiter, fCreatedPackageFragment.getJavaProject());
		formattedContent= Strings.trimLeadingTabsAndSpaces(formattedContent);
		buffer.replace(sourceRange.getOffset(), sourceRange.getLength(), formattedContent);
		compilationUnit.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
	} finally {
		compilationUnit.discardWorkingCopy();
	}
}
 
Example 13
Source File: JavaDocAutoIndentStrategy.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Copies the indentation of the previous line and adds a star.
 * If the Javadoc just started on this line add standard method tags
 * and close the Javadoc.
 *
 * @param d the document to work on
 * @param c the command to deal with
 */
private void indentAfterNewLine(IDocument d, DocumentCommand c) {

	int offset= c.offset;
	if (offset == -1 || d.getLength() == 0)
		return;

	try {
		int p= (offset == d.getLength() ? offset - 1 : offset);
		IRegion line= d.getLineInformationOfOffset(p);

		int lineOffset= line.getOffset();
		int firstNonWS= findEndOfWhiteSpace(d, lineOffset, offset);
		Assert.isTrue(firstNonWS >= lineOffset, "indentation must not be negative"); //$NON-NLS-1$

		StringBuffer buf= new StringBuffer(c.text);
		IRegion prefix= findPrefixRange(d, line);
		String indentation= d.get(prefix.getOffset(), prefix.getLength());
		int lengthToAdd= Math.min(offset - prefix.getOffset(), prefix.getLength());

		buf.append(indentation.substring(0, lengthToAdd));

		if (firstNonWS < offset) {
			if (d.getChar(firstNonWS) == '/') {
				// Javadoc started on this line
				buf.append(" * "); //$NON-NLS-1$

				if (isPreferenceTrue(PreferenceConstants.EDITOR_CLOSE_JAVADOCS) && isNewComment(d, offset)) {
					c.shiftsCaret= false;
					c.caretOffset= c.offset + buf.length();
					String lineDelimiter= TextUtilities.getDefaultLineDelimiter(d);

					int eolOffset= lineOffset + line.getLength();
					int replacementLength= eolOffset - p;
					String restOfLine= d.get(p, replacementLength);
					String endTag= lineDelimiter + indentation + " */"; //$NON-NLS-1$

					if (isPreferenceTrue(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS)) {
						// we need to close the comment before computing
						// the correct tags in order to get the method
						d.replace(offset, replacementLength, endTag);

						// evaluate method signature
						ICompilationUnit unit= getCompilationUnit();

						if (unit != null) {
							try {
								JavaModelUtil.reconcile(unit);
								String string= createJavaDocTags(d, c, indentation, lineDelimiter, unit);
								buf.append(restOfLine);
								// only add tags if they are non-empty - the empty line has already been added above.
								if (string != null && !string.trim().equals("*")) //$NON-NLS-1$
									buf.append(string);
							} catch (CoreException e) {
								// ignore
							}
						}
					} else {
						c.length= replacementLength;
						buf.append(restOfLine);
						buf.append(endTag);
					}
				}

			}
		}

		// move the caret behind the prefix, even if we do not have to insert it.
		if (lengthToAdd < prefix.getLength())
			c.caretOffset= offset + prefix.getLength() - lengthToAdd;
		c.text= buf.toString();

	} catch (BadLocationException excp) {
		// stop work
	}
}