コード例 #1
0
 @Override
 public final boolean accept(FileObject file) {
   // the ProjectSharabilityQuery filters out nbproject/private,
   // but we need it for remote build
   if (file.getNameExt().equals("private")) { // NOI18N
     FileObject parent = file.getParent();
     if (parent != null && parent.getNameExt().equals("nbproject")) { // NOI18N
       return true;
     }
   }
   Sharability sharability = SharabilityQuery.getSharability(file);
   if (TRACE_SHARABILITY) {
     RemoteUtil.LOGGER.log(
         Level.INFO,
         "{0} sharability is {1}",
         new Object[] {file.getPath(), sharabilityToString(sharability)});
   }
   switch (sharability) {
     case NOT_SHARABLE:
       return false;
     case MIXED:
     case SHARABLE:
     case UNKNOWN:
       return true;
     default:
       CndUtils.assertTrueInConsole(
           false, "Unexpected sharability value: " + sharability); // NOI18N
       return true;
   }
 }
コード例 #2
0
ファイル: AnalysisWorker.java プロジェクト: rforge/timpgui
  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));
  }
コード例 #3
0
  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;
  }
コード例 #4
0
  /* (non-Javadoc)
   * @see org.openide.util.actions.NodeAction#performAction(org.openide.nodes.Node[])
   */
  @Override
  protected void performAction(Node[] nodes) {
    // context.

    if (null != nodes) {
      for (Node currentnode : nodes) {
        DataObject dObj = currentnode.getLookup().lookup(DataObject.class);
        // Project pRoot = currentnode.getLookup().lookup(Project.class);
        Project pRoot = Te2mWizardBase.findProjectThatOwnsNode(currentnode);
        if (null != dObj) {
          determineSelectedClass(dObj);
          FileObject fo = dObj.getPrimaryFile();

          JavaSource jsource = JavaSource.forFileObject(fo);

          if (jsource == null) {
            StatusDisplayer.getDefault().setStatusText("Not a Java file: " + fo.getPath());
          } else {
            StatusDisplayer.getDefault().setStatusText("Hurray! A Java file: " + fo.getPath());

            executeWizard(currentnode);
          }
        }
      }
    }
  }
コード例 #5
0
 @Override
 public String findMIMEType(FileObject fo) {
   if (fo.getExt().equals("coffee") || fo.getNameExt().equals("Cakefile")) {
     return CoffeeScriptLanguage.MIME_TYPE;
   }
   return null;
 }
コード例 #6
0
 private void processFaceletsLibraryDescriptors(
     Iterable<? extends FileObject> files, Context context) {
   if (files == null) {
     return;
   }
   for (FileObject file : findLibraryDescriptors(files, JsfIndexSupport.FACELETS_LIB_SUFFIX)) {
     // no special mimetype for facelet library descriptor AFAIK
     if (file.getNameExt().endsWith(JsfIndexSupport.FACELETS_LIB_SUFFIX)) {
       try {
         String namespace = FaceletsLibraryDescriptor.parseNamespace(file.getInputStream());
         if (namespace != null) {
           JsfIndexSupport.indexFaceletsLibraryDescriptor(context, file, namespace);
           LOGGER.log(
               Level.FINE,
               "The file {0} indexed as a Facelets Library Descriptor",
               file); // NOI18N
         }
       } catch (IOException ex) {
         LOGGER.info(
             String.format(
                 "Error parsing %s file: %s", file.getPath(), ex.getMessage())); // NOI18N
       }
     }
   }
 }
コード例 #7
0
  @Override
  public void initialize(WizardDescriptor wiz) {
    this.wiz = wiz;
    index = 0;
    panels = createPanels();
    // Make sure list of steps is accurate.
    String[] steps = createSteps();
    for (int i = 0; i < panels.length; i++) {
      Component c = panels[i].getComponent();
      if (steps[i] == null) {
        // Default step name to component name of panel.
        // Mainly useful for getting the name of the target
        // chooser to appear in the list of steps.
        steps[i] = c.getName();
      }
      if (c instanceof JComponent) { // assume Swing components
        JComponent jc = (JComponent) c;
        // Step #.
        jc.putClientProperty(WizardProperties.SELECTED_INDEX, new Integer(i));
        // Step name (actually the whole list for reference).
        jc.putClientProperty(WizardProperties.CONTENT_DATA, steps);
      }
    }

    FileObject template = Templates.getTemplate(wiz);

    wiz.putProperty(WizardProperties.NAME, template.getName());
  }
コード例 #8
0
  /**
   * Add element starting with filter value to list.
   *
   * @param fo FileObject for adding
   * @param filter filtering with this value
   * @param elements List for adding (add to this)
   * @param pluginName plugin name if target is not plugin, set the null
   * @return true if add, otherwise false
   */
  protected boolean addElement(
      FileObject fo, String filter, List<String> elements, String pluginName) {
    String name = getFileName(fo);
    // set subdirectory path
    if (!subDirectoryPath.isEmpty()) {
      name = subDirectoryPath + SLASH + name; // NOI18N
    }

    // is root
    if (filter.startsWith(SLASH)) {
      name = SLASH + name;
      filter = filter.replaceFirst(SLASH, ""); // NOI18N
    }

    // filtering
    String fileName = getFileName(fo);
    if (fileName.startsWith(filter)) {
      if (!fo.isFolder() && extFilter != null && !extFilter.contains(fo.getExt())) {
        return false;
      }
      if (fo.isFolder() || !fo.getExt().isEmpty()) {
        if (fo.isFolder()) {
          name = name + SLASH;
        }
        if (pluginName != null && !pluginName.isEmpty()) {
          name = pluginName + DOT + name;
        }
        elements.add(name);
        return true;
      }
    }
    return false;
  }
コード例 #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
  /**
   * This method returns the ImageFile associated with this data object. This saves other classes
   * from having to parse this information and keeps the implementation localized to this method.
   *
   * @return the ImageFile instance contained within the ImageFileDataObject
   */
  public ImageFile getImageFile() {
    // a template that's a completely empty file doesn't seem to work correctly;
    // the name in the wizard is blank. Having at least one character in the file
    // appears to work around this, so my template contains the word 'EMPTY'

    // default to a new empty ImageFile instance, since that will occur when a new one is
    // created from the "empty" template.  OTOH, it might also mean the file was corrupt.
    if (ImageFile == null) {
      try {
        FileObject ImageFileFileObj = getPrimaryFile();
        if (ImageFileFileObj != null && ImageFileFileObj.getSize() > 15) {
          ObjectInputStream ois = new ObjectInputStream(ImageFileFileObj.getInputStream());
          ImageFile = (ImageFile) ois.readObject();
        } else {
          ImageFile = new ImageFile();
        }
      } catch (IOException ioe) {
        // TODO : better error handling needed here
        System.err.println("Could not load ImageFile instance: " + ioe);
      } catch (ClassNotFoundException cnfe) {
        System.err.println("Could not load ImageFile instance: " + cnfe);
      }
    }

    return ImageFile;
  }
コード例 #11
0
ファイル: IcanproViews.java プロジェクト: bflavius/nb-soa
    private void createNodes() {
      List l = new ArrayList();
      /*
      l.add(KEY_EJBS);
      */

      DataFolder docBaseDir = getFolder(IcanproProjectProperties.META_INF);
      if (docBaseDir != null) {
        /*
        l.add(KEY_DOC_BASE);
         */
      }

      DataFolder srcDir = getFolder(IcanproProjectProperties.SRC_DIR);
      if (srcDir != null) {
        l.add(KEY_SOURCE_DIR);
      }

      FileObject setupFolder = getSetupFolder();
      if (setupFolder != null && setupFolder.isFolder()) {
        l.add(KEY_SETUP_DIR);
      }
      /*
                  l.add(WEBSERVICES_DIR);
      */
      setKeys(l);
    }
コード例 #12
0
ファイル: CasaHelper.java プロジェクト: bflavius/nb-soa
  /**
   * Get the set of Java Projects
   *
   * @param project the compapp project
   * @param extensionNamespace
   * @param elementName
   * @param attributeName
   * @return the set of Java Projects
   */
  private static Set<String> collectCasaPortExtensionAttributes(
      JbiProject project, String extensionNamespace, String elementName, String attributeName) {

    Set<String> ret = new HashSet<String>();

    FileObject casaFO = CasaHelper.getCasaFileObject(project, true);
    if (casaFO == null) {
      return ret;
    }

    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setNamespaceAware(true);
      factory.setValidating(false);
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document casaDocument = builder.parse(casaFO.getInputStream());

      NodeList casaPorts = casaDocument.getElementsByTagName(CASA_PORT_ELEM_NAME);

      for (int i = 0; i < casaPorts.getLength(); i++) {
        Element casaPort = (Element) casaPorts.item(i);

        NodeList extElements = casaPort.getElementsByTagNameNS(extensionNamespace, elementName);
        for (int j = 0; j < extElements.getLength(); j++) {
          Element extElement = (Element) extElements.item(j);
          String attributeValue = extElement.getAttribute(attributeName);
          ret.add(attributeValue);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return ret;
  }
コード例 #13
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)));
 }
コード例 #14
0
  /**
   * Test of validateDirectory method, of class YiiCustomizerValidator.
   *
   * @throws java.io.IOException
   */
  @Test
  public void testValidateDirectory() throws IOException {
    FileSystem fileSystem = FileUtil.createMemoryFileSystem();
    FileObject sourceDirectory = fileSystem.getRoot();
    sourceDirectory.createFolder("myfolder");
    sourceDirectory.createData("test.php");

    // existing directory
    YiiCustomizerValidator validator =
        new YiiCustomizerValidator().validateDirectory(sourceDirectory, "myfolder");
    ValidationResult result = validator.getResult();
    assertFalse(result.hasErrors());
    assertFalse(result.hasWarnings());

    // not existing directory
    validator = new YiiCustomizerValidator().validateDirectory(sourceDirectory, "dummy");
    result = validator.getResult();
    assertFalse(result.hasErrors());
    assertTrue(result.hasWarnings());

    // file
    validator = new YiiCustomizerValidator().validateDirectory(sourceDirectory, "test.php");
    result = validator.getResult();
    assertFalse(result.hasErrors());
    assertTrue(result.hasWarnings());
  }
コード例 #15
0
  public List<? extends Task> scan(FileObject fo) {
    List<Task> violations = new ArrayList<Task>();

    if (!fo.hasExt("php") && !fo.hasExt("php5") && !fo.hasExt("phtml")) {
      return violations;
    }

    if (codeSnifferBinary.exists() == true) {
      CodeSnifferXmlLogResult rs = getCodeSniffer().execute(fo);

      for (int i = 0; i < rs.getCsErrors().size(); i++) {
        violations.add(
            Task.create(
                fo,
                "error",
                rs.getCsErrors().get(i).getShortDescription(),
                rs.getCsErrors().get(i).getLineNum() + 1));
      }
      for (int i = 0; i < rs.getCsWarnings().size(); i++) {
        violations.add(
            Task.create(
                fo,
                "warning",
                rs.getCsWarnings().get(i).getShortDescription(),
                rs.getCsWarnings().get(i).getLineNum() + 1));
      }
    }

    return violations;
  }
コード例 #16
0
 // XXX lock any loaded XML files while the project is modified, to prevent manual editing,
 // and reload any modified files if the project is unmodified
 private MakeProjectHelperImpl(
     FileObject dir, Document projectXml, ProjectState state, MakeProjectTypeImpl type) {
   this.dir = dir;
   try {
     this.fileSystem = dir.getFileSystem();
   } catch (FileStateInvalidException ex) {
     throw new IllegalStateException(ex);
   }
   this.state = state;
   assert state != null;
   this.type = type;
   assert type != null;
   this.projectXml = projectXml;
   projectXmlValid = true;
   assert projectXml != null;
   fileListener = new FileListener();
   FileObject resolveFileObject = resolveFileObject(PROJECT_XML_PATH);
   if (resolveFileObject != null) {
     resolveFileObject.addFileChangeListener(fileListener);
   } else {
     FileSystemProvider.addFileChangeListener(fileListener, fileSystem, PROJECT_XML_PATH);
   }
   resolveFileObject = resolveFileObject(PRIVATE_XML_PATH);
   if (resolveFileObject != null) {
     resolveFileObject.addFileChangeListener(fileListener);
   } else {
     FileSystemProvider.addFileChangeListener(fileListener, fileSystem, PRIVATE_XML_PATH);
   }
 }
コード例 #17
0
  /**
   * 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();
  }
コード例 #18
0
 private void change(FileEvent fe) {
   synchronized (saveActions) {
     for (AtomicAction a : saveActions) {
       if (fe.firedFrom(a)) {
         return;
       }
     }
   }
   String path;
   FileObject f = fe.getFile();
   synchronized (modifiedMetadataPaths) {
     if (f.equals(resolveFileObject(PROJECT_XML_PATH))) {
       if (modifiedMetadataPaths.contains(PROJECT_XML_PATH)) {
         // #68872: don't do anything if the given file has non-saved changes:
         return;
       }
       path = PROJECT_XML_PATH;
       projectXmlValid = false;
     } else if (f.equals(resolveFileObject(PRIVATE_XML_PATH))) {
       if (modifiedMetadataPaths.contains(PRIVATE_XML_PATH)) {
         // #68872: don't do anything if the given file has non-saved changes:
         return;
       }
       path = PRIVATE_XML_PATH;
       privateXmlValid = false;
     } else {
       LOG.log(
           Level.WARNING,
           "#184132: unexpected file change in {0}; possibly deleted project?",
           f);
       return;
     }
   }
   fireExternalChange(path);
 }
コード例 #19
0
ファイル: Skit.java プロジェクト: claurendine/Nerduino-host
  @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;
  }
コード例 #20
0
  /**
   * Perform special enablement check in addition to the normal one.
   *
   * <p>protected boolean enable (Node[] nodes) { if (!super.enable(nodes)) { return false; } }
   *
   * <p>if (...) { ... }
   */
  @Override
  protected boolean enable(Node[] nodes) {
    if (nodes.length == 0) {
      return false;
    }

    for (Node node : nodes) {
      DataObject dataObj = node.getCookie(DataObject.class);
      if (dataObj != null) {
        FileObject fileObj = dataObj.getPrimaryFile();
        if ((fileObj == null) || !fileObj.isValid()) {
          continue;
        }

        Project prj = FileOwnerQuery.getOwner(fileObj);
        if ((prj == null) || (getSourceGroup(fileObj, prj) == null)) {
          continue;
        }

        if (TestUtil.isJavaFile(fileObj) || (node.getCookie(DataFolder.class) != null)) {
          return true;
        }
      }
    }
    return false;
  }
コード例 #21
0
 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();
   }
 }
コード例 #22
0
  public void write(java.io.Writer w, Object inst) throws IOException {
    w.write(
        "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"
            + XMLSettingsSupport.LINE_SEPARATOR); // NOI18N
    w.write("<!DOCTYPE properties PUBLIC \""); // NOI18N

    FileObject foEntity = Env.findEntityRegistration(providerFO);
    if (foEntity == null) foEntity = providerFO;
    Object publicId = foEntity.getAttribute(Env.EA_PUBLICID);
    if (publicId == null || !(publicId instanceof String)) {
      throw new IOException(
          "missing or invalid attribute: "
              + // NOI18N
              Env.EA_PUBLICID
              + ", provider: "
              + foEntity); // NOI18N
    }

    w.write((String) publicId);
    w.write(
        "\" \"http://www.netbeans.org/dtds/properties-1_0.dtd\">"
            + XMLSettingsSupport.LINE_SEPARATOR); // NOI18N
    w.write("<properties>" + XMLSettingsSupport.LINE_SEPARATOR); // NOI18N
    Properties p = getProperties(inst);
    if (p != null && !p.isEmpty()) writeProperties(w, p);
    w.write("</properties>" + XMLSettingsSupport.LINE_SEPARATOR); // NOI18N
  }
コード例 #23
0
  /**
   * Determines the selected class.
   *
   * @param dObj the d obj
   * @throws IllegalArgumentException the illegal argument exception
   */
  protected final void determineSelectedClass(DataObject dObj) throws IllegalArgumentException {
    if (null != dObj) {

      FileObject fo = dObj.getPrimaryFile();

      JavaSource jsource = JavaSource.forFileObject(fo);

      if (jsource == null) {
        StatusDisplayer.getDefault().setStatusText("Not a Java file: " + fo.getPath());
      } else {
        // StatusDisplayer.getDefault().setStatusText("Hurray! A Java file: " + fo.getPath());

        try {
          jsource.runUserActionTask(
              (CompilationController p) -> {
                p.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                CompilationUnitTree tree = p.getCompilationUnit();
                MemberVisitor scanner = new MemberVisitor(p);
                scanner.scan(p.getCompilationUnit(), null);
                te = scanner.getTypeElement();
                Document document = p.getDocument();
              },
              true);
        } catch (IOException ex) {
          Exceptions.printStackTrace(ex);
        }
      }
    }
  }
コード例 #24
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();
        }

    }
    */

  }
コード例 #25
0
 private void assertHeader(FileObject fo, String header, String expectedMimeType)
     throws IOException {
   OutputStream os = fo.getOutputStream();
   os.write(header.getBytes());
   os.close();
   assertEquals("Header " + header + " wrongly resolved.", expectedMimeType, fo.getMIMEType());
 }
コード例 #26
0
    public void destroy() throws IOException {
      FileObject parent = dataFolder.getPrimaryFile().getParent();
      // First; delete all files except packages
      DataObject ch[] = dataFolder.getChildren();
      boolean empty = true;
      for (int i = 0; ch != null && i < ch.length; i++) {
        if (!ch[i].getPrimaryFile().isFolder()) {
          ch[i].delete();
        } else {
          empty = false;
        }
      }

      // If empty delete itself
      if (empty) {
        super.destroy();
      }

      // Second; delete empty super packages
      while (!parent.equals(root) && parent.getChildren().length == 0) {
        FileObject newParent = parent.getParent();
        parent.delete();
        parent = newParent;
      }
    }
コード例 #27
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));
    }
  }
コード例 #28
0
ファイル: Povray.java プロジェクト: vparfonov/api-samples
  private File getFileToRender() throws IOException {
    FileObject render = toRender;
    if (render == null) {
      PovrayProject proj = renderService.getProject();
      MainFileProvider provider =
          (MainFileProvider) proj.getLookup().lookup(MainFileProvider.class);
      if (provider == null) {
        throw new IllegalStateException("Main file provider missing");
      }
      render = provider.getMainFile();
      if (render == null) {
        ProjectInformation info =
            (ProjectInformation) proj.getLookup().lookup(ProjectInformation.class);

        // XXX let the user choose
        throw new IOException(
            NbBundle.getMessage(Povray.class, "MSG_NoMainFile", info.getDisplayName()));
      }
    }
    assert render != null;
    File result = FileUtil.toFile(render);
    if (result == null) {
      throw new IOException(NbBundle.getMessage(Povray.class, "MSG_VirtualFile", render.getName()));
    }
    assert result.exists();
    assert result.isFile();
    return result;
  }
コード例 #29
0
ファイル: GitProjectUtils.java プロジェクト: jonas/nbgit
  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;
  }
コード例 #30
0
 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();
   }
 }