public boolean visit(IResource resource) throws CoreException {
      if (resource.isDerived()) {
        return false;
      }

      handler.handleResourceStart(resource);

      if (resource.getType() == IResource.FILE
          && ContentTypeUtils.isGroovyLikeFileName(resource.getName())) {
        if (Util.isExcluded(resource, includes, excludes)) {
          return false;
        }

        GroovyCompilationUnit unit = (GroovyCompilationUnit) JavaCore.create((IFile) resource);
        if (unit != null && unit.isOnBuildPath()) {
          if (monitor.isCanceled()) {
            throw new OperationCanceledException();
          }
          monitor.subTask(resource.getName());
          handler.setResource((IFile) resource);
          Map<Integer, String> commentsMap = findComments(unit);
          StaticTypeCheckerRequestor requestor =
              new StaticTypeCheckerRequestor(handler, commentsMap, onlyAssertions);
          TypeInferencingVisitorWithRequestor visitor =
              new TypeInferencingVisitorFactory().createVisitor(unit);
          try {
            unit.becomeWorkingCopy(monitor);
            visitor.visitCompilationUnit(requestor);
          } finally {
            unit.discardWorkingCopy();
          }
        }
      }
      return true;
    }
  /** {@inheritDoc} */
  @Override
  public void resourceChanged(IResourceChangeEvent pEvent) {

    if (IResourceChangeEvent.POST_CHANGE == pEvent.getType()) {
      // Extract all the additions among the changes
      IResourceDelta delta = pEvent.getDelta();
      IResourceDelta[] added = delta.getAffectedChildren();

      // In all the added resources, process the projects
      for (int i = 0, length = added.length; i < length; i++) {
        IResourceDelta addedi = added[i];

        // Get the project
        IResource resource = addedi.getResource();
        IProject project = resource.getProject();

        if (ProjectsManager.getProject(project.getName()) == null && project.isOpen()) {
          ProjectAdderJob job = new ProjectAdderJob(project);
          job.schedule();
        }
      }
    } else if (IResourceChangeEvent.PRE_DELETE == pEvent.getType()) {
      // detect UNO IDL project about to be deleted
      IResource removed = pEvent.getResource();
      if (ProjectsManager.getProject(removed.getName()) != null) {
        ProjectsManager.removeProject(removed.getName());
      }
    } else if (IResourceChangeEvent.PRE_CLOSE == pEvent.getType()) {
      IResource res = pEvent.getResource();
      if (res != null && ProjectsManager.getProject(res.getName()) != null) {
        // Project about to be closed: remove for the available uno projects
        ProjectsManager.removeProject(res.getName());
      }
    }
  }
Exemple #3
0
 public boolean visit(IResource resource) {
   if (resource instanceof IFile
       && (resource.getName().endsWith(".hts") || resource.getName().endsWith(".uxml"))) {
     codeUpdater.createUpdateInfo(resource, targetList);
   }
   return true; // continue visiting children.
 }
  @Override
  public StyledString getStyledText(Object element) {
    if (element instanceof IResource) {
      IResource resource = (IResource) element;

      // Un-analyzed resources are grey.
      if (!DartCore.isAnalyzed(resource)) {
        return new StyledString(resource.getName(), StyledString.QUALIFIER_STYLER);
      }

      StyledString string = new StyledString(resource.getName());

      DartElement dartElement = DartCore.create(resource);

      // Append the library name to library units.
      if (dartElement instanceof CompilationUnit) {
        if (((CompilationUnit) dartElement).definesLibrary()) {
          DartLibrary library = ((CompilationUnit) dartElement).getLibrary();

          string.append(" [" + library.getDisplayName() + "]", StyledString.QUALIFIER_STYLER);
        }
      }

      return string;
    }

    return workbenchLabelProvider.getStyledText(element);
  }
  public void newResource(final IResource resource) {
    if (resource instanceof IFile
        && resource.getName().endsWith(".groovy")
        && !resource.getName().endsWith("Tests.groovy")) {
      // Only open resource if is in any source folder
      IJavaProject jp = JdtUtils.getJavaProject(project);
      if (jp != null) {
        try {
          for (IClasspathEntry entry : jp.getRawClasspath()) {
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
              if (entry.getPath() != null && entry.getPath().isPrefixOf(resource.getFullPath())) {
                Display.getDefault()
                    .asyncExec(
                        new Runnable() {

                          public void run() {
                            SpringUIUtils.openInEditor((IFile) resource, -1);
                          }
                        });
                break;
              }
            }
          }
        } catch (JavaModelException e) {
        }
      }
    }
  }
Exemple #6
0
    public boolean visit(IResourceDelta delta) throws CoreException {
      IResource resource = delta.getResource();
      if (!(resource instanceof IFile)
          || !resource.getName().endsWith(".java")
          || !resource.exists()) {
        return true;
      }
      monitor.subTask(resource.getName());

      switch (delta.getKind()) {
        case IResourceDelta.ADDED:
          check(resource, architecture, true);
          monitor.worked(1);
          break;
        case IResourceDelta.REMOVED:
          delete(resource);
          monitor.worked(1);
          break;
        case IResourceDelta.CHANGED:
          check(resource, architecture, true);
          monitor.worked(1);
          break;
      }

      /* return true to continue visiting children */
      return true;
    }
  private void addLayoutFileChanges(IProject project, CompositeChange result) {
    try {
      // Update references in XML resource files
      IFolder resFolder = project.getFolder(SdkConstants.FD_RESOURCES);

      IResource[] folders = resFolder.members();
      for (IResource folder : folders) {
        String folderName = folder.getName();
        ResourceFolderType folderType = ResourceFolderType.getFolderType(folderName);
        if (folderType != ResourceFolderType.LAYOUT) {
          continue;
        }
        if (!(folder instanceof IFolder)) {
          continue;
        }
        IResource[] files = ((IFolder) folder).members();
        for (int i = 0; i < files.length; i++) {
          IResource member = files[i];
          if ((member instanceof IFile) && member.exists()) {
            IFile file = (IFile) member;
            String fileName = member.getName();

            if (SdkUtils.endsWith(fileName, DOT_XML)) {
              addXmlFileChanges(file, result, false);
            }
          }
        }
      }
    } catch (CoreException e) {
      RefactoringUtil.log(e);
    }
  }
 @Override
 public boolean select(Viewer viewer, Object parent, Object element) {
   IResource eRes = (IResource) element;
   if (eRes.getType() == IResource.PROJECT) {
     return this.projectName.equals(eRes.getName());
   }
   if (eRes.getType() == IResource.FILE) {
     return false;
   }
   if (eRes.getType() == IResource.FOLDER) {
     IProject project = eRes.getProject();
     if (!this.projectName.equals(project.getName())) {
       return false;
     }
     if (eRes.getParent().getType() == IResource.PROJECT) {
       try {
         String backupDir = VistACorePrefs.getServerBackupDirectory(project);
         return !eRes.getName().equals(backupDir);
       } catch (CoreException coreException) {
         StatusManager.getManager().handle(coreException.getStatus(), StatusManager.LOG);
         return false;
       }
     } else {
       return true;
     }
   }
   return true;
 }
Exemple #9
0
  /**
   * Final check before the actual refactoring
   *
   * @return status
   * @throws OperationCanceledException
   */
  public RefactoringStatus checkFinalConditions() throws OperationCanceledException {
    RefactoringStatus status = new RefactoringStatus();
    IContainer destination = fProcessor.getDestination();
    IProject sourceProject = fProcessor.getSourceSelection()[0].getProject();
    IProject destinationProject = destination.getProject();
    if (sourceProject != destinationProject)
      status.merge(MoveUtils.checkMove(phpFiles, sourceProject, destination));

    // Checks if one of the resources already exists with the same name in
    // the destination
    IPath dest = fProcessor.getDestination().getFullPath();
    IResource[] sourceResources = fProcessor.getSourceSelection();

    for (IResource element : sourceResources) {
      String newFilePath = dest.toOSString() + File.separatorChar + element.getName();
      IResource resource =
          ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(newFilePath));
      if (resource != null && resource.exists()) {
        status.merge(
            RefactoringStatus.createFatalErrorStatus(
                NLS.bind(
                    PhpRefactoringCoreMessages.getString("MoveDelegate.6"),
                    element.getName(),
                    dest.toOSString()))); // $NON-NLS-1$
      }
    }
    return status;
  }
        public Map<String, IStatus> validate(Object value, Object context) {

          if (value == null || "".equals(value)) { // $NON-NLS-1$
            return createErrormessage(
                new Status(
                    IStatus.ERROR,
                    SeamCorePlugin.PLUGIN_ID,
                    SeamCoreMessages.VALIDATOR_FACTORY_PRJ_NOT_SELECTED));
          }
          IResource project = ResourcesPlugin.getWorkspace().getRoot().findMember(value.toString());

          if (project == null || !(project instanceof IProject) || !project.exists()) {
            return createErrormessage(
                new Status(
                    IStatus.ERROR,
                    SeamCorePlugin.PLUGIN_ID,
                    NLS.bind(SeamCoreMessages.VALIDATOR_FACTORY_PROJECT_DOES_NOT_EXIST, value)));
          } else {
            IProject selection = (IProject) project;
            try {
              if (!selection.hasNature(ISeamProject.NATURE_ID)
                  || SeamCorePlugin.getSeamPreferences(selection) == null
                  // ||
                  // selection.getAdapter(IFacetedProject.class)==null
                  // || !((IFacetedProject)selection.getAdapter(
                  // IFacetedProject
                  // .class)).hasProjectFacet(ProjectFacetsManager
                  // .getProjectFacet("jst.web"))
                  || ""
                      .equals(
                          SeamCorePlugin.getSeamPreferences(selection)
                              .get(
                                  ISeamFacetDataModelProperties.JBOSS_AS_DEPLOY_AS,
                                  ""))) { //$NON-NLS-1$
                return createErrormessage(
                    new Status(
                        IStatus.ERROR,
                        SeamCorePlugin.PLUGIN_ID,
                        NLS.bind(
                            SeamCoreMessages
                                .VALIDATOR_FACTORY_SELECTED_PROJECT_IS_NOT_A_SEAM_WEB_PROJECT,
                            project.getName())));
              } else {
                // TODO validate project(s) structure
              }
            } catch (CoreException e) {
              // it might happen only if project is closed and project
              // name typed by hand
              return createErrormessage(
                  new Status(
                      IStatus.ERROR,
                      SeamCorePlugin.PLUGIN_ID,
                      NLS.bind(
                          SeamCoreMessages.VALIDATOR_FACTORY_SELECTED_PRJ_IS_CLOSED,
                          project.getName())));
            }
          }
          return NO_ERRORS;
        }
Exemple #11
0
 public boolean visit(IResource resource) throws CoreException {
   if (resource instanceof IFile && resource.getName().endsWith(".java")) {
     monitor.subTask(resource.getName());
     check(resource, architecture, reextractDependencies);
     monitor.worked(1);
   }
   return true;
 }
  private void configure(
      final IProject project,
      Collection<IFile> filesToAnalyze,
      final Properties properties,
      final IProgressMonitor monitor) {
    String projectName = project.getName();
    String encoding;
    try {
      encoding = project.getDefaultCharset();
    } catch (CoreException e) {
      throw new SonarEclipseException("Unable to get charset from project", e);
    }

    properties.setProperty(SonarLintProperties.PROJECT_NAME_PROPERTY, projectName);
    properties.setProperty(SonarLintProperties.PROJECT_VERSION_PROPERTY, "0.1-SNAPSHOT");
    properties.setProperty(SonarLintProperties.ENCODING_PROPERTY, encoding);

    ProjectConfigurationRequest configuratorRequest =
        new ProjectConfigurationRequest(project, filesToAnalyze, properties);
    Collection<ProjectConfigurator> configurators = ConfiguratorUtils.getConfigurators();
    for (ProjectConfigurator configurator : configurators) {
      if (configurator.canConfigure(project)) {
        configurator.configure(configuratorRequest, monitor);
        usedConfigurators.add(configurator);
      }
    }

    ProjectConfigurator.appendProperty(
        properties,
        SonarConfiguratorProperties.TEST_INCLUSIONS_PROPERTY,
        PreferencesUtils.getTestFileRegexps());
    if (!properties.containsKey(SonarConfiguratorProperties.SOURCE_DIRS_PROPERTY)
        && !properties.containsKey(SonarConfiguratorProperties.TEST_DIRS_PROPERTY)) {
      // Try to analyze all files
      properties.setProperty(SonarConfiguratorProperties.SOURCE_DIRS_PROPERTY, ".");
      properties.setProperty(SonarConfiguratorProperties.TEST_DIRS_PROPERTY, ".");
      // Try to exclude derived folders
      try {
        for (IResource member : project.members()) {
          if (member.isDerived()) {
            ProjectConfigurator.appendProperty(
                properties,
                SonarConfiguratorProperties.SOURCE_EXCLUSIONS_PROPERTY,
                member.getName() + "/**/*");
            ProjectConfigurator.appendProperty(
                properties,
                SonarConfiguratorProperties.TEST_EXCLUSIONS_PROPERTY,
                member.getName() + "/**/*");
          }
        }
      } catch (CoreException e) {
        throw new IllegalStateException("Unable to list members of " + project, e);
      }
    }
  }
 public String getText(Object obj) {
   if (obj instanceof IFolder) {
     IResource res = (IResource) obj;
     return StringUtils.capitalize(res.getName());
   } else if (obj instanceof IFile) {
     IResource res = (IResource) obj;
     return res.getName();
   } else {
     return obj.toString();
   }
 }
Exemple #14
0
  public IRpcFuture startCompileErl(
      final IProject project,
      final BuildResource bres,
      final String outputDir0,
      final IBackend backend,
      final OtpErlangList compilerOptions,
      final boolean force) {
    final IPath projectPath = project.getLocation();
    final IResource res = bres.getResource();
    final String s = res.getFileExtension();
    if (!"erl".equals(s)) {
      ErlLogger.warn("trying to compile " + res.getName() + "?!?!");
    }

    MarkerUtils.deleteMarkers(res);

    String outputDir;
    outputDir = getRealOutputDir(bres, outputDir0, projectPath);

    final Collection<IPath> includeDirs = getAllIncludeDirs(project);

    // delete beam file
    final IPath beamPath = getBeamForErl(res);
    final IResource beam = project.findMember(beamPath);

    try {
      final boolean shouldCompile = force || shouldCompile(project, res, beam);

      if (shouldCompile) {
        if (beam != null) {
          try {
            beam.delete(true, null);
          } catch (final Exception e) {
            ErlLogger.warn(e);
          }
        }
        if (isDebugging()) {
          ErlLogger.debug("compiling %s", res.getName());
        }

        createTaskMarkers(project, res);
        return InternalErlideBuilder.compileErl(
            backend, res.getLocation(), outputDir, includeDirs, compilerOptions);

      } else {
        return null;
      }
    } catch (final Exception e) {
      ErlLogger.warn(e);
      return null;
    }
  }
Exemple #15
0
 @Override
 public int compare(Viewer viewer, Object e1, Object e2) {
   if (e1 instanceof IFolder && e2 instanceof IFile) {
     return -1;
   } else if (e1 instanceof IFile && e2 instanceof IFolder) {
     return 1;
   } else if (e1 instanceof IResource && e2 instanceof IResource) {
     IResource r1 = (IResource) e1;
     IResource r2 = (IResource) e2;
     return r1.getName().compareToIgnoreCase(r2.getName());
   } else {
     return super.compare(viewer, e1, e2);
   }
 }
 /**
  * @param resource
  * @param sourceFilesArg
  * @throws CoreException
  */
 private void getAllSourceFiles(IResource resource, List sourceFilesArg) throws CoreException {
   if (resource != null) {
     if (resource.getName().endsWith(".java")
         || resource.getName().endsWith(".cj")) { // $NON-NLS-1$ //$NON-NLS-2$
       sourceFilesArg.add(resource.getFullPath().toOSString());
     } else if (resource instanceof Container) {
       Container container = (Container) resource;
       IResource[] resources = container.members();
       for (int i = 0; i < resources.length; i++) {
         getAllSourceFiles(resources[i], sourceFilesArg);
       }
     }
   }
 }
 @Override
 public boolean visit(IResource resource) throws CoreException {
   System.out.println("Visit called on " + resource.getName());
   if (resource.getType() == IResource.FILE && JavaCore.isJavaLikeFileName(resource.getName())) {
     methodLocations = MethodLocations.getInstance();
     methodLocations.clearLocations();
     ICompilationUnit icu = JavaCore.createCompilationUnitFrom((IFile) resource);
     CompilationUnit cu = parse(icu);
     cu.accept(new MyASTVisitor());
     processComments(cu);
     DatabaseLoader.getInstance().workedFile();
   }
   return true;
 }
Exemple #18
0
  /**
   * 取得Method相關資訊
   *
   * @param resource 來源
   * @param methodIdx Method的Index
   * @return 是否成功
   */
  protected boolean findCurrentMethod(IResource resource, int methodIdx) {
    if (resource instanceof IFile && resource.getName().endsWith(".java")) {
      try {
        IJavaElement javaElement = JavaCore.create(resource);

        if (javaElement instanceof IOpenable) {
          actOpenable = (IOpenable) javaElement;
        }

        // Create AST to parse
        ASTParser parser = ASTParser.newParser(AST.JLS3);
        parser.setKind(ASTParser.K_COMPILATION_UNIT);

        parser.setSource((ICompilationUnit) javaElement);
        parser.setResolveBindings(true);
        actRoot = (CompilationUnit) parser.createAST(null);
        // AST 2.0紀錄方式
        actRoot.recordModifications();

        // 取得該class所有的method
        ASTMethodCollector methodCollector = new ASTMethodCollector();
        actRoot.accept(methodCollector);
        List<MethodDeclaration> methodList = methodCollector.getMethodList();

        // 取得目前要被修改的method node
        currentMethodNode = methodList.get(methodIdx);

        return true;
      } catch (Exception ex) {
        logger.error("[Find DH Method] EXCEPTION ", ex);
      }
    }
    return false;
  }
  protected boolean checkForClassFileChanges(
      IResourceDelta binaryDelta, ClasspathMultiDirectory md, int segmentCount)
      throws CoreException {
    IResource resource = binaryDelta.getResource();
    // remember that if inclusion & exclusion patterns change then a full build is done
    boolean isExcluded =
        (md.exclusionPatterns != null || md.inclusionPatterns != null)
            && Util.isExcluded(resource, md.inclusionPatterns, md.exclusionPatterns);
    switch (resource.getType()) {
      case IResource.FOLDER:
        if (isExcluded && md.inclusionPatterns == null)
          return true; // no need to go further with this delta since its children cannot be
        // included

        IResourceDelta[] children = binaryDelta.getAffectedChildren();
        for (int i = 0, l = children.length; i < l; i++)
          if (!checkForClassFileChanges(children[i], md, segmentCount)) return false;
        return true;
      case IResource.FILE:
        if (!isExcluded
            && org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(resource.getName())) {
          // perform full build if a managed class file has been changed
          IPath typePath =
              resource.getFullPath().removeFirstSegments(segmentCount).removeFileExtension();
          if (this.newState.isKnownType(typePath.toString())) {
            if (JavaBuilder.DEBUG)
              System.out.println(
                  "MUST DO FULL BUILD. Found change to class file " + typePath); // $NON-NLS-1$
            return false;
          }
          return true;
        }
    }
    return true;
  }
 @Override
 public synchronized void resourceChanged(IResourceChangeEvent event) {
   IResource res = event.getResource();
   if (!(res instanceof IProject)) return;
   String name = res.getName();
   IResourceDelta delta = event.getDelta();
   if (delta == null) return;
   int kind = delta.getKind();
   if (configs.containsKey(name)) {
     if (kind == IResourceDelta.REMOVED) {
       configs.remove(name);
       tmpConfigs.remove(name);
     } else if (kind == IResourceDelta.CHANGED) {
       int flags = delta.getFlags();
       if ((flags & IResourceDelta.MOVED_TO) != 0) {
         IPath path = delta.getMovedToPath();
         Map<String, IAConfiguration> cfgs = configs.get(name);
         String newName = path.lastSegment();
         configs.remove(name);
         configs.put(newName, cfgs);
         Map<String, IAConfiguration> tmpcfgs = tmpConfigs.get(name);
         tmpConfigs.remove(name);
         tmpConfigs.put(newName, tmpcfgs);
       }
     }
   }
 }
  /**
   * Set up the selection values for the resources and put them in the selectionMap. If a resource
   * is a file see if it matches one of the selected extensions. If not then check the children.
   */
  private void setupSelectionsBasedOnSelectedTypes(Map selectionMap, IContainer parent) {

    List selections = new ArrayList();
    IResource[] resources;
    boolean hasFiles = false;

    try {
      resources = parent.members();
    } catch (CoreException exception) {
      // Just return if we can't get any info
      return;
    }

    for (int i = 0; i < resources.length; i++) {
      IResource resource = resources[i];
      if (resource.getType() == IResource.FILE) {
        if (hasExportableExtension(resource.getName())) {
          hasFiles = true;
          selections.add(resource);
        }
      } else {
        setupSelectionsBasedOnSelectedTypes(selectionMap, (IContainer) resource);
      }
    }

    // Only add it to the list if there are files in this folder
    if (hasFiles) {
      selectionMap.put(parent, selections);
    }
  }
 @Override
 public void exportArtifact(
     List<ArtifactData> artifactList,
     Map<IProject, Map<String, IResource>> resourceProjectList,
     IFolder splitESBResources,
     DependencyData dependencyData,
     Object parent,
     Object self)
     throws Exception {
   IProject resProject = (IProject) parent;
   if (!resourceProjectList.containsKey(resProject)) {
     Map<String, IResource> artifacts = new HashMap<String, IResource>();
     List<IResource> buildProject =
         ExportUtil.buildProject(resProject, dependencyData.getCApptype());
     for (IResource res : buildProject) {
       if (res instanceof IFolder) {
         artifacts.put(res.getName(), res);
       }
     }
     resourceProjectList.put(resProject, artifacts);
   }
   if (resourceProjectList.containsKey(resProject)) {
     Map<String, IResource> artifacts = resourceProjectList.get(resProject);
     if (artifacts.containsKey(getArtifactDir(dependencyData))) {
       ArtifactData artifactData = new ArtifactData();
       artifactData.setDependencyData(dependencyData);
       artifactData.setFile("registry-info.xml");
       artifactData.setResource(artifacts.get(getArtifactDir(dependencyData)));
       artifactList.add(artifactData);
     }
   }
 }
  public void decorate(Object element, IDecoration decoration) {
    if (!(element instanceof IResource)) return;
    IResource resource = (IResource) element;
    if (!resource.exists()) return;
    IProject project = resource.getProject();
    if (project == null) {
      Log.error(
          Messages.getString("ErrorDecorator.PROJECT_FOR")
              + resource.getName()
              + Messages.getString("ErrorDecorator.IS_NULL"),
          new Throwable()); //$NON-NLS-1$ //$NON-NLS-2$
      return;
    }
    try {
      if (!project.isOpen()) return;
      project.open(null);
      if (project.hasNature(LSLProjectNature.ID)) {
        LSLProjectNature nature = (LSLProjectNature) project.getNature(LSLProjectNature.ID);

        if (nature == null) return;

        IMarker[] m =
            resource.findMarkers("lslforge.problem", true, IResource.DEPTH_INFINITE); // $NON-NLS-1$

        if (m == null || m.length == 0) return;
      } else {
        return;
      }
    } catch (CoreException e) {
      Log.error("exception caught trying to determine project nature!", e); // $NON-NLS-1$
      return;
    }

    decoration.addOverlay(descriptor, IDecoration.BOTTOM_LEFT);
  }
 private void setSelectedEditor(String fileName) {
   outer:
   for (IWorkbenchWindow w : PlatformUI.getWorkbench().getWorkbenchWindows()) {
     for (IWorkbenchPage p : w.getPages()) {
       for (IEditorReference e : p.getEditorReferences()) {
         try {
           if (e.getEditorInput() instanceof IFileEditorInput) {
             IFileEditorInput editorInput = (IFileEditorInput) e.getEditorInput();
             if (editorInput.getFile().getParent().findMember("opaeum.properties") != null) {
               for (IResource r : editorInput.getFile().getParent().members()) {
                 if (r.getName().equals(fileName)) {
                   selectedEditor = e.getEditor(true);
                   break outer;
                 }
               }
             }
           }
         } catch (PartInitException e1) {
           e1.printStackTrace();
         } catch (CoreException e2) {
           e2.printStackTrace();
         }
       }
     }
   }
 }
  public void elementEncode(XMLWriter writer, IPath projectPath, boolean newLine) {
    // Keeping this as a HashMap (not a Map) for the XMLWriter
    HashMap parameters = new HashMap();

    parameters.put(TAG_ENTRY_KIND, IncludePathEntry.entryKindToString(this.entryKind));
    parameters.put(TAG_CONTENT_KIND, IncludePathEntry.contentKindToString(this.contentKind));
    parameters.put(
        TAG_CREATEDREFERENCE, createdReference ? "true" : "false"); // $NON-NLS-1$ //$NON-NLS-2$

    IPath xmlPath = this.path;
    if (this.entryKind != IIncludePathEntry.IPE_VARIABLE
        && this.entryKind != IIncludePathEntry.IPE_CONTAINER) {
      // translate to project relative from absolute (unless a device path)
      if (projectPath != null && projectPath.isPrefixOf(xmlPath)) {
        if (xmlPath.segment(0).equals(projectPath.segment(0))) {
          xmlPath = xmlPath.removeFirstSegments(1);
          xmlPath = xmlPath.makeRelative();
        } else {
          xmlPath = xmlPath.makeAbsolute();
        }
      }
    }
    parameters.put(TAG_PATH, String.valueOf(xmlPath));
    if (resource != null) {
      parameters.put(TAG_RESOURCE, resource.getName());
    }
    if (this.isExported) {
      parameters.put(TAG_EXPORTED, "true"); // $NON-NLS-1$
    }

    writer.printTag(TAG_INCLUDEPATHENTRY, parameters);
    writer.endTag(TAG_INCLUDEPATHENTRY);
  }
  protected IFile getManifest(IPackageFragmentRoot[] roots, IJavaProject javaProject)
      throws CoreException {

    IFolder metaFolder = null;
    for (IPackageFragmentRoot root : roots) {
      if (!root.isArchive() && !root.isExternal()) {
        IResource resource = root.getResource();
        metaFolder = getMetaFolder(resource);
        if (metaFolder != null) {
          break;
        }
      }
    }

    // Otherwise look for manifest file in the java project:
    if (metaFolder == null) {
      metaFolder = getMetaFolder(javaProject.getProject());
    }

    if (metaFolder != null) {
      IResource[] members = metaFolder.members();
      if (members != null) {
        for (IResource mem : members) {
          if (MANIFEST_FILE.equals(mem.getName().toUpperCase()) && mem instanceof IFile) {
            return (IFile) mem;
          }
        }
      }
    }

    return null;
  }
  private void restoreTestProject() throws Exception {
    IJavaProject javaProject = getRoot().getJavaProject();
    if (javaProject.exists()) {
      IClasspathEntry srcEntry = getRoot().getRawClasspathEntry();
      IClasspathEntry jreEntry = RefactoringTestSetup.getJRELibrary().getRawClasspathEntry();
      IClasspathEntry[] cpes = javaProject.getRawClasspath();
      ArrayList newCPEs = new ArrayList();
      boolean cpChanged = false;
      for (int i = 0; i < cpes.length; i++) {
        IClasspathEntry cpe = cpes[i];
        if (cpe.equals(srcEntry) || cpe.equals(jreEntry)) {
          newCPEs.add(cpe);
        } else {
          cpChanged = true;
        }
      }
      if (cpChanged) {
        IClasspathEntry[] newCPEsArray =
            (IClasspathEntry[]) newCPEs.toArray(new IClasspathEntry[newCPEs.size()]);
        javaProject.setRawClasspath(newCPEsArray, null);
      }

      Object[] nonJavaResources = javaProject.getNonJavaResources();
      for (int i = 0; i < nonJavaResources.length; i++) {
        Object kid = nonJavaResources[i];
        if (kid instanceof IResource) {
          IResource resource = (IResource) kid;
          if (!PROJECT_RESOURCE_CHILDREN.contains(resource.getName())) {
            JavaProjectHelper.delete(resource);
          }
        }
      }
    }
  }
Exemple #28
0
  public static void addEGLPathToJavaPathIfNecessary(
      IJavaProject javaProject, IProject currProject, Set<IProject> seen, List<String> classpath) {
    if (seen.contains(currProject)) {
      return;
    }
    seen.add(currProject);

    try {
      if (currProject.hasNature(EGLCore.NATURE_ID)) {
        IEGLProject eglProject = EGLCore.create(currProject);
        for (IEGLPathEntry pathEntry : eglProject.getResolvedEGLPath(true)) {
          if (pathEntry.getEntryKind() == IEGLPathEntry.CPE_PROJECT) {
            IPath path = pathEntry.getPath();
            IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
            try {
              if (resource != null
                  && resource.getType() == IResource.PROJECT
                  && !seen.contains(resource)
                  && ((IProject) resource).hasNature(JavaCore.NATURE_ID)
                  && !javaProject.isOnClasspath(resource)) {
                classpath.add(getWorkspaceProjectClasspathEntry(resource.getName()));
                addEGLPathToJavaPathIfNecessary(javaProject, (IProject) resource, seen, classpath);
              }
            } catch (CoreException ce) {
            }
          }
        }
      }
    } catch (EGLModelException e) {
    } catch (CoreException e) {
    }
  }
    @SuppressWarnings("unchecked")
    public int compare(final Viewer viewer, final Object obj1, final Object obj2) {
      final IResource r1 = (IResource) obj1;
      final IResource r2 = (IResource) obj2;

      final boolean isResource1Container = (r1 instanceof IContainer);
      final boolean isResource2Container = (r2 instanceof IContainer);

      if (isResource1Container == isResource2Container) {
        return Policy.getComparator().compare(r1.getName(), r2.getName());
      } else if (isResource1Container) {
        return -1;
      } else {
        return 1;
      }
    }
  @Override
  public Change createChange(IProgressMonitor monitor)
      throws CoreException, OperationCanceledException {
    IFolder assetsFolder = resource.getProject().getFolder("assets");
    if (assetsFolder == null || !assetsFolder.exists()) {
      return null;
    }

    if (!"assets".equals(resource.getProjectRelativePath().segment(0))) {
      return null;
    }

    if (resource instanceof IFile && Assets.getAssetType(resource.getName()) == null) {
      return null;
    }

    IResource[] rootResources =
        RefractoringUtils.getSearchScopeRootResources(resource.getProject());
    if (Values.isEmpty(rootResources)) {
      return null;
    }

    IPath assetsFolderPath = assetsFolder.getProjectRelativePath();
    IPath oldResourcePath = resource.getProjectRelativePath().makeRelativeTo(assetsFolderPath);
    String newName = getArguments().getNewName();
    IPath newResourcePath = oldResourcePath.removeLastSegments(1).append(newName);

    String regex =
        "(?<=[[:|\\s|\\r|\\n]{1}[\\s|\\r|\\n]{0,100}]|^)"
            + Pattern.quote(oldResourcePath.toString())
            + "(?=\"|/|\\s|\\r|\\n|$)";
    return RefractoringUtils.createChange(
        false, monitor, rootResources, regex, newResourcePath.toString());
  }