source: trunk/CrypPlugins/PeerToPeerJobs/JobResult.cs @ 1137

Last change on this file since 1137 was 1137, checked in by arnold, 12 years ago

Completely redesigned Manager-JobAdmin-Worker-infrastructure to distribute Jobs with a Peer-to-Peer infrastructure to remote CT2-Workspaces.

To test this infrastructure, open 2 instances of CT and load P2P_Manager_NEW_DES.cte and in the other instance P2P_Worker_NEW.cte.
HINT: Working with remote peers isn't possible every time, because the so called "SuperNode", which is necessary for relaying, sometimes goes down. But testing this infrastructure on different computers in the same network should work every time.

File size: 12.8 KB
Line 
1/* Copyright 2010 Team CrypTool (Christian Arnold), Uni Duisburg-Essen
2
3   Licensed under the Apache License, Version 2.0 (the "License");
4   you may not use this file except in compliance with the License.
5   You may obtain a copy of the License at
6
7       http://www.apache.org/licenses/LICENSE-2.0
8
9   Unless required by applicable law or agreed to in writing, software
10   distributed under the License is distributed on an "AS IS" BASIS,
11   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   See the License for the specific language governing permissions and
13   limitations under the License.
14*/
15
16using System;
17using System.Collections.Generic;
18using System.Linq;
19using System.Text;
20using System.IO;
21using System.Reflection;
22using Cryptool.PluginBase.Miscellaneous;
23
24namespace Cryptool.Plugins.PeerToPeer.Jobs
25{
26    public abstract class JobResult<JobResultType> : IJobResult<JobResultType>
27    {
28        #region Variables
29
30        private BigInteger jobId;
31        public BigInteger JobId
32        {
33            get {  return this.jobId; }
34            set { this.jobId = value; }
35        }
36        private bool isIntermediateJobResult = false;
37        public bool IsIntermediateResult
38        {
39            get { return this.isIntermediateJobResult;}
40            set { this.isIntermediateJobResult = value; }
41        }
42        private TimeSpan processingTime;
43        public TimeSpan ProcessingTime
44        {
45            get { return this.processingTime;}
46            set { this.processingTime = value; } 
47        }
48        private JobResultType result;
49        public JobResultType Result
50        { 
51            get{return this.result;}
52            set { this.result = value; }
53        }
54
55        #endregion
56
57        /// <summary>
58        /// Creates a new JobResult (this is an endresul!)
59        /// </summary>
60        /// <param name="jobId">jobId for which you have a result</param>
61        /// <param name="result">result of the job (e.g. simple conclusion, list, complex data structure)</param>
62        /// <param name="processingTime">Timespan between begin and end of processing the job</param>
63        public JobResult(BigInteger jobId, JobResultType result, TimeSpan processingTime)
64            :this(jobId,result,processingTime,false)
65        { } 
66
67        /// <summary>
68        /// Creates a new JobResult (you can choose if this is only an intermediate result or the endresult)
69        /// </summary>
70        /// <param name="jobId">jobId for which you have a result</param>
71        /// <param name="result">result of the job (e.g. simple conclusion, list, complex data structure)</param>
72        /// <param name="processingTime">Timespan between begin and end of processing the job</param>
73        /// <param name="isIntermediateResult">Is this is only an intermediate result, set this parameter to true, otherwise choose false</param>
74        public JobResult(BigInteger jobId, JobResultType result, TimeSpan processingTime, bool isIntermediateResult)
75        {
76            this.JobId = jobId;
77            this.Result = result;
78            this.ProcessingTime = processingTime;
79            this.IsIntermediateResult = isIntermediateResult;
80        }
81
82        // TODO: Test this constructor, if it works fine, delete Deserialize Method
83        /// <summary>
84        /// If you have a serialized JobResult class, you can deserialize it by using this constructor!
85        /// </summary>
86        /// <param name="serializedJobResult">serialized JobResult class as a byte[]</param>
87        public JobResult(byte[] serializedJobResult)
88        {
89            BigInteger temp_jobId;
90            JobResultType temp_result;
91            bool temp_isIntermediateResult;
92            TimeSpan temp_processingTime;
93
94            MemoryStream memStream = new MemoryStream(serializedJobResult, false);
95            try
96            {
97                Int32 testValue = 3000;
98                byte[] readInt = BitConverter.GetBytes(testValue);
99
100                /* Deserialize JobId */
101                memStream.Read(readInt, 0, readInt.Length);
102                int jobIdLen = BitConverter.ToInt32(readInt, 0);
103                byte[] jobIdByte = new byte[jobIdLen];
104                memStream.Read(jobIdByte, 0, jobIdByte.Length);
105                temp_jobId = new BigInteger(jobIdByte, jobIdByte.Length);
106
107                /* Deserialize Job result data */
108                //memStream.Read(readInt, 0, readInt.Length);
109                //int serializedDataLen = BitConverter.ToInt32(readInt, 0);
110                //byte[] serializedJobResultByte = new byte[serializedDataLen];
111                //memStream.Read(serializedJobResultByte, 0, serializedJobResultByte.Length);
112                //temp_result = (JobResultType)GetDeserializationViaReflection(serializedJobResultByte, this.Result);
113
114                // right for bool???
115                temp_isIntermediateResult = Convert.ToBoolean(memStream.ReadByte());
116
117                memStream.Read(readInt, 0, readInt.Length);
118                int days = BitConverter.ToInt32(readInt, 0);
119                memStream.Read(readInt, 0, readInt.Length);
120                int hours = BitConverter.ToInt32(readInt, 0);
121                memStream.Read(readInt, 0, readInt.Length);
122                int minutes = BitConverter.ToInt32(readInt, 0);
123                memStream.Read(readInt, 0, readInt.Length);
124                int seconds = BitConverter.ToInt32(readInt, 0);
125                memStream.Read(readInt, 0, readInt.Length);
126                int millisec = BitConverter.ToInt32(readInt, 0);
127                temp_processingTime = new TimeSpan(days, hours, minutes, seconds, millisec);
128
129                // read the rest of the byte[]-stream, this is the specialized JobResulType
130                byte[] serializedJobResultByte = new byte[memStream.Length - memStream.Position];
131                memStream.Read(serializedJobResultByte, 0, serializedJobResultByte.Length);
132                temp_result = DeserializeResultType(serializedJobResultByte);
133
134                this.JobId = temp_jobId;
135                this.IsIntermediateResult = temp_isIntermediateResult;
136                this.ProcessingTime = temp_processingTime;
137                this.Result = temp_result;
138            }
139            catch (Exception ex)
140            {
141                throw ex;
142            }
143            finally
144            {
145                memStream.Flush();
146                memStream.Close();
147                memStream.Dispose();
148            }
149        }
150
151        #region comparing methods
152
153        public override bool Equals(object obj)
154        {
155            if(obj == null)
156                return false;
157
158            if (ReferenceEquals(this, obj))
159                return true;
160
161            if (this.GetType() != obj.GetType())
162                return false;
163
164            return this == (JobResult<JobResultType>)obj;
165        }
166
167        public static bool operator ==(JobResult<JobResultType> left, JobResult<JobResultType> right)
168        {
169            if ((object)left == (object)right)
170                return true;
171
172            if ((object)left == null || (object)right == null)
173                return false;
174
175            if (left.jobId == right.JobId)
176                return true;
177
178            return false;
179        }
180
181        public static bool operator !=(JobResult<JobResultType> left, JobResult<JobResultType> right)
182        {
183            return !(left == right);
184        }
185
186        public override int GetHashCode()
187        {
188            return this.JobId.GetHashCode();
189        }
190
191        #endregion
192
193        #region Serialization methods
194
195        protected abstract byte[] SerializeResultType();
196
197        protected abstract JobResultType DeserializeResultType(byte[] serializedResultType);
198
199        /* 4 Bytes: serialized JobId
200         * 4 Bytes: serialized Job Result length
201         * y Bytes: serialized Job Result data
202         * 4 Bytes: isIntermedResult
203         * 4 Bytes: procTime.Days
204         * 4 Bytes: procTime.Hours
205         * 4 Bytes: procTime.Minutes
206         * 4 Bytes: procTime.Seconds
207         * 4 Bytes: procTime.Milliseconds */
208        /// <summary>
209        /// Serializes the whole class, so you can recreate this instance elsewhere by dint of this byte[].
210        /// HINT: You can Deserialize a byte[] representation of this class by using the constructor with
211        /// the byte[] parameter!
212        /// </summary>
213        /// <returns>serialized class as an byte[]</returns>
214        public byte[] Serialize()
215        {
216            byte[] ret = null;
217            MemoryStream memStream = new MemoryStream();
218            try
219            {
220                /* Serialize jobId */
221                byte[] jobIdByte = this.JobId.getBytes();
222                byte[] jobIdLen = BitConverter.GetBytes(jobIdByte.Length);
223                memStream.Write(jobIdLen, 0, jobIdLen.Length);
224                memStream.Write(jobIdByte, 0, jobIdByte.Length);
225
226                /* Serialize job result via Reflection */
227                //byte[] serializedJobResult = GetSerializationViaReflection(this.Result);
228                //byte[] byJobResultLen = BitConverter.GetBytes(serializedJobResult.Length);
229                //memStream.Write(byJobResultLen, 0, byJobResultLen.Length);
230                //memStream.Write(serializedJobResult, 0, serializedJobResult.Length);
231
232                byte[] intResultBytes = BitConverter.GetBytes(this.isIntermediateJobResult);
233                memStream.Write(intResultBytes,0,intResultBytes.Length);
234                /* Storing processingTimeSpan */
235                byte[] daysBytes = BitConverter.GetBytes(this.processingTime.Days);
236                memStream.Write(daysBytes,0,daysBytes.Length);
237                byte[] hoursBytes = (BitConverter.GetBytes(this.processingTime.Hours));
238                memStream.Write(hoursBytes,0,hoursBytes.Length);
239                byte[] minutesBytes = BitConverter.GetBytes(this.processingTime.Minutes);
240                memStream.Write(minutesBytes,0,minutesBytes.Length);
241                byte[] secondsBytes = BitConverter.GetBytes(this.processingTime.Seconds);
242                memStream.Write(secondsBytes,0,secondsBytes.Length);
243                byte[] msecondsBytes = BitConverter.GetBytes(this.processingTime.Milliseconds);
244                memStream.Write(msecondsBytes,0,msecondsBytes.Length);
245
246
247                byte[] serializedJobResult = SerializeResultType();
248                memStream.Write(serializedJobResult, 0, serializedJobResult.Length);
249
250
251                ret = memStream.ToArray();
252            }
253            catch (Exception ex)
254            {
255                throw ex;
256            }
257            finally
258            {
259                memStream.Flush();
260                memStream.Close();
261                memStream.Dispose();
262            }
263            return ret;
264        }
265
266        #endregion
267
268        //#region Reflection methods
269
270        //private byte[] GetSerializationViaReflection(object objectToSerialize)
271        //{
272        //    byte[] serializedBytes = null;
273        //    try
274        //    {
275        //        MethodInfo methInfo = objectToSerialize.GetType().GetMethod("Serialize");
276        //        ParameterInfo[] paramInfo = methInfo.GetParameters();
277        //        ParameterInfo returnParam = methInfo.ReturnParameter;
278        //        Type returnType = methInfo.ReturnType;
279
280        //        serializedBytes = methInfo.Invoke(objectToSerialize, null) as byte[];
281        //        if (serializedBytes == null)
282        //            throw (new Exception("Serializing " + objectToSerialize.GetType().ToString() + " canceled!"));
283        //    }
284        //    catch (Exception ex)
285        //    {
286        //        throw (new Exception("Invocing method 'Serialize' of '"
287        //            + objectToSerialize.GetType().ToString() + "' wasn't possible. " + ex.ToString()));
288        //    }
289        //    return serializedBytes;
290        //}
291
292        //private object GetDeserializationViaReflection(object serializedData, object returnType)
293        //{
294        //    try
295        //    {
296        //        MethodInfo methInfo = returnType.GetType().GetMethod("Deserialize", new[] { serializedData.GetType() });
297        //        object deserializedData = methInfo.Invoke(returnType, new object[] { serializedData });
298        //        if (deserializedData == null)
299        //            throw (new Exception("Deserializing " + returnType.ToString() + " canceled!"));
300        //        return deserializedData;
301        //    }
302        //    catch (Exception ex)
303        //    {
304        //        throw (new Exception("Invocing method 'Deserialize' of '"
305        //            + returnType.ToString() + "' wasn't possible. " + ex.ToString()));
306        //    }
307        //}
308
309        //#endregion
310    }
311}
Note: See TracBrowser for help on using the repository browser.