List of usage examples for org.eclipse.jdt.core IType isEnum
boolean isEnum() throws JavaModelException;
From source file:at.bestsolution.efxclipse.tooling.fxgraph.ui.util.JDTHelper.java
License:Open Source License
private TypeData createData(List<IMethod> allMethods, IJavaProject jproject) throws JavaModelException { TypeData d = new TypeData(); for (IMethod m : allMethods) { if (!Flags.isPublic(m.getFlags())) { continue; }/*from w ww .ja v a2 s.c o m*/ if (m.getElementName().startsWith("impl_") || m.getElementName().startsWith("getImpl_")) { continue; } if (m.getElementName().startsWith("get") && m.getParameterNames().length == 0) { String returnSignature = Signature.toString(m.getReturnType()); if (returnSignature.startsWith("javafx.event.EventHandler<? super ") || returnSignature.startsWith("javafx.event.EventHandler<")) { String eventType; if (returnSignature.startsWith("javafx.event.EventHandler<? super ")) { eventType = returnSignature.substring("javafx.event.EventHandler<? super ".length(), returnSignature.length() - 1); } else { eventType = returnSignature.substring("javafx.event.EventHandler<".length(), returnSignature.length() - 1); } EventValueProperty p = new EventValueProperty(m, extractAttributename(m.getElementName()), m.getParent().getElementName(), eventType); d.properties.add(p); } else { String propName = extractAttributename(m.getElementName()); String ownerName = m.getParent().getElementName(); boolean isReadonly = isReadonlySetter(propName, allMethods); if ("double".equals(returnSignature) || "float".equals(returnSignature)) { if (!isReadonly) { FloatingValueProperty p = new FloatingValueProperty(m, propName, ownerName, returnSignature); d.properties.add(p); } } else if ("int".equals(returnSignature) || "long".equals(returnSignature) || "short".equals(returnSignature) || "byte".equals(returnSignature) || "char".equals(returnSignature)) { if (!isReadonly) { IntegerValueProperty p = new IntegerValueProperty(m, propName, ownerName, returnSignature); d.properties.add(p); } } else { IType type; if (returnSignature.indexOf('<') == -1) { type = jproject.findType(returnSignature); } else { type = jproject.findType(returnSignature.substring(0, returnSignature.indexOf('<'))); } if (type == null) { continue; } if (type.isEnum()) { if (!isReadonly) { EnumValueProperty p = new EnumValueProperty(m, propName, ownerName, returnSignature, type); d.properties.add(p); } } else { boolean isLists = false; boolean isMap = false; if ("java.util.List".equals(type.getFullyQualifiedName())) { isLists = true; } else { for (String i : type.getSuperInterfaceNames()) { if (i.equals("java.util.List")) { isLists = true; } } } if (!isLists) { if ("java.util.Map".equals(type.getFullyQualifiedName())) { isMap = true; } else { for (String i : type.getSuperInterfaceNames()) { if (i.equals("java.util.Map")) { isMap = true; } } } } if (isLists) { String listType; if (returnSignature.indexOf('<') != -1) { listType = returnSignature.substring(returnSignature.indexOf('<') + 1, returnSignature.lastIndexOf('>')); } else { listType = "?"; } if (!propName.endsWith("Unmodifiable")) { ListValueProperty p = new ListValueProperty(m, propName, ownerName, listType, isReadonly); d.properties.add(p); } } else if (isMap) { MapValueProperty p = new MapValueProperty(m, propName, ownerName); d.properties.add(p); } else if (type.getFullyQualifiedName().equals("java.lang.String")) { if (!isReadonly) { StringValueProperty p = new StringValueProperty(m, propName, ownerName, returnSignature); d.properties.add(p); } } else { if (!isReadonly) { List<Proposal> props = getProposals(type, jproject); ElementValueProperty p = new ElementValueProperty(m, propName, ownerName, returnSignature, props); d.properties.add(p); } } } } } } else if (m.getElementName().startsWith("is") && m.getParameterNames().length == 0 && "Z".equals(m.getReturnType())) { String propName = extractAttributename(m.getElementName()); boolean isReadonly = isReadonlySetter(propName, allMethods); if (!isReadonly) { BooleanValueProperty p = new BooleanValueProperty(m, propName, m.getParent().getElementName(), "boolean"); d.properties.add(p); } } } return d; }
From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java
License:Open Source License
/** * Appends the label for a type. Considers the T_* flags. * * @param type the element to render// ww w . j ava 2s. c o m * @param flags the rendering flags. Flags with names starting with 'T_' are considered. */ public void appendTypeLabel(IType type, long flags) { if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED)) { IPackageFragment pack = type.getPackageFragment(); if (!pack.isDefaultPackage()) { appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS)); fBuffer.append('.'); } } IJavaElement parent = type.getParent(); if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.T_CONTAINER_QUALIFIED)) { IType declaringType = type.getDeclaringType(); if (declaringType != null) { appendTypeLabel(declaringType, JavaElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS)); fBuffer.append('.'); } int parentType = parent.getElementType(); if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) { // anonymous or local appendElementLabel(parent, 0); fBuffer.append('.'); } } String typeName; boolean isAnonymous = false; if (type.isLambda()) { typeName = "() -> {...}"; //$NON-NLS-1$ try { String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures(); if (superInterfaceSignatures.length > 0) { typeName = typeName + ' ' + getSimpleTypeName(type, superInterfaceSignatures[0]); } } catch (JavaModelException e) { //ignore } } else { typeName = getElementName(type); try { isAnonymous = type.isAnonymous(); } catch (JavaModelException e1) { // should not happen, but let's play safe: isAnonymous = typeName.length() == 0; } if (isAnonymous) { try { if (parent instanceof IField && type.isEnum()) { typeName = '{' + JavaElementLabels.ELLIPSIS_STRING + '}'; } else { String supertypeName = null; String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures(); if (superInterfaceSignatures.length > 0) { supertypeName = getSimpleTypeName(type, superInterfaceSignatures[0]); } else { String supertypeSignature = type.getSuperclassTypeSignature(); if (supertypeSignature != null) { supertypeName = getSimpleTypeName(type, supertypeSignature); } } if (supertypeName == null) { typeName = JavaUIMessages.JavaElementLabels_anonym; } else { typeName = Messages.format(JavaUIMessages.JavaElementLabels_anonym_type, supertypeName); } } } catch (JavaModelException e) { //ignore typeName = JavaUIMessages.JavaElementLabels_anonym; } } } fBuffer.append(typeName); if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS)) { if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && type.isResolved()) { BindingKey key = new BindingKey(type.getKey()); if (key.isParameterizedType()) { String[] typeArguments = key.getTypeArguments(); appendTypeArgumentSignaturesLabel(type, typeArguments, flags); } else { String[] typeParameters = Signature.getTypeParameters(key.toSignature()); appendTypeParameterSignaturesLabel(typeParameters, flags); } } else if (type.exists()) { try { appendTypeParametersLabels(type.getTypeParameters(), flags); } catch (JavaModelException e) { // ignore } } } // category if (getFlag(flags, JavaElementLabels.T_CATEGORY) && type.exists()) { try { appendCategoryLabel(type, flags); } catch (JavaModelException e) { // ignore } } // post qualification if (getFlag(flags, JavaElementLabels.T_POST_QUALIFIED)) { int offset = fBuffer.length(); fBuffer.append(JavaElementLabels.CONCAT_STRING); IType declaringType = type.getDeclaringType(); if (declaringType == null && type.isBinary() && isAnonymous) { // workaround for Bug 87165: [model] IType#getDeclaringType() does not work for anonymous binary type String tqn = type.getTypeQualifiedName(); int lastDollar = tqn.lastIndexOf('$'); if (lastDollar != 1) { String declaringTypeCF = tqn.substring(0, lastDollar) + ".class"; //$NON-NLS-1$ declaringType = type.getPackageFragment().getClassFile(declaringTypeCF).getType(); try { ISourceRange typeSourceRange = type.getSourceRange(); if (declaringType.exists() && SourceRange.isAvailable(typeSourceRange)) { IJavaElement realParent = declaringType.getTypeRoot() .getElementAt(typeSourceRange.getOffset() - 1); if (realParent != null) { parent = realParent; } } } catch (JavaModelException e) { // ignore } } } if (declaringType != null) { appendTypeLabel(declaringType, JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); int parentType = parent.getElementType(); if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) { // anonymous or local fBuffer.append('.'); appendElementLabel(parent, 0); } } else { appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS); } // if (getFlag(flags, JavaElementLabels.COLORIZE)) { // fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE); // } } }
From source file:com.codenvy.ide.ext.java.server.internal.core.BinaryMethod.java
License:Open Source License
public ILocalVariable[] getParameters() throws JavaModelException { IBinaryMethod info = (IBinaryMethod) getElementInfo(); int length = this.parameterTypes.length; if (length == 0) { return LocalVariable.NO_LOCAL_VARIABLES; }/* w w w. j a va 2 s . c o m*/ ILocalVariable[] localVariables = new ILocalVariable[length]; char[][] argumentNames = info.getArgumentNames(); if (argumentNames == null || argumentNames.length < length) { argumentNames = new char[length][]; for (int j = 0; j < length; j++) { argumentNames[j] = ("arg" + j).toCharArray(); //$NON-NLS-1$ } } int startIndex = 0; try { if (isConstructor()) { IType declaringType = this.getDeclaringType(); if (declaringType.isEnum()) { startIndex = 2; } else if (declaringType.isMember() && !Flags.isStatic(declaringType.getFlags())) { startIndex = 1; } } } catch (JavaModelException e) { // ignore } for (int i = 0; i < length; i++) { if (i < startIndex) { LocalVariable localVariable = new LocalVariable(this, manager, new String(argumentNames[i]), 0, -1, 0, -1, this.parameterTypes[i], null, -1, true); localVariables[i] = localVariable; localVariable.annotations = Annotation.NO_ANNOTATIONS; } else { LocalVariable localVariable = new LocalVariable(this, manager, new String(argumentNames[i]), 0, -1, 0, -1, this.parameterTypes[i], null, -1, true); localVariables[i] = localVariable; IAnnotation[] annotations = getAnnotations(localVariable, info.getParameterAnnotations(i - startIndex)); localVariable.annotations = annotations; } } return localVariables; }
From source file:com.codenvy.ide.ext.java.server.internal.core.BinaryMethod.java
License:Open Source License
public String[] getParameterNames() throws JavaModelException { if (this.parameterNames != null) return this.parameterNames; // force source mapping if not already done IType type = (IType) getParent();//from w ww. j a va 2 s .co m SourceMapper mapper = getSourceMapper(); if (mapper != null) { char[][] paramNames = mapper.getMethodParameterNames(this); // map source and try to find parameter names if (paramNames == null) { IBinaryType info = (IBinaryType) ((BinaryType) getDeclaringType()).getElementInfo(); char[] source = mapper.findSource(type, info); if (source != null) { mapper.mapSource(type, source, info); } paramNames = mapper.getMethodParameterNames(this); } // if parameter names exist, convert parameter names to String array if (paramNames != null) { String[] names = new String[paramNames.length]; for (int i = 0; i < paramNames.length; i++) { names[i] = new String(paramNames[i]); } return this.parameterNames = names; } } // try to see if we can retrieve the names from the attached javadoc IBinaryMethod info = (IBinaryMethod) getElementInfo(); // https://bugs.eclipse.org/bugs/show_bug.cgi?id=316937 // Use Signature#getParameterCount() only if the argument names are not already available. int paramCount = Signature.getParameterCount(new String(info.getMethodDescriptor())); if (this.isConstructor()) { final IType declaringType = this.getDeclaringType(); if (declaringType.isMember() && !Flags.isStatic(declaringType.getFlags())) { paramCount--; // remove synthetic argument from constructor param count } else if (declaringType.isEnum()) { if (paramCount >= 2) // https://bugs.eclipse.org/bugs/show_bug.cgi?id=436347 paramCount -= 2; } } if (paramCount != 0) { // don't try to look for javadoc for synthetic methods int modifiers = getFlags(); if ((modifiers & ClassFileConstants.AccSynthetic) != 0) { return this.parameterNames = getRawParameterNames(paramCount); } JavadocContents javadocContents = null; IType declaringType = getDeclaringType(); JavaModelManager.PerProjectInfo projectInfo = manager.getPerProjectInfoCheckExistence(); synchronized (projectInfo.javadocCache) { javadocContents = (JavadocContents) projectInfo.javadocCache.get(declaringType); if (javadocContents == null) { projectInfo.javadocCache.put(declaringType, BinaryType.EMPTY_JAVADOC); } } String methodDoc = null; if (javadocContents == null) { long timeOut = 50; // default value try { String option = getJavaProject() .getOption(JavaCore.TIMEOUT_FOR_PARAMETER_NAME_FROM_ATTACHED_JAVADOC, true); if (option != null) { timeOut = Long.parseLong(option); } } catch (NumberFormatException e) { // ignore } if (timeOut == 0) { // don't try to fetch the values and don't cache either (https://bugs.eclipse.org/bugs/show_bug.cgi?id=329671) return getRawParameterNames(paramCount); } final class ParametersNameCollector { String javadoc; public void setJavadoc(String s) { this.javadoc = s; } public String getJavadoc() { return this.javadoc; } } /* * The declaring type is not in the cache yet. The thread wil retrieve the javadoc contents */ final ParametersNameCollector nameCollector = new ParametersNameCollector(); Thread collect = new Thread() { public void run() { try { // this call has a side-effect on the per project info cache nameCollector.setJavadoc(BinaryMethod.this.getAttachedJavadoc(null)); } catch (JavaModelException e) { // ignore } synchronized (nameCollector) { nameCollector.notify(); } } }; collect.start(); synchronized (nameCollector) { try { nameCollector.wait(timeOut); } catch (InterruptedException e) { // ignore } } methodDoc = nameCollector.getJavadoc(); } else if (javadocContents != BinaryType.EMPTY_JAVADOC) { // need to extract the part relative to the binary method since javadoc contains the javadoc for the declaring type try { methodDoc = javadocContents.getMethodDoc(this); } catch (JavaModelException e) { javadocContents = null; } } if (methodDoc != null) { int indexOfOpenParen = methodDoc.indexOf('('); // Annotations may have parameters, so make sure we are parsing the actual method parameters. if (info.getAnnotations() != null) { while (indexOfOpenParen != -1 && !isOpenParenForMethod(methodDoc, getElementName(), indexOfOpenParen)) { indexOfOpenParen = methodDoc.indexOf('(', indexOfOpenParen + 1); } } if (indexOfOpenParen != -1) { final int indexOfClosingParen = methodDoc.indexOf(')', indexOfOpenParen); if (indexOfClosingParen != -1) { final char[] paramsSource = CharOperation.replace( methodDoc.substring(indexOfOpenParen + 1, indexOfClosingParen).toCharArray(), " ".toCharArray(), //$NON-NLS-1$ new char[] { ' ' }); final char[][] params = splitParameters(paramsSource, paramCount); final int paramsLength = params.length; String[] names = new String[paramsLength]; for (int i = 0; i < paramsLength; i++) { final char[] param = params[i]; int indexOfSpace = CharOperation.lastIndexOf(' ', param); if (indexOfSpace != -1) { names[i] = String.valueOf(param, indexOfSpace + 1, param.length - indexOfSpace - 1); } else { names[i] = "arg" + i; //$NON-NLS-1$ } } return this.parameterNames = names; } } } // let's see if we can retrieve them from the debug infos char[][] argumentNames = info.getArgumentNames(); if (argumentNames != null && argumentNames.length == paramCount) { String[] names = new String[paramCount]; for (int i = 0; i < paramCount; i++) { names[i] = new String(argumentNames[i]); } return this.parameterNames = names; } } // If still no parameter names, produce fake ones, but don't cache them (https://bugs.eclipse.org/bugs/show_bug.cgi?id=329671) return getRawParameterNames(paramCount); // throw new UnsupportedOperationException(); }
From source file:com.codenvy.ide.ext.java.server.internal.core.ClassFileInfo.java
License:Open Source License
/** * Creates the handles and infos for the methods of the given binary type. * Adds new handles to the given vector. *///from w w w . j a v a 2 s . c om private void generateMethodInfos(IType type, IBinaryType typeInfo, HashMap newElements, ArrayList childrenHandles, ArrayList typeParameterHandles) { IBinaryMethod[] methods = typeInfo.getMethods(); if (methods == null) { return; } for (int i = 0, methodCount = methods.length; i < methodCount; i++) { IBinaryMethod methodInfo = methods[i]; final boolean isConstructor = methodInfo.isConstructor(); boolean isEnum = false; try { isEnum = type.isEnum(); } catch (JavaModelException e) { // ignore } // TODO (jerome) filter out synthetic members // indexer should not index them as well // if ((methodInfo.getModifiers() & IConstants.AccSynthetic) != 0) continue; // skip synthetic boolean useGenericSignature = true; char[] signature = methodInfo.getGenericSignature(); String[] pNames = null; if (signature == null) { useGenericSignature = false; signature = methodInfo.getMethodDescriptor(); if (isEnum && isConstructor) { pNames = Signature.getParameterTypes(new String(signature)); int length = pNames.length - 2; if (length >= 0) // https://bugs.eclipse.org/bugs/show_bug.cgi?id=436347 System.arraycopy(pNames, 2, pNames = new String[length], 0, length); } } String selector = new String(methodInfo.getSelector()); if (isConstructor) { selector = type.getElementName(); } try { if (!(isEnum && isConstructor && !useGenericSignature)) { pNames = Signature.getParameterTypes(new String(signature)); } if (isConstructor && useGenericSignature && type.isMember() && !Flags.isStatic(type.getFlags())) { int length = pNames.length; System.arraycopy(pNames, 0, (pNames = new String[length + 1]), 1, length); char[] descriptor = methodInfo.getMethodDescriptor(); final String[] parameterTypes = Signature.getParameterTypes(new String(descriptor)); pNames[0] = parameterTypes[0]; } } catch (IllegalArgumentException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); } catch (JavaModelException e) { // protect against malformed .class file (e.g. com/sun/crypto/provider/SunJCE_b.class has a 'a' generic signature) signature = methodInfo.getMethodDescriptor(); pNames = Signature.getParameterTypes(new String(signature)); } char[][] paramNames = new char[pNames.length][]; for (int j = 0; j < pNames.length; j++) { paramNames[j] = pNames[j].toCharArray(); } char[][] parameterTypes = ClassFile.translatedNames(paramNames); JavaModelManager manager = ((JavaElement) type).manager; selector = manager.intern(selector); for (int j = 0; j < pNames.length; j++) { pNames[j] = manager.intern(new String(parameterTypes[j])); } BinaryMethod method = new BinaryMethod((JavaElement) type, manager, selector, pNames); childrenHandles.add(method); // ensure that 2 binary methods with the same signature but with different return types have different occurrence counts. // (case of bridge methods in 1.5) while (newElements.containsKey(method)) method.occurrenceCount++; newElements.put(method, methodInfo); int max = pNames.length; char[][] argumentNames = methodInfo.getArgumentNames(); if (argumentNames == null || argumentNames.length < max) { argumentNames = new char[max][]; for (int j = 0; j < max; j++) { argumentNames[j] = ("arg" + j).toCharArray(); //$NON-NLS-1$ } } int startIndex = 0; try { if (isConstructor) { if (isEnum) { startIndex = 2; } else if (type.isMember() && !Flags.isStatic(type.getFlags())) { startIndex = 1; } } } catch (JavaModelException e) { // ignore } // for (int j = startIndex; j < max; j++) { // IBinaryAnnotation[] parameterAnnotations = methodInfo.getParameterAnnotations(j - startIndex); // if (parameterAnnotations != null) { // LocalVariable localVariable = new LocalVariable( // method, // new String(argumentNames[j]), // 0, // -1, // 0, // -1, // method.parameterTypes[j], // null, // -1, // true); // generateAnnotationsInfos(localVariable, argumentNames[j], parameterAnnotations, methodInfo.getTagBits(), newElements); // } // } generateTypeParameterInfos(method, signature, newElements, typeParameterHandles); generateAnnotationsInfos(method, methodInfo.getAnnotations(), methodInfo.getTagBits(), newElements); Object defaultValue = methodInfo.getDefaultValue(); if (defaultValue instanceof IBinaryAnnotation) { generateAnnotationInfo(method, newElements, (IBinaryAnnotation) defaultValue, new String(methodInfo.getSelector())); } } }
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 www .ja va 2 s . c om * * @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.BasicSearchEngine.java
License:Open Source License
/** * Searches for all top-level types and member types in the given scope using a case sensitive exact match * with the given qualified names and type names. * * @see org.eclipse.jdt.core.search.SearchEngine#searchAllTypeNames(char[][], char[][], org.eclipse.jdt.core.search.IJavaSearchScope, * org.eclipse.jdt.core.search.TypeNameRequestor, int, org.eclipse.core.runtime.IProgressMonitor) * for detailed comment//from w w w . j a va 2s.c o m */ public void searchAllTypeNames(final char[][] qualifications, final char[][] typeNames, final int matchRule, int searchFor, IJavaSearchScope scope, final IRestrictedAccessTypeRequestor nameRequestor, int waitingPolicy, IProgressMonitor progressMonitor) throws JavaModelException { // Debug if (VERBOSE) { Util.verbose( "BasicSearchEngine.searchAllTypeNames(char[][], char[][], int, int, IJavaSearchScope, IRestrictedAccessTypeRequestor, int, IProgressMonitor)"); //$NON-NLS-1$ Util.verbose(" - package name: " + (qualifications == null ? "null" : new String(CharOperation.concatWith(qualifications, ',')))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - type name: " + (typeNames == null ? "null" : new String(CharOperation.concatWith(typeNames, ',')))); //$NON-NLS-1$ //$NON-NLS-2$ Util.verbose(" - match rule: " + getMatchRuleString(matchRule)); //$NON-NLS-1$ Util.verbose(" - search for: " + searchFor); //$NON-NLS-1$ Util.verbose(" - scope: " + scope); //$NON-NLS-1$ } // Create pattern 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 MultiTypeDeclarationPattern pattern = new MultiTypeDeclarationPattern(qualifications, typeNames, typeSuffix, matchRule); // 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 QualifiedTypeDeclarationPattern record = (QualifiedTypeDeclarationPattern) 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 qualificationLength = (record.qualification == null || record.qualification.length == 0) ? 0 : record.qualification.length + 1; int nameLength = record.simpleName == null ? 0 : record.simpleName.length; char[] path = new char[qualificationLength + nameLength]; int pos = 0; if (qualificationLength > 0) { System.arraycopy(record.qualification, 0, path, pos, qualificationLength - 1); CharOperation.replace(path, '.', '/'); path[qualificationLength - 1] = '/'; pos += qualificationLength; } 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); } } nameRequestor.acceptType(record.modifiers, record.pkg, record.simpleName, record.enclosingTypeNames, documentPath, accessRestriction); return true; } }; try { if (progressMonitor != null) { progressMonitor.beginTask(Messages.engine_searching, 100); } // 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, 100)); // add type names from working copies if (copies != null) { for (int i = 0, length = copies.length; i < length; i++) { ICompilationUnit workingCopy = copies[i]; 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; char[] qualification = packageDeclaration; if (parent instanceof IType) { char[] parentQualifiedName = ((IType) parent).getTypeQualifiedName('.') .toCharArray(); enclosingTypeNames = CharOperation.splitOn('.', parentQualifiedName); qualification = CharOperation.concat(qualification, parentQualifiedName); } else { enclosingTypeNames = CharOperation.NO_CHAR_CHAR; } char[] simpleName = type.getElementName().toCharArray(); char suffix = IIndexConstants.TYPE_SUFFIX; if (type.isClass()) { suffix = IIndexConstants.CLASS_SUFFIX; } else if (type.isInterface()) { suffix = IIndexConstants.INTERFACE_SUFFIX; } else if (type.isEnum()) { suffix = IIndexConstants.ENUM_SUFFIX; } else if (type.isAnnotation()) { suffix = IIndexConstants.ANNOTATION_TYPE_SUFFIX; } if (pattern.matchesDecodedKey(new QualifiedTypeDeclarationPattern(qualification, simpleName, suffix, matchRule))) { 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) { SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern( packageDeclaration, typeDeclaration.name, convertTypeKind(TypeDeclaration.kind(typeDeclaration.modifiers)), matchRule); if (pattern.matchesDecodedKey(decodedPattern)) { nameRequestor.acceptType(typeDeclaration.modifiers, packageDeclaration, typeDeclaration.name, CharOperation.NO_CHAR_CHAR, path, null); } return true; } public boolean visit(TypeDeclaration memberTypeDeclaration, ClassScope classScope) { // compute enclosing type names char[] qualification = packageDeclaration; TypeDeclaration enclosing = memberTypeDeclaration.enclosingType; char[][] enclosingTypeNames = CharOperation.NO_CHAR_CHAR; while (enclosing != null) { qualification = CharOperation.concat(qualification, enclosing.name, '.'); enclosingTypeNames = CharOperation .arrayConcat(new char[][] { enclosing.name }, enclosingTypeNames); if ((enclosing.bits & ASTNode.IsMemberType) != 0) { enclosing = enclosing.enclosingType; } else { enclosing = null; } } SearchPattern decodedPattern = new QualifiedTypeDeclarationPattern( qualification, memberTypeDeclaration.name, convertTypeKind(TypeDeclaration.kind(memberTypeDeclaration.modifiers)), matchRule); if (pattern.matchesDecodedKey(decodedPattern)) { nameRequestor.acceptType(memberTypeDeclaration.modifiers, packageDeclaration, memberTypeDeclaration.name, enclosingTypeNames, path, null); } return true; } } parsedUnit.traverse(new AllTypeDeclarationsVisitor(), parsedUnit.scope); } } } } } finally { if (progressMonitor != null) { progressMonitor.done(); } } }
From source file:com.codenvy.ide.ext.java.server.javadoc.JavaElementLabelComposer.java
License:Open Source License
/** * Appends the label for a type. Considers the T_* flags. * * @param type the element to render/* w w w . j a v a 2 s .c o m*/ * @param flags the rendering flags. Flags with names starting with 'T_' are considered. */ public void appendTypeLabel(IType type, long flags) { if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED)) { IPackageFragment pack = type.getPackageFragment(); if (!pack.isDefaultPackage()) { appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS)); fBuffer.append('.'); } } IJavaElement parent = type.getParent(); if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.T_CONTAINER_QUALIFIED)) { IType declaringType = type.getDeclaringType(); if (declaringType != null) { appendTypeLabel(declaringType, JavaElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS)); fBuffer.append('.'); } int parentType = parent.getElementType(); if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) { // anonymous or local appendElementLabel(parent, 0); fBuffer.append('.'); } } String typeName; boolean isAnonymous = false; if (type.isLambda()) { typeName = "() -> {...}"; //$NON-NLS-1$ try { String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures(); if (superInterfaceSignatures.length > 0) { typeName = typeName + ' ' + getSimpleTypeName(type, superInterfaceSignatures[0]); } } catch (JavaModelException e) { //ignore } } else { typeName = getElementName(type); try { isAnonymous = type.isAnonymous(); } catch (JavaModelException e1) { // should not happen, but let's play safe: isAnonymous = typeName.length() == 0; } if (isAnonymous) { try { if (parent instanceof IField && type.isEnum()) { typeName = '{' + JavaElementLabels.ELLIPSIS_STRING + '}'; } else { String supertypeName; String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures(); if (superInterfaceSignatures.length > 0) { supertypeName = getSimpleTypeName(type, superInterfaceSignatures[0]); } else { supertypeName = getSimpleTypeName(type, type.getSuperclassTypeSignature()); } typeName = MessageFormat.format("new {0}() '{'...}", supertypeName); } } catch (JavaModelException e) { //ignore typeName = "new Anonymous"; } } } fBuffer.append(typeName); if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS)) { if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && type.isResolved()) { BindingKey key = new BindingKey(type.getKey()); if (key.isParameterizedType()) { String[] typeArguments = key.getTypeArguments(); appendTypeArgumentSignaturesLabel(type, typeArguments, flags); } else { String[] typeParameters = Signature.getTypeParameters(key.toSignature()); appendTypeParameterSignaturesLabel(typeParameters, flags); } } else if (type.exists()) { try { appendTypeParametersLabels(type.getTypeParameters(), flags); } catch (JavaModelException e) { // ignore } } } // category if (getFlag(flags, JavaElementLabels.T_CATEGORY) && type.exists()) { try { appendCategoryLabel(type, flags); } catch (JavaModelException e) { // ignore } } // post qualification if (getFlag(flags, JavaElementLabels.T_POST_QUALIFIED)) { int offset = fBuffer.length(); fBuffer.append(JavaElementLabels.CONCAT_STRING); IType declaringType = type.getDeclaringType(); if (declaringType == null && type.isBinary() && isAnonymous) { // workaround for Bug 87165: [model] IType#getDeclaringType() does not work for anonymous binary type String tqn = type.getTypeQualifiedName(); int lastDollar = tqn.lastIndexOf('$'); if (lastDollar != 1) { String declaringTypeCF = tqn.substring(0, lastDollar) + ".class"; //$NON-NLS-1$ declaringType = type.getPackageFragment().getClassFile(declaringTypeCF).getType(); try { ISourceRange typeSourceRange = type.getSourceRange(); if (declaringType.exists() && SourceRange.isAvailable(typeSourceRange)) { IJavaElement realParent = declaringType.getTypeRoot() .getElementAt(typeSourceRange.getOffset() - 1); if (realParent != null) { parent = realParent; } } } catch (JavaModelException e) { // ignore } } } if (declaringType != null) { appendTypeLabel(declaringType, JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); int parentType = parent.getElementType(); if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) { // anonymous or local fBuffer.append('.'); appendElementLabel(parent, 0); } } else { appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS); } // if (getFlag(flags, JavaElementLabels.COLORIZE)) { // fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE); // } } }
From source file:com.codenvy.ide.ext.java.server.SourcesFromBytecodeGenerator.java
License:Open Source License
private void generateType(IType type, StringBuilder builder, String indent) throws JavaModelException { int flags = 0; appendAnnotationLabels(type.getAnnotations(), flags, builder, indent.substring(TAB.length())); builder.append(indent.substring(TAB.length())); builder.append(getModifiers(type.getFlags(), type.getFlags())).append(' ').append(getJavaType(type)) .append(' ').append(type.getElementName()); if (type.isResolved()) { BindingKey key = new BindingKey(type.getKey()); if (key.isParameterizedType()) { String[] typeArguments = key.getTypeArguments(); appendTypeArgumentSignaturesLabel(type, typeArguments, flags, builder); } else {//from w ww .ja v a 2 s . c o m String[] typeParameters = Signature.getTypeParameters(key.toSignature()); appendTypeParameterSignaturesLabel(typeParameters, builder); } } else { appendTypeParametersLabels(type.getTypeParameters(), flags, builder); } if (!"java.lang.Object".equals(type.getSuperclassName()) && !"java.lang.Enum".equals(type.getSuperclassName())) { builder.append(" extends "); if (type.getSuperclassTypeSignature() != null) { // appendTypeSignatureLabel(type, type.getSuperclassTypeSignature(), flags, builder); builder.append(Signature.toString(type.getSuperclassTypeSignature())); } else { builder.append(type.getSuperclassName()); } } if (!type.isAnnotation()) { if (type.getSuperInterfaceNames().length != 0) { builder.append(" implements "); String[] signatures = type.getSuperInterfaceTypeSignatures(); if (signatures.length == 0) { signatures = type.getSuperInterfaceNames(); } for (String interfaceFqn : signatures) { builder.append(Signature.toString(interfaceFqn)).append(", "); } builder.delete(builder.length() - 2, builder.length()); } } builder.append(" {\n"); List<IField> fields = new ArrayList<>(); if (type.isEnum()) { builder.append(indent); for (IField field : type.getFields()) { if (field.isEnumConstant()) { builder.append(field.getElementName()).append(", "); } else { fields.add(field); } } if (", ".equals(builder.substring(builder.length() - 2))) { builder.delete(builder.length() - 2, builder.length()); } builder.append(";\n"); } else { fields.addAll(Arrays.asList(type.getFields())); } for (IField field : fields) { if (Flags.isSynthetic(field.getFlags())) { continue; } appendAnnotationLabels(field.getAnnotations(), flags, builder, indent); builder.append(indent).append(getModifiers(field.getFlags(), type.getFlags())); if (builder.charAt(builder.length() - 1) != ' ') { builder.append(' '); } builder.append(Signature.toCharArray(field.getTypeSignature().toCharArray())).append(' ') .append(field.getElementName()); if (field.getConstant() != null) { builder.append(" = "); if (field.getConstant() instanceof String) { builder.append('"').append(field.getConstant()).append('"'); } else { builder.append(field.getConstant()); } } builder.append(";\n"); } builder.append('\n'); for (IMethod method : type.getMethods()) { if (method.getElementName().equals("<clinit>") || Flags.isSynthetic(method.getFlags())) { continue; } appendAnnotationLabels(method.getAnnotations(), flags, builder, indent); BindingKey resolvedKey = method.isResolved() ? new BindingKey(method.getKey()) : null; String resolvedSig = (resolvedKey != null) ? resolvedKey.toSignature() : null; builder.append(indent).append(getModifiers(method.getFlags(), type.getFlags())); if (builder.charAt(builder.length() - 1) != ' ') { builder.append(' '); } if (resolvedKey != null) { if (resolvedKey.isParameterizedMethod()) { String[] typeArgRefs = resolvedKey.getTypeArguments(); if (typeArgRefs.length > 0) { appendTypeArgumentSignaturesLabel(method, typeArgRefs, flags, builder); builder.append(' '); } } else { String[] typeParameterSigs = Signature.getTypeParameters(resolvedSig); if (typeParameterSigs.length > 0) { appendTypeParameterSignaturesLabel(typeParameterSigs, builder); builder.append(' '); } } } else if (method.exists()) { ITypeParameter[] typeParameters = method.getTypeParameters(); if (typeParameters.length > 0) { appendTypeParametersLabels(typeParameters, flags, builder); builder.append(' '); } } if (!method.isConstructor()) { String returnTypeSig = resolvedSig != null ? Signature.getReturnType(resolvedSig) : method.getReturnType(); appendTypeSignatureLabel(method, returnTypeSig, 0, builder); builder.append(' '); // builder.append(Signature.toCharArray(method.getReturnType().toCharArray())).append(' '); } builder.append(method.getElementName()); builder.append('('); for (ILocalVariable variable : method.getParameters()) { builder.append(Signature.toString(variable.getTypeSignature())); builder.append(' ').append(variable.getElementName()).append(", "); } if (builder.charAt(builder.length() - 1) == ' ') { builder.delete(builder.length() - 2, builder.length()); } builder.append(')'); String[] exceptionTypes = method.getExceptionTypes(); if (exceptionTypes != null && exceptionTypes.length != 0) { builder.append(' ').append("throws "); for (String exceptionType : exceptionTypes) { builder.append(Signature.toCharArray(exceptionType.toCharArray())).append(", "); } builder.delete(builder.length() - 2, builder.length()); } if (type.isInterface() || type.isAnnotation()) { builder.append(";\n\n"); } else { builder.append(" {").append(METHOD_BODY).append("}\n\n"); } } for (IType iType : type.getTypes()) { generateType(iType, builder, indent + indent); } builder.append(indent.substring(TAB.length())); builder.append("}\n"); }
From source file:com.codenvy.ide.ext.java.server.SourcesFromBytecodeGenerator.java
License:Open Source License
private String getJavaType(IType type) throws JavaModelException { if (type.isAnnotation()) { return "@interface"; }/*from w w w . j av a 2s. c om*/ if (type.isClass()) { return "class"; } if (type.isInterface()) { return "interface"; } if (type.isEnum()) { return "enum"; } return "can't determine type"; }