/**
   * Displays a project chooser dialog which lists all available projects with the Android nature.
   *
   * <p>The list of project is built from Android flagged projects currently opened in the
   * workspace.
   *
   * @param projectName If non null and not empty, represents the name of an Android project that
   *     will be selected by default.
   * @return the project chosen by the user in the dialog, or null if the dialog was canceled.
   */
  public IJavaProject chooseJavaProject(String projectName) {
    ILabelProvider labelProvider =
        new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
    ElementListSelectionDialog dialog = new ElementListSelectionDialog(mParentShell, labelProvider);
    dialog.setTitle("Project Selection");
    dialog.setMessage("Select a project to constrain your search.");

    IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
    IJavaModel javaModel = JavaCore.create(workspaceRoot);

    // set the elements in the dialog. These are opened android projects.
    dialog.setElements(getAndroidProjects(javaModel));

    // look for the project matching the given project name
    IJavaProject javaProject = null;
    if (projectName != null && projectName.length() > 0) {
      javaProject = javaModel.getJavaProject(projectName);
    }

    // if we found it, we set the initial selection in the dialog to this one.
    if (javaProject != null) {
      dialog.setInitialSelections(new Object[] {javaProject});
    }

    // open the dialog and return the object selected if OK was clicked, or null otherwise
    if (dialog.open() == Window.OK) {
      return (IJavaProject) dialog.getFirstResult();
    }
    return null;
  }
  public static void fixAsEJB(ILaunchConfiguration config) {
    try {
      LaunchConfigurationInfo info =
          (LaunchConfigurationInfo) BeanUtils.invokeMethod(config, "getInfo");
      Map map = (Map) BeanUtils.getFieldValue(info, "fAttributes");

      String projectName = (String) map.get(ATTR_PROJECT_NAME);
      IJavaModel jModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
      IJavaProject jp = jModel.getJavaProject(projectName);
      Assert.notNull(jp);

      File root = jp.getProject().getLocation().toFile();
      map.put("org.eclipse.jdt.launching.MAIN_TYPE", "jef.database.JefClassLoader");

      String arg = (String) map.get(ATTR_PROGRAM_ARGUMENTS);
      if (arg == null) {
        File openEjbFolder = findOpenEjbFolder();
        String projectPath = root.getAbsolutePath();
        String openEjbPath = openEjbFolder.getAbsolutePath();
        map.put(
            ATTR_PROGRAM_ARGUMENTS,
            "jef.ejb.server.OpenejbServer " + projectPath + " " + openEjbPath);
      }

    } catch (ReflectionException e) {
      e.printStackTrace();
    }
  }
Пример #3
0
  /**
   * Returns whether elements of the given project or jar can see the given focus (an IJavaProject
   * or a JarPackageFragmentRot) either because the focus is part of the project or the jar, or
   * because it is accessible throught the project's classpath
   */
  public static boolean canSeeFocus(SearchPattern pattern, IPath projectOrJarPath) {
    try {
      IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
      IJavaProject project = getJavaProject(projectOrJarPath, model);
      IJavaElement[] focuses = getFocusedElementsAndTypes(pattern, project, null);
      if (focuses.length == 0) return false;
      if (project != null) {
        return canSeeFocus(focuses, (JavaProject) project, null);
      }

      // projectOrJarPath is a jar
      // it can see the focus only if it is on the classpath of a project that can see the focus
      IJavaProject[] allProjects = model.getJavaProjects();
      for (int i = 0, length = allProjects.length; i < length; i++) {
        JavaProject otherProject = (JavaProject) allProjects[i];
        IClasspathEntry entry = otherProject.getClasspathEntryFor(projectOrJarPath);
        if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
          if (canSeeFocus(focuses, otherProject, null)) {
            return true;
          }
        }
      }
      return false;
    } catch (JavaModelException e) {
      return false;
    }
  }
  public Object convertToObject(String parameterValue) throws ParameterValueConversionException {

    assertWellFormed(parameterValue != null);

    final int projectEndPosition = parameterValue.indexOf(PROJECT_END_CHAR);
    assertWellFormed(projectEndPosition != -1);

    String projectName = parameterValue.substring(0, projectEndPosition);
    String javaElementRef = parameterValue.substring(projectEndPosition + 1);

    IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
    assertExists(javaModel);

    IJavaProject javaProject = javaModel.getJavaProject(projectName);
    assertExists(javaProject);

    final int typeEndPosition = javaElementRef.indexOf(TYPE_END_CHAR);
    String typeName;
    if (typeEndPosition == -1) {
      typeName = javaElementRef;
    } else {
      typeName = javaElementRef.substring(0, typeEndPosition);
    }

    IType type = null;
    try {
      type = javaProject.findType(typeName);
    } catch (JavaModelException ex) {
      // type == null
    }
    assertExists(type);

    if (typeEndPosition == -1) {
      return type;
    }

    String memberRef = javaElementRef.substring(typeEndPosition + 1);

    final int paramStartPosition = memberRef.indexOf(PARAM_START_CHAR);
    if (paramStartPosition == -1) {
      IField field = type.getField(memberRef);
      assertExists(field);
      return field;
    }
    String methodName = memberRef.substring(0, paramStartPosition);
    String signature = memberRef.substring(paramStartPosition);
    String[] parameterTypes = null;
    try {
      parameterTypes = Signature.getParameterTypes(signature);
    } catch (IllegalArgumentException ex) {
      // parameterTypes == null
    }
    assertWellFormed(parameterTypes != null);
    IMethod method = type.getMethod(methodName, parameterTypes);
    assertExists(method);
    return method;
  }
Пример #5
0
  private IJavaProject getJavaProject() {

    String projTxt = StringUtils.trimToEmpty(txtProject.getText());

    if (StringUtils.isBlank(projTxt)) {
      return null;
    }

    IJavaModel model = JavaCore.create(getWorkspaceRoot());
    return model.getJavaProject(projTxt);
  }
Пример #6
0
 public Object[] getElements(Object arg0) {
   try {
     IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
     IJavaProject[] javaProjects = javaModel.getJavaProjects();
     for (IJavaProject project : javaProjects) {
       projects.put(project.getElementName(), project);
     }
     return javaProjects;
   } catch (JavaModelException e) {
     Activator.error("Error getting java projects", e);
     throw new RuntimeException(e);
   }
 }
  @Test
  public void shouldConfigureProjectsWithCircularDependencies() throws CoreException, IOException {
    // the bug appeared when at least 3 projects were involved: the first project depends on the
    // second one which has a circular dependency
    // towards the second one
    Properties sonarProperties = new Properties();
    // mock three projects that depend on each other
    final String project1Name = "project1";
    final String project2Name = "project2";
    final String project3Name = "project3";
    IJavaProject project1 = mock(IJavaProject.class, Mockito.RETURNS_DEEP_STUBS);
    IJavaProject project2 = mock(IJavaProject.class, Mockito.RETURNS_DEEP_STUBS);
    IJavaProject project3 = mock(IJavaProject.class, Mockito.RETURNS_DEEP_STUBS);
    // these are required during the call to configureJavaProject
    when(project1.getOption(JavaCore.COMPILER_SOURCE, true)).thenReturn("1.6");
    when(project1.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true)).thenReturn("1.6");
    when(project1.getProject().getName()).thenReturn(project1Name);
    when(project2.getProject().getName()).thenReturn(project2Name);
    when(project3.getProject().getName()).thenReturn(project3Name);

    // create three classpathEntries, one for each Project
    IClasspathEntry entryProject1 = mock(IClasspathEntry.class, Mockito.RETURNS_DEEP_STUBS);
    IClasspathEntry entryProject2 = mock(IClasspathEntry.class, Mockito.RETURNS_DEEP_STUBS);
    IClasspathEntry entryProject3 = mock(IClasspathEntry.class, Mockito.RETURNS_DEEP_STUBS);
    when(entryProject1.getEntryKind()).thenReturn(IClasspathEntry.CPE_PROJECT);
    when(entryProject1.getPath().segment(0)).thenReturn(project1Name);
    when(entryProject2.getEntryKind()).thenReturn(IClasspathEntry.CPE_PROJECT);
    when(entryProject2.getPath().segment(0)).thenReturn(project2Name);
    when(entryProject3.getEntryKind()).thenReturn(IClasspathEntry.CPE_PROJECT);
    when(entryProject3.getPath().segment(0)).thenReturn(project3Name);
    // project1 depends on project2, which depends on project3, which depends on project2
    IClasspathEntry[] classpath1 = new IClasspathEntry[] {entryProject2};
    IClasspathEntry[] classpath2 = new IClasspathEntry[] {entryProject3};
    IClasspathEntry[] classpath3 = new IClasspathEntry[] {entryProject2};
    when(project1.getResolvedClasspath(true)).thenReturn(classpath1);
    when(project2.getResolvedClasspath(true)).thenReturn(classpath2);
    when(project3.getResolvedClasspath(true)).thenReturn(classpath3);

    // mock the JavaModel
    IJavaModel javaModel = mock(IJavaModel.class);
    when(javaModel.getJavaProject(project1Name)).thenReturn(project1);
    when(javaModel.getJavaProject(project2Name)).thenReturn(project2);
    when(javaModel.getJavaProject(project3Name)).thenReturn(project3);

    when(project1.getJavaModel()).thenReturn(javaModel);
    when(project2.getJavaModel()).thenReturn(javaModel);
    when(project3.getJavaModel()).thenReturn(javaModel);

    // this call should not fail (StackOverFlowError before patch)
    configurator.configureJavaProject(project1, sonarProperties);
  }
Пример #8
0
 /**
  * Returns the java project that corresponds to the given path. Returns null if the path doesn't
  * correspond to a project.
  */
 private static IJavaProject getJavaProject(IPath path, IJavaModel model) {
   IJavaProject project = model.getJavaProject(path.lastSegment());
   if (project.exists()) {
     return project;
   }
   return null;
 }
 public Object[] getChildren(Object element) {
   if (element instanceof IJavaModel) {
     IJavaModel model = (IJavaModel) element;
     Set<IJavaProject> set = new HashSet<IJavaProject>();
     try {
       IJavaProject[] projects = model.getJavaProjects();
       for (int i = 0; i < projects.length; i++) {
         if (ProjectUtil.isLiferayFacetedProject(projects[i].getProject())) {
           set.add(projects[i]);
         }
       }
     } catch (JavaModelException jme) {
       // ignore
     }
     return set.toArray();
   }
   return super.getChildren(element);
 }
  public static String[] getEjbStartParams(ILaunchConfiguration config) throws Exception {
    String[] result = new String[2];
    LaunchConfigurationInfo info =
        (LaunchConfigurationInfo) BeanUtils.invokeMethod(config, "getInfo");
    Map map = (Map) BeanUtils.getFieldValue(info, "fAttributes");

    String projectName = (String) map.get(ATTR_PROJECT_NAME);
    IJavaModel jModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
    IJavaProject jp = jModel.getJavaProject(projectName);

    File root = jp.getProject().getLocation().toFile();
    File openEjbFolder = findOpenEjbFolder();
    String projectPath = root.getAbsolutePath();
    String openEjbPath = openEjbFolder.getAbsolutePath();

    result[0] = projectPath;
    result[1] = openEjbPath;

    return result;
  }
Пример #11
0
 public static List<IJavaProject> getAllDependingJavaProjects(IJavaProject project) {
   List<IJavaProject> javaProjects = new ArrayList<IJavaProject>();
   IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
   if (model != null) {
     try {
       String[] names = project.getRequiredProjectNames();
       IJavaProject[] projects = model.getJavaProjects();
       for (int index = 0; index < projects.length; index++) {
         for (int offset = 0; offset < names.length; offset++) {
           String name = projects[index].getProject().getName();
           if (name.equals(names[offset])) {
             javaProjects.add(projects[index]);
           }
         }
       }
     } catch (JavaModelException exception) {
     }
   }
   return javaProjects;
 }
 @Override
 public void resourceChanged(IResourceChangeEvent event) {
   IPath path = BMClasspathContainer.PATH;
   try {
     IJavaModel model = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot());
     for (IJavaProject javaProject : model.getJavaProjects()) {
       for (IClasspathEntry rawEntry : javaProject.readRawClasspath()) {
         if (rawEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
           IPath entryPath = rawEntry.getPath();
           if (path.isPrefixOf(entryPath)) {
             this.initialize(entryPath, javaProject);
             return;
           }
         }
       }
     }
   } catch (JavaModelException e) {
     e.printStackTrace();
   } catch (CoreException e) {
     e.printStackTrace();
   }
 }
Пример #13
0
  /**
   * Add a path to current java search scope or all project fragment roots if null. Use project
   * resolved classpath to retrieve and store access restriction on each classpath entry. Recurse if
   * dependent projects are found.
   *
   * @param javaProject Project used to get resolved classpath entries
   * @param pathToAdd Path to add in case of single element or null if user want to add all project
   *     package fragment roots
   * @param includeMask Mask to apply on classpath entries
   * @param projectsToBeAdded Set to avoid infinite recursion
   * @param visitedProjects Set to avoid adding twice the same project
   * @param referringEntry Project raw entry in referring project classpath
   * @throws JavaModelException May happen while getting java model info
   */
  void add(
      JavaProject javaProject,
      IPath pathToAdd,
      int includeMask,
      HashSet projectsToBeAdded,
      HashSet visitedProjects,
      IClasspathEntry referringEntry)
      throws JavaModelException {
    IProject project = javaProject.getProject();
    if (!project.isAccessible() || !visitedProjects.add(project)) return;

    IPath projectPath = project.getFullPath();
    String projectPathString = projectPath.toString();
    addEnclosingProjectOrJar(projectPath);

    IClasspathEntry[] entries = javaProject.getResolvedClasspath();
    IJavaModel model = javaProject.getJavaModel();
    JavaModelManager.PerProjectInfo perProjectInfo = javaProject.getPerProjectInfo();
    for (int i = 0, length = entries.length; i < length; i++) {
      IClasspathEntry entry = entries[i];
      AccessRuleSet access = null;
      ClasspathEntry cpEntry = (ClasspathEntry) entry;
      if (referringEntry != null) {
        // Add only exported entries.
        // Source folder are implicitly exported.
        if (!entry.isExported() && entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
          continue;
        }
        cpEntry = cpEntry.combineWith((ClasspathEntry) referringEntry);
        //				cpEntry = ((ClasspathEntry)referringEntry).combineWith(cpEntry);
      }
      access = cpEntry.getAccessRuleSet();
      switch (entry.getEntryKind()) {
        case IClasspathEntry.CPE_LIBRARY:
          IClasspathEntry rawEntry = null;
          Map rootPathToRawEntries = perProjectInfo.rootPathToRawEntries;
          if (rootPathToRawEntries != null) {
            rawEntry = (IClasspathEntry) rootPathToRawEntries.get(entry.getPath());
          }
          if (rawEntry == null) break;
          rawKind:
          switch (rawEntry.getEntryKind()) {
            case IClasspathEntry.CPE_LIBRARY:
            case IClasspathEntry.CPE_VARIABLE:
              if ((includeMask & APPLICATION_LIBRARIES) != 0) {
                IPath path = entry.getPath();
                if (pathToAdd == null || pathToAdd.equals(path)) {
                  Object target = JavaModel.getTarget(path, false /*don't check existence*/);
                  if (target instanceof IFolder) // case of an external folder
                  path = ((IFolder) target).getFullPath();
                  String pathToString =
                      path.getDevice() == null ? path.toString() : path.toOSString();
                  add(
                      projectPath.toString(),
                      "",
                      pathToString,
                      false /*not a package*/,
                      access); //$NON-NLS-1$
                  addEnclosingProjectOrJar(entry.getPath());
                }
              }
              break;
            case IClasspathEntry.CPE_CONTAINER:
              IClasspathContainer container =
                  JavaCore.getClasspathContainer(rawEntry.getPath(), javaProject);
              if (container == null) break;
              switch (container.getKind()) {
                case IClasspathContainer.K_APPLICATION:
                  if ((includeMask & APPLICATION_LIBRARIES) == 0) break rawKind;
                  break;
                case IClasspathContainer.K_SYSTEM:
                case IClasspathContainer.K_DEFAULT_SYSTEM:
                  if ((includeMask & SYSTEM_LIBRARIES) == 0) break rawKind;
                  break;
                default:
                  break rawKind;
              }
              IPath path = entry.getPath();
              if (pathToAdd == null || pathToAdd.equals(path)) {
                Object target = JavaModel.getTarget(path, false /*don't check existence*/);
                if (target instanceof IFolder) // case of an external folder
                path = ((IFolder) target).getFullPath();
                String pathToString =
                    path.getDevice() == null ? path.toString() : path.toOSString();
                add(
                    projectPath.toString(),
                    "",
                    pathToString,
                    false /*not a package*/,
                    access); //$NON-NLS-1$
                addEnclosingProjectOrJar(entry.getPath());
              }
              break;
          }
          break;
        case IClasspathEntry.CPE_PROJECT:
          if ((includeMask & REFERENCED_PROJECTS) != 0) {
            IPath path = entry.getPath();
            if (pathToAdd == null || pathToAdd.equals(path)) {
              JavaProject referencedProject = (JavaProject) model.getJavaProject(path.toOSString());
              if (!projectsToBeAdded.contains(
                  referencedProject)) { // do not recurse if depending project was used to create
                                        // the scope
                add(
                    referencedProject,
                    null,
                    includeMask,
                    projectsToBeAdded,
                    visitedProjects,
                    cpEntry);
              }
            }
          }
          break;
        case IClasspathEntry.CPE_SOURCE:
          if ((includeMask & SOURCES) != 0) {
            IPath path = entry.getPath();
            if (pathToAdd == null || pathToAdd.equals(path)) {
              add(
                  projectPath.toString(),
                  Util.relativePath(path, projectPath.segmentCount() /*remove project segment*/),
                  projectPathString,
                  false /*not a package*/,
                  access);
            }
          }
          break;
      }
    }
  }
Пример #14
0
  /*
   *  Compute the list of paths which are keying index files.
   */
  private void initializeIndexLocations() {
    IPath[] projectsAndJars = this.searchScope.enclosingProjectsAndJars();
    IndexManager manager = JavaModelManager.getIndexManager();
    SimpleSet locations = new SimpleSet();
    IJavaElement focus = MatchLocator.projectOrJarFocus(this.pattern);
    if (focus == null) {
      for (int i = 0; i < projectsAndJars.length; i++) {
        IPath path = projectsAndJars[i];
        Object target = JavaModel.getTarget(path, false /*don't check existence*/);
        if (target instanceof IFolder) // case of an external folder
        path = ((IFolder) target).getFullPath();
        locations.add(manager.computeIndexLocation(path));
      }
    } else {
      try {
        // See whether the state builder might be used to reduce the number of index locations

        // find the projects from projectsAndJars that see the focus then walk those projects
        // looking for the jars from projectsAndJars
        int length = projectsAndJars.length;
        JavaProject[] projectsCanSeeFocus = new JavaProject[length];
        SimpleSet visitedProjects = new SimpleSet(length);
        int projectIndex = 0;
        SimpleSet externalLibsToCheck = new SimpleSet(length);
        ObjectVector superTypes = new ObjectVector();
        IJavaElement[] focuses = getFocusedElementsAndTypes(this.pattern, focus, superTypes);
        char[][][] focusQualifiedNames = null;
        boolean isAutoBuilding = ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
        if (isAutoBuilding && focus instanceof IJavaProject) {
          focusQualifiedNames = getQualifiedNames(superTypes);
        }
        IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
        for (int i = 0; i < length; i++) {
          IPath path = projectsAndJars[i];
          JavaProject project = (JavaProject) getJavaProject(path, model);
          if (project != null) {
            visitedProjects.add(project);
            if (canSeeFocus(focuses, project, focusQualifiedNames)) {
              locations.add(manager.computeIndexLocation(path));
              projectsCanSeeFocus[projectIndex++] = project;
            }
          } else {
            externalLibsToCheck.add(path);
          }
        }
        for (int i = 0; i < projectIndex && externalLibsToCheck.elementSize > 0; i++) {
          IClasspathEntry[] entries = projectsCanSeeFocus[i].getResolvedClasspath();
          for (int j = entries.length; --j >= 0; ) {
            IClasspathEntry entry = entries[j];
            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
              IPath path = entry.getPath();
              if (externalLibsToCheck.remove(path) != null) {
                Object target = JavaModel.getTarget(path, false /*don't check existence*/);
                if (target instanceof IFolder) // case of an external folder
                path = ((IFolder) target).getFullPath();
                locations.add(manager.computeIndexLocation(path));
              }
            }
          }
        }
        // jar files can be included in the search scope without including one of the projects that
        // references them, so scan all projects that have not been visited
        if (externalLibsToCheck.elementSize > 0) {
          IJavaProject[] allProjects = model.getJavaProjects();
          for (int i = 0, l = allProjects.length;
              i < l && externalLibsToCheck.elementSize > 0;
              i++) {
            JavaProject project = (JavaProject) allProjects[i];
            if (!visitedProjects.includes(project)) {
              IClasspathEntry[] entries = project.getResolvedClasspath();
              for (int j = entries.length; --j >= 0; ) {
                IClasspathEntry entry = entries[j];
                if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                  IPath path = entry.getPath();
                  if (externalLibsToCheck.remove(path) != null) {
                    Object target = JavaModel.getTarget(path, false /*don't check existence*/);
                    if (target instanceof IFolder) // case of an external folder
                    path = ((IFolder) target).getFullPath();
                    locations.add(manager.computeIndexLocation(path));
                  }
                }
              }
            }
          }
        }
      } catch (JavaModelException e) {
        // ignored
      }
    }

    this.indexLocations = new IPath[locations.elementSize];
    Object[] values = locations.values;
    int count = 0;
    for (int i = values.length; --i >= 0; )
      if (values[i] != null) this.indexLocations[count++] = (IPath) values[i];
  }