aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/gnunet/util/Program.java
blob: 34ee01e281eb0cff3c3988a154bdca66d2800150 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/*
 This file is part of GNUnet.
 Copyright (C) 2011, 2012 Christian Grothoff (and other contributing authors)

 GNUnet is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published
 by the Free Software Foundation; either version 3, or (at your
 option) any later version.

 GNUnet is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GNUnet; see the file COPYING.  If not, write to the
 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 Boston, MA 02111-1307, USA.
 */

package org.gnunet.util;

import org.apache.log4j.*;
import org.gnunet.util.getopt.Argument;
import org.gnunet.util.getopt.ArgumentAction;
import org.gnunet.util.getopt.Parser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;


/**
 * Program is the entry point class for everything that uses GNUnet services or APIs.
 *
 * Also specifies the default command line arguments using the org.gnunet.util.getopt annotations.
 *
 * @see Service
 */
public abstract class Program {
    private static final Logger logger = LoggerFactory
            .getLogger(Program.class);


    protected final Configuration cfg = new Configuration();

    @Argument(shortname = "c", longname = "config",
            description = "path of the configuration file",
            argumentName = "FILENAME",
            action = ArgumentAction.STORE_STRING)
    public String cfgFileName;

    @Argument(shortname = "h", longname = "help",
            description = "print this help message",
            action = ArgumentAction.SET)
    public boolean printHelp;

    @Argument(shortname = "v", longname = "version",
            description = "print version",
            action = ArgumentAction.SET)
    public boolean showVersion;


    @Argument(shortname = "L", longname = "log",
            description = "configure logging to use LOGLEVEL",
            argumentName = "LOGLEVEL",
            action = ArgumentAction.STORE_STRING)
    public String logLevel;

    @Argument(shortname = "l", longname = "logfile",
            description = "configure logging to write logs to LOGFILE",
            argumentName = "LOGFILE",
            action = ArgumentAction.STORE_STRING)
    public String logFile;

    /**
     * Positional arguments, excluding those that have been processed
     * by the command line parser.
     */
    protected String[] unprocessedArgs;

    /**
     * Return value for the program.
     * We prefer setting the return value, as System.exit(...) does bad things sometimes.
     * (In JUnit test cases, for instance)
     */
    private int returnValue = 0;

    /**
     * Configure logging with the given log level and log file.
     *
     * @param logLevel one of DEBUG,INFO,WARN,ERROR,OFF
     * @param logFile logfile, absolute or relative to the current working directory
     */
    public static void configureLogging(String logLevel, String logFile) {
        org.apache.log4j.Logger rootLogger = LogManager.getRootLogger();

        rootLogger.removeAllAppenders();

        // %c{2}: category 2 levels
        Layout layout = new PatternLayout("%d{dd MMM yyyy HH:mm:ss-SSS} %c{2} %p: %m%n");

        if (logFile == null) {
            rootLogger.addAppender(new ConsoleAppender(layout, ConsoleAppender.SYSTEM_OUT));
        } else {
            Appender appender = null;
            try {
                appender = new FileAppender(layout, logFile);
            } catch (IOException e) {
                logger.warn("could not open log file {}", logFile);
            }
            if (appender!= null) {
                rootLogger.removeAllAppenders();
                rootLogger.addAppender(appender);
            }
        }
        if (logLevel == null) {
            rootLogger.setLevel(Level.INFO);
        } else if (logLevel.equalsIgnoreCase("debug")) {
            rootLogger.setLevel(Level.DEBUG);
        } else if (logLevel.equalsIgnoreCase("info")) {
            rootLogger.setLevel(Level.INFO);
        } else if (logLevel.equalsIgnoreCase("warn") || logLevel.equalsIgnoreCase("warning")) {
            rootLogger.setLevel(Level.WARN);
        } else if (logLevel.equalsIgnoreCase("error")) {
            rootLogger.setLevel(Level.ERROR);
        } else if (logLevel.equalsIgnoreCase("off")) {
            rootLogger.setLevel(Level.OFF);
        } else {
            rootLogger.setLevel(Level.INFO);
            logger.info("unknown log level '{}'; defaulting to INFO", logLevel);
        }
    }

    public static void configureLogging(String logLevel) {
        configureLogging(logLevel, null);
    }

    public static void configureLogging() {
        configureLogging(null, null);
    }


    /**
     * Override to display a different help text on "-h/--help"
     *
     * @return the help text
     */
    protected String makeHelpText() {
        return "gnunet-java tool";
    }

    /**
     * Override to display a different version description on "-h/--help"
     *
     * @return version description
     */
    protected String makeVersionDescription() {
        return "development version of gnunet-java";
    }

    final protected void setReturnValue(int x) {
        returnValue = x;
    }

    /**
     * Overridden by specializations of Program, like Service.
     *
     * Allows for start() to be final.
     */
    /* package-private */
    void runHook() {
        run();
    }

    /**
     * Override to implement the behavior of the Program.
     */
    protected abstract void run();

    protected final Configuration getConfiguration() {
        return cfg;
    }


    /**
     * Start the Program.  Invokes the run method.
     *
     * @param withScheduler determines whether the run-method
     *                      is invoked inside a scheduler task or not
     * @return the exit value of the program
     */
    public final int start(boolean withScheduler, String... args) {
        Parser optParser = new Parser(this);
        unprocessedArgs = optParser.parse(args);

        configureLogging(logLevel, logFile);

        cfg.loadDefaults();

        if (cfgFileName != null) {
            cfg.parse(cfgFileName);
        }

        Resolver.getInstance().setConfiguration(cfg);

        if (showVersion) {
            System.out.println(makeVersionDescription());
        } else if (printHelp) {
            System.out.println(makeHelpText());
            System.out.print(optParser.getHelp());
        } else {
            if (withScheduler) {
                Scheduler.run(new Scheduler.Task() {
                    public void run(Scheduler.RunContext c) {
                        Program.this.runHook();
                    }
                });
            } else {
                Program.this.runHook();
            }
        }

        if (Scheduler.hasTasks()) {
            logger.error("scheduler still has pending tasks after program returned");
        }

        return returnValue;
    }


    /**
     * Start the Program as the initial task of the Scheduler.
     *
     * @return the exit value of the program
     */
    public final int start(String... args) {
        return start(true, args);
    }


    /**
     * Start the program without setting up the scheduler.
     *
     * @return the exit value of the program
     */
    public final int startWithoutScheduler(String... args) {
        return start(false, args);
    }
}