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)});
  }
Exemple #2
0
 /**
  * Returns a status for this library describing any error states
  *
  * @return
  */
 IStatus validate() {
   if (!getSystemLibraryPath().toFile().exists()) {
     return new Status(
         IStatus.ERROR,
         IJavaDebugUIConstants.PLUGIN_ID,
         IJavaDebugUIConstants.INTERNAL_ERROR,
         "System library does not exist: " + getSystemLibraryPath().toOSString(),
         null); //$NON-NLS-1$
   }
   IPath path = getSystemLibrarySourcePath();
   if (!path.isEmpty()) {
     if (!path.toFile().exists()) {
       // check for workspace resource
       IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
       if (resource == null || !resource.exists()) {
         return new Status(
             IStatus.ERROR,
             IJavaDebugUIConstants.PLUGIN_ID,
             IJavaDebugUIConstants.INTERNAL_ERROR,
             "Source attachment does not exist: " + path.toOSString(),
             null); //$NON-NLS-1$
       }
     }
   }
   return Status.OK_STATUS;
 }
  public static IFile LinkFile(String path) {
    IWorkspace ws = ResourcesPlugin.getWorkspace();
    IProject project = ws.getRoot().getProject("tmp");
    if (!project.exists())
      try {
        project.create(null);
      } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    if (!project.isOpen())
      try {
        project.open(null);
      } catch (CoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    IPath location = new Path(path);
    IFile file = project.getFile(location.lastSegment());

    try {
      file.delete(true, null);
    } catch (CoreException e1) {
    }

    try {
      file.createLink(location, IResource.NONE, null);
    } catch (CoreException e) {
    }
    return file;
  }
  protected void finishedWith(
      String sourceLocator,
      CompilationResult result,
      char[] mainTypeName,
      ArrayList definedTypeNames,
      ArrayList duplicateTypeNames) {
    char[][] previousTypeNames = this.newState.getDefinedTypeNamesFor(sourceLocator);
    if (previousTypeNames == null) previousTypeNames = new char[][] {mainTypeName};
    IPath packagePath = null;
    next:
    for (int i = 0, l = previousTypeNames.length; i < l; i++) {
      char[] previous = previousTypeNames[i];
      for (int j = 0, m = definedTypeNames.size(); j < m; j++)
        if (CharOperation.equals(previous, (char[]) definedTypeNames.get(j))) continue next;

      SourceFile sourceFile = (SourceFile) result.getCompilationUnit();
      if (packagePath == null) {
        int count = sourceFile.sourceLocation.sourceFolder.getFullPath().segmentCount();
        packagePath =
            sourceFile.resource.getFullPath().removeFirstSegments(count).removeLastSegments(1);
      }
      if (this.secondaryTypesToRemove == null)
        this.secondaryTypesToRemove = new SimpleLookupTable();
      ArrayList types =
          (ArrayList) this.secondaryTypesToRemove.get(sourceFile.sourceLocation.binaryFolder);
      if (types == null) types = new ArrayList(definedTypeNames.size());
      types.add(packagePath.append(new String(previous)));
      this.secondaryTypesToRemove.put(sourceFile.sourceLocation.binaryFolder, types);
    }
    super.finishedWith(sourceLocator, result, mainTypeName, definedTypeNames, duplicateTypeNames);
  }
  private IStatus validateProject() {
    hostPageProject = null;

    String str = projectField.getText().trim();
    if (str.length() == 0) {
      return Util.newErrorStatus("Enter the project name");
    }

    IPath path = new Path(str);
    if (path.segmentCount() != 1) {
      return Util.newErrorStatus("Invalid project path");
    }

    IProject project = Util.getWorkspaceRoot().getProject(str);
    if (!project.exists()) {
      return Util.newErrorStatus("Project does not exist");
    }

    if (!project.isOpen()) {
      return Util.newErrorStatus("Project is not open");
    }

    if (!GWTNature.isGWTProject(project)) {
      return Util.newErrorStatus("Project is not a GWT project");
    }

    hostPageProject = project;
    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;
  }
  protected ILaunch doLaunch(ILaunchConfiguration config, String testName)
      throws URISyntaxException, IOException, CoreException {
    ILaunch launch;
    IPath pathToFiles = getPathToFiles(testName);

    if (!ValgrindTestsPlugin.RUN_VALGRIND) {
      bindLocation(pathToFiles);
    }

    ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
    wc.setAttribute(
        LaunchConfigurationConstants.ATTR_INTERNAL_OUTPUT_DIR, pathToFiles.toOSString());
    wc.doSave();

    ValgrindTestLaunchDelegate delegate = new ValgrindTestLaunchDelegate();
    launch = new Launch(config, ILaunchManager.PROFILE_MODE, null);

    DebugPlugin.getDefault().getLaunchManager().addLaunch(launch);
    launches.add(launch);
    delegate.launch(config, ILaunchManager.PROFILE_MODE, launch, null);

    if (ValgrindTestsPlugin.RUN_VALGRIND) {
      unbindLocation(pathToFiles);
    }
    return launch;
  }
 /**
  * Checks if all source files are existing. If not, create them.
  *
  * @param javaProj
  */
 private void checkSourceFolders(final IJavaProject javaProj) {
   if (javaProj == null) return;
   if (javaProj.exists()) {
     try {
       if (!javaProj.isOpen()) {
         javaProj.open(new NullProgressMonitor());
       }
       IClasspathEntry[] entries = javaProj.getRawClasspath();
       for (IClasspathEntry entry : entries) {
         if (IClasspathEntry.CPE_SOURCE == entry.getEntryKind()) {
           IPath path = entry.getPath();
           final IPath folderPath = path.removeFirstSegments(1);
           if (!folderPath.isEmpty()) {
             Display.getDefault()
                 .asyncExec(
                     new Runnable() {
                       public void run() {
                         try {
                           ImportUtils.createFolders(
                               javaProj.getProject(), folderPath, IResource.FORCE);
                         } catch (CoreException e) {
                           _log.error(e.getMessage());
                         }
                       }
                     });
           }
         }
       }
     } catch (JavaModelException e) {
       _log.error("findProjectSources: Could not retrieve project sources:", e); // $NON-NLS-1$
     }
   }
 }
 public void finish() {
   String destination = destinationText.getText().trim();
   if (!"".equals(destination)) {
     IPath path = Path.fromOSString(destination);
     getDialogSettings().put(getClass().getName(), path.removeLastSegments(1).toOSString());
   }
 }
  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();
  }
Exemple #11
0
  /**
   * Return true if the IFile with the given name exists in this project.
   *
   * @param aFileName filename can be relative to one of the input file paths for the
   *     WorkbenchURIConverter.
   * @return <code>true</code> if filename exists in this project
   * @since 1.0.0
   */
  public boolean fileExists(String aFileName) {
    if (aFileName == null) return false;

    IPath path = new Path(aFileName);
    if (path.isAbsolute()) return ResourcesPlugin.getWorkspace().getRoot().getFile(path).exists();
    else return getWorkbenchURIConverter().canGetUnderlyingResource(aFileName);
  }
 /**
  * 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;
 }
 @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);
       }
     }
   }
 }
  @Override
  protected boolean validatePage() {
    IStatus status =
        JavaConventions.validateCompilationUnitName(
            this.getFileName() + ".java", CompilerOptions.VERSION_1_3, CompilerOptions.VERSION_1_3);
    if (!status.isOK()) {
      setErrorMessage(status.getMessage());
      return false;
    }
    IProject project =
        ResourcesPlugin.getWorkspace().getRoot().getProject(getContainerFullPath().segment(0));

    // This may need to change depending on how we want to deal with localized components in future.
    LocatePlugin locatePlugin = LocatePlugin.getDefault();
    try {
      LocalizedComponentsLocateResult result =
          locatePlugin.getLocalizedComponentsLocateResult(project, getFileName());
      if (result.getResources().length > 0) {
        setErrorMessage("A component by that name already exists");
        return false;
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    // Check that we aren't going to create a wocomponent inside another wocomponent
    IPath path = getContainerFullPath();
    if (path.lastSegment().endsWith(".wo")) {
      setErrorMessage("Cannot create a component within another component");
      return false;
    }

    return super.validatePage();
  }
Exemple #15
0
  /**
   * Creates new symbolic file system link from file or folder to another filesystem file. The
   * target path has to be present on disk.
   *
   * @param linkPath - filesystem path of the link being created.
   * @param realPath - file or folder on the file system, the target of the link.
   * @throws UnsupportedOperationException on Windows where links are not supported.
   * @throws IOException if execution of the command fails.
   */
  public static void createSymbolicLink(IPath linkPath, IPath realPath) throws IOException {
    if (!isSymbolicLinkSupported()) {
      throw new UnsupportedOperationException("Windows links .lnk are not supported.");
    }

    String command = "ln -s " + realPath.toOSString() + ' ' + linkPath.toOSString();
    Process process = Runtime.getRuntime().exec(command);

    // Wait for up to 2.5s...
    for (int i = 0; i < 5; i++) {
      try {
        Assert.assertTrue("ln process exited with non-zero status", process.waitFor() == 0);
        // If exitValue succeeded, then the process has exitted successfully.
        break;
      } catch (InterruptedException e) {
        // Clear interrupted state, see Java bug http://bugs.sun.com/view_bug.do?bug_id=6420270
        Thread.interrupted();
      }
      // wait for a 500ms before checking again
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        /*don't care*/
      }
    }
    Assert.assertTrue(
        "Symbolic link not created, command=[" + command + "]", linkPath.toFile().exists());
  }
Exemple #16
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);
    }
  }
 /**
  * Copy the content in the directory with the given name located in the <code>test_data</code>
  * directory in the plug-in with the given id into the specified target directory.
  *
  * @param pluginId the id of the plug-in containing the project
  * @param projectName the name of the directory containing the project
  * @param targetDirectory the directory into which the content is copied. This directory is
  *     created if it does not already exist
  * @throws IOException if a required file cannot be accessed
  */
 public static void copyPluginRelativeContent(
     String pluginId, String projectName, File targetDirectory) throws IOException {
   URL pluginInstallUri = PluginUtilities.getInstallUrl(pluginId);
   URL sourceUrl = new URL(pluginInstallUri, PROJECT_DIRECTORY_NAME + "/" + projectName);
   IPath sourcePath = new Path(FileLocator.toFileURL(sourceUrl).getPath());
   FileUtilities.copyDirectoryContents(sourcePath.toFile(), targetDirectory);
 }
        @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);
        }
Exemple #19
0
  public static SDK getSDK(IProject project) {
    SDK retval = null;

    // try to determine SDK based on project location
    IPath projectLocation = project.getRawLocation();

    if (projectLocation == null) {
      projectLocation = project.getLocation();
    }

    if (projectLocation != null) {
      IPath sdkLocation = projectLocation.removeLastSegments(2);

      retval = SDKManager.getInstance().getSDK(sdkLocation);

      if (retval == null) {
        retval = SDKUtil.createSDKFromLocation(sdkLocation);

        if (retval != null) {
          SDKManager.getInstance().addSDK(retval);
        }
      }
    }

    return retval;
  }
  /**
   * 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();
  }
  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;
  }
  /** Tests creating a linked folder under a virtual folder */
  public void testCreateLinkedFolderUnderVirtualFolder() {
    // get a non-existing location
    IPath location = getRandomLocation();
    IFolder linkedFolder = existingVirtualFolderInExistingProject.getFolder(getUniqueString());

    try {
      linkedFolder.createLink(location, IResource.ALLOW_MISSING_LOCAL, getMonitor());
    } catch (CoreException e) {
      fail("1.0", e);
    }

    assertTrue("2.0", linkedFolder.exists());
    assertEquals("3.0", location, linkedFolder.getLocation());
    assertTrue("4.0", !location.toFile().exists());

    // getting children should succeed (and be empty)
    try {
      assertEquals("5.0", 0, linkedFolder.members().length);
    } catch (CoreException e) {
      fail("6.0", e);
    }

    // delete should succeed
    try {
      linkedFolder.delete(IResource.NONE, getMonitor());
    } catch (CoreException e) {
      fail("7.0", e);
    }
  }
  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;
  }
  /**
   * Returns the tool tip text for the given element.
   *
   * @param element the element
   * @return the tooltip for the element
   */
  String getToolTipText(Object element) {
    String result;
    if (!(element instanceof IResource)) {
      result =
          ScriptElementLabels.getDefault()
              .getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
    } else {
      IPath path = ((IResource) element).getFullPath();
      if (path.isRoot()) {
        result = getConfigurationElement().getAttribute("name"); // $NON-NLS-1$
      } else {
        result = path.makeRelative().toString();
      }
    }

    if (fWorkingSetFilterActionGroup == null
        || fWorkingSetFilterActionGroup.getWorkingSet() == null) return result;

    IWorkingSet ws = fWorkingSetFilterActionGroup.getWorkingSet();
    String wsstr =
        Messages.format(
            ScriptBrowsingMessages.JavaBrowsingPart_toolTip, new String[] {ws.getLabel()});
    if (result.length() == 0) return wsstr;
    return Messages.format(
        ScriptBrowsingMessages.JavaBrowsingPart_toolTip2, new String[] {result, ws.getLabel()});
  }
 public void changeControlPressed(DialogField field) {
   IJavaProject jproject = chooseProject();
   if (jproject != null) {
     IPath path = jproject.getProject().getFullPath().makeRelative();
     projectField.setText(path.toString());
   }
 }
  /**
   * Returns whether this page's controls currently all contain valid values.
   *
   * @return <code>true</code> if all controls are valid, and <code>false</code> if at least one is
   *     invalid
   */
  private boolean validatePage() {

    String locationFieldContents = getProjectLocationFieldValue();

    if (locationFieldContents.equals("")) { // $NON-NLS-1$
      setErrorMessage(null);
      setMessage(DataTransferMessages.WizardExternalProjectImportPage_projectLocationEmpty);
      return false;
    }

    IPath path = new Path(""); // $NON-NLS-1$
    if (!path.isValidPath(locationFieldContents)) {
      setErrorMessage(DataTransferMessages.WizardExternalProjectImportPage_locationError);
      return false;
    }

    File projectFile = projectFile(locationFieldContents);
    if (projectFile == null) {
      setErrorMessage(
          NLS.bind(
              DataTransferMessages.WizardExternalProjectImportPage_notAProject,
              locationFieldContents));
      return false;
    }
    setProjectName(projectFile);

    if (getProjectHandle().exists()) {
      setErrorMessage(DataTransferMessages.WizardExternalProjectImportPage_projectExistsMessage);
      return false;
    }

    setErrorMessage(null);
    setMessage(null);
    return true;
  }
  /**
   * ************************************************************************ Get the database path
   * for this project
   *
   * @return ***********************************************************************
   */
  @SuppressWarnings("unchecked")
  public String getDatabasePath() {
    HashMap<QualifiedName, Object> properties = null;
    try {
      properties = new HashMap<QualifiedName, Object>(m_project.getPersistentProperties());
    } catch (CoreException e1) {
      System.err.println(
          "Cannot retrieve persistent properties for project " + m_project.getName());
      return null;
    }
    if (!properties.containsKey(ProjectDatabaseProperty.GCS_DATABASE.getKey())) {
      restoreProjectProperties(ProjectDatabaseProperty.GCS_DATABASE);
    }

    try {
      String path = m_project.getPersistentProperty(ProjectDatabaseProperty.GCS_DATABASE.getKey());
      // Relative path
      boolean absolute = true;
      if (!path.isEmpty()) {
        absolute = new File(path).isAbsolute();
      }
      if (!path.isEmpty() && !absolute) {
        IPath projAbsolute = m_project.getLocation();
        String projectPath = projAbsolute.toFile().getAbsolutePath();
        path = projectPath + File.separator + path;
      }
      return path;
    } catch (CoreException e) {
      return null;
    }
  }
Exemple #28
0
  /**
   * Creates new symbolic file system link from file or folder on project root to another file
   * system file. The filename can include relative path as a part of the name but the the path has
   * to be present on disk.
   *
   * @param project - project where to create the file.
   * @param linkName - name of the link being created.
   * @param realPath - file or folder on the file system, the target of the link.
   * @return file handle.
   * @throws UnsupportedOperationException on Windows where links are not supported.
   * @throws IOException...
   * @throws CoreException...
   */
  public static IResource createSymbolicLink(IProject project, String linkName, IPath realPath)
      throws IOException, CoreException, UnsupportedOperationException {

    if (!isSymbolicLinkSupported()) {
      throw new UnsupportedOperationException("Windows links .lnk are not supported.");
    }

    Assert.assertTrue(
        "Path for symbolic link does not exist: [" + realPath.toOSString() + "]",
        new File(realPath.toOSString()).exists());

    IPath linkedPath = project.getLocation().append(linkName);
    createSymbolicLink(linkedPath, realPath);

    IResource resource = project.getFile(linkName);
    resource.refreshLocal(IResource.DEPTH_ZERO, null);

    if (!resource.exists()) {
      resource = project.getFolder(linkName);
      resource.refreshLocal(IResource.DEPTH_ZERO, null);
    }
    Assert.assertTrue("Failed to create resource form symbolic link", resource.exists());

    externalFilesCreated.add(linkedPath.toOSString());
    ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, NULL_MONITOR);
    return resource;
  }
  public void connect(IDocument document) {
    fDocument = document;

    // special checks to see source validation should really execute
    IFile file = null;
    IStructuredModel model = null;
    try {
      model = StructuredModelManager.getModelManager().getExistingModelForRead(document);
      if (model != null) {
        String baseLocation = model.getBaseLocation();
        // The baseLocation may be a path on disk or relative to the
        // workspace root. Don't translate on-disk paths to
        // in-workspace resources.
        IPath basePath = new Path(baseLocation);
        if (basePath.segmentCount() > 1) {
          file = ResourcesPlugin.getWorkspace().getRoot().getFile(basePath);
          /*
           * If the IFile doesn't exist, make sure it's not returned
           */
          if (!file.exists()) file = null;
        }
      }
    } finally {
      if (model != null) {
        model.releaseFromRead();
      }
    }
    fEnableSourceValidation =
        (file != null
            && isBatchValidatorPreferenceEnabled(file)
            && shouldValidate(file)
            && fragmentCheck(file));
  }
  private void saveConfigInfoIntoCache(String configType, String configInfo, IPath portalDir) {
    IPath versionsInfoPath = null;

    if (configType.equals(CONFIG_TYPE_VERSION)) {
      versionsInfoPath =
          LiferayServerCore.getDefault().getStateLocation().append("version.properties");
    } else if (configType.equals(CONFIG_TYPE_SERVER)) {
      versionsInfoPath =
          LiferayServerCore.getDefault().getStateLocation().append("serverInfos.properties");
    }

    if (versionsInfoPath != null) {
      File versionInfoFile = versionsInfoPath.toFile();

      if (configInfo != null) {
        String portalDirKey = CoreUtil.createStringDigest(portalDir.toPortableString());
        Properties properties = new Properties();

        try (FileInputStream fileInput = new FileInputStream(versionInfoFile)) {
          properties.load(fileInput);
        } catch (Exception e) {
        }

        try (FileOutputStream fileOutput = new FileOutputStream(versionInfoFile)) {
          properties.put(portalDirKey, configInfo);
          properties.store(fileOutput, StringPool.EMPTY);
        } catch (Exception e) {
          LiferayServerCore.logError(e);
        }
      }
    }
  }