source: trunk/java-utils/src/main/java/de/ugoe/cs/util/console/TextConsole.java

Last change on this file was 1355, checked in by pharms, 10 years ago
  • improved logging
File size: 5.1 KB
Line 
1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
15package de.ugoe.cs.util.console;
16
17import java.io.IOException;
18import java.nio.charset.Charset;
19import java.text.SimpleDateFormat;
20import java.util.Date;
21import java.util.logging.Level;
22
23import de.ugoe.cs.util.console.listener.IErrorListener;
24import de.ugoe.cs.util.console.listener.IExceptionListener;
25import de.ugoe.cs.util.console.listener.IOutputListener;
26import de.ugoe.cs.util.console.listener.ITraceListener;
27
28/**
29 * <p>
30 * Implements a simple console observer that prints normal text to {@code stdout}, errors to
31 * {@code stderr} and reads from {@code stdin}.
32 * </p>
33 *
34 * @author Steffen Herbold
35 * @version 1.0
36 */
37public class TextConsole implements IOutputListener, IErrorListener, ITraceListener,
38    IExceptionListener
39{
40
41    /**
42     * <p>
43     * Defines the trace level used by this console.
44     * </p>
45     */
46    private Level traceLevel;
47
48    private final SimpleDateFormat ft = new SimpleDateFormat("HH:mm:ss");
49
50    /**
51     * <p>
52     * Creates a new text console and automatically registers it as observer. The trace level is
53     * {@link Level#WARNING}.
54     * </p>
55     */
56    public TextConsole() {
57        this(Level.WARNING);
58    }
59
60    /**
61     * <p>
62     * Creates a new text console and automatically registers it as observer.
63     * </p>
64     *
65     * @param traceLevel
66     *            trace level used by this text console
67     */
68    public TextConsole(Level traceLevel) {
69        Console.getInstance().registerOutputListener(this);
70        Console.getInstance().registerErrorListener(this);
71        Console.getInstance().registerTraceListener(this);
72        Console.getInstance().registerExceptionListener(this);
73        this.traceLevel = traceLevel;
74    }
75
76    /**
77     * <p>
78     * Prints messages to {@code stdout}.
79     * </p>
80     *
81     * @see ConsoleObserver#outputMsg(java.lang.String)
82     */
83    public void outputMsg(String newMessage) {
84        System.out.print(newMessage);
85    }
86
87    /**
88     * <p>
89     * Prints messages to {@code stderr}.
90     * </p>
91     *
92     * @see ConsoleObserver#errorMsg(String)
93     */
94    @Override
95    public void errorMsg(String errMessage) {
96        System.err.print(errMessage);
97    }
98
99    /**
100     * <p>
101     * Prints the stacktrace of an exception to {@code stderr} if the log level is more or equally
102     * detailed to <code>Level.FINE</code>. Otherwise, it just prints a line naming the exception
103     * or only the message, if any.
104     * </p>
105     *
106     * @see ConsoleObserver#logException(Exception)
107     */
108    @Override
109    public void logException(Exception e) {
110        if (traceLevel.intValue() > Level.FINE.intValue()) {
111            if (e.getMessage() != null) {
112                System.err.println(e.getMessage());
113            }
114            else {
115                System.err.println(e);
116            }
117        }
118        else {
119            e.printStackTrace(System.err);
120        }
121    }
122
123    /**
124     * <p>
125     * Prints messages to {@code stdout}. These messages are only printed, if the console is run in
126     * debug mode.
127     * </p>
128     */
129    @Override
130    public void traceMsg(String traceMessage, Level level) {
131        if (level.intValue() >= traceLevel.intValue()) {
132            System.out.print("[" + level.toString() + "] [" + ft.format(new Date()) + "] " +
133                traceMessage);
134        }
135    }
136
137    /**
138     * <p>
139     * Starts a new TextConsole. If the text console is started, it can be used not only to print
140     * message, but also to execute commands by reading {@code stdin}.
141     * </p>
142     */
143    public void run() {
144        CommandExecuter exec = CommandExecuter.getInstance();
145        while (true) {
146            System.out.print("> ");
147            String command = getCommand().trim();
148            if (!command.equals("")) {
149                exec.exec(command);
150            }
151        }
152    }
153
154    /**
155     * <p>
156     * Reads a new command from {@code stdin}.
157     * </p>
158     *
159     * @return a string with a command
160     */
161    protected String getCommand() {
162        byte[] buffer = new byte[1024];
163        int bytesRead = 0;
164        String command;
165        try {
166            bytesRead = System.in.read(buffer);
167        }
168        catch (IOException e) {
169
170        }
171        if (bytesRead == 0) {
172            command = "";
173        }
174        else {
175            command = new String(buffer, Charset.defaultCharset());
176        }
177        return command;
178    }
179
180}
Note: See TracBrowser for help on using the repository browser.