summaryrefslogtreecommitdiffstats
path: root/dozentenmodul/src/main/java/org/openslx/dozmod/Branding.java
blob: 34dceee3afa5e846a59974a8154beb3d33c40d35 (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
package org.openslx.dozmod;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openslx.dozmod.Config.ProxyMode;
import org.openslx.dozmod.util.OsHelper;
import org.openslx.util.Util;

public final class Branding {

	private final static Logger LOGGER = LogManager.getLogger(Branding.class);

	private static final String VIRTUALIZER_WEBSITE = "virtualizer.website";
	private static final String SERVICE_EMAIL = "service.email";
	private static final String CONFIG_DIRECTORY = "config.directory";
	private static final String SERVICE_NAME = "service.name";
	private static final String SERVICE_FAQ_WEBSITE = "service.faq.website";
	private static final String APPLICATION_NAME = "application.name";
	private static final String MASTERSERVER_IDM = "masterserver.idm";
	private static final String MASTERSERVER_ADDRESS = "masterserver.address";

	private final static String PROPERTIES_FILE = "branding.properties";
	private final static Properties PROPERTIES = new Properties();
	private final static List<Path> RESOURCES = new ArrayList<Path>();

	public static final String RESOURCE_FS_DIR;

	private final static Map<String, String> DEFAULTS = new HashMap<String, String>() {
		private static final long serialVersionUID = -5625624201188857134L;

		{
			put(MASTERSERVER_ADDRESS, "bwlp-masterserver.ruf.uni-freiburg.de");
			put(MASTERSERVER_IDM, "bwIDM");
			put(APPLICATION_NAME, "bwLehrpool-Suite");
			put(SERVICE_FAQ_WEBSITE, "https://www.bwLehrpool.de");
			put(SERVICE_NAME, "bwLehrpool");
			put(CONFIG_DIRECTORY, "bwSuite");
			put(SERVICE_EMAIL, "support@bwlehrpool.de");
			put(VIRTUALIZER_WEBSITE, "https://www.bwlehrpool.de/doku.php/allgemein/virtualisierer");
		}
	};

	static {
		String path = null;
		try {
			RESOURCES.add(Paths.get(PROPERTIES_FILE));
			RESOURCES.add(Paths.get("img"));
			RESOURCES.add(Paths.get("txt"));
			// Built-in properties file takes precedence
			boolean ok = false;
			try (InputStream in = App.class.getClassLoader().getResourceAsStream(PROPERTIES_FILE)) {
				PROPERTIES.load(in);
				LOGGER.info("Loaded branding from jar");
				ok = true;
			} catch (Exception e) {
				LOGGER.debug("Failed to read 'jar:" + PROPERTIES_FILE + "': ");
			}
			if (!ok) {
				// Try CWD
				try (InputStream in = new FileInputStream(PROPERTIES_FILE)) {
					PROPERTIES.load(in);
					LOGGER.info("Loaded branding from current working directory");
					path = "./";
					ok = true;
				} catch (Exception e) {
					LOGGER.debug("Failed to read './" + PROPERTIES_FILE + "': ");
				}
			}
			if (!ok) {
				// Try system-wide defaults
				if (OsHelper.isWindows()) {
					path = System.getenv("ProgramData");
					if (Util.isEmptyString(path)) {
						path = "C:\\ProgramData";
					}
				} else {
					path = "/etc";
				}
				path = path + "/bwlp/";
				try (InputStream in = new FileInputStream(path + PROPERTIES_FILE)) {
					PROPERTIES.load(in);
					LOGGER.info("Loaded system-wide branding");
					ok = true;
				} catch (Exception e) {
					LOGGER.debug("Failed to read '" + path + PROPERTIES_FILE + "': ");
					path = null;
				}
			}
			// Fill in missing fields
			PROPERTIES.store(System.out, "");
			for (Entry<String, String> it : DEFAULTS.entrySet()) {
				if (!PROPERTIES.containsKey(it.getKey())) {
					PROPERTIES.setProperty(it.getKey(), it.getValue());
				}
			}
			PROPERTIES.store(System.out, "");
		} catch (Throwable t) {
			t.printStackTrace();
			System.exit(1);
		}
		RESOURCE_FS_DIR = path;
	}

	public final static String getMasterServerAddress() {
		return PROPERTIES.getProperty(MASTERSERVER_ADDRESS);
	}

	public final static String getMasterServerIdm() {
		return PROPERTIES.getProperty(MASTERSERVER_IDM);
	}

	public final static String getApplicationName() {
		return PROPERTIES.getProperty(APPLICATION_NAME);
	}

	public final static String getServiceFAQWebsite() {
		return PROPERTIES.getProperty(SERVICE_FAQ_WEBSITE);
	}

	public final static String getServiceName() {
		return PROPERTIES.getProperty(SERVICE_NAME);
	}

	public final static String getConfigDirectory() {
		return PROPERTIES.getProperty(CONFIG_DIRECTORY);
	}

	public final static String getServiceEmail() {
		return PROPERTIES.getProperty(SERVICE_EMAIL);
	}

	public final static String getVirtualizerWebsite() {
		return PROPERTIES.getProperty(VIRTUALIZER_WEBSITE);
	}

	public final static String getProxyMode() {
		return PROPERTIES.getProperty("proxy.mode", ProxyMode.AUTO.toString());
	}

	public static void dump(final String localDir) {
		if (localDir == null || localDir.isEmpty())
			return;
		final Path dumpDir = Paths.get(localDir);
		if (!Files.isDirectory(dumpDir)) {
			try {
				Files.createDirectories(dumpDir);
			} catch (IOException e) {
				LOGGER.error("Failed to create missing dump directory: ", e);
				return;
			}
		}
		final URI jarUri = getRunningJarURI();
		if (jarUri == null || jarUri.getPath() == null || jarUri.getPath().isEmpty())
			return;
		copyBranding(jarUri, dumpDir.toString(), false);

	}

	public static void pack(final String localDir, final String outputJar) {
		final URI jarUri = getRunningJarURI();
		if (jarUri == null || jarUri.getPath() == null || jarUri.getPath().isEmpty())
			return;

		final File brandingDir = new File(localDir);
		if (!brandingDir.isDirectory()) {
			LOGGER.error("Given path is not a directory: " + localDir);
			return;
		}
		final Path newJarPath = Paths.get(outputJar);
		try {
			Files.copy(Paths.get(jarUri), newJarPath);
		} catch (Exception e) {
			LOGGER.error("Failed to copy jar file at location '" + jarUri.getPath() + "' to '" + newJarPath
					+ "': ", e);
			try {
				Files.delete(newJarPath);
			} catch (IOException e1) {
				LOGGER.error("Failed to cleanup '" + newJarPath + ": ", e1);
			}
		}
		// copied jar successfully, now insert the contents from the directory
		copyBranding(newJarPath.toUri(), localDir, true);
	}

	private static void copyBranding(final URI jarUri, final String localDir, final boolean pack) {
		try (FileSystem fs = FileSystems.newFileSystem(URI.create("jar:" + jarUri),
				new HashMap<String, String>() {
					private static final long serialVersionUID = -5625624201188857134L;

					{
						put("create", "true");
						put("encoding", "UTF-8");
					}
				})) {
			// hacky default using the fs' separator as root directory
			Path rootPathJar = fs.getPath(fs.getSeparator());
			Iterator<Path> it = fs.getRootDirectories().iterator();
			if (it.hasNext()) {
				rootPathJar = it.next();
				if (it.hasNext()) {
					// there should only be one ... TODO handle multiples?
					LOGGER.debug("Multiple root directories within the JAR found? Trying with first one '"
							+ rootPathJar + "'...");
				}
			}
			Path rootPathLocal = Paths.get(localDir);
			for (Path res : RESOURCES) {
				final Path src, dst;
				if (pack) {
					src = rootPathLocal.resolve(res);
					dst = rootPathJar.resolve(rootPathLocal.relativize(res).toString());
				} else {
					src = rootPathJar.resolve(res.toString());
					dst = rootPathLocal.resolve(res);
				}
				if (!Files.isReadable(src)) {
					if (!pack && res.endsWith(PROPERTIES_FILE)) {
						// Missing properties file is OK, just dump current state
						try (FileOutputStream fos = new FileOutputStream(dst.toFile())) {
							PROPERTIES.store(fos, "");
						}
					} else {
						LOGGER.error("Failed to find or read '" + src + "'.");
					}
					continue;
				}

				if (Files.isDirectory(src)) {
					Files.walkFileTree(src, new SimpleFileVisitor<Path>() {
						@Override
						public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
								throws IOException {
							Path cur = dst.resolve(src.relativize(file).toString());
							if (!Files.isDirectory(cur.getParent())) {
								Files.createDirectory(cur.getParent());
							}
							Files.copy(file, cur, StandardCopyOption.REPLACE_EXISTING);
							return FileVisitResult.CONTINUE;
						}
					});
				} else if (Files.isRegularFile(src)) {
					Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING);
				} else {
					LOGGER.error("Unknown file type for '" + src + "'.");
				}
			}
		} catch (Exception e) {
			LOGGER.error("Failed to dump branding resources from JAR: ", e);
			return;
		}
	}

	private static URI getRunningJarURI() {
		CodeSource cs = App.class.getProtectionDomain().getCodeSource();
		if (cs == null) {
			LOGGER.error("Failed to get code source of this class.");
			return null;
		}
		try {
			return cs.getLocation().toURI();
		} catch (URISyntaxException e) {
			LOGGER.error("Failed to get location of this JAR.");
		}
		return null;
	}
}