Example usage for org.apache.commons.vfs2 UserAuthenticationData USERNAME

List of usage examples for org.apache.commons.vfs2 UserAuthenticationData USERNAME

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 UserAuthenticationData USERNAME.

Prototype

Type USERNAME

To view the source code for org.apache.commons.vfs2 UserAuthenticationData USERNAME.

Click Source Link

Document

The user name.

Usage

From source file:org.pentaho.reporting.libraries.pensol.PentahoSolutionFileProvider.java

private FileSystem createJCRFileSystem(final LayeredFileName genericRootName,
        final FileSystemOptions fileSystemOptions) {
    UserAuthenticationData authData = null;
    try {/*from ww  w. j a  va2  s.  c  om*/
        authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, AUTHENTICATOR_TYPES);
        final GenericFileName outerName = (GenericFileName) genericRootName.getOuterName();

        final String username = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(outerName.getUserName())));

        final String password = UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(outerName.getPassword())));
        final PentahoSolutionsFileSystemConfigBuilder configBuilder = new PentahoSolutionsFileSystemConfigBuilder();
        final int timeOut = configBuilder.getTimeOut(fileSystemOptions);

        final JCRSolutionFileModel model = new JCRSolutionFileModel(outerName.getURI(), username, password,
                timeOut);
        return new JCRSolutionFileSystem(genericRootName, fileSystemOptions, model);
    } finally {
        UserAuthenticatorUtils.cleanup(authData);
    }
}

From source file:org.pentaho.vfs.ui.VfsFileChooserDialog.java

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 {//from   ww  w .j a v a  2 s.c  om
            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;
    }
}

From source file:pl.otros.vfs.browser.auth.AuthStoreUtilsTest.java

@Test
public void testSave() throws Exception {
    //given/* w  ww . ja v a2s . co  m*/
    AuthStore authStore = new MemoryAuthStore();
    UserAuthenticationDataWrapper authenticationData1 = new UserAuthenticationDataWrapper();
    authenticationData1.setData(UserAuthenticationData.USERNAME, "Stefan".toCharArray());
    authenticationData1.setData(UserAuthenticationData.PASSWORD, "Password".toCharArray());
    authenticationData1.setData(new UserAuthenticationData.Type("path"), "c:\\file".toCharArray());

    UserAuthenticationDataWrapper authenticationData2 = new UserAuthenticationDataWrapper();
    authenticationData2.setData(UserAuthenticationData.USERNAME, "Stefaan".toCharArray());
    authenticationData2.setData(UserAuthenticationData.PASSWORD, "Passwodrd".toCharArray());
    authenticationData2.setData(UserAuthenticationData.DOMAIN, "MS".toCharArray());

    UserAuthenticationDataWrapper authenticationData3 = new UserAuthenticationDataWrapper();
    authenticationData3.setData(UserAuthenticationData.USERNAME, "Stefan".toCharArray());
    authenticationData3.setData(UserAuthenticationData.PASSWORD, "Passwo@rd".toCharArray());
    authenticationData3.setData(UserAuthenticationData.DOMAIN, "MSzx!X%a".toCharArray());

    authStore.add(new UserAuthenticationInfo("ftp", "host1", "stefan"), authenticationData1);
    authStore.add(new UserAuthenticationInfo("ftp", "host1", "stefan9"), authenticationData1);
    authStore.add(new UserAuthenticationInfo("sftp", "host1a", "astefan"), authenticationData1);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    String expected = IOUtils.toString(this.getClass().getResourceAsStream("credentials.xml"));
    expected = expected.replaceAll(">\\s+", ">").replaceAll("\\s+<", "<")
            .replaceAll("<Type>password</Type><Data>.*?<", "<Type>password</Type><Data><").trim();

    //when
    authStoreUtils.save(authStore, bout);

    //then
    System.out.println(new String(bout.toByteArray()));
    String result = new String(bout.toByteArray()).replaceAll(">\\s+", ">").replaceAll("\\s+<", "<")
            .replaceAll("<Type>password</Type><Data>.*?<", "<Type>password</Type><Data><").trim();
    assertEquals(result, expected);

}

From source file:pl.otros.vfs.browser.auth.AuthStoreUtilsTest.java

@Test
public void testLoad() throws Exception {
    //given// ww  w  . ja  v a  2  s .  c o m
    MemoryAuthStore memoryAuthStore = new MemoryAuthStore();
    InputStream resourceAsStream = this.getClass().getResourceAsStream("credentials.xml");

    //when
    authStoreUtils.load(memoryAuthStore, resourceAsStream);

    //then
    assertEquals(memoryAuthStore.getAll().size(), 3);
    UserAuthenticationDataWrapper userAuthenticationData1 = memoryAuthStore
            .getUserAuthenticationData(new UserAuthenticationInfo("ftp", "host1", "stefan"));
    assertEquals(userAuthenticationData1.getData(UserAuthenticationData.USERNAME), "Stefan".toCharArray());
    LOGGER.info("Password for stefan:"
            + new String(userAuthenticationData1.getData(UserAuthenticationData.PASSWORD)));
    assertEquals(userAuthenticationData1.getData(UserAuthenticationData.PASSWORD), "Password".toCharArray());
    assertEquals(userAuthenticationData1.getData(new UserAuthenticationData.Type("path")),
            "c:\\file".toCharArray());

}

From source file:pl.otros.vfs.browser.auth.UserPassUserAuthenticator.java

@Override
protected void getAuthenticationData(UserAuthenticationData authenticationData) {
    authenticationData.setData(UserAuthenticationData.USERNAME,
            nameTf.getSelectedItem().toString().toCharArray());
    authenticationData.setData(UserAuthenticationData.PASSWORD, passTx.getPassword());

}

From source file:pl.otros.vfs.browser.auth.UserPassUserAuthenticator.java

@Override
protected JPanel getOptionsPanel() {

    Collection<UserAuthenticationDataWrapper> userAuthenticationDatas = getAuthStore()
            .getUserAuthenticationDatas(getVfsUriParser().getProtocol().getName(),
                    getVfsUriParser().getHostname());
    String[] names = new String[userAuthenticationDatas.size()];
    int i = 0;//from ww  w.  j a v  a  2  s . c  om
    for (UserAuthenticationData userAuthenticationData : userAuthenticationDatas) {
        names[i] = new String(userAuthenticationData.getData(UserAuthenticationData.USERNAME));
        i++;
    }

    JPanel panel = new JPanel(new MigLayout());
    String header = Messages.getMessage("authenticator.enterCredentialsForUrl", getUrl());
    panel.add(new JLabel(header), "growx,span");
    panel.add(new JLabel(Messages.getMessage("authenticator.username")));
    nameTf = new JXComboBox(names);
    nameTf.setEditable(true);
    nameTf.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            userSelected(nameTf.getSelectedItem().toString());
        }
    });

    AutoCompleteDecorator.decorate(nameTf);
    nameTf.addAncestorListener(new AncestorListener() {

        @Override
        public void ancestorRemoved(AncestorEvent event) {

        }

        @Override
        public void ancestorMoved(AncestorEvent event) {

        }

        @Override
        public void ancestorAdded(AncestorEvent event) {
            event.getComponent().requestFocusInWindow();
        }
    });
    panel.add(nameTf, "wrap, growx, span");
    panel.add(new JLabel(Messages.getMessage("authenticator.password")));
    passTx = new JPasswordField(15);
    passTx.setText(getVfsUriParser().getPassword());
    panel.add(passTx, "wrap, growx,span");

    if (StringUtils.isNotBlank(getVfsUriParser().getUsername())) {
        nameTf.setSelectedItem(getVfsUriParser().getUsername());
    }
    if (names.length > 0) {
        nameTf.setSelectedIndex(0);
    }
    return panel;
}

From source file:pl.otros.vfs.browser.util.VFSUtils.java

/**
 * Returns a file representation/*  ww w.  j  a  v  a  2s. c om*/
 *
 * @param filePath The file path
 * @param options  The filesystem options
 * @return a file representation
 * @throws FileSystemException
 */
public static FileObject resolveFileObject(String filePath, FileSystemOptions options,
        OtrosUserAuthenticator authenticator, AuthStore persistentAuthStore, AuthStore sessionAuthStore)
        throws FileSystemException {
    if (filePath.startsWith("sftp://")) {
        SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance();
        builder.setStrictHostKeyChecking(opts, "no");
        builder.setUserDirIsRoot(opts, false);
        builder.setCompression(opts, "zlib,none");
    }

    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(options, authenticator);
    FileObject resolveFile;

    VFSURIParser parser = new VFSURIParser(filePath);
    //Get file type to force authentication
    try {
        resolveFile = getFileSystemManager().resolveFile(filePath, options);
        resolveFile.getType();
    } catch (FileSystemException e) {
        LOGGER.error("Error resolving file " + filePath, e);
        Throwable rootCause = Throwables.getRootCause(e);
        boolean authorizationFailed = false;
        authorizationFailed = checkForWrongCredentials(rootCause);
        if (authorizationFailed) {
            LOGGER.error("Wrong user name or password for " + filePath);
            //clear last data
            //authenticator can be null if user/password was entered in URL
            if (authenticator != null) {
                UserAuthenticationDataWrapper lastUserAuthenticationData = authenticator
                        .getLastUserAuthenticationData();
                lastUserAuthenticationData.remove(UserAuthenticationDataWrapper.PASSWORD);
                String user = new String(lastUserAuthenticationData.getData(UserAuthenticationData.USERNAME));
                UserAuthenticationInfo auInfo = new UserAuthenticationInfo(parser.getProtocol().getName(),
                        parser.getHostname(), user);
                sessionAuthStore.remove(auInfo);
                sessionAuthStore.add(auInfo, lastUserAuthenticationData);
                LOGGER.info("Removing password for {} on {}",
                        new Object[] {
                                new String(lastUserAuthenticationData.getData(UserAuthenticationData.USERNAME)),
                                filePath });
            }
        }
        throw e;
    }

    if (resolveFile != null && authenticator != null && authenticator.getLastUserAuthenticationData() != null) {
        UserAuthenticationDataWrapper lastUserAuthenticationData = authenticator
                .getLastUserAuthenticationData();
        Map<Type, char[]> addedTypes = lastUserAuthenticationData.getAddedTypes();
        String user = new String(addedTypes.get(UserAuthenticationData.USERNAME));
        UserAuthenticationInfo auInfo = new UserAuthenticationInfo(parser.getProtocol().getName(),
                parser.getHostname(), user);
        sessionAuthStore.add(auInfo, lastUserAuthenticationData.copy());
        if (authenticator.isPasswordSave()) {
            LOGGER.info("Saving password for {}://{}@{}",
                    new Object[] { parser.getProtocol().getName(), user, parser.getHostname() });
            persistentAuthStore.add(auInfo, lastUserAuthenticationData);
            saveAuthStore();
        }
    }
    return resolveFile;
}