001 /*
002 *
003 * ====================================================================
004 *
005 * Copyright 2004 The Apache Software Foundation
006 *
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 * http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 *
019 */
020 package org.apache.commons.contract.util;
021
022 import java.io.BufferedReader;
023 import java.io.IOException;
024 import java.io.InputStreamReader;
025 import java.util.HashMap;
026 import java.util.Locale;
027 import java.util.Map;
028
029 import org.apache.commons.contract.Context;
030 import org.apache.commons.contract.ContractViolationException;
031 import org.apache.commons.contract.Executor;
032 import org.apache.commons.contract.Processor;
033 import org.apache.commons.contract.Result;
034 import org.apache.commons.contract.context.VMContext;
035 import org.apache.commons.contract.descriptor.ParameterDescriptor;
036 import org.apache.commons.contract.i18n.ParameterBundle;
037
038 public class InteractiveMainWrapper extends MainWrapper {
039 public static Result main(String []args, Processor processor) {
040 Executor.init();
041 printUsage(processor);
042 Context context = new VMContext();
043 ParameterDescriptor[] parameterDescriptors = processor.getParameterDescriptors();
044 Map parameters = new HashMap();
045 BufferedReader in = new BufferedReader( new InputStreamReader( System.in ) );
046 for ( int i = 0; i < parameterDescriptors.length; i++ ) {
047 Object value = null;
048 do {
049 System.out.print(parameterDescriptors[i].getName()+" - ");
050 printParameterInfo(parameterDescriptors[i]);
051 System.out.print(((ParameterBundle)parameterDescriptors[i].getDescription()).getPrompt(Locale.getDefault()));
052 try {
053 String userInput = in.readLine();
054 value = Executor.prepareValue(parameterDescriptors[i], userInput, context);
055 } catch (IOException e) {
056 value = null;
057 } catch (ContractViolationException e) {
058 printException(e);
059 value = null;
060 }
061 } while ( value == null );
062 parameters.put(parameterDescriptors[i].getName(), value);
063 }
064 try {
065 Result result = Executor.process(processor, parameters, context);
066 printInformations(context.getInformations());
067 return result;
068 } catch ( ContractViolationException exception ) {
069 printException(exception);
070 System.out.println();
071 printUsage(processor);
072 } catch ( Exception exception ) {
073 exception.printStackTrace();
074 }
075 return null;
076 }
077 }