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;
      }
    }
  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 Transferable paste() throws IOException {
   assert this.op != DnDConstants.ACTION_NONE;
   for (int ni = 0; ni < nodes.length; ni++) {
     FileObject fo = srcRoot;
     if (!nodes[ni].isDefaultPackage) {
       String pkgName = nodes[ni].getName();
       StringTokenizer tk = new StringTokenizer(pkgName, "."); // NOI18N
       while (tk.hasMoreTokens()) {
         String name = tk.nextToken();
         FileObject tmp = fo.getFileObject(name, null);
         if (tmp == null) {
           tmp = fo.createFolder(name);
         }
         fo = tmp;
       }
     }
     DataFolder dest = DataFolder.findFolder(fo);
     DataObject[] children = nodes[ni].dataFolder.getChildren();
     boolean cantDelete = false;
     for (int i = 0; i < children.length; i++) {
       if (children[i].getPrimaryFile().isData()
           && VisibilityQuery.getDefault().isVisible(children[i].getPrimaryFile())) {
         // Copy only the package level
         children[i].copy(dest);
         if (this.op == DnDConstants.ACTION_MOVE) {
           try {
             children[i].delete();
           } catch (IOException ioe) {
             cantDelete = true;
           }
         }
       } else {
         cantDelete = true;
       }
     }
     if (this.op == DnDConstants.ACTION_MOVE && !cantDelete) {
       try {
         FileObject tmpFo = nodes[ni].dataFolder.getPrimaryFile();
         FileObject originalRoot = nodes[ni].root;
         assert tmpFo != null && originalRoot != null;
         while (!tmpFo.equals(originalRoot)) {
           if (tmpFo.getChildren().length == 0) {
             FileObject tmpFoParent = tmpFo.getParent();
             tmpFo.delete();
             tmpFo = tmpFoParent;
           } else {
             break;
           }
         }
       } catch (IOException ioe) {
         // Not important
       }
     }
   }
   return ExTransferable.EMPTY;
 }
 @Override
 protected FileSystem createFS(String... resources) throws IOException {
   for (String s : resources) {
     FileObject fo = FileUtil.getConfigFile(s.replaceAll("/.*", ""));
     if (fo != null) {
       fo.delete();
     }
   }
   FileSystem sfs = FileUtil.getConfigRoot().getFileSystem();
   for (String s : resources) {
     assertNotNull("creating: " + s, FileUtil.createData(sfs.getRoot(), s));
   }
   return sfs;
 }
  public void testDeleteCreateFile() throws IOException {

    // non atomic delete and create
    File file1 = new File(dataRootDir, "file1");
    file1 = FileUtil.normalizeFile(file1);
    file1.createNewFile();

    final FileObject fo1 = FileUtil.toFileObject(file1);
    fo1.delete();
    fo1.getParent().createData(fo1.getName());

    // get intercepted events
    String[] nonAtomic =
        DeleteCreateTestAnnotationProvider.instance.events.toArray(
            new String[DeleteCreateTestAnnotationProvider.instance.events.size()]);
    DeleteCreateTestAnnotationProvider.instance.events.clear();

    // atomic delete and create
    File file2 = new File(dataRootDir, "file2");
    file2 = FileUtil.normalizeFile(file2);
    file2.createNewFile();

    final FileObject fo2 = FileUtil.toFileObject(file2);
    AtomicAction a =
        new AtomicAction() {
          public void run() throws IOException {
            fo2.delete();
            fo2.getParent().createData(fo2.getName());
          }
        };
    fo2.getFileSystem().runAtomicAction(a);
    // get intercepted events
    String[] atomic =
        DeleteCreateTestAnnotationProvider.instance.events.toArray(
            new String[DeleteCreateTestAnnotationProvider.instance.events.size()]);

    Logger l = Logger.getLogger(DeleteCreateTest.class.getName());
    l.info("- atomic events ----------------------------------");
    for (String s : atomic) l.info(s);
    l.info("- non atomic events ------------------------------");
    for (String s : nonAtomic) l.info(s);
    l.info("-------------------------------");

    // test
    assertEquals(atomic.length, nonAtomic.length);
    for (int i = 0; i < atomic.length; i++) {
      assertEquals(atomic[i], nonAtomic[i]);
    }
  }
 void _removeService(Saas service) {
   try {
     if (service instanceof WsdlSaas) {
       WsdlSaas saas = (WsdlSaas) service;
       WsdlUtil.removeWsdlData(saas.getDelegate().getUrl());
     }
     FileObject saasFolder = service.getSaasFolder();
     if (saasFolder != null) {
       saasFolder.delete();
     }
     service.setState(Saas.State.REMOVED);
   } catch (IOException e) {
     Exceptions.printStackTrace(e);
   }
 }
  public void register(Project webApp) {
    int result = SUCCESS;

    Path target = createRegistry();

    if (target == null) {
      return;
    }
    FileObject propsFo =
        FileUtil.toFileObject(target.toFile())
            .getFileObject(SuiteConstants.SERVER_INSTANCE_WEB_APPS_PROPS);
    Properties props = new Properties();
    if (propsFo != null) {
      props = BaseUtil.loadProperties(propsFo);
      try {
        propsFo.delete();
      } catch (IOException ex) {
        LOG.log(Level.INFO, ex.getMessage());
      }
    }

    WebModule wm = WebModule.getWebModule(webApp.getProjectDirectory());

    String cp = wm.getContextPath();

    if (cp != null) {
      props.setProperty(cp, webApp.getProjectDirectory().getPath());
    } else {
      result = CONTEXTPATH_NOT_FOUND;
    }
    if (result == SUCCESS) {
      BaseUtil.storeProperties(
          props,
          FileUtil.toFileObject(target.toFile()),
          SuiteConstants.SERVER_INSTANCE_WEB_APPS_PROPS);
      String uri = SuiteManager.getManager(serverInstance).getUri();
      SuiteNotifier sn =
          SuiteManager.getServerSuiteProject(uri).getLookup().lookup(SuiteNotifier.class);
      sn.childrenChanged(this, webApp);
    }
    return;
  }
  public void setServerInstanceProperty(String name, String value) {
    Properties props = new Properties();
    Path target = createRegistry();
    if (target == null) {
      return;
    }
    FileObject propsFo =
        FileUtil.toFileObject(target.toFile())
            .getFileObject(SuiteConstants.SERVER_INSTANCE_PROPERTIES_FILE);

    if (propsFo != null) {
      props = BaseUtil.loadProperties(propsFo);
      try {
        propsFo.delete();
      } catch (IOException ex) {
        LOG.log(Level.INFO, ex.getMessage());
      }
    }
    props.setProperty(name, value);
    BaseUtil.storeProperties(
        props,
        FileUtil.toFileObject(target.toFile()),
        SuiteConstants.SERVER_INSTANCE_PROPERTIES_FILE);
  }
    public void setName(String name) {
      PackageRenameHandler handler = getRenameHandler();
      if (handler != null) {
        handler.handleRename(this, name);
        return;
      }

      if (isDefaultPackage) {
        return;
      }
      String oldName = getName();
      if (oldName.equals(name)) {
        return;
      }
      if (!isValidPackageName(name)) {
        DialogDisplayer.getDefault()
            .notify(
                new NotifyDescriptor.Message(
                    NbBundle.getMessage(PackageViewChildren.class, "MSG_InvalidPackageName"),
                    NotifyDescriptor.INFORMATION_MESSAGE));
        return;
      }
      name = name.replace('.', '/') + '/'; // NOI18N
      oldName = oldName.replace('.', '/') + '/'; // NOI18N
      int i;
      for (i = 0; i < oldName.length() && i < name.length(); i++) {
        if (oldName.charAt(i) != name.charAt(i)) {
          break;
        }
      }
      i--;
      int index = oldName.lastIndexOf('/', i); // NOI18N
      String commonPrefix = index == -1 ? null : oldName.substring(0, index);
      String toCreate = (index + 1 == name.length()) ? "" : name.substring(index + 1); // NOI18N
      try {
        FileObject commonFolder =
            commonPrefix == null ? this.root : this.root.getFileObject(commonPrefix);
        FileObject destination = commonFolder;
        StringTokenizer dtk = new StringTokenizer(toCreate, "/"); // NOI18N
        while (dtk.hasMoreTokens()) {
          String pathElement = dtk.nextToken();
          FileObject tmp = destination.getFileObject(pathElement);
          if (tmp == null) {
            tmp = destination.createFolder(pathElement);
          }
          destination = tmp;
        }
        FileObject source = this.dataFolder.getPrimaryFile();
        DataFolder sourceFolder = DataFolder.findFolder(source);
        DataFolder destinationFolder = DataFolder.findFolder(destination);
        DataObject[] children = sourceFolder.getChildren();
        for (int j = 0; j < children.length; j++) {
          if (children[j].getPrimaryFile().isData()) {
            children[j].move(destinationFolder);
          }
        }
        while (!commonFolder.equals(source)) {
          if (source.getChildren().length == 0) {
            FileObject tmp = source;
            source = source.getParent();
            tmp.delete();
          } else {
            break;
          }
        }
      } catch (IOException ioe) {
        ErrorManager.getDefault().notify(ioe);
      }
    }
  public int unregister(Project webApp) {
    int result = SUCCESS;
    Path serverDir = Paths.get(serverInstance.getProjectDirectory().getPath());
    String root = serverDir.getRoot().toString().replaceAll(":", "_");
    if (root.startsWith("/")) {
      root = root.substring(1);
    }
    Path targetPath = serverDir.getRoot().relativize(serverDir);
    String tmp = System.getProperty("java.io.tmpdir");

    Path target = Paths.get(tmp, SuiteConstants.TMP_DIST_WEB_APPS, root, targetPath.toString());

    File file = target.toFile();
    if (!file.exists()) {
      try {
        FileUtil.createFolder(file);
      } catch (IOException ex) {
        result = CREATE_FOLDER_ERROR;
        LOG.log(Level.INFO, ex.getMessage());
      }
    }

    FileObject propsFo =
        FileUtil.toFileObject(target.toFile())
            .getFileObject(SuiteConstants.SERVER_INSTANCE_WEB_APPS_PROPS);
    Properties props = new Properties();
    if (propsFo != null) {
      props = BaseUtil.loadProperties(propsFo);
      try {
        propsFo.delete();
      } catch (IOException ex) {
        result = CREATE_FOLDER_ERROR;
        LOG.log(Level.INFO, ex.getMessage());
      }
    }

    WebModule wm = WebModule.getWebModule(webApp.getProjectDirectory());

    String cp = wm.getContextPath();

    if (cp != null) {
      props.remove(cp);
      FileObject targetFo = FileUtil.toFileObject(target.toFile());
    } else {
      result = CONTEXTPATH_NOT_FOUND;
    }
    if (result == SUCCESS) {
      BaseUtil.storeProperties(
          props,
          FileUtil.toFileObject(target.toFile()),
          SuiteConstants.SERVER_INSTANCE_WEB_APPS_PROPS);
      String uri = SuiteManager.getManager(serverInstance).getUri();
      Project suite = SuiteManager.getServerSuiteProject(uri);
      if (suite == null) {
        result = NOT_A_SUITE;
      } else {
        SuiteNotifier sn = suite.getLookup().lookup(SuiteNotifier.class);
        sn.childrenChanged(this, webApp);
      }
    }
    return result;
  }
  @ForAllEnvironments
  public void testCyclicLinksDelete() throws Exception {
    String baseDir = null;
    try {
      baseDir = mkTempAndRefreshParent(true);
      String selfLinkName = "link";
      String linkName1 = "link1";
      String linkName2 = "link2";
      String parentName2 = "link2parent";
      String baseDirlinkName = "linkToDir";
      String cyclickLink1 = "cl1";
      String cyclickLink2 = "cl2";
      String cyclickLink3 = "cl3";
      String script =
          "cd "
              + baseDir
              + "; "
              + "ln -s "
              + selfLinkName
              + ' '
              + selfLinkName
              + ";"
              + "ln -s "
              + linkName1
              + ' '
              + linkName2
              + ";"
              + "ln -s "
              + linkName2
              + ' '
              + linkName1
              + ";"
              + "ln -s . "
              + parentName2
              + ";"
              + "ln -s "
              + cyclickLink1
              + ' '
              + cyclickLink2
              + ";"
              + "ln -s "
              + cyclickLink2
              + ' '
              + cyclickLink3
              + ";"
              + "ln -s "
              + cyclickLink3
              + ' '
              + cyclickLink1
              + ";"
              + "ln -s "
              + baseDir
              + ' '
              + baseDirlinkName;
      ProcessUtils.ExitStatus res = ProcessUtils.execute(execEnv, "sh", "-c", script);
      assertEquals("Error executing script \"" + script + "\": " + res.error, 0, res.exitCode);

      FileObject baseDirFO = getFileObject(baseDir);
      baseDirFO.refresh();
      FileObject[] children =
          baseDirFO.getChildren(); // otherwise existent children are empty => refresh won't cycle
      baseDirFO.delete();
    } finally {
      removeRemoteDirIfNotNull(baseDir);
    }
  }