001    /**
002     *  Licensed to the Apache Software Foundation (ASF) under one or more
003     *  contributor license agreements.  See the NOTICE file distributed with
004     *  this work for additional information regarding copyright ownership.
005     *  The ASF licenses this file to You under the Apache License, Version 2.0
006     *  (the "License"); you may not use this file except in compliance with
007     *  the License.  You may obtain a copy of the License at
008     *
009     *     http://www.apache.org/licenses/LICENSE-2.0
010     *
011     *  Unless required by applicable law or agreed to in writing, software
012     *  distributed under the License is distributed on an "AS IS" BASIS,
013     *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     *  See the License for the specific language governing permissions and
015     *  limitations under the License.
016     */
017    package org.apache.geronimo.deployment.cli;
018    
019    import java.io.BufferedReader;
020    import java.io.IOException;
021    import java.io.InputStreamReader;
022    import java.io.PrintWriter;
023    import java.net.URL;
024    import java.util.ArrayList;
025    import java.util.HashMap;
026    import java.util.Iterator;
027    import java.util.List;
028    import java.util.Map;
029    
030    import javax.enterprise.deploy.spi.DeploymentManager;
031    import javax.security.auth.login.FailedLoginException;
032    
033    import org.apache.geronimo.cli.deployer.BaseCommandArgs;
034    import org.apache.geronimo.cli.deployer.CommandArgs;
035    import org.apache.geronimo.common.DeploymentException;
036    import org.apache.geronimo.deployment.plugin.GeronimoDeploymentManager;
037    import org.apache.geronimo.kernel.repository.Artifact;
038    import org.apache.geronimo.system.plugin.DownloadResults;
039    import org.apache.geronimo.system.plugin.PluginList;
040    import org.apache.geronimo.system.plugin.PluginMetadata;
041    
042    /**
043     * The CLI deployer logic to start.
044     *
045     * @version $Rev: 549455 $ $Date: 2007-06-21 08:12:27 -0400 (Thu, 21 Jun 2007) $
046     */
047    public class CommandListConfigurations extends AbstractCommand {
048    
049        //todo: provide a way to handle a username and password for the remote repo?
050    
051        public void execute(PrintWriter out, ServerConnection connection, CommandArgs commandArgs) throws DeploymentException {
052            DeploymentManager dmgr = connection.getDeploymentManager();
053            if(dmgr instanceof GeronimoDeploymentManager) {
054                GeronimoDeploymentManager mgr = (GeronimoDeploymentManager) dmgr;
055                try {
056                    String repo = null;
057                    if(commandArgs.getArgs().length == 1) {
058                        repo = commandArgs.getArgs()[0];
059                    } else {
060                        repo = getRepository(out, new BufferedReader(new InputStreamReader(System.in)), mgr);
061                    }
062                    PluginList data;
063                    URL repository;
064                    try {
065                        repository = new URL(repo);
066                        data = mgr.listPlugins(repository, null, null);
067                    } catch (IOException e) {
068                        throw new DeploymentException("Unable to list configurations", e);
069                    } catch (FailedLoginException e) {
070                        throw new DeploymentException("Invalid login for Maven repository '"+repo+"'", e);
071                    }
072                    if (data == null) {
073                        out.println();
074                        out.println("No plugins were returned from this site.");
075                        return;
076                    }
077                    Map categories = new HashMap();
078                    List available = new ArrayList();
079                    for (int i = 0; i < data.getPlugins().length; i++) {
080                        PluginMetadata metadata = data.getPlugins()[i];
081                        List list = (List) categories.get(metadata.getCategory());
082                        if(list == null) {
083                            list = new ArrayList();
084                            categories.put(metadata.getCategory(), list);
085                        }
086                        list.add(metadata);
087                    }
088                    for (Iterator it = categories.entrySet().iterator(); it.hasNext();) {
089                        Map.Entry entry = (Map.Entry) it.next();
090                        String category = (String) entry.getKey();
091                        List items = (List) entry.getValue();
092                        out.println();
093                        out.print(DeployUtils.reformat(category, 4, 72));
094                        for (int i = 0; i < items.size(); i++) {
095                            PluginMetadata metadata = (PluginMetadata) items.get(i);
096                            String prefix = "    ";
097                            if(!metadata.isInstalled() && metadata.isEligible()) {
098                                available.add(metadata);
099                                prefix = Integer.toString(available.size());
100                                if(available.size() < 10) {
101                                    prefix += " ";
102                                }
103                                prefix += ": ";
104                            }
105                            out.print(DeployUtils.reformat(prefix+metadata.getName()+" ("+metadata.getVersion()+")", 8, 72));
106                            out.flush();
107                        }
108                    }
109                    if(available.size() == 0) {
110                        out.println();
111                        out.println("No plugins from this site are eligible for installation.");
112                        return;
113                    }
114                    out.println();
115                    out.print("Install Service [enter number or 'q' to quit]: ");
116                    out.flush();
117                    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
118                    String answer = in.readLine();
119                    if(answer.equalsIgnoreCase("q")) {
120                        return;
121                    }
122                    int selection = Integer.parseInt(answer);
123                    PluginMetadata target = ((PluginMetadata) available.get(selection - 1));
124                    long start = System.currentTimeMillis();
125                    Object key = mgr.startInstall(PluginList.createInstallList(data, target.getModuleId()), null, null);
126                    DownloadResults results = CommandInstallCAR.showProgress(mgr, key);
127                    int time = (int)(System.currentTimeMillis() - start) / 1000;
128                    out.println();
129                    if(!results.isFailed()) {
130                        out.print(DeployUtils.reformat("**** Installation Complete!", 4, 72));
131                        for (int i = 0; i < results.getDependenciesPresent().length; i++) {
132                            Artifact uri = results.getDependenciesPresent()[i];
133                            out.print(DeployUtils.reformat("Used existing: "+uri, 4, 72));
134                        }
135                        for (int i = 0; i < results.getDependenciesInstalled().length; i++) {
136                            Artifact uri = results.getDependenciesInstalled()[i];
137                            out.print(DeployUtils.reformat("Installed new: "+uri, 4, 72));
138                        }
139                        out.println();
140                        out.print(DeployUtils.reformat("Downloaded "+(results.getTotalDownloadBytes()/1024)+" kB in "+time+"s ("+results.getTotalDownloadBytes()/(1024*time)+" kB/s)", 4, 72));
141                    }
142                    if(results.isFinished() && !results.isFailed()) {
143                        out.print(DeployUtils.reformat("Now starting "+target.getModuleId()+"...", 4, 72));
144                        out.flush();
145                        new CommandStart().execute(out, connection, new BaseCommandArgs(new String[]{target.getModuleId().toString()}));
146                    }
147                } catch (IOException e) {
148                    throw new DeploymentException("Unable to install configuration", e);
149                } catch(NumberFormatException e) {
150                    throw new DeploymentException("Invalid response");
151                }
152            } else {
153                throw new DeploymentException("Cannot list repositories when connected to "+connection.getServerURI());
154            }
155        }
156    
157        private String getRepository(PrintWriter out, BufferedReader in, GeronimoDeploymentManager mgr) throws IOException, DeploymentException {
158            URL[] all = mgr.getRepositories();
159            if(all.length == 0) {
160                throw new DeploymentException("No default repositories available.  Please either specify the repository " +
161                        "URL on the command line, or go into the console Plugin page and update the list of available " +
162                        "repositories.");
163            }
164            out.println();
165            out.println("Select repository:");
166            for (int i = 0; i < all.length; i++) {
167                URL url = all[i];
168                out.println("  "+(i+1)+". "+url);
169            }
170            out.println();
171            out.print("Enter Repository Number: ");
172            out.flush();
173            String entry = in.readLine().trim();
174            int index = Integer.parseInt(entry);
175            return all[index-1].toString();
176        }
177    }