List of usage examples for org.eclipse.jdt.core ICompilationUnit getType
IType getType(String name);
From source file:com.codenvy.ide.ext.java.server.internal.core.search.BasicSearchEngine.java
License:Open Source License
/** * Searches for all top-level types and member types in the given scope. * The search can be selecting specific types (given a package or a type name * prefix and match modes)./*from w w w .j a va2 s . com*/ * * @see org.eclipse.jdt.core.search.SearchEngine#searchAllTypeNames(char[], int, char[], int, int, * org.eclipse.jdt.core.search.IJavaSearchScope, org.eclipse.jdt.core.search.TypeNameRequestor, int, * org.eclipse.core.runtime.IProgressMonitor) * for detailed comment */ public void searchAllTypeNames(final char[] packageName, final int packageMatchRule, final char[] typeName, final int typeMatchRule, int searchFor, IJavaSearchScope scope, final IRestrictedAccessTypeRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException { // Validate match rule first final int validatedTypeMatchRule = SearchPattern .validateMatchRule(typeName == null ? null : new String(typeName), typeMatchRule); // Debug if (VERBOSE) { Util.verbose( "BasicSearchEngine.searchAllTypeNames(char[], char[], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, " + "int, IProgressMonitor)"); //$NON-NLS-1$ Util.verbose(" - package name: " + (packageName == null ? "null" : new String(packageName))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - package match rule: " + getMatchRuleString(packageMatchRule)); //$NON-NLS-1$ Util.verbose(" - type name: " + (typeName == null ? "null" : new String(typeName))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - type match rule: " + getMatchRuleString(typeMatchRule)); //$NON-NLS-1$ if (validatedTypeMatchRule != typeMatchRule) { Util.verbose(" - validated type match rule: " + getMatchRuleString(validatedTypeMatchRule)); //$NON-NLS-1$ } Util.verbose(" - search for: " + searchFor); //$NON-NLS-1$ Util.verbose(" - scope: " + scope); //$NON-NLS-1$ } if (validatedTypeMatchRule == -1) return; // invalid match rule => return no results final char typeSuffix; switch (searchFor) { case IJavaSearchConstants.CLASS: typeSuffix = IIndexConstants.CLASS_SUFFIX; break; case IJavaSearchConstants.CLASS_AND_INTERFACE: typeSuffix = IIndexConstants.CLASS_AND_INTERFACE_SUFFIX; break; case IJavaSearchConstants.CLASS_AND_ENUM: typeSuffix = IIndexConstants.CLASS_AND_ENUM_SUFFIX; break; case IJavaSearchConstants.INTERFACE: typeSuffix = IIndexConstants.INTERFACE_SUFFIX; break; case IJavaSearchConstants.INTERFACE_AND_ANNOTATION: typeSuffix = IIndexConstants.INTERFACE_AND_ANNOTATION_SUFFIX; break; case IJavaSearchConstants.ENUM: typeSuffix = IIndexConstants.ENUM_SUFFIX; break; case IJavaSearchConstants.ANNOTATION_TYPE: typeSuffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX; break; default: typeSuffix = IIndexConstants.TYPE_SUFFIX; break; } final TypeDeclarationPattern pattern = packageMatchRule == SearchPattern.R_EXACT_MATCH ? new TypeDeclarationPattern(packageName, null, typeName, typeSuffix, validatedTypeMatchRule) : new QualifiedTypeDeclarationPattern(packageName, packageMatchRule, typeName, typeSuffix, validatedTypeMatchRule); // Get working copy path(s). Store in a single string in case of only one to optimize comparison in requestor final HashSet workingCopyPaths = new HashSet(); String workingCopyPath = null; ICompilationUnit[] copies = getWorkingCopies(); final int copiesLength = copies == null ? 0 : copies.length; if (copies != null) { if (copiesLength == 1) { workingCopyPath = copies[0].getPath().toString(); } else { for (int i = 0; i < copiesLength; i++) { ICompilationUnit workingCopy = copies[i]; workingCopyPaths.add(workingCopy.getPath().toString()); } } } final String singleWkcpPath = workingCopyPath; // Index requestor IndexQueryRequestor searchRequestor = new IndexQueryRequestor() { public boolean acceptIndexMatch(String documentPath, SearchPattern indexRecord, SearchParticipant participant, AccessRuleSet access) { // Filter unexpected types TypeDeclarationPattern record = (TypeDeclarationPattern) indexRecord; if (record.enclosingTypeNames == IIndexConstants.ONE_ZERO_CHAR) { return true; // filter out local and anonymous classes } switch (copiesLength) { case 0: break; case 1: if (singleWkcpPath.equals(documentPath)) { return true; // filter out *the* working copy } break; default: if (workingCopyPaths.contains(documentPath)) { return true; // filter out working copies } break; } // Accept document path AccessRestriction accessRestriction = null; if (access != null) { // Compute document relative path int pkgLength = (record.pkg == null || record.pkg.length == 0) ? 0 : record.pkg.length + 1; int nameLength = record.simpleName == null ? 0 : record.simpleName.length; char[] path = new char[pkgLength + nameLength]; int pos = 0; if (pkgLength > 0) { System.arraycopy(record.pkg, 0, path, pos, pkgLength - 1); CharOperation.replace(path, '.', '/'); path[pkgLength - 1] = '/'; pos += pkgLength; } if (nameLength > 0) { System.arraycopy(record.simpleName, 0, path, pos, nameLength); pos += nameLength; } // Update access restriction if path is not empty if (pos > 0) { accessRestriction = access.getViolatedRestriction(path); } } if (match(record.typeSuffix, record.modifiers)) { nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction); } return true; } }; try { if (progressMonitor != null) { progressMonitor.beginTask(Messages.engine_searching, 1000); } // add type names from indexes indexManager.performConcurrentJob( new PatternSearchJob(pattern, getDefaultSearchParticipant(indexManager), // Java search only scope, searchRequestor, indexManager), waitingPolicy, progressMonitor == null ? null : new SubProgressMonitor(progressMonitor, 1000 - copiesLength)); // add type names from working copies if (copies != null) { for (int i = 0; i < copiesLength; i++) { final ICompilationUnit workingCopy = copies[i]; if (scope instanceof HierarchyScope) { if (!((HierarchyScope) scope).encloses(workingCopy, progressMonitor)) continue; } else { if (!scope.encloses(workingCopy)) continue; } final String path = workingCopy.getPath().toString(); if (workingCopy.isConsistent()) { IPackageDeclaration[] packageDeclarations = workingCopy.getPackageDeclarations(); char[] packageDeclaration = packageDeclarations.length == 0 ? CharOperation.NO_CHAR : packageDeclarations[0].getElementName().toCharArray(); IType[] allTypes = workingCopy.getAllTypes(); for (int j = 0, allTypesLength = allTypes.length; j < allTypesLength; j++) { IType type = allTypes[j]; IJavaElement parent = type.getParent(); char[][] enclosingTypeNames; if (parent instanceof IType) { char[] parentQualifiedName = ((IType) parent).getTypeQualifiedName('.') .toCharArray(); enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName); } else { enclosingTypeNames = CharOperation.NO_CHAR_CHAR; } char[] simpleName = type.getElementName().toCharArray(); int kind; if (type.isEnum()) { kind = TypeDeclaration.ENUM_DECL; } else if (type.isAnnotation()) { kind = TypeDeclaration.ANNOTATION_TYPE_DECL; } else if (type.isClass()) { kind = TypeDeclaration.CLASS_DECL; } else /*if (type.isInterface())*/ { kind = TypeDeclaration.INTERFACE_DECL; } if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule, kind, packageDeclaration, simpleName)) { if (nameRequestor instanceof TypeNameMatchRequestorWrapper) { ((TypeNameMatchRequestorWrapper) nameRequestor).requestor.acceptTypeNameMatch( new JavaSearchTypeNameMatch(type, type.getFlags())); } else { nameRequestor.acceptType(type.getFlags(), packageDeclaration, simpleName, enclosingTypeNames, path, null); } } } } else { Parser basicParser = getParser(); org.eclipse.jdt.internal.compiler.env.ICompilationUnit unit = (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) workingCopy; CompilationResult compilationUnitResult = new CompilationResult(unit, 0, 0, this.compilerOptions.maxProblemsPerUnit); CompilationUnitDeclaration parsedUnit = basicParser.dietParse(unit, compilationUnitResult); if (parsedUnit != null) { final char[] packageDeclaration = parsedUnit.currentPackage == null ? CharOperation.NO_CHAR : CharOperation.concatWith(parsedUnit.currentPackage.getImportName(), '.'); class AllTypeDeclarationsVisitor extends ASTVisitor { public boolean visit(TypeDeclaration typeDeclaration, BlockScope blockScope) { return false; // no local/anonymous type } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope compilationUnitScope) { if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule, TypeDeclaration.kind(typeDeclaration.modifiers), packageDeclaration, typeDeclaration.name)) { if (nameRequestor instanceof TypeNameMatchRequestorWrapper) { IType type = workingCopy.getType(new String(typeName)); ((TypeNameMatchRequestorWrapper) nameRequestor).requestor .acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, typeDeclaration.modifiers)); } else { nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration, typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null); } } return true; } public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) { if (match(typeSuffix, packageName, packageMatchRule, typeName, validatedTypeMatchRule, TypeDeclaration.kind(memberTypeDeclaration.modifiers), packageDeclaration, memberTypeDeclaration.name)) { // compute enclosing type names TypeDeclaration enclosing = memberTypeDeclaration.enclosingType; char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR; while (enclosing != null) { enclosingTypeNames = CharOperation.arrayConcat( new char[][] { enclosing.name }, enclosingTypeNames); if ((enclosing.bits & ASTNode.IsMemberType) != 0) { enclosing = enclosing.enclosingType; } else { enclosing = null; } } // report if (nameRequestor instanceof TypeNameMatchRequestorWrapper) { IType type = workingCopy.getType(new String(enclosingTypeNames[0])); for (int j = 1, l = enclosingTypeNames.length; j < l; j++) { type = type.getType(new String(enclosingTypeNames[j])); } ((TypeNameMatchRequestorWrapper) nameRequestor).requestor .acceptTypeNameMatch(new JavaSearchTypeNameMatch(type, 0)); } else { nameRequestor.acceptType(memberTypeDeclaration.modifiers, packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames, path, null); } } return true; } } parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope); } } if (progressMonitor != null) { if (progressMonitor.isCanceled()) throw new OperationCanceledException(); progressMonitor.worked(1); } } } } finally { if (progressMonitor != null) { progressMonitor.done(); } } }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.TypeNameMatchRequestorWrapper.java
License:Open Source License
public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) { // Get type//from www . j a v a 2s. co m try { IType type = null; if (this.handleFactory != null) { //todo openable Openable openable = null;//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 org.eclipse.jdt.internal.core.search.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 } }
From source file:com.codenvy.ide.ext.java.server.internal.core.search.TypeNameMatchRequestorWrapper.java
License:Open Source License
private IType createTypeFromPath(String resourcePath, String simpleTypeName, char[][] enclosingTypeNames) throws JavaModelException { // path to a file in a directory // Optimization: cache package fragment root handle and package handles int rootPathLength = -1; if (this.lastPkgFragmentRootPath == null || !(resourcePath.startsWith(this.lastPkgFragmentRootPath) && (rootPathLength = this.lastPkgFragmentRootPath.length()) > 0 && resourcePath.charAt(rootPathLength) == '/')) { PackageFragmentRoot root = (PackageFragmentRoot) ((AbstractJavaSearchScope) this.scope) .packageFragmentRoot(resourcePath, -1/*not a jar*/, null/*no jar path*/); if (root == null) return null; this.lastPkgFragmentRoot = root; this.lastPkgFragmentRootPath = root.internalPath().toString(); this.packageHandles = new HashtableOfArrayToObject(5); }/*w w w. j a va 2 s .c om*/ // create handle resourcePath = resourcePath.substring(this.lastPkgFragmentRootPath.length() + 1); String[] simpleNames = new Path(resourcePath).segments(); String[] pkgName; int length = simpleNames.length - 1; if (length > 0) { pkgName = new String[length]; System.arraycopy(simpleNames, 0, pkgName, 0, length); } else { pkgName = CharOperation.NO_STRINGS; } IPackageFragment pkgFragment = (IPackageFragment) this.packageHandles.get(pkgName); if (pkgFragment == null) { pkgFragment = ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); this.packageHandles.put(pkgName, pkgFragment); } String simpleName = simpleNames[length]; if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(simpleName)) { ICompilationUnit unit = pkgFragment.getCompilationUnit(simpleName); int etnLength = enclosingTypeNames == null ? 0 : enclosingTypeNames.length; IType type = (etnLength == 0) ? unit.getType(simpleTypeName) : unit.getType(new String(enclosingTypeNames[0])); if (etnLength > 0) { for (int i = 1; i < etnLength; i++) { type = type.getType(new String(enclosingTypeNames[i])); } type = type.getType(simpleTypeName); } return type; } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(simpleName)) { IClassFile classFile = pkgFragment.getClassFile(simpleName); return classFile.getType(); } return null; }
From source file:com.google.gdt.eclipse.appengine.rpc.util.CompilationUnitCreator.java
License:Open Source License
/** * /*from w w w . ja v a2 s . co m*/ * @param type IType - entity to generate request factory code * @param pack IPackageFragment - package for the file * @param name String - name of the file * @param rpcType int - whether proxy, locator, service, request, * requestfactory * @param monitor IProgressMonitor * @return IJavaElement - the created element * @throws CoreException */ public IJavaElement create(IType type, IPackageFragment pack, String name, RpcType rpcType, IProgressMonitor monitor) throws CoreException { IJavaElement element = null; IType createdType = null; ImportsManager imports; ICompilationUnit connectedCU = null; current = type; lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-N$ try { ICompilationUnit parentCU = pack.createCompilationUnit(name + ".java", //$NON-NLS-N$ "", true, new SubProgressMonitor(monitor, 1)); parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); connectedCU = parentCU; IBuffer buffer = parentCU.getBuffer(); String simpleTypeStub = constructSimpleTypeStub(name); String content = CodeGeneration.getCompilationUnitContent(parentCU, null, null, simpleTypeStub, lineDelimiter); buffer.setContents(content); CompilationUnit astRoot = createASTForImports(parentCU); imports = new ImportsManager(astRoot); String typeContent; String annotation = ""; List<String> interfaces = new ArrayList<String>(); boolean isInterface = true; switch (rpcType) { case SERVICE: isInterface = false; break; case LOCATOR: isInterface = false; interfaces.add("com.google.web.bindery.requestfactory.shared.Locator"); //$NON-NLS-N$ if (RequestFactoryUtils.shouldBeProxiedAsAnEntity(type)) { for (IMethod method : type.getMethods()) { if (method.getElementName().equals("getId")) { //$NON-NLS-N$ entityIdType = Signature.toString(method.getReturnType()); } } } else { entityIdType = "Void"; //$NON-NLS-N$ } break; case PROXY: if (RequestFactoryUtils.shouldBeProxiedAsAnEntity(current)) { interfaces.add("com.google.web.bindery.requestfactory.shared.EntityProxy"); //$NON-NLS-N$ } else { interfaces.add("com.google.web.bindery.requestfactory.shared.ValueProxy");//$NON-NLS-N$ } annotation = "@ProxyForName(value=\"" + current.getFullyQualifiedName() //$NON-NLS-N$ + "\",\nlocator = \"" + current.getFullyQualifiedName() + "Locator\")"; break; case REQUEST: interfaces.add("com.google.web.bindery.requestfactory.shared.RequestContext");//$NON-NLS-N$ annotation = "@ServiceName(\"" + serviceName //$NON-NLS-N$ + "\")"; break; case REQ_FACTORY: interfaces.add("com.google.web.bindery.requestfactory.shared.RequestFactory"); //$NON-NLS-N$ break; } typeContent = constructTypeStub(parentCU, name, isInterface, interfaces, annotation, imports); int index = content.lastIndexOf(simpleTypeStub); if (index == -1) { AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0); int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition(); int end = typeNode.getStartPosition() + typeNode.getLength(); buffer.replace(start, end - start, typeContent); } else { buffer.replace(index, simpleTypeStub.length(), typeContent); } createdType = parentCU.getType(name); ICompilationUnit cu = createdType.getCompilationUnit(); imports.create(false, new SubProgressMonitor(monitor, 1)); cu.reconcile(ICompilationUnit.NO_AST, false, null, null); astRoot = createASTForImports(cu); imports = new ImportsManager(astRoot); switch (rpcType) { case SERVICE: constructServiceBody(createdType, imports, new SubProgressMonitor(monitor, 1)); break; case LOCATOR: constructLocatorBody(createdType, imports, new SubProgressMonitor(monitor, 1)); break; case PROXY: constructProxyBody(createdType, imports, new SubProgressMonitor(monitor, 1)); break; case REQUEST: requestTypes.add(createdType); constructRequestBody(createdType, imports, monitor); break; case REQ_FACTORY: constructReqFactoryBody(createdType, imports, new SubProgressMonitor(monitor, 1)); break; } imports.create(false, new SubProgressMonitor(monitor, 1)); removeUnusedImports(cu, getExistingImports(astRoot), false); cu.reconcile(ICompilationUnit.NO_AST, false, null, null); ISourceRange range = createdType.getSourceRange(); IBuffer buf = cu.getBuffer(); String originalContent = buf.getText(range.getOffset(), range.getLength()); String formattedContent = CodegenUtils.format(originalContent, CodeFormatter.K_CLASS_BODY_DECLARATIONS); buf.replace(range.getOffset(), range.getLength(), formattedContent); cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1)); element = cu.getPrimaryElement(); } finally { if (connectedCU != null) { connectedCU.discardWorkingCopy(); } } monitor.done(); return element; }
From source file:com.google.gdt.eclipse.appengine.rpc.wizards.helpers.RpcServiceLayerCreator.java
License:Open Source License
private void createCompilationUnit(IPackageFragment pack, String name, RpcType rpcType, IProgressMonitor monitor) throws CoreException { IType createdType = null;/* w w w . j a v a 2 s. c o m*/ ImportsManager imports; ICompilationUnit connectedCU = null; try { ICompilationUnit parentCU = pack.createCompilationUnit(name + ".java", //$NON-NLS-N$ "", true, new SubProgressMonitor(monitor, 1)); parentCU.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); connectedCU = parentCU; IBuffer buffer = parentCU.getBuffer(); String simpleTypeStub = constructSimpleTypeStub(name); String typeComment = null; switch (rpcType) { case ANNOTATION: typeComment = "/**" + lineDelimiter + " * Annotation on method specifying that the method is a service method" + lineDelimiter + "* and needs to have the corresponding request factory code " + lineDelimiter + "*/"; break; } String content = CodeGeneration.getCompilationUnitContent(parentCU, null, typeComment, simpleTypeStub, lineDelimiter); buffer.setContents(content); CompilationUnit astRoot = createASTForImports(parentCU); // Set<String> existingImports = getExistingImports(astRoot); imports = new ImportsManager(astRoot); String typeContent; String annotation = ""; List<String> interfaces = new ArrayList<String>(); switch (rpcType) { case ANNOTATION: annotation = "@Target(ElementType.METHOD)" + lineDelimiter + "@Retention(RetentionPolicy.CLASS)"; imports.addImport("java.lang.annotation.ElementType"); imports.addImport("java.lang.annotation.Retention"); imports.addImport("java.lang.annotation.RetentionPolicy"); imports.addImport("java.lang.annotation.Target"); break; case LOCATOR: interfaces.add("com.google.web.bindery.requestfactory.shared.Locator"); break; case PROXY: if (RequestFactoryUtils.shouldBeProxiedAsAnEntity(current)) { interfaces.add("com.google.web.bindery.requestfactory.shared.EntityProxy"); //$NON-NLS-N$ } else { interfaces.add("com.google.web.bindery.requestfactory.shared.ValueProxy");//$NON-NLS-N$ } annotation = "@ProxyForName(value=\"" + current.getFullyQualifiedName() //$NON-NLS-N$ + "\",\nlocator = \"" + current.getFullyQualifiedName() + "Locator\")"; break; case REQUEST: interfaces.add("com.google.web.bindery.requestfactory.shared.RequestContext");//$NON-NLS-N$ annotation = "@ServiceName(value=\"" + packageName + "." + serviceName //$NON-NLS-N$ + "\", locator=\"" + packageName + "." + serviceName + "Locator\")"; break; case REQ_FACTORY: interfaces.add("com.google.web.bindery.requestfactory.shared.RequestFactory"); //$NON-NLS-N$ break; case SERVICE_LOCATOR: interfaces.add("com.google.web.bindery.requestfactory.shared.ServiceLocator"); break; } typeContent = constructTypeStub(parentCU, name, rpcType, interfaces, annotation, imports); int index = content.lastIndexOf(simpleTypeStub); if (index == -1) { AbstractTypeDeclaration typeNode = (AbstractTypeDeclaration) astRoot.types().get(0); int start = ((ASTNode) typeNode.modifiers().get(0)).getStartPosition(); int end = typeNode.getStartPosition() + typeNode.getLength(); buffer.replace(start, end - start, typeContent); } else { buffer.replace(index, simpleTypeStub.length(), typeContent); } createdType = parentCU.getType(name); ICompilationUnit cu = createdType.getCompilationUnit(); imports.create(false, new SubProgressMonitor(monitor, 1)); JavaModelUtil.reconcile(cu); astRoot = createASTForImports(cu); imports = new ImportsManager(astRoot); switch (rpcType) { case SERVICE: constructServiceBody(createdType, imports, new SubProgressMonitor(monitor, 1)); break; case LOCATOR: constructLocatorBody(createdType, imports, new SubProgressMonitor(monitor, 1)); break; case PROXY: constructProxyBody(createdType, imports, new SubProgressMonitor(monitor, 1)); break; case REQUEST: requestTypes.add(createdType); constructRequestBody(createdType, imports, monitor); break; case REQ_FACTORY: constructReqFactoryBody(createdType, imports, new SubProgressMonitor(monitor, 1)); break; case SERVICE_LOCATOR: constructServiceLocatorBody(createdType, imports, new SubProgressMonitor(monitor, 1)); break; } imports.create(false, new SubProgressMonitor(monitor, 1)); removeUnusedImports(cu, getExistingImports(astRoot), false); JavaModelUtil.reconcile(cu); ISourceRange range = createdType.getSourceRange(); IBuffer buf = cu.getBuffer(); String originalContent = buf.getText(range.getOffset(), range.getLength()); String formattedContent = format(originalContent, CodeFormatter.K_CLASS_BODY_DECLARATIONS); buf.replace(range.getOffset(), range.getLength(), formattedContent); cu.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1)); if (rpcType == RpcType.SERVICE) { serviceJavaElement = cu.getPrimaryElement(); } } finally { if (connectedCU != null) { connectedCU.discardWorkingCopy(); } monitor.done(); } }
From source file:com.google.gdt.eclipse.core.TypeCreator.java
License:Open Source License
/** * Creates the new type.//from w w w . ja va 2s . com * * 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); JavaModelUtil.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(); } } }
From source file:com.google.gwt.eclipse.core.refactoring.GWTDeleteCompilationUnitParticipantTest.java
License:Open Source License
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());//from w w w . ja va 2 s .com // 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()); }
From source file:com.google.gwt.eclipse.core.refactoring.GWTMoveTypeParticipant.java
License:Open Source License
@Override protected boolean initialize(Object element) { if (!(element instanceof IType)) { return false; }//from w w w. ja v a 2 s .c o m 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; }
From source file:com.google.gwt.eclipse.core.refactoring.JsniTypeReferenceChangeTest.java
License:Open Source License
public void testPerformCompilationUnitChanged() { final ICompilationUnit targetCu = refactorTestClass.getCompilationUnit(); final IType newType = targetCu.getType("RefactorTest2"); GWTTypeRefactoringSupport refactoringSupport = new GWTTypeRefactoringSupport() { @Override//w w w .j ava2s . c om 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()); }
From source file:com.idega.eclipse.ejbwizards.BeanCreator.java
License:Open Source License
protected BeanCreator(IResource resource, boolean isLegacyOrSessionBean) { this.isLegacyEntity = isLegacyOrSessionBean; this.isSessionBean = isLegacyOrSessionBean; String resourceName = resource.getName(); IJavaElement javaElement = JavaCore.create(resource); if (javaElement instanceof ICompilationUnit) { String typeName = resourceName.substring(0, resourceName.indexOf(".java")); ICompilationUnit compilationUnit = (ICompilationUnit) javaElement; fillImportMap(compilationUnit);/* w w w. j a v a 2 s .com*/ this.type = compilationUnit.getType(typeName); } Map map = javaElement.getJavaProject().getOptions(false); if (map != null) { String value = (String) map.get("org.eclipse.jdt.core.compiler.compliance"); if (value != null) { float version = Float.parseFloat(value); if (version > 1.4) { this.isJDK1_5 = true; } } } try { generateCode(); } catch (JavaModelException jme) { jme.printStackTrace(System.err); } }