Projekt

Obecné

Profil

« Předchozí | Další » 

Revize f7eb37b3

Přidáno uživatelem Eliška Mourycová před téměř 4 roky(ů)

Refactor + logging config modification

Zobrazit rozdíly:

Server/ServerApp/App.config
25 25
        <root>
26 26
            <level value="ALL" />
27 27
            <appender-ref ref="LogFileAppender" />
28
            <appender-ref ref="ConsoleAppender" />
29 28
        </root>
30 29
    </log4net>
31 30
</configuration>
Server/ServerApp/Connection/ConnectionListener.cs
65 65

  
66 66
			//Console.WriteLine("Listening...");
67 67
			logger.Info("Started listening at ip: " + ip + ", port: " + PORT);
68

  
68
			Console.WriteLine("Server ready to receive requests.");
69 69

  
70 70
			var result = listener.BeginGetContext(ListenerCallback, listener);
71 71
			// result.AsyncWaitHandle.WaitOne(); // ????
......
80 80
		}
81 81

  
82 82

  
83
		private void HandleRequest(HttpListenerContext context)
84
		{
83
		//private void HandleRequest(HttpListenerContext context)
84
		//{
85 85

  
86
			//Console.WriteLine("Handling request.");
87
			logger.Debug("Handling request.");
88
			// Obtain a request object.
89
			HttpListenerRequest request = context.Request;
90
			// Obtain a response object.
91
			HttpListenerResponse response = context.Response;
86
		//	//Console.WriteLine("Handling request.");
87
		//	logger.Debug("Handling request.");
88
		//	// Obtain a request object.
89
		//	HttpListenerRequest request = context.Request;
90
		//	// Obtain a response object.
91
		//	HttpListenerResponse response = context.Response;
92 92

  
93 93

  
94 94

  
95
			// add the headers and everything:
96
			response.AddHeader("Access-Control-Allow-Credentials", "true");
97
			response.AddHeader("Access-Control-Expose-Headers", "ETag");
98
			response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time");
99
			response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
100
			response.AddHeader("Access-Control-Allow-Origin", "*");
95
		//	// add the headers and everything:
96
		//	response.AddHeader("Access-Control-Allow-Credentials", "true");
97
		//	response.AddHeader("Access-Control-Expose-Headers", "ETag");
98
		//	response.AddHeader("Access-Control-Allow-Headers", "Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time");
99
		//	response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
100
		//	response.AddHeader("Access-Control-Allow-Origin", "*");
101 101

  
102
			string responseString = "";
103
			// Construct a response.
104
			if (context.Request.HttpMethod == "GET") // when client says download
105
			{
106
				logger.Info("received GET request");
102
		//	string responseString = "";
103
		//	// Construct a response.
104
		//	if (context.Request.HttpMethod == "GET") // when client says download
105
		//	{
106
		//		logger.Info("received GET request");
107 107

  
108
				string text;
109
				using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
110
					text = reader.ReadToEnd();
111
				string requestString = HttpUtility.UrlDecode(text);
108
		//		string text;
109
		//		using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
110
		//			text = reader.ReadToEnd();
111
		//		string requestString = HttpUtility.UrlDecode(text);
112 112

  
113
				responseString = ConstructGETResponse(requestString);
113
		//		responseString = ConstructGETResponse(requestString);
114 114

  
115
			}
116
			else if (context.Request.HttpMethod == "POST") // when client says upload
117
			{
118
				logger.Info("received POST request");
119
				string text;
120
				using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
121
					text = reader.ReadToEnd();
122
				string requestString = HttpUtility.UrlDecode(text);
115
		//	}
116
		//	else if (context.Request.HttpMethod == "POST") // when client says upload
117
		//	{
118
		//		logger.Info("received POST request");
119
		//		string text;
120
		//		using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
121
		//			text = reader.ReadToEnd();
122
		//		string requestString = HttpUtility.UrlDecode(text);
123 123

  
124
				responseString = ConstructPOSTResponse(requestString);
124
		//		responseString = ConstructPOSTResponse(requestString);
125 125

  
126 126

  
127
			}
128
			else
129
			{
130
				logger.Warn("received request other than GET or POST");
127
		//	}
128
		//	else
129
		//	{
130
		//		logger.Warn("received request other than GET or POST");
131 131

  
132
			}
132
		//	}
133 133

  
134 134

  
135
			System.IO.Stream output = response.OutputStream;
136
			if (!string.IsNullOrEmpty(responseString))
137
			{
138
				logger.Debug("Response is not null or empty, sending it to the client.");
139
				byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
135
		//	System.IO.Stream output = response.OutputStream;
136
		//	if (!string.IsNullOrEmpty(responseString))
137
		//	{
138
		//		logger.Debug("Response is not null or empty, sending it to the client.");
139
		//		byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
140 140

  
141
				// Get a response stream and write the response to it.
142
				response.ContentLength64 = buffer.Length;
143
				output.Write(buffer, 0, buffer.Length);
144
			}
145
			else
146
			{
147
				logger.Debug("Response was null or empty, not sending anything.");
148
			}
141
		//		// Get a response stream and write the response to it.
142
		//		response.ContentLength64 = buffer.Length;
143
		//		output.Write(buffer, 0, buffer.Length);
144
		//	}
145
		//	else
146
		//	{
147
		//		logger.Debug("Response was null or empty, not sending anything.");
148
		//	}
149 149

  
150 150

  
151
			// Close the output stream.
152
			//output.Close();
153
			response.Close();
151
		//	// Close the output stream.
152
		//	//output.Close();
153
		//	response.Close();
154 154

  
155
			logger.Debug("At the end of HandleRequest");
156
		}
155
		//	logger.Debug("At the end of HandleRequest");
156
		//}
157 157

  
158 158
		/// <summary>
159 159
		/// The callnack method triggered when client request received
......
250 250
		/// <returns>The response string, empty if client's request doesn't follow protocol</returns>
251 251
		private string ConstructGETResponse(string requestString)
252 252
		{
253
			//Console.WriteLine("Constructiing a response for GET request.");
254

  
255
			//int rand = new Random().Next(1, 10);
256
			//string msg = "This is a response from the server :) " + rand;
257

  
258
			//Response xmlResp = Response.Randomize();
259
			//var xml = XmlCommunication.Serialize(xmlResp);
260

  
261
			//return xml;
262

  
263 253

  
264 254
			logger.Info("Constructing a response for GET request.");
265
			logger.Info("Request string: ");
266
			logger.Info(requestString);
255
			//logger.Info("Request string: ");
256
			//logger.Info(requestString);
267 257

  
268 258

  
269 259

  
......
288 278
			logger.Info("Getting the prediction from the predictor.");
289 279
			logger.Debug("Deserialized request is null? : " + requestDeserialized == null);
290 280
			Response responsePrediction = predictionController.Predict(requestDeserialized);
281
			
291 282

  
292 283
			string constructedXml = XmlCommunication.Serialize(responsePrediction);
293
			logger.Info("Constructed response:");
294
			logger.Info(constructedXml);
284
			//logger.Info("Constructed response:");
285
			//logger.Info(constructedXml);
295 286

  
296 287
			// build the xml from the prediction: - TODO mbe an exception can happen here as well? - it shouldnt
297 288
			return constructedXml;//XmlCommunication.Serialize(responsePrediction);
......
307 298
		private string ConstructPOSTResponse(string requestString)
308 299
		{
309 300
			logger.Info("Constructing a response for POST request.");
310
			logger.Info("Request string: ");
311
			logger.Info(requestString);
301
			//logger.Info("Request string: ");
302
			//logger.Info(requestString);
312 303

  
313 304

  
314 305

  
......
322 313
			}
323 314
			catch
324 315
			{
325
				logger.Warn("wrong format of request!");
316
				logger.Warn("Wrong format of request!");
326 317

  
327 318
				// don't bother to send anything:
328 319
				return string.Empty;
......
336 327

  
337 328

  
338 329
			string constructedXml = XmlCommunication.Serialize(responsePrediction);
339
			logger.Info("Constructed response:");
340
			logger.Info(constructedXml);
330
			//logger.Info("Constructed response:");
331
			//logger.Info(constructedXml);
341 332

  
342 333
			// build the xml from the prediction: - TODO mbe an exception can happen here as well? - it shouldnt
343 334
			return constructedXml;//XmlCommunication.Serialize(responsePrediction);
......
346 337

  
347 338
		}
348 339

  
340

  
341
		public XMLProtocolHandler.Date CheckTimeSpanModifyEnd(Date startDate, Date endDate, int maxTimeSpan)
342
		{
343
			int comp = startDate.CompareTo(endDate); // -1 if start date lower
344

  
345
			if (comp >= 0)
346
				return endDate;
347

  
348
			// now we're in a situation where startDate is before endDate - check if span too much:
349

  
350

  
351
			DateTime start = new DateTime(); 
352
			DateTime end = new DateTime();
353
			try
354
			{
355
				start = new DateTime(startDate.year, startDate.month, startDate.day);
356
				end = new DateTime(endDate.year, endDate.month, endDate.day);
357
			}
358
			catch(ArgumentOutOfRangeException aore)
359
			{
360
				// hopefully the predictor will know what to do
361
				return endDate;
362
			}
363

  
364

  
365
			int diff = (end - start).Days;
366

  
367
			if(diff > maxTimeSpan)
368
			{
369
				DateTime newEnd = start.AddDays(maxTimeSpan);
370
				endDate.year = newEnd.Year;
371
				endDate.month = newEnd.Month;
372
				endDate.day = newEnd.Day;
373

  
374
				return endDate;
375
			}
376

  
377

  
378
			return endDate;
379
		}
380

  
349 381
		/// <summary>
350 382
		/// Gets the IPv4 IP of the machine
351 383
		/// </summary>
Server/ServerApp/Program.cs
1
using log4net.Config;
1
using log4net;
2
using log4net.Config;
2 3
using ServerApp.Connection;
3 4
using ServerApp.Connection.XMLProtocolHandler;
4 5
using ServerApp.DataDownload;
......
27 28

  
28 29
    public class Program
29 30
    {
31
		// logger class instance
32
		private static readonly ILog logger = LogManager.GetLogger(typeof(Program));
30 33

  
31
        static void Main(string[] args)
34
		static void Main(string[] args)
32 35
        {
36
			Console.WriteLine("Server start.");
37

  
33 38
            // setup logging service
34 39
            XmlConfigurator.Configure();
35 40

  
......
41 46
				Console.ReadLine();
42 47
				return;
43 48
			}
49
			Console.WriteLine("Config parsing successful.");
50

  
51
			//logger.Debug("ahoj");
52
			//logger.Warn("ahoj2");
53
			//Console.ReadLine();
44 54

  
45
			// data download test
46
			DataDownloader dd = DataDownloadAndRetrievalTest(config);
55
			// data download init
56
			Console.WriteLine("Downloading open data...");
57
			DataDownloader dd = DataDownloaderInit(config);
58
			Console.WriteLine("Data downloaded and saved.");
47 59

  
48 60
			//WeatherAsStringTest(dd);
49 61
			//Console.ReadLine();
......
51 63
			// xml building test
52 64
			//XMLTest();
53 65

  
54
			// PARSE DATA
55
			//DataParser parser = new DataParser(dd);
56
			//parser.Parse(new DateTime())
57 66

  
58 67
			// json parser test
59 68
			//JSONParserTest();
60 69

  
61
			// model test
62
			IPredictionController controller = PredictionTest(dd);
70
			// model init
71
			Console.WriteLine("Training the predictor...");
72
			IPredictionController controller = PredictionControllerInit(dd);
73
			Console.WriteLine("Predictor training finished.");
63 74

  
64
			//parse(new DateTime(2019, 10, 5), , interval = 1, wholeDay = true)
65 75

  
66 76
			// commands accepting test
67 77
			// create a thread for commands accepting:
......
70 80
			inputThread.Start();
71 81

  
72 82

  
73
			// connection test
74
			ConnectionTest(controller, config);
83
			// connection init
84
			ConnectionInit(controller, config);
75 85

  
76
			//Console.ReadLine();
77 86
        }
78 87

  
79 88

  
80
		private static DataDownloader DataDownloadAndRetrievalTest(Config config)
89
		private static DataDownloader DataDownloaderInit(Config config)
81 90
		{
82 91
			//test scenario -data download:
83 92
			DataDownloader dd = new DataDownloader(config.DataRootDir, config.DataWebsite, config.DownloadedFilesNaming, config.WeatherSite);
......
91 100

  
92 101

  
93 102

  
94
			Console.WriteLine("Saved files: ");
95
			foreach (string s in savedFiles)
96
			{
97
				Console.WriteLine(s);
98
			}
103
			//Console.WriteLine("Saved files: ");
104
			//foreach (string s in savedFiles)
105
			//{
106
			//	Console.WriteLine(s);
107
			//}
99 108

  
100
			Console.WriteLine("subdirectories: ");
101
			foreach (KeyValuePair<DataType, string> kvp in dd.DataSubDirectories)
102
			{
103
				Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
104
			}
109
			//Console.WriteLine("subdirectories: ");
110
			//foreach (KeyValuePair<DataType, string> kvp in dd.DataSubDirectories)
111
			//{
112
			//	Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
113
			//}
105 114

  
106
			List<string> retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], new DataDownload.Date(10, 2019), new DataDownload.Date(12, 2020));
107
			Console.WriteLine("Retrieved data: ");
108
			foreach (string s in retrievedData)
109
			{
110
				Console.WriteLine(s);
111
			}
112
			Console.WriteLine("all from directory:");
113
			retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], null, null);
114
			foreach (string s in retrievedData)
115
			{
116
				Console.WriteLine(s);
117
			}
115
			//List<string> retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], new DataDownload.Date(10, 2019), new DataDownload.Date(12, 2020));
116
			//Console.WriteLine("Retrieved data: ");
117
			//foreach (string s in retrievedData)
118
			//{
119
			//	Console.WriteLine(s);
120
			//}
121
			//Console.WriteLine("all from directory:");
122
			//retrievedData = dd.GetData(dd.DataSubDirectories[DataType.JIS], null, null);
123
			//foreach (string s in retrievedData)
124
			//{
125
			//	Console.WriteLine(s);
126
			//}
118 127

  
119 128

  
120 129
			return dd;
......
166 175
			Console.WriteLine(dd.DownloadWeatherPrediction());
167 176
		}
168 177

  
169
		private static IPredictionController PredictionTest(DataDownloader dd)
178
		private static IPredictionController PredictionControllerInit(DataDownloader dd)
170 179
		{
171
			// TODO nastavit čas
172 180
			IDataParser p = new DataParser(dd);
173 181
            // FIXME pass the right references to the JsonParser constructor
174 182
            IJsonParser jsonP = new JsonParser(dd, new CsvDataLoader());
175 183
            IPredictionController predictionController = new PredictionController(jsonP, p);
176 184
            predictionController.Train();
177
            //var results = predictionController.Predict()
178 185
			
179 186

  
180 187
			return predictionController;
181 188
		}
182 189

  
183
		private static void ConnectionTest(IPredictionController predictionController, Config config)
190
		private static void ConnectionInit(IPredictionController predictionController, Config config)
184 191
		{
185 192
			ConnectionListenerAsync cl = new ConnectionListenerAsync(int.Parse(config.Port), predictionController);
186 193
			cl.StartListening();
......
195 202

  
196 203
			Config extractedConfigInfo = new Config();
197 204

  
198
			Console.WriteLine(Directory.GetCurrentDirectory());
199 205
			Console.WriteLine("Parsing configuration file...");
200 206
			
201 207
			if (args.Length != 1)
Server/ServerAppFunctionalTests/XMLComTests/XMLDateTesting.cs
1
using Microsoft.VisualStudio.TestTools.UnitTesting;
2
using System;
3
using System.Collections.Generic;
4
using System.Linq;
5
using System.Text;
6
using System.Threading.Tasks;
7
using ServerApp.Connection;
8
using ServerApp.Connection.XMLProtocolHandler;
9
using ServerApp.Predictor;
10
using ServerApp.DataDownload;
11
using Date = ServerApp.Connection.XMLProtocolHandler.Date;
12
using ServerApp.WeatherPredictionParser;
13
using ServerApp.Parser.InputData;
14
using ServerApp.Parser.Parsers;
15

  
16
namespace ServerAppFunctionalTests.XMLComTests
17
{
18
	[TestClass]
19
	public class XMLDateTesting
20
	{
21

  
22

  
23
		[TestMethod]
24
		public void ModifyTimeSpanShort()
25
		{
26
			ConnectionListenerAsync conn = new ConnectionListenerAsync(0, null);
27

  
28
			Date startDate = new Date();
29
			startDate.year = 2019;
30
			startDate.month = 1;
31
			startDate.day = 1;
32

  
33

  
34
			Date endDate = new Date();
35
			endDate.year = 2019;
36
			endDate.month = 1;
37
			endDate.day = 2;
38

  
39
			Date res = conn.CheckTimeSpanModifyEnd(startDate, endDate, 15);
40

  
41
			Assert.IsNotNull(res);
42
			Assert.AreEqual(endDate.year, res.year);
43
			Assert.AreEqual(endDate.month, res.month);
44
			Assert.AreEqual(endDate.day, res.day);
45

  
46
		}
47

  
48

  
49
		[TestMethod]
50
		public void ModifyTimeSpanLong()
51
		{
52
			ConnectionListenerAsync conn = new ConnectionListenerAsync(0, null);
53

  
54
			Date startDate = new Date();
55
			startDate.year = 2019;
56
			startDate.month = 1;
57
			startDate.day = 1;
58

  
59

  
60
			Date endDate = new Date();
61
			endDate.year = 2019;
62
			endDate.month = 1;
63
			endDate.day = 30;
64

  
65
			Date res = conn.CheckTimeSpanModifyEnd(startDate, endDate, 15);
66

  
67
			Assert.IsNotNull(res);
68
			Assert.AreEqual(endDate.year, res.year);
69
			Assert.AreEqual(endDate.month, res.month);
70
			Assert.AreEqual(endDate.day, 16);
71

  
72
		}
73
	}
74
}

Také k dispozici: Unified diff