001    /*
002     * JBoss DNA (http://www.jboss.org/dna)
003     * See the COPYRIGHT.txt file distributed with this work for information
004     * regarding copyright ownership.  Some portions may be licensed
005     * to Red Hat, Inc. under one or more contributor license agreements.
006     * See the AUTHORS.txt file in the distribution for a full listing of 
007     * individual contributors. 
008     *
009     * JBoss DNA is free software. Unless otherwise indicated, all code in JBoss DNA
010     * is licensed to you under the terms of the GNU Lesser General Public License as
011     * published by the Free Software Foundation; either version 2.1 of
012     * the License, or (at your option) any later version.
013     *
014     * JBoss DNA is distributed in the hope that it will be useful,
015     * but WITHOUT ANY WARRANTY; without even the implied warranty of
016     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
017     * Lesser General Public License for more details.
018     *
019     * You should have received a copy of the GNU Lesser General Public
020     * License along with this software; if not, write to the Free
021     * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
022     * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
023     */
024    package org.jboss.example.dna.sequencer;
025    
026    import java.io.BufferedReader;
027    import java.io.File;
028    import java.io.IOException;
029    import java.io.InputStreamReader;
030    import java.net.URL;
031    import java.util.List;
032    import org.jboss.dna.repository.sequencer.SequencingService;
033    
034    /**
035     * @author Randall Hauch
036     */
037    public class ConsoleInput implements UserInterface {
038    
039        protected static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
040    
041        public ConsoleInput( final SequencingClient client ) {
042            try {
043                System.out.println();
044                System.out.print("Starting repository and sequencing service ... ");
045                client.startRepository();
046                System.out.print("done.\nStarting sequencing service ... ");
047                client.startDnaServices();
048                System.out.println("done.");
049                System.out.println();
050    
051                System.out.println(getMenu());
052                Thread eventThread = new Thread(new Runnable() {
053    
054                    private boolean quit = false;
055    
056                    public void run() {
057                        try {
058                            while (!quit) {
059                                System.out.print(">");
060                                try {
061                                    String input = in.readLine();
062                                    if (input.length() != 1) {
063                                        System.out.println("Please enter a valid option.");
064                                        continue;
065                                    }
066    
067                                    char option = input.charAt(0);
068                                    switch (option) {
069                                        case 'u':
070                                            client.uploadFile();
071                                            break;
072                                        case 's':
073                                            client.search();
074                                            break;
075                                        case 'm':
076                                        case '?':
077                                        case 'h':
078                                            System.out.println(getMenu());
079                                            break;
080                                        case 'd':
081                                            System.out.println(getStatistics(client.getStatistics()));
082                                            break;
083                                        case 'q':
084                                            quit = true;
085                                            break;
086                                        default:
087                                            System.out.println("Invalid option.");
088                                            break;
089                                    }
090                                } catch (NumberFormatException e) {
091                                    System.out.println("Invalid integer " + e.getMessage());
092                                } catch (IllegalArgumentException e) {
093                                    System.out.println(e.getMessage());
094                                } catch (IOException e) {
095                                    e.printStackTrace();
096                                } catch (Throwable e) {
097                                    e.printStackTrace();
098                                }
099                            }
100                        } finally {
101                            try {
102                                // Terminate ...
103                                System.out.println();
104                                System.out.print("Shutting down sequencing service ... ");
105                                client.shutdownDnaServices();
106                                System.out.print("done.\nShutting down repository ... ");
107                                client.shutdownRepository();
108                                System.out.print("done.");
109                                System.out.println();
110                                System.out.println();
111                            } catch (Exception err) {
112                                System.out.println("Error shutting down sequencing service and repository: "
113                                                   + err.getLocalizedMessage());
114                                err.printStackTrace(System.err);
115                            }
116                        }
117                    }
118                });
119    
120                eventThread.start();
121            } catch (Exception err) {
122                System.out.println("Error: " + err.getLocalizedMessage());
123                err.printStackTrace(System.err);
124            }
125        }
126    
127        protected String getMenu() {
128            StringBuilder buffer = new StringBuilder();
129            buffer.append("-----------------------------------\n");
130            buffer.append("Menu:\n");
131            buffer.append("\n");
132            buffer.append("u) Upload a file to the repository\n");
133            buffer.append("s) Search the repository using extracted metadata\n");
134            buffer.append("\n");
135            buffer.append("d) Display statistics\n");
136            buffer.append("\n");
137            buffer.append("?) Show this menu\n");
138            buffer.append("q) Quit");
139            return buffer.toString();
140        }
141    
142        /**
143         * {@inheritDoc}
144         */
145        public URL getFileToUpload() throws IllegalArgumentException, IOException {
146            System.out.println("Please enter the file to upload:");
147            String path = in.readLine();
148            File file = new File(path);
149            if (!file.exists()) {
150                throw new IllegalArgumentException("The file \"" + file.getAbsolutePath() + "\" does not exist.");
151            }
152            if (!file.canRead()) {
153                throw new IllegalArgumentException("Unable to read \"" + file.getAbsolutePath() + "\".");
154            }
155            if (!file.isFile()) {
156                throw new IllegalArgumentException("Please specify a file.  The file \"" + file.getAbsolutePath()
157                                                   + "\" is a directory.");
158            }
159            return file.toURI().toURL();
160        }
161    
162        public String getRepositoryPath( String defaultPath ) throws IllegalArgumentException, IOException {
163            if (defaultPath != null) defaultPath = defaultPath.trim();
164            if (defaultPath.length() == 0) defaultPath = null;
165            String displayDefaultPath = defaultPath == null ? "" : " [" + defaultPath.trim() + "]";
166            System.out.println("Please enter the repository path where the file should be placed" + displayDefaultPath + ":");
167            String path = in.readLine().trim();
168            if (path.length() == 0) {
169                if (defaultPath == null) {
170                    throw new IllegalArgumentException("The path \"" + path + "\" is not valid.");
171                }
172                path = defaultPath;
173            }
174            return path;
175        }
176    
177        public void displaySearchResults( List<ContentInfo> contentInfos ) {
178            System.out.println();
179            if (contentInfos.isEmpty()) {
180                System.out.println("No results were found.");
181                System.out.println();
182                return;
183            }
184            if (contentInfos.size() == 1) {
185                System.out.println("1 result was found:");
186            } else {
187                System.out.println("" + contentInfos.size() + " results were found:");
188            }
189            int counter = 1;
190            for (ContentInfo info : contentInfos) {
191                System.out.println(" " + info.getInfoType() + " " + counter++);
192                System.out.println(info.toString());
193            }
194            System.out.println();
195        }
196    
197        public String getStatistics( SequencingService.Statistics stats ) {
198            StringBuilder sb = new StringBuilder();
199            sb.append("\n");
200            sb.append("# nodes sequenced: ").append(stats.getNumberOfNodesSequenced()).append("\n");
201            sb.append("# nodes skipped: ").append(stats.getNumberOfNodesSkipped()).append("\n");
202            sb.append("\n");
203            return sb.toString();
204        }
205    }