1 package org.jastacry.layer;
2
3 import java.io.IOException;
4 import java.io.InputStream;
5 import java.io.OutputStream;
6 import java.util.concurrent.CountDownLatch;
7
8 import org.apache.logging.log4j.LogManager;
9 import org.apache.logging.log4j.Logger;
10 import org.jastacry.GlobalData.Action;
11 import org.jastacry.JastacryException;
12
13
14
15
16
17
18
19
20 public abstract class AbstractBasicLayer implements Runnable, Layer
21 {
22
23
24
25 private static final int BYTE_VALUE_OVER = 256;
26
27
28
29
30 private static final int BYTE_VALUE_MAX = 255;
31
32
33
34
35 private String realLayerName;
36
37
38
39
40 private Action action;
41
42
43
44
45 protected InputStream inputStream;
46
47
48
49
50 protected OutputStream outputStream;
51
52
53
54
55 protected final Logger logger;
56
57
58
59
60 protected CountDownLatch endController;
61
62
63
64
65
66
67
68 protected AbstractBasicLayer(final Class<?> caller, final String layerName)
69 {
70 logger = LogManager.getLogger(caller);
71 setAction(null);
72 setInputStream(null);
73 setOutputStream(null);
74 setRealLayerName(layerName);
75 }
76
77
78
79
80
81
82
83
84 public final String toString()
85 {
86 return realLayerName;
87 }
88
89
90
91
92
93
94
95 protected final int rangeCheck(final int iInput)
96 {
97 int iTmp = iInput;
98 if (iTmp < 0)
99 {
100 iTmp += BYTE_VALUE_OVER;
101 }
102 else
103 {
104 if (iTmp > BYTE_VALUE_MAX)
105 {
106 iTmp -= BYTE_VALUE_OVER;
107 }
108 }
109
110 return iTmp;
111 }
112
113
114
115
116 @Override
117 public final void setInputStream(final InputStream newInputStream)
118 {
119 this.inputStream = newInputStream;
120 }
121
122
123
124
125 @Override
126 public final void setOutputStream(final OutputStream newOutputStream)
127 {
128 this.outputStream = newOutputStream;
129 }
130
131
132
133
134 @Override
135 public final void setAction(final Action newAction)
136 {
137 this.action = newAction;
138 }
139
140
141
142
143
144
145 public final void setEndController(final CountDownLatch newEndController)
146 {
147 this.endController = newEndController;
148 }
149
150
151
152
153 @Override
154 public final void setRealLayerName(final String newRealLayerName)
155 {
156 this.realLayerName = newRealLayerName;
157 }
158
159
160
161
162 @Override
163 public void run()
164 {
165 logger.info("started thread");
166 try
167 {
168 switch (action)
169 {
170 case ENCODE:
171 this.encStream(inputStream, outputStream);
172 break;
173 case DECODE:
174 this.decStream(inputStream, outputStream);
175 break;
176 case UNKOWN:
177 default:
178 logger.error("unknown action '{}'", action);
179 break;
180 }
181 outputStream.close();
182 }
183 catch (final JastacryException | IOException exception)
184 {
185 logger.catching(exception);
186 }
187 finally
188 {
189 endController.countDown();
190 }
191 logger.info("finished thread");
192 }
193 }