001/*
002 * (C) Copyright 2006-2010 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 */
019package org.nuxeo.shell.automation.cmds;
020
021import java.util.Map;
022
023import org.nuxeo.shell.Argument;
024import org.nuxeo.shell.Command;
025import org.nuxeo.shell.Context;
026import org.nuxeo.shell.Parameter;
027import org.nuxeo.shell.Shell;
028import org.nuxeo.shell.ShellException;
029import org.nuxeo.shell.automation.AutomationFeature;
030
031/**
032 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
033 */
034@Command(name = "connect", help = "Connect to a remote automation server")
035public class Connect implements Runnable {
036
037    @Context
038    protected Shell shell;
039
040    @Argument(name = "url", index = 0, required = false, help = "The url of the automation server")
041    protected String url;
042
043    @Parameter(name = "-u", hasValue = true, help = "The username")
044    protected String username;
045
046    @Parameter(name = "-p", hasValue = true, help = "The password")
047    protected String password;
048
049    @Parameter(name = "-d", hasValue = true, help = "The initial directory")
050    protected String initialDirectory;
051
052    public void run() {
053        Map<String, String> args = (Map<String, String>) shell.getMainArguments();
054        if (username == null && args != null) {
055            username = args.get("-u");
056        }
057        if (password == null && args != null) {
058            password = args.get("-p");
059        }
060        if (initialDirectory == null && args != null) {
061            initialDirectory = args.get("-d");
062        }
063        if (initialDirectory == null) {
064            initialDirectory = "/";
065        }
066        if (url == null && args != null) {
067            url = args.get("#1");
068        }
069        if (username != null && password == null) {
070            password = shell.getConsole().readLine("Password: ", '*');
071        }
072        try {
073            shell.getFeature(AutomationFeature.class).connect(url, username, password, initialDirectory);
074        } catch (ShellException e) {
075            throw e;
076        } catch (Throwable e) {
077            throw new ShellException("Failed to connect to " + url, e);
078        }
079    }
080
081}