forked from petabridge/akka-bootcamp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConsoleReaderActor.cs
94 lines (83 loc) · 3.03 KB
/
ConsoleReaderActor.cs
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
using System;
using Akka.Actor;
namespace WinTail
{
/// <summary>
/// Actor responsible for reading FROM the console.
/// Also responsible for calling <see cref="ActorSystem.Shutdown"/>.
/// </summary>
class ConsoleReaderActor : UntypedActor
{
public const string StartCommand = "start";
public const string ExitCommand = "exit";
private readonly IActorRef _consoleWriterActor;
public ConsoleReaderActor(IActorRef consoleWriterActor)
{
_consoleWriterActor = consoleWriterActor;
}
protected override void OnReceive(object message)
{
if (message.Equals(StartCommand))
{
DoPrintInstructions();
}
else if (message is Messages.InputError)
{
_consoleWriterActor.Tell(message as Messages.InputError);
}
GetAndValidateInput();
}
#region Internal methods
private void DoPrintInstructions()
{
Console.WriteLine("Write whatever you want into the console!");
Console.WriteLine("Some entries will pass validation, and some won't...\n\n");
Console.WriteLine("Type 'exit' to quit this application at any time.\n");
}
/// <summary>
/// Reads input from console, validates it, then signals appropriate response
/// (continue processing, error, success, etc.).
/// </summary>
private void GetAndValidateInput()
{
var message = Console.ReadLine();
if (string.IsNullOrEmpty(message))
{
// signal that the user needs to supply an input, as previously
// received input was blank
Self.Tell(new Messages.NullInputError("No input received."));
}
else if (String.Equals(message, ExitCommand, StringComparison.OrdinalIgnoreCase))
{
// shut down the entire actor system (allows the process to exit)
Context.System.Shutdown();
}
else
{
var valid = IsValid(message);
if (valid)
{
_consoleWriterActor.Tell(new Messages.InputSuccess("Thank you! Message was valid."));
// continue reading messages from console
Self.Tell(new Messages.ContinueProcessing());
}
else
{
Self.Tell(new Messages.ValidationError("Invalid: input had odd number of characters."));
}
}
}
/// <summary>
/// Validates <see cref="message"/>.
/// Currently says messages are valid if contain even number of characters.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
private static bool IsValid(string message)
{
var valid = message.Length % 2 == 0;
return valid;
}
#endregion
}
}