public static void openFile(IWorkbenchPage page, IFile destinationFile, byte[] initialContent) {
   try {
     if (destinationFile != null) {
       // TODO: prompt to create the file ?  I say no, why would you try the shortcut if you didn't
       // want it created
       if (!destinationFile.exists()) {
         IPath fullPath = destinationFile.getLocation();
         if (fullPath.toFile().getParentFile().mkdirs()) {
           // create Eclipse resource so that the create file doesn't blow chunks
           destinationFile
               .getProject()
               .getFile(destinationFile.getParent().getProjectRelativePath())
               .refreshLocal(IFile.DEPTH_ZERO, null);
         }
         destinationFile.create(new ByteArrayInputStream(initialContent), false, null);
       }
       if (destinationFile.exists()) {
         IDE.openEditor(page, destinationFile);
       }
     }
   } catch (CoreException e) {
     String clazz = destinationFile.getName();
     System.err.println("OpenCakeFile can not open file: " + clazz);
     e.printStackTrace();
   }
 }
  /**
   * @param filePath
   * @return
   */
  protected IFile findFilePath(String filePath) {
    IPath path = null;
    IPath fp = new Path(filePath);
    if (fp.isAbsolute()) {
      if (getBaseDirectory().isPrefixOf(fp)) {
        int segments = getBaseDirectory().matchingFirstSegments(fp);
        path = fp.removeFirstSegments(segments);
      } else {
        path = fp;
      }
    } else {
      path = getWorkingDirectory().append(filePath);
    }

    IFile file = null;
    // The workspace may throw an IllegalArgumentException
    // Catch it and the parser should fallback to scan the entire project.
    try {
      file = findFileInWorkspace(path);
    } catch (Exception e) {
    }

    // We have to do another try, on Windows for cases like "TEST.C" vs "test.c"
    // We use the java.io.File canonical path.
    if (file == null || !file.exists()) {
      File f = path.toFile();
      try {
        String canon = f.getCanonicalPath();
        path = new Path(canon);
        file = findFileInWorkspace(path);
      } catch (IOException e1) {
      }
    }
    return (file != null && file.exists()) ? file : null;
  }
Exemple #3
0
    @Override
    protected void build(IFile result, IProgressMonitor monitor) throws CoreException {
      IFile file = getRelated(result, "owl");
      if (!file.exists()) {
        clean(result, monitor);
        return;
      }

      CIMBuilder.removeMarkers(file);

      ProfileValidator checker =
          new ProfileValidator(getProfileModel(file), getBackgroundModel(file));
      try {
        checker.run();
      } catch (IOException e) {
        throw error("Failed to validate profile", e);
      } catch (ParserException e) {
        throw error("Failed to validate profile", e);
      }

      if (checker.hasErrors()) {
        write(checker.getLog(), null, false, result, IO.RDF_XML_WITH_NODEIDS, monitor);
        result.setDerived(true);
        CIMBuilder.addMarker(
            file,
            "Profile " + file.getName() + " has consistency errors with respect to its schema");
      } else {
        if (result.exists()) result.delete(false, monitor);
      }
    }
  public static IStatus cssBuild(IProject project) throws CoreException {

    SDK sdk = SDKUtil.getSDK(project);

    if (sdk == null) {
      throw new CoreException(
          ThemeCore.createErrorStatus("No SDK for project configured. Could not build theme."));
    }

    ILiferayRuntime liferayRuntime = ServerUtil.getLiferayRuntime(project);

    if (liferayRuntime == null) {
      throw new CoreException(
          ThemeCore.createErrorStatus(
              "Could not get portal runtime for project.  Could not build theme."));
    }

    Map<String, String> appServerProperties = ServerUtil.configureAppServerProperties(project);

    IStatus status = sdk.compileThemePlugin(project, null, appServerProperties);

    if (!status.isOK()) {
      throw new CoreException(status);
    }

    IFolder docroot = CoreUtil.getDocroot(project);

    IFile lookAndFeelFile =
        docroot.getFile("WEB-INF/" + ILiferayConstants.LIFERAY_LOOK_AND_FEEL_XML_FILE);

    if (!lookAndFeelFile.exists()) {
      String id = project.getName().replaceAll(ISDKConstants.THEME_PLUGIN_PROJECT_SUFFIX, "");
      IFile propsFile =
          docroot.getFile("WEB-INF/" + ILiferayConstants.LIFERAY_PLUGIN_PACKAGE_PROPERTIES_FILE);
      String name = id;
      if (propsFile.exists()) {
        Properties props = new Properties();
        try {
          props.load(propsFile.getContents());
          String nameValue = props.getProperty("name");
          if (!CoreUtil.isNullOrEmpty(nameValue)) {
            name = nameValue;
          }
        } catch (IOException e) {
          ThemeCore.logError("Unable to load plugin package properties.", e);
        }
      }

      if (liferayRuntime != null) {
        ThemeDescriptorHelper.createDefaultFile(
            lookAndFeelFile, liferayRuntime.getPortalVersion() + "+", id, name);
      }
    }

    if (docroot != null && docroot.exists()) {
      docroot.refreshLocal(IResource.DEPTH_INFINITE, null);
    }

    return status;
  }
Exemple #5
0
  public static String getBundleSymbolicName(IModule module) throws CoreException {
    String symbolicName = null;

    if (module == null || module.getProject() == null) return "";

    IFile manifest = module.getProject().getFile("target/classes/META-INF/MANIFEST.MF");
    if (!manifest.exists()) {
      manifest = module.getProject().getFile("META-INF/MANIFEST.MF");
    }
    if (manifest.exists()) {
      try {
        Manifest mf = new Manifest(new FileInputStream(manifest.getLocation().toFile()));
        symbolicName = mf.getMainAttributes().getValue("Bundle-SymbolicName");
      } catch (IOException ex) {
        symbolicName = null;
      }
    } else {
      // no OSGi bundle - lets take the project name instead
      symbolicName = null;
    }

    if (symbolicName == null) {
      // no manifest - so grab the artifactId
      symbolicName = getArtifactId(module);
    }

    if (symbolicName == null) {
      symbolicName = module.getId();
    }

    return symbolicName;
  }
  /** Ensures that controls are correctly set. */
  private void dialogChanged() {
    IResource resource =
        ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(getContainerName()));
    if (resource == null) {
      updateStatus("File container must be specified");
      return;
    }
    IContainer container = (IContainer) resource;
    String fileName = getFileName();
    String author = getAuthor();
    String titleName = getModelName();

    final IFile modelfile = container.getFile(new Path("models/" + fileName));
    final IFile htmlfile = container.getFile(new Path("doc/" + titleName + ".html"));

    if (getContainerName().length() == 0) {
      updateStatus("File container must be specified");
      return;
    }
    if ((resource.getType() & (IResource.PROJECT | IResource.FOLDER)) == 0) {
      updateStatus("File container must exist");
      return;
    }
    if (!resource.isAccessible()) {
      updateStatus("Project must be writable");
      return;
    }
    if (fileName.length() == 0) {
      updateStatus("File name must be specified");
      return;
    }
    if (fileName.replace('\\', '/').indexOf('/', 1) > 0) {
      updateStatus("File name must be valid");
      return;
    }
    if (!fileName.endsWith(".gaml")) {
      updateStatus("File extension must be \".gaml\"");
      return;
    }
    if (author.length() == 0) {
      updateStatus("Author name must be specified");
      return;
    }
    if (modelfile.exists()) {
      updateStatus("File already exists");
      return;
    }
    if (htmlfile.exists()) {
      updateStatus("Model name already defined");
      return;
    }

    if (titleName.length() == 0) {
      updateStatus("Model name must be specified");
      return;
    }
    updateStatus(null);
  }
  /**
   * Tries to delete an open project containing an irremovable file. Works only for Linux with
   * natives.
   */
  public void testDeleteOpenProjectLinux() {
    if (!(Platform.getOS().equals(Platform.OS_LINUX) && isReadOnlySupported())) return;

    IProject project = null;
    File projectRoot = null;
    IFolder folder = null;
    try {
      IWorkspace workspace = getWorkspace();
      project = workspace.getRoot().getProject(getUniqueString());
      folder = project.getFolder("a_folder");
      IFile file1 = folder.getFile("file1.txt");
      IFile file2 = project.getFile("file2.txt");

      ensureExistsInWorkspace(new IResource[] {file1, file2}, true);
      projectRoot = project.getLocation().toFile();

      // marks folder as read-only so its files cannot be deleted on Linux
      setReadOnly(folder, true);

      IFile projectFile = project.getFile(".project");
      assertTrue("1.2", projectFile.exists());
      assertTrue("1.3", projectFile.isSynchronized(IResource.DEPTH_INFINITE));

      try {
        project.delete(IResource.FORCE, getMonitor());
        fail("2.0 - should have failed");
      } catch (CoreException ce) {
        // success - a file couldn't be removed
      }
      assertTrue("2.1", project.exists());
      assertTrue("2.2", file1.exists());
      assertTrue("2.3", !file2.exists());
      assertTrue("2.5", folder.exists());
      assertTrue("2.6", projectFile.exists());
      assertTrue("2.7", project.isSynchronized(IResource.DEPTH_INFINITE));

      setReadOnly(folder, false);

      assertTrue("3.5", project.isSynchronized(IResource.DEPTH_INFINITE));
      try {
        project.delete(IResource.FORCE, getMonitor());
      } catch (CoreException ce) {
        ce.printStackTrace();
        fail("4.0", ce);
      }

      assertTrue("5.1", !project.exists());
      assertTrue("5.2", !file1.exists());
      assertTrue("5.3", file1.isSynchronized(IResource.DEPTH_INFINITE));
      assertTrue("5.4", project.isSynchronized(IResource.DEPTH_INFINITE));

      assertTrue("6.0", !projectRoot.exists());
    } finally {
      if (folder != null && folder.exists()) setReadOnly(folder, false);
      if (projectRoot != null) ensureDoesNotExistInFileSystem(projectRoot);
    }
  }
  /** Tries to delete a folder containing an unremovable file. Works only for Windows. */
  public void testDeleteFolderWindows() {
    if (!isWindows()) return;

    IProject project = null;
    InputStream input = null;
    File projectRoot = null;
    try {
      IWorkspace workspace = getWorkspace();
      project = workspace.getRoot().getProject(getUniqueString());
      IFolder folder = project.getFolder("a_folder");
      IFile file1 = folder.getFile("file1.txt");
      IFile file3 = folder.getFile("file3.txt");

      ensureExistsInWorkspace(new IResource[] {file1, file3}, true);
      projectRoot = project.getLocation().toFile();

      // opens a file so it cannot be removed on Windows
      try {
        input = file1.getContents();
      } catch (CoreException ce) {
        ce.printStackTrace();
        fail("1.0");
      }

      try {
        folder.delete(IResource.FORCE, getMonitor());
        fail("2.0 - should have failed");
      } catch (CoreException ce) {
        // success - a file couldn't be removed
      }
      assertTrue("2.2", file1.exists());
      assertTrue("2.4", !file3.exists());
      assertTrue("2.5", folder.exists());
      assertTrue("2.7", folder.isSynchronized(IResource.DEPTH_INFINITE));

      assertClose(input);

      assertTrue("3.5", project.isSynchronized(IResource.DEPTH_INFINITE));
      try {
        folder.delete(IResource.FORCE, getMonitor());
      } catch (CoreException ce) {
        ce.printStackTrace();
        fail("4.0", ce);
      }
      assertTrue("5.1", !file1.exists());
      assertTrue("5.2", !folder.exists());
      assertTrue("5.3", file1.isSynchronized(IResource.DEPTH_INFINITE));
      assertTrue("5.4", folder.isSynchronized(IResource.DEPTH_INFINITE));
    } finally {
      try {
        assertClose(input);
      } finally {
        if (projectRoot != null) ensureDoesNotExistInFileSystem(projectRoot);
      }
    }
  }
 // CreateShortcut, LoadResource, InitDiagramFileAction
 public void testPredefinedActions() throws Exception {
   DiaGenSource s1 = createLibraryGen(false);
   final GenEditorGenerator editorGen = s1.getGenDiagram().getEditorGen();
   GenContextMenu menu = GMFGenFactory.eINSTANCE.createGenContextMenu();
   menu.getContext().add(s1.getGenDiagram());
   final CreateShortcutAction createShortcutAction =
       GMFGenFactory.eINSTANCE.createCreateShortcutAction();
   final LoadResourceAction loadResourceAction =
       GMFGenFactory.eINSTANCE.createLoadResourceAction();
   menu.getItems().add(createShortcutAction);
   menu.getItems().add(loadResourceAction);
   editorGen.getContextMenus().clear(); // make sure there's no other (default) menus
   editorGen.getContextMenus().add(menu);
   editorGen.getDiagram().getContainsShortcutsTo().add("ecore");
   assertTrue("sanity", editorGen.getDiagram().generateCreateShortcutAction());
   //
   generateAndCompile(s1);
   //
   IProject generatedProject =
       ResourcesPlugin.getWorkspace().getRoot().getProject(editorGen.getPlugin().getID());
   IFile generatedManifest = generatedProject.getFile("plugin.xml");
   assertTrue(generatedManifest.exists());
   DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   Document parsedManifest = db.parse(new InputSource(generatedManifest.getContents()));
   XPath xf = XPathFactory.newInstance().newXPath();
   XPathExpression xe =
       xf.compile("/plugin/extension[@point = 'org.eclipse.ui.menus']/menuContribution/command");
   NodeList result = (NodeList) xe.evaluate(parsedManifest, XPathConstants.NODESET);
   assertEquals(2, result.getLength());
   xe = xf.compile("/plugin/extension[@point = 'org.eclipse.ui.commands']/command");
   result = (NodeList) xe.evaluate(parsedManifest, XPathConstants.NODESET);
   assertTrue(result.getLength() > 2);
   HashSet<String> allCommands = new HashSet<String>();
   for (int i = result.getLength() - 1; i >= 0; i--) {
     allCommands.add(result.item(i).getAttributes().getNamedItem("defaultHandler").getNodeValue());
   }
   assertTrue(allCommands.contains(createShortcutAction.getQualifiedClassName()));
   assertTrue(allCommands.contains(loadResourceAction.getQualifiedClassName()));
   IFile file1 =
       generatedProject.getFile(
           "/src/" + createShortcutAction.getQualifiedClassName().replace('.', '/') + ".java");
   IFile file2 =
       generatedProject.getFile(
           "/src/" + loadResourceAction.getQualifiedClassName().replace('.', '/') + ".java");
   assertTrue(file1.exists());
   assertTrue(file2.exists());
   //
   //		DiaGenSource s2 = createLibraryGen(true);
   //		fail("TODO");
 }
 @SuppressWarnings("unchecked")
 public IEditorPart openEditor(IStructuredSelection selection) {
   Object o = selection.getFirstElement();
   EObject obj = null;
   if (o instanceof EObject) {
     obj = (EObject) o;
   }
   if (o instanceof EObjectGroup) {
     EObjectGroup group = (EObjectGroup) o;
     if (!group.getEObjects().isEmpty()) {
       obj = group.getEObjects().getFirst();
     }
   }
   if (obj != null) {
     //			URI uri = obj.eResource().getURI();
     //			String fileString = URI.decode(uri.path());
     //			fileString = fileString.replaceFirst("/resource", "");
     //			IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(fileString));
     //			IWorkbench workbench = PlatformUI.getWorkbench();
     IFile file = ((LinkedList<ResultModel>) viewer.getInput()).get(0).getIFile();
     IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
     IWorkbenchPage page = workbenchWindow.getActivePage();
     try {
       if (file.exists()) {
         return IDE.openEditor(page, file);
       }
     } catch (PartInitException exception) {
       return null;
     }
   }
   return null;
 }
  public static IClasspathContainer readMavenClasspath(IJavaProject javaProject) {
    IFile file = javaProject.getProject().getFile(".che/classpath.maven");
    IClasspathEntry[] entries;
    if (file.exists()) {
      try {
        char[] chars = Util.getResourceContentsAsCharArray(file);
        String content = new String(chars);
        if (!content.isEmpty()) {
          String[] pathToJars = content.split(":");
          List<IClasspathEntry> classpathEntry = new ArrayList<>();
          for (String path : pathToJars) {
            String srcPath = path.substring(0, path.lastIndexOf('.')) + "-sources.jar";
            classpathEntry.add(
                JavaCore.newLibraryEntry(
                    new org.eclipse.core.runtime.Path(path),
                    new org.eclipse.core.runtime.Path(srcPath),
                    null));
          }
          entries = classpathEntry.toArray(new IClasspathEntry[classpathEntry.size()]);
        } else {
          entries = EMPTY;
        }
      } catch (JavaModelException e) {
        LOG.error("Can't read maven classpath.", e);
        entries = EMPTY;
      }
    } else {
      entries = EMPTY;
    }

    return new MavenClasspathContainer(entries);
  }
  @Before
  public void setUp() throws Exception {
    PHPCoreTests.waitForIndexer();
    PHPCoreTests.waitForAutoBuild();

    project1 = FileUtils.createProject("project1");

    IFolder folder = project1.getFolder("src");

    if (!folder.exists()) {
      folder.create(true, true, new NullProgressMonitor());
    }
    file = folder.getFile("test23.php");

    InputStream source =
        new ByteArrayInputStream(
            "<?php class Item { public $title;} class ItemEx extends Item{public $title;} $a=new ItemEx(); $a->title;?>"
                .getBytes());

    if (!file.exists()) {
      file.create(source, true, new NullProgressMonitor());
    } else {
      file.setContents(source, IFile.FORCE, new NullProgressMonitor());
    }

    PHPCoreTests.waitForIndexer();
    PHPCoreTests.waitForAutoBuild();
  }
  /**
   * Validates the fields, displays errors and warnings. Enables the finish button if there are no
   * errors.
   */
  private void validatePage() {
    String error = null;
    String warning = null;

    // -- validate type
    TypeInfo type = mValues.type;
    if (error == null) {
      if (type == null) {
        error = "One of the types must be selected (e.g. layout, values, etc.)";
      }
    }

    // -- validate project
    if (mValues.project == null) {
      error = "Please select an Android project.";
    }

    // -- validate type API level
    if (error == null) {
      IAndroidTarget target = Sdk.getCurrent().getTarget(mValues.project);
      int currentApiLevel = 1;
      if (target != null) {
        currentApiLevel = target.getVersion().getApiLevel();
      }

      assert type != null;
      if (type.getTargetApiLevel() > currentApiLevel) {
        error =
            "The API level of the selected type (e.g. AppWidget, etc.) is not "
                + "compatible with the API level of the project.";
      }
    }

    // -- validate filename
    if (error == null) {
      String fileName = mValues.getFileName();
      assert type != null;
      ResourceFolderType folderType = type.getResFolderType();
      error = ResourceNameValidator.create(true, folderType).isValid(fileName);
    }

    // -- validate destination file doesn't exist
    if (error == null) {
      IFile file = mValues.getDestinationFile();
      if (file != null && file.exists()) {
        warning = "The destination file already exists";
      }
    }

    // -- update UI & enable finish if there's no error
    setPageComplete(error == null);
    if (error != null) {
      setMessage(error, IMessageProvider.ERROR);
    } else if (warning != null) {
      setMessage(warning, IMessageProvider.WARNING);
    } else {
      setErrorMessage(null);
      setMessage(null);
    }
  }
Exemple #14
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);
    }
  }
Exemple #15
0
  public LoadedDeclarations parse(XModelObject o, IPath source, IKbProject sp) {
    if (o == null) return null;

    if (o.getParent() instanceof FolderImpl) {
      IFile f = ResourcesPlugin.getWorkspace().getRoot().getFile(source);
      if (f != null && f.exists()) {
        try {
          ((FolderImpl) o.getParent()).updateChildFile(o, f.getLocation().toFile());
        } catch (XModelException e) {
          ModelPlugin.getPluginLog().logError(e);
        }
        if (o.getParent() == null) {
          boolean b = isLikelyComponentSource(f);
          if (!b) return null;
          o = EclipseResourceUtil.getObjectByResource(o.getModel(), f);
          if (o == null) return null;
        }
      }
    }

    LoadedDeclarations ds = new LoadedDeclarations();
    if (LibraryScanner.isTLDFile(o)) {
      parseTLD(o, source, ds);
    } else if (LibraryScanner.isFaceletTaglibFile(o)) {
      parseFaceletTaglib(o, source, ds);
    } else if (LibraryScanner.isFacesConfigFile(o)) {
      parseFacesConfig(o, source, ds);
    }
    return ds;
  }
 public void addNotationInfo(RootContainer rootContainer, IEditorInput input) {
   try {
     IFile file = getNotationInfoFile(((FileEditorInput) input).getFile());
     if (file.exists()) {
       Element notationInfo =
           documentBuilderFactory
               .newDocumentBuilder()
               .parse(file.getContents())
               .getDocumentElement();
       Element changedInfo = convertCheck(notationInfo);
       processRootContainer(rootContainer, changedInfo == null ? notationInfo : changedInfo);
       if (changedInfo != null) {
         file.setContents(
             new ByteArrayInputStream(toNotationInfoXml(rootContainer).getBytes()),
             true,
             true,
             null);
       }
     } else {
       file.create(
           new ByteArrayInputStream(createInitialNotationInfo().toString().getBytes()),
           true,
           null);
     }
   } catch (Exception e) {
     Logger.logError("Problem adding notation info", e);
     throw new RuntimeException(e);
   }
 }
  /**
   * Method "replace".
   *
   * @return true if ok
   */
  public boolean replace(String migrationTaskName) {
    IFolder librariesFolder = ResourceManager.getLibrariesFolder();
    IFile definitionFile = librariesFolder.getFile(TALENDDEFINITIONFILENAME);

    if (definitionFile.exists()) {
      File file = new File(definitionFile.getLocationURI());
      try {
        String content = FileUtils.readFileToString(file, EMFUtil.ENCODING);
        for (String oldString : old2new.keySet()) {
          String newString = old2new.get(oldString);
          if (log.isInfoEnabled()) {
            log.info(
                DefaultMessagesImpl.getString(
                    "TalendDefinitionFileUpdate_MigLog",
                    migrationTaskName,
                    oldString,
                    newString)); //$NON-NLS-1$
          }
          content = StringUtils.replace(content, oldString, newString);
        }
        FileUtils.writeStringToFile(file, content, EMFUtil.ENCODING);
      } catch (IOException e) {
        log.error(e.getMessage(), e);
        return false;
      }
    }

    return true;
  }
  protected void addOrUpdateProjectToConf(EditorProject editorProject, IProject gemocProject) {
    IFile configFile = gemocProject.getFile(new Path(Activator.GEMOC_PROJECT_CONFIGURATION_FILE));
    if (configFile.exists()) {
      Resource.Factory.Registry reg = Resource.Factory.Registry.INSTANCE;
      Map<String, Object> m = reg.getExtensionToFactoryMap();
      m.put(Activator.GEMOC_PROJECT_CONFIGURATION_FILE_EXTENSION, new XMIResourceFactoryImpl());

      // Obtain a new resource set
      ResourceSet resSet = new ResourceSetImpl();

      // get the resource
      Resource resource =
          resSet.getResource(URI.createURI(configFile.getLocationURI().toString()), true);

      LanguageDefinition gemocLanguageWorkbenchConfiguration =
          (LanguageDefinition) resource.getContents().get(0);
      addOrUpdateProjectToConf(editorProject, gemocLanguageWorkbenchConfiguration);

      try {
        resource.save(null);
      } catch (IOException e) {
        Activator.error(e.getMessage(), e);
      }
    }
    try {
      configFile.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
    } catch (CoreException e) {
      Activator.error(e.getMessage(), e);
    }
  }
Exemple #19
0
  /**
   * this will convert the IO file name of the resource bundle to java package name
   *
   * @param project
   * @param value - the io file name
   * @return - the java package name of the resource bundle
   */
  public static String convertIOToJavaFileName(IProject project, String value) {
    String rbIOFile = value.substring(value.lastIndexOf("/") + 1); // $NON-NLS-1$
    IFile resourceBundleFile = null;
    IWorkspace workspace = ResourcesPlugin.getWorkspace();
    IWorkspaceRoot wroot = workspace.getRoot();
    IClasspathEntry[] cpEntries = CoreUtil.getClasspathEntries(project);
    for (IClasspathEntry iClasspathEntry : cpEntries) {
      if (IClasspathEntry.CPE_SOURCE == iClasspathEntry.getEntryKind()) {
        IPath entryPath = wroot.getFolder(iClasspathEntry.getPath()).getLocation();
        entryPath = entryPath.append(rbIOFile);
        resourceBundleFile = wroot.getFileForLocation(entryPath);
        // System.out.println( "ResourceBundleValidationService.validate():" + resourceBundleFile );
        if (resourceBundleFile != null && resourceBundleFile.exists()) {
          break;
        }
      }
    }

    String javaName = resourceBundleFile.getProjectRelativePath().toPortableString();
    if (javaName.indexOf('.') != -1) {
      // Strip the extension
      javaName = value.substring(0, value.lastIndexOf('.'));
      // Replace all "/" by "."
      javaName = javaName.replace('/', '.');
    }
    return javaName;
  }
  public void testNewBeansXMLWizard() throws CoreException {
    NewBeansXMLWizardContext context = new NewBeansXMLWizardContext();
    context.init("org.jboss.tools.cdi.ui.wizard.NewBeansXMLCreationWizard");

    try {

      WizardNewFileCreationPage page =
          (WizardNewFileCreationPage) context.wizard.getPage("newFilePage1");
      String s = page.getFileName();
      assertEquals("beans.xml", s);
      assertFalse(context.wizard.canFinish());
      page.setFileName("beans2.xml");
      assertTrue(context.wizard.canFinish());
      String c = page.getContainerFullPath().toString();
      assertEquals("/tck/WebContent/WEB-INF", c);

      context.wizard.performFinish();

      IFile f =
          context.tck.getParent().getFile(page.getContainerFullPath().append(page.getFileName()));
      assertTrue(f.exists());

      String text = FileUtil.readStream(f.getContents());
      assertTrue(text.indexOf("http://java.sun.com/xml/ns/javaee") > 0);

    } finally {
      context.close();
    }
  }
  private static IFileEditorInput getFileStorage(int index) throws CoreException {
    String filename = getBatchDateString();
    filename += (index > 0 ? "_" + index : "") + ".tcl";
    IFolder templateFolder =
        SicsVisualBatchViewer.getProjectFolder(
            SicsVisualBatchViewer.EXPERIMENT_PROJECT, FOLDER_TEMPLATE);
    IFile templateFile = templateFolder.getFile(FILE_TEMPLATE);
    IFolder folder =
        SicsVisualBatchViewer.getProjectFolder(
            SicsVisualBatchViewer.EXPERIMENT_PROJECT, SicsVisualBatchViewer.AUTOSAVE_FOLDER);
    IFileEditorInput input = new FileEditorInput(folder.getFile(filename));
    if (input.exists()) {
      return getFileStorage(index++);
    } else {
      try {
        byte[] read = null;
        if (templateFile.exists()) {
          long size = EFS.getStore(templateFile.getLocationURI()).fetchInfo().getLength();
          //					long size = templateFolder.getLocation().toFile().length();
          read = new byte[(int) size];
          InputStream inputStream = templateFile.getContents();
          inputStream.read(read);
        } else {
          read = new byte[0];
          templateFile.create(new ByteArrayInputStream(read), IResource.ALLOW_MISSING_LOCAL, null);
        }
        input.getFile().create(new ByteArrayInputStream(read), IResource.ALLOW_MISSING_LOCAL, null);
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return input;
  }
  /**
   * Gets the fully qualified class name for an active file. For example, its value is foo.bar.Baz.
   *
   * @param file Get fully qualified class file.
   * @return The fully qualified class name. For example,foo.bar.Baz.
   */
  private String getFullyQualifedClassName(IFile file) {
    String fullClassName = "";
    if (file.exists() && file.getName().endsWith(EclipseSensorConstants.JAVA_EXT)) {
      ICompilationUnit compilationUnit = (ICompilationUnit) JavaCore.create(file);
      String className = compilationUnit.getElementName();
      if (className.endsWith(EclipseSensorConstants.JAVA_EXT)) {
        className = className.substring(0, className.length() - 5);
      }

      try {
        IPackageDeclaration[] packageDeclarations = compilationUnit.getPackageDeclarations();
        // Should only have one package declaration
        if (packageDeclarations == null || packageDeclarations.length == 0) {
          fullClassName = className;
        } else {
          fullClassName = packageDeclarations[0].getElementName() + '.' + className;
        }
      } catch (JavaModelException e) {
        // This exception will be thrown if user is working on a Java but did not open
        // it with "Java Perspective". Thus, the Java Model does not exist to parse
        // Java files. So we only log out exception while Eclipse's Java Perspective
        // exits.
        if (!e.isDoesNotExist()) {
          EclipseSensorPlugin.getDefault().log(file.getName(), e);
        }
      }
    }

    return fullClassName;
  }
  @Test
  public void testNewLiferayModuleProjectNewProperties() throws Exception {
    NewLiferayModuleProjectOp op = NewLiferayModuleProjectOp.TYPE.instantiate();

    op.setProjectName("test-properties-in-portlet");

    op.setProjectTemplateName("portlet");
    op.setComponentName("Test");

    PropertyKey pk = op.getPropertyKeys().insert();

    pk.setName("property-test-key");
    pk.setValue("property-test-value");

    Status exStatus =
        NewLiferayModuleProjectOpMethods.execute(
            op, ProgressMonitorBridge.create(new NullProgressMonitor()));

    assertEquals("OK", exStatus.message());

    IProject modPorject = CoreUtil.getProject(op.getProjectName().content());
    modPorject.open(new NullProgressMonitor());

    SearchFilesVisitor sv = new SearchFilesVisitor();
    List<IFile> searchFiles = sv.searchFiles(modPorject, "TestPortlet.java");
    IFile componentClassFile = searchFiles.get(0);

    assertEquals(componentClassFile.exists(), true);

    String actual = CoreUtil.readStreamToString(componentClassFile.getContents());

    assertTrue(actual, actual.contains("\"property-test-key=property-test-value\""));
  }
  @Override
  public boolean equals(Object obj) {
    if (obj == null) return false;

    if (this == obj) return true;

    if (!(obj instanceof BPELModuleDelegate)) return false;

    BPELModuleDelegate bmd = (BPELModuleDelegate) obj;

    if (this.getProject() != null
        && this.getProject().exists()
        && !this.getProject().equals(bmd.getProject())) {
      return false;
    }

    if (file != null
        && file.exists()
        && !(file.getFullPath().equals(bmd.getFile().getFullPath()))) {
      return false;
    }

    if (getId() != null && !getId().equals(bmd.getId())) return false;

    return true;
  }
 private void replaceToReference(MapEntryModel entry) {
   for (DFPropModel child : entry.getChild()) {
     if (child instanceof MapModel) {
       boolean update = false;
       DFPropModel[] elements = child.getChild();
       for (int i = 0; i < elements.length; i++) {
         DFPropModel element = elements[i];
         if (element instanceof NamedModel) {
           try {
             IFile refFile = getReferencesFile((NamedModel) element);
             if (refFile.exists()) {
               String source = getReferencesSource(refFile);
               DFPropFileModel propModel = new DFPropModelParser().parse(source);
               propModel.setFileName(refFile.getName());
               propModel.setFilePath(refFile.getProjectRelativePath().toString());
               propModel.setReferences(true);
               elements[i] = new DFPropReferenceModel((NamedModel) element, propModel);
               update = true;
             }
           } catch (CoreException e) {
           }
         }
       }
       if (update) {
         ((MapModel) child).replaceChild(elements);
       }
     }
   }
 }
  /** @throws PartInitException */
  @Test
  public void testDS3466TableColumnHAlignmentProperty() throws PartInitException {
    IFile moduleFile = getProject().getFile(MODULE_MODEL);
    Assert.assertTrue(moduleFile.exists());
    IEditorPart ep = openDefaultEditor(moduleFile);
    PageUiAssert.assertInstanceOfMultiPageEditorPart(ep);
    MultiPageEditorPart mep = (MultiPageEditorPart) ep;
    DesignEditor editor = (DesignEditor) mep.getSelectedPage();
    RootEditPart rep = editor.getViewer().getRootEditPart();
    List<?> list = rep.getChildren();
    if (!list.isEmpty()) {
      WidgetEditPart wep = (WidgetEditPart) list.get(0);
      Assert.assertNotNull("Module WidgetEditPart is not found", wep);
      List<?> children = wep.getChildren();
      Assert.assertFalse("Module Widget has no children", children.isEmpty());
      WidgetEditPart bep = (WidgetEditPart) children.get(0);
      Assert.assertFalse("Box Widget has no children", bep.getChildren().isEmpty());
      WidgetEditPart tableep = (WidgetEditPart) bep.getChildren().get(0);
      IFigure mfig = tableep.getFigure();
      Assert.assertTrue(mfig instanceof TableFigure);

      List<?> tableChildren = tableep.getChildren();
      Assert.assertFalse("Table Widget has no columns", tableChildren.isEmpty());
      WidgetEditPart tcep = (WidgetEditPart) tableChildren.get(1);
      String halign = tcep.getWidget().getContents().get(0).getPropertyValue("item-halign");
      Assert.assertNotNull("Horizontal Alignment property not found for table column", halign);
      Assert.assertEquals("center", halign);
    }
  }
  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;
  }
 /**
  * Deletes a set of files from the file system, and also their parent folders if those become
  * empty during this process.
  *
  * @param nameSet set of file paths
  * @param monitor progress monitor
  * @throws CoreException if an error occurs
  */
 private void deleteFiles(final Set<IPath> nameSet, IProgressMonitor monitor)
     throws CoreException {
   if (nameSet == null || nameSet.isEmpty()) {
     return;
   }
   Set<IContainer> subFolders = new HashSet<IContainer>();
   for (IPath filePath : nameSet) {
     // Generate new path
     IFile currentFile = project.getFile(filePath);
     if (currentFile.exists()) {
       // Retrieve parent folder and store for deletion
       IContainer folder = currentFile.getParent();
       subFolders.add(folder);
       currentFile.delete(true, monitor);
     }
     monitor.worked(1);
   }
   // Delete parent folders, if they are empty
   for (IContainer folder : subFolders) {
     if (folder.exists() && folder.members().length == 0) {
       folder.delete(true, monitor);
     }
     monitor.worked(1);
   }
 }
  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));
  }
 public boolean pageExists(String wiki, String space, String page, String language) {
   IFile pageFile =
       baseFolder
           .getFolder(PAGES_DIRECTORY)
           .getFile(getFileNameForPage(wiki, space, page, language));
   return pageFile.exists();
 }