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 DNA repository and sequencing service ... ");
045                client.startRepository();
046                System.out.println("done.");
047                System.out.println();
048    
049                System.out.println(getMenu());
050                Thread eventThread = new Thread(new Runnable() {
051    
052                    private boolean quit = false;
053    
054                    public void run() {
055                        try {
056                            while (!quit) {
057                                System.out.print(">");
058                                try {
059                                    String input = in.readLine();
060                                    if (input.length() != 1) {
061                                        System.out.println("Please enter a valid option.");
062                                        continue;
063                                    }
064    
065                                    char option = input.charAt(0);
066                                    switch (option) {
067                                        case 'u':
068                                            client.uploadFile();
069                                            break;
070                                        case 's':
071                                            client.search();
072                                            break;
073                                        case 'm':
074                                        case '?':
075                                        case 'h':
076                                            System.out.println(getMenu());
077                                            break;
078                                        case 'd':
079                                            System.out.println(getStatistics(client.getStatistics()));
080                                            break;
081                                        case 'q':
082                                            quit = true;
083                                            break;
084                                        default:
085                                            System.out.println("Invalid option.");
086                                            break;
087                                    }
088                                } catch (NumberFormatException e) {
089                                    System.out.println("Invalid integer " + e.getMessage());
090                                } catch (IllegalArgumentException e) {
091                                    System.out.println(e.getMessage());
092                                } catch (IOException e) {
093                                    e.printStackTrace();
094                                } catch (Throwable e) {
095                                    e.printStackTrace();
096                                }
097                            }
098                        } finally {
099                            try {
100                                // Terminate ...
101                                System.out.println();
102                                System.out.print("Shutting down repository ... ");
103                                client.shutdownRepository();
104                                System.out.print("done.");
105                                System.out.println();
106                                System.out.println();
107                            } catch (Exception err) {
108                                System.out.println("Error shutting down sequencing service and repository: "
109                                                   + err.getLocalizedMessage());
110                                err.printStackTrace(System.err);
111                            }
112                        }
113                    }
114                });
115    
116                eventThread.start();
117            } catch (Exception err) {
118                System.out.println("Error: " + err.getLocalizedMessage());
119                err.printStackTrace(System.err);
120            }
121        }
122    
123        protected String getMenu() {
124            StringBuilder buffer = new StringBuilder();
125            buffer.append("-----------------------------------\n");
126            buffer.append("Menu:\n");
127            buffer.append("\n");
128            buffer.append("u) Upload a file to the repository\n");
129            buffer.append("s) Search the repository using extracted metadata\n");
130            buffer.append("\n");
131            buffer.append("d) Display statistics\n");
132            buffer.append("\n");
133            buffer.append("?) Show this menu\n");
134            buffer.append("q) Quit");
135            return buffer.toString();
136        }
137    
138        /**
139         * {@inheritDoc}
140         */
141        public URL getFileToUpload() throws IllegalArgumentException, IOException {
142            System.out.println("Please enter the file to upload:");
143            String path = in.readLine();
144            File file = new File(path);
145            if (!file.exists()) {
146                throw new IllegalArgumentException("The file \"" + file.getAbsolutePath() + "\" does not exist.");
147            }
148            if (!file.canRead()) {
149                throw new IllegalArgumentException("Unable to read \"" + file.getAbsolutePath() + "\".");
150            }
151            if (!file.isFile()) {
152                throw new IllegalArgumentException("Please specify a file.  The file \"" + file.getAbsolutePath()
153                                                   + "\" is a directory.");
154            }
155            return file.toURI().toURL();
156        }
157    
158        public String getRepositoryPath( String defaultPath ) throws IllegalArgumentException, IOException {
159            if (defaultPath != null) defaultPath = defaultPath.trim();
160            if (defaultPath.length() == 0) defaultPath = null;
161            String displayDefaultPath = defaultPath == null ? "" : " [" + defaultPath.trim() + "]";
162            System.out.println("Please enter the repository path where the file should be placed" + displayDefaultPath + ":");
163            String path = in.readLine().trim();
164            if (path.length() == 0) {
165                if (defaultPath == null) {
166                    throw new IllegalArgumentException("The path \"" + path + "\" is not valid.");
167                }
168                path = defaultPath;
169            }
170            return path;
171        }
172    
173        public void displaySearchResults( List<ContentInfo> contentInfos ) {
174            System.out.println();
175            if (contentInfos.isEmpty()) {
176                System.out.println("No results were found.");
177                System.out.println();
178                return;
179            }
180            if (contentInfos.size() == 1) {
181                System.out.println("1 result was found:");
182            } else {
183                System.out.println("" + contentInfos.size() + " results were found:");
184            }
185            int counter = 1;
186            for (ContentInfo info : contentInfos) {
187                System.out.println(" " + info.getInfoType() + " " + counter++);
188                System.out.println(info.toString());
189            }
190            System.out.println();
191        }
192    
193        public String getStatistics( SequencingService.Statistics stats ) {
194            StringBuilder sb = new StringBuilder();
195            sb.append("\n");
196            sb.append("# nodes sequenced: ").append(stats.getNumberOfNodesSequenced()).append("\n");
197            sb.append("# nodes skipped: ").append(stats.getNumberOfNodesSkipped()).append("\n");
198            sb.append("\n");
199            return sb.toString();
200        }
201    
202        public void displayError( Exception e ) {
203            System.err.println(e.getMessage());
204        }
205    }