private IField getFieldInWorkingCopy( ICompilationUnit newWorkingCopyOfDeclaringCu, String elementName) { IType type = fField.getDeclaringType(); IType typeWc = (IType) JavaModelUtil.findInCompilationUnit(newWorkingCopyOfDeclaringCu, type); if (typeWc == null) return null; return typeWc.getField(elementName); }
public Object convertToObject(String parameterValue) throws ParameterValueConversionException { assertWellFormed(parameterValue != null); final int projectEndPosition = parameterValue.indexOf(PROJECT_END_CHAR); assertWellFormed(projectEndPosition != -1); String projectName = parameterValue.substring(0, projectEndPosition); String javaElementRef = parameterValue.substring(projectEndPosition + 1); IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); assertExists(javaModel); IJavaProject javaProject = javaModel.getJavaProject(projectName); assertExists(javaProject); final int typeEndPosition = javaElementRef.indexOf(TYPE_END_CHAR); String typeName; if (typeEndPosition == -1) { typeName = javaElementRef; } else { typeName = javaElementRef.substring(0, typeEndPosition); } IType type = null; try { type = javaProject.findType(typeName); } catch (JavaModelException ex) { // type == null } assertExists(type); if (typeEndPosition == -1) { return type; } String memberRef = javaElementRef.substring(typeEndPosition + 1); final int paramStartPosition = memberRef.indexOf(PARAM_START_CHAR); if (paramStartPosition == -1) { IField field = type.getField(memberRef); assertExists(field); return field; } String methodName = memberRef.substring(0, paramStartPosition); String signature = memberRef.substring(paramStartPosition); String[] parameterTypes = null; try { parameterTypes = Signature.getParameterTypes(signature); } catch (IllegalArgumentException ex) { // parameterTypes == null } assertWellFormed(parameterTypes != null); IMethod method = type.getMethod(methodName, parameterTypes); assertExists(method); return method; }
public static IField[] getFields(IType type, String[] names) { if (names == null) return new IField[0]; Set fields = new HashSet(); for (int i = 0; i < names.length; i++) { IField field = type.getField(names[i]); assertTrue("field " + field.getElementName() + " does not exist", field.exists()); fields.add(field); } return (IField[]) fields.toArray(new IField[fields.size()]); }
/** * Returns the activities associated with the given layout file. Makes an educated guess by * peeking at the usages of the R.layout.name field corresponding to the layout and if it finds a * usage. * * @param project the project containing the layout * @param layoutName the layout whose activity we want to look up * @param pkg the package containing activities * @return the activity name */ @NonNull public static List<String> guessActivities(IProject project, String layoutName, String pkg) { final LinkedList<String> activities = new LinkedList<String>(); SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { Object element = match.getElement(); if (element instanceof IMethod) { IMethod method = (IMethod) element; IType declaringType = method.getDeclaringType(); String fqcn = declaringType.getFullyQualifiedName(); if ((declaringType.getSuperclassName() != null && declaringType.getSuperclassName().endsWith("Activity")) // $NON-NLS-1$ || method.getElementName().equals("onCreate")) { // $NON-NLS-1$ activities.addFirst(fqcn); } else { activities.addLast(fqcn); } } } }; try { IJavaProject javaProject = BaseProjectHelper.getJavaProject(project); if (javaProject == null) { return Collections.emptyList(); } // TODO - look around a bit more and see if we can figure out whether the // call if from within a setContentView call! // Search for which java classes call setContentView(R.layout.layoutname); String typeFqcn = "R.layout"; // $NON-NLS-1$ if (pkg != null) { typeFqcn = pkg + '.' + typeFqcn; } IType type = javaProject.findType(typeFqcn); if (type != null) { IField field = type.getField(layoutName); if (field.exists()) { SearchPattern pattern = SearchPattern.createPattern(field, REFERENCES); try { search(requestor, javaProject, pattern); } catch (OperationCanceledException canceled) { // pass } } } } catch (CoreException e) { AdtPlugin.log(e, null); } return activities; }
public void testMissingField() { try { IType type = fProject.findType("tests.apiusescan.coretestproject.TestInterfaceImpl"); IField field = type.getField("fField"); field.rename("fField1", true, null); ExternalDependencyTestUtils.waitForBuild(); IMarker[] markers = type.getUnderlyingResource() .findMarkers( IApiMarkerConstants.API_USESCAN_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); assertEquals( "No API Use Scan problem marker found for missing field TestInterfaceImpl.fField", 1, markers.length); String typeName = markers[0].getAttribute(IApiMarkerConstants.API_USESCAN_TYPE, null); assertEquals( "Marker for missing field TestInterfaceImpl.fField not found", "tests.apiusescan.coretestproject.TestInterfaceImpl", typeName); type = fProject.findType("tests.apiusescan.coretestproject.TestInterfaceImpl"); field = type.getField("fField1"); field.rename("fField", true, null); ExternalDependencyTestUtils.waitForBuild(); markers = type.getUnderlyingResource() .findMarkers( IApiMarkerConstants.API_USESCAN_PROBLEM_MARKER, false, IResource.DEPTH_ZERO); assertEquals( "API Use Scan problem marker for missing field TestInterfaceImpl.fField did not clear.", 0, markers.length); } catch (JavaModelException e) { fail(e.getMessage()); } catch (CoreException e) { fail(e.getMessage()); } }
/** * Adds a static import for the member with name <code>qualifiedMemberName</code>. The member is * either a static field or a static method or a '*' to import all static members of a type. * * @param qualifiedMemberName the fully qualified name of the member to import or a qualified type * name plus a '.*' suffix. * @return returns either the simple member name if the import was successful or else the * qualified name. * @since 3.4 */ public String addStaticImport(String qualifiedMemberName) { if (isReadOnly()) return qualifiedMemberName; ICompilationUnit cu = getCompilationUnit(); if (cu == null) return qualifiedMemberName; int memberOffset = qualifiedMemberName.lastIndexOf('.'); if (memberOffset == -1) return qualifiedMemberName; String typeName = qualifiedMemberName.substring(0, memberOffset); String memberName = qualifiedMemberName.substring(memberOffset + 1, qualifiedMemberName.length()); try { boolean isField; if ("*".equals(memberName)) { // $NON-NLS-1$ isField = true; } else { IJavaProject javaProject = cu.getJavaProject(); IType type = javaProject.findType(typeName); if (type == null) return qualifiedMemberName; IField field = type.getField(memberName); if (field.exists()) { isField = true; } else if (hasMethod(type, memberName)) { isField = false; } else { return qualifiedMemberName; } } CompilationUnit root = getASTRoot(cu); if (fImportRewrite == null) { if (root == null) { fImportRewrite = StubUtility.createImportRewrite(cu, true); } else { fImportRewrite = StubUtility.createImportRewrite(root, true); } } ImportRewriteContext context; if (root == null) context = null; else context = new ContextSensitiveImportRewriteContext(root, getCompletionOffset(), fImportRewrite); return fImportRewrite.addStaticImport(typeName, memberName, isField, context); } catch (JavaModelException e) { handleException(null, e); return typeName; } }
public void testCustomPreferences() throws Exception { DiaGenSource s = createLibraryGen(false); final GenDiagram gd = s.getGenDiagram(); GenCustomPreferencePage pp = GMFGenFactory.eINSTANCE.createGenCustomPreferencePage(); if (gd.getPreferencePages().isEmpty()) { gd.getPreferencePages().add(pp); } else { gd.getPreferencePages().get(0).getChildren().add(pp); } pp.setGenerateBoilerplate(true); pp.setName("Page Name"); pp.setQualifiedClassName( gd.getEditorGen().getEditor().getPackageName() + ".CustomPreferencePage"); GenPreference p1 = GMFGenFactory.eINSTANCE.createGenPreference(); p1.setName("PREF_XXX_ONE"); p1.setDefaultValue("\"XXX_ONE_DEFAULT\""); GenPreference p2 = GMFGenFactory.eINSTANCE.createGenPreference(); p2.setName("NO_PREFIX_XXX_TWO"); p2.setKey("KEY.XXX.TWO"); pp.getPreferences().add(p1); pp.getPreferences().add(p2); // generateAndCompile(s); // IProject generatedProject = ResourcesPlugin.getWorkspace().getRoot().getProject(gd.getEditorGen().getPlugin().getID()); IFile file_pp = generatedProject.getFile("/src/" + pp.getQualifiedClassName().replace('.', '/') + ".java"); assertTrue(file_pp.exists()); ICompilationUnit cuPage = (ICompilationUnit) JavaCore.create(file_pp); assertNotNull(cuPage); IType mainClass = cuPage.getTypes()[0]; assertNotNull(mainClass); assertEquals(2, mainClass.getFields().length); final IField p1field = mainClass.getField(p1.getName()); final IField p2field = mainClass.getField(p2.getName()); assertTrue(Flags.isPublic(p1field.getFlags())); assertTrue(Flags.isStatic(p1field.getFlags())); assertTrue(Flags.isPublic(p2field.getFlags())); assertTrue(Flags.isStatic(p2field.getFlags())); assertEquals('"' + p1.getKey() + '"', p1field.getConstant()); assertEquals('"' + p2.getKey() + '"', p2field.getConstant()); IMethod initMethod = mainClass.getMethod( "initDefaults", new String[] {"Q" + IPreferenceStore.class.getSimpleName() + ";"}); assertNotNull(initMethod); String methodText = initMethod.getSource(); assertTrue(methodText.indexOf(p1.getName()) != -1); assertTrue(methodText.indexOf(p1.getDefaultValue()) != -1); assertTrue(methodText.indexOf(p2.getName()) == -1); }
/** * Builds a string of the constructor parameters. * * @param type The type containing the fields. * @param fields The array of fields. * @return The parameters string. */ protected String buildParams(IType type, String[] fields) throws Exception { StringBuffer params = new StringBuffer(); for (int ii = 0; ii < fields.length; ii++) { if (ii != 0) { params.append(", "); } IField field = type.getField(fields[ii]); params .append(Signature.getSignatureSimpleName(field.getTypeSignature())) .append(' ') .append(field.getElementName()); } return params.toString(); }
/** * Returns the source range to use for the given field within the given {@link IType} * * @param type the type to look in for the given {@link IApiField} * @param reference the reference the field is involved in * @param field the field to find the range for * @return the {@link ISourceRange} in the given {@link IType} that encloses the given {@link * IApiField} * @throws JavaModelException * @throws CoreException */ protected Position getSourceRangeForField(IType type, IReference reference, IApiField field) throws JavaModelException, CoreException { IField javaField = type.getField(field.getName()); Position pos = null; if (javaField.exists()) { ISourceRange range = javaField.getNameRange(); if (range != null) { pos = new Position(range.getOffset(), range.getLength()); } } if (pos == null) { return defaultSourcePosition(type, reference); } return pos; }
private static void checkFieldInType( IType destinationType, RefactoringStatus result, IField field) throws JavaModelException { IField destinationTypeField = destinationType.getField(field.getElementName()); if (!destinationTypeField.exists()) return; String message = Messages.format( RefactoringCoreMessages.MemberCheckUtil_field_exists, new String[] { BasicElementLabels.getJavaElementName(field.getElementName()), getQualifiedLabel(destinationType) }); RefactoringStatusContext context = JavaStatusContext.create( destinationType.getCompilationUnit(), destinationTypeField.getSourceRange()); result.addError(message, context); }
private RefactoringStatus checkEnclosingHierarchy() { IType current = fField.getDeclaringType(); if (Checks.isTopLevel(current)) return null; RefactoringStatus result = new RefactoringStatus(); while (current != null) { IField otherField = current.getField(getNewElementName()); if (otherField.exists()) { String msg = Messages.format( RefactoringCoreMessages.RenameFieldRefactoring_hiding2, new String[] { BasicElementLabels.getJavaElementName(getNewElementName()), BasicElementLabels.getJavaElementName(current.getFullyQualifiedName('.')), BasicElementLabels.getJavaElementName(otherField.getElementName()) }); result.addWarning(msg, JavaStatusContext.create(otherField)); } current = current.getDeclaringType(); } return result; }
public void run(IMarker marker) { IFile file = (IFile) javaDeclaration.getResource(); try { ICompilationUnit original = EclipseUtil.getCompilationUnit(file); if (original == null) { return; } ICompilationUnit compilationUnit = original.getWorkingCopy(new NullProgressMonitor()); String lineDelim = JavaPropertyGenerator.getLineDelimiterUsed(compilationUnit); Hashtable<String, String> options = JavaCore.getOptions(); int tabSize = new Integer(options.get("org.eclipse.jdt.core.formatter.tabulation.size")); StringBuffer tabBuf = new StringBuffer(); for (int i = 0; i < tabSize; i++) tabBuf.append(" "); String tab = tabBuf.toString(); IType type = compilationUnit.findPrimaryType(); IField field = type.getField(property.getName()); String propertyType = ""; if (field != null && field.exists()) { propertyType = field.getTypeSignature(); } else { propertyType = "String"; // $NON-NLS-1$ StringBuffer buf = new StringBuffer(); buf.append( tab + "private " + propertyType + " " + property.getName() + ";"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append(lineDelim); field = type.createField(buf.toString(), null, false, new NullProgressMonitor()); if (field != null) { IBuffer buffer = compilationUnit.getBuffer(); buffer.replace( field.getSourceRange().getOffset(), field.getSourceRange().getLength(), buf.toString()); synchronized (compilationUnit) { compilationUnit.reconcile(ICompilationUnit.NO_AST, true, null, null); } } } IMethod oldMethod = GetterSetterUtil.getSetter(field); if (oldMethod == null || !oldMethod.exists()) { String setterName = GetterSetterUtil.getSetterName(field, null); // JavaPropertyGenerator.createSetter(compilationUnit, type, "public", // field.getTypeSignature(), setterName, lineDelim); String stub = GetterSetterUtil.getSetterStub(field, setterName, true, Flags.AccPublic); IMethod newMethod = type.createMethod(stub, null, false, new NullProgressMonitor()); if (newMethod != null) { IBuffer buffer = compilationUnit.getBuffer(); // format StringBuffer buf = new StringBuffer(); buf.append(lineDelim); buf.append( tab + "public void " + setterName + "(" + propertyType + " " + property.getName() + "){"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ buf.append(lineDelim); buf.append(tab + tab + "this." + property.getName() + " = " + property.getName() + ";"); buf.append(lineDelim); buf.append(tab + "}"); buf.append(lineDelim); buffer.replace( newMethod.getSourceRange().getOffset(), newMethod.getSourceRange().getLength(), buf.toString()); } } compilationUnit.commitWorkingCopy(false, new NullProgressMonitor()); compilationUnit.discardWorkingCopy(); } catch (CoreException ex) { SeamGuiPlugin.getPluginLog().logError(ex); } }
/** {@inheritDoc} */ public Object execute(CommandLine commandLine) throws Exception { String project = commandLine.getValue(Options.PROJECT_OPTION); String file = commandLine.getValue(Options.FILE_OPTION); String propertiesOption = commandLine.getValue(Options.PROPERTIES_OPTION); String[] properties = {}; if (propertiesOption != null) { properties = StringUtils.split(propertiesOption, ','); } int offset = getOffset(commandLine); // validate supplied fields. ICompilationUnit src = JavaUtils.getCompilationUnit(project, file); IType type = TypeUtils.getType(src, offset); for (int ii = 0; ii < properties.length; ii++) { if (!type.getField(properties[ii]).exists()) { throw new RuntimeException( Services.getMessage("field.not.found", properties[ii], type.getElementName())); } } // check if constructor already exists. IMethod method = null; if (properties.length == 0) { method = type.getMethod(type.getElementName(), null); } else { String[] fieldSigs = new String[properties.length]; for (int ii = 0; ii < properties.length; ii++) { fieldSigs[ii] = type.getField(properties[ii]).getTypeSignature(); } method = type.getMethod(type.getElementName(), fieldSigs); } if (method.exists()) { throw new RuntimeException( Services.getMessage( "constructor.already.exists", type.getElementName() + " (" + buildParams(type, properties) + ")")); } // find the sibling to insert before. IJavaElement sibling = null; IMethod[] methods = type.getMethods(); for (int ii = 0; ii < methods.length; ii++) { if (methods[ii].isConstructor()) { sibling = ii < methods.length - 1 ? methods[ii + 1] : null; } } // insert before any other methods or inner classes if any. if (sibling == null) { if (methods.length > 0) { sibling = methods[0]; } else { IType[] types = type.getTypes(); sibling = types != null && types.length > 0 ? types[0] : null; } } HashMap<String, Object> values = new HashMap<String, Object>(); values.put("type", type.getElementName()); boolean hasProperties = properties != null && properties.length > 0; values.put("fields", hasProperties ? properties : null); values.put("params", hasProperties ? buildParams(type, properties) : StringUtils.EMPTY); PluginResources resources = (PluginResources) Services.getPluginResources(PluginResources.NAME); String constructor = TemplateUtils.evaluate(resources, TEMPLATE, values); Position position = TypeUtils.getPosition(type, type.createMethod(constructor, sibling, false, null)); JavaUtils.format( src, CodeFormatter.K_COMPILATION_UNIT, position.getOffset(), position.getLength()); return null; }