Java Code Examples for org.eclipse.jdt.core.ICompilationUnit#getType()

The following examples show how to use org.eclipse.jdt.core.ICompilationUnit#getType() . 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: ProjectAwareUniqueClassNameValidator.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
private SourceTraversal doCheckUniqueInProjectSource(String packageName, String typeName, JvmDeclaredType type,
		List<IPackageFragmentRoot> sourceFolders) throws JavaModelException {
	IndexManager indexManager = JavaModelManager.getIndexManager();
	for (IPackageFragmentRoot sourceFolder : sourceFolders) {
		if (indexManager.awaitingJobsCount() > 0) {
			if (!isDerived(sourceFolder.getResource())) {
				IPackageFragment packageFragment = sourceFolder.getPackageFragment(packageName);
				if (packageFragment.exists()) {
					for (ICompilationUnit unit : packageFragment.getCompilationUnits()) {
						if (!isDerived(unit.getResource())) {
							IType javaType = unit.getType(typeName);
							if (javaType.exists()) {
								addIssue(type, unit.getElementName());
								return SourceTraversal.DUPLICATE;
							}
						}
					}
				}
			}
		} else {
			return SourceTraversal.INTERRUPT;
		}
	}
	return SourceTraversal.UNIQUE;
}
 
Example 2
Source File: JdtTypeProvider.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.9
 */
protected IType findSecondaryTypeInSourceFolders(String packageName, final String typeName, IPackageFragmentRoot[] sourceFolders) throws JavaModelException {
	for(IPackageFragmentRoot sourceFolder: sourceFolders) {
		IPackageFragment packageFragment = sourceFolder.getPackageFragment(Strings.emptyIfNull(packageName));
		if (packageFragment.exists()) {
			ICompilationUnit[] units = packageFragment.getCompilationUnits();
			for(ICompilationUnit unit: units) {
				IType type = unit.getType(typeName);
				if (type.exists()) {
					return type;
				}
			}
		}
	}
	return null;
}
 
Example 3
Source File: NLSRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Computes whether the Eclipse NLSing mechanism is used.
 *
 * @return		<code>true</code> if NLSing is done the Eclipse way
 * 				and <code>false</code> if the standard resource bundle mechanism is used
 * @since 3.1
 */
public boolean detectIsEclipseNLS() {
	ICompilationUnit accessorCU= getAccessorClassPackage().getCompilationUnit(getAccessorCUName());
	IType type= accessorCU.getType(getAccessorClassName());
	if (type.exists()) {
		try {
			String superclassName= type.getSuperclassName();
			if (!"NLS".equals(superclassName) && !NLS.class.getName().equals(superclassName)) //$NON-NLS-1$
				return false;
			IType superclass= type.newSupertypeHierarchy(null).getSuperclass(type);
			return superclass != null && NLS.class.getName().equals(superclass.getFullyQualifiedName());
		} catch (JavaModelException e) {
			// use default
		}
	}
	// Bug 271375: Make the default be to use Eclipse's NLS mechanism if it's available.
	return isEclipseNLSAvailable();
}
 
Example 4
Source File: ExtractSupertypeProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Computes the destination type based on the new name.
 *
 * @param name the new name
 * @return the destination type
 */
public IType computeExtractedType(final String name) {
	if (name != null && !name.equals("")) {//$NON-NLS-1$
		final IType declaring= getDeclaringType();
		try {
			final ICompilationUnit[] units= declaring.getPackageFragment().getCompilationUnits(fOwner);
			final String newName= JavaModelUtil.getRenamedCUName(declaring.getCompilationUnit(), name);
			ICompilationUnit result= null;
			for (int index= 0; index < units.length; index++) {
				if (units[index].getElementName().equals(newName))
					result= units[index];
			}
			if (result != null) {
				final IType type= result.getType(name);
				setDestinationType(type);
				return type;
			}
		} catch (JavaModelException exception) {
			JavaPlugin.log(exception);
		}
	}
	return null;
}
 
Example 5
Source File: JsniTypeReferenceChangeTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void testPerformCompilationUnitChanged() {
  final ICompilationUnit targetCu = refactorTestClass.getCompilationUnit();
  final IType newType = targetCu.getType("RefactorTest2");

  GWTTypeRefactoringSupport refactoringSupport = new GWTTypeRefactoringSupport() {
    @Override
    public IType getNewType() {
      return newType;
    }

    @Override
    public IType getOldType() {
      return targetCu.getType("RefactorTest");
    }
  };

  JsniTypeReferenceChangeFactory factory = new JsniTypeReferenceChangeFactory(
      refactoringSupport);
  IJsniTypeReferenceChange change = factory.createChange(targetCu);
  assertEquals(newType.getCompilationUnit(), change.getCompilationUnit());
}
 
Example 6
Source File: GWTDeleteCompilationUnitParticipantTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
public void testCreateChange() throws OperationCanceledException,
    CoreException {
  // We're going to delete compilation unit R.java
  ICompilationUnit cu = rClass.getCompilationUnit();
  IType r = cu.getType("R");

  // Verify that the index currently contains one JSNI reference to R
  Set<IIndexedJavaRef> refs = JavaRefIndex.getInstance().findTypeReferences(
      r.getFullyQualifiedName());
  assertEquals(1, refs.size());

  // Delete R.java
  cu.delete(true, null);
  assertFalse(cu.exists());

  // Now verify that the index entries pointing to R have been purged
  refs = JavaRefIndex.getInstance().findTypeReferences(r.getElementName());
  assertEquals(0, refs.size());
}
 
Example 7
Source File: GenerateGetterAndSetterTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testNoGeneratorForInterface() throws OperationCanceledException, CoreException {
	/* @formatter:off */
	ICompilationUnit b = fPackageP.createCompilationUnit("C.java", "package p;\r\n" +
			"\r\n" +
			"public interface C {\r\n" +
			"\r\n" +
			"	Object o;\r\n" +
			"\r\n" +
			"}", true, null);
	/* @formatter:on */
	IType classC = b.getType("C");
	assertNull(runOperation(classC));
}
 
Example 8
Source File: TypeNameMatchRequestorWrapper.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) {

	// Get type
	try {
		IType type = null;
		if (this.handleFactory != null) {
			Openable openable = this.handleFactory.createOpenable(path, this.scope);
			if (openable == null) return;
			switch (openable.getElementType()) {
				case IJavaElement.COMPILATION_UNIT:
					ICompilationUnit cu = (ICompilationUnit) openable;
					if (enclosingTypeNames != null && enclosingTypeNames.length > 0) {
						type = cu.getType(new String(enclosingTypeNames[0]));
						for (int j=1, l=enclosingTypeNames.length; j<l; j++) {
							type = type.getType(new String(enclosingTypeNames[j]));
						}
						type = type.getType(new String(simpleTypeName));
					} else {
						type = cu.getType(new String(simpleTypeName));
					}
					break;
				case IJavaElement.CLASS_FILE:
					type = ((IClassFile)openable).getType();
					break;
			}
		} else {
			int separatorIndex= path.indexOf(IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR);
			type = separatorIndex == -1
				? createTypeFromPath(path, new String(simpleTypeName), enclosingTypeNames)
				: createTypeFromJar(path, separatorIndex);
		}

		// Accept match if the type has been found
		if (type != null) {
			// hierarchy scopes require one more check:
			if (!(this.scope instanceof HierarchyScope) || ((HierarchyScope)this.scope).enclosesFineGrained(type)) {

				// Create the match
				final JavaSearchTypeNameMatch match = new JavaSearchTypeNameMatch(type, modifiers);

				// Update match accessibility
				if(access != null) {
					switch (access.getProblemId()) {
						case IProblem.ForbiddenReference:
							match.setAccessibility(IAccessRule.K_NON_ACCESSIBLE);
							break;
						case IProblem.DiscouragedReference:
							match.setAccessibility(IAccessRule.K_DISCOURAGED);
							break;
					}
				}

				// Accept match
				this.requestor.acceptTypeNameMatch(match);
			}
		}
	} catch (JavaModelException e) {
		// skip
	}
}
 
Example 9
Source File: NewTypeWizardPage.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Hook method that gets called when the type name has changed. The method validates the
 * type name and returns the status of the validation.
 * <p>
 * Subclasses may extend this method to perform their own validation.
 * </p>
 *
 * @return the status of the validation
 */
protected IStatus typeNameChanged() {
	StatusInfo status= new StatusInfo();
	fCurrType= null;
	String typeNameWithParameters= getTypeName();
	// must not be empty
	if (typeNameWithParameters.length() == 0) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_EnterTypeName);
		return status;
	}

	String typeName= getTypeNameWithoutParameters();
	if (typeName.indexOf('.') != -1) {
		status.setError(NewWizardMessages.NewTypeWizardPage_error_QualifiedName);
		return status;
	}

	IJavaProject project= getJavaProject();
	IStatus val= validateJavaTypeName(typeName, project);
	if (val.getSeverity() == IStatus.ERROR) {
		status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, val.getMessage()));
		return status;
	} else if (val.getSeverity() == IStatus.WARNING) {
		status.setWarning(Messages.format(NewWizardMessages.NewTypeWizardPage_warning_TypeNameDiscouraged, val.getMessage()));
		// continue checking
	}

	// must not exist
	if (!isEnclosingTypeSelected()) {
		IPackageFragment pack= getPackageFragment();
		if (pack != null) {
			ICompilationUnit cu= pack.getCompilationUnit(getCompilationUnitName(typeName));
			fCurrType= cu.getType(typeName);
			IResource resource= cu.getResource();

			if (resource.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
			if (!ResourcesPlugin.getWorkspace().validateFiltered(resource).isOK()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameFiltered);
				return status;
			}
			URI location= resource.getLocationURI();
			if (location != null) {
				try {
					IFileStore store= EFS.getStore(location);
					if (store.fetchInfo().exists()) {
						status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExistsDifferentCase);
						return status;
					}
				} catch (CoreException e) {
					status.setError(Messages.format(
						NewWizardMessages.NewTypeWizardPage_error_uri_location_unkown,
						BasicElementLabels.getURLPart(Resources.getLocationString(resource))));
				}
			}
		}
	} else {
		IType type= getEnclosingType();
		if (type != null) {
			fCurrType= type.getType(typeName);
			if (fCurrType.exists()) {
				status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeNameExists);
				return status;
			}
		}
	}

	if (!typeNameWithParameters.equals(typeName) && project != null) {
		if (!JavaModelUtil.is50OrHigher(project)) {
			status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters);
			return status;
		}
		String typeDeclaration= "class " + typeNameWithParameters + " {}"; //$NON-NLS-1$//$NON-NLS-2$
		ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
		parser.setSource(typeDeclaration.toCharArray());
		parser.setProject(project);
		CompilationUnit compilationUnit= (CompilationUnit) parser.createAST(null);
		IProblem[] problems= compilationUnit.getProblems();
		if (problems.length > 0) {
			status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidTypeName, problems[0].getMessage()));
			return status;
		}
	}
	return status;
}
 
Example 10
Source File: ExtractInterfaceProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public final Change createChange(final IProgressMonitor monitor) throws CoreException, OperationCanceledException {
	Assert.isNotNull(monitor);
	try {
		monitor.beginTask("", 1); //$NON-NLS-1$
		monitor.setTaskName(RefactoringCoreMessages.ExtractInterfaceProcessor_creating);
		final Map<String, String> arguments= new HashMap<String, String>();
		String project= null;
		final IJavaProject javaProject= fSubType.getJavaProject();
		if (javaProject != null)
			project= javaProject.getElementName();
		int flags= JavaRefactoringDescriptor.JAR_MIGRATION | JavaRefactoringDescriptor.JAR_REFACTORING | RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
		try {
			if (fSubType.isLocal() || fSubType.isAnonymous())
				flags|= JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
		} catch (JavaModelException exception) {
			JavaPlugin.log(exception);
		}
		final IPackageFragment fragment= fSubType.getPackageFragment();
		final ICompilationUnit cu= fragment.getCompilationUnit(JavaModelUtil.getRenamedCUName(fSubType.getCompilationUnit(), fSuperName));
		final IType type= cu.getType(fSuperName);
		final String description= Messages.format(RefactoringCoreMessages.ExtractInterfaceProcessor_description_descriptor_short, BasicElementLabels.getJavaElementName(fSuperName));
		final String header= Messages.format(RefactoringCoreMessages.ExtractInterfaceProcessor_descriptor_description, new String[] { JavaElementLabels.getElementLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED), JavaElementLabels.getElementLabel(fSubType, JavaElementLabels.ALL_FULLY_QUALIFIED) });
		final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
		comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractInterfaceProcessor_refactored_element_pattern, JavaElementLabels.getElementLabel(type, JavaElementLabels.ALL_FULLY_QUALIFIED)));
		final String[] settings= new String[fMembers.length];
		for (int index= 0; index < settings.length; index++)
			settings[index]= JavaElementLabels.getElementLabel(fMembers[index], JavaElementLabels.ALL_FULLY_QUALIFIED);
		comment.addSetting(JDTRefactoringDescriptorComment.createCompositeSetting(RefactoringCoreMessages.ExtractInterfaceProcessor_extracted_members_pattern, settings));
		addSuperTypeSettings(comment, true);
		final ExtractInterfaceDescriptor descriptor= RefactoringSignatureDescriptorFactory.createExtractInterfaceDescriptor(project, description, comment.asString(), arguments, flags);
		arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fSubType));
		arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fSuperName);
		for (int index= 0; index < fMembers.length; index++)
			arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_ELEMENT + (index + 1), JavaRefactoringDescriptorUtil.elementToHandle(project, fMembers[index]));
		arguments.put(ATTRIBUTE_ABSTRACT, Boolean.valueOf(fAbstract).toString());
		arguments.put(ATTRIBUTE_COMMENTS, Boolean.valueOf(fComments).toString());
		arguments.put(ATTRIBUTE_PUBLIC, Boolean.valueOf(fPublic).toString());
		arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplace).toString());
		arguments.put(ATTRIBUTE_INSTANCEOF, Boolean.valueOf(fInstanceOf).toString());
		final DynamicValidationRefactoringChange change= new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.ExtractInterfaceRefactoring_name, fChangeManager.getAllChanges());
		final IFile file= ResourceUtil.getFile(fSubType.getCompilationUnit());
		if (fSuperSource != null && fSuperSource.length() > 0)
			change.add(new CreateCompilationUnitChange(fSubType.getPackageFragment().getCompilationUnit(JavaModelUtil.getRenamedCUName(fSubType.getCompilationUnit(), fSuperName)), fSuperSource, file.getCharset(false)));
		monitor.worked(1);
		return change;
	} finally {
		monitor.done();
	}
}
 
Example 11
Source File: GWTMoveTypeParticipant.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected boolean initialize(Object element) {
  if (!(element instanceof IType)) {
    return false;
  }

  Object destObj = getArguments().getDestination();
  if (!(destObj instanceof IJavaElement)) {
    return false;
  }

  IType oldType = (IType) element;
  IJavaElement dest = (IJavaElement) destObj;

  // TODO: support moving inner classes to other declaring types?

  // We only support moving top-level types to other packages, for now
  if (dest instanceof IPackageFragment && oldType.getDeclaringType() == null) {
    IPackageFragment newPckgFragment = (IPackageFragment) dest;

    // Initialize the refactoring support properties
    GWTRefactoringSupport support = getRefactoringSupport();
    support.setOldElement(oldType);

    // For some reason, getUpdateReferences() returns false when the
    // destination is the default package, even if the checkbox in the UI for
    // 'update references' is checked.
    support.setUpdateReferences(getArguments().getUpdateReferences()
        || newPckgFragment.isDefaultPackage());

    /*
     * Figure out the new type after the move. To this, we use the old
     * compilation unit and old type name, rooted under the destination
     * package fragment. It's okay to do this before the actual move takes
     * place, because the getXXX methods we're using are all handle-only
     * methods. That is, the IType we end up setting as the new element would
     * return false if we called exists() on it at this point.
     */
    ICompilationUnit oldCu = oldType.getCompilationUnit();
    ICompilationUnit newCu = newPckgFragment.getCompilationUnit(oldCu.getElementName());
    IType newType = newCu.getType(oldType.getElementName());
    support.setNewElement(newType);

    return true;
  }

  return false;
}
 
Example 12
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 13
Source File: GenerateGetterAndSetterTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verify existing setters are not overwritten, and getters are created
 *
 * @throws Exception
 */
@Test
public void test10() throws Exception {
	/* @formatter:off */
	ICompilationUnit b= fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"\r\n" +
			"	private Object o;\r\n" +
			"\r\n" +
			"	/**\r\n" +
			"	 * @param o The o to set.\r\n" +
			"	 */\r\n" +
			"	synchronized void setO(Object o) {\r\n" +
			"		this.o = o;\r\n" +
			"	}\r\n" +
			"}", true, null);
	/* @formatter:on */

	IType classB = b.getType("B");
	runAndApplyOperation(classB);

	/* @formatter:off */
	String expected= "public class B {\r\n" +
			"\r\n" +
			"	private Object o;\r\n" +
			"\r\n" +
			"	/**\r\n" +
			"	 * @param o The o to set.\r\n" +
			"	 */\r\n" +
			"	synchronized void setO(Object o) {\r\n" +
			"		this.o = o;\r\n" +
			"	}\r\n" +
			"\r\n" +
			"	/**\r\n" +
			"	 * @return Returns the o.\r\n" +
			"	 */\r\n" +
			"	public Object getO() {\r\n" +
			"		return o;\r\n" +
			"	}\r\n" +
			"}";
	/* @formatter:on */

	compareSource(expected, classB.getSource());
}
 
Example 14
Source File: GenerateGetterAndSetterTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verify existing getters are not overwritten, and setters are created
 *
 * @throws Exception
 */
@Test
public void test9() throws Exception {
	/* @formatter:off */
	ICompilationUnit b= fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"\r\n" +
			"	private Object o;\r\n" +
			"\r\n" +
			"	/**\r\n" +
			"	 * @return Returns the o.\r\n" +
			"	 */\r\n" +
			"	synchronized Object getO() {\r\n" +
			"		return o;\r\n" +
			"	}\r\n" +
			"}", true, null);
	/* @formatter:on */

	IType classB = b.getType("B");
	runAndApplyOperation(classB);

	/* @formatter:off */
	String expected= "public class B {\r\n" +
			"\r\n" +
			"	private Object o;\r\n" +
			"\r\n" +
			"	/**\r\n" +
			"	 * @return Returns the o.\r\n" +
			"	 */\r\n" +
			"	synchronized Object getO() {\r\n" +
			"		return o;\r\n" +
			"	}\r\n" +
			"\r\n" +
			"	/**\r\n" +
			"	 * @param o The o to set.\r\n" +
			"	 */\r\n" +
			"	public void setO(Object o) {\r\n" +
			"		this.o = o;\r\n" +
			"	}\r\n" +
			"}";
	/* @formatter:on */

	compareSource(expected, classB.getSource());
}
 
Example 15
Source File: GenerateGetterAndSetterTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Test generation for more than one field
 * @throws Exception
 */
@Test
public void test5() throws Exception {
	createNewType("q.Other");
	/* @formatter:off */
	ICompilationUnit b= fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"import q.Other;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"\r\n" +
			"	private String a;\r\n" +
			"	private String b;\r\n" +
			"	protected Other c;\r\n" +
			"	public String d;\r\n" +
			"}", true, null);
	/* @formatter:on */

	IType classB= b.getType("B");
	IField field1= classB.getField("a");
	IField field2= classB.getField("b");
	IField field3= classB.getField("c");
	IField field4= classB.getField("d");
	runAndApplyOperation(classB);

	/* @formatter:off */
	String expected= "public class B {\r\n" +
					"\r\n" +
					"	private String a;\r\n" +
					"	private String b;\r\n" +
					"	protected Other c;\r\n" +
					"	public String d;\r\n" +
					"	/**\r\n" +
					"	 * @return Returns the a.\r\n" +
					"	 */\r\n" +
					"	public String getA() {\r\n" +
					"		return a;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @param a The a to set.\r\n" +
					"	 */\r\n" +
					"	public void setA(String a) {\r\n" +
					"		this.a = a;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @return Returns the b.\r\n" +
					"	 */\r\n" +
					"	public String getB() {\r\n" +
					"		return b;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @param b The b to set.\r\n" +
					"	 */\r\n" +
					"	public void setB(String b) {\r\n" +
					"		this.b = b;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @return Returns the c.\r\n" +
					"	 */\r\n" +
					"	public Other getC() {\r\n" +
					"		return c;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @param c The c to set.\r\n" +
					"	 */\r\n" +
					"	public void setC(Other c) {\r\n" +
					"		this.c = c;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @return Returns the d.\r\n" +
					"	 */\r\n" +
					"	public String getD() {\r\n" +
					"		return d;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @param d The d to set.\r\n" +
					"	 */\r\n" +
					"	public void setD(String d) {\r\n" +
					"		this.d = d;\r\n" +
					"	}\r\n" +
					"}";
	/* @formatter:on */

	compareSource(expected, classB.getSource());
}
 
Example 16
Source File: GenerateGetterAndSetterTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Test parameterized types in field declarations
 * @throws Exception
 */
@Test
public void test3() throws Exception {
	/* @formatter:off */
	ICompilationUnit b = fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"import java.util.HashMap;\r\n" +
			"import java.util.Map;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"\r\n" +
			"	Map<String,String> a = new HashMap<String,String>();\r\n" +
			"}\r\n", true, null);
	/* @formatter:on */

	IType classB = b.getType("B");
	runAndApplyOperation(classB);

	/* @formatter:off */
	String expected= "public class B {\r\n" +
					"\r\n" +
					"	Map<String,String> a = new HashMap<String,String>();\r\n" +
					"\r\n" +
					"	/**\r\n" +
					"	 * @return Returns the a.\r\n" +
					"	 */\r\n" +
					"	public Map<String, String> getA() {\r\n" +
					"		return a;\r\n" +
					"	}\r\n" +
					"\r\n" +
					"	/**\r\n" +
					"	 * @param a The a to set.\r\n" +
					"	 */\r\n" +
					"	public void setA(Map<String, String> a) {\r\n" +
					"		this.a = a;\r\n" +
					"	}\r\n" +
					"}";
	/* @formatter:on */

	compareSource(expected, classB.getSource());
}
 
Example 17
Source File: GenerateAccessorsHandlerTest.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testGenerateAccessors() throws ValidateEditException, CoreException, IOException {
	//@formatter:off
	ICompilationUnit unit = fPackageP.createCompilationUnit("B.java", "package p;\r\n" +
			"\r\n" +
			"public class B {\r\n" +
			"	private static String staticField = \"23434343\";\r\n" +
			"	private final String finalField;\r\n" +
			"	String name;\r\n" +
			"}"
			, true, null);
	//@formatter:on
	IType classB = unit.getType("B");
	generateAccessors(classB);

	/* @formatter:off */
	String expected = "public class B {\r\n" +
					"	private static String staticField = \"23434343\";\r\n" +
					"	private final String finalField;\r\n" +
					"	String name;\r\n" +
					"	/**\r\n" +
					"	 * @return Returns the staticField.\r\n" +
					"	 */\r\n" +
					"	public static String getStaticField() {\r\n" +
					"		return staticField;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @param staticField The staticField to set.\r\n" +
					"	 */\r\n" +
					"	public static void setStaticField(String staticField) {\r\n" +
					"		B.staticField = staticField;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @return Returns the finalField.\r\n" +
					"	 */\r\n" +
					"	public String getFinalField() {\r\n" +
					"		return finalField;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @return Returns the name.\r\n" +
					"	 */\r\n" +
					"	public String getName() {\r\n" +
					"		return name;\r\n" +
					"	}\r\n" +
					"	/**\r\n" +
					"	 * @param name The name to set.\r\n" +
					"	 */\r\n" +
					"	public void setName(String name) {\r\n" +
					"		this.name = name;\r\n" +
					"	}\r\n" +
					"}";
	/* @formatter:on */

	compareSource(expected, classB.getSource());
}
 
Example 18
Source File: ProjectAwareUniqueClassNameValidator.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
public boolean doCheckUniqueInProject(QualifiedName name, JvmDeclaredType type) throws JavaModelException {
	IJavaProject javaProject = javaProjectProvider.getJavaProject(type.eResource().getResourceSet());
	getContext().put(ProjectAwareUniqueClassNameValidator.OUTPUT_CONFIGS,
			outputConfigurationProvider.getOutputConfigurations(type.eResource()));

	String packageName = type.getPackageName();
	String typeName = type.getSimpleName();
	IndexManager indexManager = JavaModelManager.getIndexManager();
	List<IPackageFragmentRoot> sourceFolders = new ArrayList<>();
	for (IPackageFragmentRoot root : javaProject.getPackageFragmentRoots()) {
		if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
			sourceFolders.add(root);
		}
	}

	if (sourceFolders.isEmpty() || indexManager.awaitingJobsCount() > 0) {
		// still indexing - don't enter a busy wait loop but ask the source folders directly
		SourceTraversal sourceTraversal = doCheckUniqueInProjectSource(packageName != null ? packageName : "", typeName, type,
				sourceFolders);
		if (sourceTraversal == SourceTraversal.DUPLICATE) {
			return false;
		} else if (sourceTraversal == SourceTraversal.UNIQUE) {
			return true;
		}
	}

	Set<String> workingCopyPaths = new HashSet<>();
	ICompilationUnit[] copies = getWorkingCopies(type);
	if (copies != null) {
		for (ICompilationUnit workingCopy : copies) {
			IPath path = workingCopy.getPath();
			if (javaProject.getPath().isPrefixOf(path) && !isDerived(workingCopy.getResource())) {
				if (workingCopy.getPackageDeclaration(packageName).exists()) {
					IType result = workingCopy.getType(typeName);
					if (result.exists()) {
						addIssue(type, workingCopy.getElementName());
						return false;
					}
				}
				workingCopyPaths.add(workingCopy.getPath().toString());
			}
		}
	}

	// The code below is adapted from BasicSearchEnginge.searchAllSecondaryTypes
	// The Index is ready, query it for a secondary type 
	char[] pkg = packageName == null ? CharOperation.NO_CHAR : packageName.toCharArray();
	TypeDeclarationPattern pattern = new TypeDeclarationPattern(pkg, //
			CharOperation.NO_CHAR_CHAR, // top level type - no enclosing type names
			typeName.toCharArray(), //
			IIndexConstants.TYPE_SUFFIX, //
			SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);

	IndexQueryRequestor searchRequestor = new IndexQueryRequestor() {

		@Override
		public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant,
				AccessRuleSet access) {
			if (workingCopyPaths.contains(documentPath)) {
				return true; // filter out working copies
			}
			IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(documentPath));
			if (!isDerived(file)) {
				addIssue(type, file.getName());
				return false;
			}
			return true;
		}
	};

	try {
		SearchParticipant searchParticipant = BasicSearchEngine.getDefaultSearchParticipant(); // Java search only
		IJavaSearchScope javaSearchScope = BasicSearchEngine.createJavaSearchScope(sourceFolders.toArray(new IJavaElement[0]));
		PatternSearchJob patternSearchJob = new PatternSearchJob(pattern, searchParticipant, javaSearchScope, searchRequestor);
		indexManager.performConcurrentJob(patternSearchJob, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
		return true;
	} catch (Throwable OperationCanceledException) {
		return false;
	}
}