예제 #1
0
  private void runJavaProcessInProject(
      TmcProjectInfo projectInfo,
      ClassPath classPath,
      String taskName,
      List<String> args,
      InputOutput inOut,
      BgTaskListener<ProcessResult> listener) {
    FileObject projectDir = projectInfo.getProjectDir();

    JavaPlatform platform =
        JavaPlatform.getDefault(); // Should probably use project's configured platform instead

    FileObject javaExe = platform.findTool("java");
    if (javaExe == null) {
      throw new IllegalArgumentException();
    }

    // TMC server packages this with every exercise for our convenience.
    // True even for Maven exercises, at least until NB's Maven API is published.
    ClassPath testRunnerClassPath = getTestRunnerClassPath(projectInfo);

    if (testRunnerClassPath != null) {
      classPath = ClassPathSupport.createProxyClassPath(classPath, testRunnerClassPath);
    }

    String[] command = new String[3 + args.size()];
    command[0] = FileUtil.toFile(javaExe).getAbsolutePath();
    command[1] = "-cp";
    command[2] = classPath.toString(ClassPath.PathConversionMode.WARN);
    System.arraycopy(args.toArray(new String[args.size()]), 0, command, 3, args.size());

    log.info(StringUtils.join(command, ' '));
    ProcessRunner runner = new ProcessRunner(command, FileUtil.toFile(projectDir), inOut);
    BgTask.start(taskName, runner, listener);
  }
예제 #2
0
 public void testFindTestSources() throws Exception {
   NbModuleProject p = generateStandaloneModule("p");
   FileObject test = p.getTestSourceDirectory("unit");
   FileObject oneTest = FileUtil.createData(test, "p/OneTest.java");
   FileObject r = FileUtil.createData(test, "p/r.png");
   FileObject otherTest = FileUtil.createData(test, "p/OtherTest.java");
   FileObject pkg = test.getFileObject("p");
   FileObject thirdTest = FileUtil.createData(test, "p2/ThirdTest.java");
   ModuleActions a = new ModuleActions(p);
   assertEquals("null", String.valueOf(a.findTestSources(Lookup.EMPTY, false)));
   assertEquals(
       "unit:p/OneTest.java",
       String.valueOf(a.findTestSources(Lookups.singleton(oneTest), false)));
   assertEquals(
       "unit:p/OneTest.java,p/OtherTest.java",
       String.valueOf(a.findTestSources(Lookups.fixed(oneTest, otherTest), false)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookups.singleton(pkg), false)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookups.singleton(r), false)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookups.fixed(oneTest, r), false)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookup.EMPTY, true)));
   assertEquals(
       "unit:p/OneTest.java", String.valueOf(a.findTestSources(Lookups.singleton(oneTest), true)));
   assertEquals(
       "unit:p/OneTest.java,p/OtherTest.java",
       String.valueOf(a.findTestSources(Lookups.fixed(oneTest, otherTest), true)));
   assertEquals("unit:p/**", String.valueOf(a.findTestSources(Lookups.singleton(pkg), true)));
   assertEquals(
       "unit:p/**,p2/ThirdTest.java",
       String.valueOf(a.findTestSources(Lookups.fixed(pkg, thirdTest), true)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookups.singleton(r), true)));
   assertEquals("null", String.valueOf(a.findTestSources(Lookups.fixed(oneTest, r), true)));
 }
예제 #3
0
 /**
  * Returns default folder icon as {@link java.awt.Image}. Never returns <code>null</code>.
  *
  * @param opened whether closed or opened icon should be returned.
  */
 public static Image getTreeFolderIcon(boolean opened) {
   Image base =
       (Image)
           UIManager.get(opened ? OPENED_ICON_KEY_UIMANAGER_NB : ICON_KEY_UIMANAGER_NB); // #70263;
   if (base == null) {
     Icon baseIcon =
         UIManager.getIcon(opened ? OPENED_ICON_KEY_UIMANAGER : ICON_KEY_UIMANAGER); // #70263
     if (baseIcon != null) {
       base = ImageUtilities.icon2Image(baseIcon);
     } else {
       try {
         // fallback to our owns
         return opened
             ? DataObject.find(FileUtil.getConfigRoot())
                 .getNodeDelegate()
                 .getOpenedIcon(BeanInfo.ICON_COLOR_16x16)
             : DataObject.find(FileUtil.getConfigRoot())
                 .getNodeDelegate()
                 .getIcon(BeanInfo.ICON_COLOR_16x16);
       } catch (DataObjectNotFoundException ex) {
         Exceptions.printStackTrace(ex);
       }
     }
   }
   assert base != null;
   return base;
 }
  @BeforeClass
  public static void setUpClass() throws Exception {
    MockServices.setServices();
    DalvikPlatformManager.getDefault().setSdkLocation(SDK_DIR);
    tempFolder = File.createTempFile("junit", "");
    tempFolder.delete();
    tempFolder.mkdir();

    FileObject scratch = FileUtil.toFileObject(tempFolder);
    FileObject cacheDir = scratch.createFolder("cache");
    CacheFolder.setCacheFolder(cacheDir);
    FileObject sdkDirFo = FileUtil.toFileObject(new File(SDK_DIR));

    projdir = scratch.createFolder("Snake");
    FileUtilities.recursiveCopy(sdkDirFo.getFileObject("samples/android-8/Snake"), projdir);

    FileObject dir = projdir;
    for (String dirName : Splitter.on('/').split("gen/com/example/android/snake")) {
      dir = dir.createFolder(dirName);
    }
    OutputStream os = dir.createData("R.java").getOutputStream();
    FileUtil.copy(ProjectRefResolverTest.class.getResourceAsStream("Snake_R_java.txt"), os);
    os.close();

    pp = ProjectManager.getDefault().findProject(projdir);
  }
 private static void unZipFile(InputStream source, FileObject projectRoot, WizardDescriptor wiz)
     throws IOException {
   try {
     ZipInputStream str = new ZipInputStream(source);
     ZipEntry entry;
     while ((entry = str.getNextEntry()) != null) {
       if (entry.isDirectory()) {
         FileUtil.createFolder(projectRoot, entry.getName());
       } else {
         FileObject fo = FileUtil.createData(projectRoot, entry.getName());
         if ("nbproject/project.xml".equals(entry.getName())) {
           // Special handling for setting name of Ant-based projects; customize as needed:
           filterProjectXML(fo, str, projectRoot.getName());
         }
         // if build.xml has been found replace its content with provided values
         else if ("build.xml".equals(entry.getName())) {
           processBuildXML(fo, str, wiz);
         } else if ("nbproject/project.properties".equals(entry.getName())) {
           processProjectProperties(fo, str, wiz, projectRoot.getName());
         } else {
           writeFile(str, fo);
         }
       }
     }
   } finally {
     source.close();
   }
 }
예제 #6
0
파일: Installer.java 프로젝트: cismet/abf
 /**
  * DOCUMENT ME!
  *
  * @param libNodes DOCUMENT ME!
  * @return DOCUMENT ME!
  */
 private boolean performDeploy(final List<Node> libNodes) {
   final List<DeployInformation> infos = new LinkedList<DeployInformation>();
   final ModificationStore modStore = ModificationStore.getInstance();
   for (final Node libNode : libNodes) {
     for (final Node node : libNode.getChildren().getNodes(true)) {
       for (final Action a : node.getActions(false)) {
         // if this action is registered it node should be of type
         // LocalManagement or StarterManagement
         if (a instanceof DeployChangedJarsAction) {
           for (final Node ch : node.getChildren().getNodes()) {
             final DeployInformation info = DeployInformation.getDeployInformation(ch);
             final String path = FileUtil.toFile(info.getSourceDir()).getAbsolutePath();
             if (modStore.anyModifiedInContext(path, ModificationStore.MOD_CHANGED)) {
               infos.add(info);
             }
           }
           // continue with outer loop since only one action of
           // this type should be registered
           break;
         }
       }
     }
   }
   try {
     JarHandler.deployAllJars(infos, JarHandler.ANT_TARGET_DEPLOY_CHANGED_JARS);
     for (final DeployInformation info : infos) {
       final String path = FileUtil.toFile(info.getSourceDir()).getAbsolutePath();
       modStore.removeAllModificationsInContext(path, ModificationStore.MOD_CHANGED);
     }
     return true;
   } catch (final IOException ex) {
     LOG.warn("could not deploy changed jars", ex); // NOI18N
     return false;
   }
 }
  public void testPreferencesEvents() throws Exception {
    storage.toFolder(true);
    FileUtil.getConfigRoot().addRecursiveListener(new FileListener());
    pref.addNodeChangeListener(new NodeListener());

    String newPath = "a/b/c";
    String[] paths = newPath.split("/");
    FileObject fo = null;
    FileObject fo0 = null;
    for (int i = 0; i < paths.length; i++) {
      String path = paths[i];
      fo = FileUtil.createFolder((fo == null) ? FileUtil.getConfigRoot() : fo, path);
      if (i == 0) {
        fo0 = fo;
      }
      nodeAddedEvent.await();
      assertEquals("Missing node added event", 0, nodeAddedEvent.getCount());
      nodeAddedEvent = new CountDownLatch(1);

      Preferences pref2 = pref.node(fo.getPath());
      pref2.addNodeChangeListener(new NodeListener());
    }

    FileObject fo1 = FileUtil.createData(fo, "a.properties");
    nodeAddedEvent.await();
    assertEquals("Missing node added event", 0, nodeAddedEvent.getCount());

    nodeRemovedEvent = new CountDownLatch(paths.length + 1);
    fo0.delete();
    nodeRemovedEvent.await();
    assertEquals("Missing node removed event", 0, nodeRemovedEvent.getCount());
  }
 public void testGeneratedSources() throws Exception { // #187595
   TestFileUtils.writeFile(
       d,
       "pom.xml",
       "<project xmlns='http://maven.apache.org/POM/4.0.0'>"
           + "<modelVersion>4.0.0</modelVersion>"
           + "<groupId>grp</groupId>"
           + "<artifactId>art</artifactId>"
           + "<packaging>jar</packaging>"
           + "<version>0</version>"
           + "</project>");
   FileObject src = FileUtil.createFolder(d, "src/main/java");
   FileObject gsrc = FileUtil.createFolder(d, "target/generated-sources/xjc");
   gsrc.createData("Whatever.class");
   FileObject tsrc = FileUtil.createFolder(d, "src/test/java");
   FileObject gtsrc = FileUtil.createFolder(d, "target/generated-test-sources/jaxb");
   gtsrc.createData("Whatever.class");
   assertEquals(
       Arrays.asList(src, gsrc),
       Arrays.asList(
           SourceForBinaryQuery.findSourceRoots(new URL(d.toURL(), "target/classes/"))
               .getRoots()));
   assertEquals(
       Arrays.asList(tsrc, gtsrc),
       Arrays.asList(
           SourceForBinaryQuery.findSourceRoots(new URL(d.toURL(), "target/test-classes/"))
               .getRoots()));
 }
예제 #9
0
  public void savePreset(String name, Layout layout) {
    Preset preset = addPreset(new Preset(name, layout));

    try {
      // Create file if dont exist
      FileObject folder = FileUtil.getConfigFile("layoutpresets");
      if (folder == null) {
        folder = FileUtil.getConfigRoot().createFolder("layoutpresets");
      }
      FileObject presetFile = folder.getFileObject(name, "xml");
      if (presetFile == null) {
        presetFile = folder.createData(name, "xml");
      }

      // Create doc
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder documentBuilder = factory.newDocumentBuilder();
      final Document document = documentBuilder.newDocument();
      document.setXmlVersion("1.0");
      document.setXmlStandalone(true);

      // Write doc
      preset.writeXML(document);

      // Write XML file
      Source source = new DOMSource(document);
      Result result = new StreamResult(FileUtil.toFile(presetFile));
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      transformer.transform(source, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
예제 #10
0
  public void fileRenamed(FileRenameEvent fe) {
    FileObject fo = fe.getFile();
    if (FileUtil.isParentOf(root, fo) && fo.isFolder()) {
      String rp = FileUtil.getRelativePath(root, fo.getParent());
      String oldPath = rp + (rp.length() == 0 ? "" : "/") + fe.getName() + fe.getExt(); // NOI18N

      boolean visible = VisibilityQuery.getDefault().isVisible(fo);
      boolean doUpdate = false;

      // Find all entries which have to be updated
      ArrayList needsUpdate = new ArrayList();
      for (Iterator it = names2nodes.keySet().iterator(); it.hasNext(); ) {
        String p = (String) it.next();
        if (p.startsWith(oldPath)) {
          if (visible) {
            needsUpdate.add(p);
          } else {
            names2nodes.remove(p);
            doUpdate = true;
          }
        }
      }

      // If the node does not exists then there might have been update
      // from ignored to non ignored
      if (get(fo) == null && visible) {
        cleanEmptyKeys(fo);
        findNonExcludedPackages(fo);
        doUpdate = true; // force refresh
      }

      int oldPathLen = oldPath.length();
      String newPath = FileUtil.getRelativePath(root, fo);
      for (Iterator it = needsUpdate.iterator(); it.hasNext(); ) {
        String p = (String) it.next();
        StringBuffer np = new StringBuffer(p);
        np.replace(0, oldPathLen, newPath);
        PackageNode n = updatePath(p, np.toString()); // Replace entries in cache
        if (n != null) {
          n.updateDisplayName(); // Update nodes
        }
      }

      if (needsUpdate.size() > 1 || doUpdate) {
        // Sorting might change
        refreshKeys();
      }
    }
    /*
    else if ( FileUtil.isParentOf( root, fo ) && fo.isFolder() ) {
        FileObject parent = fo.getParent();
        PackageNode n = get( parent );
        if ( n != null && VisibilityQuery.getDefault().isVisible( parent ) ) {
            n.updateChildren();
        }

    }
    */

  }
예제 #11
0
  public static String getProjectName(final File root) {
    if (root == null || !root.isDirectory()) {
      return null;
    }
    final ProjectManager projectManager = ProjectManager.getDefault();
    FileObject rootFileObj = FileUtil.toFileObject(FileUtil.normalizeFile(root));
    // This can happen if the root is "ssh://<something>"
    if (rootFileObj == null || projectManager == null) {
      return null;
    }
    String res = null;
    if (projectManager.isProject(rootFileObj)) {
      try {
        Project prj = projectManager.findProject(rootFileObj);

        res = getProjectName(prj);
      } catch (Exception ex) {
        Git.LOG.log(
            Level.FINE,
            "getProjectName() file: {0} {1}",
            new Object[] {rootFileObj.getPath(), ex.toString()}); // NOI18N
      }
    }
    return res;
  }
예제 #12
0
 private void setRoots(Project[] projects) {
   Set<File> newRoots = new HashSet<File>();
   for (Project project : projects) {
     Sources sources = ProjectUtils.getSources(project);
     SourceGroup[] groups = sources.getSourceGroups(Sources.TYPE_GENERIC);
     for (SourceGroup group : groups) {
       FileObject fo = group.getRootFolder();
       File root = FileUtil.toFile(fo);
       if (root == null) {
         LOG.log(
             Level.WARNING, "source group{0} returned null root folder", group.getDisplayName());
       } else {
         addRootFile(newRoots, root);
       }
     }
     File root = FileUtil.toFile(project.getProjectDirectory());
     if (root == null) {
       LOG.log(
           Level.WARNING, "project {0} returned null root folder", project.getProjectDirectory());
     } else {
       addRootFile(newRoots, root);
     }
   }
   synchronized (roots) {
     roots.clear();
     roots.addAll(newRoots);
   }
   fireFileEvent(EVENT_PROJECTS_CHANGED, null);
 }
예제 #13
0
  private void writeResultsXml(GtaResult resultsObject) throws IOException {

    String newAnResFileName =
        FileUtil.findFreeFileName(
            resultsfolder,
            resultsfolder.getName() + "_" + modelReference.getFilename() + "_results",
            "xml");
    FileObject newAnResFile = resultsfolder.createData(newAnResFileName, "xml");
    resultsObject.setSummary(new Summary());
    resultsObject.getSummary().setFitModelCall(fitModelCall);
    // TODO resolve problem with multiple modelcalls
    resultsObject.getSummary().setInitModelCall(modelCalls.get(0));

    for (int i = 0; i < relationsList.size(); i++) {
      resultsObject.getDatasetRelations().add(new DatasetRelation());
      resultsObject
          .getDatasetRelations()
          .get(i)
          .setTo(String.valueOf((int) floor(relationsList.get(i)[0])));
      resultsObject
          .getDatasetRelations()
          .get(i)
          .setFrom(String.valueOf((int) floor(relationsList.get(i)[1])));
      // TODO do this in a different way
      // resultsObject.getDatasetRelations().get(i).getValues().add(relationsList.get(i)[2]);
      String cmd =
          timpcontroller.NAME_OF_RESULT_OBJECT
              + "$currTheta[["
              + (int) floor(relationsList.get(i)[0])
              + "]]@drel";
      resultsObject.getDatasetRelations().get(i).getValues().add(timpcontroller.getDouble(cmd));
    }

    createAnalysisResultsFile(resultsObject, FileUtil.toFile(newAnResFile));
  }
 private static void unZipFile(InputStream source, FileObject projectRoot) throws IOException {
   try {
     ZipInputStream str = new ZipInputStream(source);
     ZipEntry entry;
     while ((entry = str.getNextEntry()) != null) {
       if (entry.isDirectory()) {
         FileUtil.createFolder(projectRoot, entry.getName());
       } else {
         FileObject fo = FileUtil.createData(projectRoot, entry.getName());
         FileLock lock = fo.lock();
         try {
           OutputStream out = fo.getOutputStream(lock);
           try {
             FileUtil.copy(str, out);
           } finally {
             out.close();
           }
         } finally {
           lock.releaseLock();
         }
       }
     }
   } finally {
     source.close();
   }
 }
 private void createCatalogIfRequired(RetrieveEntry rent) {
   URI curURI = null;
   String addr = rent.getEffectiveAddress();
   try {
     // check if this is the first entry and the connection was redirected. If yes, then
     // store the URI as the original URI instead of the redirected URI
     String tempStr =
         URLResourceRetriever.resolveURL(rent.getBaseAddress(), rent.getCurrentAddress());
     if (!(new URI(tempStr).equals(new URI(addr)))) {
       addr = tempStr;
     }
   } catch (URISyntaxException ex) {
     // ignore
   }
   if (isSave2SingleFolder()) {
     if (!rent.getCurrentAddress().equals(rent.getEffectiveAddress()))
       addr = rent.getCurrentAddress();
   }
   try {
     curURI = new URI(addr);
   } catch (URISyntaxException ex) {
     // this is not supposed to happen. But if it does, then just return
     return;
   }
   FileObject fobj = null;
   try {
     fobj = FileUtil.toFileObject(FileUtil.normalizeFile(rent.getSaveFile()));
   } catch (Exception e) {
     return;
   }
   if (fobj == null) return;
   CatalogWriteModel dr = null;
   try {
     if (this.catalogFileObject == null) {
       Project project = FileOwnerQuery.getOwner(fobj);
       if (project == null) {
         // See issue #176769
         // In can happen if the file was saved outside of the project
         return;
       }
       dr = CatalogWriteModelFactory.getInstance().getCatalogWriteModelForProject(fobj);
     } else {
       dr =
           CatalogWriteModelFactory.getInstance()
               .getCatalogWriteModelForCatalogFile(this.catalogFileObject);
     }
   } catch (CatalogModelException ex) {
     // ignore this exception but return
     return;
   }
   // fobj = FileUtil.toFileObject(rent.getSaveFile());
   try {
     dr.addURI(curURI, fobj);
   } catch (Exception ex) {
     // ignore this exception but return
     ex = new Exception("Exception while writing in to catalog.", ex);
     handleException(rent, ex);
     return;
   }
 }
 public File getProjectsFolder(boolean create) {
   String result = getProperty(PROP_PROJECTS_FOLDER);
   if (result == null || !(new File(result)).exists()) {
     // property for overriding default projects dir location
     String userPrjDir = System.getProperty("netbeans.projects.dir"); // NOI18N
     if (userPrjDir != null) {
       File f = new File(userPrjDir);
       if (f.exists() && f.isDirectory()) {
         return FileUtil.normalizeFile(f);
       }
     }
     if (Boolean.getBoolean("netbeans.full.hack")) { // NOI18N
       return FileUtil.normalizeFile(new File(System.getProperty("java.io.tmpdir", ""))); // NOI18N
     }
     File defaultDir = FileSystemView.getFileSystemView().getDefaultDirectory();
     if (defaultDir != null && defaultDir.exists() && defaultDir.isDirectory()) {
       String nbPrjDirName =
           NbBundle.getMessage(OpenProjectListSettings.class, "DIR_NetBeansProjects");
       File nbPrjDir = new File(defaultDir, nbPrjDirName);
       if (nbPrjDir.exists() && nbPrjDir.canWrite()) {
         return nbPrjDir;
       } else {
         boolean created = create && nbPrjDir.mkdir();
         if (created) {
           // #75960 - using Preferences to temporarily save created projects folder path,
           // folder will be deleted after wizard is finished if nothing was created in it
           getPreferences().put(PROP_CREATED_PROJECTS_FOLDER, nbPrjDir.getAbsolutePath());
           return nbPrjDir;
         }
       }
     }
     result = System.getProperty("user.home"); // NOI18N
   }
   return FileUtil.normalizeFile(new File(result));
 }
예제 #17
0
  @Override
  @SuppressWarnings("unchecked")
  public TopComponent getTopComponent() {
    // Loading the multiview windows:
    FileObject multiviewsFolder = FileUtil.getConfigFile("skitmultiviews");
    FileObject[] kids = multiviewsFolder.getChildren();
    MultiViewDescription[] descriptionArray = new MultiViewDescription[kids.length];
    ArrayList<MultiViewDescription> listOfDescs = new ArrayList<MultiViewDescription>();

    for (FileObject kid : FileUtil.getOrder(Arrays.asList(kids), true)) {
      MultiViewDescription attribute = (MultiViewDescription) kid.getAttribute("multiview");

      if (attribute instanceof ContextAwareInstance) {
        Lookup lu = Lookups.fixed(this);
        attribute =
            ((ContextAwareInstance<MultiViewDescription>) attribute).createContextAwareInstance(lu);
      }

      listOfDescs.add(attribute);
    }

    for (int i = 0; i < listOfDescs.size(); i++) {
      descriptionArray[i] = listOfDescs.get(i);
    }

    CloneableTopComponent ctc =
        MultiViewFactory.createCloneableMultiView(descriptionArray, descriptionArray[0]);

    return ctc;
  }
  public Set /*<FileObject>*/ instantiate(/*ProgressHandle handle*/ ) throws IOException {
    Set<FileObject> resultSet = new LinkedHashSet<FileObject>();
    File dirF = FileUtil.normalizeFile((File) wiz.getProperty("projdir"));
    dirF.mkdirs();

    FileObject template = Templates.getTemplate(wiz);
    FileObject dir = FileUtil.toFileObject(dirF);
    unZipFile(template.getInputStream(), dir);

    // Always open top dir as a project:
    resultSet.add(dir);
    // Look for nested projects to open as well:
    Enumeration<? extends FileObject> e = dir.getFolders(true);
    while (e.hasMoreElements()) {
      FileObject subfolder = e.nextElement();
      if (ProjectManager.getDefault().isProject(subfolder)) {
        resultSet.add(subfolder);
      }
    }

    File parent = dirF.getParentFile();
    if (parent != null && parent.exists()) {
      ProjectChooser.setProjectsFolder(parent);
    }

    return resultSet;
  }
예제 #19
0
  protected @Override void setUp() throws Exception {
    MockLookup.setLayersAndInstances(TestUtil.testProjectFactory());
    ProjectManager.getDefault().reset();
    FileOwnerQuery.reset();
    scratch = TestUtil.makeScratchDir(this);
    projdir = scratch.createFolder("my-project");
    projdir.createFolder("testproject");
    randomfile = scratch.createData("randomfile");
    projfile = projdir.createData("projfile");
    FileObject projsubdir = projdir.createFolder("projsubdir");
    projfile2 = projsubdir.createData("projfile2");
    subprojdir = projdir.createFolder("subproject");
    subprojdir.createFolder("testproject");
    subprojfile = subprojdir.createData("subprojfile");
    scratch.createFolder("external1").createFolder("subdir").createData("file");
    scratch.createFolder("external2").createFolder("subdir").createData("file");
    scratch.createFolder("external3").createFolder("subproject").createFolder("testproject");
    p = ProjectManager.getDefault().findProject(projdir);
    assertNotNull("found a project successfully", p);

    // make jar:file:/.../projdir/foo.jar!/zipfile/zippedfile
    FileObject foojar = TestFileUtils.writeZipFile(projdir, "foo.jar", "zipdir/zippedfile:");
    FileObject foojarRoot = FileUtil.getArchiveRoot(foojar);
    assertNotNull("have an archive in " + foojar, foojarRoot);
    zippedfile = foojarRoot.getFileObject("zipdir/zippedfile");
    assertNotNull("zippedfile found in it", zippedfile);

    hashedFile = TestFileUtils.writeZipFile(projdir, ".#webapp.jar.1.45", "zipdir/zippedfile:");
    foojarRoot = FileUtil.getArchiveRoot(hashedFile);
    assertNotNull("have an archive in " + hashedFile, foojarRoot);
    hashedFile = foojarRoot.getFileObject("zipdir/zippedfile");
  }
  /**
   * Simulates deadlock issue 133616 - create MultiFileSystem - create lookup to set our
   * MultiFileSystem and system filesystem - create handler to manage threads - put test FileObject
   * to 'potentialLock' set - call hasLocks - it call LocalFileSystemEx.getInvalid which ends in our
   * DeadlockHandler - it starts lockingThread which calls FileObject.lock which locks our
   * FileObject - when we in LocalFileSystemEx.lock, we notify main thread which continues in
   * getInvalid and tries to accuire lock on FileObject and it dead locks
   */
  public void testLocalFileSystemEx133616() throws Exception {
    System.setProperty("workdir", getWorkDirPath());
    clearWorkDir();

    FileSystem lfs =
        TestUtilHid.createLocalFileSystem("mfs1" + getName(), new String[] {"/fold/file1"});
    LocalFileSystemEx exfs = new LocalFileSystemEx();
    exfs.setRootDirectory(FileUtil.toFile(lfs.getRoot()));
    FileSystem xfs = TestUtilHid.createXMLFileSystem(getName(), new String[] {});
    FileSystem mfs = new MultiFileSystem(exfs, xfs);
    testedFS = mfs;
    System.setProperty(
        "org.openide.util.Lookup", LocalFileSystemEx133616Test.class.getName() + "$Lkp");
    Lookup l = Lookup.getDefault();
    if (!(l instanceof Lkp)) {
      fail("Wrong lookup: " + l);
    }

    final FileObject file1FO = mfs.findResource("/fold/file1");
    File file1File = FileUtil.toFile(file1FO);

    Logger.getLogger(LocalFileSystemEx.class.getName()).setLevel(Level.FINEST);
    Logger.getLogger(LocalFileSystemEx.class.getName()).addHandler(new DeadlockHandler(file1FO));
    LocalFileSystemEx.potentialLock(file1FO.getPath());
    LocalFileSystemEx.hasLocks();
  }
예제 #21
0
  /**
   * See issue #57773 for details. Toolbar should be updated with possible changes after module
   * install/uninstall
   */
  private void installModulesInstallationListener() {
    moduleRegListener =
        new FileChangeAdapter() {
          public @Override void fileChanged(FileEvent fe) {
            // some module installed/uninstalled. Refresh toolbar content
            Runnable r =
                new Runnable() {
                  public void run() {
                    if (isToolbarVisible()) {
                      checkPresentersRemoved();
                      checkPresentersAdded();
                    }
                  }
                };
            Utilities.runInEventDispatchThread(r);
          }
        };

    FileObject moduleRegistry = FileUtil.getConfigFile("Modules"); // NOI18N

    if (moduleRegistry != null) {
      moduleRegistry.addFileChangeListener(
          FileUtil.weakFileChangeListener(moduleRegListener, moduleRegistry));
    }
  }
예제 #22
0
  private List<String> getCommandArguments() {
    List<String> args = new ArrayList<>();

    if (outputDirectory != null) {
      args.add("-o");
      args.add(FileUtil.toFile(outputDirectory).getAbsolutePath());
    }

    // Where do we want ANTLR to look for .tokens and import grammars?
    if (libDirectory != null && libDirectory.isFolder()) {
      args.add("-lib");
      args.add(FileUtil.toFile(libDirectory).getAbsolutePath());
    }

    if (atn) {
      args.add("-atn");
    }

    if (encoding != null && !encoding.isEmpty()) {
      args.add("-encoding");
      args.add(encoding);
    }

    if (listener) {
      args.add("-listener");
    } else {
      args.add("-no-listener");
    }

    if (visitor) {
      args.add("-visitor");
    } else {
      args.add("-no-visitor");
    }

    if (treatWarningsAsErrors) {
      args.add("-Werror");
    }

    if (forceATN) {
      args.add("-Xforce-atn");
    }

    if (targetArgument != null) {
      args.add("-Dlanguage=" + targetArgument);
    }

    if (options != null) {
      for (Map.Entry<String, String> option : options.entrySet()) {
        args.add(String.format("-D%s=%s", option.getKey(), option.getValue()));
      }
    }

    if (arguments != null) {
      args.addAll(arguments);
    }

    return args;
  }
  @Override
  public Set instantiate(ProgressHandle handle) throws IOException {
    handle.start(2);
    handle.progress(
        NbBundle.getMessage(
            JavaEESamplesWizardIterator.class,
            "LBL_NewSampleProjectWizardIterator_WizardProgress_CreatingProject"),
        1);

    Set resultSet = new LinkedHashSet();
    File dirF = FileUtil.normalizeFile((File) wiz.getProperty(WizardProperties.PROJ_DIR));
    String name = (String) wiz.getProperty(WizardProperties.NAME);
    FileObject template = Templates.getTemplate(wiz);

    FileObject dir = null;
    if ("web".equals(template.getAttribute("prjType"))) {
      // Use generator from web.examples to create project with specified name
      dir = WebSampleProjectGenerator.createProjectFromTemplate(template, dirF, name);
    } else {
      // Unzip prepared project only (no way to change name of the project)
      // FIXME: should be modified to create projects with specified name (project.xml files in
      // sub-projects should be modified too)
      // FIXME: web.examples and j2ee.samples modules may be merged into one module
      createFolder(dirF);
      dir = FileUtil.toFileObject(dirF);
      unZipFile(template.getInputStream(), dir);
      WebSampleProjectGenerator.configureServer(dir);
      for (FileObject child : dir.getChildren()) {
        WebSampleProjectGenerator.configureServer(child);
      }
    }

    ProjectManager.getDefault().clearNonProjectCache();
    handle.progress(
        NbBundle.getMessage(
            JavaEESamplesWizardIterator.class,
            "LBL_NewSampleProjectWizardIterator_WizardProgress_PreparingToOpen"),
        2);

    // Always open top dir as a project:
    resultSet.add(dir);
    // Look for nested projects to open as well:
    Enumeration e = dir.getFolders(true);
    while (e.hasMoreElements()) {
      FileObject subfolder = (FileObject) e.nextElement();
      if (ProjectManager.getDefault().isProject(subfolder)) {
        resultSet.add(subfolder);
      }
    }

    File parent = dirF.getParentFile();
    if (parent != null && parent.exists()) {
      ProjectChooser.setProjectsFolder(parent);
    }

    handle.finish();
    return resultSet;
  }
  boolean valid(WizardDescriptor wizardDescriptor) {

    String projDirName = projectLocationTextField.getText();
    String projName = projectNameTextField.getText();

    if (projDirName == null || projDirName.isEmpty()) {
      // TODO if using org.openide.dialogs >= 7.8, can use WizardDescriptor.PROP_ERROR_MESSAGE:
      wizardDescriptor.putProperty(
          WizardDescriptor.PROP_ERROR_MESSAGE,
          NbBundle.getMessage(
              NameAndLocationWizardPanelVisual.class,
              "PlatypusApplicationPanelVisual.badProjectLocation"));
      return false; // Display name not specified
    }
    if (projName == null || projName.isEmpty()) {
      // TODO if using org.openide.dialogs >= 7.8, can use WizardDescriptor.PROP_ERROR_MESSAGE:
      wizardDescriptor.putProperty(
          WizardDescriptor.PROP_ERROR_MESSAGE,
          NbBundle.getMessage(
              NameAndLocationWizardPanelVisual.class,
              "PlatypusApplicationPanelVisual.badProjectName"));
      return false; // Display name not specified
    }
    File projDir = FileUtil.normalizeFile(new File(projDirName).getAbsoluteFile());
    if (!projDir.isDirectory()) {
      String message =
          NbBundle.getMessage(
              NameAndLocationWizardPanelVisual.class,
              "PlatypusApplicationPanelVisual.badProjectLocation");
      wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, message);
      return false;
    }
    String consideredFileName = projDir.getAbsolutePath() + File.separator + projName;
    if (projDir != null && projName != null) {
      createdFileTextField.setText(consideredFileName);
    }
    final File destFolder = FileUtil.normalizeFile(new File(consideredFileName).getAbsoluteFile());
    if (destFolder.exists()) {
      wizardDescriptor.putProperty(
          WizardDescriptor.PROP_ERROR_MESSAGE,
          NbBundle.getMessage(
              NameAndLocationWizardPanelVisual.class,
              "PlatypusApplicationPanelVisual.projectFileAlreadyExists"));
      return false;
    }
    String projTitle = projectTiteTextField.getText();
    if (projTitle == null || projTitle.isEmpty()) {
      wizardDescriptor.putProperty(
          WizardDescriptor.PROP_ERROR_MESSAGE,
          NbBundle.getMessage(
              NameAndLocationWizardPanelVisual.class,
              "PlatypusApplicationPanelVisual.projectTitleMissing"));
      return false;
    }
    wizardDescriptor.putProperty(WizardDescriptor.PROP_ERROR_MESSAGE, "");
    return true;
  }
예제 #25
0
  /** 对所有有改动的文件,做编译单元的查询 */
  @Override
  public CompilationUnit findCompilationUnit(String basePath, String objectFile) {
    List<String> diffFiles = Lists.newArrayList();
    for (ASTFileLocation fileLocation : fileLocations) {
      if (!new File(fileLocation.getFilename()).exists()) continue;
      diffFiles.add(fileLocation.getFilename());
    }

    String sourceFile = objectFileParser.lookForSourceFile(objectFile, basePath);
    if (sourceFile == null) {
      logger.error(
          String.format(
              "Can not parse source file from [%s], " + "you should compile it with \"-g\" option",
              objectFile));
      return null;
    }

    if (isIgnoreByPattern(new File(sourceFile))) return null;
    if (!diffFiles.contains(sourceFile.toString())) return null;

    String gcdaFile = objectFileParser.lookForGcdaPath(objectFile, basePath);
    if (gcdaFile == null) {
      logger.warn(
          String.format(
              "Can not parse data file from [%s], "
                  + "you should compile it with \"-ftest-coverage -fprofile-arcs\" options",
              objectFile));
      zeroFiles.add(sourceFile);
      return null;
    }

    // TODO 2012-01-09 Wu Liang 如果某一个文件一行代码都没有被覆盖到,则数据文件将不会被生成
    if (!new File(gcdaFile).exists()) {
      logger.warn(String.format("[%s] does not exist, becasuse not be coveraged", gcdaFile));
      zeroFiles.add(sourceFile);
      return null;
    }

    // TODO 2011-12-07 Wu Liang 如果有文件类似X.gcda.gcda的话,这块会有问题
    File gcnoFile = new File(gcdaFile.toString().replace(".gcda", ".gcno"));
    if (!gcnoFile.exists()) {
      logger.warn(
          String.format(
              "Can not parse data file from [%s], "
                  + "you should compile it with \"-ftest-coverage -fprofile-arcs\" options",
              objectFile));
      zeroFiles.add(sourceFile);
      return null;
    }

    CompilationUnit compilationUnit = new CompilationUnit();
    compilationUnit.setObjectFile(FileUtil.normalizePath(objectFile));
    compilationUnit.setSourceFile(FileUtil.normalizePath(sourceFile));
    compilationUnit.setGcdaFile(FileUtil.normalizePath(gcdaFile));
    return compilationUnit;
  }
예제 #26
0
 protected FileBase(final File file, final String pkgName, final String name) {
   super(pkgName, name);
   assert file != null;
   assert file.equals(FileUtil.normalizeFile(file))
       : "File: "
           + file.getAbsolutePath()
           + " Normalized File: "
           + FileUtil.normalizeFile(file).getAbsolutePath(); // NOI18N
   this.f = file;
 }
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    MockServices.setServices(DL.class);

    fo = FileUtil.createData(FileUtil.createMemoryFileSystem().getRoot(), "data.dat");
    obj = DataObject.find(fo);
    assertEquals("MDO: " + obj, MDO.class, obj.getClass());
    node = obj.getNodeDelegate();
  }
  private FileObject getArchivedFile(FileObject fileObject) {
    // ZIP and JAR archives
    if (FileUtil.isArchiveFile(fileObject)) {
      try {
        fileObject = FileUtil.getArchiveRoot(fileObject).getChildren()[0];
      } catch (Exception e) {
        throw new RuntimeException(
            "The archive can't be opened, be sure it has no password and contains a single file, without folders");
      }
    } else { // GZ or BZIP2 archives
      boolean isGz = fileObject.getExt().equalsIgnoreCase("gz");
      boolean isBzip = fileObject.getExt().equalsIgnoreCase("bz2");
      if (isGz || isBzip) {
        try {
          String[] splittedFileName = fileObject.getName().split("\\.");
          if (splittedFileName.length < 2) {
            return fileObject;
          }

          String fileExt1 = splittedFileName[splittedFileName.length - 1];
          String fileExt2 = splittedFileName[splittedFileName.length - 2];

          File tempFile = null;
          if (fileExt1.equalsIgnoreCase("tar")) {
            String fname = fileObject.getName().replaceAll("\\.tar$", "");
            fname = fname.replace(fileExt2, "");
            tempFile = File.createTempFile(fname, "." + fileExt2);
            // Untar & unzip
            if (isGz) {
              tempFile = getGzFile(fileObject, tempFile, true);
            } else {
              tempFile = getBzipFile(fileObject, tempFile, true);
            }
          } else {
            String fname = fileObject.getName();
            fname = fname.replace(fileExt1, "");
            tempFile = File.createTempFile(fname, "." + fileExt1);
            // Unzip
            if (isGz) {
              tempFile = getGzFile(fileObject, tempFile, false);
            } else {
              tempFile = getBzipFile(fileObject, tempFile, false);
            }
          }
          tempFile.deleteOnExit();
          tempFile = FileUtil.normalizeFile(tempFile);
          fileObject = FileUtil.toFileObject(tempFile);
        } catch (IOException ex) {
          Exceptions.printStackTrace(ex);
        }
      }
    }
    return fileObject;
  }
 public FuelPhpIgnoredFilesExtender(PhpModule pm) {
   assert pm != null;
   docs = new File(FileUtil.toFile(pm.getProjectDirectory()), "docs"); // NOI18N
   // add settings whether MVC direcotries is ignored
   if (FuelPhpPreferences.ignoreMVCNode(pm)) {
     controller = FileUtil.toFile(FuelUtils.getControllerDirectory(pm));
     model = FileUtil.toFile(FuelUtils.getModelDirectory(pm));
     views = FileUtil.toFile(FuelUtils.getViewsDirectory(pm));
     modules = FileUtil.toFile(FuelUtils.getModulesDirectory(pm));
   }
 }
  boolean valid(WizardDescriptor wizardDescriptor) {

    if (projectNameTextField.getText().length() == 0) {
      wizardDescriptor.putProperty(
          WIZARD_PANEL_ERROR_MESSAGE,
          org.openide.util.NbBundle.getMessage(
              SampleAppPanelVisual.class, "SampleAppPanelVisual.invalid_folder_name"));
      return false; // Display name not specified
    }
    File f = FileUtil.normalizeFile(new File(projectLocationTextField.getText()).getAbsoluteFile());
    if (!f.isDirectory()) {
      String message =
          org.openide.util.NbBundle.getMessage(
              SampleAppPanelVisual.class, "SampleAppPanelVisual.invalid_path");
      wizardDescriptor.putProperty(WIZARD_PANEL_ERROR_MESSAGE, message);
      return false;
    }
    final File destFolder =
        FileUtil.normalizeFile(new File(createdFolderTextField.getText()).getAbsoluteFile());

    File projLoc = destFolder;
    while (projLoc != null && !projLoc.exists()) {
      projLoc = projLoc.getParentFile();
    }
    if (projLoc == null || !projLoc.canWrite()) {
      wizardDescriptor.putProperty(
          WIZARD_PANEL_ERROR_MESSAGE,
          org.openide.util.NbBundle.getMessage(
              SampleAppPanelVisual.class, "SampleAppPanelVisual.folder_creation_error"));
      return false;
    }

    if (FileUtil.toFileObject(projLoc) == null) {
      String message =
          org.openide.util.NbBundle.getMessage(
              SampleAppPanelVisual.class, "SampleAppPanelVisual.invalid_path");
      wizardDescriptor.putProperty(WIZARD_PANEL_ERROR_MESSAGE, message);
      return false;
    }

    File[] kids = destFolder.listFiles();
    if (destFolder.exists() && kids != null && kids.length > 0) {
      // Folder exists and is not empty
      wizardDescriptor.putProperty(
          WIZARD_PANEL_ERROR_MESSAGE,
          org.openide.util.NbBundle.getMessage(
              SampleAppPanelVisual.class, "SampleAppPanelVisual.folder_exists"));
      return false;
    }
    wizardDescriptor.putProperty(WIZARD_PANEL_ERROR_MESSAGE, "");
    return true;
  }