@Before
 public void createProject() throws Exception {
   project =
       StsTestUtil.createPredefinedProject(
           "jdt-annotation-tests", "org.springframework.ide.eclipse.beans.core.tests");
   javaProject = JdtUtils.getJavaProject(project);
   classloader = JdtUtils.getClassLoader(project, ApplicationContext.class.getClassLoader());
   factory = new JdtMetadataReaderFactory(javaProject, classloader);
 }
Beispiel #2
0
  /**
   * Returns the corresponding Java type for given full-qualified class name.
   *
   * @param project the JDT project the class belongs to
   * @param className the full qualified class name of the requested Java type
   * @return the requested Java type or null if the class is not defined or the project is not
   *     accessible
   */
  public static IType getJavaType(IProject project, String className) {
    IJavaProject javaProject = JdtUtils.getJavaProject(project);

    if (className != null) {

      // For inner classes replace '$' by '.'
      String unchangedClassName = null;
      int pos = className.lastIndexOf('$');
      if (pos > 0) {
        unchangedClassName = className;
        className = className.replace('$', '.');
      }

      try {
        IType type = null;
        // First look for the type in the Java project
        if (javaProject != null) {
          type = javaProject.findType(className, new NullProgressMonitor());

          if (type == null && unchangedClassName != null) {
            type =
                findTypeWithInnerClassesInvolved(
                    javaProject, unchangedClassName, new NullProgressMonitor());
          }

          if (type != null) {
            return type;
          }
        }

        // Then look for the type in the referenced Java projects
        for (IProject refProject : project.getReferencedProjects()) {
          IJavaProject refJavaProject = JdtUtils.getJavaProject(refProject);
          if (refJavaProject != null) {
            type = refJavaProject.findType(className);

            if (type == null && unchangedClassName != null) {
              type =
                  findTypeWithInnerClassesInvolved(
                      javaProject, unchangedClassName, new NullProgressMonitor());
            }

            if (type != null) {
              return type;
            }
          }
        }

        // fall back and try to locate the class using AJDT
        return getAjdtType(project, className);
      } catch (CoreException e) {
        SpringCore.log("Error getting Java type '" + className + "'", e);
      }
    }

    return null;
  }
  /**
   * Create a {@link BeansJavaCompletionProposal} for the given {@link IMethod} and report it on the
   * {@link ContentAssistRequest}.
   */
  protected void createMethodProposal(IContentAssistProposalRecorder recorder, IMethod method) {
    try {
      String[] parameterNames = method.getParameterNames();
      String[] parameterTypes = JdtUtils.getParameterTypesString(method);
      String returnType = JdtUtils.getReturnTypeString(method, true);
      String methodName = JdtUtils.getMethodName(method);

      String replaceText = methodName;

      StringBuilder buf = new StringBuilder();

      // add method name
      buf.append(replaceText);

      // add method parameters
      if (parameterTypes.length > 0 && parameterNames.length > 0) {
        buf.append(" (");
        for (int i = 0; i < parameterTypes.length; i++) {
          buf.append(parameterTypes[i]);
          buf.append(' ');
          buf.append(parameterNames[i]);
          if (i < (parameterTypes.length - 1)) {
            buf.append(", ");
          }
        }
        buf.append(") ");
      } else {
        buf.append("() ");
      }

      // add return type
      if (returnType != null) {
        buf.append(Signature.getSimpleName(returnType));
        buf.append(" - ");
      } else {
        buf.append(" void - ");
      }

      // add class name
      buf.append(JdtUtils.getParentName(method));

      String displayText = buf.toString();
      Image image =
          Activator.getDefault()
              .getJavaElementLabelProvider()
              .getImageLabel(method, method.getFlags() | JavaElementImageProvider.SMALL_ICONS);

      recorder.recordProposal(image, METHOD_RELEVANCE, displayText, replaceText, method);
    } catch (JavaModelException e) {
      // do nothing
    }
  }
Beispiel #4
0
 public static IType getJavaTypeFromSignatureClassName(String className, IType contextType) {
   if (contextType == null || className == null) {
     return null;
   }
   try {
     return JdtUtils.getJavaType(
         contextType.getJavaProject().getProject(),
         JdtUtils.resolveClassNameBySignature(className, contextType));
   } catch (IllegalArgumentException e) {
     // do Nothing
   }
   return null;
 }
Beispiel #5
0
 public static final IType getJavaTypeForMethodReturnType(IMethod method, IType contextType) {
   try {
     return JdtUtils.getJavaTypeFromSignatureClassName(method.getReturnType(), contextType);
   } catch (JavaModelException e) {
   }
   return null;
 }
  /** {@inheritDoc} */
  public IHyperlink createHyperlink(
      String name,
      String target,
      Node node,
      Node parentNode,
      IDocument document,
      ITextViewer textViewer,
      IRegion hyperlinkRegion,
      IRegion cursor) {
    String parentName = null;
    if (parentNode != null) {
      parentName = parentNode.getNodeName();
    }

    List<String> propertyPaths = new ArrayList<String>();
    hyperlinkRegion =
        BeansEditorUtils.extractPropertyPathFromCursorPosition(
            hyperlinkRegion, cursor, target, propertyPaths);
    if ("bean".equals(parentName) && StringUtils.hasText(target)) {
      IFile file = BeansEditorUtils.getFile(document);
      String className =
          BeansEditorUtils.getClassNameForBean(file, node.getOwnerDocument(), parentNode);
      IType type = JdtUtils.getJavaType(file.getProject(), className);

      if (type != null) {
        IBeansConfig config = BeansCorePlugin.getModel().getConfig(file);
        if (config != null && parentNode instanceof Element) {
          IModelElement element = BeansModelUtils.getModelElement((Element) parentNode, config);
          int argIndex = getArgumentIndex(node);
          if (argIndex >= 0) {
            if (element instanceof IBean) {
              IBean bean = (IBean) element;
              int count = bean.getConstructorArguments().size();
              if (count > 0) {
                try {
                  Set<IMethod> methods = Introspector.getConstructors(type, count, false);
                  Iterator<IMethod> iter = methods.iterator();
                  while (iter.hasNext()) {
                    IMethod candidate = iter.next();
                    if (target.equalsIgnoreCase(candidate.getParameterNames()[argIndex])) {
                      // return new JavaElementHyperlink(hyperlinkRegion,
                      // candidate.getParameters()[argIndex]);
                      // TODO: just a temporary workaround for making this Eclipse 3.6 compatible
                      return new JavaElementHyperlink(hyperlinkRegion, candidate);
                    }
                  }
                } catch (JavaModelException e) {
                  // do nothing
                }
              }
            }
          }
        }
      }
    }
    return null;
  }
Beispiel #7
0
 public static final List<IType> getJavaTypesForMethodParameterTypes(
     IMethod method, IType contextType) {
   if (method == null
       || method.getParameterTypes() == null
       || method.getParameterTypes().length == 0) {
     return Collections.EMPTY_LIST;
   }
   List<IType> parameterTypes = new ArrayList<IType>(method.getParameterTypes().length);
   String[] parameterTypeNames = method.getParameterTypes();
   for (String parameterTypeName : parameterTypeNames) {
     parameterTypes.add(
         JdtUtils.getJavaTypeFromSignatureClassName(parameterTypeName, contextType));
   }
   return parameterTypes;
 }
  @Test
  public void testSimpleClass() throws Exception {
    MetadataReader metadataReader = factory.getMetadataReader("org.test.spring.NoAnnotations");

    ClassMetadata metadata = metadataReader.getClassMetadata();
    assertEquals("org.test.spring.NoAnnotations", metadata.getClassName());
    assertEquals(0, metadata.getInterfaceNames().length);

    assertFalse(metadata.hasEnclosingClass());
    assertNull(metadata.getEnclosingClassName());

    assertTrue(metadata.hasSuperClass());
    assertEquals("java.lang.Object", metadata.getSuperClassName());

    assertTrue(metadata instanceof JdtConnectedMetadata);
    IType type = JdtUtils.getJavaType(project, "org.test.spring.NoAnnotations");
    assertEquals(type, ((JdtConnectedMetadata) metadata).getJavaElement());
  }
  /** Filters out every {@link IFile} which is has unknown root elements in its XML content. */
  @Override
  protected Set<IFile> filterMatchingFiles(Set<IFile> files) {
    // if project is a java project remove bin dirs from the list
    Set<String> outputDirectories = new HashSet<String>();
    IJavaProject javaProject = JdtUtils.getJavaProject(project);
    if (javaProject != null) {
      try {
        // add default output directory
        outputDirectories.add(javaProject.getOutputLocation().toString());

        // add source folder specific output directories
        for (IClasspathEntry entry : javaProject.getRawClasspath()) {
          if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE
              && entry.getOutputLocation() != null) {
            outputDirectories.add(entry.getOutputLocation().toString());
          }
        }
      } catch (JavaModelException e) {
        BeansCorePlugin.log(e);
      }
    }

    Set<IFile> detectedFiles = new LinkedHashSet<IFile>();
    for (IFile file : files) {
      boolean skip = false;
      // first check if the file sits in an output directory
      String path = file.getFullPath().toString();
      for (String outputDirectory : outputDirectories) {
        if (path.startsWith(outputDirectory)) {
          skip = true;
        }
      }
      if (skip) {
        continue;
      }

      // check if the file is known Spring xml file
      IStructuredModel model = null;
      try {
        try {
          model = StructuredModelManager.getModelManager().getExistingModelForRead(file);
        } catch (RuntimeException e) {
          // sometimes WTP throws a NPE in concurrency situations
        }
        if (model == null) {
          model = StructuredModelManager.getModelManager().getModelForRead(file);
        }
        if (model != null) {
          IDOMDocument document = ((DOMModelImpl) model).getDocument();
          if (document != null && document.getDocumentElement() != null) {
            String namespaceUri = document.getDocumentElement().getNamespaceURI();
            if (applyNamespaceFilter(file, namespaceUri)) {
              detectedFiles.add(file);
            }
          }
        }
      } catch (IOException e) {
        BeansCorePlugin.log(e);
      } catch (CoreException e) {
        BeansCorePlugin.log(e);
      } finally {
        if (model != null) {
          model.releaseFromRead();
        }
      }
    }
    return detectedFiles;
  }