コード例 #1
1
  public void testBasic() throws Exception {
    if (!Dpkg.available()) {
      return;
    }

    DebPackagingFormat packagingFormat = (DebPackagingFormat) lookup(PackagingFormat.ROLE, "deb");

    FileObject dpkgTest = VFS.getManager().resolveFile(getTestPath("target/deb-test"));
    FileObject packageRoot = dpkgTest.resolveFile("root");
    File packageFile = VfsUtil.asFile(dpkgTest.resolveFile("file.deb"));

    PackageVersion version = packageVersion("1.0", "123", false, some("1"));
    PackageParameters parameters =
        packageParameters(
                "mygroup",
                "myartifact",
                version,
                "id",
                "default-name",
                Option.<java.lang.String>none(),
                EMPTY,
                EMPTY)
            .contact("Kurt Cobain")
            .architecture("all");

    List<String> nil = List.nil();
    packagingFormat
        .start()
        .parameters(parameters)
        .debParameters(Option.<String>none(), some("devel"), false, nil, nil, nil, nil, nil, nil)
        .debug(true)
        .workingDirectory(packageRoot)
        .packageToFile(packageFile, ScriptUtil.Strategy.SINGLE);

    assertTrue(packageFile.canRead());
  }
コード例 #2
0
 /**
  * Parse a set of URLs from a comma-separated list of URLs. If the URL points to a directory all
  * jar files within that directory will be returned as well.
  *
  * @param urlString Comma-separated list of URLs (relative or absolute)
  * @return List of URLs resolved from {@code urlString}
  */
 protected List<URL> parseURLs(FileObject root, String urlString) {
   if (urlString == null || urlString.trim().isEmpty()) {
     return Collections.emptyList();
   }
   String[] paths = urlString.split(",");
   List<URL> urls = new ArrayList<URL>();
   for (String path : paths) {
     try {
       FileObject file = root.resolveFile(path.trim());
       if (!file.exists()) {
         file = defaultFsm.resolveFile(path.trim());
       }
       if (FileType.FOLDER.equals(file.getType())) {
         // Add directories with a trailing / so the URL ClassLoader interprets
         // them as directories
         urls.add(new URL(file.getURL().toExternalForm() + "/"));
         // Also add all jars within this directory
         urls.addAll(findJarsIn(file, 1, new HashSet<String>()));
       } else {
         urls.add(file.getURL());
       }
     } catch (Exception e) {
       // Log invalid path
       logger.error(BaseMessages.getString(PKG, "Error.InvalidClasspathEntry", path));
     }
   }
   return urls;
 }
コード例 #3
0
    /** Invoked when an action occurs. */
    public void actionPerformed(final ActionEvent e) {
      final CreateNewRepositoryFolderDialog newFolderDialog =
          new CreateNewRepositoryFolderDialog(RepositoryPublishDialog.this);

      if (!newFolderDialog.performEdit()) {
        return;
      }

      final FileObject treeNode = getSelectedView();
      if (treeNode == null) {
        return;
      }

      if (!StringUtils.isEmpty(newFolderDialog.getName())) {
        final Component glassPane =
            SwingUtilities.getRootPane(RepositoryPublishDialog.this).getGlassPane();
        try {
          glassPane.setVisible(true);
          glassPane.setCursor(new Cursor(Cursor.WAIT_CURSOR));
          final FileObject child = treeNode.resolveFile(newFolderDialog.getFolderName());
          child.createFolder();
          if (child instanceof WebSolutionFileObject) {
            final WebSolutionFileObject webSolutionFileObject = (WebSolutionFileObject) child;
            webSolutionFileObject.setDescription(newFolderDialog.getDescription());
          }
          getTable().refresh();
        } catch (Exception e1) {
          UncaughtExceptionsModel.getInstance().addException(e1);
        } finally {
          glassPane.setVisible(false);
          glassPane.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
      }
    }
コード例 #4
0
  /**
   * Tests closing all FileSystems
   *
   * @throws Exception
   */
  @Ignore("vfs close file system doesn't seem to work properly")
  @Test
  public void testCloseFileSystems() throws Exception {
    logger.info("*************** testCloseFileSystems");
    String[] validUrls = server.getVFSRootURLs();
    ArrayList<FileObject> fos = new ArrayList<FileObject>();
    for (String validUrl : validUrls) {
      FileObject mounted = VFSMountManagerHelper.mount(validUrl);
      Assert.assertTrue(mounted.exists());
      fos.add(mounted);
    }

    VFSMountManagerHelper.closeFileSystems(Arrays.asList(validUrls));

    boolean onlyExceptions = true;
    for (FileObject closedFo : fos) {
      try {
        FileObject toto = closedFo.resolveFile("toto");
        toto.createFile();
        onlyExceptions = false;
        logger.error(toto.getURL() + " exists : " + toto.exists());
      } catch (FileSystemException e) {
        // this should occur
      }
    }
    Assert.assertTrue("Only Exceptions received", onlyExceptions);
  }
コード例 #5
0
ファイル: Shell.java プロジェクト: penSecIT/commons-vfs
  /** Does a 'cp' command. */
  private void cp(final String[] cmd) throws Exception {
    if (cmd.length < 3) {
      throw new Exception("USAGE: cp <src> <dest>");
    }

    final FileObject src = mgr.resolveFile(cwd, cmd[1]);
    FileObject dest = mgr.resolveFile(cwd, cmd[2]);
    if (dest.exists() && dest.getType() == FileType.FOLDER) {
      dest = dest.resolveFile(src.getName().getBaseName());
    }

    dest.copyFrom(src, Selectors.SELECT_ALL);
  }
コード例 #6
0
  /** Locates a file object, by absolute URI. */
  public FileObject findFile(
      final FileObject baseFile, final String uri, final FileSystemOptions properties)
      throws FileSystemException {
    // Split the URI up into its parts
    final LayeredFileName name = (LayeredFileName) parseUri(uri);

    // Make the URI canonical

    // Resolve the outer file name
    final String fileName = name.getOuterUri();
    final FileObject file = getContext().resolveFile(baseFile, fileName, properties);

    // Create the file system
    final FileObject rootFile = createFileSystem(name.getScheme(), file, properties);

    // Resolve the file
    return rootFile.resolveFile(name.getPath());
  }
コード例 #7
0
 public void testDefault() throws Exception {
   Heuristics heuristics = RuleBasedHeuristics.getDefaultInstance();
   FileSystemManager fsm = VFS.getManager();
   FileObject root =
       fsm.resolveFile(
               RuleBasedHeuristicsTest.class.getResource("/heuristics/.root").toExternalForm())
           .getParent();
   for (Reason reason : Reason.values()) {
     for (FileObject file : root.resolveFile(reason.toString().toLowerCase()).getChildren()) {
       InputStream is = file.getContent().getInputStream();
       DeliveryStatus ds = new DeliveryStatus(is);
       is.close();
       assertEquals(
           "Reason for " + file,
           reason,
           heuristics.getReason(ds.getPerRecipientParts()[0].getDiagnostic()));
     }
   }
 }
コード例 #8
0
  protected boolean validateInputs(final boolean onConfirm) {
    if (super.validateInputs(onConfirm) == false) {
      return false;
    }

    if (onConfirm == false) {
      return true;
    }

    final String reportName = getFileNameTextField().getText();
    if (StringUtils.isEmpty(reportName) == false
        && reportName.endsWith(REPORT_BUNDLE_EXTENSION) == false) {
      final String safeReportName = reportName + REPORT_BUNDLE_EXTENSION;
      getFileNameTextField().setText(safeReportName);
    }

    try {
      final FileObject selectedView = getSelectedView();
      final String validateName = getSelectedFile();
      if (validateName == null || selectedView == null) {
        return false;
      }

      final FileObject targetFile = selectedView.resolveFile(getFileNameTextField().getText());
      final FileObject fileObject = selectedView.getFileSystem().resolveFile(targetFile.getName());
      if (fileObject.getType() == FileType.IMAGINARY) {
        return true;
      }

      final int result =
          JOptionPane.showConfirmDialog(
              this,
              Messages.getInstance()
                  .formatMessage("PublishToServerAction.FileExistsOverride", validateName),
              Messages.getInstance().getString("PublishToServerAction.Information.Title"),
              JOptionPane.YES_NO_OPTION);
      return result == JOptionPane.YES_OPTION;
    } catch (FileSystemException fse) {
      UncaughtExceptionsModel.getInstance().addException(fse);
      return false;
    }
  }
コード例 #9
0
  protected boolean configureJaasModule() {
    String tcInstallDir = getProperty("tomcatInstallDir");
    String jbInstallDir = getProperty("jbossInstallDir");
    final String JOSSO_TOMCAT_MODULE_DEFINITION =
        "\n\njosso {\n"
            + "org.josso.liferay5.agent.jaas.SSOGatewayLoginModule required debug=true;\n"
            + "};";

    if (tcInstallDir != null) {
      log.debug("[configureJaasModule]: Tomcat install dir: " + tcInstallDir);
      try {
        FileObject tomcatInstallDir = getFileSystemManager().resolveFile(tcInstallDir);
        FileObject jaasConfigFile = tomcatInstallDir.resolveFile("conf/jaas.config");
        if (jaasConfigFile != null) {
          BufferedWriter writerJaas =
              new BufferedWriter(
                  new OutputStreamWriter(
                      new FileOutputStream(jaasConfigFile.getURL().getFile(), true)));
          writerJaas.write(JOSSO_TOMCAT_MODULE_DEFINITION);
          writerJaas.flush();
          writerJaas.close();
          return true;
        } else {
          getPrinter()
              .printActionErrStatus(
                  "Configure", "JOSSO SSO Filter", "jaas.conf doesn't exist on given path");
          return false;
        }
      } catch (FileSystemException e) {
        getPrinter()
            .printActionErrStatus(
                "Configure", "JOSSO SSO Filter", "Tomcat install directory is wrong.");
      } catch (IOException e) {
        getPrinter()
            .printActionErrStatus("Configure", "JOSSO SSO Filter", "Can not write to jaas.conf.");
      }
    }

    if (jbInstallDir != null) {
      log.debug("[configureJaasModule]: JBoss install dir: " + jbInstallDir);
      FileObject jbossInstallDir = null;
      try {
        jbossInstallDir = getFileSystemManager().resolveFile(jbInstallDir);
        FileObject loginConfig =
            jbossInstallDir.resolveFile("server/default/conf/login-config.xml");
        Node xDom = readContentAsDom(loginConfig);

        if (xDom == null) {
          log.debug(
              "[configureJaasModule]: XML is not loaded.  "
                  + loginConfig.getName().getFriendlyURI());
          return false;
        }
        String xupdJossoModule =
            "\n\t<xupdate:append select=\"/policy\" >\n"
                + "\t\t<xupdate:element name=\"application-policy\">\n"
                + "\t\t\t<xupdate:attribute name=\"name\">josso</xupdate:attribute>\n"
                + "\t\t\t<authentication>\n"
                + "\t\t\t\t<login-module code=\"org.josso.liferay5.agent.jaas.SSOGatewayLoginModule\" flag=\"required\">\n"
                + "\t\t\t\t\t<module-option name=\"debug\">true</module-option>\n"
                + "\t\t\t\t</login-module>\n"
                + "\t\t\t</authentication>\n"
                + "\t\t</xupdate:element>\n"
                + "\t</xupdate:append>";

        String qry = XUpdateUtil.XUPDATE_START + xupdJossoModule + XUpdateUtil.XUPDATE_END;
        log.debug("XUPDATE QUERY: \n" + qry);
        XUpdateQuery xq = new XUpdateQueryImpl();
        xq.setQString(qry);
        xq.execute(xDom);

        writeContentFromDom(xDom, loginConfig);

        getPrinter()
            .printActionOkStatus(
                "Changed login-config.xml",
                "JOSSO Liferay 5 Agent ",
                "server/default/conf/login-config.xml");
        return true;

      } catch (FileSystemException e) {
        getPrinter()
            .printActionErrStatus(
                "Configure", "JOSSO SSO Filter", "JBoss install directory is wrong.");
      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    return false;
  }
コード例 #10
0
  public FileObject open(
      Shell applicationShell,
      String[] schemeRestrictions,
      String initialScheme,
      boolean showFileScheme,
      String fileName,
      String[] fileFilters,
      String[] fileFilterNames,
      boolean returnUserAuthenticatedFile,
      int fileDialogMode,
      boolean showLocation,
      boolean showCustomUI) {

    this.fileDialogMode = fileDialogMode;
    this.fileFilters = fileFilters;
    this.fileFilterNames = fileFilterNames;
    this.applicationShell = applicationShell;
    this.showFileScheme = showFileScheme;
    this.initialScheme = initialScheme;
    this.schemeRestrictions = schemeRestrictions;
    this.showLocation = showLocation;
    this.showCustomUI = showCustomUI;

    FileObject tmpInitialFile = initialFile;

    if (defaultInitialFile != null && rootFile == null) {
      try {
        rootFile = defaultInitialFile.getFileSystem().getRoot();
        initialFile = defaultInitialFile;
      } catch (FileSystemException ignored) {
        // well we tried
      }
    }

    createDialog(applicationShell);

    if (!showLocation) {
      comboPanel.setParent(fakeShell);
    } else {
      comboPanel.setParent(customUIPanel);
    }

    if (!showCustomUI) {
      customUIPanel.setParent(fakeShell);
    } else {
      customUIPanel.setParent(dialog);
    }

    // create our file chooser tool bar, contains parent folder combo and various controls
    createToolbarPanel(dialog);
    // create our vfs browser component
    createVfsBrowser(dialog);
    populateCustomUIPanel(dialog);
    if (fileDialogMode == VFS_DIALOG_SAVEAS) {
      createFileNamePanel(dialog, fileName);
    } else {
      // create file filter panel
      createFileFilterPanel(dialog);
    }
    // create our ok/cancel buttons
    createButtonPanel(dialog);

    initialFile = tmpInitialFile;
    // set the initial file selection
    try {
      if (initialFile != null || rootFile != null) {
        vfsBrowser.selectTreeItemByFileObject(initialFile != null ? initialFile : rootFile, true);
        updateParentFileCombo(initialFile != null ? initialFile : rootFile);
        setSelectedFile(initialFile != null ? initialFile : rootFile);
        openFileCombo.setText(
            initialFile != null ? initialFile.getName().getURI() : rootFile.getName().getURI());
      }
    } catch (FileSystemException e) {
      MessageBox box = new MessageBox(dialog.getShell());
      box.setText(Messages.getString("VfsFileChooserDialog.error")); // $NON-NLS-1$
      box.setMessage(e.getMessage());
      box.open();
    }

    // set the size and show the dialog
    int height = 550;
    int width = 800;
    dialog.setSize(width, height);
    Rectangle bounds = dialog.getDisplay().getPrimaryMonitor().getClientArea();
    int x = (bounds.width - width) / 2;
    int y = (bounds.height - height) / 2;
    dialog.setLocation(x, y);
    dialog.open();

    if (rootFile != null && fileDialogMode == VFS_DIALOG_SAVEAS) {
      if (!rootFile.getFileSystem().hasCapability(Capability.WRITE_CONTENT)) {
        MessageBox messageDialog = new MessageBox(dialog.getShell(), SWT.OK);
        messageDialog.setText(Messages.getString("VfsFileChooserDialog.warning")); // $NON-NLS-1$
        messageDialog.setMessage(
            Messages.getString("VfsFileChooserDialog.noWriteSupport")); // $NON-NLS-1$
        messageDialog.open();
      }
    }

    vfsBrowser.fileSystemTree.forceFocus();
    while (!dialog.isDisposed()) {
      if (!dialog.getDisplay().readAndDispatch()) dialog.getDisplay().sleep();
    }

    // we just woke up, we are probably disposed already..
    if (!dialog.isDisposed()) {
      hideCustomPanelChildren();
      dialog.dispose();
    }
    if (okPressed) {
      FileObject returnFile = vfsBrowser.getSelectedFileObject();
      if (returnFile != null && fileDialogMode == VFS_DIALOG_SAVEAS) {
        try {
          if (returnFile.getType().equals(FileType.FILE)) {
            returnFile = returnFile.getParent();
          }
          returnFile = returnFile.resolveFile(enteredFileName);
        } catch (FileSystemException e) {
          e.printStackTrace();
        }
      }

      // put user/pass on the filename so it comes out in the getUri call.
      if (!returnUserAuthenticatedFile) {
        // make sure to put the user/pass on the url if it's not there
        if (returnFile != null && returnFile.getName() instanceof URLFileName) {
          URLFileName urlFileName = (URLFileName) returnFile.getName();
          if (urlFileName.getUserName() == null || urlFileName.getPassword() == null) {
            // set it
            String user = "";
            String pass = "";

            UserAuthenticator userAuthenticator =
                DefaultFileSystemConfigBuilder.getInstance()
                    .getUserAuthenticator(returnFile.getFileSystem().getFileSystemOptions());

            if (userAuthenticator != null) {
              UserAuthenticationData data =
                  userAuthenticator.requestAuthentication(AUTHENTICATOR_TYPES);
              user = String.valueOf(data.getData(UserAuthenticationData.USERNAME));
              pass = String.valueOf(data.getData(UserAuthenticationData.PASSWORD));
              try {
                user = URLEncoder.encode(user, "UTF-8");
                pass = URLEncoder.encode(pass, "UTF-8");
              } catch (UnsupportedEncodingException e) {
                // ignore, just use the un encoded values
              }
            }

            // build up the url with user/pass on it
            int port = urlFileName.getPort();
            String portString = (port < 1) ? "" : (":" + port);
            String urlWithUserPass =
                urlFileName.getScheme()
                    + "://"
                    + user
                    + ":"
                    + pass
                    + "@"
                    + urlFileName.getHostName()
                    + portString
                    + urlFileName.getPath();

            try {
              returnFile = currentPanel.resolveFile(urlWithUserPass);
            } catch (FileSystemException e) {
              // couldn't resolve with user/pass on url??? interesting
              e.printStackTrace();
            }
          }
        }
      }
      return returnFile;
    } else {
      return null;
    }
  }
コード例 #11
0
 public void beforeAssembly(FileAttributes defaultDirectoryAttributes) throws IOException {
   specFile.beforeAssembly(directory(BASE, new LocalDateTime(), defaultDirectoryAttributes));
   fileCollector = new FsFileCollector(workingDirectory.resolveFile("assembly"));
 }
コード例 #12
0
  /**
   * Internal method for resolving a file, will mount the file system if it is not mounted yet
   *
   * @param uri virtual uri of the file
   * @param ownerActiveObjectId Id of active object requesting this file
   * @param spaceRootFOUri root file system to use
   * @return
   * @throws FileSystemException
   */
  private DataSpacesFileObject doResolveFile(
      final DataSpacesURI uri, final String ownerActiveObjectId, String spaceRootFOUri)
      throws FileSystemException {

    DataSpacesURI spacePart = uri.getSpacePartOnly();

    if (spaceRootFOUri != null) {
      ensureFileSystemIsMounted(spacePart, spaceRootFOUri);
    } else {
      try {
        readLock.lock();
        LinkedHashSet<String> los = accessibleFileObjectUris.get(spacePart);
        spaceRootFOUri = los.iterator().next();
      } finally {
        readLock.unlock();
      }
      ensureFileSystemIsMounted(spacePart, spaceRootFOUri);
    }

    final String relativeToSpace = uri.getRelativeToSpace();
    try {
      readLock.lock();

      if (!mountedSpaces.containsKey(spacePart)) {
        throw new FileSystemException("Could not access file that should exist (be mounted)");
      }

      final ConcurrentHashMap<String, FileObject> spaceRoots = mountedSpaces.get(spacePart);
      FileObject spaceRoot = spaceRoots.get(spaceRootFOUri);
      FileName dataSpaceVFSFileName = null;

      final FileObject file;
      // the dataspace "File name" (it is actually a File Path) is computed using the Virtual Space
      // root
      if (dataSpaceVFSFileName == null) {
        dataSpaceVFSFileName = spaceRoot.getName();
      }
      try {
        if (relativeToSpace == null) file = spaceRoot;
        else file = spaceRoot.resolveFile(relativeToSpace);
        final DataSpacesLimitingFileObject limitingFile =
            new DataSpacesLimitingFileObject(
                file, spacePart, spaceRoot.getName(), ownerActiveObjectId);
        return new VFSFileObjectAdapter(
            limitingFile,
            spacePart,
            dataSpaceVFSFileName,
            new ArrayList<String>(accessibleFileObjectUris.get(spacePart)),
            spaceRootFOUri,
            this,
            ownerActiveObjectId);
      } catch (org.apache.commons.vfs.FileSystemException x) {
        logger.error("[VFSMountManager] Could not access file within a space: " + uri);

        throw new FileSystemException(x);
      } catch (FileSystemException e) {
        ProActiveLogger.logImpossibleException(logger, e);
        throw new ProActiveRuntimeException(e);
      }

    } finally {
      readLock.unlock();
    }
  }