public String getText(Object element) {
    if (!(element instanceof IResource)) return null;

    IResource resource = (IResource) element;
    String text = null;

    if (!resource.exists()) text = SearchMessages.FileLabelProvider_removed_resource_label;
    else {
      IPath path = resource.getFullPath().removeLastSegments(1);
      if (path.getDevice() == null) path = path.makeRelative();
      if (fOrder == SHOW_LABEL || fOrder == SHOW_LABEL_PATH) {
        text = fLabelProvider.getText(resource);
        if (path != null && fOrder == SHOW_LABEL_PATH) {
          fArgs[0] = text;
          fArgs[1] = path.toString();
          text = MessageFormat.format(fgSeparatorFormat, fArgs);
        }
      } else {
        if (path != null) text = path.toString();
        else text = ""; // $NON-NLS-1$
        if (fOrder == SHOW_PATH_LABEL) {
          fArgs[0] = text;
          fArgs[1] = fLabelProvider.getText(resource);
          text = MessageFormat.format(fgSeparatorFormat, fArgs);
        }
      }
    }

    int matchCount = 0;
    AbstractTextSearchResult result = fPage.getInput();
    if (result != null) matchCount = result.getMatchCount(element);
    if (matchCount <= 1) return text;
    String format = SearchMessages.FileLabelProvider_count_format;
    return MessageFormat.format(format, new Object[] {text, new Integer(matchCount)});
  }
Example #2
0
 /* (non-Javadoc)
  * @see IJavaSearchScope#encloses(IJavaElement)
  */
 public boolean encloses(IJavaElement element) {
   if (this.elements != null) {
     for (int i = 0, length = this.elements.size(); i < length; i++) {
       IJavaElement scopeElement = (IJavaElement) this.elements.get(i);
       IJavaElement searchedElement = element;
       while (searchedElement != null) {
         if (searchedElement.equals(scopeElement)) return true;
         searchedElement = searchedElement.getParent();
       }
     }
     return false;
   }
   IPackageFragmentRoot root =
       (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
   if (root != null && root.isArchive()) {
     // external or internal jar
     IPath rootPath = root.getPath();
     String rootPathToString =
         rootPath.getDevice() == null ? rootPath.toString() : rootPath.toOSString();
     IPath relativePath = getPath(element, true /*relative path*/);
     return indexOf(rootPathToString, relativePath.toString()) >= 0;
   }
   // resource in workspace
   String fullResourcePathString = getPath(element, false /*full path*/).toString();
   return indexOf(fullResourcePathString) >= 0;
 }
Example #3
0
  /**
   * Checks if full merge data is available for the given <em>baseName</em>.<br>
   * Full merge data means a full 3-way-merge is possible:
   *
   * <ul>
   *   <li>local source file content
   *   <li>local cpc data file content
   *   <li>base source file content
   *   <li>base cpc data file content
   *   <li>remote source file content
   *   <li>remote cpc data file content
   * </ul>
   *
   * The <em>baseName</em> is typically an {@link ICloneFile} UUID.
   *
   * @param baseName the base name, i.e. a file UUID, never null.
   * @return
   */
  public static boolean isFullMergeDataAvailable(String baseName) {
    if (log.isTraceEnabled()) log.trace("isFullMergeDataAvailable() - baseName: " + baseName);

    IPath stateLoc = CPCStoreRemoteLMIPlugin.getDefault().getStateLocation().makeAbsolute();
    stateLoc.append("temp");

    File[] tmpFiles =
        new File[] {
          new File(stateLoc.toString(), baseName + ".local.src"),
          new File(stateLoc.toString(), baseName + ".local.cpc"),
          new File(stateLoc.toString(), baseName + ".base.src"),
          new File(stateLoc.toString(), baseName + ".base.cpc"),
          new File(stateLoc.toString(), baseName + ".remote.src"),
          new File(stateLoc.toString(), baseName + ".remote.cpc"),
        };

    for (File tmpFile : tmpFiles) {
      if (!tmpFile.exists()) {
        if (log.isTraceEnabled())
          log.trace("isFullMergeDataAvailable - result: false - missing file: " + tmpFile);
        return false;
      }
    }

    log.trace("isFullMergeDataAvailable - result: true");

    return true;
  }
  /*
   * (non-Javadoc)
   *
   * @see IJavaSearchScope#encloses(IModelElement)
   */
  public boolean encloses(IModelElement element) {
    IDLTKLanguageToolkit elementToolkit = DLTKLanguageManager.getLanguageToolkit(element);
    if (!toolkit.getNatureId().equals(elementToolkit.getNatureId())) {
      return false;
    }

    if (this.elements != null) {
      for (int i = 0, length = this.elements.size(); i < length; i++) {
        IModelElement scopeElement = this.elements.get(i);
        IModelElement searchedElement = element;
        while (searchedElement != null) {
          if (searchedElement.equals(scopeElement)) return true;
          searchedElement = searchedElement.getParent();
        }
      }
      return false;
    }
    IProjectFragment root = (IProjectFragment) element.getAncestor(IModelElement.PROJECT_FRAGMENT);
    if (root != null && root.isArchive()) {
      // external or internal archive
      IPath rootPath = root.getPath();
      String rootPathToString = rootPath.toString();
      IPath relativePath = getPath(element, true /* relative path */);
      return indexOf(rootPathToString, relativePath.toString()) >= 0;
    }
    // resource in workspace
    String fullResourcePathString = getPath(element, false /* full path */).toString();
    return indexOf(fullResourcePathString) >= 0;
  }
Example #5
0
  /**
   * Recreates the index for a given path, keeping the same read-write monitor. Returns the new
   * empty index or null if it didn't exist before. Warning: Does not check whether index is
   * consistent (not being used)
   */
  public synchronized Index recreateIndex(IPath containerPath) {
    // only called to over write an existing cached index...
    String containerPathString =
        containerPath.getDevice() == null ? containerPath.toString() : containerPath.toOSString();
    try {
      // Path is already canonical
      IPath indexLocation = computeIndexLocation(containerPath);

      Index index = (Index) this.indexes.get(indexLocation);
      ReadWriteMonitor monitor = index == null ? null : index.monitor;

      if (VERBOSE)
        Util.verbose(
            "-> recreating index: "
                + indexLocation
                + " for path: "
                + containerPathString); //$NON-NLS-1$ //$NON-NLS-2$
      index =
          new Index(indexLocation.toString(), containerPathString, false /* reuse index file */);
      this.indexes.put(indexLocation, index);
      index.monitor = monitor;
      return index;
    } catch (IOException e) {
      // The file could not be created. Possible reason: the project has been deleted.
      if (VERBOSE) {
        Util.verbose("-> failed to recreate index for path: " + containerPathString); // $NON-NLS-1$
        e.printStackTrace();
      }
      return null;
    }
  }
Example #6
0
 public String convertPathToString(IPath path) {
   if (host.getSystemType().isWindows()) {
     return path.toString().replace('/', '\\');
   } else {
     return path.toString();
   }
 }
  @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());
  }
Example #8
0
  /**
   * (non-Javadoc)
   *
   * @see org.eclipse.ice.core.iCore.ICore#importFile(java.net.URI,
   *     org.eclipse.core.resources.IProject)
   */
  @Override
  public void importFile(URI file, IProject project) {
    // Only do this if the file is good
    if (file != null) {
      // Get the file handle
      IPath path = (new Path(file.toString()));
      IFile fileInProject = project.getFile(path.lastSegment());
      // Get the paths and convert them to strings
      IPath fullPathInProject = fileInProject.getLocation();
      String path1 = path.toString(), path2 = fullPathInProject.toString();
      // Remove devices ids and other such things from the path strings
      path1 = path1.substring(path1.lastIndexOf(":") + 1);
      path2 = path2.substring(path2.lastIndexOf(":") + 1);
      // Only manipulate the file if it is not already in the workspace.
      // It is completely reasonable to stick the file in the workspace
      // and then "import" it, so a simple check here relieves some
      // heartburn I would no doubt otherwise endure.
      if (!path1.equals(path2)) {
        // If the project space contains a file by the same name, but
        // with a different absolute path, delete that file.
        if (fileInProject.exists()) {
          try {
            fileInProject.delete(true, null);
          } catch (CoreException e) {
            // Complain and don't do anything else.
            logger.info("Core Message: " + "Unable to import file.");
            logger.error(getClass().getName() + " Exception!", e);
            return;
          }
        }
        try {
          // Open a stream of the file
          FileInputStream fileStream = new FileInputStream(new File(file));
          // Import the file
          fileInProject.create(fileStream, true, null);
        } catch (FileNotFoundException e) {
          // Complain and don't do anything else.
          logger.info("Core Message: " + "Unable to import file.");
          logger.error(getClass().getName() + " Exception!", e);
          return;
        } catch (CoreException e) {
          // Complain and don't do anything else.
          logger.info("Core Message: " + "Unable to import file.");
          logger.error(getClass().getName() + " Exception!", e);
          return;
        }
      }
      // Refresh all of the Items
      itemManager.reloadItemData();

      // Drop some debug info.
      if (System.getProperty("DebugICE") != null) {
        logger.info("Core Message: " + "Imported file " + file.toString());
      }
    } else {
      logger.info("File could not be imported into project because the File URI was not valid.");
    }
  }
  private void validateFolders() {
    boolean useFolders = fFoldersAsSourceFolder.getSelection();

    fSrcFolderNameText.setEnabled(useFolders);
    fBinFolderNameText.setEnabled(useFolders);
    fSrcFolderNameLabel.setEnabled(useFolders);
    fBinFolderNameLabel.setEnabled(useFolders);
    if (useFolders) {
      String srcName = fSrcFolderNameText.getText();
      String binName = fBinFolderNameText.getText();
      if (srcName.length() + binName.length() == 0) {
        updateStatus(
            new StatusInfo(
                IStatus.ERROR,
                PreferencesMessages.NewJavaProjectPreferencePage_folders_error_namesempty));
        return;
      }
      IWorkspace workspace = JavaPlugin.getWorkspace();
      IProject dmy = workspace.getRoot().getProject("project"); // $NON-NLS-1$

      IStatus status;
      IPath srcPath = dmy.getFullPath().append(srcName);
      if (srcName.length() != 0) {
        status = workspace.validatePath(srcPath.toString(), IResource.FOLDER);
        if (!status.isOK()) {
          String message =
              Messages.format(
                  PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidsrcname,
                  status.getMessage());
          updateStatus(new StatusInfo(IStatus.ERROR, message));
          return;
        }
      }
      IPath binPath = dmy.getFullPath().append(binName);
      if (binName.length() != 0) {
        status = workspace.validatePath(binPath.toString(), IResource.FOLDER);
        if (!status.isOK()) {
          String message =
              Messages.format(
                  PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidbinname,
                  status.getMessage());
          updateStatus(new StatusInfo(IStatus.ERROR, message));
          return;
        }
      }
      IClasspathEntry entry = JavaCore.newSourceEntry(srcPath);
      status =
          JavaConventions.validateClasspath(
              JavaCore.create(dmy), new IClasspathEntry[] {entry}, binPath);
      if (!status.isOK()) {
        String message = PreferencesMessages.NewJavaProjectPreferencePage_folders_error_invalidcp;
        updateStatus(new StatusInfo(IStatus.ERROR, message));
        return;
      }
    }
    updateStatus(new StatusInfo()); // set to OK
  }
 /**
  * Updates the program arguments with a model path, a target folder path, and other Acceleo
  * arguments.
  *
  * @param config is an editable copy of the current launch configuration
  * @param model is the model path, relative to the workspace
  * @param target is the target folder path, relative to the workspace
  * @param args are the Acceleo application arguments (properties)
  */
 public void updateArguments(
     ILaunchConfigurationWorkingCopy config, String model, String target, String args) {
   IPath modelPath;
   if (model != null) {
     modelPath = new Path(model);
   } else {
     modelPath = new Path(""); // $NON-NLS-1$
   }
   if (modelPath.segmentCount() > 1) {
     modelPath = ResourcesPlugin.getWorkspace().getRoot().getFile(modelPath).getLocation();
   }
   if (modelPath == null) {
     modelPath = new Path(""); // $NON-NLS-1$
   }
   IPath targetPath;
   if (target != null) {
     targetPath = new Path(target);
   } else {
     targetPath = new Path(""); // $NON-NLS-1$
   }
   if (targetPath.segmentCount() == 1) {
     targetPath =
         ResourcesPlugin.getWorkspace()
             .getRoot()
             .getProject(targetPath.lastSegment())
             .getLocation();
   } else if (targetPath.segmentCount() > 1) {
     targetPath = ResourcesPlugin.getWorkspace().getRoot().getFolder(targetPath).getLocation();
   }
   if (targetPath == null) {
     targetPath = new Path(""); // $NON-NLS-1$
   }
   StringBuffer newBuffer = new StringBuffer();
   newBuffer.append('"');
   newBuffer.append(modelPath.toString());
   newBuffer.append("\" \""); // $NON-NLS-1$
   newBuffer.append(targetPath.toString());
   newBuffer.append('"');
   if (args.length() > 0) {
     StringTokenizer st = new StringTokenizer(args, "\n"); // $NON-NLS-1$
     while (st.hasMoreTokens()) {
       String token = st.nextToken().trim();
       newBuffer.append(" \""); // $NON-NLS-1$
       newBuffer.append(token);
       newBuffer.append('"');
     }
   }
   String newText = newBuffer.toString();
   if (!newText.equals(fPrgmArgumentsText.getText())) {
     fPrgmArgumentsText.setText(newText);
     config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, newText);
   }
 }
  /**
   * Test method for {@link
   * org.talend.dataprofiler.core.CorePlugin#itemIsOpening(org.talend.core.model.properties.Item,
   * boolean)}.
   */
  @Test
  public void testItemIsOpeningItemBoolean() {
    try {
      CorePlugin cpMock = mock(CorePlugin.class);
      PowerMockito.mockStatic(CorePlugin.class);
      when(CorePlugin.getDefault()).thenReturn(cpMock);

      IWorkbench workbenchMock = mock(IWorkbench.class);
      when(cpMock.getWorkbench()).thenReturn(workbenchMock);

      IWorkbenchWindow workbenchWindowMock = mock(IWorkbenchWindow.class);
      when(workbenchMock.getActiveWorkbenchWindow()).thenReturn(workbenchWindowMock);

      IWorkbenchPage workbenchPageMock = mock(IWorkbenchPage.class);
      when(workbenchWindowMock.getActivePage()).thenReturn(workbenchPageMock);

      IEditorReference editorRefMock = mock(IEditorReference.class);
      IEditorReference[] editorRefMocks = new IEditorReference[] {editorRefMock};
      when(workbenchPageMock.getEditorReferences()).thenReturn(editorRefMocks);

      FileEditorInput fileEditorInputMock = mock(FileEditorInput.class);
      when(editorRefMock.getEditorInput()).thenReturn(fileEditorInputMock);

      String path1 = "/abc1"; // $NON-NLS-1$
      String path2 = "/abc2"; // $NON-NLS-1$

      IFile inputFileMock = mock(IFile.class);
      when(fileEditorInputMock.getFile()).thenReturn(inputFileMock);

      IPath inputFilePathMock = mock(IPath.class);
      when(inputFileMock.getFullPath()).thenReturn(inputFilePathMock);

      when(inputFilePathMock.toString()).thenReturn(path1);

      Item itemMock = mock(Item.class);
      Property propertyMock = mock(Property.class);
      when(itemMock.getProperty()).thenReturn(propertyMock);

      Resource resourceMock = mock(Resource.class);
      when(propertyMock.eResource()).thenReturn(resourceMock);

      IPath ipathMock = mock(IPath.class);
      PowerMockito.mockStatic(PropertyHelper.class);
      when(PropertyHelper.getItemPath(propertyMock)).thenReturn(ipathMock);
      when(ipathMock.toString()).thenReturn(path2);

      CorePlugin cp = new CorePlugin();
      assertFalse(cp.itemIsOpening(itemMock, false));
    } catch (PartInitException e) {
      fail(e.getMessage());
    }
  }
Example #12
0
 protected void registerClientResources(List<IPath> resources, ClassLoader loader) {
   ResourceManager resourceManager = getResourceManager();
   try {
     for (IPath filePath : resources) {
       boolean isRegistered = resourceManager.isRegistered(filePath.toString());
       if (!isRegistered) {
         registerResource(resourceManager, loader, filePath.toString());
       }
     }
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
  /* Initialisierung */
  static {
    IPath actLoc = Activator.getDefault().getStateLocation();
    IPath p = Platform.getLocation();
    IStatus ae =
        new Status(IStatus.INFO, Activator.PLUGIN_ID, "actLoc.toString(): " + actLoc.toString());
    ILOGGER.log(ae);
    ae = new Status(IStatus.INFO, Activator.PLUGIN_ID, "p.toString(): " + p.toString());
    ILOGGER.log(ae);

    // develop in eclipse
    String pdrHome = System.getenv("AE_RAP_HOME");
    if (pdrHome != null) {
      AE_RAP_HOME = pdrHome;
    } else {

      // rap
      AE_RAP_HOME = actLoc.removeLastSegments(8).toOSString();
    }
    ae = new Status(IStatus.INFO, Activator.PLUGIN_ID, "reduced string: " + AE_RAP_HOME);
    ILOGGER.log(ae);
    /** Properties laden. */
    PROPERTIES = new Properties();
    PROPERTIES_FILENAME = AE_RAP_HOME + FS + "RAPConfig" + FS + "config.properties";
    File file = new File(PROPERTIES_FILENAME);
    // try {
    // if (_i) _l.info("Lade: " + file.toURI().toString());
    try {
      PROPERTIES.load(new FileInputStream(file));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    PROJECT_IDS = PROPERTIES.getProperty("PROJECT_IDS").split("\\|");
    REPOSITORY_ID = Integer.parseInt(PROPERTIES.getProperty("REPOSITORY_ID"));
    PROJECT_ID = Integer.parseInt(PROPERTIES.getProperty("PROJECT_ID"));
    REPOSITORY_URL = PROPERTIES.getProperty("REPOSITORY_URL");
    if (PROPERTIES.getProperty("USER_IDS_BLACK_LIST") != null) {
      USER_IDS_BLACK_LIST = PROPERTIES.getProperty("USER_IDS_BLACK_LIST").split("\\|");
    } else {
      USER_IDS_BLACK_LIST = null;
    }
    if (PROPERTIES.getProperty("USER_IDS_WHITE_LIST") != null) {
      USER_IDS_WHITE_LIST = PROPERTIES.getProperty("USER_IDS_WHITE_LIST").split("\\|");
    } else {
      USER_IDS_WHITE_LIST = null;
    }
  }
  /**
   * Based on the selected board and parameters save all info needed to the build environments
   *
   * @param confdesc
   */
  public void saveAllSelections(ICConfigurationDescription confdesc) {
    String boardFile = this.mControlBoardsTxtFile.getText().trim();
    String boardName = this.mcontrolBoardName.getText().trim();
    String uploadPort = this.mControlUploadPort.getValue();
    IEnvironmentVariableManager envManager = CCorePlugin.getDefault().getBuildEnvironmentManager();
    IContributedEnvironment contribEnv = envManager.getContributedEnvironment();

    // Set the path variables
    IPath platformPath =
        new Path(new File(this.mControlBoardsTxtFile.getText().trim()).getParent())
            .append(Const.PLATFORM_FILE_NAME);
    Common.setBuildEnvironmentVariable(
        contribEnv, confdesc, Const.ENV_KEY_JANTJE_BOARDS_FILE, boardFile);
    Common.setBuildEnvironmentVariable(
        contribEnv, confdesc, Const.ENV_KEY_JANTJE_PLATFORM_FILE, platformPath.toString());
    Common.setBuildEnvironmentVariable(
        contribEnv, confdesc, Const.ENV_KEY_JANTJE_BOARD_NAME, boardName);
    Common.setBuildEnvironmentVariable(
        contribEnv, confdesc, Const.ENV_KEY_JANTJE_COM_PORT, uploadPort);

    Common.setBuildEnvironmentVariable(
        contribEnv, confdesc, Const.ENV_KEY_JANTJE_PACKAGE_ID, getPackage());
    Common.setBuildEnvironmentVariable(
        contribEnv, confdesc, Const.ENV_KEY_JANTJE_ARCITECTURE_ID, getArchitecture());
    Common.setBuildEnvironmentVariable(
        contribEnv, confdesc, Const.ENV_KEY_JANTJE_BOARD_ID, getBoardID());

    for (LabelCombo curLabelCombo : this.mBoardOptionCombos) {
      curLabelCombo.StoreValue(confdesc);
    }
    saveAllLastUseds();
  }
        @Override
        public void handleEvent(Event e) {
          IEnvironmentVariableManager envManager =
              CCorePlugin.getDefault().getBuildEnvironmentManager();
          IContributedEnvironment contribEnv = envManager.getContributedEnvironment();
          ICConfigurationDescription confdesc = getConfdesc();

          int selectedBoardFile = BoardSelectionPage.this.mControlBoardsTxtFile.getSelectionIndex();
          String boardFile = BoardSelectionPage.this.mControlBoardsTxtFile.getText().trim();
          if (confdesc != null) {
            IEnvironmentVariable var =
                new EnvironmentVariable(Const.ENV_KEY_JANTJE_BOARDS_FILE, boardFile);
            contribEnv.addVariable(var, confdesc);
            IPath platformPath =
                new Path(new File(boardFile).getParent()).append(Const.PLATFORM_FILE_NAME);
            var =
                new EnvironmentVariable(
                    Const.ENV_KEY_JANTJE_PLATFORM_FILE, platformPath.toString());
            contribEnv.addVariable(var, confdesc);
          }

          /*
           * Change the list of available boards
           */
          String CurrentBoard = BoardSelectionPage.this.mcontrolBoardName.getText();
          BoardSelectionPage.this.mcontrolBoardName.removeAll();
          BoardSelectionPage.this.mcontrolBoardName.setItems(
              BoardSelectionPage.this.mAllBoardsFiles[selectedBoardFile].GetArduinoBoards());
          BoardSelectionPage.this.mcontrolBoardName.setText(CurrentBoard);

          BoardSelectionPage.this.BoardModifyListener.handleEvent(null);
        }
  /**
   * Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings.
   * Paths are ordered from most to least specific match.
   *
   * @param site The hosted site.
   * @param pathInfo Path to be rewritten.
   * @param queryString
   * @return The rewritten path. May be either:
   *     <ul>
   *       <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code>
   *       <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code>
   *     </ul>
   *
   * @return The rewritten paths.
   * @throws URISyntaxException
   */
  private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString)
      throws URISyntaxException {
    final Map<String, List<String>> map = site.getMappings();
    final IPath originalPath = pathInfo;
    IPath path = originalPath.removeTrailingSeparator();

    List<URI> uris = new ArrayList<URI>();
    String rest = null;
    final int count = path.segmentCount();
    for (int i = 0; i <= count; i++) {
      List<String> base = map.get(path.toString());
      if (base != null) {
        rest = originalPath.removeFirstSegments(count - i).toString();
        for (int j = 0; j < base.size(); j++) {
          URI uri =
              rest.equals("") ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest);
          uris.add(
              new URI(
                  uri.getScheme(),
                  uri.getUserInfo(),
                  uri.getHost(),
                  uri.getPort(),
                  uri.getPath(),
                  queryString,
                  uri.getFragment()));
        }
      }
      path = path.removeLastSegments(1);
    }
    if (uris.size() == 0)
      // No mapping for /
      return null;
    else return uris.toArray(new URI[uris.size()]);
  }
Example #17
0
  public void testFindFilesByLocation() throws Exception {
    fProject.create(new NullProgressMonitor());
    fProject.open(new NullProgressMonitor());
    createFolder(fProject, "folder1");
    createFolder(fProject, "folder2");
    IFile file = createFile(fProject, "abc.h");
    createFile(fProject, "folder1/abc.h");
    createFile(fProject, "folder2/abC.h");

    URI uri = file.getLocationURI();
    IPath path = file.getLocation();
    IFile[] files = ResourceLookup.findFilesForLocationURI(uri);
    assertEquals(1, files.length);
    files = ResourceLookup.findFilesForLocation(path);
    assertEquals(1, files.length);

    if (new File("a").equals(new File("A"))) {
      URI upperCase =
          new URI(uri.getScheme(), uri.getSchemeSpecificPart().toUpperCase(), uri.getFragment());
      IPath upperCasePath = new Path(path.toString().toUpperCase());
      files = ResourceLookup.findFilesForLocationURI(upperCase);
      assertEquals(1, files.length);
      files = ResourceLookup.findFilesForLocation(upperCasePath);
      assertEquals(1, files.length);
    }
  }
  protected void projectChanged() {

    projectText = projectCombo.getText();
    IJavaProject selectedProject = null;
    for (int i = 0; i < gwtProjects.length; i++) {
      IJavaProject gwtProject = gwtProjects[i];
      if (projectText.equals(gwtProject.getProject().getName())) {
        selectedProject = gwtProject;
        break;
      }
    }

    if (selectedProject != null) {
      try {
        moduleCombo.removeAll();
        List modulesList = Util.findModules(selectedProject);
        for (Iterator i = modulesList.iterator(); i.hasNext(); ) {
          IFile file = (IFile) i.next();
          IPath projectRelativePath = file.getProjectRelativePath();
          String fileName = file.getName();
          String moduleName =
              fileName.substring(0, fileName.length() - Constants.GWT_XML_EXT.length() - 1);
          moduleCombo.add(projectRelativePath.toString());
          moduleCombo.setData(moduleName, file);
        }
        int i = modulesList.indexOf(selectedModule);
        if (i == -1) i = 0;
        moduleCombo.select(i);
        moduleText = moduleCombo.getText();
      } catch (CoreException e) {
        Activator.logException(e);
      }
    }
    doStatusUpdate();
  }
  @Override
  public File createFeedbackFile() {
    finishedSelected();
    IPath rootPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
    String path = rootPath.toString() + File.separator + "questionnaire.txt";
    File questionnaireFile = new File(path);

    if (questionnaireFile.exists()) {
      questionnaireFile.delete();
    }

    OutputStream outputStream;
    try {
      outputStream = new FileOutputStream(questionnaireFile);

      String buffer = "Tasks: " + getTaskPerformedFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      buffer = "MentalModel: " + getMentalModelFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      buffer = "DOI: " + getDoiModelFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      buffer = "Integrate: " + getIntegrateFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      buffer = "Positive: " + getPositiveFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      buffer = "Negative: " + getNegativeFeedback() + "\r\n";
      outputStream.write(buffer.getBytes());
      outputStream.close();
      return questionnaireFile;
    } catch (IOException e) {
      StatusHandler.log(
          new Status(IStatus.ERROR, MylynUserStudyExamplePlugin.ID_PLUGIN, "Failed to submit", e));
    }
    return null;
  }
  public BundleModuleRegistry(String bundleSymbolicName, Collection<IPath> paths) {
    if (bundleSymbolicName == null || bundleSymbolicName.length() == 0) {
      throw new IllegalArgumentException("Invalid bundle symbolic name"); // $NON-NLS-1$
    }

    for (IPath nextPath : paths) {
      if (nextPath == null || nextPath.isEmpty() || !nextPath.isValidPath(nextPath.toString())) {
        throw new IllegalArgumentException("Invalid resource path:" + nextPath); // $NON-NLS-1$
      }
    }

    this.bundleID = bundleSymbolicName;
    this.defaultFolderItems = Collections.emptySet();
    this.filePaths = new HashSet<IPath>();
    this.folderPaths = new HashSet<IPath>();

    for (IPath filePath : paths) {
      if (filePath.segmentCount() > 1) {
        extractFolderPaths(folderPaths, filePath);
        filePaths.add(filePath);
      } else {
        if (defaultFolderItems.isEmpty()) {
          defaultFolderItems = new HashSet<IPath>();
        }
        defaultFolderItems.add(filePath);
      }
    }
  }
 /**
  * Returns the resource containing the workflow. Uses lazy initialization.
  *
  * @param path
  * @return
  */
 public Resource getResource(IPath path) {
   if (resource == null) {
     ResourceSet resSet = getResourceSet();
     resource = resSet.getResource(URI.createPlatformResourceURI(path.toString()), true);
   }
   return resource;
 }
 /**
  * Possible failures:
  *
  * <ul>
  *   <li>NO_ELEMENTS_TO_PROCESS - the root supplied to the operation is <code>null</code>.
  *   <li>INVALID_NAME - the name provided to the operation is <code>null</code> or is not a valid
  *       script folder name.
  *   <li>READ_ONLY - the root provided to this operation is read only.
  *   <li>NAME_COLLISION - there is a pre-existing resource (file) with the same name as a folder
  *       in the script folder's hierarchy.
  *   <li>ELEMENT_NOT_PRESENT - the underlying resource for the root is missing
  * </ul>
  *
  * @see IScriptModelStatus
  * @see ScriptConventions
  */
 @Override
 public IModelStatus verify() {
   if (getParentElement() == null) {
     return new ModelStatus(IModelStatusConstants.NO_ELEMENTS_TO_PROCESS);
   }
   IPath packageName = this.pkgName == null ? null : this.pkgName.append("."); // $NON-NLS-1$
   String packageNameValue = null;
   if (packageName != null) {
     packageNameValue = packageName.toOSString();
   }
   if (this.pkgName == null
       || (this.pkgName.segmentCount() > 0
           && !Util.isValidFolderNameForPackage(
               (IContainer) getParentElement().getResource(), packageName.toString()))) {
     return new ModelStatus(IModelStatusConstants.INVALID_NAME, packageNameValue);
   }
   IProjectFragment root = (IProjectFragment) getParentElement();
   if (root.isReadOnly()) {
     return new ModelStatus(IModelStatusConstants.READ_ONLY, root);
   }
   IContainer parentFolder = (IContainer) root.getResource();
   int i;
   for (i = 0; i < this.pkgName.segmentCount(); i++) {
     IResource subFolder = parentFolder.findMember(this.pkgName.segment(i));
     if (subFolder != null) {
       if (subFolder.getType() != IResource.FOLDER) {
         return new ModelStatus(
             IModelStatusConstants.NAME_COLLISION,
             Messages.bind(Messages.status_nameCollision, subFolder.getFullPath().toString()));
       }
       parentFolder = (IContainer) subFolder;
     }
   }
   return ModelStatus.VERIFIED_OK;
 }
  /**
   * @see
   *     com.metamatrix.modeler.core.metamodel.aspect.sql.SqlAspect#getName(org.eclipse.emf.ecore.EObject)
   */
  public String getName(final EObject eObject) {
    CoreArgCheck.isInstanceOf(XmlElement.class, eObject);

    IPath path = new Path(getShortName(eObject));
    EObject parent = eObject.eContainer();
    SqlAspect parentAspect = AspectManager.getSqlAspect(parent);
    while (parentAspect != null) {
      if (parent instanceof XmlDocument) {
        // XmlDocumentSqlAspect now implements SqlTableAspect AND SqlColumnAspect
        break;
      }
      if (parentAspect instanceof SqlColumnAspect) {
        String name = null;
        if (parentAspect instanceof AbstractXmlDocumentEntitySqlAspect) {
          name = ((AbstractXmlDocumentEntitySqlAspect) parentAspect).getShortName(parent);
        } else {
          name = parentAspect.getName(parent);
        }
        path = new Path("").append(name).append(path); // $NON-NLS-1$
      } else if (parentAspect instanceof SqlTableAspect) {
        break;
      }
      // Walk up to the parent ...
      parent = parent.eContainer();
      parentAspect = AspectManager.getSqlAspect(parent);
    }

    return path.toString().replace(IPath.SEPARATOR, '.');
  }
  private IStatus validateFileName() {
    fileName = null;

    String str = fileNameField.getText().trim();
    if (str.length() == 0) {
      return Util.newErrorStatus("Enter a file name");
    }

    // Validate the file name
    IStatus nameStatus = ResourcesPlugin.getWorkspace().validateName(str, IResource.FILE);
    if (nameStatus.matches(IStatus.ERROR)) {
      return Util.newErrorStatus("Invalid file name. {0}", nameStatus.getMessage());
    }

    // Make sure the host page doesn't already exist in the public path
    if (hostPagePath != null) {
      IPath htmlFilePath =
          hostPagePath
              .append(str)
              .removeFileExtension()
              .addFileExtension(((AbstractNewFileWizard) getWizard()).getFileExtension());
      IFile htmlFile = ResourcesPlugin.getWorkspace().getRoot().getFile(htmlFilePath);
      if (htmlFile.exists()) {
        return Util.newErrorStatus("''{0}'' already exists", htmlFilePath.toString());
      }
    }

    fileName = str;
    return Status.OK_STATUS;
  }
  /**
   * Populate properties with everything required for the SonarLint analysis in issues mode.
   *
   * @param monitor
   * @param properties
   * @return
   */
  public Properties configureAnalysis(
      final IProgressMonitor monitor, List<SonarLintProperty> extraProps) {
    Properties properties = new Properties();
    IProject project = request.getProject();
    final File baseDir = project.getLocation().toFile();
    IPath projectSpecificWorkDir = project.getWorkingLocation(SonarLintCorePlugin.PLUGIN_ID);

    // Preview mode by default
    properties.setProperty(
        SonarLintProperties.ANALYSIS_MODE, SonarLintProperties.ANALYSIS_MODE_ISSUES);

    // Configuration by configurators (common and language specific)
    configure(project, this.request.getOnlyOnFiles(), properties, monitor);

    // Append workspace and project properties
    for (SonarLintProperty sonarProperty : extraProps) {
      properties.put(sonarProperty.getName(), sonarProperty.getValue());
    }
    if (this.request.getOnlyOnFiles() != null) {
      Collection<String> paths = new ArrayList<>(this.request.getOnlyOnFiles().size());
      for (IFile file : this.request.getOnlyOnFiles()) {
        MarkerUtils.deleteIssuesMarkers(file);
        paths.add(file.getProjectRelativePath().toString());
      }
      ProjectConfigurator.setPropertyList(properties, "sonar.tests", paths);
      ProjectConfigurator.setPropertyList(properties, "sonar.sources", paths);
    } else {
      MarkerUtils.deleteIssuesMarkers(project);
    }

    properties.setProperty(SonarLintProperties.PROJECT_BASEDIR, baseDir.toString());
    properties.setProperty(SonarLintProperties.WORK_DIR, projectSpecificWorkDir.toString());

    return properties;
  }
Example #26
0
  protected void handleApplicationBrowseButton() {
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    AppSelectionDialog dialog =
        new AppSelectionDialog(getShell(), workspace.getRoot(), new HtmlWebResourceFilter());
    dialog.setTitle("Select a HTML page to launch");
    dialog.setInitialPattern(".", FilteredItemsSelectionDialog.FULL_SELECTION); // $NON-NLS-1$
    IPath path = new Path(htmlText.getText());
    if (workspace.validatePath(path.toString(), IResource.FILE).isOK()) {
      IFile file = workspace.getRoot().getFile(path);
      if (file != null && file.exists()) {
        dialog.setInitialSelections(new Object[] {path});
      }
    }

    dialog.open();

    Object[] results = dialog.getResult();

    if ((results != null) && (results.length > 0) && (results[0] instanceof IFile)) {
      IFile file = (IFile) results[0];
      String pathStr = file.getFullPath().toPortableString();

      htmlText.setText(pathStr);
    }
  }
  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;
  }
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.eclipse.core.resources.IWorkspaceRunnable#run(org.eclipse.core.runtime.IProgressMonitor)
  */
 public void run(IProgressMonitor monitor) throws CoreException {
   monitor.beginTask(
       AcceleoUIMessages.getString("AcceleoCompileOperation.Task.Compile"),
       files.length); // $NON-NLS-1$
   for (int i = 0; i < files.length; i++) {
     checkCanceled(monitor);
     monitor.subTask(
         AcceleoUIMessages.getString(
             "AcceleoCompileOperation.Task.Clean",
             files[0].getFullPath().toString())); // $NON-NLS-1$
     if (files[i].isAccessible()) {
       files[i].deleteMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
       files[i].deleteMarkers(IMarker.TASK, true, IResource.DEPTH_INFINITE);
       files[i].deleteMarkers(
           AcceleoMarkerUtils.OVERRIDE_MARKER_ID, true, IResource.DEPTH_INFINITE);
     }
   }
   if (!isClean) {
     doCompileResources(monitor);
   } else {
     for (IFile file : this.files) {
       AcceleoProject acceleoProject = new AcceleoProject(project);
       IPath outputPath = acceleoProject.getOutputFilePath(file);
       if (outputPath != null) {
         URI platformURI = URI.createPlatformResourceURI(outputPath.toString(), false);
         try {
           AcceleoUIResourceSet.removeResource(platformURI);
         } catch (IOException e) {
           AcceleoUIActivator.log(e, true);
         }
       }
     }
   }
   monitor.done();
 }
 public void changeControlPressed(DialogField field) {
   IJavaProject jproject = chooseProject();
   if (jproject != null) {
     IPath path = jproject.getProject().getFullPath().makeRelative();
     projectField.setText(path.toString());
   }
 }
Example #30
0
  protected void checkIfPathValid() {
    fFolder = null;
    IContainer folder = null;
    if (fUseFolderButton.isSelected()) {
      String pathStr = fContainerDialogField.getText();
      if (pathStr.length() == 0) {
        fContainerFieldStatus.setError(NewWizardMessages.NewSourceFolderDialog_error_enterpath);
        return;
      }
      IPath path = fCurrProject.getFullPath().append(pathStr);
      IWorkspace workspace = fCurrProject.getWorkspace();

      IStatus pathValidation = workspace.validatePath(path.toString(), IResource.FOLDER);
      if (!pathValidation.isOK()) {
        fContainerFieldStatus.setError(
            Messages.format(
                NewWizardMessages.NewSourceFolderDialog_error_invalidpath,
                pathValidation.getMessage()));
        return;
      }
      folder = fCurrProject.getFolder(pathStr);
    } else {
      folder = fCurrProject;
    }
    if (isExisting(folder)) {
      fContainerFieldStatus.setError(NewWizardMessages.NewSourceFolderDialog_error_pathexists);
      return;
    }
    fContainerFieldStatus.setOK();
    fFolder = folder;
  }