/**
  * Checks if all source files are existing. If not, create them.
  *
  * @param javaProj
  */
 private void checkSourceFolders(final IJavaProject javaProj) {
   if (javaProj == null) return;
   if (javaProj.exists()) {
     try {
       if (!javaProj.isOpen()) {
         javaProj.open(new NullProgressMonitor());
       }
       IClasspathEntry[] entries = javaProj.getRawClasspath();
       for (IClasspathEntry entry : entries) {
         if (IClasspathEntry.CPE_SOURCE == entry.getEntryKind()) {
           IPath path = entry.getPath();
           final IPath folderPath = path.removeFirstSegments(1);
           if (!folderPath.isEmpty()) {
             Display.getDefault()
                 .asyncExec(
                     new Runnable() {
                       public void run() {
                         try {
                           ImportUtils.createFolders(
                               javaProj.getProject(), folderPath, IResource.FORCE);
                         } catch (CoreException e) {
                           _log.error(e.getMessage());
                         }
                       }
                     });
           }
         }
       }
     } catch (JavaModelException e) {
       _log.error("findProjectSources: Could not retrieve project sources:", e); // $NON-NLS-1$
     }
   }
 }
 public void initFromSelection() {
   IJavaElement je = getSelectedJavaElement(selection);
   if (je instanceof IJavaProject) {
     IJavaProject jp = (IJavaProject) je;
     if (jp.isOpen()) {
       // default to the first source dir
       // we find in the selected project
       try {
         for (IPackageFragmentRoot pfr : jp.getAllPackageFragmentRoots()) {
           if (!pfr.isExternal() && !pfr.isArchive()) {
             je = pfr;
             break;
           }
         }
       } catch (JavaModelException e) {
       }
     }
   }
   if (je instanceof IPackageFragmentRoot) {
     sourceDir = (IPackageFragmentRoot) je;
     packageFragment = sourceDir.getPackageFragment("");
     packageName = packageFragment.getElementName();
   } else if (je instanceof IPackageFragment) {
     packageFragment = (IPackageFragment) je;
     packageName = packageFragment.getElementName();
     sourceDir = (IPackageFragmentRoot) packageFragment.getAncestor(PACKAGE_FRAGMENT_ROOT);
   }
 }
  protected void validateJavaAttribute(Element element, Attr attr) {
    String value = attr.getValue();
    IJavaProject javaProject = JavaCore.create(fFile.getProject());

    // be careful: people have the option to use the format:
    // fullqualifiedName:staticMethod
    int index = value.indexOf(":"); // $NON-NLS-1$
    if (index != -1) value = value.substring(0, index);

    // assume we're on the classpath already
    boolean onClasspath = true;
    int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_CLASS);
    if (severity != CompilerFlags.IGNORE && javaProject.isOpen()) {
      onClasspath = PDEJavaHelper.isOnClasspath(value, javaProject);
      if (!onClasspath) {
        report(
            NLS.bind(
                MDECoreMessages.Builders_Manifest_class, (new String[] {value, attr.getName()})),
            getLine(element, attr.getName()),
            severity,
            MDEMarkerFactory.P_UNKNOWN_CLASS,
            element,
            attr.getName() + F_ATT_VALUE_PREFIX + attr.getValue(),
            MDEMarkerFactory.CAT_FATAL);
      }
    }

    severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DISCOURAGED_CLASS);
    if (severity != CompilerFlags.IGNORE && javaProject.isOpen()) {
      BundleDescription desc = fModel.getBundleDescription();
      if (desc == null) return;
      // only check if we're discouraged if there is something on the classpath
      if (onClasspath && PDEJavaHelper.isDiscouraged(value, javaProject, desc)) {
        report(
            NLS.bind(
                MDECoreMessages.Builders_Manifest_discouragedClass,
                (new String[] {value, attr.getName()})),
            getLine(element, attr.getName()),
            severity,
            MDEMarkerFactory.M_DISCOURAGED_CLASS,
            element,
            attr.getName() + F_ATT_VALUE_PREFIX + attr.getValue(),
            MDEMarkerFactory.CAT_OTHER);
      }
    }
  }
  /** Handle browse package. */
  private void handleBrowsePackage() {

    IPackageFragment[] packages = null;
    IJavaProject javaProject = JavaCore.create(project);
    IJavaElement javaElementArray[] = null;
    ArrayList<IJavaElement> javaElementsList = new ArrayList<IJavaElement>();

    // Si el projecto no esta abierto se cancela el proceso
    if (javaProject.isOpen() == false) {
      MessageDialog.openError(
          getShell(),
          Messages.WizardPageChooseSourceFolderAndPackage_29,
          Messages.WizardPageChooseSourceFolderAndPackage_30);
      return;
    }

    // Lee los paquetes solo del proyecto
    try {
      packages = javaProject.getPackageFragments();

      for (IPackageFragment iPackageFragment : packages) {
        if (iPackageFragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
          javaElementsList.add(iPackageFragment);
        }
      }
      if (javaElementsList.size() > 0) {
        javaElementArray = new IJavaElement[javaElementsList.size()];
        javaElementArray = javaElementsList.toArray(javaElementArray);
      }
    } catch (JavaModelException e) {
      MessageDialog.openError(
          getShell(), Messages.WizardPageChooseSourceFolderAndPackage_31, e.getMessage());
    }

    Shell shell = getShell();
    IJavaSearchScope iJavaSearchScope = SearchEngine.createJavaSearchScope(javaElementArray, false);
    PackageSelectionDialog packageSelectionDialog =
        new PackageSelectionDialog(
            shell,
            new ProgressMonitorDialog(shell),
            PackageSelectionDialog.F_REMOVE_DUPLICATES | PackageSelectionDialog.F_HIDE_EMPTY_INNER,
            iJavaSearchScope);

    packageSelectionDialog.setTitle(Messages.WizardPageChooseSourceFolderAndPackage_32);
    packageSelectionDialog.setMessage(Messages.WizardPageChooseSourceFolderAndPackage_33);

    if (packageSelectionDialog.open() == Window.OK) {
      Object results[] = packageSelectionDialog.getResult();
      if (results != null && results.length > 0) {
        PackageFragment packageFragment = (PackageFragment) results[0];
        txtPackage.setText(packageFragment.getElementName());
        EclipseGeneratorUtil.javaEntityPackage = packageFragment.getElementName();
      }
    }
  }
예제 #5
0
  /**
   * Creates a JavaProject prom the given project
   *
   * @param project
   * @return the created JavaProject
   */
  public IJavaProject createJavaProject(IProject project) {
    try {
      // addJavaNature(project);
      IJavaProject javaProject = JavaCore.create(project);
      if (!javaProject.isOpen()) {
        javaProject.open(null);
      }
      createBinFolder(project, javaProject);
      clearSourcePath(javaProject);

      IClasspathEntry sourceFolder = createSourceFolder("src", project);

      addToClasspath(javaProject, sourceFolder);
      addJREContainerToProject(javaProject);
      return javaProject;
    } catch (CoreException e) {
      e.printStackTrace();
    }
    return null;
  }
예제 #6
0
  @Override
  public void initializeDefaults(ILaunchConfiguration configuration) throws CoreException {
    dispose();
    setLaunchConfiguration(configuration);
    String projectName =
        configuration.getAttribute(
            IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); // $NON-NLS-1$
    if (projectName != null && projectName.length() > 0) {
      IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
      if (project != null && project.isOpen()) {
        ProjectState state = Sdk.getProjectState(project);
        if (state == null) {
          initDefaults();
          return;
        }
        IAndroidTarget target = state.getTarget();
        if (target == null) {
          initDefaults();
          return;
        }
        //                String path = target.getPath(IAndroidTarget.ANDROID_JAR);
        String path = AdtPlugin.getAuidtJar();

        if (path == null) {
          initDefaults();
          return;
        }
        IJavaProject javaProject = JavaCore.create(project);
        if (javaProject != null && javaProject.isOpen()) {
          IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
          IClasspathEntry androidEntry = null;
          for (int i = 0; i < entries.length; i++) {
            IClasspathEntry entry = entries[i];
            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY
                && path.equals(entry.getPath().toString())) {
              androidEntry = entry;
              break;
            }
          }
          if (androidEntry != null) {
            IPath sourceAttachmentPath = androidEntry.getSourceAttachmentPath();
            if (sourceAttachmentPath != null) {
              String androidSrc = sourceAttachmentPath.toString();
              if (androidSrc != null && androidSrc.trim().length() > 0) {
                File srcFile = new File(androidSrc);
                ISourceContainer adtContainer = null;
                if (srcFile.isFile()) {
                  adtContainer = new ExternalArchiveSourceContainer(androidSrc, true);
                }
                if (srcFile.isDirectory()) {
                  adtContainer = new DirectorySourceContainer(srcFile, false);
                }
                if (adtContainer != null) {
                  ISourceContainer defaultContainer = new DefaultSourceContainer();
                  setSourceContainers(new ISourceContainer[] {adtContainer, defaultContainer});
                  initializeParticipants();
                  return;
                }
              }
            }
          }
        }
      }
    }
    initDefaults();
  }
예제 #7
0
  /**
   * Get the options that are presented to annotation processors by the
   * AnnotationProcessorEnvironment. Options are key/value pairs which are set in the project
   * properties.
   *
   * <p>Option values can begin with a percent-delimited token representing a classpath variable or
   * one of several predefined values. The token must either be followed by a path delimiter, or be
   * the entire value. Such tokens will be replaced with their resolved value. The predefined values
   * are <code>%ROOT%</code>, which is replaced by the absolute pathname of the workspace root
   * directory, and <code>%PROJECT.DIR%</code>, which will be replaced by the absolute pathname of
   * the project root directory. For example, a value of <code>
   * %ECLIPSE_HOME%/configuration/config.ini</code> might be resolved to <code>
   * d:/eclipse/configuration/config.ini</code>.
   *
   * <p>This method returns some options which are set programmatically but are not directly
   * editable, are not displayed in the configuration GUI, and are not persisted to the preference
   * store. This is meant to emulate the behavior of Sun's apt command-line tool, which passes most
   * of its command line options to the processor environment. The programmatically set options are:
   * <code>-classpath</code> [set to Java build path] <code>-sourcepath</code> [set to Java source
   * path] <code>-s</code> [set to generated src dir] <code>-d</code> [set to binary output dir]
   * <code>-target</code> [set to compiler target version] <code>-source</code> [set to compiler
   * source version]
   *
   * <p>There are some slight differences between the options returned by this method and the
   * options returned from this implementation of @see AnnotationProcessorEnvironment#getOptions().
   * First, that method returns additional options which are only meaningful during a build, such as
   * <code>phase</code>. Second, that method also adds alternate encodings of each option, to be
   * compatible with a bug in Sun's apt implementation: specifically, for each option key="k",
   * value="v", an additional option is created with key="-Ak=v", value=null. This includes the
   * user-created options, but does not include the programmatically defined options listed above.
   *
   * @param jproj a project, or null to query the workspace-wide setting.
   * @return a mutable, possibly empty, map of (key, value) pairs. The value part of a pair may be
   *     null (equivalent to "-Akey" on the Sun apt command line). The value part may contain
   *     spaces.
   */
  public static Map<String, String> getProcessorOptions(IJavaProject jproj) {
    Map<String, String> rawOptions = getRawProcessorOptions(jproj);
    // map is large enough to also include the programmatically generated options
    Map<String, String> options = new HashMap<String, String>(rawOptions.size() + 6);

    // Resolve path metavariables like %ROOT%
    for (Map.Entry<String, String> entry : rawOptions.entrySet()) {
      String resolvedValue = resolveVarPath(jproj, entry.getValue());
      String value = (resolvedValue == null) ? entry.getValue() : resolvedValue;
      options.put(entry.getKey(), value);
    }

    if (jproj == null) {
      // there are no programmatically set options at the workspace level
      return options;
    }

    IWorkspaceRoot root = jproj.getProject().getWorkspace().getRoot();

    // Add sourcepath and classpath variables
    try {
      IClasspathEntry[] classpathEntries = jproj.getResolvedClasspath(true);
      Set<String> classpath = new LinkedHashSet<String>();
      Set<String> sourcepath = new LinkedHashSet<String>();

      // For projects on the classpath, loops can exist; need to make sure we
      // don't loop forever
      Set<IJavaProject> projectsProcessed = new HashSet<IJavaProject>();
      projectsProcessed.add(jproj);
      for (IClasspathEntry entry : classpathEntries) {
        int kind = entry.getEntryKind();
        if (kind == IClasspathEntry.CPE_LIBRARY) {
          IPath cpPath = entry.getPath();

          IResource res = root.findMember(cpPath);

          // If res is null, the path is absolute (it's an external jar)
          if (res == null) {
            classpath.add(cpPath.toOSString());
          } else {
            // It's relative
            classpath.add(res.getLocation().toOSString());
          }
        } else if (kind == IClasspathEntry.CPE_SOURCE) {
          IResource res = root.findMember(entry.getPath());
          if (res == null) {
            continue;
          }
          IPath srcPath = res.getLocation();
          if (srcPath == null) {
            continue;
          }

          sourcepath.add(srcPath.toOSString());
        } else if (kind == IClasspathEntry.CPE_PROJECT) {
          // Add the dependent project's build path and classpath to ours
          IPath otherProjectPath = entry.getPath();
          IProject otherProject = root.getProject(otherProjectPath.segment(0));

          // Note: JavaCore.create() is safe, even if the project is null --
          // in that case, we get null back
          IJavaProject otherJavaProject = JavaCore.create(otherProject);

          // If it doesn't exist, ignore it
          if (otherJavaProject != null && otherJavaProject.isOpen()) {
            addProjectClasspath(root, otherJavaProject, projectsProcessed, classpath);
          }
        }
      }
      // if you add options here, also add them in isAutomaticProcessorOption(),
      // and document them in docs/reference/automatic_processor_options.html.

      // Classpath and sourcepath
      options.put("-classpath", convertPathCollectionToString(classpath)); // $NON-NLS-1$    	
      options.put("-sourcepath", convertPathCollectionToString(sourcepath)); // $NON-NLS-1$

      // Get absolute path for generated source dir
      IFolder genSrcDir = jproj.getProject().getFolder(getGenSrcDir(jproj));
      String genSrcDirString = genSrcDir.getRawLocation().toOSString();
      options.put("-s", genSrcDirString); // $NON-NLS-1$

      // Absolute path for bin dir as well
      IPath binPath = jproj.getOutputLocation();
      IResource binPathResource = root.findMember(binPath);
      String binDirString;
      if (binPathResource != null) {
        binDirString = root.findMember(binPath).getLocation().toOSString();
      } else {
        binDirString = binPath.toOSString();
      }
      options.put("-d", binDirString); // $NON-NLS-1$

      String target = jproj.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true);
      options.put("-target", target); // $NON-NLS-1$

      String source = jproj.getOption(JavaCore.COMPILER_SOURCE, true);
      options.put("-source", source); // $NON-NLS-1$
    } catch (JavaModelException jme) {
      AptPlugin.log(jme, "Could not get the classpath for project: " + jproj); // $NON-NLS-1$
    }

    return options;
  }