Repository navigation
Expand file tree
/
Copy pathConfig.cs
More file actions
380 lines (341 loc) · 13.1 KB
/
Copy pathConfig.cs
File metadata and controls
380 lines (341 loc) · 13.1 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections;
using System.Collections.Generic;
using IBM.Watson.DeveloperCloud.Logging;
using UnityEngine;
using FullSerializer;
using System.IO;
using MiniJSON;
using System;
namespace IBM.Watson.DeveloperCloud.Utilities
{
/// <summary>
/// This class is used to hold configuration data for SDK.
/// </summary>
public class Config
{
/// <summary>
/// Serialized class for holding generic key/value pairs.
/// </summary>
[fsObject]
public class Variable
{
/// <summary>
/// The key name.
/// </summary>
public string Key { get; set; }
/// <summary>
/// The value referenced by the key.
/// </summary>
public string Value { get; set; }
};
/// <summary>
/// Serialized class for holding the user credentials for a service.
/// </summary>
[fsObject]
public class CredentialInfo
{
/// <summary>
/// The ID of the service this is the credentials.
/// </summary>
public string m_ServiceID;
/// <summary>
/// The URL for these credentials.
/// </summary>
public string m_URL;
/// <summary>
/// The user name for these credentials.
/// </summary>
public string m_User;
/// <summary>
/// The password for these credentials.
/// </summary>
public string m_Password;
/// <summary>
/// Generate JSON credentials.
/// </summary>
/// <returns>Returns a string of the JSON.</returns>
public string MakeJSON()
{
return "{\n\t\"credentials\": {\n\t\t\"url\": \"" + m_URL + "\",\n\t\t\"username\": \"" + m_User + "\",\n\t\t\"password\": \"" + m_Password + "\"\n\t}\n}";
}
/// <summary>
/// Parses a BlueMix json credentials into this object.
/// </summary>
/// <param name="json">The JSON data to parse.</param>
/// <returns>Returns true on success.</returns>
public bool ParseJSON(string json)
{
try
{
IDictionary iParse = Json.Deserialize(json) as IDictionary;
IDictionary iCredentials = iParse["credentials"] as IDictionary;
m_URL = (string)iCredentials["url"];
m_User = (string)iCredentials["username"];
m_Password = (string)iCredentials["password"];
return true;
}
catch (Exception e)
{
Log.Error("Config", "Caught Exception: {0}", e.ToString());
}
return false;
}
/// <summary>
/// Determines whether this instance has credentials.
/// </summary>
/// <returns><c>true</c> if this instance has credentials; otherwise, <c>false</c>.</returns>
public bool HasCredentials()
{
return !string.IsNullOrEmpty(m_User) && !string.IsNullOrEmpty(m_Password);
}
}
#region Private Data
[fsProperty]
private string m_ClassifierDirectory = "Watson/Scripts/Editor/Classifiers/";
[fsProperty]
private float m_TimeOut = 30.0f;
[fsProperty]
private int m_MaxRestConnections = 5;
[fsProperty]
private List<CredentialInfo> m_Credentials = new List<CredentialInfo>();
[fsProperty]
private List<Variable> m_Variables = new List<Variable>();
private static fsSerializer sm_Serializer = new fsSerializer();
#endregion
#region Public Properties
/// <summary>
/// Returns true if the configuration is loaded or not.
/// </summary>
[fsIgnore]
public bool ConfigLoaded { get; private set; }
/// <summary>
/// Returns the singleton instance.
/// </summary>
public static Config Instance { get { return Singleton<Config>.Instance; } }
/// <summary>
/// Returns the location of the classifiers
/// </summary>
public string ClassifierDirectory { get { return m_ClassifierDirectory; } set { m_ClassifierDirectory = value; } }
/// <summary>
/// Returns the Timeout for requests made to the server.
/// </summary>
public float TimeOut { get { return m_TimeOut; } set { m_TimeOut = value; } }
/// <summary>
/// Maximum number of connections Watson will make to the server back-end at any one time.
/// </summary>
public int MaxRestConnections { get { return m_MaxRestConnections; } set { m_MaxRestConnections = value; } }
/// <summary>
/// Returns the list of credentials used to login to the various services.
/// </summary>
public List<CredentialInfo> Credentials { get { return m_Credentials; } set { m_Credentials = value; } }
/// <summary>
/// Returns a list of variables which can hold key/value data.
/// </summary>
public List<Variable> Variables { get { return m_Variables; } set { m_Variables = value; } }
#endregion
/// <summary>
/// Default constructor will call LoadConfig() automatically.
/// </summary>
public Config()
{
LoadConfig();
}
/// <summary>
/// Find BlueMix credentials by the service ID.
/// </summary>
/// <param name="serviceID">The ID of the service to find.</param>
/// <returns>Returns null if the credentials cannot be found.</returns>
public CredentialInfo FindCredentials(string serviceID)
{
foreach (var info in m_Credentials)
if (info.m_ServiceID == serviceID)
return info;
return null;
}
/// <summary>
/// Invoking this function will start the co-routine to load the configuration. The user should check the
/// ConfigLoaded property to check when the configuration is actually loaded.
/// </summary>
public void LoadConfig()
{
#if !UNITY_ANDROID || UNITY_EDITOR
try
{
if (!Directory.Exists(Application.streamingAssetsPath))
Directory.CreateDirectory(Application.streamingAssetsPath);
LoadConfig(System.IO.File.ReadAllText(Application.streamingAssetsPath + Constants.Path.CONFIG_FILE));
}
catch (System.IO.FileNotFoundException)
{
// mark as loaded anyway, so we don't keep retrying..
Log.Error("Config", "Failed to load config file.");
ConfigLoaded = true;
}
#else
Runnable.Run(LoadConfigCR());
#endif
}
/// <summary>
/// Load the configuration from the given JSON data.
/// </summary>
/// <param name="json">The string containing the configuration JSON data.</param>
/// <returns></returns>
public bool LoadConfig(string json)
{
try
{
fsData data = null;
fsResult r = fsJsonParser.Parse(json, out data);
if (!r.Succeeded)
{
Log.Error("Config", "Failed to parse Config.json: {0}", r.ToString());
return false;
}
object obj = this;
r = sm_Serializer.TryDeserialize(data, GetType(), ref obj);
if (!r.Succeeded)
{
Log.Error("Config", "Failed to parse Config.json: {0}", r.ToString());
return false;
}
ConfigLoaded = true;
return true;
}
catch (Exception e)
{
Log.Error("Config", "Failed to load config: {0}", e.ToString());
}
ConfigLoaded = true;
return false;
}
/// <summary>
/// Save this COnfig into JSON.
/// </summary>
/// <param name="pretty">If true, then the json data will be formatted for readability.</param>
/// <returns></returns>
public string SaveConfig(bool pretty = true)
{
fsData data = null;
sm_Serializer.TrySerialize(GetType(), this, out data);
if (!System.IO.Directory.Exists(Application.streamingAssetsPath))
System.IO.Directory.CreateDirectory(Application.streamingAssetsPath);
if (pretty)
return fsJsonPrinter.PrettyJson(data);
return fsJsonPrinter.CompressedJson(data);
}
/// <summary>
/// Save this config to fileSystem
/// </summary>
public bool SaveConfigToFileSystem()
{
bool success = true;
try
{
File.WriteAllText(Application.streamingAssetsPath + Constants.Path.CONFIG_FILE, SaveConfig(true));
}
catch (Exception ex)
{
success = false;
Log.Error("Config", "Exception on SaveConfigToFileSystem. {0}", ex.Message);
}
return success;
}
/// <summary>
/// Finds a variable name and returns the Variable object
/// </summary>
/// <param name="key">The name of the variable to find.</param>
/// <returns>Returns the Variable object or null if not found.</returns>
public Variable GetVariable(string key)
{
foreach (var var in m_Variables)
if (var.Key == key)
return var;
return null;
}
/// <summary>
/// Gets the variable value.
/// </summary>
/// <returns>The variable value.</returns>
/// <param name="key">Key.</param>
public string GetVariableValue(string key)
{
Variable v = GetVariable(key);
if (v != null)
return v.Value;
return null;
}
/// <summary>
/// Sets the variable value.
/// </summary>
/// <returns><c>true</c>, if variable value was set, <c>false</c> otherwise.</returns>
/// <param name="key">Key.</param>
/// <param name="value">Value.</param>
public bool SetVariableValue(string key, string value, bool bAdd = false)
{
Variable v = GetVariable(key);
if (v == null)
{
if (!bAdd)
return false;
v = new Variable();
v.Key = key;
m_Variables.Add(v);
}
v.Value = value;
return true;
}
/// <summary>
/// Resolves any variables found in the input string and returns the variable values in the returned string.
/// </summary>
/// <param name="input">A string containing variables.</param>
/// <returns>Returns the string with all variables resolved to their actual values. Any missing variables are removed from the string.</returns>
public string ResolveVariables(string input, bool recursive = true)
{
string output = input;
foreach (var var in m_Variables)
{
string value = var.Value;
if (recursive && value.Contains("${"))
value = ResolveVariables(value, false);
output = output.Replace("${" + var.Key + "}", value);
}
// remove any variables still in the string..
int variableIndex = output.IndexOf("${");
while (variableIndex >= 0)
{
int endVariable = output.IndexOf("}", variableIndex);
if (endVariable < 0)
break; // end not found..
output = output.Remove(variableIndex, (endVariable - variableIndex) + 1);
// next..
variableIndex = output.IndexOf("${");
}
return output;
}
private IEnumerator LoadConfigCR()
{
// load the config using WWW, since this works on all platforms..
WWW request = new WWW(Application.streamingAssetsPath + Constants.Path.CONFIG_FILE);
while (!request.isDone)
yield return null;
LoadConfig(request.text);
yield break;
}
}
}