29d7abd85ae1e65e2c419cf749d8c879209042f2
[controller.git] / opendaylight / netconf / netconf-cli / src / test / java / org / opendaylight / controller / netconf / cli / ConsoleIOTestImpl.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.netconf.cli;
9
10 import java.io.IOException;
11 import java.util.Deque;
12 import java.util.HashMap;
13 import java.util.List;
14 import java.util.Map;
15 import org.opendaylight.controller.netconf.cli.io.ConsoleIOImpl;
16
17 public class ConsoleIOTestImpl extends ConsoleIOImpl {
18
19     Map<String, Deque<String>> inputValues = new HashMap<>();
20     String lastMessage;
21     private final List<ValueForMessage> valuesForMessages;
22
23     public ConsoleIOTestImpl(final Map<String, Deque<String>> inputValues, final List<ValueForMessage> valuesForMessages)
24             throws IOException {
25         super();
26         this.inputValues = inputValues;
27         this.valuesForMessages = valuesForMessages;
28     }
29
30     StringBuilder output = new StringBuilder();
31
32     @Override
33     public String read() throws IOException {
34         final String prompt = buildPrompt();
35         output.append(prompt);
36         System.out.print(prompt);
37
38         String value = inputValues.get(prompt).pollFirst();
39         if (value == null) {
40             value = getValueForLastMessage();
41         }
42
43         value = value != null ? value : "****NO VALUE****";
44
45         output.append(value + "\n");
46         System.out.print(value + "\n");
47         return value;
48     }
49
50     private String getValueForLastMessage() {
51         for (final ValueForMessage valueForMessage : valuesForMessages) {
52             if (containsLastMessageKeyWords(valueForMessage.getKeyWords())) {
53                 return valueForMessage.getValue();
54             }
55         }
56         return null;
57     }
58
59     private boolean containsLastMessageKeyWords(final List<String> keyWords) {
60         for (final String keyWord : keyWords) {
61             if (!lastMessage.contains(keyWord)) {
62                 return false;
63             }
64         }
65         return true;
66     }
67
68     @Override
69     public void write(final CharSequence data) throws IOException {
70         output.append(data);
71         lastMessage = (String) data;
72         System.out.print(data);
73     }
74
75     @Override
76     public void writeLn(final CharSequence data) throws IOException {
77         write(data);
78         output.append("\n");
79         System.out.print("\n");
80     }
81
82     public String getConsoleOutput() {
83         return output.toString();
84     }
85 }