summaryrefslogtreecommitdiffstats
path: root/dozentenmodulserver/src/main/java/org/openslx/bwlp/sat/web/WebServer.java
blob: c68e5a8fecc308fbd0abf76e9a77805dc82051e5 (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
package org.openslx.bwlp.sat.web;

import java.io.ByteArrayInputStream;
import java.sql.SQLException;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.openslx.bwlp.sat.database.mappers.DbLecture;
import org.openslx.bwlp.thrift.iface.TNotFoundException;
import org.openslx.util.GenericDataCache;
import org.openslx.util.vm.VmMetaData;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import fi.iki.elonen.NanoHTTPD;

public class WebServer extends NanoHTTPD {

	private static final GenericDataCache<byte[]> lectureListCache = new GenericDataCache<byte[]>(15000) {
		Serializer serializer = new Persister();

		@Override
		protected byte[] update() throws Exception {
			VmChooserListXml listXml = DbLecture.getUsableListXml(false);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			serializer.write(listXml, baos);
			return baos.toByteArray();
		}
	};

	public WebServer(int port) {
		super(port);
	}

	@Override
	public Response serve(IHTTPSession session) {
		String uri = session.getUri();

		if (uri == null || uri.length() == 0) {
			return internalServerError();
		}

		// Our special stuff
		if (uri.startsWith("/vmchooser/list")) {
			return serveVmChooserList();
		}
		if (uri.startsWith("/vmchooser/lecture/")) {
			return serveLectureStart(uri.substring(19));
		}

		return notFound();
	}

	private Response notFound() {
		return new NanoHTTPD.Response(NanoHTTPD.Response.Status.NOT_FOUND, "text/plain", "Nicht gefunden!");
	}

	private Response serveLectureStart(String lectureId) {
		VmMetaData meta;
		try {
			meta = DbLecture.getClientLaunchData(lectureId);
		} catch (TNotFoundException e) {
			return notFound();
		} catch (SQLException e) {
			return internalServerError();
		}
		return new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, "text/plain; charset=utf-8",
				new ByteArrayInputStream(meta.getFilteredDefinitionArray()));
	}

	private Response serveVmChooserList() {
		return new NanoHTTPD.Response(NanoHTTPD.Response.Status.OK, "text/xml; charset=utf-8",
				new ByteArrayInputStream(lectureListCache.get()));
	}

	private Response internalServerError() {
		return new NanoHTTPD.Response(NanoHTTPD.Response.Status.INTERNAL_ERROR, "text/plain",
				"Internal Server Error");
	}

}