001/*
002 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     bstefanescu
016 */
017package org.nuxeo.shell.automation.cmds;
018
019import java.util.Map;
020
021import org.nuxeo.shell.Argument;
022import org.nuxeo.shell.Command;
023import org.nuxeo.shell.Context;
024import org.nuxeo.shell.Parameter;
025import org.nuxeo.shell.Shell;
026import org.nuxeo.shell.ShellException;
027import org.nuxeo.shell.automation.AutomationFeature;
028
029/**
030 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
031 */
032@Command(name = "connect", help = "Connect to a remote automation server")
033public class Connect implements Runnable {
034
035    @Context
036    protected Shell shell;
037
038    @Argument(name = "url", index = 0, required = false, help = "The url of the automation server")
039    protected String url;
040
041    @Parameter(name = "-u", hasValue = true, help = "The username")
042    protected String username;
043
044    @Parameter(name = "-p", hasValue = true, help = "The password")
045    protected String password;
046
047    @Parameter(name = "-d", hasValue = true, help = "The initial directory")
048    protected String initialDirectory;
049
050    public void run() {
051        Map<String, String> args = (Map<String, String>) shell.getMainArguments();
052        if (username == null && args != null) {
053            username = args.get("-u");
054        }
055        if (password == null && args != null) {
056            password = args.get("-p");
057        }
058        if (initialDirectory == null && args != null) {
059            initialDirectory = args.get("-d");
060        }
061        if (initialDirectory == null) {
062            initialDirectory = "/";
063        }
064        if (url == null && args != null) {
065            url = args.get("#1");
066        }
067        if (username != null && password == null) {
068            password = shell.getConsole().readLine("Password: ", '*');
069        }
070        try {
071            shell.getFeature(AutomationFeature.class).connect(url, username, password, initialDirectory);
072        } catch (ShellException e) {
073            throw e;
074        } catch (Throwable e) {
075            throw new ShellException("Failed to connect to " + url, e);
076        }
077    }
078
079}