예제 #1
0
 public static List<IField> findAllFields(final IType clazz) {
   final List<IField> fields = new ArrayList<IField>();
   try {
     for (final IField field : clazz.getFields()) {
       final int flags = field.getFlags();
       final boolean notStatic = !Flags.isStatic(flags);
       if (notStatic) fields.add(field);
     }
   } catch (final JavaModelException e) {
     e.printStackTrace();
   }
   return fields;
 }
 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);
 }
예제 #3
0
 /** @since 3.2.0 */
 public static IField getField(IType type, String fieldName, boolean includeHierarchy) {
   try {
     while (type != null) {
       for (IField field : type.getFields()) {
         if (field.getElementName().equals(fieldName)) {
           return field;
         }
       }
       if (!includeHierarchy) break;
       type = Introspector.getSuperType(type);
     }
   } catch (JavaModelException e) {
   }
   return null;
 }
예제 #4
0
 /**
  * We don't include nested types because structural changes of nested types should not affect
  * Xtend classes which use top level types.
  *
  * @deprecated This method is not used anymore.
  */
 @Deprecated
 protected void traverseType(IType type, NameBasedEObjectDescriptionBuilder acceptor) {
   try {
     if (type.exists()) {
       for (IField field : type.getFields()) {
         if (!Flags.isSynthetic(field.getFlags())) {
           String fieldName = field.getElementName();
           acceptor.accept(fieldName);
         }
       }
       for (IMethod method : type.getMethods()) {
         if (!Flags.isSynthetic(method.getFlags())) {
           String methodName = method.getElementName();
           acceptor.accept(methodName);
         }
       }
     }
   } catch (JavaModelException e) {
     if (LOGGER.isDebugEnabled()) LOGGER.debug(e, e);
   }
 }
  private IJavaElement visit(IType javaType) {
    IBindingProvider mirror = null;
    if (ceylonDeclaration instanceof LazyClass) {
      LazyClass lazyClass = (LazyClass) ceylonDeclaration;
      if (!lazyClass.isAbstraction() && lazyClass.isOverloaded()) {
        IBindingProvider constructor = (IBindingProvider) lazyClass.getConstructor();
        if (constructor != null) {
          mirror = constructor;
        }
      }
      if (mirror == null) {
        mirror = (IBindingProvider) lazyClass.classMirror;
      }
    }
    if (ceylonDeclaration instanceof LazyInterface) {
      mirror = (IBindingProvider) ((LazyInterface) ceylonDeclaration).classMirror;
    }
    if (ceylonDeclaration instanceof LazyValue) {
      mirror = (IBindingProvider) ((LazyValue) ceylonDeclaration).classMirror;
    }
    if (ceylonDeclaration instanceof JavaBeanValue) {
      JavaBeanValue javaBeanValue = ((JavaBeanValue) ceylonDeclaration);
      Scope container = javaBeanValue.getContainer();
      if (container instanceof LazyClass) {
        mirror = (IBindingProvider) ((LazyClass) container).classMirror;
      }
      if (container instanceof LazyInterface) {
        mirror = (IBindingProvider) ((LazyInterface) container).classMirror;
      }
      if (container instanceof LazyValue) {
        mirror = (IBindingProvider) ((LazyValue) container).classMirror;
      }
      if (declarationMatched(javaType, mirror) != null) {
        try {
          for (IMethod javaMethod : javaType.getMethods()) {
            if (javaMethod.getElementName().equals(javaBeanValue.getGetterName())) {
              return javaMethod;
            }
          }
        } catch (JavaModelException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      return visit((IParent) javaType);
    }
    if (ceylonDeclaration instanceof FieldValue) {
      FieldValue fieldValue = ((FieldValue) ceylonDeclaration);
      Scope container = fieldValue.getContainer();
      if (container instanceof LazyClass) {
        mirror = (IBindingProvider) ((LazyClass) container).classMirror;
      }
      if (container instanceof LazyInterface) {
        mirror = (IBindingProvider) ((LazyInterface) container).classMirror;
      }
      if (container instanceof LazyValue) {
        mirror = (IBindingProvider) ((LazyValue) container).classMirror;
      }
      if (declarationMatched(javaType, mirror) != null) {
        try {
          for (IField javaField : javaType.getFields()) {
            if (javaField.getElementName().equals(fieldValue.getRealName())) {
              return javaField;
            }
          }
        } catch (JavaModelException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      return visit((IParent) javaType);
    }

    IJavaElement result = declarationMatched(javaType, mirror);
    if (result != null) {
      return result;
    }
    return visit((IParent) javaType);
  }
  private void extractIType(IType type) {
    try {
      String fqn = type.getFullyQualifiedName();

      // Write the entity
      if (type.isClass()) {
        entityWriter.writeClass(fqn, type.getFlags(), path);

        // Write the superclass
        String superSig = type.getSuperclassTypeSignature();
        if (superSig != null) {
          relationWriter.writeExtends(fqn, typeSignatureToFqn(superSig), path);
        }
      } else if (type.isAnnotation()) {
        entityWriter.writeAnnotation(fqn, type.getFlags(), path);
      } else if (type.isInterface()) {
        entityWriter.writeInterface(fqn, type.getFlags(), path);
      } else if (type.isEnum()) {
        entityWriter.writeEnum(fqn, type.getFlags(), path);
      }

      // Write the superinterfaces
      for (String superIntSig : type.getSuperInterfaceTypeSignatures()) {
        relationWriter.writeImplements(fqn, typeSignatureToFqn(superIntSig), path);
      }

      if (!fqnStack.isEmpty()) {
        relationWriter.writeInside(type.getFullyQualifiedName(), fqnStack.peek(), path);
      }

      fqnStack.push(type.getFullyQualifiedName());

      for (IType child : type.getTypes()) {
        extractIType(child);
      }

      for (IField field : type.getFields()) {
        if (!Flags.isSynthetic(field.getFlags())) {
          extractIField(field);
        }
      }

      for (IMethod method : type.getMethods()) {
        if (!Flags.isSynthetic(method.getFlags())
            || (Flags.isSynthetic(method.getFlags())
                && method.isConstructor()
                && method.getParameterTypes().length == 0)) {
          extractIMethod(method, type.isAnnotation());
        }
      }

      int pos = 0;
      for (ITypeParameter param : type.getTypeParameters()) {
        relationWriter.writeParametrizedBy(fqn, getTypeParam(param), pos++, path);
      }

      fqnStack.pop();
    } catch (Exception e) {
      logger.log(Level.SEVERE, "Error in extracting class file", e);
    }
  }
  /**
   * Finds the key defined by the given match. The assumption is that the key is the only argument
   * and it is a string literal i.e. quoted ("...") or a string constant i.e. 'static final String'
   * defined in the same class.
   *
   * @param keyPositionResult reference parameter: will be filled with the position of the found key
   * @param enclosingElement enclosing java element
   * @return a string denoting the key, {@link #NO_KEY} if no key can be found and <code>null</code>
   *     otherwise
   * @throws CoreException if a problem occurs while accessing the <code>enclosingElement</code>
   */
  private String findKey(Position keyPositionResult, IJavaElement enclosingElement)
      throws CoreException {
    ICompilationUnit unit =
        (ICompilationUnit) enclosingElement.getAncestor(IJavaElement.COMPILATION_UNIT);
    if (unit == null) return null;

    String source = unit.getSource();
    if (source == null) return null;

    IJavaProject javaProject = unit.getJavaProject();
    IScanner scanner = null;
    if (javaProject != null) {
      String complianceLevel = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
      String sourceLevel = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
      scanner = ToolFactory.createScanner(false, false, false, sourceLevel, complianceLevel);
    } else {
      scanner = ToolFactory.createScanner(false, false, false, false);
    }
    scanner.setSource(source.toCharArray());
    scanner.resetTo(keyPositionResult.getOffset() + keyPositionResult.getLength(), source.length());

    try {
      if (scanner.getNextToken() != ITerminalSymbols.TokenNameDOT) return null;

      if (scanner.getNextToken() != ITerminalSymbols.TokenNameIdentifier) return null;

      String src = new String(scanner.getCurrentTokenSource());
      int tokenStart = scanner.getCurrentTokenStartPosition();
      int tokenEnd = scanner.getCurrentTokenEndPosition();

      if (scanner.getNextToken() == ITerminalSymbols.TokenNameLPAREN) {
        // Old school
        // next must be key string. Ignore methods which do not take a single String parameter (Bug
        // 295040).
        int nextToken = scanner.getNextToken();
        if (nextToken != ITerminalSymbols.TokenNameStringLiteral
            && nextToken != ITerminalSymbols.TokenNameIdentifier) return null;

        tokenStart = scanner.getCurrentTokenStartPosition();
        tokenEnd = scanner.getCurrentTokenEndPosition();
        int token;
        while ((token = scanner.getNextToken()) == ITerminalSymbols.TokenNameDOT) {
          if ((nextToken = scanner.getNextToken()) != ITerminalSymbols.TokenNameIdentifier) {
            return null;
          }
          tokenStart = scanner.getCurrentTokenStartPosition();
          tokenEnd = scanner.getCurrentTokenEndPosition();
        }
        if (token != ITerminalSymbols.TokenNameRPAREN) return null;

        if (nextToken == ITerminalSymbols.TokenNameStringLiteral) {
          keyPositionResult.setOffset(tokenStart + 1);
          keyPositionResult.setLength(tokenEnd - tokenStart - 1);
          return source.substring(tokenStart + 1, tokenEnd);
        } else if (nextToken == ITerminalSymbols.TokenNameIdentifier) {
          keyPositionResult.setOffset(tokenStart);
          keyPositionResult.setLength(tokenEnd - tokenStart + 1);
          IType parentClass = (IType) enclosingElement.getAncestor(IJavaElement.TYPE);
          IField[] fields = parentClass.getFields();
          String identifier = source.substring(tokenStart, tokenEnd + 1);
          for (int i = 0; i < fields.length; i++) {
            if (fields[i].getElementName().equals(identifier)) {
              if (!Signature.getSignatureSimpleName(fields[i].getTypeSignature())
                  .equals("String")) // $NON-NLS-1$
              return null;
              Object obj = fields[i].getConstant();
              return obj instanceof String
                  ? ((String) obj).substring(1, ((String) obj).length() - 1)
                  : NO_KEY;
            }
          }
        }
        return NO_KEY;
      } else {
        keyPositionResult.setOffset(tokenStart);
        keyPositionResult.setLength(tokenEnd - tokenStart + 1);
        return src;
      }
    } catch (InvalidInputException e) {
      throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, e));
    }
  }