aboutsummaryrefslogtreecommitdiff
path: root/src/org/gnunet/util/Program.java
blob: a5cd1474c135d15dc9be0a0b5b9b09cdb4b3c029 (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
/*
 This file is part of GNUnet.
 (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.Option;
import org.gnunet.util.getopt.OptionAction;
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.
 *
 * @see Service
 */
public abstract class Program {
    private static final Logger logger = LoggerFactory
            .getLogger(Program.class);


    protected final Configuration cfg = new Configuration();

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

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

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


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

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


    protected String[] unprocessedArgs;

    private final String[] args;


    /**
     * A program with the desired environment for a gnunet utility.
     * While executing the scheduler is guaranteed to run, command arguments are parsed,
     * the default configuration is loaded and the DNS Resolver is initialized.
     *
     * @param args array of command line arguments to parse. used to automatically load additional settings
     *             and configure log levels.
     */
    public Program(String... args) {
        this.args = args;

        /*
         * Remember: We can't parse command line arguments here, as java's initialization order
         * dictates that member variables of subclasses are initialized *after* the superclass constructor (here).
         */
    }

    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);
        }
    }

    /**
     * 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";
    }

    /**
     * Start the Program as the initial task of the Scheduler.
     */
    public void start() {
        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 {
            Scheduler.run(new Scheduler.Task() {
                public void run(Scheduler.RunContext c) {
                    Program.this.run();
                }
            });
        }
    }

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

    public final Configuration getConfiguration() {
        return cfg;
    }
}