/**
   * Map public URLs to Alt URLs. Replaces {@link URLHyperlink}s computed by default by instances
   * with the alternative URL.
   *
   * @param hyperlinks
   */
  private IHyperlink[] removeURLHyperlinksOfManagedResources(IHyperlink[] hyperlinks) {
    if (hyperlinks == null) return hyperlinks;

    List<IHyperlink> result = new ArrayList<>(hyperlinks.length);
    for (int i = 0; i < hyperlinks.length; i++) {
      IHyperlink hyperlink = hyperlinks[i];
      if (hyperlink instanceof URLHyperlink) {
        URLHyperlink urlHyperlink = (URLHyperlink) hyperlink;
        String publicUri = urlHyperlink.getURLString();
        IConfigurationManagerForIDE cmgr = null;
        try {
          // get the configuration manager for the edited resource
          IResource editedResource =
              (IResource) getEditor().getEditorInput().getAdapter(IResource.class);
          SadlModelManager visitor =
              sadlModelManagerProvider.get(URI.createURI(editedResource.getLocation().toString()));
          cmgr = visitor.getConfigurationMgr(editedResource.getLocation().toString());

          // map the public URL to the mapped URL
          String altUrl = cmgr.getAltUrlFromPublicUri(publicUri);
          result.add(new URLHyperlinkExt(hyperlink.getHyperlinkRegion(), altUrl));
          // TODO: Actually this hyperlink should not be added
          // but if left out, also no Xtext hyperlink appears. Have to check out why
          // at least this one is mapped
        } catch (ConfigurationException | URISyntaxException | IOException e) {
        }
      } else {
        result.add(hyperlink);
      }
    }
    return result.toArray(hyperlinks);
  }
예제 #2
0
 public void test_DartImportImplTest_1() throws Exception {
   DartImportContainerImpl container = new DartImportContainerImpl(null);
   DartLibraryImpl lib = (DartLibraryImpl) MoneyProjectUtilities.getMoneyLibrary();
   DartImportImpl element = new DartImportImpl(container, lib.getLibrarySourceFile());
   assertTrue(element.getImportName().endsWith("money.dart"));
   IResource res = element.resource();
   assertEquals("money.dart", res.getLocation().lastSegment());
   res = element.getUnderlyingResource();
   assertEquals("money.dart", res.getLocation().lastSegment());
 }
예제 #3
0
  /* (non-Javadoc)
   * @see org.eclipse.cdt.managedbuilder.builddescription.IBuildResource#getLocation()
   */
  public IPath getLocation() {
    if (fFullWorkspacePath == null) {
      return new Path(fLocationURI.getPath());
    }

    IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(fFullWorkspacePath);
    if (resource == null) {
      return new Path(fLocationURI.getPath());
    }

    if (resource.getLocation() != null) return resource.getLocation();
    else return new Path(fLocationURI.getPath());
  }
예제 #4
0
 protected String packageNameForComponentFolder(IFolder folder) {
   try {
     for (IResource resource : folder.members()) {
       if ("wo".equals(resource.getLocation().getFileExtension())) {
         return packageNameForComponent(
             resource.getLocation().removeFileExtension().lastSegment());
       }
     }
   } catch (CoreException e) {
     e.printStackTrace();
   }
   return null;
 }
  private void setClassLoader() {
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    IJavaProject javaProject = getJavaProject();

    try {
      if (javaProject != null) {
        List<URL> entries = new ArrayList<URL>();
        IPath path = javaProject.getOutputLocation();
        IResource iResource = root.findMember(path);
        path = iResource.getLocation();
        path = path.addTrailingSeparator();
        entries.add(path.toFile().toURL());

        IClasspathEntry[] cpEntries = javaProject.getRawClasspath();
        for (IClasspathEntry cpEntry : cpEntries) {
          switch (cpEntry.getEntryKind()) {
            case IClasspathEntry.CPE_SOURCE:
              path = cpEntry.getOutputLocation();
              if (path != null) {
                iResource = root.findMember(path);
                path = iResource.getLocation();
                path = path.addTrailingSeparator();
                entries.add(path.toFile().toURL());
              }
              break;

            case IClasspathEntry.CPE_LIBRARY:
              iResource = root.findMember(cpEntry.getPath());
              if (iResource == null) {
                // resource is not in workspace, must be an external JAR
                path = cpEntry.getPath();
              } else {
                path = iResource.getLocation();
              }
              entries.add(path.toFile().toURL());
              break;
          }
        }

        ClassLoader oldCl = Thread.currentThread().getContextClassLoader();
        URL[] entryArray = new URL[entries.size()];
        entries.toArray(entryArray);
        ClassLoader newCl = new URLClassLoader(entryArray, oldCl);
        Thread.currentThread().setContextClassLoader(newCl);
        oldClassLoader = oldCl;
      }
    } catch (Exception e) {
      // ignore - something too complex is wrong
      ;
    }
  }
  @Override
  public void setFocus() {

    super.setFocus();

    MoMLParser.purgeAllModelRecords();

    if (actor == null && momlPath != null) {
      final MoMLParser parser = new MoMLParser(new Workspace());
      try {
        final IResource moml = ResourcesPlugin.getWorkspace().getRoot().findMember(momlPath);
        CompositeActor toplevel =
            (CompositeActor) parser.parse(null, new File(moml.getLocation().toString()).toURL());
        toplevel.workspace().setName(moml.getProject().getName());
        ComponentEntity entity = PasserelleProjectUtils.findEntityByName(toplevel, actorName);

        if (entity != null && entity.getName().equals(actorName)) {
          this.actor = (SubstitutionParticipant) entity;
        }

      } catch (Exception e) {
        logger.error("Cannot parse " + momlPath, e);
      }
    }

    if (actor != null) {
      viewer.setContentProvider(createActorContentProvider());
      viewer.setInput(new Object());
    }
  }
예제 #7
0
 /** Initialize this index with information from the user libraries. */
 private boolean indexUserLibraries() {
   boolean librariesIndexed = true;
   try {
     AnalysisServer analysisServer = PackageLibraryManagerProvider.getDefaultAnalysisServer();
     SavedContext savedContext = analysisServer.getSavedContext();
     DartModel model = DartCore.create(ResourcesPlugin.getWorkspace().getRoot());
     for (DartProject project : model.getDartProjects()) {
       for (DartLibrary library : project.getDartLibraries()) {
         CompilationUnit compilationUnit = library.getDefiningCompilationUnit();
         if (compilationUnit == null) {
           continue;
         }
         IResource libraryResource = compilationUnit.getResource();
         if (libraryResource == null) {
           continue;
         }
         IPath libraryLocation = libraryResource.getLocation();
         if (libraryLocation == null) {
           continue;
         }
         File libraryFile = libraryLocation.toFile();
         savedContext.resolve(libraryFile, null);
       }
     }
   } catch (Exception exception) {
     librariesIndexed = false;
     DartCore.logError("Could not index user libraries", exception);
   }
   return librariesIndexed;
 }
예제 #8
0
 /**
  * Returns the location of the Javadoc.
  *
  * @param element whose Javadoc location has to be found
  * @param isBinary <code>true</code> if the Java element is from a binary container
  * @return the location URL of the Javadoc or <code>null</code> if the location cannot be found
  * @throws JavaModelException thrown when the Java element cannot be accessed
  * @since 3.9
  */
 public static String getBaseURL(IJavaElement element, boolean isBinary)
     throws JavaModelException {
   if (isBinary) {
     // Source attachment usually does not include Javadoc resources
     // => Always use the Javadoc location as base:
     URL baseURL = JavaUI.getJavadocLocation(element, false);
     if (baseURL != null) {
       if (baseURL.getProtocol().equals(JAR_PROTOCOL)) {
         // It's a JarURLConnection, which is not known to the browser widget.
         // Let's start the help web server:
         URL baseURL2 =
             PlatformUI.getWorkbench().getHelpSystem().resolve(baseURL.toExternalForm(), true);
         if (baseURL2 != null) { // can be null if org.eclipse.help.ui is not available
           baseURL = baseURL2;
         }
       }
       return baseURL.toExternalForm();
     }
   } else {
     IResource resource = element.getResource();
     if (resource != null) {
       /*
        * Too bad: Browser widget knows nothing about EFS and custom URL handlers,
        * so IResource#getLocationURI() does not work in all cases.
        * We only support the local file system for now.
        * A solution could be https://bugs.eclipse.org/bugs/show_bug.cgi?id=149022 .
        */
       IPath location = resource.getLocation();
       if (location != null) return location.toFile().toURI().toString();
     }
   }
   return null;
 }
예제 #9
0
 /**
  * Determine if the specified event should be forwarded to listeners.
  *
  * @param event the event, not {@code null}
  * @return {@code true} if the event should be forwarded
  */
 private boolean shouldForward(ResourceDeltaEvent event) {
   if (hasIgnores) {
     IResource res = event.getResource();
     if (res == null || ignoreManager.isIgnored(res.getLocation())) {
       return false;
     }
   }
   return true;
 }
예제 #10
0
  // We need this as a separate method, as we'll put dependent projects' output
  // on the classpath
  private static void addProjectClasspath(
      IWorkspaceRoot root,
      IJavaProject otherJavaProject,
      Set<IJavaProject> projectsProcessed,
      Set<String> classpath) {

    // Check for cycles. If we've already seen this project,
    // no need to go any further.
    if (projectsProcessed.contains(otherJavaProject)) {
      return;
    }
    projectsProcessed.add(otherJavaProject);

    try {
      // Add the output directory first as a binary entry for other projects
      IPath binPath = otherJavaProject.getOutputLocation();
      IResource binPathResource = root.findMember(binPath);
      String binDirString;
      if (binPathResource != null) {
        binDirString = root.findMember(binPath).getLocation().toOSString();
      } else {
        binDirString = binPath.toOSString();
      }
      classpath.add(binDirString);

      // Now the rest of the classpath
      IClasspathEntry[] classpathEntries = otherJavaProject.getResolvedClasspath(true);
      for (IClasspathEntry entry : classpathEntries) {
        if (entry.getEntryKind() == 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 (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
          IPath otherProjectPath = entry.getPath();
          IProject otherProject = root.getProject(otherProjectPath.segment(0));
          IJavaProject yetAnotherJavaProject = JavaCore.create(otherProject);
          if (yetAnotherJavaProject != null) {
            addProjectClasspath(root, yetAnotherJavaProject, projectsProcessed, classpath);
          }
        }
        // Ignore source types
      }
    } catch (JavaModelException jme) {
      AptPlugin.log(
          jme,
          "Failed to get the classpath for the following project: "
              + otherJavaProject); //$NON-NLS-1$
    }
  }
예제 #11
0
 private boolean compare(final IResource resource, final String s, final int theHow) {
   if (theHow == FIND_BY_NAME) {
     return samePath(resource.getName(), s);
   } else if (theHow == FIND_BY_LOCATION) {
     return samePath(resource.getLocation().toString(), s);
   } else {
     return false;
   }
 }
예제 #12
0
  private void map(final RepositoryMapping m) {
    final IResource r;
    final File git;
    final IResource dotGit;
    IContainer c = null;

    m.clear();
    r = getProject().findMember(m.getContainerPath());
    if (r instanceof IContainer) {
      c = (IContainer) r;
    } else if (r != null) {
      c = Utils.getAdapter(r, IContainer.class);
    }

    if (c == null) {
      logAndUnmapGoneMappedResource(m);
      return;
    }
    m.setContainer(c);

    IPath absolutePath = m.getGitDirAbsolutePath();
    if (absolutePath == null) {
      logAndUnmapGoneMappedResource(m);
      return;
    }
    git = absolutePath.toFile();
    if (!git.isDirectory() || !new File(git, "config").isFile()) { // $NON-NLS-1$
      logAndUnmapGoneMappedResource(m);
      return;
    }

    try {
      m.setRepository(Activator.getDefault().getRepositoryCache().lookupRepository(git));
    } catch (IOException ioe) {
      logAndUnmapGoneMappedResource(m);
      return;
    }

    m.fireRepositoryChanged();

    trace(
        "map " //$NON-NLS-1$
            + c
            + " -> " //$NON-NLS-1$
            + m.getRepository());
    try {
      c.setSessionProperty(MAPPING_KEY, m);
    } catch (CoreException err) {
      Activator.logError(CoreText.GitProjectData_failedToCacheRepoMapping, err);
    }

    dotGit = c.findMember(Constants.DOT_GIT);
    if (dotGit != null && dotGit.getLocation().toFile().equals(git)) {
      protect(dotGit);
    }
  }
예제 #13
0
 /**
  * Utility for getting an absolute file from a resurce.
  *
  * @param resource the resource from which to derive the File, or null
  * @return the File that corresponds to the input resource, or null if no File can be determined.
  */
 public static File absoluteFileFrom(IResource resource) {
   if (resource == null) {
     return null;
   }
   IPath location = resource.getLocation();
   if (location != null) {
     return location.toFile();
   }
   return null;
 }
 /** @since 2.9 */
 protected Object getLastModified(IResource resource) throws CoreException {
   IPath location = resource.getLocation();
   if (location != null) {
     return location.toFile().lastModified();
   }
   long timestamp = resource.getLocalTimeStamp();
   if (timestamp == IResource.NULL_STAMP) {
     return null;
   }
   return timestamp;
 }
예제 #15
0
  protected long computeModificationStamp(IResource resource) {
    long modificationStamp = resource.getModificationStamp();

    IPath path = resource.getLocation();
    if (path == null) {
      return modificationStamp;
    }

    modificationStamp = path.toFile().lastModified();
    return modificationStamp;
  }
예제 #16
0
 @Override
 public boolean select(Viewer viewer, Object parentElement, Object element) {
   if (element instanceof IFile) {
     IResource i = (IResource) element;
     String fileName = i.getLocation().toOSString();
     for (IContentType type : contentTypes) {
       if (type.isAssociatedWith(fileName)) return true;
     }
     return false;
   } else return super.select(viewer, parentElement, element);
 }
 /*
  * (non-Javadoc)
  * @see org.jboss.tools.seam.internal.core.project.facet.SeamFacetAbstractInstallDelegate#doExecuteForEjb(org.eclipse.core.resources.IProject, org.eclipse.wst.common.project.facet.core.IProjectFacetVersion, org.eclipse.wst.common.frameworks.datamodel.IDataModel, org.eclipse.core.runtime.IProgressMonitor)
  */
 @Override
 protected void doExecuteForEjb(
     final IProject project, IProjectFacetVersion fv, IDataModel model, IProgressMonitor monitor)
     throws CoreException {
   super.doExecuteForEjb(project, fv, model, monitor);
   IResource src = getSrcFolder(project);
   if (src != null && seamHomeFolder != null && shouldCopyLibrariesAndTemplates(model)) {
     File srcFile = src.getLocation().toFile();
     AntCopyUtils.copyFileToFolder(
         new File(seamGenResFolder, "security.drl"), srcFile, false); // $NON-NLS-1$
   }
 }
예제 #18
0
 public IPath getResourcePath() {
   if (m_resourceFileForTests != null) {
     return m_resourceFileForTests.removeLastSegments(1);
   }
   SystemModel_c parent = getRoot();
   if (parent != null) {
     IResource pr = (IResource) parent.getAdapter(IResource.class);
     if (pr != null) {
       if (pr.getFullPath().segmentCount() == 1) {
         // this is for single file domains in test cases
         // TODO Remove when test cases are converted to multi-file
         IPath loc = pr.getLocation();
         return loc.append(MODELS_DIRNAME);
       } else {
         IPath loc = pr.getLocation();
         return loc.removeLastSegments(1);
       }
     }
   }
   return null;
 }
예제 #19
0
 @Override
 public Object execute(ExecutionEvent event) throws ExecutionException {
   ISelection selection =
       PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getSelection();
   if (!(selection instanceof StructuredSelection)) return null;
   Object selected = ((StructuredSelection) selection).getFirstElement();
   IResource resource = null;
   String path = "";
   if (selected instanceof IFile) {
     resource = (IResource) Platform.getAdapterManager().getAdapter(selected, IResource.class);
     path = resource.getLocation().toString();
     new ResultGenerator().parser(path);
   } else if (selected instanceof PlatformObject) {
     resource = (IResource) Platform.getAdapterManager().getAdapter(selected, IResource.class);
     path = resource.getLocation().toString();
     if (resource.getFileExtension() != null && resource.getFileExtension().equals("jar")) {
       new ResultGenerator().parser(path);
     }
   }
   return null;
 }
  /** {@inheritDoc} */
  protected URL resolveLocation(ICheckConfiguration checkConfiguration) throws IOException {
    IResource configFileResource =
        ResourcesPlugin.getWorkspace().getRoot().findMember(checkConfiguration.getLocation());

    if (configFileResource != null) {
      return configFileResource.getLocation().toFile().toURI().toURL();
    } else {
      throw new FileNotFoundException(
          NLS.bind(
              Messages.ProjectConfigurationType_msgFileNotFound, checkConfiguration.getLocation()));
    }
  }
예제 #21
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;
    }
  }
 /**
  * @see
  *     com.aptana.jaxer.connectors.servlet.interfaces.IDocumentRootResolver#getPageFile(javax.servlet.ServletRequest,
  *     javax.servlet.ServletResponse)
  */
 public String getPageFile(ServletRequest request, ServletResponse response) {
   String path = null;
   try {
     if (request instanceof HttpServletRequest) {
       path = ((HttpServletRequest) request).getServletPath();
       String ref = ((HttpServletRequest) request).getHeader("Referer"); // $NON-NLS-1$
       if (ref != null) {
         URL url = new URL(ref);
         String refPath = url.getPath();
         IResource resource = workspaceRoot.findMember(new Path(refPath));
         if (resource != null) {
           IProject project = resource.getProject();
           path = HTMLContextRootUtils.resolveURL(project, path);
           IResource candidate = workspaceRoot.findMember(new Path(path));
           if (candidate != null
               && candidate.getProject().equals(project)
               && candidate instanceof IFile) {
             path = candidate.getLocation().makeAbsolute().toString();
           } else {
             candidate = project.findMember(new Path(path));
             if (candidate != null
                 && candidate.getProject().equals(project)
                 && candidate instanceof IFile) {
               path = candidate.getLocation().makeAbsolute().toString();
             }
           }
         }
       } else {
         IResource resource = workspaceRoot.findMember(new Path(path));
         if (resource != null && resource instanceof IFile) {
           path = resource.getLocation().makeAbsolute().toString();
         }
       }
     }
   } catch (Exception e) {
     path = null;
   }
   return path;
 }
예제 #23
0
  public static IPath getResourceLocation(IResource resource) {
    IPath retval = null;

    if (resource != null) {
      retval = resource.getLocation();

      if (retval == null) {
        retval = resource.getRawLocation();
      }
    }

    return retval;
  }
예제 #24
0
  public IRpcFuture startCompileYrl(
      final IProject project,
      final IResource resource,
      final IBackend backend,
      final OtpErlangList compilerOptions) {
    // final IPath projectPath = project.getLocation();
    // final OldErlangProjectProperties prefs = new
    // OldErlangProjectProperties(project);

    MarkerUtils.deleteMarkers(resource);
    // try {
    // resource.deleteMarkers(PROBLEM_MARKER, true,
    // IResource.DEPTH_INFINITE);
    // } catch (final CoreException e1) {
    // }

    final IPath erl = getErlForYrl(resource);
    final IResource br = project.findMember(erl);

    // we should check timestamps, but yrl files are rare, so it doesn't
    // matter much

    try {
      if (br != null && br.exists()) {
        try {
          br.delete(true, null);
        } catch (final Exception e) {
          ErlLogger.warn(e);
        }
      }

      final String input = resource.getLocation().toString();
      final String output = resource.getLocation().removeFileExtension().toString();
      return InternalErlideBuilder.compileYrl(backend, input, output);
    } catch (final Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  /**
   * @see
   *     com.aptana.jaxer.connectors.servlet.interfaces.IDocumentRootResolver#getDocumentRoot(javax.servlet.ServletRequest,
   *     javax.servlet.ServletResponse)
   */
  public String getDocumentRoot(ServletRequest request, ServletResponse res) {
    String path = null;
    try {
      if (request instanceof HttpServletRequest) {
        path = ((HttpServletRequest) request).getServletPath();
        String ref = ((HttpServletRequest) request).getHeader("Referer"); // $NON-NLS-1$
        IProject project = null;
        if (ref != null) {
          URL url = new URL(ref);
          String refPath = url.getPath();
          IResource resource = workspaceRoot.findMember(new Path(refPath));
          if (resource != null) {
            project = resource.getProject();

          } else {
            resource = workspaceRoot.findMember(new Path(path));
            if (resource != null && resource instanceof IFile) {
              project = resource.getProject();
            }
          }
        } else {
          IResource resource = workspaceRoot.findMember(new Path(path));
          if (resource != null && resource instanceof IFile) {
            project = resource.getProject();
          }
        }
        if (project != null) {
          String override =
              project.getPersistentProperty(
                  new QualifiedName(
                      "", //$NON-NLS-1$
                      HTMLPreviewConstants.HTML_PREVIEW_OVERRIDE));
          if (HTMLPreviewConstants.TRUE.equals(override)) {
            String contextRoot =
                project.getPersistentProperty(
                    new QualifiedName(
                        "", //$NON-NLS-1$
                        HTMLPreviewConstants.CONTEXT_ROOT));
            IResource root = project.findMember(new Path(contextRoot));
            path = root.getLocation().makeAbsolute().toString();
          } else {
            path = project.getLocation().makeAbsolute().toString();
          }
        }
      }
    } catch (Exception e) {
      path = null;
    }
    return path;
  }
 private static String getXsdTargetNamespace(final IResource iResource) {
   if (ModelUtil.isXsdFile(iResource)) {
     final String location = iResource.getLocation().toOSString();
     final File resourceFile = new File(location);
     if (resourceFile.exists())
       try {
         final XsdHeader header = XsdHeaderReader.readHeader(resourceFile);
         if (header != null) return header.getTargetNamespaceURI();
       } catch (final TeiidException e) {
         ModelerCore.Util.log(IStatus.ERROR, e, e.getMessage());
       }
   }
   return null;
 }
  @SuppressWarnings("static-access")
  public Object execute(ExecutionEvent event) throws ExecutionException {

    IWorkbenchPage page = Workbench.getWorkbenchPage();
    if (page == null) {
      return null;
    }
    IPerspectiveDescriptor perspective = page.getPerspective();
    if (perspective != null & perspective.getLabel().equals("PyDev")) {
      Global.FileList.clear();
      ISelection selection = page.getSelection();
      // Console.println(selection.toString());
      if (selection instanceof ITreeSelection) {

        ITreeSelection treeSelection = (ITreeSelection) selection;
        TreePath[] paths = treeSelection.getPaths();
        if (paths.length == 1) {
          if (paths[0] != null) {
            Object object = paths[0].getLastSegment();
            if (object instanceof IAdaptable) {
              IAdaptable adaptable = (IAdaptable) object;
              IResource resource = (IResource) adaptable.getAdapter(IResource.class);
              if (resource != null) {
                if (resource.getType() == resource.FILE) {
                  OpenExplorerFile(resource.getLocation().toOSString());
                } else if (resource.getType() == resource.PROJECT
                    || resource.getType() == resource.FOLDER) {
                  OpenExplorerPath(resource.getLocation().toOSString());
                }
              }
            }
          }
        }
      }
    }
    return null;
  }
 /** @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction) */
 public void run(IAction action) {
   ShellView shellView = null;
   if (!ShellViewUtil.isTargetAvailable()) {
     // No ShellView available
     if (MessageDialogHandler.openConfirmationMessage(
         targetPart.getSite().getShell(),
         "There is no Shell available, do you want to open a new one?")) {
       try {
         shellView = (ShellView) targetPart.getSite().getPage().showView(ShellID.SHELL_VIEW_ID);
       } catch (PartInitException exception) {
         shellLogger.error(exception.getMessage(), exception);
       }
     }
   } else {
     shellView = ShellViewUtil.selectTargetFromAvailable("Change To Folder", true);
   }
   if (shellView != null) {
     IShellDescriptor shellDescriptor =
         shellView.getShellViewer().getShellFacade().getShellDescriptor();
     ICommandProvider commandProvider = shellDescriptor.getCommandProvider();
     File file;
     if (currentResource.getLocation().toFile().isDirectory()) {
       file = new File(currentResource.getLocation().toOSString());
     } else {
       file = new File(currentResource.getLocation().toOSString()).getParentFile();
     }
     String changeDirectoryCommand =
         commandProvider.getChangeDirectoryCommand(shellDescriptor, file);
     shellView.getShellViewer().getShellFacade().executeCommand(changeDirectoryCommand);
     shellView.setFocus();
   } else {
     MessageDialogHandler.openInformationMessage(
         targetPart.getSite().getShell(),
         "No Shell was selected. Please choose one to change to the selected folder.");
   }
 }
 /**
  * Tries to infer a file location from given object, using various strategies
  *
  * @param o an object
  * @return a {@link File} associated to this object, or null.
  */
 public static File toFile(Object o) {
   if (o instanceof File) {
     return (File) o;
   } else if (o instanceof IResource) {
     IPath location = ((IResource) o).getLocation();
     return location == null ? null : location.toFile();
   } else if (o instanceof IAdaptable) {
     IResource resource = ((IAdaptable) o).getAdapter(IResource.class);
     if (resource != null) {
       IPath location = resource.getLocation();
       return location == null ? null : location.toFile();
     }
   }
   return null;
 }
예제 #30
0
  @Override
  protected void buttonPressed(int buttonId) {
    if (buttonId == 1) {
      FileDialog dialog = new FileDialog(this.getShell(), SWT.OPEN);
      dialog.setText(GprofLaunchMessages.GprofNoGmonDialog_OpenGmon);
      if (project != null) {
        dialog.setFilterPath(project.getLocation().toOSString());
      }
      String s = dialog.open();
      if (s != null) {
        gmonPath = s;
      }
    } else if (buttonId == 2) {
      ElementTreeSelectionDialog dialog =
          new ElementTreeSelectionDialog(
              getShell(), new WorkbenchLabelProvider(), new WorkbenchContentProvider());
      dialog.setTitle(GprofLaunchMessages.GprofNoGmonDialog_OpenGmon);
      dialog.setMessage(GprofLaunchMessages.GprofNoGmonDialog_OpenGmon);
      dialog.setInput(ResourcesPlugin.getWorkspace().getRoot());
      dialog.setComparator(new ResourceComparator(ResourceComparator.NAME));
      dialog.setAllowMultiple(false);
      dialog.setInitialSelection(project);
      dialog.setValidator(
          new ISelectionStatusValidator() {
            @Override
            public IStatus validate(Object[] selection) {
              if (selection.length != 1) {
                return new Status(IStatus.ERROR, GprofLaunch.PLUGIN_ID, 0, "", null); // $NON-NLS-1$
              }
              if (!(selection[0] instanceof IFile)) {
                return new Status(IStatus.ERROR, GprofLaunch.PLUGIN_ID, 0, "", null); // $NON-NLS-1$
              }
              return new Status(IStatus.OK, GprofLaunch.PLUGIN_ID, 0, "", null); // $NON-NLS-1$
            }
          });
      if (dialog.open() == IDialogConstants.OK_ID) {
        IResource resource = (IResource) dialog.getFirstResult();
        gmonPath = resource.getLocation().toOSString();
      }
    }

    if (gmonPath == null) {
      setReturnCode(0);
    } else {
      setReturnCode(buttonId);
    }
    close();
  }