summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/App.java
blob: ed2645ffe858a72062fe8e79e071e2cd536a5885 (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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
package org.openslx.dozmod;

import java.awt.AWTEvent;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ContainerEvent;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.SSLContext;
import javax.swing.SwingUtilities;
import javax.swing.UIDefaults;
import javax.swing.UIManager;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;
import org.openslx.dozmod.Config.ProxyMode;
import org.openslx.dozmod.gui.Gui;
import org.openslx.dozmod.gui.MainWindow;
import org.openslx.dozmod.gui.helper.MessageType;
import org.openslx.dozmod.util.ClientVersion;
import org.openslx.dozmod.util.ProxyConfigurator;
import org.openslx.thrifthelper.ThriftManager;
import org.openslx.util.Util;

public class App {

	// Logger
	private final static Logger LOGGER = Logger.getLogger(App.class);

	public static final String MASTER_SERVER_ADDRESS = "bwlp-masterserver.ruf.uni-freiburg.de";

	public static final int THRIFT_PORT = 9090;

	public static final int THRIFT_SSL_PORT = THRIFT_PORT + 1;

	public static final int THRIFT_TIMEOUT_MS = 15000;

	private static Thread proxyThread = null;

	private static void setupLogger() {

		// path to the log file
		final String logFilePath = Config.getPath() + File.separator + "bwSuite.log";

		// check if we had an old log file
		final File logFile = new File(logFilePath);
		if (logFile.exists() && !logFile.isDirectory()) {
			// we have one, rename it to 'bwSuite.log.old'
			LOGGER.info("renaming old log file");
			try {
				File oldFile = new File(logFilePath + ".old");
				oldFile.delete();
				logFile.renameTo(oldFile);
				logFile.delete();
			} catch (Exception e) {
				LOGGER.error("Could not move '" + logFilePath + "' to '" + logFilePath + ".old'", e);
			}
		}

		// add file appender to global logger
		FileAppender fa = null;
		try {
			fa = new FileAppender(new PatternLayout("%d [%F:%M] %m%n"), logFilePath);
			// All classes should log to file, configure global file appender.
		} catch (IOException e) {
			e.printStackTrace();
			BasicConfigurator.configure();
			return;
		}

		final FileAppender ffa = fa;
		final Pattern re = Pattern.compile("authorization:(\\w|\\+|/|\\s)+", Pattern.CASE_INSENSITIVE
				| Pattern.MULTILINE);

		AppenderSkeleton ap = new AppenderSkeleton() {

			@Override
			public boolean requiresLayout() {
				return ffa.requiresLayout();
			}

			@Override
			public void close() {
				ffa.close();
			}

			@Override
			protected void append(LoggingEvent event) {
				String s = event.getRenderedMessage();
				if (s.contains("uthorization")) {
					Matcher m = re.matcher(s);
					if (m.find()) {
						s = m.replaceAll("Authorization: ***********");
					}
				}
				ffa.append(new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(),
						event.getTimeStamp(), event.getLevel(), s, event.getThreadName(),
						event.getThrowableInformation(), event.getNDC(), event.getLocationInformation(),
						event.getProperties()));
			}
		};

		BasicConfigurator.configure(ap);
		LOGGER.info("Starting logging to: " + logFilePath);
	}

	public static void main(final String[] args) throws InvocationTargetException, InterruptedException {
		if (args.length >= 2 && args[0].equals("--json")) {
			writeJsonUpdateFile(args[1]);
			return;
		}
		try {
			Config.init();
		} catch (Exception e) {
			Gui.showMessageBox(null, "Error loading configuration", MessageType.ERROR, LOGGER, e);
			return;
		}

		setupLogger();

		if (Config.getProxyMode() == ProxyMode.AUTO) {
			// Initialize the proxy settings
			proxyThread = new Thread() {
				@Override
				public void run() {
					ProxyConfigurator.init();
				}
			};
			proxyThread.start();
		}

		// Setup swing style
		System.setProperty("awt.useSystemAAFontSettings", "on");
		System.setProperty("swing.aatext", "true");
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
		} catch (Exception e1) {
			try {
				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
			} catch (Exception e) {
			}
		}
		// Adjust font size
		adjustFontSize(Config.getFontScaling());

		// Set up connection to master server
		final String host;
		int port;
		boolean useSsl;
		if (args.length == 3) {
			host = args[0];
			port = Util.parseInt(args[1], -1);
			useSsl = Boolean.getBoolean(args[2]);
		} else {
			host = MASTER_SERVER_ADDRESS;
			port = THRIFT_SSL_PORT;
			useSsl = true;
		}
		if (useSsl) {
			try {
				SSLContext ctx = SSLContext.getInstance("TLSv1.2");
				ctx.init(null, null, null);
				ThriftManager.setMasterServerAddress(ctx, host, port, THRIFT_TIMEOUT_MS);
			} catch (final Exception e1) {
				SwingUtilities.invokeAndWait(new Runnable() {
					@Override
					public void run() {
						boolean ret = Gui.showMessageBox(null,
								"SSL nicht verfügbar. Wollen Sie sich trotzdem unverschlüsselt verbinden?",
								MessageType.QUESTION_YESNO, LOGGER, e1);
						if (!ret) {
							System.exit(1);
						}
					}
				});
				useSsl = false;
				port = port - 1; // This assumes SSL port is always plain port + 1
			}
		}
		// No "else", might be fallback for failed SSL
		if (!useSsl) {
			ThriftManager.setMasterServerAddress(null, host, port, THRIFT_TIMEOUT_MS);
		}

		// Setup global thrift connection error handler and then open the GUI
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
					@Override
					public void uncaughtException(Thread t, Throwable e) {
						Gui.showMessageBox(null, "Ungefangene Ausnahme in Faden " + t.getName() + "\n\n"
								+ "Die Anwendung könnte instabil laufen.\n"
								+ "Zur Sicherheit sollten Sie sie neustarten.", MessageType.WARNING, LOGGER,
								e);
					}
				});
				MainWindow.open();
			}
		});
	}

	private static void writeJsonUpdateFile(String destination) {
		try {
			ClientVersion.createJson(destination);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void adjustFontSize(int percent) {
		if (percent == 100 || percent <= 0 || percent > 1000)
			return;
		final float scaling = 0.01f * (float) percent;
		int size = determineDefaultFontSize(UIManager.getLookAndFeelDefaults());
		if (size == -1) {
			size = determineDefaultFontSize(UIManager.getDefaults());
		}
		if (size == -1) {
			size = 12;
		}
		final float defaultSize = size;
		Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
			@Override
			public void eventDispatched(AWTEvent event) {
				if (event instanceof ContainerEvent) {
					ContainerEvent containerEvent = (ContainerEvent) event;
					if (containerEvent.getID() == ContainerEvent.COMPONENT_ADDED) {
						Font font = containerEvent.getChild().getFont();
						if (font != null && font.getSize2D() <= defaultSize) {
							containerEvent.getChild().setFont(
									new Font(font.getName(), font.getStyle(), Math.round(font.getSize2D()
											* scaling)));
						}
					}
				}
			}
		}, AWTEvent.COMPONENT_EVENT_MASK | AWTEvent.CONTAINER_EVENT_MASK);
		Font tbFont = UIManager.getFont("TitledBorder.font");
		if (tbFont != null) {
			UIManager.put("TitledBorder.font", tbFont.deriveFont(tbFont.getSize2D() * scaling));
		}
	}

	private static int determineDefaultFontSize(UIDefaults defaults) {
		if (defaults == null)
			return -1;
		int sizes[] = new int[100];
		Set<Object> keys = new HashSet<>(defaults.keySet());
		for (Object key : keys) {
			if (key == null)
				continue;
			Object value = defaults.get(key);
			if (value == null)
				continue;
			if (value instanceof Font) {
				Font font = (Font) value;
				if (font.getSize() > 0 && font.getSize() < sizes.length) {
					sizes[font.getSize()]++;
				}
			}
		}
		int best = -1;
		for (int index = 0; index < sizes.length; ++index) {
			if (best == -1 || sizes[best] < sizes[index]) {
				best = index;
			}
		}
		return sizes[best];
	}

	/**
	 * Blocks as long as initialization is still going on. Currently this is
	 * just the proxy setup, so this should be used before any network
	 * communication happens.
	 */
	public static synchronized void waitForInit() {
		if (proxyThread == null)
			return;
		try {
			proxyThread.join();
		} catch (InterruptedException e) {
		}
		proxyThread = null;
	}

	public static synchronized boolean isInitDone() {
		return proxyThread == null;
	}
}